diff --git a/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/NMSBinding.java b/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/NMSBinding.java index 50b4f86bb..63eb0975e 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/NMSBinding.java +++ b/adapters/bukkit/nms/v26_2_R1/src/main/java/art/arcane/iris/core/nms/v26_2_R1/NMSBinding.java @@ -1279,7 +1279,7 @@ public class NMSBinding implements INMSBinding { boolean studioBootstrap = platformGenerator != null && platformGenerator.isStudioEntryBootstrapActive(); boolean jigsawStudio = platformGenerator != null - && platformGenerator.isJigsawStudioActive(); + && platformGenerator.isPaintedStudioActive(); if (jigsawStudio) { requireIrisGenerator(generator); if (currentState.possibleStructureSets().isEmpty()) { diff --git a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/nms/v26_2_R1/NMSBindingDatapackStructureScopeTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/nms/v26_2_R1/NMSBindingDatapackStructureScopeTest.java index 5d41a6130..9499831dc 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/nms/v26_2_R1/NMSBindingDatapackStructureScopeTest.java +++ b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/nms/v26_2_R1/NMSBindingDatapackStructureScopeTest.java @@ -362,7 +362,7 @@ public class NMSBindingDatapackStructureScopeTest { assertTrue(standardPublication > retention); assertTrue(immediateInitialization > standardPublication); assertFalse(method.contains("scopedState.ensureStructuresGenerated();")); - assertFalse(method.contains("if (studioBootstrap && platformGenerator.isJigsawStudioActive())")); + assertFalse(method.contains("if (studioBootstrap && platformGenerator.isPaintedStudioActive())")); } @Test diff --git a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/structure/VillageImporterListPoolElementRuntimeContractTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/structure/VillageImporterListPoolElementRuntimeContractTest.java index 3c472a150..7edfc22a1 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/structure/VillageImporterListPoolElementRuntimeContractTest.java +++ b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/core/structure/VillageImporterListPoolElementRuntimeContractTest.java @@ -54,13 +54,14 @@ public class VillageImporterListPoolElementRuntimeContractTest { StructureTemplatePool.Projection.RIGID ); - VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(towers); + PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(towers); Map entry = VillageImporter.piecePoolEntry( "qa/pillager_outpost/piece/minecraft/pillager_outpost/watchtower", 1 ); StructureLoss loss = VillageImporter.listElementFallbackLoss( - resolution, + resolution.listLevels(), + resolution.omittedElements(), "minecraft:pillager_outpost/towers" ); Map basePlatePiece = VillageImporter.pieceJson( @@ -103,7 +104,7 @@ public class VillageImporterListPoolElementRuntimeContractTest { StructurePoolElement waystone = StructurePoolElement .legacy("dungeons_and_taverns:waystones/waystone_scaffold") .apply(StructureTemplatePool.Projection.RIGID); - VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(waystone); + PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(waystone); VillageImporter.PoolMemberNormalization normalization = VillageImporter.normalizePoolMember( "dungeons_and_taverns:waystones", "qa/pool/dungeons_and_taverns/waystones", @@ -130,7 +131,7 @@ public class VillageImporterListPoolElementRuntimeContractTest { StructurePoolElement orphan = StructurePoolElement .legacy("test:orphan_house") .apply(StructureTemplatePool.Projection.RIGID); - VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(orphan); + PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(orphan); VillageImporter.PoolMemberNormalization normalization = VillageImporter.normalizePoolMember( "test:orphan_pool", "qa/pool/test/orphan_pool", @@ -160,7 +161,7 @@ public class VillageImporterListPoolElementRuntimeContractTest { StructurePoolElement start = StructurePoolElement .legacy("test:air_start") .apply(StructureTemplatePool.Projection.RIGID); - VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(start); + PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(start); VillageImporter.PoolMemberNormalization normalization = VillageImporter.normalizePoolMember( "test:start", "qa/pool/test/start", @@ -184,7 +185,7 @@ public class VillageImporterListPoolElementRuntimeContractTest { StructurePoolElement inert = StructurePoolElement .legacy("test:mixed_air_inert") .apply(StructureTemplatePool.Projection.RIGID); - VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(inert); + PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(inert); VillageImporter.PoolMemberNormalization normalization = VillageImporter.normalizePoolMember( "test:mixed", "qa/pool/test/mixed", @@ -214,8 +215,8 @@ public class VillageImporterListPoolElementRuntimeContractTest { StructurePoolElement nonAirElement = StructurePoolElement .legacy("test:mixed_non_air_primary") .apply(StructureTemplatePool.Projection.RIGID); - VillageImporter.PoolElementResolution allAirResolution = VillageImporter.resolvePoolElement(allAirElement); - VillageImporter.PoolElementResolution nonAirResolution = VillageImporter.resolvePoolElement(nonAirElement); + PoolElementReader.PoolElementResolution allAirResolution = PoolElementReader.resolvePoolElement(allAirElement); + PoolElementReader.PoolElementResolution nonAirResolution = PoolElementReader.resolvePoolElement(nonAirElement); VillageImporter.PoolMemberNormalization allAir = VillageImporter.normalizePoolMember( "test:mixed", "qa/pool/test/mixed", @@ -257,8 +258,8 @@ public class VillageImporterListPoolElementRuntimeContractTest { StructurePoolElement nonAirElement = StructurePoolElement .legacy("test:non_air_primary") .apply(StructureTemplatePool.Projection.RIGID); - VillageImporter.PoolElementResolution allAirResolution = VillageImporter.resolvePoolElement(allAirElement); - VillageImporter.PoolElementResolution nonAirResolution = VillageImporter.resolvePoolElement(nonAirElement); + PoolElementReader.PoolElementResolution allAirResolution = PoolElementReader.resolvePoolElement(allAirElement); + PoolElementReader.PoolElementResolution nonAirResolution = PoolElementReader.resolvePoolElement(nonAirElement); VillageImporter.PoolMemberNormalization allAir = VillageImporter.normalizePoolMember( "test:primary", "qa/pool/test/primary", diff --git a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureFitBridgeTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureFitBridgeTest.java index 85dcafea6..b8d75d1bb 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureFitBridgeTest.java +++ b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureFitBridgeTest.java @@ -1,6 +1,7 @@ package art.arcane.iris.nativegen; import art.arcane.iris.engine.framework.NativeStartMemo; +import art.arcane.iris.engine.mantle.components.StructureModule; import art.arcane.iris.engine.framework.NativeStructureReach; import art.arcane.iris.engine.framework.nativefit.NativeFitPiece; import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting; @@ -1032,7 +1033,7 @@ public class NativeStructureFitBridgeTest { } private static final class BuiltInFitting { - private static final NativeStructureFitting FITTING = NativeStructureFitting.builtInModules(); + private static final NativeStructureFitting FITTING = NativeStructureFitting.ofModules(new StructureModule()); } private static PoolElementStructurePiece rigidTemplatePiece( diff --git a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureFitPinTest.java b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureFitPinTest.java index cfc37e2fc..220a30d94 100644 --- a/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureFitPinTest.java +++ b/adapters/bukkit/nms/v26_2_R1/src/test/java/art/arcane/iris/nativegen/NativeStructureFitPinTest.java @@ -1,6 +1,7 @@ package art.arcane.iris.nativegen; import art.arcane.iris.engine.framework.NativeStartMemo; +import art.arcane.iris.engine.mantle.components.StructureModule; import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting; import com.mojang.datafixers.util.Either; import net.minecraft.SharedConstants; @@ -140,7 +141,7 @@ public class NativeStructureFitPinTest { /** The built-in modules load once for every scenario. */ private static final class BuiltInFitting { - private static final NativeStructureFitting FITTING = NativeStructureFitting.builtInModules(); + private static final NativeStructureFitting FITTING = NativeStructureFitting.ofModules(new StructureModule()); } /** diff --git a/adapters/bukkit/plugin/build.gradle b/adapters/bukkit/plugin/build.gradle index ba8ed62a5..de579a69b 100644 --- a/adapters/bukkit/plugin/build.gradle +++ b/adapters/bukkit/plugin/build.gradle @@ -66,13 +66,15 @@ tasks.named('jar', Jar).configure { tasks.named('test').configure { systemProperty('iris.commandFindSource', file('src/main/java/art/arcane/iris/core/commands/CommandFind.java').absolutePath) - systemProperty('iris.commandStructureSource', file('src/main/java/art/arcane/iris/core/commands/CommandStructure.java').absolutePath) + systemProperty('iris.importCommandsSource', rootProject.file('module/src/main/java/art/arcane/iris/core/structure/tooling/ImportCommands.java').absolutePath) + systemProperty('iris.studioLifecycleCommandsSource', rootProject.file('module/src/main/java/art/arcane/iris/core/structure/tooling/StudioLifecycleCommands.java').absolutePath) systemProperty('iris.commandIrisSource', file('src/main/java/art/arcane/iris/core/commands/CommandIris.java').absolutePath) systemProperty('iris.bukkitChunkGeneratorSource', rootProject.file('core/src/main/java/art/arcane/iris/engine/platform/BukkitChunkGenerator.java').absolutePath) systemProperty('iris.pregeneratorJobSource', rootProject.file('core/src/main/java/art/arcane/iris/core/gui/PregeneratorJob.java').absolutePath) systemProperty('iris.bukkitEnginePlatformHooksSource', file('src/main/java/art/arcane/iris/core/runtime/BukkitEnginePlatformHooks.java').absolutePath) systemProperty('iris.engineSvcSource', file('src/main/java/art/arcane/iris/core/service/IrisEngineSVC.java').absolutePath) - systemProperty('iris.jigsawStudioSvcSource', rootProject.file('core/src/main/java/art/arcane/iris/core/service/JigsawStudioService.java').absolutePath) + systemProperty('iris.jigsawStudioSvcSource', rootProject.file('module/src/main/java/art/arcane/iris/core/service/JigsawStudioService.java').absolutePath) + systemProperty('iris.toolWorldServiceSource', file('src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorldService.java').absolutePath) systemProperty('iris.studioSvcSource', rootProject.file('core/src/main/java/art/arcane/iris/core/service/StudioSVC.java').absolutePath) systemProperty('iris.terrainSvcSource', file('src/main/java/art/arcane/iris/core/service/IrisTerrainSVC.java').absolutePath) systemProperty('iris.apiEventSvcSource', file('src/main/java/art/arcane/iris/core/service/IrisApiEventSVC.java').absolutePath) diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/Iris.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/Iris.java index 65b15b25b..20a3a57b0 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/Iris.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/Iris.java @@ -47,6 +47,10 @@ import art.arcane.iris.core.lifecycle.WorldLifecycleService; import art.arcane.iris.core.runtime.BukkitEnginePlatformHooks; import art.arcane.iris.core.runtime.WorldDeletionQueue; import art.arcane.iris.core.runtime.WorldRuntimeControlService; +import art.arcane.iris.core.toolworld.BukkitToolWorldService; +import art.arcane.iris.core.structure.BukkitPlatformStructures; +import art.arcane.iris.core.tooling.ToolWorldsHost; +import com.volmit.tooling.PlatformStructures; import art.arcane.iris.api.terrain.IrisTerrainService; import art.arcane.iris.core.link.CustomBlockSource; import art.arcane.iris.core.link.IrisPapiInstaller; @@ -72,7 +76,6 @@ import art.arcane.iris.core.service.IrisEngineSVC; import art.arcane.iris.core.service.IrisIntegrationService; import art.arcane.iris.core.service.IrisProtocolService; import art.arcane.iris.core.service.IrisTerrainSVC; -import art.arcane.iris.core.service.JigsawStudioService; import art.arcane.iris.core.service.LogFilterSVC; import art.arcane.iris.core.service.MultiverseSVC; import art.arcane.iris.core.service.ObjectSVC; @@ -645,7 +648,6 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware { new EditSVC(), new ObjectSVC(), new ObjectStudioSaveService(), - new JigsawStudioService(), new StudioSVC(), new DatapackStructureScopeSVC(), new IrisEngineSVC(), @@ -655,6 +657,7 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware { new EntityRiseSVC(), new WandSVC(), new BoardSVC(), + new BukkitToolWorldService(), new IrisIntegrationService(), new MultiverseSVC(), new IrisProtocolService(), @@ -670,6 +673,8 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware { services.put(serviceType, i); IrisServices.register(serviceType, i); } + IrisServices.register(ToolWorldsHost.class, services.get(BukkitToolWorldService.class)); + IrisServices.register(PlatformStructures.class, new BukkitPlatformStructures()); IrisServices.register(BlockEditAccess.class, services.get(EditSVC.class)); IrisServices.register(CustomBlockSource.class, services.get(ExternalDataSVC.class)); IrisServices.register(PreservationRegistry.class, services.get(PreservationSVC.class)); @@ -998,14 +1003,6 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware { private void quiesceRuntimeForServerShutdown(String reason) { serverStopTeardownDeferred.set(true); - JigsawStudioService jigsawStudioService = IrisServices.getOrNull(JigsawStudioService.class); - if (jigsawStudioService != null) { - try { - jigsawStudioService.quiesceForServerShutdown(); - } catch (Throwable e) { - Iris.reportError("Failed to quiesce Jigsaw Studio before server shutdown.", e); - } - } StudioSVC studioService = IrisServices.getOrNull(StudioSVC.class); if (studioService != null) { studioService.quiesceDownloadsForShutdown(); diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandIris.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandIris.java index 25044bc87..3ab2e0555 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandIris.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandIris.java @@ -86,8 +86,6 @@ public class CommandIris implements DirectorExecutor { private CommandStudio studio; private CommandPregen pregen; private CommandObject object; - private CommandStructure structure; - private CommandJigsaw jigsaw; private CommandWhat what; private CommandEdit edit; private CommandDeveloper developer; diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java deleted file mode 100644 index a9a217ed2..000000000 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java +++ /dev/null @@ -1,2209 +0,0 @@ -package art.arcane.iris.core.commands; - -import art.arcane.iris.engine.framework.structure.StructureResources; -import art.arcane.iris.Iris; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.pack.BrokenPackException; -import art.arcane.iris.core.runtime.WorldRuntimeControlService; -import art.arcane.iris.core.runtime.StudioOpenCoordinator; -import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarArchetype; -import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarTopology; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioActivation; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBay; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioGraphMapper; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioGraphEditor; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioPoolEditor; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioProjectCreator; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioSession; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioStructureEditor; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariant; -import art.arcane.iris.core.service.JigsawStudioGraphEvaluation; -import art.arcane.iris.core.service.JigsawStudioService; -import art.arcane.iris.core.service.StudioSVC; -import art.arcane.iris.core.structure.StructureImporter; -import art.arcane.iris.core.structure.VillageImporter; -import art.arcane.iris.core.structure.authoring.StructureKey; -import art.arcane.iris.core.structure.authoring.StructureOwnershipManifest; -import art.arcane.iris.core.structure.authoring.StructureTransactionWriter; -import art.arcane.iris.core.structure.authoring.StructureWriteResult; -import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionDiagnostic; -import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionInputKind; -import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionPlan; -import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionRequest; -import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionResult; -import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionService; -import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionStrategy; -import art.arcane.iris.core.structure.export.VanillaJigsawDatapackExporter; -import art.arcane.iris.core.structure.export.VanillaJigsawExportDiagnostic; -import art.arcane.iris.core.structure.export.VanillaJigsawExportFormat; -import art.arcane.iris.core.structure.export.VanillaJigsawExportRequest; -import art.arcane.iris.core.structure.export.VanillaJigsawExportResult; -import art.arcane.iris.core.structure.export.VanillaJigsawExportSource; -import art.arcane.iris.engine.framework.structure.PlanarJigsawWorkcellResolver; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawCompatibility; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.engine.object.structure.IrisStructure; -import art.arcane.iris.platform.bukkit.BukkitPlatform; -import art.arcane.iris.util.common.director.DirectorExecutor; -import art.arcane.iris.util.common.director.specialhandlers.IrisStructureHandler; -import art.arcane.iris.util.common.format.C; -import art.arcane.iris.util.common.plugin.VolmitSender; -import art.arcane.iris.util.common.scheduling.J; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.director.DirectorOrigin; -import art.arcane.volmlib.util.director.DirectorParameterHandler; -import art.arcane.volmlib.util.director.annotations.Director; -import art.arcane.volmlib.util.director.annotations.Param; -import art.arcane.volmlib.util.director.exceptions.DirectorParsingException; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.NamespacedKey; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.data.type.Jigsaw; -import org.bukkit.entity.Player; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.LinkOption; -import java.nio.file.Path; -import java.util.HashSet; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.CompletionException; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.regex.Pattern; - -@Director(name = "jigsaw", aliases = {"jig", "jgs"}, description = "Iris Jigsaw Studio tools", - origin = DirectorOrigin.PLAYER) -public class CommandJigsaw implements DirectorExecutor { - private static final long DEFAULT_STUDIO_SEED = 1337L; - static final StudioOpenCoordinator.StudioOpenKind STUDIO_OPEN_KIND = - StudioOpenCoordinator.StudioOpenKind.JIGSAW; - private static final Pattern EXPORT_OUTPUT_NAME = Pattern.compile("[a-zA-Z0-9_-][a-zA-Z0-9._-]{0,127}"); - private static final Map PLAYER_PACKS = new ConcurrentHashMap<>(); - private static final Map ADOPTION_PLANS = new ConcurrentHashMap<>(); - private static final Map ADOPTION_SERVICES = new ConcurrentHashMap<>(); - private static final Set EXPORTING_PLAYERS = ConcurrentHashMap.newKeySet(); - private static final Set EXPORT_DESTINATIONS = ConcurrentHashMap.newKeySet(); - - private CommandJigsawPiece piece; - private CommandJigsawPool pool; - private CommandJigsawConnector connector; - private CommandJigsawVariant variant; - private CommandJigsawWorkcell workcell; - private CommandJigsawRules rules; - private CommandJigsawPreview preview; - private CommandJigsawAdopt adopt; - - @Director(description = "Create and open a new atomic Jigsaw Studio project", sync = true, - origin = DirectorOrigin.PLAYER) - public void create( - @Param(description = "Pack dimension") IrisDimension dimension, - @Param(name = "key", aliases = {"structure", "name"}, - description = "New key written as structures/.json") String structure, - @Param(description = "planar or spatial", defaultValue = "planar", - customHandler = JigsawModeHandler.class) String mode, - @Param(description = "iris or vanilla", defaultValue = "iris", - customHandler = JigsawCompatibilityHandler.class) String compatibility, - @Param(description = "Cell width", defaultValue = "15") int width, - @Param(description = "Cell height", defaultValue = "15") int height, - @Param(description = "Cell depth", defaultValue = "15") int depth, - @Param(description = "Studio world seed", defaultValue = "1337") long seed - ) { - IrisData data = requireData(dimension); - if (data == null) { - return; - } - JigsawStudioMode studioMode; - JigsawStudioCompatibilityTarget target; - JigsawStudioCellDimensions dimensions; - try { - studioMode = parseMode(mode); - target = parseCompatibility(compatibility); - dimensions = new JigsawStudioCellDimensions(width, height, depth); - } catch (IllegalArgumentException exception) { - sendError(exception.getMessage()); - return; - } - - StructureWriteResult result; - try { - result = JigsawStudioProjectCreator.create( - data.getDataFolder().toPath(), - new JigsawStudioProjectCreator.Options(structure, studioMode, target, dimensions)); - } catch (IOException | RuntimeException exception) { - Iris.reportError("Failed to create Jigsaw Studio project '" + structure + "'.", exception); - sendError("Jigsaw project creation failed: " + exception.getMessage()); - return; - } - if (!result.successful()) { - sendError("Jigsaw project was not created: " + result.status()); - if (!result.conflicts().isEmpty()) { - sendError(result.conflicts().getFirst().relativePath() + ": " - + result.conflicts().getFirst().reason()); - } - return; - } - try { - JigsawStudioService.clearAutosaveHistory( - data.getDataFolder().toPath(), - structure); - } catch (IOException exception) { - Iris.reportError("Failed to clear stale Jigsaw Studio history for '" + structure + "'.", exception); - sendError("Jigsaw project was created, but stale autosave history could not be cleared: " - + exception.getMessage()); - return; - } - data.invalidateStructureResources(); - sender().sendMessage(C.GREEN + "Created Jigsaw project '" + structure + "' atomically."); - open(dimension, structure, seed); - } - - @Director(description = "Import a registered vanilla or datapack jigsaw graph into Iris Studio", - aliases = {"import", "import-vanilla"}, sync = true, origin = DirectorOrigin.PLAYER) - public void convert( - @Param(description = "Pack dimension") IrisDimension dimension, - @Param(description = "Registered structure key such as minecraft:village_plains") String source, - @Param(description = "New Iris structure key, or auto", defaultValue = "auto") String target, - @Param(description = "Studio world seed", defaultValue = "1337") long seed - ) { - if (studioIsActiveOrOpening()) { - sendError("Close the active or opening Jigsaw Studio before importing another graph."); - return; - } - IrisData data = requireData(dimension); - if (data == null) { - return; - } - NamespacedKey sourceKey; - String targetKey; - try { - sourceKey = parseRegisteredStructureKey(source); - targetKey = resolveConversionTarget(sourceKey, target); - } catch (IllegalArgumentException exception) { - sendError(exception.getMessage()); - return; - } - - VillageImporter.Result result = VillageImporter.importVillage( - data, - sourceKey, - targetKey, - StructureImporter.Mode.ADD_ONLY); - if (!result.success()) { - sendError(conversionFailureMessage(result)); - return; - } - data.invalidateStructureResources(); - VolmitSender commandSender = sender(); - commandSender.sendMessage(C.GREEN + result.message()); - openProject(player(), commandSender, dimension, targetKey, seed); - } - - @Director(description = "Open an existing Iris jigsaw graph in transient Studio", - aliases = {"edit", "reopen"}, sync = true, origin = DirectorOrigin.PLAYER) - public void open( - @Param(description = "Pack dimension") IrisDimension dimension, - @Param(name = "key", aliases = {"structure", "name"}, - description = "Existing key loaded from structures/.json", - customHandler = IrisStructureHandler.class) String structure, - @Param(description = "Studio world seed", defaultValue = "1337") long seed - ) { - openProject(player(), sender(), dimension, structure, seed); - } - - private static void openProject( - Player targetPlayer, - VolmitSender commandSender, - IrisDimension dimension, - String structure, - long seed - ) { - UUID playerId = targetPlayer.getUniqueId(); - UUID ownerId = JigsawStudioActivation.activeOwnerId(); - if (ownerId != null && !ownerId.equals(playerId)) { - sendError(commandSender, "Jigsaw Studio is already owned by another player session."); - return; - } - UUID openingOwner = JigsawStudioActivation.openingOwnerId(); - if (openingOwner != null) { - sendError(commandSender, openingOwner.equals(playerId) - ? "Your Jigsaw Studio is already opening." - : "Jigsaw Studio is already opening for another player."); - return; - } - ActiveContext previous = active(targetPlayer); - if (ownerId != null && previous == null) { - sendError(commandSender, "Your active Jigsaw Studio binding is unavailable. Close it before opening another project."); - return; - } - ActiveContext dirty = findDirtyContext(); - if (dirty != null) { - sendError(commandSender, - "The current Jigsaw Studio is waiting for autosave. Wait for it to finish or close with discard=true."); - return; - } - IrisData data = requireData(dimension, commandSender); - if (data == null) { - return; - } - IrisStructure irisStructure = StructureResources.structure(data.getPackResources(), structure); - if (irisStructure == null) { - sendError(commandSender, "No Iris jigsaw structure '" + structure + "' exists in this pack."); - return; - } - - JigsawStudioLayout layout; - try { - layout = JigsawStudioGraphMapper.map(data, irisStructure); - } catch (RuntimeException exception) { - Iris.reportError("Failed to map Jigsaw Studio graph '" + structure + "'.", exception); - sendError(commandSender, "Could not map this jigsaw graph: " + exception.getMessage()); - return; - } - String packKey = dimension.getLoadKey(); - if (!JigsawStudioActivation.tryBeginOpen(playerId)) { - sendError(commandSender, - "Jigsaw Studio began opening for another player. Try again after it finishes."); - return; - } - JigsawStudioService studioService = JigsawStudioService.get(); - UUID closingRequestId = previous == null ? null : previous.request().requestId(); - if (closingRequestId != null) { - JigsawStudioService.CloseStart closeStart = studioService.tryBeginClose( - closingRequestId, - playerId, - false); - if (closeStart != JigsawStudioService.CloseStart.STARTED) { - JigsawStudioActivation.finishOpen(playerId); - sendError(commandSender, closeStart == JigsawStudioService.CloseStart.SAVE_IN_PROGRESS - ? "The current Jigsaw Studio is saving. Wait for it to finish before opening another project." - : closeStart == JigsawStudioService.CloseStart.OPERATION_IN_PROGRESS - ? "The current Jigsaw Studio is loading a variant. Wait for it to finish before opening another project." - : closeStart == JigsawStudioService.CloseStart.DIRTY - ? "The current Jigsaw Studio is waiting for autosave. Wait for it to finish before opening another project." - : "The current Jigsaw Studio could not be reserved for replacement."); - return; - } - } - JigsawStudioActivation.StagedActivation staged; - try { - staged = JigsawStudioActivation.stage( - packKey, - structure, - layout.mode(), - compatibilityOf(irisStructure), - layout.cellDimensions(), - data, - layout, - playerId, - closingRequestId); - } catch (RuntimeException exception) { - JigsawStudioActivation.finishOpen(playerId); - studioService.cancelClose(closingRequestId); - Iris.reportError("Failed to stage Jigsaw Studio for '" + structure + "'.", exception); - sendError(commandSender, "Jigsaw Studio staging failed: " + exception.getMessage()); - return; - } - commandSender.sendMessage(C.GREEN + "Opening transient Jigsaw Studio for '" + structure + "' with " - + layout.bays().size() + " workcells."); - - try { - Iris.service(StudioSVC.class).openTracked( - commandSender, - seed, - packKey, - STUDIO_OPEN_KIND, - () -> beginStagedOpen(staged), - world -> finishOpen(targetPlayer, world, staged, studioService)) - .whenComplete((result, throwable) -> J.s(() -> finishOpenAttempt( - commandSender, - playerId, - structure, - closingRequestId, - studioService, - staged, - result, - throwable))); - } catch (Throwable exception) { - JigsawStudioActivation.finishOpen(playerId); - studioService.cancelClose(closingRequestId); - JigsawStudioActivation.rollback(staged); - Iris.reportError("Failed to open Jigsaw Studio for '" + structure + "'.", exception); - sendError(commandSender, "Jigsaw Studio open failed: " + exception.getMessage()); - } - } - - @Director(description = "Close the active Jigsaw Studio", sync = true, - origin = DirectorOrigin.PLAYER) - public void close( - @Param(description = "Discard unsaved Studio layout changes", defaultValue = "false") boolean discard - ) { - Player targetPlayer = player(); - ActiveContext context = active(targetPlayer); - if (context == null) { - sendError("You do not have an active Jigsaw Studio session."); - return; - } - if (context.session().isDirty() && !discard) { - sendError("This Jigsaw Studio is waiting for autosave. Wait for it to finish or run close with discard=true."); - return; - } - JigsawStudioService studioService = JigsawStudioService.get(); - UUID requestId = context.request().requestId(); - JigsawStudioService.CloseStart closeStart = studioService.tryBeginClose( - requestId, - targetPlayer.getUniqueId(), - discard); - if (closeStart != JigsawStudioService.CloseStart.STARTED) { - sendError(closeStart == JigsawStudioService.CloseStart.SAVE_IN_PROGRESS - ? "This Jigsaw Studio is saving. Wait for the save to finish before closing it." - : closeStart == JigsawStudioService.CloseStart.OPERATION_IN_PROGRESS - ? "This Jigsaw Studio is loading a variant. Wait for it to finish before closing it." - : closeStart == JigsawStudioService.CloseStart.DIRTY - ? "This Jigsaw Studio is waiting for autosave. Wait for it to finish or run close with discard=true." - : closeStart == JigsawStudioService.CloseStart.NOT_OWNER - ? "This Jigsaw Studio is owned by another player session." - : "This Jigsaw Studio session is no longer active."); - return; - } - VolmitSender commandSender = sender(); - try { - Iris.service(StudioSVC.class).close().whenComplete((result, throwable) -> J.s(() -> { - if (throwable != null || result == null || result.failureCause() != null) { - studioService.cancelClose(requestId); - Throwable failure = throwable != null ? throwable : result == null ? null : result.failureCause(); - commandSender.sendMessage(C.RED + "Jigsaw Studio close failed: " - + (failure == null ? "unknown failure" : failure.getMessage())); - return; - } - JigsawStudioActivation.deactivate(context.packKey(), requestId); - PLAYER_PACKS.remove(targetPlayer.getUniqueId(), - new SessionBinding(context.packKey(), requestId)); - commandSender.sendMessage(C.GREEN + "Jigsaw Studio closed."); - })); - } catch (Throwable exception) { - studioService.cancelClose(requestId); - Iris.reportError("Failed to close Jigsaw Studio '" + context.request().structureKey() + "'.", exception); - sendError("Jigsaw Studio close failed: " + exception.getMessage()); - } - } - - @Director(name = "delete", aliases = "remove", description = "Delete the active owned jigsaw project", - sync = true, origin = DirectorOrigin.PLAYER) - public void delete( - @Param(description = "Confirm permanent project deletion", defaultValue = "false") boolean confirm - ) { - if (requireActive() == null) { - return; - } - if (!confirm) { - sendError("Project deletion removes every resource owned by this jigsaw. Run again with confirm=true."); - return; - } - JigsawStudioService.get().deleteProject(player()); - } - - @Director(description = "Show active Jigsaw Studio and dynamic evaluation state", sync = true, - origin = DirectorOrigin.PLAYER) - public void status() { - ActiveContext context = requireActive(); - if (context == null) { - return; - } - JigsawStudioLayout layout = context.session().layout(); - String selection = context.session().selectedBayId().orElse("none"); - JigsawStudioVariant activeVariant = "none".equals(selection) - ? null - : context.session().activeVariant(selection).orElse(null); - JigsawStudioBay selectedBay = "none".equals(selection) ? null : layout.get(selection); - JigsawStudioCellDimensions selectedDimensions = selectedBay == null - ? null - : selectedBay.bounds().dimensions(); - Optional evaluation = JigsawStudioService.get().evaluation(player()); - sender().sendMessage(C.AQUA + "Jigsaw Studio: " + context.request().structureKey()); - sender().sendMessage(C.GRAY + "mode=" + layout.mode() - + ", compatibility=" + context.request().compatibilityTarget() - + ", defaultCell=" + layout.cellDimensions().width() + "x" - + layout.cellDimensions().height() + "x" + layout.cellDimensions().depth() - + ", workcells=" + layout.bays().size() - + ", variants=" + layout.variantCatalog().size()); - sender().sendMessage(C.GRAY + "selected=" + selection - + ", activeVariant=" + (activeVariant == null ? "none" : activeVariant.pieceKey()) - + ", size=" + (selectedDimensions == null ? "none" : selectedDimensions.width() + "x" - + selectedDimensions.height() + "x" + selectedDimensions.depth()) - + ", enabled=" + (selectedBay == null ? "n/a" : selectedBay.enabled()) - + ", autosavePending=" + context.session().isDirty()); - if (evaluation.isPresent()) { - JigsawStudioGraphEvaluation current = evaluation.get(); - sender().sendMessage(C.GRAY + "evaluation=" + current.state() - + ", seed=" + current.seed() - + ", theme=" + (current.selectedTheme().isBlank() ? "unthemed" : current.selectedTheme()) - + ", pieces=" + current.pieceCount() - + ", detail=" + current.detail()); - } else { - sender().sendMessage(C.GRAY + "evaluation=PENDING, seed=" + DEFAULT_STUDIO_SEED); - } - } - - @Director(description = "Open the Jigsaw Studio workcell and variant menu", sync = true, - origin = DirectorOrigin.PLAYER) - public void menu() { - if (requireActive() != null) { - JigsawStudioService.get().openControlMenu(player()); - } - } - - @Director(description = "Select the Jigsaw Studio workcell containing you", sync = true, - origin = DirectorOrigin.PLAYER) - public void select() { - ActiveContext context = requireActive(); - if (context == null) { - return; - } - Location location = player().getLocation(); - JigsawStudioBay bay = context.session().layout().findAt( - location.getBlockX(), location.getBlockY(), location.getBlockZ()); - if (bay == null) { - sendError("Stand inside a Jigsaw Studio workcell before selecting it."); - return; - } - context.session().selectBay(bay.stableId()); - sender().sendMessage(C.GREEN + "Selected " + bay.stableId() + " (" + bay.kind() + ")."); - } - - @Director(name = "bounds", aliases = {"cell", "resize"}, - description = "Set the selected Studio workcell capacity", - sync = true, origin = DirectorOrigin.PLAYER) - public void bounds( - @Param(description = "Cell width") int width, - @Param(description = "Cell height") int height, - @Param(description = "Cell depth") int depth - ) { - ActiveContext context = requireActive(); - if (context == null) { - return; - } - JigsawStudioBay selected = selectedBay(context); - if (selected == null) { - sendError("Select a Jigsaw Studio workcell before changing its capacity."); - return; - } - JigsawStudioCellDimensions dimensions; - try { - dimensions = new JigsawStudioCellDimensions(width, height, depth); - } catch (IllegalArgumentException exception) { - sendError(exception.getMessage()); - return; - } - if (dimensions.equals(selected.capacity())) { - sender().sendMessage(C.YELLOW + "Workcell capacity is unchanged."); - return; - } - JigsawStudioService.get().updateWorkcellDimensions(player(), selected.stableId(), dimensions); - } - - @Director(description = "Flush the automatic save for a workcell now", sync = true, - origin = DirectorOrigin.PLAYER) - public void save( - @Param(description = "Workcell ID or selected", defaultValue = "selected") String bay - ) { - ActiveContext context = requireActive(); - if (context == null) { - return; - } - if ("selected".equalsIgnoreCase(bay)) { - JigsawStudioBay selected = selectedBay(context); - if (selected == null) { - sendError("Select a Jigsaw Studio workcell before flushing its autosave."); - return; - } - JigsawStudioService.get().flushAutosave(player(), selected.stableId()); - return; - } - JigsawStudioService.get().flushAutosave(player(), bay); - } - - @Director(name = "goto", aliases = "teleport", description = "Select and teleport to a Studio workcell", - sync = true, origin = DirectorOrigin.PLAYER) - public void gotoBay( - @Param(description = "Workcell ID") String bay - ) { - if (requireActive() != null) { - JigsawStudioService.get().teleportTo(player(), bay); - } - } - - @Director(description = "Enable or disable Jigsaw Studio particles", sync = true, - origin = DirectorOrigin.PLAYER) - public void particles( - @Param(description = "Whether particles are visible") boolean visible - ) { - if (requireActive() != null) { - JigsawStudioService.get().setParticles(player(), visible); - } - } - - @Director(description = "Export the clean active graph as a vanilla datapack", sync = true, - origin = DirectorOrigin.PLAYER) - public void export( - @Param(description = "Datapack namespace", defaultValue = "iris") String namespace, - @Param(description = "Output name under the Studio exports folder", defaultValue = "jigsaw-export") - String output, - @Param(description = "directory or zip", defaultValue = "zip") String format, - @Param(description = "Replace an existing export", defaultValue = "false") boolean replace - ) { - ActiveContext context = requireActive(); - if (context == null) { - return; - } - if (context.session().isDirty()) { - sendError("Wait for the pending autosave or discard the edits before exporting the on-disk graph."); - return; - } - VanillaJigsawExportFormat exportFormat; - try { - exportFormat = parseFormat(format); - } catch (IllegalArgumentException exception) { - sendError(exception.getMessage()); - return; - } - Path exportRoot = new File(Iris.service(StudioSVC.class).getWorkspaceFolder(), "exports") - .toPath().toAbsolutePath().normalize(); - Path destination; - try { - destination = resolveExportDestination(exportRoot, output, exportFormat); - } catch (IllegalArgumentException exception) { - sendError(exception.getMessage()); - return; - } - VanillaJigsawExportRequest request; - try { - request = VanillaJigsawExportRequest.builder( - VanillaJigsawExportSource.forData( - context.request().source(), context.request().structureKey()), destination) - .namespace(namespace) - .resourcePath(context.request().structureKey()) - .format(exportFormat) - .replaceExisting(replace) - .build(); - } catch (IllegalArgumentException exception) { - sendError(exception.getMessage()); - return; - } - Player targetPlayer = player(); - UUID playerId = targetPlayer.getUniqueId(); - UUID requestId = context.request().requestId(); - JigsawStudioService studioService = JigsawStudioService.get(); - JigsawStudioService.ExportStart exportStart = studioService.tryBeginExport(requestId, playerId); - if (exportStart != JigsawStudioService.ExportStart.STARTED) { - sendError(exportStartError(exportStart)); - return; - } - if (!beginExport(playerId, destination)) { - studioService.finishExport(requestId); - sendError("A vanilla Jigsaw export for this player or output is already in progress."); - return; - } - ExportLease lease = new ExportLease(() -> { - finishExport(playerId, destination); - studioService.finishExport(requestId); - }); - ExportOperation operation = new ExportOperation( - targetPlayer, - sender(), - requestId, - context.request().structureKey(), - request, - lease); - sender().sendMessage(C.GRAY + "Exporting '" + operation.structureKey() - + "' in the background to " + destination + "..."); - try { - J.a(() -> runExport(operation)); - } catch (RuntimeException exception) { - operation.lease().release(); - Iris.reportError("Failed to schedule vanilla Jigsaw export for '" - + operation.structureKey() + "'.", exception); - sendError("Vanilla export could not be scheduled: " + exception.getMessage()); - } - } - - static String exportStartError(JigsawStudioService.ExportStart exportStart) { - Objects.requireNonNull(exportStart, "Jigsaw Studio export start status"); - return switch (exportStart) { - case NOT_ACTIVE -> "The active Jigsaw Studio is no longer available."; - case NOT_OWNER -> "Only the Jigsaw Studio owner can export this project."; - case DIRTY -> "Wait for the pending autosave or discard the edits before exporting the on-disk graph."; - case CLOSING -> "The active Jigsaw Studio is closing and cannot be exported."; - case SAVE_IN_PROGRESS -> "Wait for the current Jigsaw Studio save to finish before exporting."; - case OPERATION_IN_PROGRESS -> "Wait for the current Jigsaw Studio operation to finish before exporting."; - case IN_PROGRESS -> "A Jigsaw Studio export is already in progress."; - case STARTED -> throw new IllegalArgumentException("STARTED is not an export failure"); - }; - } - - static boolean beginExport(UUID playerId, Path destination) { - Objects.requireNonNull(playerId); - Path normalizedDestination = Objects.requireNonNull(destination).toAbsolutePath().normalize(); - if (!EXPORTING_PLAYERS.add(playerId)) { - return false; - } - if (EXPORT_DESTINATIONS.add(normalizedDestination)) { - return true; - } - EXPORTING_PLAYERS.remove(playerId); - return false; - } - - static void finishExport(UUID playerId, Path destination) { - EXPORTING_PLAYERS.remove(Objects.requireNonNull(playerId)); - EXPORT_DESTINATIONS.remove(Objects.requireNonNull(destination).toAbsolutePath().normalize()); - } - - private static void pruneAdoptionPlanBindings() { - for (Map.Entry entry : ADOPTION_PLANS.entrySet()) { - AdoptionPlanBinding binding = entry.getValue(); - if (binding.service().plan(entry.getKey()).isEmpty()) { - ADOPTION_PLANS.remove(entry.getKey(), binding); - } - } - } - - private static boolean studioIsActiveOrOpening() { - return JigsawStudioActivation.activeOwnerId() != null - || JigsawStudioActivation.openingOwnerId() != null; - } - - private static void runAdoptionApply( - Player targetPlayer, - VolmitSender commandSender, - UUID planId, - AdoptionPlanBinding binding - ) { - if (studioIsActiveOrOpening()) { - ADOPTION_PLANS.putIfAbsent(planId, binding); - J.runEntity(targetPlayer, () -> sendError(commandSender, - "Close the active or opening Jigsaw Studio before applying an adoption plan.")); - return; - } - IrisStructureAdoptionResult result; - Throwable failure = null; - try { - result = binding.service().apply(binding.plan()); - } catch (Throwable throwable) { - result = null; - failure = throwable; - Iris.reportError("Failed to apply Jigsaw adoption plan '" + planId + "'.", throwable); - } - IrisStructureAdoptionResult completedResult = result; - Throwable completedFailure = failure; - J.runEntity(targetPlayer, () -> finishAdoptionApply( - targetPlayer, - commandSender, - binding, - completedResult, - completedFailure)); - } - - private static void runAdoptionInspect( - Player targetPlayer, - VolmitSender commandSender, - UUID ownerId, - IrisDimension dimension, - IrisData data, - Path root, - String sourceKey, - Optional targetKey, - IrisStructureAdoptionStrategy strategy - ) { - IrisStructureAdoptionService service = null; - IrisStructureAdoptionPlan plan = null; - Throwable failure = null; - try { - IrisStructureAdoptionInputKind inputKind = adoptionInputKind(root, sourceKey); - service = ADOPTION_SERVICES.computeIfAbsent(root, IrisStructureAdoptionService::new); - plan = service.inspect(new IrisStructureAdoptionRequest( - sourceKey, - targetKey, - strategy, - inputKind)); - } catch (Throwable throwable) { - failure = throwable; - Iris.reportError("Failed to inspect Jigsaw adoption source '" + sourceKey + "'.", throwable); - } - IrisStructureAdoptionService completedService = service; - IrisStructureAdoptionPlan completedPlan = plan; - Throwable completedFailure = failure; - J.runEntity(targetPlayer, () -> finishAdoptionInspect( - commandSender, - ownerId, - dimension, - data, - completedService, - completedPlan, - completedFailure)); - } - - private static void finishAdoptionInspect( - VolmitSender commandSender, - UUID ownerId, - IrisDimension dimension, - IrisData data, - IrisStructureAdoptionService service, - IrisStructureAdoptionPlan plan, - Throwable failure - ) { - if (failure != null || service == null || plan == null) { - sendError(commandSender, "Jigsaw adoption inspection failed: " - + (failure == null ? "no result" : failure.getMessage())); - return; - } - pruneAdoptionPlanBindings(); - if (service.plan(plan.planId()).isPresent()) { - ADOPTION_PLANS.put(plan.planId(), new AdoptionPlanBinding( - ownerId, dimension, data, service, plan)); - } - reportAdoptionPlan(commandSender, plan); - } - - private static void finishAdoptionApply( - Player targetPlayer, - VolmitSender commandSender, - AdoptionPlanBinding binding, - IrisStructureAdoptionResult result, - Throwable failure - ) { - if (failure != null || result == null) { - sendError(commandSender, "Jigsaw adoption failed: " - + (failure == null ? "no result" : failure.getMessage())); - return; - } - reportAdoptionResult(commandSender, result); - if (!result.successful()) { - return; - } - StructureKey target = result.receipt().orElseThrow().targetStructure(); - binding.data().invalidateStructureResources(); - openProject(targetPlayer, commandSender, binding.dimension(), target.path(), DEFAULT_STUDIO_SEED); - } - - private static void reportAdoptionPlan(VolmitSender commandSender, IrisStructureAdoptionPlan plan) { - C statusColor = plan.canApply() ? C.GREEN : C.RED; - commandSender.sendMessage(statusColor + "Adoption plan " + plan.planId() + " -> " - + plan.disposition() + " for " + plan.targetStructure().value() + "."); - commandSender.sendMessage(C.GRAY + "Resources=" + plan.resourceCount() - + ", bytes=" + plan.totalSourceBytes() - + ", errors=" + plan.errorCount() - + ", warnings=" + plan.warningCount() + "."); - for (IrisStructureAdoptionDiagnostic diagnostic : plan.diagnostics()) { - commandSender.sendMessage(adoptionColor(diagnostic).toString() + diagnostic.summary()); - } - if (plan.canApply()) { - commandSender.sendMessage(C.AQUA + "Apply with /iris jigsaw adopt apply " + plan.planId()); - } - } - - private static void reportAdoptionResult(VolmitSender commandSender, IrisStructureAdoptionResult result) { - commandSender.sendMessage((result.successful() ? C.GREEN : C.RED) - + "Adoption plan " + result.planId() + ": " + result.status() + "."); - for (IrisStructureAdoptionDiagnostic diagnostic : result.diagnostics()) { - commandSender.sendMessage(adoptionColor(diagnostic).toString() + diagnostic.summary()); - } - } - - private static C adoptionColor(IrisStructureAdoptionDiagnostic diagnostic) { - return switch (diagnostic.severity()) { - case ERROR -> C.RED; - case WARNING -> C.YELLOW; - case INFO -> C.GRAY; - }; - } - - private static void runExport(ExportOperation operation) { - VanillaJigsawExportResult result = null; - Throwable failure = null; - try { - result = new VanillaJigsawDatapackExporter().export(operation.request()); - } catch (Throwable throwable) { - failure = throwable; - Iris.reportError("Vanilla Jigsaw export failed for '" + operation.structureKey() + "'.", throwable); - } finally { - operation.lease().release(); - } - VanillaJigsawExportResult completedResult = result; - Throwable completedFailure = failure; - Runnable response = () -> reportExport(operation, completedResult, completedFailure); - J.runEntity(operation.player(), response); - } - - private static void reportExport( - ExportOperation operation, - VanillaJigsawExportResult result, - Throwable failure - ) { - if (failure != null || result == null) { - operation.sender().sendMessage(C.RED + "Background vanilla export for '" - + operation.structureKey() + "' failed: " - + (failure == null ? "no result" : failure.getMessage())); - return; - } - for (VanillaJigsawExportDiagnostic diagnostic : result.diagnostics()) { - C color = diagnostic.isBlocking() ? C.RED : C.YELLOW; - operation.sender().sendMessage(color.toString() + diagnostic.code() + ": " + diagnostic.message()); - } - ActiveContext current = active(operation.player()); - boolean sameSession = current != null - && current.request().requestId().equals(operation.requestId()); - String contextLabel = sameSession ? "Vanilla export" : "Background vanilla export for '" - + operation.structureKey() + "'"; - operation.sender().sendMessage((result.isSuccess() ? C.GREEN : C.RED) + contextLabel + " " - + result.status() + ": " + result.output()); - } - - static ActiveContext active(Player player) { - if (player == null) { - return null; - } - SessionBinding binding = PLAYER_PACKS.get(player.getUniqueId()); - if (binding == null) { - return null; - } - ActiveContext context = context(binding); - if (context == null) { - PLAYER_PACKS.remove(player.getUniqueId(), binding); - return null; - } - return context; - } - - private static ActiveContext context(SessionBinding binding) { - JigsawStudioActivation.Request request = JigsawStudioActivation.getRequest(binding.packKey()); - JigsawStudioSession session = JigsawStudioActivation.getSession(binding.packKey()); - if (request == null || session == null - || !binding.requestId().equals(request.requestId()) - || !request.requestId().equals(session.sessionId())) { - return null; - } - return new ActiveContext(binding.packKey(), request, session); - } - - private static ActiveContext findDirtyContext() { - for (SessionBinding binding : PLAYER_PACKS.values()) { - JigsawStudioActivation.Request request = JigsawStudioActivation.getRequest(binding.packKey()); - JigsawStudioSession session = JigsawStudioActivation.getSession(binding.packKey()); - if (request != null && session != null - && binding.requestId().equals(request.requestId()) - && session.isDirty()) { - return new ActiveContext(binding.packKey(), request, session); - } - } - return null; - } - - private ActiveContext requireActive() { - ActiveContext context = active(player()); - if (context == null) { - sendError("Open a Jigsaw Studio project first."); - } - return context; - } - - private IrisData requireData(IrisDimension dimension) { - return requireData(dimension, sender()); - } - - private static IrisData requireData(IrisDimension dimension, VolmitSender commandSender) { - IrisData data = dimension == null ? null : dimension.getLoader(); - if (data == null) { - sendError(commandSender, "Could not resolve the requested Iris pack dimension."); - } - return data; - } - - private static void beginStagedOpen(JigsawStudioActivation.StagedActivation staged) { - if (!JigsawStudioActivation.beginStagedGeneration(staged)) { - throw new IllegalStateException("The staged Jigsaw Studio activation is no longer current"); - } - } - - private static void finishOpenAttempt( - VolmitSender commandSender, - UUID playerId, - String structureKey, - UUID closingRequestId, - JigsawStudioService studioService, - JigsawStudioActivation.StagedActivation staged, - StudioOpenCoordinator.StudioOpenResult result, - Throwable throwable - ) { - JigsawStudioActivation.finishOpen(playerId); - if (throwable == null && result != null) { - studioService.cancelClose(closingRequestId); - return; - } - studioService.cancelClose(closingRequestId); - JigsawStudioActivation.rollback(staged); - Throwable failure = unwrapCompletionFailure(throwable == null - ? new IllegalStateException("Studio open completed without a result") - : throwable); - if (isExpectedOpenDenial(failure)) { - Iris.warn("Jigsaw Studio open for '%s' was denied: %s", - structureKey, failure.getMessage()); - return; - } - Iris.reportError("Failed to open Jigsaw Studio for '" + structureKey + "'.", failure); - sendError(commandSender, "Jigsaw Studio open failed: " + failure.getMessage()); - } - - private static void finishOpen( - Player targetPlayer, - World world, - JigsawStudioActivation.StagedActivation staged, - JigsawStudioService studioService - ) { - if (world == null) { - throw new IllegalStateException("Jigsaw Studio opened without a world"); - } - JigsawStudioActivation.Request request = staged.request(); - JigsawStudioSession session = staged.session(); - try { - WorldRuntimeControlService.get().applyObjectStudioWorldRules(world); - } catch (Throwable exception) { - Iris.reportError("Failed to apply Jigsaw Studio world rules for '" + world.getName() + "'.", exception); - } - JigsawStudioBay destination = initialBay(session.layout()); - Location target = destination == null - ? new Location(world, 0.5D, 66D, 0.5D) - : new Location( - world, - destination.bounds().originX() + destination.bounds().dimensions().width() / 2.0D, - destination.bounds().maxY() + 2.0D, - destination.bounds().originZ() + destination.bounds().dimensions().depth() / 2.0D); - if (destination != null) { - session.selectBay(destination.stableId()); - } - if (!JigsawStudioActivation.commit(staged)) { - throw new IllegalStateException("The staged Jigsaw Studio activation could not be committed"); - } - studioService.activationCommitted(world, request.requestId()); - PLAYER_PACKS.put(targetPlayer.getUniqueId(), new SessionBinding( - request.packKey(), request.requestId())); - try { - J.runEntity(targetPlayer, () -> BukkitPlatform.teleportAsync(targetPlayer, target) - .thenRun(() -> J.runEntity(targetPlayer, () -> targetPlayer.setGameMode(GameMode.CREATIVE)))); - } catch (RuntimeException exception) { - Iris.reportError("Failed to move the player to the committed Jigsaw Studio workcell.", exception); - } - } - - private static JigsawStudioBay initialBay(JigsawStudioLayout layout) { - for (JigsawStudioBay bay : layout.bays()) { - if (layout.defaultVariant(bay).isPresent()) { - return bay; - } - } - return layout.bays().isEmpty() ? null : layout.bays().getFirst(); - } - - private static Throwable unwrapCompletionFailure(Throwable failure) { - Throwable current = failure; - while (current instanceof CompletionException && current.getCause() != null) { - current = current.getCause(); - } - return current; - } - - static boolean isExpectedOpenDenial(Throwable failure) { - return unwrapCompletionFailure(failure) instanceof BrokenPackException; - } - - private void sendError(String message) { - sender().sendMessage(C.RED + message); - } - - private static void sendError(VolmitSender commandSender, String message) { - commandSender.sendMessage(C.RED + message); - } - - private static JigsawStudioMode parseMode(String value) { - return switch (value.trim().toLowerCase(Locale.ROOT)) { - case "planar", "2d", "planar_jigsaw" -> JigsawStudioMode.PLANAR_JIGSAW; - case "spatial", "3d", "spatial_jigsaw" -> JigsawStudioMode.SPATIAL_JIGSAW; - default -> throw new IllegalArgumentException("Mode must be planar or spatial."); - }; - } - - private static JigsawStudioCompatibilityTarget parseCompatibility(String value) { - return switch (value.trim().toLowerCase(Locale.ROOT)) { - case "extended", "iris", "iris_extended" -> JigsawStudioCompatibilityTarget.IRIS_EXTENDED; - case "vanilla", "portable", "vanilla_portable" -> JigsawStudioCompatibilityTarget.VANILLA_PORTABLE; - default -> throw new IllegalArgumentException("Compatibility must be iris or vanilla."); - }; - } - - private static JigsawStudioCompatibilityTarget compatibilityOf(IrisStructure structure) { - return structure.resolvedCompatibility() == IrisJigsawCompatibility.VANILLA_PORTABLE - ? JigsawStudioCompatibilityTarget.VANILLA_PORTABLE - : JigsawStudioCompatibilityTarget.IRIS_EXTENDED; - } - - static NamespacedKey parseRegisteredStructureKey(String value) { - String normalized = Objects.requireNonNull(value, "Registered structure key").trim() - .toLowerCase(Locale.ROOT); - NamespacedKey key = NamespacedKey.fromString(normalized); - if (key == null) { - throw new IllegalArgumentException( - "Registered structure source must use a valid namespace:path key."); - } - return key; - } - - static String resolveConversionTarget(NamespacedKey source, String value) { - Objects.requireNonNull(source, "Registered structure key"); - String normalized = Objects.requireNonNull(value, "Conversion target").trim() - .toLowerCase(Locale.ROOT); - if (normalized.isEmpty() || "auto".equals(normalized)) { - return StructureImporter.deriveName(source); - } - StructureKey target = StructureKey.parse(normalized, "iris"); - if (!"iris".equals(target.namespace())) { - throw new IllegalArgumentException("Converted Studio targets must use the iris namespace."); - } - return target.path(); - } - - static String conversionFailureMessage(VillageImporter.Result result) { - String message = Objects.requireNonNull(result, "Village import result").message(); - String obsoleteInstruction = "; use 'import' for single-template structures"; - int instructionIndex = message.indexOf(obsoleteInstruction); - if (instructionIndex < 0) { - return message; - } - return message.substring(0, instructionIndex) - + ". This Studio converter accepts registered jigsaw structures only."; - } - - static String parseAdoptionSource(String value) { - String normalized = Objects.requireNonNull(value, "Adoption source").trim() - .toLowerCase(Locale.ROOT); - StructureKey source = StructureKey.parse(normalized, "iris"); - if (!"iris".equals(source.namespace())) { - throw new IllegalArgumentException("Adoption sources must use the iris namespace."); - } - return source.path(); - } - - static Optional parseAdoptionTarget(String value) { - String normalized = Objects.requireNonNull(value, "Adoption target").trim() - .toLowerCase(Locale.ROOT); - if (normalized.isEmpty() || "auto".equals(normalized)) { - return Optional.empty(); - } - StructureKey target = StructureKey.parse(normalized, "iris"); - if (!"iris".equals(target.namespace())) { - throw new IllegalArgumentException("Adoption targets must use the iris namespace."); - } - return Optional.of(target); - } - - private static IrisStructureAdoptionStrategy parseAdoptionStrategy(String value) { - return switch (Objects.requireNonNull(value, "Adoption strategy").trim().toLowerCase(Locale.ROOT)) { - case "auto" -> IrisStructureAdoptionStrategy.AUTO; - case "in-place", "in_place", "inplace", "claim" -> IrisStructureAdoptionStrategy.IN_PLACE; - case "clone", "copy" -> IrisStructureAdoptionStrategy.CLONE; - default -> throw new IllegalArgumentException("Adoption strategy must be auto, in-place, or clone."); - }; - } - - static IrisStructureAdoptionInputKind adoptionInputKind(Path packRoot, String source) throws IOException { - Path root = canonicalAdoptionRoot(packRoot); - StructureKey sourceKey = new StructureKey("iris", parseAdoptionSource(source)); - Path manifestPath = new StructureTransactionWriter(root).ownershipManifestPath(sourceKey); - if (!Files.exists(manifestPath, LinkOption.NOFOLLOW_LINKS)) { - return IrisStructureAdoptionInputKind.UNOWNED_IRIS; - } - if (!Files.isRegularFile(manifestPath, LinkOption.NOFOLLOW_LINKS)) { - throw new IOException("Ownership manifest is not a regular file: " + manifestPath); - } - StructureOwnershipManifest manifest; - try { - manifest = StructureOwnershipManifest.fromJson(Files.readAllBytes(manifestPath)); - } catch (RuntimeException exception) { - throw new IOException("Invalid ownership manifest at " + manifestPath, exception); - } - if (!manifest.structure().equals(sourceKey)) { - throw new IOException("Ownership manifest at " + manifestPath - + " belongs to " + manifest.structure().value()); - } - return manifest.provenance().origin() == StructureOwnershipManifest.Origin.MANAGED_DATAPACK - ? IrisStructureAdoptionInputKind.MANAGED_DATAPACK - : IrisStructureAdoptionInputKind.UNOWNED_IRIS; - } - - private static Path canonicalAdoptionRoot(Path packRoot) throws IOException { - Path normalized = Objects.requireNonNull(packRoot, "Adoption pack root").toAbsolutePath().normalize(); - return Files.exists(normalized, LinkOption.NOFOLLOW_LINKS) ? normalized.toRealPath() : normalized; - } - - private static VanillaJigsawExportFormat parseFormat(String value) { - return switch (value.trim().toLowerCase(Locale.ROOT)) { - case "zip" -> VanillaJigsawExportFormat.ZIP; - case "directory", "dir", "folder" -> VanillaJigsawExportFormat.DIRECTORY; - default -> throw new IllegalArgumentException("Export format must be directory or zip."); - }; - } - - static Path resolveExportDestination( - Path exportRoot, - String output, - VanillaJigsawExportFormat format - ) { - Path root = Objects.requireNonNull(exportRoot, "Jigsaw export root").toAbsolutePath().normalize(); - String requested = Objects.requireNonNull(output, "Jigsaw export output name"); - String name = requested.trim(); - if (!name.equals(requested) || !EXPORT_OUTPUT_NAME.matcher(name).matches()) { - throw new IllegalArgumentException( - "Export output must be one file name using letters, numbers, '.', '_', or '-'."); - } - String fileName = format == VanillaJigsawExportFormat.ZIP && !name.endsWith(".zip") - ? name + ".zip" : name; - Path destination = root.resolve(fileName).normalize(); - if (destination.equals(root) || !root.equals(destination.getParent())) { - throw new IllegalArgumentException("Export output must be one artifact inside the Studio exports folder."); - } - return destination; - } - - static JigsawStudioBay selectedBay(ActiveContext context) { - String selected = context.session().selectedBayId().orElse(null); - return selected == null ? null : context.session().layout().get(selected); - } - - static JigsawStudioVariant selectedVariant(ActiveContext context) { - JigsawStudioBay selected = selectedBay(context); - return selected == null - ? null - : context.session().activeVariant(selected.stableId()).orElse(null); - } - - static boolean runGraphMutation( - Player player, - ActiveContext context, - JigsawStudioService.CommandGraphMutation mutation - ) { - return JigsawStudioService.get().runCommandGraphMutation( - player, - context.request().requestId(), - mutation); - } - - static JigsawStudioLayout loadPersistedLayout(ActiveContext context) throws IOException { - IrisData source = context.request().source(); - source.invalidateStructureResources(); - IrisStructure structure = StructureResources.structure(source.getPackResources(), context.request().structureKey()); - if (structure == null) { - throw new IOException("The structure could not be reloaded after the graph transaction"); - } - return JigsawStudioGraphMapper.map(source, structure); - } - - static JigsawStudioService.CommandGraphMutationResult mappedMutationResult( - ActiveContext context, - String activateWorkcellId, - String activatePieceKey, - String message - ) throws IOException { - return new JigsawStudioService.CommandGraphMutationResult( - loadPersistedLayout(context), - activateWorkcellId, - activatePieceKey, - message); - } - - static String workcellIdForVariant(JigsawStudioLayout layout, String pieceKey) throws IOException { - JigsawStudioVariant variant = layout.variantCatalog().find(pieceKey).orElse(null); - if (variant == null) { - throw new IOException("Persisted variant '" + pieceKey + "' did not map to a Studio workcell"); - } - return variant.archetype() - .map(archetype -> archetype.stableId()) - .orElse(JigsawStudioLayout.SPATIAL_WORKCELL_ID); - } - - static PieceWorkcellResolution resolvePieceWorkcell( - JigsawStudioLayout layout, - IrisJigsawPiece piece, - IrisObject object - ) { - JigsawStudioLayout activeLayout = Objects.requireNonNull(layout, "Jigsaw Studio layout"); - IrisJigsawPiece activePiece = Objects.requireNonNull(piece, "Jigsaw piece"); - IrisObject activeObject = Objects.requireNonNull(object, "Jigsaw piece object"); - String workcellId; - IrisPosition requiredDimensions; - if (activeLayout.mode() == JigsawStudioMode.PLANAR_JIGSAW) { - IrisJigsawWorkcellArchetype modelArchetype = IrisJigsawWorkcellArchetype.fromPiece(activePiece); - workcellId = JigsawPlanarArchetype.fromModel(modelArchetype).stableId(); - requiredDimensions = PlanarJigsawWorkcellResolver.canonicalDimensions(activePiece, activeObject); - } else { - workcellId = JigsawStudioLayout.SPATIAL_WORKCELL_ID; - requiredDimensions = new IrisPosition( - activeObject.getW(), - activeObject.getH(), - activeObject.getD()); - } - JigsawStudioBay workcell = activeLayout.get(workcellId); - if (workcell == null) { - throw new IllegalArgumentException("Workcell '" + workcellId + "' is not configured"); - } - return new PieceWorkcellResolution(workcell, requiredDimensions); - } - - static String nextThemeKey(ActiveContext context) throws IOException { - IrisStructure structure = StructureResources.structure( - context.request().source().getPackResources(), - context.request().structureKey()); - if (structure == null) { - throw new IOException("The active jigsaw structure could not be loaded"); - } - Set declared = new HashSet<>(); - if (structure.getThemeSets() != null) { - for (IrisJigsawThemeSet themeSet : structure.getThemeSets()) { - if (themeSet != null && themeSet.getKey() != null) { - declared.add(themeSet.getKey()); - } - } - } - int candidate = 1; - while (candidate > 0) { - String key = "variant-" + candidate; - if (!declared.contains(key)) { - return key; - } - candidate = Math.incrementExact(candidate); - } - throw new IOException("Jigsaw Studio cannot allocate another numbered family key"); - } - - static void sendError(DirectorExecutor executor, String message) { - executor.sender().sendMessage(C.RED + message); - } - - public record ActiveContext( - String packKey, - JigsawStudioActivation.Request request, - JigsawStudioSession session - ) { - } - - record PieceWorkcellResolution( - JigsawStudioBay workcell, - IrisPosition requiredDimensions - ) { - PieceWorkcellResolution { - workcell = Objects.requireNonNull(workcell, "Jigsaw Studio workcell"); - requiredDimensions = Objects.requireNonNull(requiredDimensions, "Jigsaw piece dimensions"); - } - - boolean fits() { - JigsawStudioCellDimensions capacity = workcell.capacity(); - return requiredDimensions.getX() <= capacity.width() - && requiredDimensions.getY() <= capacity.height() - && requiredDimensions.getZ() <= capacity.depth(); - } - } - - private record SessionBinding(String packKey, UUID requestId) { - } - - private record ExportOperation( - Player player, - VolmitSender sender, - UUID requestId, - String structureKey, - VanillaJigsawExportRequest request, - ExportLease lease - ) { - } - - static final class ExportLease { - private final Runnable release; - private final AtomicBoolean released; - - ExportLease(Runnable release) { - this.release = Objects.requireNonNull(release, "Jigsaw export lease release action"); - this.released = new AtomicBoolean(); - } - - void release() { - if (released.compareAndSet(false, true)) { - release.run(); - } - } - } - - private record AdoptionPlanBinding( - UUID ownerId, - IrisDimension dimension, - IrisData data, - IrisStructureAdoptionService service, - IrisStructureAdoptionPlan plan - ) { - } - - public static final class JigsawModeHandler implements DirectorParameterHandler { - @Override - public KList getPossibilities() { - return new KList<>("planar", "spatial"); - } - - @Override - public String toString(String value) { - return value == null ? "" : value; - } - - @Override - public String parse(String input, boolean force) throws DirectorParsingException { - try { - return parseMode(input) == JigsawStudioMode.PLANAR_JIGSAW ? "planar" : "spatial"; - } catch (IllegalArgumentException exception) { - throw new DirectorParsingException(exception.getMessage()); - } - } - - @Override - public boolean supports(Class type) { - return type == String.class; - } - } - - public static final class JigsawCompatibilityHandler implements DirectorParameterHandler { - @Override - public KList getPossibilities() { - return new KList<>("iris", "vanilla"); - } - - @Override - public String toString(String value) { - return value == null ? "" : value; - } - - @Override - public String parse(String input, boolean force) throws DirectorParsingException { - try { - return parseCompatibility(input) == JigsawStudioCompatibilityTarget.IRIS_EXTENDED - ? "iris" : "vanilla"; - } catch (IllegalArgumentException exception) { - throw new DirectorParsingException(exception.getMessage()); - } - } - - @Override - public boolean supports(Class type) { - return type == String.class; - } - } - - public static final class JigsawAdoptionStrategyHandler implements DirectorParameterHandler { - @Override - public KList getPossibilities() { - return new KList<>("auto", "in-place", "clone"); - } - - @Override - public String toString(String value) { - return value == null ? "" : value; - } - - @Override - public String parse(String input, boolean force) throws DirectorParsingException { - try { - return switch (parseAdoptionStrategy(input)) { - case AUTO -> "auto"; - case IN_PLACE -> "in-place"; - case CLONE -> "clone"; - }; - } catch (IllegalArgumentException exception) { - throw new DirectorParsingException(exception.getMessage()); - } - } - - @Override - public boolean supports(Class type) { - return type == String.class; - } - } - - public static final class JigsawAdoptionPlanHandler implements DirectorParameterHandler { - @Override - public KList getPossibilities() { - return new KList<>(); - } - - @Override - public String toString(String value) { - return value == null ? "" : value; - } - - @Override - public String parse(String input, boolean force) throws DirectorParsingException { - try { - return UUID.fromString(input).toString(); - } catch (IllegalArgumentException exception) { - throw new DirectorParsingException("Adoption plan ID must be a UUID."); - } - } - - @Override - public boolean supports(Class type) { - return type == String.class; - } - } - - @Director(name = "adopt", description = "Inspect and apply safe ownership adoption plans", - origin = DirectorOrigin.PLAYER) - public static class CommandJigsawAdopt implements DirectorExecutor { - @Director(description = "Inspect an Iris graph for safe Studio ownership adoption", sync = true, - origin = DirectorOrigin.PLAYER) - public void inspect( - @Param(description = "Pack dimension") IrisDimension dimension, - @Param(description = "Existing Iris structure key") String source, - @Param(description = "New owned Iris key, or auto", defaultValue = "auto") String target, - @Param(description = "auto, in-place, or clone", defaultValue = "auto", - customHandler = JigsawAdoptionStrategyHandler.class) String strategy - ) { - VolmitSender commandSender = sender(); - IrisData data = requireData(dimension, commandSender); - if (data == null) { - return; - } - String sourceKey; - Optional targetKey; - IrisStructureAdoptionStrategy adoptionStrategy; - Path root; - try { - sourceKey = parseAdoptionSource(source); - targetKey = parseAdoptionTarget(target); - adoptionStrategy = parseAdoptionStrategy(strategy); - root = canonicalAdoptionRoot(data.getDataFolder().toPath()); - } catch (IOException | IllegalArgumentException exception) { - sendError(commandSender, "Could not inspect adoption source: " + exception.getMessage()); - return; - } - Player targetPlayer = player(); - UUID ownerId = targetPlayer.getUniqueId(); - commandSender.sendMessage(C.GRAY + "Inspecting Jigsaw adoption source '" + sourceKey - + "' asynchronously..."); - try { - J.a(() -> runAdoptionInspect( - targetPlayer, - commandSender, - ownerId, - dimension, - data, - root, - sourceKey, - targetKey, - adoptionStrategy)); - } catch (RuntimeException exception) { - Iris.reportError("Failed to schedule Jigsaw adoption inspection for '" - + sourceKey + "'.", exception); - sendError(commandSender, "Jigsaw adoption inspection could not be scheduled: " - + exception.getMessage()); - } - } - - @Director(description = "Apply one inspected adoption plan without overwriting", sync = true, - origin = DirectorOrigin.PLAYER) - public void apply( - @Param(description = "Plan UUID returned by adopt inspect", - customHandler = JigsawAdoptionPlanHandler.class) String planId - ) { - VolmitSender commandSender = sender(); - UUID parsedPlanId; - try { - parsedPlanId = UUID.fromString(planId); - } catch (IllegalArgumentException exception) { - sendError(commandSender, "Adoption plan ID must be a UUID."); - return; - } - if (studioIsActiveOrOpening()) { - sendError(commandSender, - "Close the active or opening Jigsaw Studio before applying an adoption plan."); - return; - } - pruneAdoptionPlanBindings(); - AdoptionPlanBinding binding = ADOPTION_PLANS.get(parsedPlanId); - UUID playerId = player().getUniqueId(); - if (binding == null || !binding.ownerId().equals(playerId)) { - sendError(commandSender, "No active adoption plan '" + parsedPlanId - + "' belongs to your player session. Run adopt inspect again."); - return; - } - if (binding.service().plan(parsedPlanId).isEmpty()) { - ADOPTION_PLANS.remove(parsedPlanId, binding); - sendError(commandSender, "Adoption plan '" + parsedPlanId - + "' expired or was already consumed. Run adopt inspect again."); - return; - } - if (!ADOPTION_PLANS.remove(parsedPlanId, binding)) { - sendError(commandSender, "Adoption plan '" + parsedPlanId + "' is already being applied."); - return; - } - Player targetPlayer = player(); - commandSender.sendMessage(C.GRAY + "Applying adoption plan '" + parsedPlanId - + "' asynchronously without overwrite..."); - try { - J.a(() -> runAdoptionApply(targetPlayer, commandSender, parsedPlanId, binding)); - } catch (RuntimeException exception) { - ADOPTION_PLANS.putIfAbsent(parsedPlanId, binding); - Iris.reportError("Failed to schedule Jigsaw adoption plan '" + parsedPlanId + "'.", exception); - sendError(commandSender, "Jigsaw adoption could not be scheduled: " + exception.getMessage()); - } - } - } - - @Director(name = "connector", description = "Inspect and configure targeted jigsaw connectors", - origin = DirectorOrigin.PLAYER) - public static class CommandJigsawConnector implements DirectorExecutor { - @Director(description = "Set the Iris-only channel on the targeted jigsaw marker", sync = true, - origin = DirectorOrigin.PLAYER) - public void channel( - @Param(description = "Exact channel, or none to clear") String channel - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - Block target = player().getTargetBlockExact(8); - if (target == null || !(target.getBlockData() instanceof Jigsaw)) { - sendError(this, "Look directly at a jigsaw marker within eight blocks."); - return; - } - JigsawStudioBay bay = context.session().layout().findAt( - target.getX(), target.getY(), target.getZ()); - JigsawStudioVariant activeVariant = bay == null - ? null - : context.session().activeVariant(bay.stableId()).orElse(null); - if (activeVariant == null) { - sendError(this, "The targeted marker must be inside a workcell with an active variant."); - return; - } - if (!activeVariant.owned()) { - sendError(this, "The active variant is read-only. Adopt it into this project before editing it."); - return; - } - IrisObject object = context.request().source().getObjectLoader().load(activeVariant.objectKey()); - if (object == null) { - sendError(this, "The active variant object '" + activeVariant.objectKey() + "' is missing."); - return; - } - IrisPosition canonicalPosition = new IrisPosition( - target.getX() - bay.bounds().originX(), - target.getY() - bay.bounds().originY(), - target.getZ() - bay.bounds().originZ()); - IrisPosition position; - try { - position = activeVariant.canonicalToSourcePosition( - canonicalPosition, - new JigsawStudioCellDimensions(object.getW(), object.getH(), object.getD())); - } catch (IllegalArgumentException exception) { - sendError(this, "Connector channel update failed: " + exception.getMessage()); - return; - } - String normalized = channel == null || channel.isBlank() || "none".equalsIgnoreCase(channel) - ? "none" - : channel.trim(); - runGraphMutation(player(), context, () -> { - JigsawStudioGraphEditor.updateConnectorChannel( - context.request().source().getDataFolder().toPath(), - context.request().structureKey(), - activeVariant.pieceKey(), - position, - channel); - return mappedMutationResult( - context, - "", - "", - "Persisted connector channel '" + normalized + "' on piece '" - + activeVariant.pieceKey() + "' at " + position.getX() + "," + position.getY() - + "," + position.getZ() + "."); - }); - } - } - - @Director(name = "pool", description = "Manage owned jigsaw pools", origin = DirectorOrigin.PLAYER) - public static class CommandJigsawPool implements DirectorExecutor { - @Director(description = "Create an empty owned jigsaw pool", sync = true, - origin = DirectorOrigin.PLAYER) - public void create( - @Param(description = "New owned pool resource key") String poolKey, - @Param(description = "Owned fallback pool key, or none", defaultValue = "none") - String fallbackPoolKey - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - String fallback = "none".equalsIgnoreCase(fallbackPoolKey) ? "" : fallbackPoolKey; - runGraphMutation(player(), context, () -> { - JigsawStudioGraphEditor.createPool( - context.request().source().getDataFolder().toPath(), - context.request().structureKey(), - poolKey, - fallback); - return mappedMutationResult( - context, - "", - "", - "Created owned pool '" + poolKey + "' with fallback '" - + (fallback.isBlank() ? "none" : fallback) + "'."); - }); - } - } - - @Director(name = "piece", description = "Manage contextual Studio pieces", origin = DirectorOrigin.PLAYER) - public static class CommandJigsawPiece implements DirectorExecutor { - @Director(description = "Create an owned piece from the selected Studio topology", sync = true, - origin = DirectorOrigin.PLAYER) - public void create( - @Param(description = "Owned pool resource key") String poolKey, - @Param(description = "New owned piece and object key") String pieceKey, - @Param(description = "Positive selection weight", defaultValue = "1") int weight - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawPlanarTopology topology = null; - JigsawStudioBay targetWorkcell = context.session().layout().get(JigsawStudioLayout.SPATIAL_WORKCELL_ID); - if (context.session().layout().mode() == JigsawStudioMode.PLANAR_JIGSAW) { - Location location = player().getLocation(); - JigsawStudioBay contextual = context.session().layout().findAt( - location.getBlockX(), location.getBlockY(), location.getBlockZ()); - if (contextual == null) { - contextual = selectedBay(context); - } else { - context.session().selectBay(contextual.stableId()); - } - if (contextual == null || contextual.topology().isEmpty()) { - sendError(this, "Stand in or select a planar topology workcell before creating a variant."); - return; - } - topology = contextual.topology().get(); - targetWorkcell = contextual; - } - if (targetWorkcell == null) { - sendError(this, "The selected Jigsaw Studio workcell is no longer available."); - return; - } - JigsawPlanarTopology selectedTopology = topology; - String activationWorkcellId = targetWorkcell.stableId(); - JigsawStudioCellDimensions dimensions = targetWorkcell.capacity(); - String topologyText = selectedTopology == null ? "blank spatial" : selectedTopology.name(); - runGraphMutation(player(), context, () -> { - JigsawStudioGraphEditor.createPiece( - context.request().source().getDataFolder().toPath(), - context.request().structureKey(), - poolKey, - pieceKey, - weight, - dimensions, - selectedTopology); - return mappedMutationResult( - context, - activationWorkcellId, - pieceKey, - "Created owned " + topologyText + " piece '" + pieceKey - + "' and added it to pool '" + poolKey + "' atomically."); - }); - } - - @Director(description = "Add an existing jigsaw piece to an owned pool transactionally", sync = true, - origin = DirectorOrigin.PLAYER) - public void add( - @Param(description = "Owned pool resource key") String poolKey, - @Param(description = "Existing jigsaw piece key") String pieceKey, - @Param(description = "Positive selection weight", defaultValue = "1") int weight - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - IrisJigsawPiece piece = StructureResources.piece(context.request().source().getPackResources(), pieceKey); - if (piece == null) { - sendError(this, "No jigsaw piece '" + pieceKey + "' exists in this pack."); - return; - } - if (piece.getObject() == null || piece.getObject().isBlank()) { - sendError(this, "Jigsaw piece '" + pieceKey + "' does not declare an object."); - return; - } - IrisObject object = context.request().source().getObjectLoader().load(piece.getObject()); - if (object == null) { - sendError(this, "Jigsaw piece '" + pieceKey + "' has no loadable object."); - return; - } - PieceWorkcellResolution resolution; - try { - resolution = resolvePieceWorkcell(context.session().layout(), piece, object); - } catch (IllegalArgumentException exception) { - sendError(this, "Jigsaw piece '" + pieceKey + "' cannot be assigned to a Studio workcell: " - + exception.getMessage()); - return; - } - if (!resolution.fits()) { - IrisPosition required = resolution.requiredDimensions(); - JigsawStudioCellDimensions capacity = resolution.workcell().capacity(); - sendError(this, "Jigsaw piece '" + pieceKey + "' requires " + required.getX() + "x" - + required.getY() + "x" + required.getZ() + " in " + resolution.workcell().displayName() - + ", but that workcell capacity is " + capacity.width() + "x" + capacity.height() - + "x" + capacity.depth() + "."); - return; - } - String objectKey = piece.getObject(); - runGraphMutation(player(), context, () -> { - if (!JigsawStudioGraphEditor.ownsPiece( - context.request().source().getDataFolder().toPath(), - context.request().structureKey(), - pieceKey, - objectKey)) { - throw new IOException("Piece add accepts only piece/object resources already owned by this project; " - + "use piece create for a new owned piece"); - } - JigsawStudioPoolEditor.PoolUpdate update = JigsawStudioPoolEditor.addPiece( - context.request().source().getDataFolder().toPath(), - context.request().structureKey(), - poolKey, - pieceKey, - weight); - if (!update.changed()) { - throw new IOException("The owned pool is missing or already references '" + pieceKey + "'"); - } - JigsawStudioLayout layout = loadPersistedLayout(context); - String activationWorkcellId = workcellIdForVariant(layout, pieceKey); - return new JigsawStudioService.CommandGraphMutationResult( - layout, - activationWorkcellId, - pieceKey, - "Added '" + pieceKey + "' to pool '" + poolKey + "' in one graph transaction."); - }); - } - - @Director(description = "Remove the selected piece from an owned pool transactionally", sync = true, - origin = DirectorOrigin.PLAYER) - public void remove( - @Param(description = "Owned pool resource key") String poolKey - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawStudioVariant selected = selectedVariant(context); - if (selected == null) { - sendError(this, "Select a workcell with an active variant before removing its pool entry."); - return; - } - String pieceKey = selected.pieceKey(); - runGraphMutation(player(), context, () -> { - JigsawStudioPoolEditor.PoolUpdate update = JigsawStudioPoolEditor.removePiece( - context.request().source().getDataFolder().toPath(), - context.request().structureKey(), - poolKey, - pieceKey); - if (!update.changed()) { - throw new IOException("The owned pool does not reference selected piece '" + pieceKey + "'"); - } - return mappedMutationResult( - context, - "", - "", - "Removed '" + pieceKey + "' from pool '" + poolKey + "' in one graph transaction."); - }); - } - - @Director(description = "Allow or forbid cardinal rotation of the selected piece", sync = true, - origin = DirectorOrigin.PLAYER) - public void rotatable( - @Param(description = "Whether the selected piece may rotate") boolean rotatable - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawStudioVariant selected = selectedVariant(context); - if (selected == null) { - sendError(this, "Select a workcell with an active variant before changing rotation."); - return; - } - if (!rotatable - && context.request().compatibilityTarget() - == JigsawStudioCompatibilityTarget.VANILLA_PORTABLE) { - sendError(this, "Vanilla-portable pieces must remain rotatable."); - return; - } - String pieceKey = selected.pieceKey(); - runGraphMutation(player(), context, () -> { - JigsawStudioGraphEditor.updateRotatable( - context.request().source().getDataFolder().toPath(), - context.request().structureKey(), - pieceKey, - rotatable); - return mappedMutationResult( - context, - "", - "", - "Persisted piece '" + pieceKey + "' rotatable=" + rotatable + "."); - }); - } - - @Director(description = "Resize the selected piece object exactly to workcell capacity", sync = true, - origin = DirectorOrigin.PLAYER) - public void expand() { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawStudioBay workcell = selectedBay(context); - if (workcell == null) { - sendError(this, "Select a workcell before expanding its active variant."); - return; - } - JigsawStudioService.get().expandVariantToCell(player(), workcell.stableId()); - } - } - - @Director(name = "workcell", aliases = "cell", description = "Manage the selected Studio workcell", - origin = DirectorOrigin.PLAYER) - public static class CommandJigsawWorkcell implements DirectorExecutor { - @Director(description = "Set capacity without resizing any variant object", sync = true, - origin = DirectorOrigin.PLAYER) - public void capacity( - @Param(description = "Capacity width") int width, - @Param(description = "Capacity height") int height, - @Param(description = "Capacity depth") int depth - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawStudioBay selected = selectedBay(context); - if (selected == null) { - sendError(this, "Select a workcell before changing its capacity."); - return; - } - JigsawStudioCellDimensions dimensions; - try { - dimensions = new JigsawStudioCellDimensions(width, height, depth); - } catch (IllegalArgumentException exception) { - sendError(this, exception.getMessage()); - return; - } - JigsawStudioService.get().updateWorkcellDimensions( - player(), - selected.stableId(), - dimensions); - } - - @Director(description = "Set the selected workcell's author-facing label", sync = true, - origin = DirectorOrigin.PLAYER) - public void label( - @Param(description = "Display label; quote labels containing spaces") String displayName - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawStudioBay selected = selectedBay(context); - if (selected == null) { - sendError(this, "Select a workcell before renaming it."); - return; - } - JigsawStudioService.get().updateWorkcellDisplayName( - player(), - selected.stableId(), - displayName); - } - - @Director(name = "label-reset", aliases = "reset-label", - description = "Reset the selected workcell to its canonical solver label", sync = true, - origin = DirectorOrigin.PLAYER) - public void labelReset() { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawStudioBay selected = selectedBay(context); - if (selected == null) { - sendError(this, "Select a workcell before resetting its label."); - return; - } - JigsawStudioService.get().updateWorkcellDisplayName(player(), selected.stableId(), ""); - } - } - - @Director(name = "variant", description = "Manage selected jigsaw variants", origin = DirectorOrigin.PLAYER) - public static class CommandJigsawVariant implements DirectorExecutor { - @Director(description = "Set the selected piece weight in a pool", sync = true, - origin = DirectorOrigin.PLAYER) - public void weight( - @Param(description = "Pool resource key") String poolKey, - @Param(description = "Positive selection weight") int weight - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawStudioVariant selected = selectedVariant(context); - if (selected == null) { - sendError(this, "Select a workcell with an active variant before changing its weight."); - return; - } - String pieceKey = selected.pieceKey(); - runGraphMutation(player(), context, () -> { - JigsawStudioPoolEditor.WeightUpdate update = JigsawStudioPoolEditor.updateWeight( - context.request().source().getDataFolder().toPath(), - context.request().structureKey(), - poolKey, - pieceKey, - weight); - if (!update.changed()) { - throw new IOException("Pool '" + poolKey + "' does not reference selected piece '" - + pieceKey + "'"); - } - return mappedMutationResult( - context, - "", - "", - "Updated " + update.changedEntries() + " pool entry weight atomically in " - + update.poolPath() + "."); - }); - } - - @Director(description = "Resize only the active variant object within workcell capacity", sync = true, - origin = DirectorOrigin.PLAYER) - public void resize( - @Param(description = "Variant width") int width, - @Param(description = "Variant height") int height, - @Param(description = "Variant depth") int depth - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawStudioBay selectedWorkcell = selectedBay(context); - JigsawStudioVariant selectedVariant = selectedVariant(context); - if (selectedWorkcell == null || selectedVariant == null) { - sendError(this, "Select a workcell with an active variant before resizing it."); - return; - } - JigsawStudioCellDimensions dimensions; - try { - dimensions = new JigsawStudioCellDimensions(width, height, depth); - } catch (IllegalArgumentException exception) { - sendError(this, exception.getMessage()); - return; - } - JigsawStudioService.get().resizeVariant( - player(), - selectedWorkcell.stableId(), - selectedVariant.pieceKey(), - dimensions); - } - - @Director(description = "Set the active variant's author-facing label", sync = true, - origin = DirectorOrigin.PLAYER) - public void label( - @Param(description = "Display label; quote labels containing spaces") String displayName - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawStudioBay selectedWorkcell = selectedBay(context); - JigsawStudioVariant selectedVariant = selectedVariant(context); - if (selectedWorkcell == null || selectedVariant == null) { - sendError(this, "Select a workcell with an active variant before renaming it."); - return; - } - JigsawStudioService.get().updateVariantDisplayName( - player(), - selectedWorkcell.stableId(), - selectedVariant.pieceKey(), - displayName); - } - - @Director(name = "label-reset", aliases = "reset-label", - description = "Reset the active variant to its resource-key label", sync = true, - origin = DirectorOrigin.PLAYER) - public void labelReset() { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawStudioBay selectedWorkcell = selectedBay(context); - JigsawStudioVariant selectedVariant = selectedVariant(context); - if (selectedWorkcell == null || selectedVariant == null) { - sendError(this, "Select a workcell with an active variant before resetting its label."); - return; - } - JigsawStudioService.get().updateVariantDisplayName( - player(), - selectedWorkcell.stableId(), - selectedVariant.pieceKey(), - ""); - } - - @Director(description = "Duplicate the active variant in only this workcell", sync = true, - origin = DirectorOrigin.PLAYER) - public void duplicate() { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - JigsawStudioBay selected = selectedBay(context); - if (selected == null || selectedVariant(context) == null) { - sendError(this, "Select a workcell with an active variant before duplicating it."); - return; - } - JigsawStudioService.get().createVariant(player(), selected.stableId(), true); - } - - @Director(name = "duplicate-family", aliases = "family", - description = "Duplicate every enabled workcell's active variant as one coherent family", - sync = true, origin = DirectorOrigin.PLAYER) - public void duplicateFamily( - @Param(description = "Family key or next", defaultValue = "next") String themeKey - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - String selectedTheme = themeKey; - if ("next".equalsIgnoreCase(themeKey)) { - try { - selectedTheme = nextThemeKey(context); - } catch (IOException | ArithmeticException exception) { - sendError(this, exception.getMessage()); - return; - } - } - JigsawStudioService.get().duplicateActiveFamily(player(), selectedTheme); - } - } - - @Director(name = "rules", aliases = "rule", description = "Manage structure-wide jigsaw rules", - origin = DirectorOrigin.PLAYER) - public static class CommandJigsawRules implements DirectorExecutor { - @Director(description = "Set maximum expansion depth and horizontal radius", sync = true, - origin = DirectorOrigin.PLAYER) - public void limits( - @Param(description = "Maximum expansion depth") int maxDepth, - @Param(description = "Maximum radius in chunks") int maxSizeChunks - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - if (context.request().compatibilityTarget() == JigsawStudioCompatibilityTarget.VANILLA_PORTABLE - && (maxDepth > 20 || maxSizeChunks > 8)) { - sendError(this, "Vanilla-portable rules require maxDepth <= 20 and maxSizeChunks <= 8."); - return; - } - runGraphMutation(player(), context, () -> { - JigsawStudioStructureEditor.updateLimits( - context.request().source().getDataFolder().toPath(), - context.request().structureKey(), - maxDepth, - maxSizeChunks); - return mappedMutationResult( - context, - "", - "", - "Persisted jigsaw limits: maxDepth=" + maxDepth - + ", maxSizeChunks=" + maxSizeChunks + "."); - }); - } - - @Director(description = "Set or clear one owned pool's direct fallback", sync = true, - origin = DirectorOrigin.PLAYER) - public void fallback( - @Param(description = "Owned pool resource key") String poolKey, - @Param(description = "Owned fallback pool key, or none") String fallbackPoolKey - ) { - ActiveContext context = active(player()); - if (context == null) { - sendError(this, "Open a Jigsaw Studio project first."); - return; - } - String fallback = "none".equalsIgnoreCase(fallbackPoolKey) ? "" : fallbackPoolKey; - runGraphMutation(player(), context, () -> { - JigsawStudioPoolEditor.PoolUpdate update = JigsawStudioPoolEditor.updateFallback( - context.request().source().getDataFolder().toPath(), - context.request().structureKey(), - poolKey, - fallback); - if (!update.changed()) { - return mappedMutationResult(context, "", "", "Pool fallback is unchanged."); - } - return mappedMutationResult( - context, - "", - "", - "Persisted pool '" + poolKey + "' fallback as '" - + (fallback.isBlank() ? "none" : fallback) + "'."); - }); - } - } - - @Director(name = "preview", description = "Assemble a read-only jigsaw preview", - origin = DirectorOrigin.PLAYER) - public static class CommandJigsawPreview implements DirectorExecutor { - @Director(name = "goto", aliases = "teleport", description = "Teleport to the live seed-1337 preview", - sync = true, origin = DirectorOrigin.PLAYER) - public void gotoPreview() { - JigsawStudioService.get().goToPreview(player()); - } - - @Director(description = "Assemble a deterministic preview at your location", sync = true, - origin = DirectorOrigin.PLAYER) - public void assemble( - @Param(description = "Assembly seed", defaultValue = "1337") long seed - ) { - JigsawStudioService.get().previewStudio(player(), seed); - } - - } -} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStructure.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStructure.java deleted file mode 100644 index 5fca87e87..000000000 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/commands/CommandStructure.java +++ /dev/null @@ -1,71 +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.commands; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.structure.BulkStructureImporter; -import art.arcane.iris.core.structure.StructureCaptureImporter; -import art.arcane.iris.core.structure.StructureImporter; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.util.common.director.DirectorExecutor; -import art.arcane.volmlib.util.director.DirectorOrigin; -import art.arcane.volmlib.util.director.annotations.Director; -import art.arcane.volmlib.util.director.annotations.Param; - -import art.arcane.iris.core.localization.IrisLanguage; -import art.arcane.volmlib.util.localization.MessageArgument; -import art.arcane.iris.core.localization.BukkitCommandMessagesExtended; -@Director(name = "structure", aliases = {"struct", "str"}, description = "Iris structure tools (index, import, info)", descriptionKey = "iris.director.commandstructure.director.iris_structure_tools_index_import_info") -public class CommandStructure implements DirectorExecutor { - @Director(name = "import", description = "Import EVERY structure - vanilla AND ingested datapacks - into this pack as editable Iris resources, always overwriting. Rebuilds jigsaw structures (villages, outposts, datapack jigsaws) as editable pool/piece graphs, imports every structure template NBT as an object, and assembles the multi-template structures (shipwrecks, ruined portals, ocean ruins, nether fossils). Run after ingesting a datapack and restarting. Regenerate chunks or use a fresh world for the imported copies to place.", descriptionKey = "iris.director.commandstructure.director.import_every_structure_vanilla_ingested_datapacks_into_this_pack_as_editable_iris", aliases = {"import-all", "reimport", "imp", "all"}, origin = DirectorOrigin.BOTH) - public void importAll( - @Param(description = "The dimension whose pack to import into", descriptionKey = "iris.director.commandstructure.param.dimension_whose_pack_import_into", aliases = "dim") - IrisDimension dimension - ) { - IrisData data = dimension.getLoader(); - if (data == null) { - sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_COULD_NOT_RESOLVE_PACK_DIMENSION_2, MessageArgument.untrusted("value", dimension.getLoadKey()))); - return; - } - sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_IMPORTING_ALL_VANILLA_DATAPACK_STRUCTURES_INTO_OVERWRITE, MessageArgument.untrusted("value", dimension.getLoadKey()))); - BulkStructureImporter.Report jigsaws = BulkStructureImporter.importAllVanilla(data, StructureImporter.Mode.OVERWRITE, true, sender()); - BulkStructureImporter.Report templates = BulkStructureImporter.importAllTemplates(data, StructureImporter.Mode.OVERWRITE, sender()); - BulkStructureImporter.Report groups = BulkStructureImporter.importTemplateGroups(data, StructureImporter.Mode.OVERWRITE, sender()); - StructureCaptureImporter.Report captured = StructureCaptureImporter.importStructures( - data, StructureImporter.Mode.OVERWRITE, sender(), jigsaws.captureCandidates()); - int imported = jigsaws.imported() + templates.imported() + groups.imported() + captured.imported(); - int failed = jigsaws.failed() + templates.failed() + groups.failed() + captured.failed(); - sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_IMPORT_COMPLETE_STRUCTURES_OBJECTS_WRITTEN_FAILED, MessageArgument.untrusted("imported", imported), MessageArgument.untrusted("failed", failed))); - sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_REFERENCE_THEM_FROM_BIOME_REGION_DIMENSION_STRUCTURES_LIST_RUN_IRIS)); - } - - @Director(name = "capture", description = "Capture live registered structures into editable Iris objects by generating each one in a throwaway scratch world and reading back its blocks. This standalone command overwrites its owned outputs; structures wider/taller than the capture cap and anything that will not generate in a flat overworld are skipped. Each captured structure becomes a single-piece Iris structure you can place from a biome/region/dimension 'structures' list. /iris structure import runs a restricted final capture pass only for non-jigsaw structures that have no loadable NBT template.", descriptionKey = "iris.director.commandstructure.director.capture_code_generated_structures_that_have_no_nbt_template_swamp_huts_igloos", aliases = {"cap"}, origin = DirectorOrigin.BOTH) - public void capture( - @Param(description = "The dimension whose pack to capture into", descriptionKey = "iris.director.commandstructure.param.dimension_whose_pack_capture_into", aliases = "dim") - IrisDimension dimension - ) { - IrisData data = dimension.getLoader(); - if (data == null) { - sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_COULD_NOT_RESOLVE_PACK_DIMENSION_3, MessageArgument.untrusted("value", dimension.getLoadKey()))); - return; - } - StructureCaptureImporter.Report report = StructureCaptureImporter.importAllStructures(data, StructureImporter.Mode.OVERWRITE, sender()); - sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_CAPTURED_STRUCTURES_PLACE_THEM_FROM_STRUCTURES_LIST_REGENERATE_CHUNKS_DELETE, MessageArgument.untrusted("value", report.imported()))); - } -} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/service/BukkitToolingSender.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/service/BukkitToolingSender.java index 52c0dbaa2..a41650b08 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/service/BukkitToolingSender.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/service/BukkitToolingSender.java @@ -19,6 +19,7 @@ package art.arcane.iris.core.service; import art.arcane.iris.core.project.IrisProject; +import art.arcane.iris.core.toolworld.BukkitToolWorldService; import art.arcane.iris.core.tooling.IrisServedPack; import art.arcane.iris.core.tooling.SenderWorld; import art.arcane.iris.core.tooling.ServedPack; @@ -30,6 +31,7 @@ import art.arcane.iris.spi.IrisServices; import art.arcane.iris.util.common.format.C; import art.arcane.iris.util.common.plugin.VolmitSender; import art.arcane.iris.util.common.scheduling.J; +import com.volmit.tooling.world.ToolPlayer; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -39,13 +41,13 @@ import java.util.Optional; * A Bukkit sender of a tooling command. It reads the world the sender stands in and the open studio when it is built, which * the adapter does on the thread that received the command, and delivers messages on the sender's own thread. */ -final class BukkitToolingSender implements ToolingSender { +public final class BukkitToolingSender implements ToolingSender { private final CommandSender sender; private final VolmitSender messages; private final Optional world; private final Optional openStudioPack; - BukkitToolingSender(CommandSender sender) { + public BukkitToolingSender(CommandSender sender) { this.sender = sender; this.messages = new VolmitSender(sender); this.world = standingWorld(sender); @@ -77,6 +79,15 @@ final class BukkitToolingSender implements ToolingSender { return type.isInstance(sender) ? Optional.of(type.cast(sender)) : Optional.empty(); } + @Override + public Optional player() { + BukkitToolWorldService toolWorlds = IrisServices.getOrNull(BukkitToolWorldService.class); + if (!(sender instanceof Player player) || toolWorlds == null) { + return Optional.empty(); + } + return Optional.of(toolWorlds.playerOf(player)); + } + @Override public boolean isOperator() { return sender.hasPermission(CommandSVC.ROOT_PERMISSION); diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitCaptureArea.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitCaptureArea.java new file mode 100644 index 000000000..c60cae150 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitCaptureArea.java @@ -0,0 +1,165 @@ +/* + * 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.structure; + +import art.arcane.iris.core.modules.BlockEntities; +import art.arcane.iris.core.modules.PlatformBlockStates; +import art.arcane.iris.core.nms.INMS; +import art.arcane.iris.engine.object.prefab.TileData; +import art.arcane.iris.platform.bukkit.BukkitBlockState; +import art.arcane.iris.util.common.plugin.VolmitSender; +import art.arcane.iris.util.common.scheduling.J; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.CapturedStructure; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.TemplateBlock; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +/** A throwaway Bukkit world structures are generated in one after another, one cell of a grid each, and removed on close. */ +final class BukkitCaptureArea implements PlatformStructures.CaptureArea { + private static final int CELL_STRIDE = 128; + private static final int CELL_COLUMNS = 8; + private static final long REGION_TIMEOUT_SECONDS = 30L; + + private final World world; + private final VolmitSender sender; + private int nextCell; + + BukkitCaptureArea(World world, VolmitSender sender) { + this.world = world; + this.sender = sender; + } + + @Override + public Optional capture(ResourceId structure, long seed, int maxSpan) { + int cellIndex = nextCell++; + int originX = (cellIndex % CELL_COLUMNS) * CELL_STRIDE; + int originZ = (cellIndex / CELL_COLUMNS) * CELL_STRIDE; + int anchorChunkX = (originX + CELL_STRIDE / 2) >> 4; + int anchorChunkZ = (originZ + CELL_STRIDE / 2) >> 4; + String key = structure.toString(); + + AtomicReference capturedRef = new AtomicReference<>(); + AtomicReference errorRef = new AtomicReference<>(); + CountDownLatch latch = new CountDownLatch(1); + + boolean scheduled = J.runRegion(world, anchorChunkX, anchorChunkZ, () -> { + try { + capturedRef.set(placeAndRead(key, anchorChunkX, anchorChunkZ, seed, maxSpan)); + } catch (Throwable e) { + errorRef.set(e); + } finally { + latch.countDown(); + } + }); + + if (!scheduled) { + throw captureFailure(key, anchorChunkX, anchorChunkZ, "region task was not accepted", null); + } + + try { + if (!latch.await(REGION_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { + throw captureFailure(key, anchorChunkX, anchorChunkZ, + "region task did not complete within " + REGION_TIMEOUT_SECONDS + " seconds", null); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw captureFailure(key, anchorChunkX, anchorChunkZ, "interrupted while waiting for the region task", e); + } + + Throwable error = errorRef.get(); + if (error != null) { + throw captureFailure(key, anchorChunkX, anchorChunkZ, "platform placement failed", error); + } + return Optional.ofNullable(capturedRef.get()); + } + + private CapturedStructure placeAndRead(String key, int anchorChunkX, int anchorChunkZ, long seed, int maxSpan) { + int[] box = INMS.get().placeStructure(world, anchorChunkX, anchorChunkZ, key, seed, maxSpan); + if (box == null) { + return null; + } + int width = box[3] - box[0] + 1; + int height = box[4] - box[1] + 1; + int depth = box[5] - box[2] + 1; + if (width <= 0 || height <= 0 || depth <= 0) { + return null; + } + List blocks = new ArrayList<>(); + for (int dx = 0; dx < width; dx++) { + for (int dy = 0; dy < height; dy++) { + for (int dz = 0; dz < depth; dz++) { + Block block = world.getBlockAt(box[0] + dx, box[1] + dy, box[2] + dz); + if (block.getType() == Material.AIR) { + continue; + } + blocks.add(blockOf(block, dx, dy, dz)); + } + } + } + unloadChunksOf(box); + return blocks.isEmpty() ? null : new CapturedStructure(new BlockPosition(width, height, depth), blocks); + } + + private static TemplateBlock blockOf(Block block, int x, int y, int z) { + BlockState state = BlockState.parse( + PlatformBlockStates.namespaced(BukkitBlockState.of(block.getBlockData()).key())); + TileData tile = TileData.getTileState(block, false); + Optional blockEntity = tile == null ? Optional.empty() : Optional.of(BlockEntities.of(tile)); + return TemplateBlock.of(new BlockPosition(x, y, z), state, blockEntity); + } + + private void unloadChunksOf(int[] box) { + int minCX = box[0] >> 4; + int maxCX = box[3] >> 4; + int minCZ = box[2] >> 4; + int maxCZ = box[5] >> 4; + for (int cx = minCX; cx <= maxCX; cx++) { + for (int cz = minCZ; cz <= maxCZ; cz++) { + try { + world.unloadChunk(cx, cz, false); + } catch (Throwable ignored) { + } + } + } + } + + @Override + public void close() { + FeatureImporter.destroyScratchWorld(world, sender); + } + + static IllegalStateException captureFailure(String key, int chunkX, int chunkZ, String detail, Throwable cause) { + String message = "Structure capture failed for '" + key + "' at chunk " + + chunkX + "," + chunkZ + ": " + detail; + return cause == null ? new IllegalStateException(message) : new IllegalStateException(message, cause); + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitPlatformStructures.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitPlatformStructures.java new file mode 100644 index 000000000..04c6e5496 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitPlatformStructures.java @@ -0,0 +1,319 @@ +/* + * 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.structure; + +import art.arcane.iris.core.nms.INMS; +import art.arcane.iris.platform.bukkit.BukkitPlatform; +import art.arcane.iris.util.common.plugin.VolmitSender; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.JigsawStructureInfo; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.Sender; +import com.volmit.tooling.StructureAccessException; +import com.volmit.tooling.StructureTemplate; +import com.volmit.tooling.TemplatePool; +import org.bukkit.Bukkit; +import org.bukkit.NamespacedKey; +import org.bukkit.World; +import org.bukkit.command.CommandSender; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.TreeSet; +import java.util.function.Predicate; + +/** + * The structures of a Bukkit server: its registered structures and structure sets through the NMS binding, the + * jigsaw structures and template pools through the server's registries, the templates through Bukkit's structure + * manager and the server's resource manager, and structure capture through the NMS binding in a scratch world. + */ +public final class BukkitPlatformStructures implements PlatformStructures { + private static final String STRUCTURE_TEMPLATE_FOLDER = "structure"; + private static final String TEMPLATE_FILE_SUFFIX = ".nbt"; + private static final String JIGSAW_STRUCTURE_CLASS_SUFFIX = "JigsawStructure"; + + @Override + public List templates() { + try { + return enumerateTemplateKeys(); + } catch (Exception e) { + throw new StructureAccessException(ServerReflection.failureDetail(e), true, e); + } + } + + @Override + public Optional template(ResourceId id) { + return BukkitTemplateReader.read(Bukkit.getStructureManager().loadStructure(new NamespacedKey(id.namespace(), id.path()))); + } + + @Override + public List structures() { + return idsOf(INMS.get().getStructureKeys()); + } + + @Override + public List structureSets() { + return idsOf(INMS.get().getStructureSetKeys()); + } + + @Override + public Optional jigsaw(ResourceId structureKey) { + Object registryAccess = registryAccess(); + Object structureRegistry; + Object structure; + try { + structureRegistry = ServerReflection.lookupRegistry(registryAccess, "STRUCTURE"); + structure = ServerReflection.registryGet(structureRegistry, structureKey); + } catch (Throwable e) { + throw new StructureAccessException("Failed to read jigsaw structure graph: " + e, true, e); + } + if (structure == null || !structure.getClass().getName().endsWith(JIGSAW_STRUCTURE_CLASS_SUFFIX)) { + return Optional.empty(); + } + Object startPool; + int maxDepth; + int maxDistanceFromCenter; + try { + startPool = ServerReflection.unwrapHolder(ServerReflection.invoke(structure, "getStartPool")); + maxDepth = ServerReflection.readIntMember(structure, "maxDepth"); + maxDistanceFromCenter = ServerReflection.readIntMember(structure, "maxDistanceFromCenter"); + } catch (Throwable e) { + throw new StructureAccessException("Failed to read jigsaw structure graph: " + e, true, e); + } + Object templatePoolRegistry = templatePoolRegistry(registryAccess); + String startPoolKey; + try { + startPoolKey = ServerReflection.registryKeyOf(templatePoolRegistry, startPool); + } catch (Throwable e) { + throw new StructureAccessException("Could not resolve the start pool key for " + structureKey + ": " + e, true, e); + } + if (startPoolKey == null) { + throw new StructureAccessException("Could not resolve the start pool key for " + structureKey, false); + } + return Optional.of(new JigsawStructureInfo( + ResourceId.parse(startPoolKey), + maxDepth, + maxDistanceFromCenter, + Bukkit.getBukkitVersion(), + new NamespacedKey(structureKey.namespace(), structureKey.path()).hashCode())); + } + + @Override + public Optional pool(ResourceId poolKey) { + Object server; + Object structureManager; + Object registry; + Object pool; + try { + server = ServerReflection.minecraftServer(); + structureManager = ServerReflection.invoke(server, "getStructureManager"); + registry = templatePoolRegistry(registryAccess()); + pool = ServerReflection.registryGet(registry, poolKey); + } catch (StructureAccessException e) { + throw e; + } catch (Throwable e) { + throw new StructureAccessException("pool " + poolKey + ": " + e.getMessage(), true, e); + } + if (pool == null) { + return Optional.empty(); + } + + Optional fallback = Optional.empty(); + Optional fallbackFailure = Optional.empty(); + try { + Object fallbackPool = ServerReflection.unwrapHolder(ServerReflection.invoke(pool, "getFallback")); + String fallbackKey = ServerReflection.registryKeyOf(registry, fallbackPool); + fallback = Optional.ofNullable(fallbackKey).map(ResourceId::parse); + } catch (Throwable e) { + fallbackFailure = Optional.of(ServerReflection.failureDetail(e)); + } + + List templates; + try { + templates = (List) ServerReflection.invoke(pool, "getTemplates"); + } catch (Throwable e) { + throw new StructureAccessException("templates " + poolKey + ": " + e.getMessage(), true, e); + } + List members = new ArrayList<>(); + for (Object pair : templates) { + members.add(PoolElementReader.memberOf(pair, structureManager)); + } + return Optional.of(new TemplatePool(members, fallback, fallbackFailure)); + } + + @Override + public boolean supportsCapture() { + return INMS.get().supportsStructureCapture(); + } + + @Override + public Optional openCaptureArea(Sender sender) { + VolmitSender messages = messagesOf(sender); + World scratch = FeatureImporter.createScratchWorld(messages); + return scratch == null ? Optional.empty() : Optional.of(new BukkitCaptureArea(scratch, messages)); + } + + private static VolmitSender messagesOf(Sender sender) { + return sender.extension(CommandSender.class).map(VolmitSender::new).orElseGet(BukkitPlatform::console); + } + + private static Object registryAccess() { + Object server; + try { + server = ServerReflection.minecraftServer(); + } catch (Throwable e) { + throw new StructureAccessException("Failed to access server registries via reflection: " + e, true, e); + } + Object registryAccess = ServerReflection.resolveRegistryAccess(server); + if (registryAccess == null) { + throw new StructureAccessException("Could not resolve RegistryAccess from the server", true); + } + return registryAccess; + } + + private static Object templatePoolRegistry(Object registryAccess) { + try { + return ServerReflection.lookupRegistry(registryAccess, "TEMPLATE_POOL"); + } catch (Throwable e) { + throw new StructureAccessException("Failed to access TEMPLATE_POOL registry: " + e, true, e); + } + } + + private static List idsOf(Iterable keys) { + TreeSet ids = new TreeSet<>(); + for (String key : keys) { + if (key == null || key.isBlank()) { + continue; + } + try { + ids.add(ResourceId.parse(key.toLowerCase(Locale.ROOT))); + } catch (IllegalArgumentException invalidKey) { + continue; + } + } + return new ArrayList<>(ids); + } + + private static List enumerateTemplateKeys() throws Exception { + Object server = ServerReflection.minecraftServer(); + Object resourceManager = resolveResourceManager(server); + if (resourceManager == null) { + throw new IllegalStateException("Could not resolve the server ResourceManager via reflection"); + } + + Method listResources = null; + for (Method m : resourceManager.getClass().getMethods()) { + if (m.getName().equals("listResources") && m.getParameterCount() == 2 + && m.getParameterTypes()[0] == String.class + && m.getParameterTypes()[1] == Predicate.class + && Map.class.isAssignableFrom(m.getReturnType())) { + listResources = m; + break; + } + } + if (listResources == null) { + throw new NoSuchMethodException("listResources(String, Predicate) on " + resourceManager.getClass().getName()); + } + listResources.setAccessible(true); + + Predicate endsWithNbt = location -> { + String path = identifierPath(location); + return path != null && path.endsWith(TEMPLATE_FILE_SUFFIX); + }; + + Object resultMap = listResources.invoke(resourceManager, STRUCTURE_TEMPLATE_FOLDER, endsWithNbt); + TreeSet keys = new TreeSet<>(); + if (resultMap instanceof Map map) { + for (Object location : map.keySet()) { + String namespace = identifierNamespace(location); + String path = identifierPath(location); + if (namespace == null || path == null) { + continue; + } + String stripped = path; + if (stripped.startsWith(STRUCTURE_TEMPLATE_FOLDER + "/")) { + stripped = stripped.substring((STRUCTURE_TEMPLATE_FOLDER + "/").length()); + } + if (stripped.endsWith(TEMPLATE_FILE_SUFFIX)) { + stripped = stripped.substring(0, stripped.length() - TEMPLATE_FILE_SUFFIX.length()); + } + if (stripped.isEmpty()) { + continue; + } + keys.add(namespace + ":" + stripped); + } + } + return idsOf(keys); + } + + private static Object resolveResourceManager(Object server) { + try { + Class resourceManagerClass = Class.forName("net.minecraft.server.packs.resources.ResourceManager"); + Method getter = null; + for (Method m : server.getClass().getMethods()) { + if (m.getName().equals("getResourceManager") && m.getParameterCount() == 0 + && resourceManagerClass.isAssignableFrom(m.getReturnType())) { + getter = m; + break; + } + } + if (getter == null) { + for (Method m : server.getClass().getMethods()) { + if (m.getParameterCount() == 0 && resourceManagerClass.isAssignableFrom(m.getReturnType())) { + getter = m; + break; + } + } + } + if (getter == null) { + return null; + } + getter.setAccessible(true); + return getter.invoke(server); + } catch (Throwable e) { + return null; + } + } + + private static String identifierNamespace(Object location) { + try { + Method m = location.getClass().getMethod("getNamespace"); + m.setAccessible(true); + Object value = m.invoke(location); + return value == null ? null : value.toString(); + } catch (Throwable e) { + return null; + } + } + + private static String identifierPath(Object location) { + try { + Method m = location.getClass().getMethod("getPath"); + m.setAccessible(true); + Object value = m.invoke(location); + return value == null ? null : value.toString(); + } catch (Throwable e) { + return null; + } + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitTemplateReader.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitTemplateReader.java new file mode 100644 index 000000000..933a006b7 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/BukkitTemplateReader.java @@ -0,0 +1,111 @@ +/* + * 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.structure; + +import art.arcane.iris.core.modules.BlockEntities; +import art.arcane.iris.core.modules.PlatformBlockStates; +import art.arcane.iris.engine.object.prefab.LegacyTileData; +import art.arcane.iris.platform.bukkit.BukkitBlockState; +import art.arcane.iris.spi.IrisLogging; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import com.volmit.tooling.StructureTemplate; +import com.volmit.tooling.TemplateBlock; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.data.BlockData; +import org.bukkit.structure.Palette; +import org.bukkit.structure.Structure; +import org.bukkit.util.BlockVector; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** Reads a Bukkit {@link Structure} as a {@link StructureTemplate}: its size, and the blocks of its first palette. */ +final class BukkitTemplateReader { + private static final String FINAL_STATE_NBT_KEY = "final_state"; + + private BukkitTemplateReader() { + } + + /** The template; empty when the structure holds no palette. */ + static Optional read(Structure structure) { + if (structure == null || structure.getPalettes().isEmpty()) { + return Optional.empty(); + } + BlockVector size = structure.getSize(); + Palette palette = structure.getPalettes().get(0); + List blocks = new ArrayList<>(); + for (org.bukkit.block.BlockState block : palette.getBlocks()) { + blocks.add(blockOf(block)); + } + return Optional.of(new StructureTemplate( + new BlockPosition(size.getBlockX(), size.getBlockY(), size.getBlockZ()), + structure.getPaletteCount(), + structure.getEntityCount(), + blocks)); + } + + private static TemplateBlock blockOf(org.bukkit.block.BlockState block) { + Location location = block.getLocation(); + BlockPosition position = new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + BlockData data = block.getBlockData(); + Material material = data.getMaterial(); + BlockState state = BlockState.parse(PlatformBlockStates.namespaced(BukkitBlockState.of(data).key())); + if (material == Material.JIGSAW) { + return new TemplateBlock(position, state, Optional.empty(), readJigsawFinalState(block)); + } + if (material == Material.STRUCTURE_BLOCK || material == Material.STRUCTURE_VOID) { + return TemplateBlock.of(position, state, Optional.empty()); + } + return TemplateBlock.of(position, state, blockEntityOf(block)); + } + + private static Optional blockEntityOf(org.bukkit.block.BlockState block) { + try { + LegacyTileData tile = LegacyTileData.fromBukkit(block); + return tile == null ? Optional.empty() : Optional.of(BlockEntities.of(tile)); + } catch (Throwable e) { + IrisLogging.reportError(e); + return Optional.empty(); + } + } + + private static Optional readJigsawFinalState(org.bukkit.block.BlockState block) { + try { + Object nbt = block.getClass().getMethod("getSnapshotNBT").invoke(block); + if (nbt == null) { + return Optional.empty(); + } + Object res = nbt.getClass().getMethod("getString", String.class).invoke(nbt, FINAL_STATE_NBT_KEY); + String finalState = null; + if (res instanceof String s) { + finalState = s; + } else if (res instanceof Optional o && o.isPresent()) { + finalState = String.valueOf(o.get()); + } + return finalState == null || finalState.isBlank() ? Optional.empty() : Optional.of(finalState); + } catch (Throwable e) { + IrisLogging.reportError(e); + return Optional.empty(); + } + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/PoolElementReader.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/PoolElementReader.java new file mode 100644 index 000000000..ce4da0d09 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/PoolElementReader.java @@ -0,0 +1,261 @@ +/* + * 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.structure; + +import com.volmit.geometry.BlockFace; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.StructureAccessException; +import com.volmit.tooling.TemplatePool; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Optional; +import java.util.function.LongSupplier; + +/** Reads the members of a registered template pool by reflection: their weights, templates and jigsaw connectors. */ +final class PoolElementReader { + private static final String LIST_POOL_ELEMENT_SUFFIX = "ListPoolElement"; + private static final String DEFAULT_FRONT = "north"; + private static final String DEFAULT_TOP = "up"; + private static final String FINAL_STATE_NBT_KEY = "final_state"; + + private PoolElementReader() { + } + + /** The member of a pool for the pair the pool lists it as: its element and weight. */ + static TemplatePool.Member memberOf(Object pair, Object structureManager) { + Object element; + int weight; + try { + element = ServerReflection.invoke(pair, "getFirst"); + Object second = ServerReflection.invoke(pair, "getSecond"); + weight = second instanceof Number ? Math.max(1, ((Number) second).intValue()) : 1; + } catch (Throwable e) { + return new TemplatePool.Unreadable(TemplatePool.Part.ENTRY, ServerReflection.failureDetail(e)); + } + if (element == null) { + return new TemplatePool.Absent(); + } + PoolElementResolution resolution; + try { + resolution = resolvePoolElement(element); + } catch (Throwable e) { + return new TemplatePool.Unreadable(TemplatePool.Part.TEMPLATE_LOCATION, ServerReflection.failureDetail(e)); + } + String type = resolution.physicalElement() == null + ? element.getClass().getSimpleName() + : resolution.physicalElement().getClass().getSimpleName(); + Optional template; + try { + template = Optional.ofNullable(resolution.templateLocation()).map(PoolElementReader::templateId); + } catch (IllegalArgumentException invalidLocation) { + return new TemplatePool.Unreadable(TemplatePool.Part.TEMPLATE_LOCATION, + "invalid piece key " + resolution.templateLocation()); + } + return new TemplatePool.Element(weight, type, template, resolution.listLevels(), resolution.omittedElements(), + shuffleSeeds -> readConnectors(element, structureManager, shuffleSeeds)); + } + + private static ResourceId templateId(String location) { + return ResourceId.parse(location.toLowerCase(Locale.ROOT)); + } + + private static TemplatePool.Connectors readConnectors(Object element, Object structureManager, LongSupplier shuffleSeeds) { + try { + Object zero = ServerReflection.staticField("net.minecraft.core.BlockPos", "ZERO"); + Object rotationNone = ServerReflection.staticField("net.minecraft.world.level.block.Rotation", "NONE"); + Method m = ServerReflection.findMethod(element.getClass(), "getShuffledJigsawBlocks", 4); + if (m == null) { + return new TemplatePool.Connectors(TemplatePool.Availability.UNAVAILABLE, List.of()); + } + m.setAccessible(true); + Object random = ServerReflection.freshRandomSource(shuffleSeeds.getAsLong()); + List blocks = (List) m.invoke(element, structureManager, zero, rotationNone, random); + if (blocks == null) { + return new TemplatePool.Connectors(TemplatePool.Availability.NO_COLLECTION, List.of()); + } + List connectors = new ArrayList<>(); + for (Object jigsaw : blocks) { + connectors.add(connectorOf(jigsaw)); + } + return new TemplatePool.Connectors(TemplatePool.Availability.READ, connectors); + } catch (Throwable e) { + throw new StructureAccessException(ServerReflection.failureDetail(e), true, e); + } + } + + private static TemplatePool.Connector connectorOf(Object jigsaw) { + try { + return connectorFrom(jigsaw); + } catch (Throwable e) { + return new TemplatePool.UnreadableConnector(ServerReflection.failureDetail(e)); + } + } + + static TemplatePool.JigsawConnector connectorFrom(Object jigsaw) throws Exception { + Object info = ServerReflection.invoke(jigsaw, "info"); + Object pos = ServerReflection.invoke(info, "pos"); + Object blockState = ServerReflection.invoke(info, "state"); + BlockPosition position = new BlockPosition( + ServerReflection.readInt(pos, "getX"), + ServerReflection.readInt(pos, "getY"), + ServerReflection.readInt(pos, "getZ")); + + Object poolKey = ServerReflection.invoke(jigsaw, "pool"); + String poolId = ServerReflection.identifierString(ServerReflection.invoke(poolKey, "identifier")); + String name = ServerReflection.identifierString(ServerReflection.invoke(jigsaw, "name")); + String target = ServerReflection.identifierString(ServerReflection.invoke(jigsaw, "target")); + Object jointType = ServerReflection.invoke(jigsaw, "jointType"); + + BlockFace front = faceOf(frontFacing(blockState)); + BlockFace top = faceOf(topFacing(blockState)); + Optional pool = poolId == null || poolId.isEmpty() ? Optional.empty() : Optional.of(ResourceId.parse(poolId)); + ConnectorMetadata metadata = readConnectorMetadata(jigsaw, info); + boolean aligned = jointType != null && jointType.toString().toUpperCase(Locale.ROOT).contains("ALIGN"); + return new TemplatePool.JigsawConnector( + position, + front, + top, + pool, + name, + target, + aligned, + metadata.finalState(), + metadata.selectionPriority(), + metadata.placementPriority()); + } + + static ConnectorMetadata readConnectorMetadata(Object jigsaw, Object info) throws Exception { + String finalState = readNbtString(ServerReflection.invoke(info, "nbt"), FINAL_STATE_NBT_KEY); + return new ConnectorMetadata( + finalState == null || finalState.isBlank() ? Optional.empty() : Optional.of(finalState), + readIntAccessor(jigsaw, "selectionPriority"), + readIntAccessor(jigsaw, "placementPriority")); + } + + record ConnectorMetadata(Optional finalState, int selectionPriority, int placementPriority) { + } + + static BlockFace faceOf(String facing) { + return switch (facing) { + case "up" -> BlockFace.UP; + case "down" -> BlockFace.DOWN; + case "south" -> BlockFace.SOUTH; + case "east" -> BlockFace.EAST; + case "west" -> BlockFace.WEST; + default -> BlockFace.NORTH; + }; + } + + private static String readNbtString(Object nbt, String key) throws Exception { + if (nbt == null) { + return null; + } + Method method = ServerReflection.findMethod(nbt.getClass(), "getString", 1); + if (method == null) { + throw new NoSuchMethodException("getString(String) on " + nbt.getClass().getName()); + } + method.setAccessible(true); + Object value = method.invoke(nbt, key); + if (value instanceof String string) { + return string; + } + if (value instanceof Optional optional) { + return optional.isPresent() ? String.valueOf(optional.get()) : null; + } + return value == null ? null : String.valueOf(value); + } + + private static int readIntAccessor(Object value, String accessor) throws Exception { + Method method = ServerReflection.findMethod(value.getClass(), accessor); + if (method == null) { + throw new NoSuchMethodException(accessor + "() on " + value.getClass().getName()); + } + method.setAccessible(true); + Object result = method.invoke(value); + if (result instanceof Number number) { + return number.intValue(); + } + throw new IllegalStateException(accessor + " on " + value.getClass().getName() + " is not numeric"); + } + + private static String frontFacing(Object blockState) throws Exception { + return facing(blockState, "getFrontFacing", DEFAULT_FRONT); + } + + private static String topFacing(Object blockState) throws Exception { + return facing(blockState, "getTopFacing", DEFAULT_TOP); + } + + private static String facing(Object blockState, String jigsawBlockMethod, String fallback) throws Exception { + Class jigsawBlock = Class.forName("net.minecraft.world.level.block.JigsawBlock"); + Method read = jigsawBlock.getMethod(jigsawBlockMethod, Class.forName("net.minecraft.world.level.block.state.BlockState")); + Object direction = read.invoke(null, blockState); + if (direction == null) { + return fallback; + } + Method getName = direction.getClass().getMethod("getName"); + getName.setAccessible(true); + return String.valueOf(getName.invoke(direction)).toLowerCase(); + } + + private static String templateLocationOf(Object element) throws Exception { + Method m = ServerReflection.findMethod(element.getClass(), "getTemplateLocation"); + if (m == null) { + return null; + } + m.setAccessible(true); + Object id = m.invoke(element); + return ServerReflection.identifierString(id); + } + + static PoolElementResolution resolvePoolElement(Object element) throws Exception { + if (element == null) { + return new PoolElementResolution(null, null, 0, 0); + } + if (!element.getClass().getSimpleName().endsWith(LIST_POOL_ELEMENT_SUFFIX)) { + return new PoolElementResolution(element, templateLocationOf(element), 0, 0); + } + Object rawElements = ServerReflection.invoke(element, "getElements"); + if (!(rawElements instanceof List elements)) { + throw new IllegalStateException("getElements on " + element.getClass().getName() + " is not a list"); + } + if (elements.isEmpty()) { + return new PoolElementResolution(null, null, 1, 0); + } + PoolElementResolution primary = resolvePoolElement(elements.getFirst()); + return new PoolElementResolution( + primary.physicalElement(), + primary.templateLocation(), + primary.listLevels() + 1, + primary.omittedElements() + elements.size() - 1 + ); + } + + record PoolElementResolution( + Object physicalElement, + String templateLocation, + int listLevels, + int omittedElements + ) { + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/ServerReflection.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/ServerReflection.java new file mode 100644 index 000000000..f878f0278 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/structure/ServerReflection.java @@ -0,0 +1,302 @@ +/* + * 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.structure; + +import art.arcane.iris.spi.IrisLogging; +import com.volmit.resource.ResourceId; +import org.bukkit.Bukkit; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Optional; + +/** + * Reads the server's registries and resource manager by reflection, because they are version-bound server internals + * that Paper's api does not reach. Every lookup finds its members by name, so a server version that renamed one fails the + * read with the member's name instead of failing to link. + */ +final class ServerReflection { + private ServerReflection() { + } + + /** The server's {@code MinecraftServer}. */ + static Object minecraftServer() throws Exception { + Object craftServer = Bukkit.getServer(); + Object dedicated = invoke(craftServer, "getHandle"); + return invoke(dedicated, "getServer"); + } + + static Object resolveRegistryAccess(Object server) { + try { + Class frozen = Class.forName("net.minecraft.core.RegistryAccess$Frozen"); + for (Method m : server.getClass().getMethods()) { + if (m.getParameterCount() == 0 && frozen.isAssignableFrom(m.getReturnType())) { + m.setAccessible(true); + Object o = m.invoke(server); + if (o != null) { + return o; + } + } + } + Class ra = Class.forName("net.minecraft.core.RegistryAccess"); + for (Method m : server.getClass().getMethods()) { + if (m.getParameterCount() == 0 && ra.isAssignableFrom(m.getReturnType())) { + m.setAccessible(true); + Object o = m.invoke(server); + if (o != null) { + return o; + } + } + } + } catch (Throwable e) { + IrisLogging.reportError(e); + } + return null; + } + + static Object lookupRegistry(Object registryAccess, String registryName) throws Exception { + Class registries = Class.forName("net.minecraft.core.registries.Registries"); + Object resourceKey = registries.getField(registryName).get(null); + Class registryClass = Class.forName("net.minecraft.core.Registry"); + Method registryOverload = null; + for (Method m : registryAccess.getClass().getMethods()) { + if (m.getName().equals("lookupOrThrow") && m.getParameterCount() == 1 + && m.getParameterTypes()[0].getName().endsWith("ResourceKey") + && registryClass.isAssignableFrom(m.getReturnType())) { + registryOverload = m; + break; + } + } + if (registryOverload == null) { + for (Method m : registryAccess.getClass().getMethods()) { + if (m.getName().equals("lookupOrThrow") && m.getParameterCount() == 1 + && m.getParameterTypes()[0].getName().endsWith("ResourceKey")) { + registryOverload = m; + break; + } + } + } + if (registryOverload == null) { + throw new NoSuchMethodException("lookupOrThrow(ResourceKey) on " + registryAccess.getClass().getName()); + } + registryOverload.setAccessible(true); + return registryOverload.invoke(registryAccess, resourceKey); + } + + static Object registryGet(Object registry, ResourceId key) throws Exception { + Object id = identifierOf(key); + for (Method m : registry.getClass().getMethods()) { + if (m.getName().equals("getValue") && m.getParameterCount() == 1 && m.getParameterTypes()[0].getName().endsWith("Identifier")) { + m.setAccessible(true); + return m.invoke(registry, id); + } + } + for (Method m : registry.getClass().getMethods()) { + if (m.getName().equals("getOptional") && m.getParameterCount() == 1 && m.getParameterTypes()[0].getName().endsWith("Identifier")) { + m.setAccessible(true); + return unwrapOptional(m.invoke(registry, id)); + } + } + return null; + } + + static String registryKeyOf(Object registry, Object value) throws Exception { + if (value == null) { + return null; + } + for (Method m : registry.getClass().getMethods()) { + if (m.getName().equals("getKey") && m.getParameterCount() == 1) { + m.setAccessible(true); + Object id = m.invoke(registry, value); + String s = identifierString(id); + if (s != null) { + return s; + } + } + } + return null; + } + + static Object identifierOf(ResourceId key) throws Exception { + Class identifier = Class.forName("net.minecraft.resources.Identifier"); + try { + Method fromNamespaceAndPath = identifier.getMethod("fromNamespaceAndPath", String.class, String.class); + return fromNamespaceAndPath.invoke(null, key.namespace(), key.path()); + } catch (NoSuchMethodException e) { + Method withDefaultNamespace = identifier.getMethod("parse", String.class); + return withDefaultNamespace.invoke(null, key.toString()); + } + } + + static String identifierString(Object id) { + if (id == null) { + return null; + } + try { + Method getNamespace = id.getClass().getMethod("getNamespace"); + Method getPath = id.getClass().getMethod("getPath"); + getNamespace.setAccessible(true); + getPath.setAccessible(true); + return getNamespace.invoke(id) + ":" + getPath.invoke(id); + } catch (Throwable e) { + return id.toString(); + } + } + + static Object unwrapHolder(Object holder) { + if (holder == null) { + return null; + } + try { + Method value = findMethod(holder.getClass(), "value"); + if (value != null) { + value.setAccessible(true); + return value.invoke(holder); + } + } catch (Throwable ignored) { + } + return holder; + } + + static Object unwrapOptional(Object opt) { + if (opt == null) { + return null; + } + if (opt instanceof Optional o) { + return o.orElse(null); + } + return opt; + } + + static int readIntMember(Object value, String memberName) throws Exception { + Class type = value.getClass(); + while (type != null) { + try { + Field field = type.getDeclaredField(memberName); + field.setAccessible(true); + return coerceInt(field.get(value), memberName, value); + } catch (NoSuchFieldException ignored) { + type = type.getSuperclass(); + } + } + Method method = findMethod(value.getClass(), memberName); + if (method != null) { + method.setAccessible(true); + return coerceInt(method.invoke(value), memberName, value); + } + throw new NoSuchFieldException(memberName + " on " + value.getClass().getName()); + } + + /** + * Members that are plain numbers on one server build are wrapper objects on another + * (JigsawStructure.maxDistanceFromCenter became a MaxDistance{horizontal, vertical} record). + * Numbers pass through; a wrapper contributes its horizontal component, else its largest + * integral component, so a distance bound is never under-read. + */ + private static int coerceInt(Object member, String memberName, Object owner) throws Exception { + if (member instanceof Number n) { + return n.intValue(); + } + if (member == null) { + throw new NoSuchFieldException(memberName + " on " + owner.getClass().getName() + " is null"); + } + Method horizontal = findMethod(member.getClass(), "horizontal"); + if (horizontal != null && Number.class.isAssignableFrom(boxedType(horizontal.getReturnType()))) { + horizontal.setAccessible(true); + return ((Number) horizontal.invoke(member)).intValue(); + } + Integer widest = null; + for (Field component : member.getClass().getDeclaredFields()) { + if (Modifier.isStatic(component.getModifiers()) + || !Number.class.isAssignableFrom(boxedType(component.getType()))) { + continue; + } + component.setAccessible(true); + Object componentValue = component.get(member); + if (componentValue instanceof Number n && (widest == null || n.intValue() > widest)) { + widest = n.intValue(); + } + } + if (widest != null) { + return widest; + } + throw new NoSuchFieldException(memberName + " on " + owner.getClass().getName() + + " is a " + member.getClass().getName() + " with no integral component"); + } + + private static Class boxedType(Class type) { + return type == int.class ? Integer.class : type; + } + + static int readInt(Object o, String method) throws Exception { + Method m = o.getClass().getMethod(method); + m.setAccessible(true); + return ((Number) m.invoke(o)).intValue(); + } + + static Object staticField(String className, String fieldName) throws Exception { + Class c = Class.forName(className); + Field f = c.getField(fieldName); + return f.get(null); + } + + static Object invoke(Object target, String method) throws Exception { + Method m = findMethod(target.getClass(), method); + if (m == null) { + throw new NoSuchMethodException(method + " on " + target.getClass().getName()); + } + m.setAccessible(true); + return m.invoke(target); + } + + static Method findMethod(Class type, String name) { + return findMethod(type, name, 0); + } + + static Method findMethod(Class type, String name, int parameterCount) { + Class c = type; + while (c != null) { + for (Method m : c.getDeclaredMethods()) { + if (m.getName().equals(name) && m.getParameterCount() == parameterCount) { + return m; + } + } + c = c.getSuperclass(); + } + for (Method m : type.getMethods()) { + if (m.getName().equals(name) && m.getParameterCount() == parameterCount) { + return m; + } + } + return null; + } + + static Object freshRandomSource(long seed) throws Exception { + Class randomSource = Class.forName("net.minecraft.util.RandomSource"); + Method create = randomSource.getMethod("create", long.class); + return create.invoke(null, seed); + } + + /** The message a failed read shows: the failure's message, else its class name. */ + static String failureDetail(Throwable failure) { + String message = failure.getMessage(); + return message == null || message.isBlank() ? failure.getClass().getSimpleName() : message; + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolBlocks.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolBlocks.java new file mode 100644 index 000000000..9bae0e4a4 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolBlocks.java @@ -0,0 +1,99 @@ +/* + * 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.toolworld; + +import art.arcane.iris.core.modules.BlockEntities; +import art.arcane.iris.engine.object.prefab.TileData; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockFace; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.data.BlockData; + +import java.util.Optional; + +/** Blocks, positions and block entities between the tool world api and Bukkit. */ +final class BukkitToolBlocks { + private BukkitToolBlocks() { + } + + static BlockPosition positionOf(Block block) { + return new BlockPosition(block.getX(), block.getY(), block.getZ()); + } + + static BlockPosition positionOf(Location location) { + return new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + } + + static Block blockAt(World world, BlockPosition at) { + return world.getBlockAt(at.x(), at.y(), at.z()); + } + + /** The complete state of {@code data}, with every property. */ + static BlockState stateOf(BlockData data) { + return BlockState.parse(data.getAsString()); + } + + /** + * The platform's data for {@code state}. + * + * @throws IllegalArgumentException when the platform has no such block or property + */ + static BlockData dataOf(BlockState state) { + return Bukkit.createBlockData(state.key()); + } + + /** The block entity of {@code block}; empty for a block without one. */ + static Optional blockEntityOf(Block block) { + return Optional.ofNullable(TileData.getTileState(block, false)).map(BlockEntities::of); + } + + /** + * Writes {@code data} into the block entity of {@code block}, which must already be the block it was made for. + * + * @throws IllegalArgumentException when the block cannot take it, or the data is not in the format Iris stores + */ + static void applyBlockEntity(Block block, BlockEntityData data) { + TileData tile = BlockEntities.tileOf(data); + if (!TileData.setTileState(block, tile)) { + throw new IllegalArgumentException("The block " + block.getType() + " at " + block.getX() + ", " + block.getY() + + ", " + block.getZ() + " cannot take block entity data of " + tile.getMaterialKey()); + } + } + + /** The api face for a Bukkit face; empty for the diagonals and for {@code SELF}. */ + static Optional faceOf(org.bukkit.block.BlockFace face) { + if (face == null) { + return Optional.empty(); + } + return switch (face) { + case UP -> Optional.of(BlockFace.UP); + case DOWN -> Optional.of(BlockFace.DOWN); + case NORTH -> Optional.of(BlockFace.NORTH); + case SOUTH -> Optional.of(BlockFace.SOUTH); + case EAST -> Optional.of(BlockFace.EAST); + case WEST -> Optional.of(BlockFace.WEST); + default -> Optional.empty(); + }; + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolItems.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolItems.java new file mode 100644 index 000000000..c0eff3214 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolItems.java @@ -0,0 +1,107 @@ +/* + * 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.toolworld; + +import com.volmit.resource.ResourceId; +import com.volmit.tooling.world.ToolItem; +import com.volmit.tooling.world.ToolText; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.persistence.PersistentDataContainer; +import org.bukkit.persistence.PersistentDataType; + +import java.util.List; +import java.util.Optional; + +/** + * {@link ToolItem}s as Bukkit item stacks. The payload is a string in the item's persistent data; its presence is what + * makes a stack a tool item, so an empty payload is stored as an empty string. + */ +final class BukkitToolItems { + static final NamespacedKey PAYLOAD_KEY = new NamespacedKey("iris", "tool_payload"); + + private BukkitToolItems() { + } + + /** + * A new stack of {@code item}. The name and lore are set as legacy strings, the way a plugin sets text on an item + * with the platform's own calls, so the stack shows what such a stack always showed. + */ + @SuppressWarnings("deprecation") + static ItemStack create(ToolItem item) { + Material material = Material.matchMaterial(item.item().toString()); + if (material == null || !material.isItem()) { + throw new IllegalArgumentException("The platform has no item " + item.item()); + } + ItemStack stack = new ItemStack(material); + ItemMeta meta = stack.getItemMeta(); + if (meta == null) { + throw new IllegalStateException("The item " + item.item() + " cannot carry a name or a payload"); + } + if (!item.name().isEmpty()) { + meta.setDisplayName(BukkitToolText.legacy(item.name())); + } + if (!item.lore().isEmpty()) { + meta.setLore(item.lore().stream().map(BukkitToolText::legacy).toList()); + } + if (item.glowing()) { + meta.setEnchantmentGlintOverride(true); + } + meta.getPersistentDataContainer().set(PAYLOAD_KEY, PersistentDataType.STRING, item.payload()); + if (!stack.setItemMeta(meta)) { + throw new IllegalStateException("The metadata of tool item " + item.item() + " was rejected"); + } + return stack; + } + + /** The tool item {@code stack} is; empty for nothing, air or a stack without the tool payload. */ + static Optional read(ItemStack stack) { + if (stack == null || stack.getType() == Material.AIR || !stack.hasItemMeta()) { + return Optional.empty(); + } + ItemMeta meta = stack.getItemMeta(); + if (meta == null) { + return Optional.empty(); + } + PersistentDataContainer data = meta.getPersistentDataContainer(); + String payload = data.get(PAYLOAD_KEY, PersistentDataType.STRING); + if (payload == null) { + return Optional.empty(); + } + return Optional.of(new ToolItem( + ResourceId.parse(stack.getType().getKey().toString()), + meta.hasDisplayName() ? plainText(meta.displayName()) : ToolText.EMPTY, + meta.hasLore() ? lore(meta) : List.of(), + Boolean.TRUE.equals(meta.getEnchantmentGlintOverride()), + payload)); + } + + private static List lore(ItemMeta meta) { + List lines = meta.lore(); + return lines == null ? List.of() : lines.stream().map(BukkitToolItems::plainText).toList(); + } + + private static ToolText plainText(Component component) { + return component == null ? ToolText.EMPTY : ToolText.plain(PlainTextComponentSerializer.plainText().serialize(component)); + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolMenus.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolMenus.java new file mode 100644 index 000000000..584637947 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolMenus.java @@ -0,0 +1,172 @@ +/* + * 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.toolworld; + +import art.arcane.iris.platform.bukkit.BukkitPlatform; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.util.common.scheduling.J; +import art.arcane.volmlib.util.data.MaterialBlock; +import art.arcane.volmlib.util.inventorygui.UIElement; +import art.arcane.volmlib.util.inventorygui.UIPaneDecorator; +import art.arcane.volmlib.util.inventorygui.UIWindow; +import art.arcane.volmlib.util.inventorygui.WindowResolution; +import com.volmit.tooling.world.MenuButton; +import com.volmit.tooling.world.MenuClick; +import com.volmit.tooling.world.ToolItem; +import com.volmit.tooling.world.ToolMenu; +import com.volmit.tooling.world.ToolText; +import org.bukkit.Material; +import org.bukkit.entity.Player; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** The chest menus tools open for players, as VolmLib inventory windows. */ +final class BukkitToolMenus { + private static final int MAX_TITLE_LENGTH = 32; + private static final int SLOTS_PER_ROW = ToolMenu.SLOTS_PER_ROW; + private static final int CENTER_SLOT_OFFSET = SLOTS_PER_ROW / 2; + + private final Map windows = new ConcurrentHashMap<>(); + + /** + * The window a player has open and what it was opened with. A menu with the rows and title of the open one fills the + * same window, as a page of buttons changing under the player's cursor; the close handler is the latest menu's. + */ + private static final class OpenMenu { + private final UIWindow window; + private final int rows; + private final String title; + private volatile Runnable onClose; + + private OpenMenu(UIWindow window, int rows, String title, Runnable onClose) { + this.window = window; + this.rows = rows; + this.title = title; + this.onClose = onClose; + } + + private boolean showsSameFrame(ToolMenu menu) { + return rows == menu.rows() && title.equals(shortened(menu.title())); + } + } + + /** Opens {@code menu} for {@code viewer}, replacing the one they had. Runs on the viewer's thread. */ + void open(BukkitToolPlayer viewer, ToolMenu menu) { + Player player = viewer.bukkit(); + OpenMenu open = windows.get(player.getUniqueId()); + if (open != null && open.showsSameFrame(menu)) { + fill(open, viewer, menu); + return; + } + close(player); + UUID playerId = player.getUniqueId(); + UIWindow window = new UIWindow(BukkitPlatform.volmitPlugin(), player); + OpenMenu created = new OpenMenu(window, menu.rows(), shortened(menu.title()), menu.onClose()); + window.setResolution(WindowResolution.W9_H6); + window.setViewportHeight(menu.rows()); + window.setDecorator(new UIPaneDecorator(Material.BLACK_STAINED_GLASS_PANE)); + window.setTitle(created.title); + window.onClosed(closed -> { + windows.remove(playerId, created); + runGuarded(created.onClose, "menu close handler of " + player.getName()); + }); + window.batch(() -> addButtons(window, viewer, menu)); + windows.put(playerId, created); + window.open(); + } + + /** Puts the buttons of {@code menu} in the window {@code open} holds, telling the menu it replaces that it closed. */ + private void fill(OpenMenu open, BukkitToolPlayer viewer, ToolMenu menu) { + Runnable replaced = open.onClose; + open.onClose = menu.onClose(); + open.window.batch(() -> { + open.window.clearElements(); + addButtons(open.window, viewer, menu); + }); + runGuarded(replaced, "menu close handler of " + viewer.name()); + } + + private static void addButtons(UIWindow window, BukkitToolPlayer viewer, ToolMenu menu) { + for (MenuButton button : menu.buttons()) { + window.setElement(positionOf(button.slot()), button.slot() / SLOTS_PER_ROW, element(viewer, button)); + } + } + + /** Closes the player's menu; does nothing when none is open. Runs on the player's thread. */ + void close(Player player) { + OpenMenu open = windows.remove(player.getUniqueId()); + if (open != null) { + open.window.close(); + } + } + + void forget(UUID playerId) { + windows.remove(playerId); + } + + private static UIElement element(BukkitToolPlayer viewer, MenuButton button) { + ToolItem icon = button.icon(); + Material material = Material.matchMaterial(icon.item().toString()); + if (material == null || !material.isItem()) { + throw new IllegalArgumentException("The platform has no item " + icon.item()); + } + UIElement element = new UIElement("slot-" + button.slot()) + .setMaterial(new MaterialBlock(material)) + .setName(BukkitToolText.legacy(icon.name())) + .setEnchanted(icon.glowing()); + icon.lore().forEach(line -> element.addLore(BukkitToolText.legacy(line))); + element.onLeftClick(clicked -> click(viewer, button, false, false)); + element.onRightClick(clicked -> click(viewer, button, true, false)); + element.onShiftLeftClick(clicked -> click(viewer, button, false, true)); + element.onShiftRightClick(clicked -> click(viewer, button, true, true)); + element.onMiddleClick(clicked -> runGuarded( + () -> button.action().accept(new MenuClick(viewer, false, false, true)), + "menu button of " + viewer.name())); + return element; + } + + private static void click(BukkitToolPlayer viewer, MenuButton button, boolean right, boolean shift) { + runGuarded(() -> button.action().accept(new MenuClick(viewer, right, shift)), "menu button of " + viewer.name()); + } + + /** The window counts positions from its middle column, left of it negative; a slot counts from the left. */ + static int positionOf(int slot) { + return slot % SLOTS_PER_ROW - CENTER_SLOT_OFFSET; + } + + /** The title in the legacy codes the window takes, cut to what it can show without leaving half a code. */ + static String shortened(ToolText title) { + String legacy = BukkitToolText.legacy(title); + if (legacy.length() <= MAX_TITLE_LENGTH) { + return legacy; + } + String cut = legacy.substring(0, MAX_TITLE_LENGTH); + return cut.endsWith("§") ? cut.substring(0, MAX_TITLE_LENGTH - 1) : cut; + } + + private static void runGuarded(Runnable task, String what) { + try { + task.run(); + } catch (RuntimeException failure) { + IrisLogging.reportError("A tool failed in the " + what + ".", failure); + } + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolPlayer.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolPlayer.java new file mode 100644 index 000000000..10ec6d5bb --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolPlayer.java @@ -0,0 +1,253 @@ +/* + * 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.toolworld; + +import art.arcane.iris.core.service.BoardSVC; +import art.arcane.iris.core.service.BukkitToolingSender; +import art.arcane.iris.platform.bukkit.BukkitPlatform; +import art.arcane.iris.spi.IrisServices; +import art.arcane.iris.util.common.scheduling.J; +import art.arcane.volmlib.util.plugin.ComponentMessenger; +import art.arcane.volmlib.util.plugin.ComponentText; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.Sender; +import com.volmit.tooling.world.Particle; +import com.volmit.tooling.world.ToolItem; +import com.volmit.tooling.world.ToolMenu; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolText; +import com.volmit.tooling.world.ToolWorld; +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +/** A Bukkit player as a tool sees them. Readers must run on the player's thread; changes hop there by themselves. */ +final class BukkitToolPlayer implements ToolPlayer { + private final Player player; + private final OpenToolWorlds worlds; + private final ToolPlayers players; + private final BukkitToolMenus menus; + + BukkitToolPlayer(Player player, OpenToolWorlds worlds, ToolPlayers players, BukkitToolMenus menus) { + this.player = player; + this.worlds = worlds; + this.players = players; + this.menus = menus; + } + + Player bukkit() { + return player; + } + + @Override + public UUID id() { + return player.getUniqueId(); + } + + @Override + public String name() { + return player.getName(); + } + + @Override + public Sender sender() { + return new BukkitToolingSender(player); + } + + @Override + public Optional world() { + return worlds.forWorld(player.getWorld()).map(world -> world); + } + + @Override + public BlockPosition position() { + return BukkitToolBlocks.positionOf(player.getLocation()); + } + + @Override + public float yaw() { + return player.getLocation().getYaw(); + } + + @Override + public float pitch() { + return player.getLocation().getPitch(); + } + + @Override + public Optional targetBlock(int maxDistance) { + return Optional.ofNullable(player.getTargetBlockExact(maxDistance)).map(BukkitToolBlocks::positionOf); + } + + @Override + public boolean sneaking() { + return player.isSneaking(); + } + + @Override + public void run(Runnable task) { + J.runEntity(player, task); + } + + @Override + public CompletableFuture teleport(ToolWorld world, double x, double y, double z, float yaw, float pitch) { + if (!(world instanceof BukkitToolWorld target)) { + return CompletableFuture.failedFuture(new IllegalArgumentException("Not a tool world of this platform: " + world)); + } + CompletableFuture arrived = new CompletableFuture<>(); + boolean scheduled = J.runEntity(player, () -> BukkitPlatform + .teleportAsync(player, new Location(target.bukkit(), x, y, z, yaw, pitch)) + .whenComplete((success, failure) -> { + if (failure != null) { + arrived.completeExceptionally(failure); + } else { + arrived.complete(Boolean.TRUE.equals(success)); + } + })); + if (!scheduled) { + arrived.complete(false); + } + return arrived; + } + + @Override + public void creative(boolean on) { + J.runEntity(player, () -> { + if (on) { + players.rememberModeBeforeCreative(player); + player.setGameMode(GameMode.CREATIVE); + return; + } + players.restoreGameMode(player); + }); + } + + @Override + public void message(ToolText text) { + J.runEntity(player, () -> ComponentMessenger.send(player, ComponentText.component(BukkitToolText.component(text)))); + } + + @Override + public void actionBar(ToolText text) { + J.runEntity(player, () -> player.sendActionBar(BukkitToolText.component(text))); + } + + @Override + public void sound(ResourceId sound, float volume, float pitch) { + J.runEntity(player, () -> player.playSound(player.getLocation(), sound.toString(), volume, pitch)); + } + + @Override + public void sidebar(ToolText title, List lines) { + BoardSVC board = IrisServices.getOrNull(BoardSVC.class); + if (board == null) { + return; + } + J.runEntity(player, () -> board.applyToolSidebar(player, + new BoardSVC.ToolSidebar(player.getWorld().getUID(), title, lines))); + } + + @Override + public void hideSidebar() { + BoardSVC board = IrisServices.getOrNull(BoardSVC.class); + if (board != null) { + board.clearToolSidebar(player); + } + } + + @Override + public void particles(List dust) { + List specks = List.copyOf(dust); + J.runEntity(player, () -> specks.forEach(this::showDust)); + } + + @Override + public boolean give(ToolItem item) { + ItemStack stack = BukkitToolItems.create(item); + if (J.isOwnedByCurrentRegion(player)) { + return player.getInventory().addItem(stack).isEmpty(); + } + J.runEntity(player, () -> player.getInventory().addItem(stack)); + return true; + } + + @Override + public Optional held() { + return BukkitToolItems.read(player.getInventory().getItemInMainHand()); + } + + @Override + public void openMenu(ToolMenu menu) { + J.runEntity(player, () -> menus.open(this, menu)); + } + + @Override + public void closeMenu() { + J.runEntity(player, () -> menus.close(player)); + } + + /** + * Sends the player to where they were before they entered a tool world, or to the spawn of the main world when that + * is not known any more, and gives back the game mode they had. Completes with whether they arrived. + */ + CompletableFuture returnToOrigin() { + CompletableFuture returned = new CompletableFuture<>(); + boolean scheduled = J.runEntity(player, () -> { + menus.close(player); + players.restoreGameMode(player); + Location destination = players.takeOrigin(player) + .filter(this::isOutsideToolWorlds) + .orElseGet(() -> Bukkit.getWorlds().getFirst().getSpawnLocation()); + BukkitPlatform.teleportAsync(player, destination).whenComplete((success, failure) -> { + if (failure != null) { + returned.completeExceptionally(failure); + } else { + returned.complete(Boolean.TRUE.equals(success)); + } + }); + }); + if (!scheduled) { + returned.complete(false); + } + return returned; + } + + private boolean isOutsideToolWorlds(Location location) { + return location.getWorld() != null && worlds.forWorld(location.getWorld()).isEmpty(); + } + + private void showDust(Particle speck) { + org.bukkit.Particle.DustOptions options = new org.bukkit.Particle.DustOptions(Color.fromRGB(speck.rgb()), speck.size()); + player.spawnParticle(org.bukkit.Particle.DUST, speck.x(), speck.y(), speck.z(), 1, 0.0D, 0.0D, 0.0D, 0.0D, options); + } + + @Override + public String toString() { + return "tool player " + player.getName(); + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolText.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolText.java new file mode 100644 index 000000000..c7a3dc4df --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolText.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.core.toolworld; + +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolText; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.TextDecoration; + +import java.util.EnumMap; +import java.util.Map; + +/** {@link ToolText} as the text Bukkit shows: an Adventure component, or the legacy string the platform's older calls take. */ +final class BukkitToolText { + private static final char SECTION = '§'; + private static final Map COLORS = new EnumMap<>(Map.ofEntries( + Map.entry(TextColor.BLACK, NamedTextColor.BLACK), + Map.entry(TextColor.DARK_BLUE, NamedTextColor.DARK_BLUE), + Map.entry(TextColor.DARK_GREEN, NamedTextColor.DARK_GREEN), + Map.entry(TextColor.DARK_AQUA, NamedTextColor.DARK_AQUA), + Map.entry(TextColor.DARK_RED, NamedTextColor.DARK_RED), + Map.entry(TextColor.DARK_PURPLE, NamedTextColor.DARK_PURPLE), + Map.entry(TextColor.GOLD, NamedTextColor.GOLD), + Map.entry(TextColor.GRAY, NamedTextColor.GRAY), + Map.entry(TextColor.DARK_GRAY, NamedTextColor.DARK_GRAY), + Map.entry(TextColor.BLUE, NamedTextColor.BLUE), + Map.entry(TextColor.GREEN, NamedTextColor.GREEN), + Map.entry(TextColor.AQUA, NamedTextColor.AQUA), + Map.entry(TextColor.RED, NamedTextColor.RED), + Map.entry(TextColor.LIGHT_PURPLE, NamedTextColor.LIGHT_PURPLE), + Map.entry(TextColor.YELLOW, NamedTextColor.YELLOW), + Map.entry(TextColor.WHITE, NamedTextColor.WHITE))); + + private BukkitToolText() { + } + + static Component component(ToolText text) { + TextComponent.Builder whole = Component.text(); + for (ToolText.Span span : text.spans()) { + Component piece = Component.text(span.text()); + if (span.color() != null) { + piece = piece.color(COLORS.get(span.color())); + } + piece = piece + .decoration(TextDecoration.BOLD, span.bold() ? TextDecoration.State.TRUE : TextDecoration.State.NOT_SET) + .decoration(TextDecoration.ITALIC, span.italic() ? TextDecoration.State.TRUE : TextDecoration.State.NOT_SET) + .decoration(TextDecoration.STRIKETHROUGH, + span.strikethrough() ? TextDecoration.State.TRUE : TextDecoration.State.NOT_SET); + whole.append(piece); + } + return whole.build(); + } + + /** The legacy string of {@code text}: formatting signs for the colour and style of each span, a reset between uncoloured ones. */ + static String legacy(ToolText text) { + StringBuilder legacy = new StringBuilder(); + for (ToolText.Span span : text.spans()) { + if (span.color() != null) { + legacy.append(SECTION).append(span.color().code()); + } else if (!legacy.isEmpty()) { + legacy.append(SECTION).append('r'); + } + if (span.bold()) { + legacy.append(SECTION).append('l'); + } + if (span.italic()) { + legacy.append(SECTION).append('o'); + } + if (span.strikethrough()) { + legacy.append(SECTION).append('m'); + } + legacy.append(span.text()); + } + return legacy.toString(); + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorld.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorld.java new file mode 100644 index 000000000..59e2f7246 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorld.java @@ -0,0 +1,408 @@ +/* + * 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.toolworld; + +import art.arcane.iris.core.nms.INMS; +import art.arcane.iris.core.project.IrisProject; +import art.arcane.iris.core.runtime.InPlaceChunkRegenerator; +import art.arcane.iris.core.runtime.StudioOpenCoordinator; +import art.arcane.iris.core.runtime.StudioPainterSlots; +import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedBlockEntity; +import art.arcane.iris.core.runtime.StudioSlotOccupant; +import art.arcane.iris.core.service.StudioSVC; +import art.arcane.iris.engine.data.chunk.TerrainChunk; +import art.arcane.iris.engine.platform.studio.TerrainChunkCanvas; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.spi.IrisServices; +import art.arcane.iris.util.common.scheduling.J; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.geometry.ChunkPos; +import com.volmit.object.BlockEntityData; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolWorld; +import com.volmit.tooling.world.ToolWorldListener; +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.World; +import org.bukkit.block.Block; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +/** + * One tool world on Bukkit: a studio world whose chunks come from the tool's painter. It exists, registered, from before + * Bukkit creates the world until the world is unloaded; {@link #bind} gives it the Bukkit world once that exists. + */ +final class BukkitToolWorld implements ToolWorld, StudioSlotOccupant { + private static final int CHUNK_SHIFT = 4; + + private final String packName; + private final String name; + private final String storageName; + private final ToolWorldListener listener; + private final StudioPainterSlots.Slot slot; + private final PendingBlockEntities pending; + private final ToolWorldPresence presence = new ToolWorldPresence(); + private final OpenToolWorlds registry; + private final ToolPlayers players; + private final AtomicBoolean closing = new AtomicBoolean(); + private final AtomicBoolean gone = new AtomicBoolean(); + private final CompletableFuture closed = new CompletableFuture<>(); + private final IrisProject project; + private volatile World world; + + BukkitToolWorld( + String packName, + String name, + String storageName, + ToolWorldListener listener, + StudioPainterSlots.Slot slot, + PendingBlockEntities pending, + OpenToolWorlds registry, + ToolPlayers players + ) { + this.packName = packName; + this.name = name; + this.storageName = storageName; + this.listener = listener; + this.slot = slot; + this.pending = pending; + this.registry = registry; + this.players = players; + this.project = new IrisProject(new File(workspaceFolder(), packName)); + } + + /** The studio project this world is, as the studio service shows the open studio to its commands. */ + @Override + public IrisProject project() { + return project; + } + + private static File workspaceFolder() { + StudioSVC studios = IrisServices.getOrNull(StudioSVC.class); + return studios == null ? new File(".") : studios.getWorkspaceFolder(); + } + + String packName() { + return packName; + } + + /** The logical name of the world's storage, which the generator finds its painter by. */ + String storageName() { + return storageName; + } + + /** Gives the world its Bukkit world, once Bukkit has created it. */ + void bind(World created) { + world = Objects.requireNonNull(created, "created"); + registry.bound(this); + } + + boolean isBound() { + return world != null; + } + + UUID worldId() { + return bukkit().getUID(); + } + + World bukkit() { + World bound = world; + if (bound == null) { + throw new IllegalStateException("The tool world " + name + " is not created yet"); + } + return bound; + } + + ToolWorldPresence presence() { + return presence; + } + + @Override + public String name() { + return name; + } + + @Override + public int minY() { + return bukkit().getMinHeight(); + } + + @Override + public int maxY() { + return bukkit().getMaxHeight(); + } + + @Override + public List players() { + return bukkit().getPlayers().stream().map(players::of).toList(); + } + + @Override + public boolean owns(BlockPosition at) { + return J.isOwnedByCurrentRegion(bukkit(), at.x() >> CHUNK_SHIFT, at.z() >> CHUNK_SHIFT); + } + + @Override + public void run(BlockPosition at, Runnable task) { + World target = bukkit(); + Runnable guarded = () -> runGuarded(task, "task at " + at); + if (!J.runRegion(target, at.x() >> CHUNK_SHIFT, at.z() >> CHUNK_SHIFT, guarded)) { + IrisLogging.warn("Tool world %s could not schedule a task at %s.", name, at); + } + } + + @Override + public CompletableFuture call(BlockPosition at, Supplier task) { + CompletableFuture result = new CompletableFuture<>(); + boolean scheduled = J.runRegion(bukkit(), at.x() >> CHUNK_SHIFT, at.z() >> CHUNK_SHIFT, () -> { + try { + result.complete(task.get()); + } catch (Throwable failure) { + result.completeExceptionally(failure); + } + }); + if (!scheduled) { + result.completeExceptionally(new IllegalStateException("Tool world " + name + " could not schedule a task at " + at)); + } + return result; + } + + @Override + public BlockState block(BlockPosition at) { + return BukkitToolBlocks.stateOf(ownedBlock(at).getBlockData()); + } + + @Override + public Optional blockEntity(BlockPosition at) { + return BukkitToolBlocks.blockEntityOf(ownedBlock(at)); + } + + @Override + public void setBlock(BlockPosition at, BlockState state, Optional data) { + Block block = ownedBlock(at); + block.setBlockData(BukkitToolBlocks.dataOf(state), false); + data.ifPresent(entity -> BukkitToolBlocks.applyBlockEntity(block, entity)); + } + + @Override + public boolean loaded(ChunkPos chunk) { + return bukkit().isChunkLoaded(chunk.x(), chunk.z()); + } + + @Override + public CompletableFuture repaint(Collection chunks) { + if (isClosed()) { + return CompletableFuture.failedFuture(new IllegalStateException("Tool world " + name + " is closed")); + } + List> repaints = chunks.stream().distinct().map(this::repaintChunk).toList(); + return CompletableFuture.allOf(repaints.toArray(CompletableFuture[]::new)); + } + + @Override + public CompletableFuture close() { + if (!closing.compareAndSet(false, true)) { + return closed; + } + sendPlayersBack() + .thenCompose(ignored -> StudioOpenCoordinator.get().closeToolWorld(bukkit(), project)) + .whenComplete((result, failure) -> finishClose(result, failure)); + return closed; + } + + @Override + public Optional closeRefusal() { + try { + return listener.closeRefusal(); + } catch (Throwable failure) { + IrisLogging.reportError("The listener of tool world " + name + " failed.", failure); + return Optional.empty(); + } + } + + @Override + public CompletableFuture prepareReplacement(Optional requestedBy) { + Optional by = requestedBy.map(Bukkit::getPlayer).map(players::of); + try { + return listener.closing(by); + } catch (Throwable failure) { + IrisLogging.reportError("The listener of tool world " + name + " failed.", failure); + return CompletableFuture.completedFuture(null); + } + } + + /** The tool's listener asked, with {@code fallback} as the answer when it throws. Runs on the caller's thread. */ + boolean ask(Function question, boolean fallback) { + try { + return question.apply(listener); + } catch (Throwable failure) { + IrisLogging.reportError("The listener of tool world " + name + " failed.", failure); + return fallback; + } + } + + /** Tells the listener something. Runs on the caller's thread. */ + void tell(Consumer news) { + ask(listener -> { + news.accept(listener); + return true; + }, true); + } + + /** A chunk of the world loaded: writes the block entities its paint asked for, then tells the tool. */ + void chunkLoaded(Chunk chunk) { + for (PaintedBlockEntity entity : pending.take(chunk.getX(), chunk.getZ())) { + applyPainted(chunk, entity); + } + tell(toolListener -> toolListener.chunkLoaded(chunk.getX(), chunk.getZ())); + } + + /** Bukkit unloaded the world, whoever asked: it is gone for the tool and for the host. */ + void unloaded() { + if (!gone.compareAndSet(false, true)) { + return; + } + StudioPainterSlots.remove(storageName); + registry.unregister(this); + releaseStudioSlot(); + tell(ToolWorldListener::closed); + } + + private void releaseStudioSlot() { + StudioSVC studios = IrisServices.getOrNull(StudioSVC.class); + if (studios != null) { + studios.releaseStudioSlot(this); + } + } + + /** Called by the opener when creating the world failed: nothing of it is left to unload. */ + void abandon() { + StudioPainterSlots.remove(storageName); + registry.unregister(this); + } + + private void finishClose(StudioOpenCoordinator.StudioCloseResult result, Throwable failure) { + unloaded(); + Throwable cause = failure != null ? unwrap(failure) : result == null ? null : result.failureCause(); + if (cause == null) { + closed.complete(null); + return; + } + closed.completeExceptionally(cause); + } + + private CompletableFuture sendPlayersBack() { + List> departures = bukkit().getPlayers().stream() + .map(player -> players.of(player).returnToOrigin()) + .toList(); + return CompletableFuture.allOf(departures.toArray(CompletableFuture[]::new)); + } + + private record Repainted(TerrainChunk terrain, TerrainChunkCanvas canvas) { + } + + private CompletableFuture repaintChunk(ChunkPos position) { + World target = bukkit(); + AtomicReference repainted = new AtomicReference<>(); + CompletableFuture painting = J.afut(() -> repainted.set(paintAgain(target, position))); + CompletableFuture loading = target.getChunkAtAsync(position.x(), position.z()); + return painting.thenCombine(loading, (ignored, chunk) -> chunk) + .thenCompose(chunk -> J.runRegionFuture(target, position.x(), position.z(), + () -> writeRepainted(target, chunk, repainted.get()))); + } + + private Repainted paintAgain(World target, ChunkPos position) { + TerrainChunk terrain = TerrainChunk.create(target); + TerrainChunkCanvas canvas = TerrainChunkCanvas.onPlatform(terrain); + slot.painter().paint(position.x(), position.z(), canvas); + return new Repainted(terrain, canvas); + } + + private void writeRepainted(World target, Chunk chunk, Repainted repainted) { + if (!INMS.get().applyChunkBlocks(chunk, repainted.terrain())) { + InPlaceChunkRegenerator.applyBlockDiffs(chunk, repainted.terrain().getChunkData(), + target.getMinHeight(), target.getMaxHeight()); + } + repainted.canvas().blockEntities().forEach(entity -> applyPainted(chunk, entity)); + target.refreshChunk(chunk.getX(), chunk.getZ()); + } + + private void applyPainted(Chunk chunk, PaintedBlockEntity entity) { + Block block = chunk.getBlock(entity.x(), entity.y(), entity.z()); + try { + BukkitToolBlocks.applyBlockEntity(block, entity.data()); + } catch (RuntimeException failure) { + IrisLogging.reportError("Tool world " + name + " could not write a block entity at " + + block.getX() + ", " + block.getY() + ", " + block.getZ() + ".", failure); + } + } + + private Block ownedBlock(BlockPosition at) { + requireOpen(); + if (!owns(at)) { + throw new IllegalStateException("The calling thread does not own " + at + " in tool world " + name); + } + return BukkitToolBlocks.blockAt(bukkit(), at); + } + + private void requireOpen() { + if (isClosed()) { + throw new IllegalStateException("Tool world " + name + " is closed"); + } + bukkit(); + } + + private boolean isClosed() { + return closing.get() || gone.get(); + } + + private void runGuarded(Runnable task, String what) { + try { + task.run(); + } catch (Throwable failure) { + IrisLogging.reportError("A task of tool world " + name + " failed: " + what + ".", failure); + } + } + + private static Throwable unwrap(Throwable failure) { + Throwable cursor = failure; + while (cursor instanceof CompletionException && cursor.getCause() != null) { + cursor = cursor.getCause(); + } + return cursor; + } + + @Override + public String toString() { + return "tool world " + name; + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorldService.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorldService.java new file mode 100644 index 000000000..fc9497139 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorldService.java @@ -0,0 +1,86 @@ +/* + * 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.toolworld; + +import art.arcane.iris.core.tooling.ToolWorldsHost; +import art.arcane.iris.platform.bukkit.BukkitPlatform; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.util.common.plugin.IrisService; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolWorlds; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.HandlerList; + +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/** + * Tool worlds on Bukkit: the platform side of {@code com.volmit.tooling.world}. It keeps the open tool worlds and the + * tool players, listens for the events that concern them ({@link ToolWorldEvents}), and hands each pack its + * {@link ToolWorlds} through {@link ToolWorldsHost}, which core reaches it by. + */ +public final class BukkitToolWorldService implements IrisService, ToolWorldsHost { + private static final long CLOSING_WAIT_SECONDS = 30L; + + private final OpenToolWorlds worlds = new OpenToolWorlds(); + private final ToolPlayers players = new ToolPlayers(worlds); + private final ToolWorldEvents events = new ToolWorldEvents(worlds, players); + + @Override + public void onEnable() { + Bukkit.getPluginManager().registerEvents(events, BukkitPlatform.plugin()); + } + + @Override + public void onDisable() { + HandlerList.unregisterAll(events); + List open = worlds.all(); + awaitClosing(open); + open.forEach(BukkitToolWorld::unloaded); + } + + /** Lets every tool hear that its world is closing, as a replacement does, so it can save what it holds before the world is gone. */ + private static void awaitClosing(List open) { + CompletableFuture[] closing = open.stream() + .map(world -> world.prepareReplacement(Optional.empty())) + .toArray(CompletableFuture[]::new); + try { + CompletableFuture.allOf(closing).get(CLOSING_WAIT_SECONDS, TimeUnit.SECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } catch (ExecutionException | TimeoutException notReady) { + IrisLogging.reportError("A tool world was not ready to close when Iris stopped.", notReady); + } + } + + @Override + public ToolWorlds worldsOf(String packName) { + return new BukkitToolWorlds(packName, worlds, players); + } + + /** The tool player for {@code player}, the same object for as long as the player is online. */ + public ToolPlayer playerOf(Player player) { + return players.of(player); + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorlds.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorlds.java new file mode 100644 index 000000000..c026b0f8e --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorlds.java @@ -0,0 +1,117 @@ +/* + * 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.toolworld; + +import art.arcane.iris.core.runtime.StudioOpenCoordinator; +import art.arcane.iris.core.runtime.StudioPainterSlots; +import art.arcane.iris.core.service.StudioSVC; +import art.arcane.iris.spi.IrisServices; +import com.volmit.tooling.world.ToolWorld; +import com.volmit.tooling.world.ToolWorldDenied; +import com.volmit.tooling.world.ToolWorldSpec; +import com.volmit.tooling.world.ToolWorlds; +import org.bukkit.World; + +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; + +/** + * The tool worlds of one pack on Bukkit. A tool world is created through the studio's own world creation, with the + * tool's painter installed first so that even the first chunk is the tool's. + */ +final class BukkitToolWorlds implements ToolWorlds { + private static final String STORAGE_NAME_PREFIX = "iris-"; + private static final long TOOL_WORLD_SEED = 1337L; + + private final String packName; + private final OpenToolWorlds registry; + private final ToolPlayers players; + + BukkitToolWorlds(String packName, OpenToolWorlds registry, ToolPlayers players) { + this.packName = packName; + this.registry = registry; + this.players = players; + } + + @Override + public CompletableFuture open(ToolWorldSpec spec) { + Optional denial = StudioSVC.packAdmissionDenial(packName, StudioOpenCoordinator.StudioOpenKind.TOOL); + if (denial.isPresent()) { + return CompletableFuture.failedFuture(new ToolWorldDenied(denial.get())); + } + PendingBlockEntities pending = new PendingBlockEntities(); + StudioPainterSlots.Slot slot = new StudioPainterSlots.Slot(spec.painter(), pending::add); + String storageName = STORAGE_NAME_PREFIX + UUID.randomUUID(); + BukkitToolWorld toolWorld = new BukkitToolWorld(packName, spec.name(), storageName, spec.listener(), slot, pending, + registry, players); + if (!registry.register(toolWorld)) { + return CompletableFuture.failedFuture(new IllegalStateException( + "A tool world called " + spec.name() + " is open already in pack " + packName)); + } + StudioPainterSlots.install(storageName, slot); + CompletableFuture opened = new CompletableFuture<>(); + IrisServices.get(StudioSVC.class).occupyStudioSlot( + toolWorld, + () -> StudioOpenCoordinator.get().open(openRequest(storageName, toolWorld)) + ).whenComplete((result, failure) -> { + if (failure != null) { + toolWorld.abandon(); + opened.completeExceptionally(unwrap(failure)); + return; + } + opened.complete(toolWorld); + }); + return opened; + } + + @Override + public Optional find(String name) { + return registry.forName(packName, name).filter(BukkitToolWorld::isBound).map(world -> world); + } + + private StudioOpenCoordinator.StudioOpenRequest openRequest(String storageName, BukkitToolWorld toolWorld) { + return new StudioOpenCoordinator.StudioOpenRequest( + packName, + toolWorld.project(), + null, + TOOL_WORLD_SEED, + storageName, + null, + StudioOpenCoordinator.StudioOpenKind.TOOL, + false, + null, + world -> prepare(toolWorld, world), + System.nanoTime()); + } + + private static void prepare(BukkitToolWorld toolWorld, World created) { + toolWorld.bind(created); + ToolWorldRules.apply(created); + } + + private static Throwable unwrap(Throwable failure) { + Throwable cursor = failure; + while (cursor instanceof CompletionException && cursor.getCause() != null) { + cursor = cursor.getCause(); + } + return cursor; + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/OpenToolWorlds.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/OpenToolWorlds.java new file mode 100644 index 000000000..9078d2d9e --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/OpenToolWorlds.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.toolworld; + +import art.arcane.iris.core.IrisWorldStorage; +import org.bukkit.World; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * The tool worlds that are open or opening: found by the Bukkit world they live in, and by the tool's name for them + * within a pack. A world is registered before Bukkit has created it, since chunks load while it is created; until it + * is bound to its Bukkit world it is found by the logical name of its storage, which the creator fixes beforehand. + */ +final class OpenToolWorlds { + private final Map byStorageName = new ConcurrentHashMap<>(); + private final Map byWorldId = new ConcurrentHashMap<>(); + private final Map byPackAndName = new ConcurrentHashMap<>(); + + /** + * Registers {@code world} under its storage name and the name its tool gave it. + * + * @return whether the tool's name was free; when it is not, nothing is registered + */ + boolean register(BukkitToolWorld world) { + if (byPackAndName.putIfAbsent(packAndName(world.packName(), world.name()), world) != null) { + return false; + } + byStorageName.put(world.storageName(), world); + return true; + } + + /** Records the Bukkit world of {@code world}, which is bound already. */ + void bound(BukkitToolWorld world) { + byWorldId.put(world.worldId(), world); + } + + void unregister(BukkitToolWorld world) { + byStorageName.remove(world.storageName(), world); + byPackAndName.remove(packAndName(world.packName(), world.name()), world); + if (world.isBound()) { + byWorldId.remove(world.worldId(), world); + } + } + + /** The tool world that {@code world} is; empty for every other world. */ + Optional forWorld(World world) { + if (world == null) { + return Optional.empty(); + } + BukkitToolWorld bound = byWorldId.get(world.getUID()); + return bound != null ? Optional.of(bound) : forOpeningWorld(world); + } + + Optional forName(String packName, String name) { + return Optional.ofNullable(byPackAndName.get(packAndName(packName, name))); + } + + List all() { + return new ArrayList<>(byStorageName.values()); + } + + private Optional forOpeningWorld(World world) { + boolean anyOpening = byStorageName.values().stream().anyMatch(candidate -> !candidate.isBound()); + if (!anyOpening) { + return Optional.empty(); + } + return Optional.ofNullable(byStorageName.get(IrisWorldStorage.logicalName(world))); + } + + private static String packAndName(String packName, String name) { + return packName + "/" + name; + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/PendingBlockEntities.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/PendingBlockEntities.java new file mode 100644 index 000000000..d94377caf --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/PendingBlockEntities.java @@ -0,0 +1,51 @@ +/* + * 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.toolworld; + +import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedBlockEntity; +import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedChunk; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * The block entities a painter asked for in chunks that are generated but not loaded yet. A chunk is painted on a + * generation thread and its block entities can only be written once it is live, so they wait here for its load. + */ +final class PendingBlockEntities { + private static final int INT_BITS = 32; + + private final Map> byChunk = new ConcurrentHashMap<>(); + + /** Keeps what a paint of a chunk asked for; a later paint of the same chunk replaces it. */ + void add(PaintedChunk painted) { + byChunk.put(chunkKey(painted.chunkX(), painted.chunkZ()), painted.blockEntities()); + } + + /** Hands over what waits for the chunk, once; empty when nothing does. */ + List take(int chunkX, int chunkZ) { + List waiting = byChunk.remove(chunkKey(chunkX, chunkZ)); + return waiting == null ? List.of() : waiting; + } + + private static long chunkKey(int chunkX, int chunkZ) { + return ((long) chunkX << INT_BITS) | (chunkZ & 0xFFFFFFFFL); + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolPlayers.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolPlayers.java new file mode 100644 index 000000000..d54e7bb0b --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolPlayers.java @@ -0,0 +1,84 @@ +/* + * 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.toolworld; + +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * The tool players: one {@link BukkitToolPlayer} for each online player, and what the host remembers about them while + * they are in tool worlds, which is where they came from and the game mode they had before a tool made them creative. + */ +final class ToolPlayers { + private final OpenToolWorlds worlds; + private final BukkitToolMenus menus = new BukkitToolMenus(); + private final Map players = new ConcurrentHashMap<>(); + private final Map origins = new ConcurrentHashMap<>(); + private final Map modesBeforeCreative = new ConcurrentHashMap<>(); + + ToolPlayers(OpenToolWorlds worlds) { + this.worlds = worlds; + } + + BukkitToolPlayer of(Player player) { + return players.computeIfAbsent(player.getUniqueId(), id -> new BukkitToolPlayer(player, worlds, this, menus)); + } + + /** Forgets everything about a player who left the server. */ + void forget(Player player) { + UUID id = player.getUniqueId(); + players.remove(id); + origins.remove(id); + modesBeforeCreative.remove(id); + menus.forget(id); + } + + /** Remembers where a player was before their first step into a tool world; later steps keep the first. */ + void rememberOrigin(Player player, Location origin) { + origins.putIfAbsent(player.getUniqueId(), origin.clone()); + } + + /** Hands over where the player came from, once. */ + Optional takeOrigin(Player player) { + return Optional.ofNullable(origins.remove(player.getUniqueId())); + } + + /** Remembers the game mode of a player a tool makes creative; the first mode is kept while they stay creative. */ + void rememberModeBeforeCreative(Player player) { + modesBeforeCreative.putIfAbsent(player.getUniqueId(), player.getGameMode()); + } + + /** Gives a player the game mode they had before a tool made them creative; does nothing when none did. */ + void restoreGameMode(Player player) { + GameMode previous = modesBeforeCreative.remove(player.getUniqueId()); + if (previous != null) { + player.setGameMode(previous); + } + } + + BukkitToolMenus menus() { + return menus; + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolWorldEvents.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolWorldEvents.java new file mode 100644 index 000000000..1de093455 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolWorldEvents.java @@ -0,0 +1,593 @@ +/* + * 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.toolworld; + +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.tooling.world.BlockChange; +import com.volmit.tooling.world.BlockChange.Cause; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolUse; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.DoubleChest; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockBurnEvent; +import org.bukkit.event.block.BlockCookEvent; +import org.bukkit.event.block.BlockDispenseEvent; +import org.bukkit.event.block.BlockExplodeEvent; +import org.bukkit.event.block.BlockFadeEvent; +import org.bukkit.event.block.BlockFormEvent; +import org.bukkit.event.block.BlockFromToEvent; +import org.bukkit.event.block.BlockGrowEvent; +import org.bukkit.event.block.BlockMultiPlaceEvent; +import org.bukkit.event.block.BlockPistonExtendEvent; +import org.bukkit.event.block.BlockPistonRetractEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.block.BlockRedstoneEvent; +import org.bukkit.event.block.BlockSpreadEvent; +import org.bukkit.event.block.BrewingStartEvent; +import org.bukkit.event.block.CrafterCraftEvent; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.event.entity.EntityChangeBlockEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.inventory.BrewEvent; +import org.bukkit.event.inventory.BrewingStandFuelEvent; +import org.bukkit.event.inventory.FurnaceBurnEvent; +import org.bukkit.event.inventory.FurnaceStartSmeltEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.inventory.FurnaceSmeltEvent; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryDragEvent; +import org.bukkit.event.inventory.InventoryMoveItemEvent; +import org.bukkit.event.inventory.InventoryPickupItemEvent; +import org.bukkit.event.player.PlayerBucketEmptyEvent; +import org.bukkit.event.player.PlayerBucketFillEvent; +import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerPortalEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.event.player.PlayerToggleSneakEvent; +import org.bukkit.event.server.ServerCommandEvent; +import org.bukkit.event.world.ChunkLoadEvent; +import org.bukkit.event.world.StructureGrowEvent; +import org.bukkit.event.world.WorldUnloadEvent; +import org.bukkit.inventory.BlockInventoryHolder; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * The one listener that maps Bukkit's events onto {@link com.volmit.tooling.world.ToolWorldListener}, for tool worlds + * only. Every handler first asks whether the event happens in a tool world and does nothing when it does not. The + * priorities and {@code ignoreCancelled} flags are those of the jigsaw studio's own handlers: decisions at HIGHEST so + * that other plugins have had their say, observations at MONITOR. + */ +public final class ToolWorldEvents implements Listener { + private static final String COMMAND_PREFIX = "/"; + + private final OpenToolWorlds worlds; + private final ToolPlayers players; + + ToolWorldEvents(OpenToolWorlds worlds, ToolPlayers players) { + this.worlds = worlds; + this.players = players; + } + + // Block changes: the tool decides, `false` cancels. + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockPlace(BlockPlaceEvent event) { + Block placed = event.getBlockPlaced(); + allowOrCancel(event, Cause.PLACE, placed.getWorld(), List.of(positionOf(placed)), Optional.of(event.getPlayer()), + Optional.of(BukkitToolBlocks.stateOf(placed.getBlockData()))); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockMultiPlace(BlockMultiPlaceEvent event) { + List replaced = event.getReplacedBlockStates().stream() + .map(state -> positionOf(state.getBlock())).toList(); + allowOrCancel(event, Cause.PLACE, event.getBlock().getWorld(), replaced, Optional.of(event.getPlayer()), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockBreak(BlockBreakEvent event) { + allowOrCancel(event, Cause.BREAK, event.getBlock(), Optional.of(event.getPlayer())); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBucketEmpty(PlayerBucketEmptyEvent event) { + allowOrCancel(event, Cause.BUCKET, event.getBlockClicked().getRelative(event.getBlockFace()), Optional.of(event.getPlayer())); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBucketFill(PlayerBucketFillEvent event) { + allowOrCancel(event, Cause.BUCKET, event.getBlockClicked(), Optional.of(event.getPlayer())); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockForm(BlockFormEvent event) { + allowOrCancel(event, Cause.PHYSICS, event.getBlock(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockFade(BlockFadeEvent event) { + allowOrCancel(event, Cause.PHYSICS, event.getBlock(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockSpread(BlockSpreadEvent event) { + allowOrCancel(event, Cause.PHYSICS, event.getBlock().getWorld(), + List.of(positionOf(event.getBlock()), positionOf(event.getSource())), Optional.empty(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockFromTo(BlockFromToEvent event) { + allowOrCancel(event, Cause.FLUID, event.getBlock().getWorld(), + List.of(positionOf(event.getBlock()), positionOf(event.getToBlock())), Optional.empty(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockGrow(BlockGrowEvent event) { + allowOrCancel(event, Cause.GROWTH, event.getBlock(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onStructureGrow(StructureGrowEvent event) { + World world = event.getLocation().getWorld(); + List grown = event.getBlocks().stream().map(state -> positionOf(state.getBlock())).toList(); + if (!grown.isEmpty()) { + allowOrCancel(event, Cause.GROWTH, world, grown, Optional.ofNullable(event.getPlayer()), Optional.empty()); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockBurn(BlockBurnEvent event) { + allowOrCancel(event, Cause.FIRE, event.getBlock(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onBlockRedstone(BlockRedstoneEvent event) { + Block block = event.getBlock(); + if (!isAllowed(Cause.REDSTONE, block.getWorld(), List.of(positionOf(block)), Optional.empty(), Optional.empty())) { + event.setNewCurrent(event.getOldCurrent()); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPistonExtend(BlockPistonExtendEvent event) { + allowPistonOrCancel(event, event.getBlock(), event.getBlocks(), event.getDirection()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPistonRetract(BlockPistonRetractEvent event) { + allowPistonOrCancel(event, event.getBlock(), event.getBlocks(), event.getDirection()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockExplode(BlockExplodeEvent event) { + keepAllowedBlocks(event.getBlock().getWorld(), event.blockList()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onEntityExplode(EntityExplodeEvent event) { + keepAllowedBlocks(event.getEntity().getWorld(), event.blockList()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onEntityChangeBlock(EntityChangeBlockEvent event) { + Optional actor = event.getEntity() instanceof Player player ? Optional.of(player) : Optional.empty(); + allowOrCancel(event, Cause.ENTITY, event.getBlock(), actor); + } + + // Containers and machines. + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onInventoryClick(InventoryClickEvent event) { + allowContainerOrCancel(event, event.getView().getTopInventory(), event.getWhoClicked() instanceof Player player ? player : null); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onInventoryDrag(InventoryDragEvent event) { + allowContainerOrCancel(event, event.getView().getTopInventory(), event.getWhoClicked() instanceof Player player ? player : null); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onInventoryMove(InventoryMoveItemEvent event) { + allowContainerOrCancel(event, event.getSource(), null); + if (!event.isCancelled()) { + allowContainerOrCancel(event, event.getDestination(), null); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onInventoryPickup(InventoryPickupItemEvent event) { + allowContainerOrCancel(event, event.getInventory(), null); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockCook(BlockCookEvent event) { + allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onFurnaceBurn(FurnaceBurnEvent event) { + allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onFurnaceSmelt(FurnaceSmeltEvent event) { + allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBrew(BrewEvent event) { + allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBrewingStandFuel(BrewingStandFuelEvent event) { + allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockDispense(BlockDispenseEvent event) { + allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onCrafterCraft(CrafterCraftEvent event) { + allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty()); + } + + // What changed inside containers and machines, told after the fact. + + @EventHandler(priority = EventPriority.MONITOR) + public void onInventoryClose(InventoryCloseEvent event) { + Player player = event.getPlayer() instanceof Player closer ? closer : null; + tellContainerChanged(containerBlocks(event.getView().getTopInventory()), Optional.ofNullable(player)); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onFurnaceStartSmelt(FurnaceStartSmeltEvent event) { + tellContainerChanged(List.of(event.getBlock()), Optional.empty()); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onBrewingStart(BrewingStartEvent event) { + tellContainerChanged(List.of(event.getBlock()), Optional.empty()); + } + + private void tellContainerChanged(List blocks, Optional player) { + for (Block block : blocks) { + Optional toolPlayer = player.map(players::of).map(ToolPlayer.class::cast); + BlockPosition at = positionOf(block); + worlds.forWorld(block.getWorld()).ifPresent(world -> + world.tell(listener -> listener.containerChanged(toolPlayer, at))); + } + } + + // What players do. + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onInteract(PlayerInteractEvent event) { + Player player = event.getPlayer(); + Optional toolWorld = worlds.forWorld(player.getWorld()); + if (toolWorld.isEmpty()) { + return; + } + ToolUse use = new ToolUse( + event.getHand() == org.bukkit.inventory.EquipmentSlot.OFF_HAND ? ToolUse.Hand.OFF : ToolUse.Hand.MAIN, + ToolUse.Action.valueOf(event.getAction().name()), + BukkitToolItems.read(event.getItem()), + Optional.ofNullable(event.getClickedBlock()).map(ToolWorldEvents::positionOf), + BukkitToolBlocks.faceOf(event.getBlockFace())); + ToolPlayer toolPlayer = players.of(player); + if (!toolWorld.get().ask(listener -> listener.used(toolPlayer, use), false)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onToggleSneak(PlayerToggleSneakEvent event) { + Player player = event.getPlayer(); + worlds.forWorld(player.getWorld()).ifPresent(world -> + world.tell(listener -> listener.sneakToggled(players.of(player), event.isSneaking()))); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPlayerCommand(PlayerCommandPreprocessEvent event) { + Player player = event.getPlayer(); + Optional toolWorld = worlds.forWorld(player.getWorld()); + if (toolWorld.isEmpty()) { + return; + } + String line = lineOf(event.getMessage()); + ToolPlayer toolPlayer = players.of(player); + if (!toolWorld.get().ask(listener -> listener.command(Optional.of(toolPlayer), line), true)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onServerCommand(ServerCommandEvent event) { + String line = lineOf(event.getCommand()); + for (BukkitToolWorld toolWorld : worlds.all()) { + if (!toolWorld.ask(listener -> listener.command(Optional.empty(), line), true)) { + event.setCancelled(true); + return; + } + } + } + + // Arriving, leaving and moving. + + @EventHandler(priority = EventPriority.NORMAL) + public void onJoin(PlayerJoinEvent event) { + Player player = event.getPlayer(); + worlds.forWorld(player.getWorld()).ifPresent(world -> enter(world, player, player.getLocation())); + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onQuit(PlayerQuitEvent event) { + Player player = event.getPlayer(); + worlds.forWorld(player.getWorld()).ifPresent(world -> leave(world, player)); + players.forget(player); + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onChangedWorld(PlayerChangedWorldEvent event) { + Player player = event.getPlayer(); + worlds.forWorld(event.getFrom()).ifPresent(world -> leave(world, player)); + worlds.forWorld(player.getWorld()).ifPresent(world -> enter(world, player, player.getLocation())); + } + + /** + * Every teleport of any player by anyone, portals included, is told to the tool worlds it touches at the time it + * happens, with the position it goes to: the world it leaves hears {@code left}, the one it enters {@code entered}, + * and the one it arrives in {@code teleported}. + */ + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onTeleport(PlayerTeleportEvent event) { + Player player = event.getPlayer(); + Location destination = event.getTo(); + Optional from = worlds.forWorld(event.getFrom().getWorld()); + Optional to = destination == null ? Optional.empty() : worlds.forWorld(destination.getWorld()); + if (from.isEmpty() && to.isPresent()) { + players.rememberOrigin(player, event.getFrom()); + } + if (from.isPresent() && to.isEmpty()) { + players.restoreGameMode(player); + players.takeOrigin(player); + } + if (!from.equals(to)) { + from.ifPresent(world -> leave(world, player)); + } + to.ifPresent(world -> enter(world, player, destination)); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onRespawn(PlayerRespawnEvent event) { + Location respawn = event.getRespawnLocation(); + worlds.forWorld(respawn.getWorld()).ifPresent(world -> enter(world, event.getPlayer(), respawn)); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMove(PlayerMoveEvent event) { + Location to = event.getTo(); + if (to == null || sameBlock(event.getFrom(), to)) { + return; + } + worlds.forWorld(to.getWorld()).ifPresent(world -> + world.tell(listener -> listener.moved(players.of(event.getPlayer()), BukkitToolBlocks.positionOf(to)))); + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onChunkLoad(ChunkLoadEvent event) { + worlds.forWorld(event.getWorld()).ifPresent(world -> world.chunkLoaded(event.getChunk())); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onWorldUnload(WorldUnloadEvent event) { + worlds.forWorld(event.getWorld()).ifPresent(BukkitToolWorld::unloaded); + } + + // The host's own rules. + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onNaturalSpawn(CreatureSpawnEvent event) { + if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.NATURAL + && worlds.forWorld(event.getLocation().getWorld()).isPresent()) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPortal(PlayerPortalEvent event) { + if (worlds.forWorld(event.getFrom().getWorld()).isPresent()) { + event.setCancelled(true); + } + } + + /** The player is in the world at {@code at}: told as having entered on the first of their arrivals, and as having arrived on each. */ + private void enter(BukkitToolWorld world, Player player, Location at) { + if (world.presence().enter(player.getUniqueId())) { + world.tell(listener -> listener.entered(players.of(player))); + } + BlockPosition arrival = BukkitToolBlocks.positionOf(at); + world.tell(listener -> listener.teleported(players.of(player), arrival)); + } + + private void leave(BukkitToolWorld world, Player player) { + if (world.presence().leave(player.getUniqueId())) { + world.tell(listener -> listener.left(players.of(player))); + } + } + + private void allowOrCancel(Cancellable event, Cause cause, Block block, Optional player) { + allowOrCancel(event, cause, block.getWorld(), List.of(positionOf(block)), player, Optional.empty()); + } + + private void allowOrCancel( + Cancellable event, + Cause cause, + World world, + List positions, + Optional player, + Optional placed + ) { + if (!isAllowed(cause, world, positions, player, placed)) { + event.setCancelled(true); + } + } + + private void allowPistonOrCancel(Cancellable event, Block piston, List moved, BlockFace direction) { + boolean allowed = isAllowed( + Cause.PISTON, + piston.getWorld(), + pistonChecked(moved, direction), + pistonChanged(piston, moved, direction), + Optional.empty(), + Optional.empty()); + if (!allowed) { + event.setCancelled(true); + } + } + + private void allowContainerOrCancel(Cancellable event, Inventory inventory, Player player) { + List blocks = containerBlocks(inventory); + if (blocks.isEmpty()) { + return; + } + List positions = blocks.stream().map(ToolWorldEvents::positionOf).toList(); + allowOrCancel(event, Cause.CONTAINER, blocks.getFirst().getWorld(), positions, Optional.ofNullable(player), Optional.empty()); + } + + /** Whether the tool lets the change happen; changes outside tool worlds are none of the host's business. */ + private boolean isAllowed( + Cause cause, + World world, + List positions, + Optional player, + Optional placed + ) { + return isAllowed(cause, world, positions, positions, player, placed); + } + + private boolean isAllowed( + Cause cause, + World world, + List positions, + List changed, + Optional player, + Optional placed + ) { + Optional toolWorld = worlds.forWorld(world); + if (toolWorld.isEmpty()) { + return true; + } + BlockChange change = new BlockChange( + cause, positions, changed, player.map(players::of).map(ToolPlayer.class::cast), placed); + return toolWorld.get().ask(listener -> listener.blockChanging(change), false); + } + + private void keepAllowedBlocks(World world, List exploded) { + if (worlds.forWorld(world).isEmpty()) { + return; + } + exploded.removeIf(block -> !isAllowed(Cause.EXPLOSION, world, List.of(positionOf(block)), Optional.empty(), Optional.empty())); + } + + /** Each block a piston moves and the block each of them enters and leaves, which a protected area is checked against; not the piston. */ + static List pistonChecked(List moved, BlockFace direction) { + List positions = new ArrayList<>(); + for (Block block : moved) { + positions.add(positionOf(block)); + positions.add(positionOf(block.getRelative(direction))); + positions.add(positionOf(block.getRelative(direction.getOppositeFace()))); + } + return positions.stream().distinct().toList(); + } + + /** The piston and the block ahead of it, then each block it moves and the block each enters: what a piston changes. */ + static List pistonChanged(Block piston, List moved, BlockFace direction) { + List positions = new ArrayList<>(); + positions.add(positionOf(piston)); + positions.add(positionOf(piston.getRelative(direction))); + for (Block block : moved) { + positions.add(positionOf(block)); + positions.add(positionOf(block.getRelative(direction))); + } + return positions.stream().distinct().toList(); + } + + /** The blocks a container inventory is made of: none for a player's or a menu, two for a double chest. */ + static List containerBlocks(Inventory inventory) { + if (inventory == null) { + return List.of(); + } + List blocks = new ArrayList<>(2); + InventoryHolder holder = inventory.getHolder(); + if (holder instanceof BlockInventoryHolder blockHolder) { + blocks.add(blockHolder.getBlock()); + } else if (holder instanceof DoubleChest doubleChest) { + addBlockOf(blocks, doubleChest.getLeftSide()); + addBlockOf(blocks, doubleChest.getRightSide()); + } + return blocks; + } + + private static void addBlockOf(List blocks, InventoryHolder holder) { + if (holder instanceof BlockInventoryHolder blockHolder && !blocks.contains(blockHolder.getBlock())) { + blocks.add(blockHolder.getBlock()); + } + } + + /** Whether two locations are in one block of one world. */ + static boolean sameBlock(Location from, Location to) { + return from.getWorld() == to.getWorld() + && from.getBlockX() == to.getBlockX() + && from.getBlockY() == to.getBlockY() + && from.getBlockZ() == to.getBlockZ(); + } + + /** What a command line is for the tool: without the slash a player types before it. */ + static String lineOf(String typed) { + return typed.startsWith(COMMAND_PREFIX) ? typed.substring(COMMAND_PREFIX.length()) : typed; + } + + private static BlockPosition positionOf(Block block) { + return BukkitToolBlocks.positionOf(block); + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolWorldPresence.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolWorldPresence.java new file mode 100644 index 000000000..30119e940 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolWorldPresence.java @@ -0,0 +1,46 @@ +/* + * 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.toolworld; + +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Who stands in one tool world, so that the platform's several ways of arriving and leaving (join, teleport, world + * change, respawn, quit) tell the tool once for each stay: {@code entered} on the first of them, {@code left} on the + * first of them after. + */ +final class ToolWorldPresence { + private final Set present = ConcurrentHashMap.newKeySet(); + + /** Whether the player was not here before, which is when the tool hears {@code entered}. */ + boolean enter(UUID player) { + return present.add(player); + } + + /** Whether the player was here, which is when the tool hears {@code left}. */ + boolean leave(UUID player) { + return present.remove(player); + } + + boolean isPresent(UUID player) { + return present.contains(player); + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolWorldRules.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolWorldRules.java new file mode 100644 index 000000000..e5e5b8663 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolWorldRules.java @@ -0,0 +1,43 @@ +/* + * 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.toolworld; + +import art.arcane.iris.core.runtime.WorldRuntimeControlService; +import org.bukkit.GameRules; +import org.bukkit.World; + +/** + * What every tool world is made to be, whatever the server's studio settings say: no natural mobs, no weather, no + * daylight cycle, no portals, on top of the rules the object and jigsaw studios already use. + */ +final class ToolWorldRules { + private ToolWorldRules() { + } + + /** Applies the rules; runs on the thread that may change the world's rules (the main or global thread). */ + static void apply(World world) { + WorldRuntimeControlService.get().applyObjectStudioWorldRules(world); + world.setGameRule(GameRules.SPAWN_MOBS, false); + world.setGameRule(GameRules.ADVANCE_WEATHER, false); + world.setGameRule(GameRules.ADVANCE_TIME, false); + world.setGameRule(GameRules.ALLOW_ENTERING_NETHER_USING_PORTALS, false); + world.setStorm(false); + world.setThundering(false); + } +} diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisShutdownOrderingTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisShutdownOrderingTest.java index c12300f44..6de0ebddb 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisShutdownOrderingTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/IrisShutdownOrderingTest.java @@ -60,7 +60,6 @@ public class IrisShutdownOrderingTest { assertTrue("Server-stop quiescence must leave queued Paper generation admitted", quiesce.contains("generator.quiesceForServerShutdown()")); assertOrdered(quiesce, - "jigsawStudioService.quiesceForServerShutdown()", "PregeneratorJob.shutdownAndWait", "generator.quiesceForServerShutdown()"); assertOrdered(onDisable, @@ -123,32 +122,21 @@ public class IrisShutdownOrderingTest { } @Test - public void jigsawStudio_quiescesOnceBeforeDeferredServiceTeardown() throws Exception { - String source = Files.readString(Path.of(System.getProperty("iris.jigsawStudioSvcSource"))); - String enable = section(source, "public void onEnable()", "public void onDisable()"); - String disable = section(source, "public void onDisable()", "public void quiesceForServerShutdown()"); - String quiesce = section(source, "public void quiesceForServerShutdown()", "public void register("); - String register = section(source, "public void register(", "public void activationCommitted("); - String activation = section(source, "public void activationCommitted(", "public void markChunkGenerated("); - String chunkGenerated = section(source, "public void markChunkGenerated(", "private void markChunkAvailable("); + public void jigsawStudio_quiescesThroughItsToolWorldBeforeTheWorldIsUnloaded() throws Exception { + String startup = Files.readString(Path.of(System.getProperty("iris.startupSource"))); + String toolWorlds = Files.readString(Path.of(System.getProperty("iris.toolWorldServiceSource"))); + String studio = Files.readString(Path.of(System.getProperty("iris.jigsawStudioSvcSource"))); + String disable = section(toolWorlds, "public void onDisable()", "public ToolWorlds worldsOf"); + String closing = section(studio, "CompletableFuture closing(", "private boolean markDirty("); - assertOrdered(enable, "disableStarted.set(false)", "enabled = true"); - assertTrue("Deferred service teardown must reuse the idempotent early disable", - disable.contains("quiesceForServerShutdown();")); - assertOrdered(quiesce, - "disableStarted.compareAndSet(false, true)", - "finalizeAllJigsawTileWatches()", - "drainAutosavesBeforeDisable()", - "enabled = false", - "activeMenuController.closeAll()", - "previewRenderer.removeAll()", - "studios.clear()"); - assertTrue("Registration must reject work after shutdown begins", - occurrences(register, "!enabled || disableStarted.get()") >= 2); - assertTrue("Activation must reject work after shutdown begins", - activation.contains("!enabled || disableStarted.get()")); - assertTrue("Chunk-generation callbacks must reject work after shutdown begins", - occurrences(chunkGenerated, "!enabled || disableStarted.get()") >= 2); + assertFalse("Iris no longer holds or quiesces a studio itself", startup.contains("JigsawStudio")); + assertOrdered(disable, + "awaitClosing(open)", + "open.forEach(BukkitToolWorld::unloaded)"); + assertTrue("The host asks every tool world to get ready to close", toolWorlds.contains("world.prepareReplacement(Optional.empty())")); + assertOrdered(closing, + "drainAutosavesBeforeRemoval(studios.get(worldId))", + "awaitCloseForReplacement("); } private static String section(String source, String startMarker, String endMarker) { diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/CommandJigsawContractTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/CommandJigsawContractTest.java deleted file mode 100644 index 1454905ee..000000000 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/CommandJigsawContractTest.java +++ /dev/null @@ -1,609 +0,0 @@ -package art.arcane.iris.core.commands; - -import art.arcane.iris.core.pack.BrokenPackException; -import art.arcane.iris.core.runtime.StudioOpenCoordinator; -import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarArchetype; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariantCatalog; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioWorkcellSpec; -import art.arcane.iris.core.service.JigsawStudioService; -import art.arcane.iris.core.structure.authoring.StructureBackend; -import art.arcane.iris.core.structure.authoring.StructureCapability; -import art.arcane.iris.core.structure.authoring.StructureHash; -import art.arcane.iris.core.structure.authoring.StructureKey; -import art.arcane.iris.core.structure.authoring.StructureOwnershipManifest; -import art.arcane.iris.core.structure.authoring.StructureSource; -import art.arcane.iris.core.structure.authoring.StructureTransactionWriter; -import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionInputKind; -import art.arcane.iris.core.structure.export.VanillaJigsawExportFormat; -import art.arcane.iris.core.tools.IrisCreator; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.value.IrisDirection; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.util.common.director.specialhandlers.IrisStructureHandler; -import art.arcane.volmlib.util.director.DirectorOrigin; -import art.arcane.volmlib.util.director.annotations.Director; -import art.arcane.volmlib.util.director.annotations.Param; -import art.arcane.volmlib.util.director.exceptions.DirectorParsingException; -import org.bukkit.NamespacedKey; -import org.bukkit.entity.Player; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Parameter; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.CompletionException; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; - -public class CommandJigsawContractTest { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - @Test - public void commandIrisRegistersJigsawTree() throws Exception { - Field field = CommandIris.class.getDeclaredField("jigsaw"); - - assertEquals(CommandJigsaw.class, field.getType()); - assertNotNull(CommandJigsaw.class.getDeclaredField("piece")); - assertNotNull(CommandJigsaw.class.getDeclaredField("pool")); - assertNotNull(CommandJigsaw.class.getDeclaredField("connector")); - assertNotNull(CommandJigsaw.class.getDeclaredField("variant")); - assertNotNull(CommandJigsaw.class.getDeclaredField("workcell")); - assertNotNull(CommandJigsaw.class.getDeclaredField("rules")); - assertNotNull(CommandJigsaw.class.getDeclaredField("preview")); - assertNotNull(CommandJigsaw.class.getDeclaredField("adopt")); - } - - @Test - public void exposesStudioLifecycleAndAuthoringCommands() throws Exception { - assertCommand("create", IrisDimension.class, String.class, String.class, String.class, - int.class, int.class, int.class, long.class); - assertCommand("convert", IrisDimension.class, String.class, String.class, long.class); - assertCommand("open", IrisDimension.class, String.class, long.class); - assertCommand("close", boolean.class); - assertCommand("delete", boolean.class); - assertCommand("status"); - assertCommand("menu"); - assertCommand("select"); - assertCommand("bounds", int.class, int.class, int.class); - assertCommand("save", String.class); - assertCommand("gotoBay", String.class); - assertCommand("particles", boolean.class); - assertCommand("export", String.class, String.class, String.class, boolean.class); - } - - @Test - public void jigsawStudioUsesItsDedicatedOpenLifecycle() { - assertEquals( - StudioOpenCoordinator.StudioOpenKind.JIGSAW, - CommandJigsaw.STUDIO_OPEN_KIND); - assertFalse(CommandJigsaw.STUDIO_OPEN_KIND.openWorkspace()); - assertFalse(CommandJigsaw.STUDIO_OPEN_KIND.teleportThroughStandardEntry()); - assertEquals( - IrisCreator.DatapackPreparation.REUSE_LOADED_RUNTIME_IF_READY, - CommandJigsaw.STUDIO_OPEN_KIND.datapackPreparation()); - } - - @Test - public void packValidationDenialsAreExpectedOpenFailures() { - BrokenPackException failure = new BrokenPackException( - "overworld", List.of("Biome 'broken' has no resolvable regions.")); - - assertTrue(CommandJigsaw.isExpectedOpenDenial(failure)); - assertTrue(CommandJigsaw.isExpectedOpenDenial( - new CompletionException(failure))); - assertFalse(CommandJigsaw.isExpectedOpenDenial( - new IllegalStateException("Unexpected Studio failure"))); - } - - @Test - public void committedActivationStartsInitialEvaluationBeforePlayerBinding() throws Exception { - String source = Files.readString(Path.of( - "src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java")).replace("\r\n", "\n"); - int commit = source.indexOf("JigsawStudioActivation.commit(staged)"); - int evaluation = source.indexOf( - "studioService.activationCommitted(world, request.requestId())", - commit); - int binding = source.indexOf("PLAYER_PACKS.put", evaluation); - - assertTrue(commit >= 0); - assertTrue(evaluation > commit); - assertTrue(binding > evaluation); - } - - @Test - public void convertIsAddOnlyWorkflowWithAliasesAndDefaults() throws Exception { - Method convert = CommandJigsaw.class.getDeclaredMethod( - "convert", IrisDimension.class, String.class, String.class, long.class); - Director command = convert.getAnnotation(Director.class); - Parameter[] parameters = convert.getParameters(); - - assertEquals(List.of("import", "import-vanilla"), List.of(command.aliases())); - assertParameter(parameters[2], "auto", null); - assertParameter(parameters[3], "1337", null); - NamespacedKey source = CommandJigsaw.parseRegisteredStructureKey("minecraft:village_plains"); - assertEquals("minecraft_village_plains", CommandJigsaw.resolveConversionTarget(source, "auto")); - assertEquals("villages/plains", CommandJigsaw.resolveConversionTarget(source, "iris:villages/plains")); - NamespacedKey ancientCity = CommandJigsaw.parseRegisteredStructureKey( - "minecraft:ancient_city"); - assertEquals("minecraft_ancient_city", - CommandJigsaw.resolveConversionTarget(ancientCity, "auto")); - assertThrows(IllegalArgumentException.class, - () -> CommandJigsaw.resolveConversionTarget(source, "custom:village")); - } - - @Test - public void adoptionCommandsExposeTwoStepPlanContract() throws Exception { - Method inspect = CommandJigsaw.CommandJigsawAdopt.class.getDeclaredMethod( - "inspect", IrisDimension.class, String.class, String.class, String.class); - Method apply = CommandJigsaw.CommandJigsawAdopt.class.getDeclaredMethod("apply", String.class); - Parameter[] inspectParameters = inspect.getParameters(); - - assertNotNull(inspect.getAnnotation(Director.class)); - assertNotNull(apply.getAnnotation(Director.class)); - assertParameter(inspectParameters[2], "auto", null); - assertParameter(inspectParameters[3], "auto", CommandJigsaw.JigsawAdoptionStrategyHandler.class); - assertEquals(CommandJigsaw.JigsawAdoptionPlanHandler.class, - apply.getParameters()[0].getAnnotation(Param.class).customHandler()); - - CommandJigsaw.JigsawAdoptionStrategyHandler strategyHandler = - new CommandJigsaw.JigsawAdoptionStrategyHandler(); - assertEquals(List.of("auto", "in-place", "clone"), strategyHandler.getPossibilities()); - assertEquals("in-place", strategyHandler.parse("claim", false)); - assertEquals("clone", strategyHandler.parse("copy", false)); - assertThrows(DirectorParsingException.class, () -> strategyHandler.parse("overwrite", false)); - } - - @Test - public void adoptionInputKindUsesOnlyOwnershipProvenance() throws Exception { - Path root = temporaryFolder.newFolder("adoption-provenance").toPath(); - - assertEquals(IrisStructureAdoptionInputKind.UNOWNED_IRIS, - CommandJigsaw.adoptionInputKind(root, "unowned")); - writeManifest(root, "datapack-created", StructureSource.Kind.DATAPACK, - StructureOwnershipManifest.Provenance.created()); - assertEquals(IrisStructureAdoptionInputKind.UNOWNED_IRIS, - CommandJigsaw.adoptionInputKind(root, "datapack-created")); - writeManifest(root, "managed-provenance", StructureSource.Kind.IRIS, managedProvenance()); - assertEquals(IrisStructureAdoptionInputKind.MANAGED_DATAPACK, - CommandJigsaw.adoptionInputKind(root, "managed-provenance")); - } - - @Test - public void legacyGraphWritersShareTheServiceMutationContract() throws Exception { - Method mutation = CommandJigsaw.class.getDeclaredMethod( - "runGraphMutation", - Player.class, - CommandJigsaw.ActiveContext.class, - JigsawStudioService.CommandGraphMutation.class); - - assertEquals(boolean.class, mutation.getReturnType()); - assertNotNull(JigsawStudioService.CommandGraphMutation.class.getDeclaredMethod("run")); - assertNotNull(JigsawStudioService.CommandGraphMutationResult.class.getDeclaredConstructor( - JigsawStudioLayout.class, - String.class, - String.class, - String.class)); - } - - @Test - public void exposesAutosaveDynamicEvaluationAndSelectedWorkcellResize() throws Exception { - Method save = CommandJigsaw.class.getDeclaredMethod("save", String.class); - Method status = CommandJigsaw.class.getDeclaredMethod("status"); - Method bounds = CommandJigsaw.class.getDeclaredMethod( - "bounds", int.class, int.class, int.class); - - assertEquals("Flush the automatic save for a workcell now", - save.getAnnotation(Director.class).description()); - assertEquals("Show active Jigsaw Studio and dynamic evaluation state", - status.getAnnotation(Director.class).description()); - assertEquals("Set the selected Studio workcell capacity", - bounds.getAnnotation(Director.class).description()); - assertThrows(NoSuchMethodException.class, - () -> CommandJigsaw.class.getDeclaredMethod("validate")); - } - - @Test - public void createDefaultsToPlanarIrisWithCompleteCellAndSeedDefaults() throws Exception { - Method create = CommandJigsaw.class.getDeclaredMethod( - "create", - IrisDimension.class, - String.class, - String.class, - String.class, - int.class, - int.class, - int.class, - long.class); - Parameter[] parameters = create.getParameters(); - - assertParameter(parameters[2], "planar", CommandJigsaw.JigsawModeHandler.class); - assertParameter(parameters[3], "iris", CommandJigsaw.JigsawCompatibilityHandler.class); - assertParameter(parameters[4], "15", null); - assertParameter(parameters[5], "15", null); - assertParameter(parameters[6], "15", null); - assertParameter(parameters[7], "1337", null); - } - - @Test - public void structureKeysExplainTheirResourceAndOpenSupportsEditingAliases() throws Exception { - Method create = CommandJigsaw.class.getDeclaredMethod( - "create", - IrisDimension.class, - String.class, - String.class, - String.class, - int.class, - int.class, - int.class, - long.class); - Method open = CommandJigsaw.class.getDeclaredMethod( - "open", IrisDimension.class, String.class, long.class); - Param createKey = create.getParameters()[1].getAnnotation(Param.class); - Param openKey = open.getParameters()[1].getAnnotation(Param.class); - Director openCommand = open.getAnnotation(Director.class); - - assertEquals("key", createKey.name()); - assertEquals(List.of("structure", "name"), List.of(createKey.aliases())); - assertEquals("New key written as structures/.json", createKey.description()); - assertEquals("key", openKey.name()); - assertEquals(List.of("structure", "name"), List.of(openKey.aliases())); - assertEquals("Existing key loaded from structures/.json", openKey.description()); - assertEquals(IrisStructureHandler.class, openKey.customHandler()); - assertEquals(List.of("edit", "reopen"), List.of(openCommand.aliases())); - } - - @Test - public void createChoiceHandlersExposeCanonicalCompletionsAndRetainAliases() throws Exception { - CommandJigsaw.JigsawModeHandler modeHandler = new CommandJigsaw.JigsawModeHandler(); - CommandJigsaw.JigsawCompatibilityHandler compatibilityHandler = - new CommandJigsaw.JigsawCompatibilityHandler(); - - assertEquals(List.of("planar", "spatial"), modeHandler.getPossibilities()); - assertEquals("planar", modeHandler.parse("2d", false)); - assertEquals("spatial", modeHandler.parse("3d", false)); - assertEquals(List.of("iris", "vanilla"), compatibilityHandler.getPossibilities()); - assertEquals("iris", compatibilityHandler.parse("extended", false)); - assertEquals("vanilla", compatibilityHandler.parse("portable", false)); - assertThrows(DirectorParsingException.class, () -> modeHandler.parse("volume", false)); - assertThrows(DirectorParsingException.class, () -> compatibilityHandler.parse("mixed", false)); - } - - @Test - public void exposesNestedPieceVariantAndPreviewCommands() throws Exception { - assertNotNull(CommandJigsaw.CommandJigsawPool.class - .getDeclaredMethod("create", String.class, String.class) - .getAnnotation(Director.class)); - assertNotNull(CommandJigsaw.CommandJigsawConnector.class - .getDeclaredMethod("channel", String.class) - .getAnnotation(Director.class)); - assertNotNull(CommandJigsaw.CommandJigsawPiece.class - .getDeclaredMethod("create", String.class, String.class, int.class) - .getAnnotation(Director.class)); - assertNotNull(CommandJigsaw.CommandJigsawPiece.class - .getDeclaredMethod("add", String.class, String.class, int.class) - .getAnnotation(Director.class)); - assertNotNull(CommandJigsaw.CommandJigsawPiece.class - .getDeclaredMethod("remove", String.class) - .getAnnotation(Director.class)); - assertNotNull(CommandJigsaw.CommandJigsawPiece.class - .getDeclaredMethod("rotatable", boolean.class) - .getAnnotation(Director.class)); - assertNotNull(CommandJigsaw.CommandJigsawPiece.class - .getDeclaredMethod("expand") - .getAnnotation(Director.class)); - assertEquals("Resize the selected piece object exactly to workcell capacity", - CommandJigsaw.CommandJigsawPiece.class - .getDeclaredMethod("expand") - .getAnnotation(Director.class) - .description()); - assertNotNull(CommandJigsaw.CommandJigsawVariant.class - .getDeclaredMethod("weight", String.class, int.class) - .getAnnotation(Director.class)); - assertNotNull(CommandJigsaw.CommandJigsawVariant.class - .getDeclaredMethod("resize", int.class, int.class, int.class) - .getAnnotation(Director.class)); - assertNotNull(CommandJigsaw.CommandJigsawVariant.class - .getDeclaredMethod("label", String.class) - .getAnnotation(Director.class)); - assertNotNull(CommandJigsaw.CommandJigsawVariant.class - .getDeclaredMethod("labelReset") - .getAnnotation(Director.class)); - assertNotNull(CommandJigsaw.CommandJigsawVariant.class - .getDeclaredMethod("duplicate") - .getAnnotation(Director.class)); - Method duplicateFamily = CommandJigsaw.CommandJigsawVariant.class - .getDeclaredMethod("duplicateFamily", String.class); - assertNotNull(duplicateFamily.getAnnotation(Director.class)); - assertParameter(duplicateFamily.getParameters()[0], "next", null); - assertNotNull(CommandJigsaw.CommandJigsawWorkcell.class - .getDeclaredMethod("capacity", int.class, int.class, int.class) - .getAnnotation(Director.class)); - assertNotNull(CommandJigsaw.CommandJigsawWorkcell.class - .getDeclaredMethod("label", String.class) - .getAnnotation(Director.class)); - assertNotNull(CommandJigsaw.CommandJigsawWorkcell.class - .getDeclaredMethod("labelReset") - .getAnnotation(Director.class)); - assertNotNull(CommandJigsaw.CommandJigsawRules.class - .getDeclaredMethod("limits", int.class, int.class) - .getAnnotation(Director.class)); - assertNotNull(CommandJigsaw.CommandJigsawRules.class - .getDeclaredMethod("fallback", String.class, String.class) - .getAnnotation(Director.class)); - assertNotNull(CommandJigsaw.CommandJigsawPreview.class - .getDeclaredMethod("assemble", long.class) - .getAnnotation(Director.class)); - assertNotNull(CommandJigsaw.CommandJigsawPreview.class - .getDeclaredMethod("gotoPreview") - .getAnnotation(Director.class)); - } - - @Test - public void pieceCreateUsesResolvedWorkcellCapacityInsteadOfLayoutDefault() throws Exception { - String source = Files.readString(Path.of( - "src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java")).replace("\r\n", "\n"); - int pieceCommands = source.indexOf("public static class CommandJigsawPiece"); - int create = source.indexOf("public void create(", pieceCommands); - int add = source.indexOf("public void add(", create); - String createSource = source.substring(create, add); - - assertTrue(createSource.contains("targetWorkcell = contextual;")); - assertTrue(createSource.contains("JigsawStudioCellDimensions dimensions = targetWorkcell.capacity();")); - assertFalse(createSource.contains("layout().cellDimensions()")); - } - - @Test - public void pieceAddUsesCanonicalAxesForRotatedRectangularPlanarWorkcells() { - JigsawStudioLayout layout = nonuniformPlanarLayout(); - IrisJigsawPiece eastEnd = new IrisJigsawPiece(); - eastEnd.getConnectors().add(new IrisJigsawConnector().setDirection(IrisDirection.EAST_POSITIVE_X)); - IrisObject exactObject = new IrisObject(7, 5, 13); - - CommandJigsaw.PieceWorkcellResolution exact = CommandJigsaw.resolvePieceWorkcell( - layout, - eastEnd, - exactObject); - CommandJigsaw.PieceWorkcellResolution oversized = CommandJigsaw.resolvePieceWorkcell( - layout, - eastEnd, - new IrisObject(8, 5, 13)); - - assertEquals(JigsawPlanarArchetype.END.stableId(), exact.workcell().stableId()); - assertEquals(new IrisPosition(13, 5, 7), exact.requiredDimensions()); - assertEquals(new JigsawStudioCellDimensions(13, 5, 7), exact.workcell().capacity()); - assertTrue(exact.fits()); - assertTrue(exactObject.getD() > exact.workcell().capacity().depth()); - assertFalse(oversized.fits()); - } - - @Test - public void pieceAddKeepsRawObjectAxesForSpatialWorkcells() { - JigsawStudioCellDimensions capacity = new JigsawStudioCellDimensions(7, 5, 13); - JigsawStudioLayout layout = JigsawStudioLayout.create( - JigsawStudioMode.SPATIAL_JIGSAW, - capacity, - JigsawStudioVariantCatalog.empty()); - IrisJigsawPiece spatialPiece = new IrisJigsawPiece(); - spatialPiece.getConnectors().add( - new IrisJigsawConnector().setDirection(IrisDirection.EAST_POSITIVE_X)); - - CommandJigsaw.PieceWorkcellResolution resolution = CommandJigsaw.resolvePieceWorkcell( - layout, - spatialPiece, - new IrisObject(7, 5, 13)); - - assertEquals(JigsawStudioLayout.SPATIAL_WORKCELL_ID, resolution.workcell().stableId()); - assertEquals(new IrisPosition(7, 5, 13), resolution.requiredDimensions()); - assertEquals(capacity, resolution.workcell().capacity()); - assertTrue(resolution.fits()); - } - - @Test - public void everyExecutableCommandRejectsNonPlayerOrigins() { - Class[] commandTypes = { - CommandJigsaw.class, - CommandJigsaw.CommandJigsawConnector.class, - CommandJigsaw.CommandJigsawPool.class, - CommandJigsaw.CommandJigsawPiece.class, - CommandJigsaw.CommandJigsawVariant.class, - CommandJigsaw.CommandJigsawWorkcell.class, - CommandJigsaw.CommandJigsawRules.class, - CommandJigsaw.CommandJigsawPreview.class, - CommandJigsaw.CommandJigsawAdopt.class - }; - - for (Class commandType : commandTypes) { - for (Method method : commandType.getDeclaredMethods()) { - Director director = method.getAnnotation(Director.class); - if (director != null) { - assertEquals(method.toString(), DirectorOrigin.PLAYER, director.origin()); - } - } - } - } - - @Test - public void exportOutputIsOneSafeChildArtifact() { - Path root = Path.of("build", "jigsaw-exports").toAbsolutePath().normalize(); - - assertEquals(root.resolve("village.zip"), CommandJigsaw.resolveExportDestination( - root, "village", VanillaJigsawExportFormat.ZIP)); - assertEquals(root.resolve("village"), CommandJigsaw.resolveExportDestination( - root, "village", VanillaJigsawExportFormat.DIRECTORY)); - assertThrows(IllegalArgumentException.class, () -> CommandJigsaw.resolveExportDestination( - root, "", VanillaJigsawExportFormat.DIRECTORY)); - assertThrows(IllegalArgumentException.class, () -> CommandJigsaw.resolveExportDestination( - root, ".", VanillaJigsawExportFormat.DIRECTORY)); - assertThrows(IllegalArgumentException.class, () -> CommandJigsaw.resolveExportDestination( - root, "../all-exports", VanillaJigsawExportFormat.DIRECTORY)); - assertThrows(IllegalArgumentException.class, () -> CommandJigsaw.resolveExportDestination( - root, "nested/export", VanillaJigsawExportFormat.DIRECTORY)); - } - - @Test - public void exportLeaseRejectsDuplicatePlayerAndDestination() { - UUID firstPlayer = UUID.randomUUID(); - UUID secondPlayer = UUID.randomUUID(); - Path firstDestination = Path.of("build", "jigsaw-exports", "first.zip"); - Path secondDestination = Path.of("build", "jigsaw-exports", "second.zip"); - - assertEquals(true, CommandJigsaw.beginExport(firstPlayer, firstDestination)); - try { - assertEquals(false, CommandJigsaw.beginExport(firstPlayer, secondDestination)); - assertEquals(false, CommandJigsaw.beginExport(secondPlayer, firstDestination)); - } finally { - CommandJigsaw.finishExport(firstPlayer, firstDestination); - } - - assertEquals(true, CommandJigsaw.beginExport(secondPlayer, firstDestination)); - CommandJigsaw.finishExport(secondPlayer, firstDestination); - } - - @Test - public void exportStartFailuresHavePreciseOperatorMessages() { - assertEquals("The active Jigsaw Studio is no longer available.", - CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.NOT_ACTIVE)); - assertEquals("Only the Jigsaw Studio owner can export this project.", - CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.NOT_OWNER)); - assertEquals("Wait for the pending autosave or discard the edits before exporting the on-disk graph.", - CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.DIRTY)); - assertEquals("The active Jigsaw Studio is closing and cannot be exported.", - CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.CLOSING)); - assertEquals("Wait for the current Jigsaw Studio save to finish before exporting.", - CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.SAVE_IN_PROGRESS)); - assertEquals("Wait for the current Jigsaw Studio operation to finish before exporting.", - CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.OPERATION_IN_PROGRESS)); - assertEquals("A Jigsaw Studio export is already in progress.", - CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.IN_PROGRESS)); - assertThrows(IllegalArgumentException.class, - () -> CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.STARTED)); - } - - @Test - public void exportLeaseReleaseActionRunsExactlyOnce() { - AtomicInteger releases = new AtomicInteger(); - CommandJigsaw.ExportLease lease = new CommandJigsaw.ExportLease(releases::incrementAndGet); - - lease.release(); - lease.release(); - - assertEquals(1, releases.get()); - } - - @Test - public void exportSourceAcquiresStudioLeaseBeforeStaticLeaseAndReleasesBothPaths() throws Exception { - String source = Files.readString(Path.of( - "src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java")).replace("\r\n", "\n"); - int serviceLease = source.indexOf("studioService.tryBeginExport(requestId, playerId)"); - int staticLease = source.indexOf("beginExport(playerId, destination)", serviceLease); - int dispatch = source.indexOf("J.a(() -> runExport(operation))", staticLease); - int schedulingRelease = source.indexOf("operation.lease().release()", dispatch); - int exporter = source.indexOf("new VanillaJigsawDatapackExporter().export(operation.request())", dispatch); - int completionRelease = source.indexOf("operation.lease().release()", exporter); - - assertTrue(serviceLease >= 0); - assertTrue(staticLease > serviceLease); - assertTrue(dispatch > staticLease); - assertTrue(schedulingRelease > dispatch); - assertTrue(exporter > schedulingRelease); - assertTrue(completionRelease > exporter); - } - - private static void assertCommand(String name, Class... parameterTypes) throws Exception { - Method method = CommandJigsaw.class.getDeclaredMethod(name, parameterTypes); - assertNotNull(method.getAnnotation(Director.class)); - } - - private static JigsawStudioLayout nonuniformPlanarLayout() { - List workcells = List.of( - workcell(JigsawPlanarArchetype.BLANK, 3, 1, 3), - workcell(JigsawPlanarArchetype.END, 13, 5, 7), - workcell(JigsawPlanarArchetype.STRAIGHT, 5, 2, 11), - workcell(JigsawPlanarArchetype.CORNER, 9, 3, 6), - workcell(JigsawPlanarArchetype.TEE, 12, 4, 8), - workcell(JigsawPlanarArchetype.CROSS, 10, 6, 10)); - return JigsawStudioLayout.createPlanar( - new JigsawStudioCellDimensions(3, 1, 3), - workcells, - JigsawStudioVariantCatalog.empty()); - } - - private static JigsawStudioWorkcellSpec workcell( - JigsawPlanarArchetype archetype, - int width, - int height, - int depth - ) { - return new JigsawStudioWorkcellSpec( - archetype, - "", - new JigsawStudioCellDimensions(width, height, depth), - true); - } - - private static void assertParameter(Parameter parameter, String defaultValue, Class customHandler) { - Param annotation = parameter.getAnnotation(Param.class); - - assertNotNull(annotation); - assertEquals(defaultValue, annotation.defaultValue()); - if (customHandler != null) { - assertEquals(customHandler, annotation.customHandler()); - } - } - - private static void writeManifest( - Path root, - String structure, - StructureSource.Kind sourceKind, - StructureOwnershipManifest.Provenance provenance - ) throws Exception { - StructureKey structureKey = new StructureKey("iris", structure); - StructureOwnershipManifest manifest = new StructureOwnershipManifest( - StructureOwnershipManifest.CURRENT_SCHEMA_VERSION, - structureKey, - StructureSource.of(sourceKind, new StructureKey("iris", "source/" + structure)), - StructureBackend.IRIS_ASSEMBLY, - List.of(StructureCapability.BLOCKS, StructureCapability.CONNECTORS), - List.of(), - Map.of("structures/" + structure + ".json", StructureHash.sha256( - structure.getBytes(StandardCharsets.UTF_8))), - provenance); - Path manifestPath = new StructureTransactionWriter(root).ownershipManifestPath(structureKey); - Files.createDirectories(manifestPath.getParent()); - Files.write(manifestPath, manifest.toJson()); - } - - private static StructureOwnershipManifest.Provenance managedProvenance() { - String path = "structures/source.json"; - String hash = StructureHash.sha256("source".getBytes(StandardCharsets.UTF_8)); - return new StructureOwnershipManifest.Provenance( - StructureOwnershipManifest.Origin.MANAGED_DATAPACK, - UUID.randomUUID().toString(), - StructureHash.sha256("plan".getBytes(StandardCharsets.UTF_8)), - StructureHash.sha256("closure".getBytes(StandardCharsets.UTF_8)), - 1L, - Map.of(path, hash), - Map.of(path, path), - StructureOwnershipManifest.RollbackDisposition.NONE); - } -} diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/IrisStructureLocateCommandContractTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/IrisStructureLocateCommandContractTest.java index 5c5c703e1..5992e6f20 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/IrisStructureLocateCommandContractTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/commands/IrisStructureLocateCommandContractTest.java @@ -228,15 +228,14 @@ public class IrisStructureLocateCommandContractTest { @Test public void bulkStructureImportRestrictsCaptureWithoutChangingStandaloneCapture() throws IOException { - String source = Files.readString(Path.of(System.getProperty("iris.commandStructureSource"))); - int importStart = source.indexOf("public void importAll("); - int importEnd = source.indexOf("@Director(name = \"capture\"", importStart); - int captureStart = source.indexOf("public void capture(", importEnd); + String source = Files.readString(Path.of(System.getProperty("iris.importCommandsSource"))); + int importStart = source.indexOf("private static void runImportAll("); + int captureStart = source.indexOf("private static void runCapture(", importStart); + int importEnd = captureStart; int captureEnd = source.length(); assertTrue(importStart >= 0); assertTrue(importEnd > importStart); - assertTrue(captureStart > importEnd); assertTrue(captureEnd > captureStart); String importMethod = source.substring(importStart, importEnd); String captureMethod = source.substring(captureStart, captureEnd); diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/runtime/StudioPlayerModeContractTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/runtime/StudioPlayerModeContractTest.java index 0e7eeba9d..6b2364be3 100644 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/runtime/StudioPlayerModeContractTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/runtime/StudioPlayerModeContractTest.java @@ -42,12 +42,11 @@ public class StudioPlayerModeContractTest { String objectCommands = Files.readString(Path.of( "src/main/java/art/arcane/iris/core/commands/CommandObject.java")).replace("\r\n", "\n"); String jigsawCommands = Files.readString(Path.of( - "src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java")).replace("\r\n", "\n"); + System.getProperty("iris.studioLifecycleCommandsSource"))).replace("\r\n", "\n"); assertTrue(objectCommands.contains("GameMode.CREATIVE")); assertTrue(objectCommands.contains("StudioOpenCoordinator.StudioOpenKind.OBJECT")); - assertTrue(jigsawCommands.contains("GameMode.CREATIVE")); + assertTrue(jigsawCommands.contains("player.creative(true)")); assertFalse(objectCommands.contains("GameMode.SPECTATOR")); - assertFalse(jigsawCommands.contains("GameMode.SPECTATOR")); - } + assertFalse(jigsawCommands.contains("GameMode.SPECTATOR")); } } diff --git a/core/src/test/java/art/arcane/iris/core/structure/StructureCaptureImporterFailureTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/BukkitCaptureAreaFailureTest.java similarity index 84% rename from core/src/test/java/art/arcane/iris/core/structure/StructureCaptureImporterFailureTest.java rename to adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/BukkitCaptureAreaFailureTest.java index 01eb94ffe..b3960f0e9 100644 --- a/core/src/test/java/art/arcane/iris/core/structure/StructureCaptureImporterFailureTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/BukkitCaptureAreaFailureTest.java @@ -6,12 +6,12 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -public class StructureCaptureImporterFailureTest { +public class BukkitCaptureAreaFailureTest { @Test public void captureFailurePreservesStructureChunkDetailAndCause() { IllegalArgumentException cause = new IllegalArgumentException("placement broke"); - IllegalStateException error = StructureCaptureImporter.captureFailure( + IllegalStateException error = BukkitCaptureArea.captureFailure( "minecraft:monument", 12, -8, "platform placement failed", cause); assertSame(cause, error.getCause()); @@ -22,7 +22,7 @@ public class StructureCaptureImporterFailureTest { @Test public void captureFailureSupportsInfrastructureFailuresWithoutACause() { - IllegalStateException error = StructureCaptureImporter.captureFailure( + IllegalStateException error = BukkitCaptureArea.captureFailure( "minecraft:stronghold", -3, 5, "region task was not accepted", null); assertNull(error.getCause()); diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/PoolElementReaderTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/PoolElementReaderTest.java new file mode 100644 index 000000000..fecce8bdb --- /dev/null +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/PoolElementReaderTest.java @@ -0,0 +1,176 @@ +/* + * 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.structure; + +import org.junit.Test; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; + +public class PoolElementReaderTest { + private static final String FINAL_STATE = + "minecraft:oak_stairs[facing=east,half=top,shape=straight,waterlogged=false]"; + + @Test + public void plainTemplateElementRemainsUnchanged() throws Exception { + FakeSinglePoolElement single = new FakeSinglePoolElement("minecraft:village/plains/houses/plains_small_house_1"); + + PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(single); + + assertSame(single, resolution.physicalElement()); + assertEquals("minecraft:village/plains/houses/plains_small_house_1", resolution.templateLocation()); + assertEquals(0, resolution.listLevels()); + assertEquals(0, resolution.omittedElements()); + } + + @Test + public void nestedListsRetainOnlyTheRecursivePrimaryTemplate() throws Exception { + FakeSinglePoolElement primary = new FakeSinglePoolElement("minecraft:pillager_outpost/watchtower"); + FakeSinglePoolElement innerOverlay = new FakeSinglePoolElement("test:inner_overlay"); + FakeSinglePoolElement outerOverlay = new FakeSinglePoolElement("test:outer_overlay"); + FakeListPoolElement inner = new FakeListPoolElement(List.of(primary, innerOverlay)); + FakeListPoolElement outer = new FakeListPoolElement(List.of(inner, outerOverlay)); + + PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(outer); + + assertSame(primary, resolution.physicalElement()); + assertEquals("minecraft:pillager_outpost/watchtower", resolution.templateLocation()); + assertEquals(2, resolution.listLevels()); + assertEquals(2, resolution.omittedElements()); + } + + @Test + public void unsupportedPrimaryDoesNotFallThroughToLaterChildren() throws Exception { + FakeFeaturePoolElement feature = new FakeFeaturePoolElement(); + FakeSinglePoolElement fallback = new FakeSinglePoolElement("test:must_not_be_selected"); + FakeListPoolElement list = new FakeListPoolElement(List.of(feature, fallback)); + + PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(list); + + assertSame(feature, resolution.physicalElement()); + assertNull(resolution.templateLocation()); + assertEquals(1, resolution.omittedElements()); + } + + @Test + public void emptyListResolvesWithoutIndexingAChild() throws Exception { + PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement( + new FakeListPoolElement(List.of()) + ); + + assertNull(resolution.physicalElement()); + assertNull(resolution.templateLocation()); + assertEquals(1, resolution.listLevels()); + assertEquals(0, resolution.omittedElements()); + } + + @Test + public void outerChoiceProducesOneEntryWithItsOriginalWeight() throws Exception { + FakeListPoolElement towers = new FakeListPoolElement(List.of( + new FakeSinglePoolElement("minecraft:pillager_outpost/watchtower"), + new FakeSinglePoolElement("minecraft:pillager_outpost/watchtower_overgrown") + )); + PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(towers); + + List> entries = List.of(VillageImporter.piecePoolEntry( + "qa/pillager_outpost/piece/minecraft/pillager_outpost/watchtower", + 7 + )); + + assertEquals(1, entries.size()); + assertEquals("minecraft:pillager_outpost/watchtower", resolution.templateLocation()); + assertEquals(7, entries.getFirst().get("weight")); + assertEquals(1, resolution.omittedElements()); + } + + @Test + public void vanillaNbtMetadataIsReadFromTheJigsawBlockInfo() throws Exception { + FakeJigsawBlockInfo jigsaw = new FakeJigsawBlockInfo(-29, -17); + FakeStructureBlockInfo info = new FakeStructureBlockInfo(new FakeCompoundTag(FINAL_STATE)); + + PoolElementReader.ConnectorMetadata metadata = PoolElementReader.readConnectorMetadata(jigsaw, info); + + assertEquals(Optional.of(FINAL_STATE), metadata.finalState()); + assertEquals(-17, metadata.selectionPriority()); + assertEquals(-29, metadata.placementPriority()); + } + + private record FakeJigsawBlockInfo(int placementPriority, int selectionPriority) { + } + + private record FakeStructureBlockInfo(FakeCompoundTag nbt) { + } + + private record FakeCompoundTag(String finalState) { + public Optional getString(String key) { + return "final_state".equals(key) ? Optional.of(finalState) : Optional.empty(); + } + } + + private static final class FakeListPoolElement { + private final List elements; + + private FakeListPoolElement(List elements) { + this.elements = List.copyOf(elements); + } + + public List getElements() { + return elements; + } + } + + private static final class FakeSinglePoolElement { + private final FakeResourceLocation location; + + private FakeSinglePoolElement(String location) { + String[] parts = location.split(":", 2); + this.location = new FakeResourceLocation(parts[0], parts[1]); + } + + public FakeResourceLocation getTemplateLocation() { + return location; + } + } + + private static final class FakeFeaturePoolElement { + } + + private static final class FakeResourceLocation { + private final String namespace; + private final String path; + + private FakeResourceLocation(String namespace, String path) { + this.namespace = namespace; + this.path = path; + } + + public String getNamespace() { + return namespace; + } + + public String getPath() { + return path; + } + } +} diff --git a/core/src/test/java/art/arcane/iris/core/structure/VillageImporterMaxDistanceReadTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/ServerReflectionMaxDistanceReadTest.java similarity index 77% rename from core/src/test/java/art/arcane/iris/core/structure/VillageImporterMaxDistanceReadTest.java rename to adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/ServerReflectionMaxDistanceReadTest.java index 62b6d72ea..b54d2d95d 100644 --- a/core/src/test/java/art/arcane/iris/core/structure/VillageImporterMaxDistanceReadTest.java +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/structure/ServerReflectionMaxDistanceReadTest.java @@ -11,7 +11,7 @@ import static org.junit.Assert.assertEquals; * IllegalArgumentException from Field.getInt, failing the jigsaw import of every datapack * structure ("Failed to read jigsaw structure graph"). */ -public class VillageImporterMaxDistanceReadTest { +public class ServerReflectionMaxDistanceReadTest { private static final class IntShape { private final int maxDistanceFromCenter = 80; } @@ -29,16 +29,16 @@ public class VillageImporterMaxDistanceReadTest { @Test public void readsPlainIntField() throws Exception { - assertEquals(80, VillageImporter.readIntMember(new IntShape(), "maxDistanceFromCenter")); + assertEquals(80, ServerReflection.readIntMember(new IntShape(), "maxDistanceFromCenter")); } @Test public void readsLargestIntComponentFromWrapperRecord() throws Exception { - assertEquals(96, VillageImporter.readIntMember(new WrapperShape(), "maxDistanceFromCenter")); + assertEquals(96, ServerReflection.readIntMember(new WrapperShape(), "maxDistanceFromCenter")); } @Test public void readsBoxedNumberField() throws Exception { - assertEquals(64, VillageImporter.readIntMember(new BoxedShape(), "maxDistanceFromCenter")); + assertEquals(64, ServerReflection.readIntMember(new BoxedShape(), "maxDistanceFromCenter")); } } diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/BukkitToolItemsTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/BukkitToolItemsTest.java new file mode 100644 index 000000000..6c65cebc3 --- /dev/null +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/BukkitToolItemsTest.java @@ -0,0 +1,80 @@ +package art.arcane.iris.core.toolworld; + +import com.volmit.resource.ResourceId; +import com.volmit.tooling.world.ToolItem; +import com.volmit.tooling.world.ToolText; +import net.kyori.adventure.text.Component; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.persistence.PersistentDataContainer; +import org.bukkit.persistence.PersistentDataType; +import org.junit.Test; + +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.when; + +public class BukkitToolItemsTest { + private ItemStack stackWith(PersistentDataContainer data, ItemMeta meta) { + ItemStack stack = mock(ItemStack.class); + when(stack.getType()).thenReturn(Material.STICK); + when(stack.hasItemMeta()).thenReturn(true); + when(stack.getItemMeta()).thenReturn(meta); + when(meta.getPersistentDataContainer()).thenReturn(data); + return stack; + } + + @Test + public void aStackWithThePayloadReadsBackAsTheToolItemItWasMadeFrom() { + PersistentDataContainer data = mock(PersistentDataContainer.class); + ItemMeta meta = mock(ItemMeta.class); + when(data.get(BukkitToolItems.PAYLOAD_KEY, PersistentDataType.STRING)).thenReturn("select:bay-1"); + when(meta.hasDisplayName()).thenReturn(true); + when(meta.displayName()).thenReturn(Component.text("Select bay")); + when(meta.hasLore()).thenReturn(true); + when(meta.lore()).thenReturn(List.of(Component.text("Right-click to use"))); + when(meta.getEnchantmentGlintOverride()).thenReturn(true); + + Optional item = BukkitToolItems.read(stackWith(data, meta)); + + assertEquals(Optional.of(new ToolItem(ResourceId.parse("minecraft:stick"), ToolText.plain("Select bay"), + List.of(ToolText.plain("Right-click to use")), true, "select:bay-1")), item); + } + + @Test + public void anEmptyPayloadStillMakesAToolItemAndAMissingOneDoesNot() { + PersistentDataContainer empty = mock(PersistentDataContainer.class); + when(empty.get(BukkitToolItems.PAYLOAD_KEY, PersistentDataType.STRING)).thenReturn(""); + PersistentDataContainer missing = mock(PersistentDataContainer.class); + + ToolItem tagged = BukkitToolItems.read(stackWith(empty, mock(ItemMeta.class))).orElseThrow(); + + assertEquals("", tagged.payload()); + assertEquals(ToolText.EMPTY, tagged.name()); + assertEquals(List.of(), tagged.lore()); + assertTrue(BukkitToolItems.read(stackWith(missing, mock(ItemMeta.class))).isEmpty()); + } + + @Test + public void nothingAirOrAStackWithoutMetadataIsNotAToolItem() { + ItemStack air = mock(ItemStack.class); + when(air.getType()).thenReturn(Material.AIR); + ItemStack plain = mock(ItemStack.class); + when(plain.getType()).thenReturn(Material.STICK); + when(plain.hasItemMeta()).thenReturn(false); + + assertTrue(BukkitToolItems.read(null).isEmpty()); + assertTrue(BukkitToolItems.read(air).isEmpty()); + assertTrue(BukkitToolItems.read(plain).isEmpty()); + } + + @Test + public void thePayloadLivesUnderTheIrisToolPayloadKey() { + assertEquals("iris:tool_payload", BukkitToolItems.PAYLOAD_KEY.toString()); + } +} diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/BukkitToolTextTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/BukkitToolTextTest.java new file mode 100644 index 000000000..f36cd29c3 --- /dev/null +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/BukkitToolTextTest.java @@ -0,0 +1,61 @@ +package art.arcane.iris.core.toolworld; + +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolText; +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.TextDecoration; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class BukkitToolTextTest { + private static final String SECTION = "§"; + + @Test + public void legacyTextHasTheColourCodeOfEachSpanAsTheOldMenusWroteThem() { + ToolText text = ToolText.builder().aqua("Structure").gray(": village").build(); + + assertEquals(SECTION + "bStructure" + SECTION + "7: village", BukkitToolText.legacy(text)); + } + + @Test + public void anUncolouredSpanAfterAnotherResets() { + ToolText text = ToolText.builder().yellow("Walk").append(" plain").build(); + + assertEquals(SECTION + "eWalk" + SECTION + "r plain", BukkitToolText.legacy(text)); + assertEquals("plain", BukkitToolText.legacy(ToolText.plain("plain"))); + assertEquals("", BukkitToolText.legacy(ToolText.EMPTY)); + } + + @Test + public void stylesFollowTheColour() { + ToolText text = ToolText.builder() + .append(new ToolText.Span("x", TextColor.GRAY, true, true, true)).build(); + + assertEquals(SECTION + "7" + SECTION + "l" + SECTION + "o" + SECTION + "mx", BukkitToolText.legacy(text)); + } + + @Test + public void aComponentCarriesTheColoursAndTheTextOfEverySpan() { + ToolText text = ToolText.builder().red("a").append("b").build(); + + Component component = BukkitToolText.component(text); + + assertEquals("ab", PlainTextComponentSerializer.plainText().serialize(component)); + assertEquals(NamedTextColor.RED, component.children().getFirst().color()); + assertEquals(null, component.children().getLast().color()); + assertEquals(TextDecoration.State.NOT_SET, component.children().getFirst().decoration(TextDecoration.ITALIC)); + } + + @Test + public void aTitleTooLongForTheWindowIsCutWithoutLeavingHalfACode() { + ToolText coloured = ToolText.colored(TextColor.GREEN, "x".repeat(40)); + + String cut = BukkitToolMenus.shortened(coloured); + + assertEquals(32, cut.length()); + assertEquals(SECTION + "a", cut.substring(0, 2)); + } +} diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/ToolWorldBookkeepingTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/ToolWorldBookkeepingTest.java new file mode 100644 index 000000000..7b00478e9 --- /dev/null +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/ToolWorldBookkeepingTest.java @@ -0,0 +1,125 @@ +package art.arcane.iris.core.toolworld; + +import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedBlockEntity; +import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedChunk; +import com.volmit.object.BlockEntityData; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolText; +import org.bukkit.World; +import org.junit.Test; + +import java.util.List; +import java.util.UUID; + +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.when; + +/** The small pieces of state the Bukkit host keeps for its tool worlds. */ +public class ToolWorldBookkeepingTest { + private static final BlockEntityData DATA = new BlockEntityData(ResourceId.parse("iris:tile"), 1, new byte[] {1}); + + @Test + public void aPlayerEntersAndLeavesOncePerStay() { + ToolWorldPresence presence = new ToolWorldPresence(); + UUID player = UUID.randomUUID(); + + assertFalse(presence.leave(player)); + assertTrue(presence.enter(player)); + assertFalse(presence.enter(player)); + assertTrue(presence.isPresent(player)); + assertTrue(presence.leave(player)); + assertFalse(presence.leave(player)); + assertTrue("a second stay is told again", presence.enter(player)); + } + + @Test + public void blockEntitiesWaitForTheirChunkAndAreHandedOverOnce() { + PendingBlockEntities pending = new PendingBlockEntities(); + PaintedBlockEntity chest = new PaintedBlockEntity(1, 64, 2, DATA); + pending.add(new PaintedChunk(-3, 7, List.of(chest))); + + assertEquals(List.of(), pending.take(3, 7)); + assertEquals(List.of(), pending.take(-3, -7)); + assertEquals(List.of(chest), pending.take(-3, 7)); + assertEquals(List.of(), pending.take(-3, 7)); + } + + @Test + public void aLaterPaintOfAChunkReplacesWhatWaitedForIt() { + PendingBlockEntities pending = new PendingBlockEntities(); + PaintedBlockEntity first = new PaintedBlockEntity(1, 64, 2, DATA); + PaintedBlockEntity second = new PaintedBlockEntity(3, 64, 4, DATA); + pending.add(new PaintedChunk(0, 0, List.of(first))); + pending.add(new PaintedChunk(0, 0, List.of(second))); + + assertEquals(List.of(second), pending.take(0, 0)); + } + + @Test + public void aToolNameIsTakenWithinAPackAndFreeAgainOnceTheWorldIsUnregistered() { + OpenToolWorlds worlds = new OpenToolWorlds(); + BukkitToolWorld first = toolWorld(worlds, "pack-a", "scratch", "iris-1"); + BukkitToolWorld sameNameOtherPack = toolWorld(worlds, "pack-b", "scratch", "iris-2"); + BukkitToolWorld sameNameSamePack = toolWorld(worlds, "pack-a", "scratch", "iris-3"); + + assertTrue(worlds.register(first)); + assertTrue(worlds.register(sameNameOtherPack)); + assertFalse(worlds.register(sameNameSamePack)); + assertEquals(first, worlds.forName("pack-a", "scratch").orElseThrow()); + + worlds.unregister(first); + + assertTrue(worlds.forName("pack-a", "scratch").isEmpty()); + assertTrue(worlds.register(sameNameSamePack)); + } + + @Test + public void aBoundWorldIsFoundByItsBukkitWorldAndNotByAnotherWorld() { + OpenToolWorlds worlds = new OpenToolWorlds(); + BukkitToolWorld toolWorld = toolWorld(worlds, "pack", "scratch", "iris-1"); + World bukkit = world(UUID.randomUUID()); + World other = world(UUID.randomUUID()); + assertTrue(worlds.register(toolWorld)); + + toolWorld.bind(bukkit); + + assertEquals(toolWorld, worlds.forWorld(bukkit).orElseThrow()); + assertTrue(worlds.forWorld(other).isEmpty()); + assertTrue(worlds.forWorld(null).isEmpty()); + + worlds.unregister(toolWorld); + + assertTrue(worlds.forWorld(bukkit).isEmpty()); + } + + @Test + public void aMenuSlotCountsFromTheMiddleColumnOfTheWindow() { + assertEquals(-4, BukkitToolMenus.positionOf(0)); + assertEquals(0, BukkitToolMenus.positionOf(4)); + assertEquals(4, BukkitToolMenus.positionOf(8)); + assertEquals(-4, BukkitToolMenus.positionOf(9)); + assertEquals(4, BukkitToolMenus.positionOf(53)); + } + + @Test + public void aMenuTitleIsShortenedToWhatTheWindowCanShow() { + assertEquals("short", BukkitToolMenus.shortened(ToolText.plain("short"))); + assertEquals(32, BukkitToolMenus.shortened(ToolText.plain("x".repeat(50))).length()); + assertEquals("§a" + "x".repeat(30), BukkitToolMenus.shortened(ToolText.colored(TextColor.GREEN, "x".repeat(50)))); + } + + private static BukkitToolWorld toolWorld(OpenToolWorlds worlds, String pack, String name, String storageName) { + return new BukkitToolWorld(pack, name, storageName, new com.volmit.tooling.world.ToolWorldListener() { }, null, + new PendingBlockEntities(), worlds, new ToolPlayers(worlds)); + } + + private static World world(UUID id) { + World world = mock(World.class); + when(world.getUID()).thenReturn(id); + return world; + } +} diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/ToolWorldEventsTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/ToolWorldEventsTest.java new file mode 100644 index 000000000..28db681a5 --- /dev/null +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/ToolWorldEventsTest.java @@ -0,0 +1,548 @@ +package art.arcane.iris.core.toolworld; + +import com.volmit.geometry.BlockPosition; +import com.volmit.tooling.world.BlockChange; +import com.volmit.tooling.world.BlockChange.Cause; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolUse; +import com.volmit.tooling.world.ToolWorldListener; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.data.BlockData; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockExplodeEvent; +import org.bukkit.event.block.BlockFromToEvent; +import org.bukkit.event.block.BlockPistonExtendEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.block.BlockRedstoneEvent; +import org.bukkit.event.block.CrafterCraftEvent; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.event.player.PlayerBucketEmptyEvent; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.event.server.ServerCommandEvent; +import org.bukkit.event.block.Action; +import org.bukkit.inventory.EquipmentSlot; +import org.junit.Before; +import org.junit.Test; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; + +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.verify; +import static org.mockito.Mockito.when; + +/** The events of a tool world reach its listener as the api says, and the events of other worlds reach nobody. */ +public class ToolWorldEventsTest { + private static final UUID TOOL_WORLD_ID = UUID.fromString("00000000-0000-0000-0000-0000000000a1"); + private static final UUID OTHER_WORLD_ID = UUID.fromString("00000000-0000-0000-0000-0000000000b2"); + private static final UUID PLAYER_ID = UUID.fromString("00000000-0000-0000-0000-0000000000c3"); + + private final List changes = new ArrayList<>(); + private final List heard = new ArrayList<>(); + private boolean allowChanges; + private boolean allowUses = true; + private boolean allowCommands = true; + private World toolBukkitWorld; + private World otherBukkitWorld; + private Player bukkitPlayer; + private ToolWorldEvents events; + + @Before + public void aToolWorldAndAnotherWorld() { + ToolWorldListener listener = new ToolWorldListener() { + @Override + public void entered(ToolPlayer player) { + heard.add("entered " + player.name()); + } + + @Override + public void left(ToolPlayer player) { + heard.add("left " + player.name()); + } + + @Override + public void teleported(ToolPlayer player, BlockPosition to) { + heard.add("teleported " + player.name() + " " + to.x() + "," + to.y() + "," + to.z()); + } + + @Override + public void containerChanged(Optional player, BlockPosition at) { + heard.add("container " + player.map(ToolPlayer::name).orElse("nobody") + " " + at.x() + "," + at.y() + "," + at.z()); + } + + @Override + public boolean used(ToolPlayer player, ToolUse use) { + heard.add("used " + use.action() + " " + use.hand()); + return allowUses; + } + + @Override + public boolean blockChanging(BlockChange change) { + changes.add(change); + return allowChanges; + } + + @Override + public boolean command(Optional sender, String line) { + heard.add("command " + sender.map(ToolPlayer::name).orElse("console") + " " + line); + return allowCommands; + } + }; + OpenToolWorlds worlds = new OpenToolWorlds(); + ToolPlayers players = new ToolPlayers(worlds); + BukkitToolWorld toolWorld = new BukkitToolWorld("pack", "scratch", "iris-test", listener, null, + new PendingBlockEntities(), worlds, players); + toolBukkitWorld = world(TOOL_WORLD_ID); + otherBukkitWorld = world(OTHER_WORLD_ID); + assertTrue(worlds.register(toolWorld)); + toolWorld.bind(toolBukkitWorld); + bukkitPlayer = mock(Player.class); + when(bukkitPlayer.getUniqueId()).thenReturn(PLAYER_ID); + when(bukkitPlayer.getName()).thenReturn("Tester"); + when(bukkitPlayer.getWorld()).thenReturn(toolBukkitWorld); + events = new ToolWorldEvents(worlds, players); + } + + private static World world(UUID id) { + World world = mock(World.class); + when(world.getUID()).thenReturn(id); + return world; + } + + private static Block block(World world, int x, int y, int z) { + Block block = mock(Block.class); + when(block.getWorld()).thenReturn(world); + when(block.getX()).thenReturn(x); + when(block.getY()).thenReturn(y); + when(block.getZ()).thenReturn(z); + BlockData data = mock(BlockData.class); + when(data.getAsString()).thenReturn("minecraft:stone"); + when(block.getBlockData()).thenReturn(data); + return block; + } + + private BlockChange onlyChange() { + assertEquals(1, changes.size()); + return changes.getFirst(); + } + + @Test + public void aPlacedBlockIsAPlaceChangeWithThePlacedStateAndThePlayer() { + Block placed = block(toolBukkitWorld, 3, 70, -4); + BlockPlaceEvent event = mock(BlockPlaceEvent.class); + when(event.getBlockPlaced()).thenReturn(placed); + when(event.getPlayer()).thenReturn(bukkitPlayer); + + events.onBlockPlace(event); + + BlockChange change = onlyChange(); + assertEquals(Cause.PLACE, change.cause()); + assertEquals(List.of(new BlockPosition(3, 70, -4)), change.positions()); + assertEquals("minecraft:stone", change.placed().orElseThrow().key()); + assertEquals("Tester", change.player().orElseThrow().name()); + verify(event).setCancelled(true); + } + + @Test + public void aListenerThatAllowsTheChangeLeavesTheEventAlone() { + allowChanges = true; + Block broken = block(toolBukkitWorld, 1, 2, 3); + BlockBreakEvent event = mock(BlockBreakEvent.class); + when(event.getBlock()).thenReturn(broken); + when(event.getPlayer()).thenReturn(bukkitPlayer); + + events.onBlockBreak(event); + + assertEquals(Cause.BREAK, onlyChange().cause()); + verify(event, never()).setCancelled(true); + } + + @Test + public void aBucketEmptiesIntoTheBlockNextToTheOneClicked() { + Block clicked = block(toolBukkitWorld, 0, 64, 0); + Block target = block(toolBukkitWorld, 0, 65, 0); + when(clicked.getRelative(BlockFace.UP)).thenReturn(target); + PlayerBucketEmptyEvent event = mock(PlayerBucketEmptyEvent.class); + when(event.getBlockClicked()).thenReturn(clicked); + when(event.getBlockFace()).thenReturn(BlockFace.UP); + when(event.getPlayer()).thenReturn(bukkitPlayer); + + events.onBucketEmpty(event); + + BlockChange change = onlyChange(); + assertEquals(Cause.BUCKET, change.cause()); + assertEquals(List.of(new BlockPosition(0, 65, 0)), change.positions()); + } + + @Test + public void flowingFluidNamesTheSourceAndTheTargetBlock() { + Block source = block(toolBukkitWorld, 0, 64, 0); + Block target = block(toolBukkitWorld, 1, 64, 0); + BlockFromToEvent event = mock(BlockFromToEvent.class); + when(event.getBlock()).thenReturn(source); + when(event.getToBlock()).thenReturn(target); + + events.onBlockFromTo(event); + + BlockChange change = onlyChange(); + assertEquals(Cause.FLUID, change.cause()); + assertEquals(List.of(new BlockPosition(0, 64, 0), new BlockPosition(1, 64, 0)), change.positions()); + assertTrue(change.player().isEmpty()); + verify(event).setCancelled(true); + } + + @Test + public void aPistonIsCheckedAgainstEveryBlockItMovesAndTheBlocksTheyLeaveAndEnterButNotItself() { + Block piston = block(toolBukkitWorld, 0, 64, 0); + Block moved = block(toolBukkitWorld, 1, 64, 0); + Block ahead = block(toolBukkitWorld, 2, 64, 0); + when(moved.getRelative(BlockFace.EAST)).thenReturn(ahead); + when(moved.getRelative(BlockFace.WEST)).thenReturn(piston); + + List positions = ToolWorldEvents.pistonChecked(List.of(moved), BlockFace.EAST); + + assertEquals(List.of(new BlockPosition(1, 64, 0), new BlockPosition(2, 64, 0), new BlockPosition(0, 64, 0)), positions); + } + + @Test + public void aPistonChangesItselfTheBlockAheadOfItAndEveryBlockItMovesAndWhereTheyGo() { + Block piston = block(toolBukkitWorld, 0, 64, 0); + Block moved = block(toolBukkitWorld, 1, 64, 0); + Block ahead = block(toolBukkitWorld, 2, 64, 0); + when(piston.getRelative(BlockFace.EAST)).thenReturn(moved); + when(moved.getRelative(BlockFace.EAST)).thenReturn(ahead); + + List changed = ToolWorldEvents.pistonChanged(piston, List.of(moved), BlockFace.EAST); + + assertEquals(List.of(new BlockPosition(0, 64, 0), new BlockPosition(1, 64, 0), new BlockPosition(2, 64, 0)), changed); + } + + @Test + public void aPistonThatMovesNothingStillChangesItsOwnBlocks() { + Block piston = block(toolBukkitWorld, 0, 64, 0); + Block ahead = block(toolBukkitWorld, 1, 64, 0); + when(piston.getRelative(BlockFace.EAST)).thenReturn(ahead); + BlockPistonExtendEvent event = mock(BlockPistonExtendEvent.class); + when(event.getBlock()).thenReturn(piston); + when(event.getBlocks()).thenReturn(List.of()); + when(event.getDirection()).thenReturn(BlockFace.EAST); + + events.onPistonExtend(event); + + BlockChange change = onlyChange(); + assertEquals(List.of(), change.positions()); + assertEquals(List.of(new BlockPosition(0, 64, 0), new BlockPosition(1, 64, 0)), change.changed()); + } + + @Test + public void aPistonExtendingInAToolWorldIsAPistonChange() { + Block piston = block(toolBukkitWorld, 0, 64, 0); + Block ahead = block(toolBukkitWorld, 1, 64, 0); + when(piston.getRelative(BlockFace.EAST)).thenReturn(ahead); + BlockPistonExtendEvent event = mock(BlockPistonExtendEvent.class); + when(event.getBlock()).thenReturn(piston); + when(event.getBlocks()).thenReturn(List.of()); + when(event.getDirection()).thenReturn(BlockFace.EAST); + + events.onPistonExtend(event); + + assertEquals(Cause.PISTON, onlyChange().cause()); + verify(event).setCancelled(true); + } + + @Test + public void anExplosionAsksForEachBlockAndKeepsOnlyTheOnesTheToolAllows() { + allowChanges = false; + Block first = block(toolBukkitWorld, 0, 64, 0); + Block second = block(toolBukkitWorld, 5, 64, 5); + List blockList = new ArrayList<>(List.of(first, second)); + Block source = block(toolBukkitWorld, 0, 70, 0); + BlockExplodeEvent event = mock(BlockExplodeEvent.class); + when(event.getBlock()).thenReturn(source); + when(event.blockList()).thenReturn(blockList); + + events.onBlockExplode(event); + + assertEquals(2, changes.size()); + assertEquals(Cause.EXPLOSION, changes.getFirst().cause()); + assertTrue("nothing was allowed to blow up", blockList.isEmpty()); + } + + @Test + public void refusedRedstoneKeepsTheOldCurrent() { + Block wire = block(toolBukkitWorld, 0, 64, 0); + BlockRedstoneEvent event = mock(BlockRedstoneEvent.class); + when(event.getBlock()).thenReturn(wire); + when(event.getOldCurrent()).thenReturn(7); + + events.onBlockRedstone(event); + + assertEquals(Cause.REDSTONE, onlyChange().cause()); + verify(event).setNewCurrent(7); + } + + @Test + public void aCrafterIsAMachine() { + Block crafter = block(toolBukkitWorld, 0, 64, 0); + CrafterCraftEvent event = mock(CrafterCraftEvent.class); + when(event.getBlock()).thenReturn(crafter); + + events.onCrafterCraft(event); + + assertEquals(Cause.MACHINE, onlyChange().cause()); + } + + @Test + public void nothingThatHappensInAnotherWorldReachesTheToolOrIsCancelled() { + Block brokenElsewhere = block(otherBukkitWorld, 1, 2, 3); + Block wireElsewhere = block(otherBukkitWorld, 1, 2, 3); + BlockBreakEvent breaking = mock(BlockBreakEvent.class); + when(breaking.getBlock()).thenReturn(brokenElsewhere); + when(breaking.getPlayer()).thenReturn(bukkitPlayer); + BlockRedstoneEvent redstone = mock(BlockRedstoneEvent.class); + when(redstone.getBlock()).thenReturn(wireElsewhere); + + events.onBlockBreak(breaking); + events.onBlockRedstone(redstone); + + assertTrue(changes.isEmpty()); + verify(breaking, never()).setCancelled(true); + verify(redstone, never()).setNewCurrent(0); + } + + @Test + public void usingTheHandIsAUseWithTheHandAndActionAndAFalseCancelsIt() { + allowUses = false; + PlayerInteractEvent event = mock(PlayerInteractEvent.class); + when(event.getPlayer()).thenReturn(bukkitPlayer); + when(event.getHand()).thenReturn(EquipmentSlot.OFF_HAND); + when(event.getAction()).thenReturn(Action.RIGHT_CLICK_AIR); + when(event.getBlockFace()).thenReturn(BlockFace.SELF); + + events.onInteract(event); + + assertEquals(List.of("used RIGHT_CLICK_AIR OFF"), heard); + verify(event).setCancelled(true); + } + + @Test + public void aCommandReachesTheToolWithoutItsSlashAndTheConsoleHasNoPlayer() { + allowCommands = false; + PlayerCommandPreprocessEvent typed = mock(PlayerCommandPreprocessEvent.class); + when(typed.getPlayer()).thenReturn(bukkitPlayer); + when(typed.getMessage()).thenReturn("/gamemode survival"); + ServerCommandEvent console = mock(ServerCommandEvent.class); + when(console.getCommand()).thenReturn("stop"); + + events.onPlayerCommand(typed); + events.onServerCommand(console); + + assertEquals(List.of("command Tester gamemode survival", "command console stop"), heard); + verify(typed).setCancelled(true); + verify(console).setCancelled(true); + } + + @Test + public void naturalSpawnsInAToolWorldAreCancelledButOtherSpawnsAreNot() { + CreatureSpawnEvent natural = mock(CreatureSpawnEvent.class); + when(natural.getSpawnReason()).thenReturn(CreatureSpawnEvent.SpawnReason.NATURAL); + when(natural.getLocation()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0)); + CreatureSpawnEvent egg = mock(CreatureSpawnEvent.class); + when(egg.getSpawnReason()).thenReturn(CreatureSpawnEvent.SpawnReason.SPAWNER_EGG); + when(egg.getLocation()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0)); + CreatureSpawnEvent elsewhere = mock(CreatureSpawnEvent.class); + when(elsewhere.getSpawnReason()).thenReturn(CreatureSpawnEvent.SpawnReason.NATURAL); + when(elsewhere.getLocation()).thenReturn(new Location(otherBukkitWorld, 0, 64, 0)); + + events.onNaturalSpawn(natural); + events.onNaturalSpawn(egg); + events.onNaturalSpawn(elsewhere); + + verify(natural).setCancelled(true); + verify(egg, never()).setCancelled(true); + verify(elsewhere, never()).setCancelled(true); + } + + @Test + public void enteringIsToldOnceHoweverManyEventsAnnounceTheArrival() { + PlayerTeleportEvent teleport = mock(PlayerTeleportEvent.class); + when(teleport.getPlayer()).thenReturn(bukkitPlayer); + when(teleport.getFrom()).thenReturn(new Location(otherBukkitWorld, 0, 64, 0)); + when(teleport.getTo()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0)); + + events.onTeleport(teleport); + events.onTeleport(teleport); + + assertEquals(List.of("entered Tester", "teleported Tester 0,64,0", "teleported Tester 0,64,0"), heard); + } + + @Test + public void aTeleportInsideAToolWorldIsToldAtOnceWithItsDestination() { + PlayerTeleportEvent teleport = mock(PlayerTeleportEvent.class); + when(teleport.getPlayer()).thenReturn(bukkitPlayer); + when(teleport.getFrom()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0)); + when(teleport.getTo()).thenReturn(new Location(toolBukkitWorld, 40, 70, -3)); + + events.onTeleport(teleport); + + assertEquals(List.of("entered Tester", "teleported Tester 40,70,-3"), heard); + } + + @Test + public void aTeleportOutOfAToolWorldIsToldAsLeaving() { + PlayerTeleportEvent in = mock(PlayerTeleportEvent.class); + when(in.getPlayer()).thenReturn(bukkitPlayer); + when(in.getFrom()).thenReturn(new Location(otherBukkitWorld, 0, 64, 0)); + when(in.getTo()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0)); + PlayerTeleportEvent out = mock(PlayerTeleportEvent.class); + when(out.getPlayer()).thenReturn(bukkitPlayer); + when(out.getFrom()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0)); + when(out.getTo()).thenReturn(new Location(otherBukkitWorld, 5, 64, 5)); + + events.onTeleport(in); + events.onTeleport(out); + + assertEquals(List.of("entered Tester", "teleported Tester 0,64,0", "left Tester"), heard); + } + + @Test + public void respawningInAToolWorldIsAnArrivalAtTheRespawnPoint() { + PlayerRespawnEvent respawn = mock(PlayerRespawnEvent.class); + when(respawn.getPlayer()).thenReturn(bukkitPlayer); + when(respawn.getRespawnLocation()).thenReturn(new Location(toolBukkitWorld, 8, 66, 8)); + + events.onRespawn(respawn); + + assertEquals(List.of("entered Tester", "teleported Tester 8,66,8"), heard); + } + + @Test + public void closingAContainerInAToolWorldTellsTheToolWhichBlockChanged() { + Block chest = block(toolBukkitWorld, 4, 65, 4); + org.bukkit.inventory.Inventory inventory = mock(org.bukkit.inventory.Inventory.class); + org.bukkit.inventory.BlockInventoryHolder holder = mock(org.bukkit.inventory.BlockInventoryHolder.class); + when(holder.getBlock()).thenReturn(chest); + when(inventory.getHolder()).thenReturn(holder); + org.bukkit.inventory.InventoryView view = mock(org.bukkit.inventory.InventoryView.class); + when(view.getTopInventory()).thenReturn(inventory); + org.bukkit.event.inventory.InventoryCloseEvent close = mock(org.bukkit.event.inventory.InventoryCloseEvent.class); + when(close.getPlayer()).thenReturn(bukkitPlayer); + when(close.getView()).thenReturn(view); + + events.onInventoryClose(close); + + assertEquals(List.of("container Tester 4,65,4"), heard); + } + + @Test + public void aFurnaceStartingToSmeltTellsTheToolWithoutAPlayer() { + Block furnace = block(toolBukkitWorld, 2, 64, 2); + org.bukkit.event.inventory.FurnaceStartSmeltEvent smelt = mock(org.bukkit.event.inventory.FurnaceStartSmeltEvent.class); + when(smelt.getBlock()).thenReturn(furnace); + + events.onFurnaceStartSmelt(smelt); + + assertEquals(List.of("container nobody 2,64,2"), heard); + } + + @Test + public void leavingByQuittingIsToldOnceAfterTheStay() { + PlayerTeleportEvent teleport = mock(PlayerTeleportEvent.class); + when(teleport.getPlayer()).thenReturn(bukkitPlayer); + when(teleport.getFrom()).thenReturn(new Location(otherBukkitWorld, 0, 64, 0)); + when(teleport.getTo()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0)); + PlayerQuitEvent quit = mock(PlayerQuitEvent.class); + when(quit.getPlayer()).thenReturn(bukkitPlayer); + + events.onTeleport(teleport); + events.onQuit(quit); + events.onQuit(quit); + + assertEquals(List.of("entered Tester", "teleported Tester 0,64,0", "left Tester"), heard); + } + + @Test + public void movingInsideOneBlockIsNotAMove() { + Location from = new Location(toolBukkitWorld, 1.1, 64.0, 2.2); + + assertTrue(ToolWorldEvents.sameBlock(from, new Location(toolBukkitWorld, 1.9, 64.5, 2.9))); + assertFalse(ToolWorldEvents.sameBlock(from, new Location(toolBukkitWorld, 2.1, 64.0, 2.2))); + assertFalse(ToolWorldEvents.sameBlock(from, new Location(otherBukkitWorld, 1.1, 64.0, 2.2))); + } + + @Test + public void aCommandLineHasNoLeadingSlash() { + assertEquals("tp a b", ToolWorldEvents.lineOf("/tp a b")); + assertEquals("tp a b", ToolWorldEvents.lineOf("tp a b")); + } + + @Test + public void everyHandlerKeepsThePriorityAndCancelFlagOfTheJigsawStudioHandlerItReplaces() { + Map byMethod = new HashMap<>(); + for (Method method : ToolWorldEvents.class.getDeclaredMethods()) { + EventHandler handler = method.getAnnotation(EventHandler.class); + if (handler != null) { + byMethod.put(method.getName(), handler); + } + } + Set checked = new HashSet<>(); + + for (String decision : List.of("onBlockPlace", "onBlockMultiPlace", "onBlockBreak", "onBucketEmpty", "onBucketFill", + "onBlockForm", "onBlockFade", "onBlockSpread", "onBlockFromTo", "onBlockGrow", "onStructureGrow", "onBlockBurn", + "onPistonExtend", "onPistonRetract", "onBlockExplode", "onEntityExplode", "onEntityChangeBlock", + "onInventoryClick", "onInventoryDrag", "onInventoryMove", "onInventoryPickup", "onBlockCook", "onFurnaceBurn", + "onFurnaceSmelt", "onBrew", "onBrewingStandFuel", "onBlockDispense", "onCrafterCraft", "onPlayerCommand", + "onServerCommand", "onNaturalSpawn", "onPortal")) { + assertPriority(byMethod, checked, decision, EventPriority.HIGHEST, true); + } + assertPriority(byMethod, checked, "onBlockRedstone", EventPriority.HIGHEST, false); + assertPriority(byMethod, checked, "onInteract", EventPriority.LOWEST, true); + assertPriority(byMethod, checked, "onToggleSneak", EventPriority.NORMAL, false); + for (String arrival : List.of("onJoin", "onQuit", "onChangedWorld", "onChunkLoad")) { + assertPriority(byMethod, checked, arrival, EventPriority.NORMAL, false); + } + assertPriority(byMethod, checked, "onTeleport", EventPriority.MONITOR, true); + assertPriority(byMethod, checked, "onMove", EventPriority.MONITOR, true); + assertPriority(byMethod, checked, "onRespawn", EventPriority.MONITOR, false); + for (String containerNews : List.of("onInventoryClose", "onFurnaceStartSmelt", "onBrewingStart")) { + assertPriority(byMethod, checked, containerNews, EventPriority.MONITOR, false); + } + assertPriority(byMethod, checked, "onWorldUnload", EventPriority.MONITOR, true); + assertEquals("every handler of the class was checked", byMethod.keySet(), checked); + } + + private static void assertPriority( + Map byMethod, + Set checked, + String method, + EventPriority priority, + boolean ignoreCancelled + ) { + checked.add(method); + EventHandler handler = byMethod.get(method); + assertTrue(method + " is a handler", handler != null); + assertEquals(method + " priority", priority, handler.priority()); + assertEquals(method + " ignoreCancelled", ignoreCancelled, handler.ignoreCancelled()); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/IrisModdedChunkGenerator.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/IrisModdedChunkGenerator.java index b7a74a3e3..de91346da 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/IrisModdedChunkGenerator.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/IrisModdedChunkGenerator.java @@ -21,6 +21,7 @@ package art.arcane.iris.modded; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.pack.PackValidationRegistry; import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.modded.toolworld.ModdedToolPainting; import art.arcane.iris.engine.framework.NativeFeatureGenerationPolicy; import art.arcane.iris.engine.framework.GenerationSessionException; import art.arcane.iris.engine.framework.GenerationSessionLease; @@ -134,6 +135,7 @@ public final class IrisModdedChunkGenerator extends ChunkGenerator { private volatile ModdedDimensionMetadata.ConfiguredPack configuredPack; private volatile ModdedDimensionMetadata.DimensionMetadata heightMetadata; private volatile ServerLevel boundLevel; + private volatile ModdedToolPainting toolPainting; public IrisModdedChunkGenerator(BiomeSource biomeSource, String dimensionKey) { this(biomeSource, dimensionKey, new IrisModdedBiomeSource(biomeSource)); @@ -165,6 +167,11 @@ public final class IrisModdedChunkGenerator extends ChunkGenerator { this.activeDimensionKey = defaultDimensionKey; } + /** Makes the chunks of this generator whatever {@code painting} paints, and nothing else: no structures, features or mobs. Null gives them back to the pack. */ + public void paintWith(ModdedToolPainting painting) { + this.toolPainting = painting; + } + public synchronized void repoint(String pack, String packDimensionKey, long seed) { ServerLevel level = boundLevel(); if (level != null) { @@ -765,6 +772,10 @@ public final class IrisModdedChunkGenerator extends ChunkGenerator { @Override public CompletableFuture fillFromNoise(Blender blender, RandomState randomState, StructureManager structureManager, ChunkAccess chunk) { + ModdedToolPainting painting = toolPainting; + if (painting != null) { + return CompletableFuture.completedFuture(painting.paint(chunk, boundLevel())); + } Engine generationEngine = engine(); ChunkPos pos = chunk.getPos(); lastChunkGenAt = System.currentTimeMillis(); @@ -896,6 +907,9 @@ public final class IrisModdedChunkGenerator extends ChunkGenerator { @Override public void applyBiomeDecoration(WorldGenLevel level, ChunkAccess chunk, StructureManager structureManager) { + if (toolPainting != null) { + return; + } Engine current = engine(); importedFeatures.prepare(current); try (GenerationSessionLease lease = requireGenerationLease(current, "modded_biome_decoration"); @@ -910,6 +924,9 @@ public final class IrisModdedChunkGenerator extends ChunkGenerator { @Override public void createStructures(RegistryAccess registryAccess, ChunkGeneratorStructureState structureState, StructureManager structureManager, ChunkAccess chunk, StructureTemplateManager templateManager, ResourceKey levelKey) { + if (toolPainting != null) { + return; + } Engine current = engine(levelKey); try (GenerationSessionLease lease = requireGenerationLease(current, "modded_create_structures"); IrisContext.Scope ignored = IrisContext.open(current, lease.sessionId(), null)) { @@ -934,6 +951,9 @@ public final class IrisModdedChunkGenerator extends ChunkGenerator { @Override public void createReferences(WorldGenLevel level, StructureManager structureManager, ChunkAccess chunk) { + if (toolPainting != null) { + return; + } Engine current = engine(level.getLevel()); try (GenerationSessionLease lease = requireGenerationLease(current, "modded_create_references"); IrisContext.Scope ignored = IrisContext.open(current, lease.sessionId(), null)) { @@ -948,6 +968,9 @@ public final class IrisModdedChunkGenerator extends ChunkGenerator { @Override public void spawnOriginalMobs(WorldGenRegion region) { + if (toolPainting != null) { + return; + } Registry registry = region.registryAccess().lookupOrThrow(Registries.BIOME); spawnTables.initializeVanillaSpawnBiomes(registry); ChunkPos center = region.getCenter(); diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedDimensionManager.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedDimensionManager.java index 29a3d3638..ade6c7014 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedDimensionManager.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedDimensionManager.java @@ -21,6 +21,7 @@ package art.arcane.iris.modded; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.modded.toolworld.ModdedToolPainting; import net.minecraft.core.BlockPos; import net.minecraft.core.Holder; import net.minecraft.core.Registry; @@ -119,7 +120,9 @@ public final class ModdedDimensionManager { return generator.commandEngine(); } - public static Handle create(MinecraftServer server, String dimensionId, String pack, String packDimensionKey, long seed) { + /** Makes the runtime dimension {@code dimensionId} generate {@code pack}, with chunks that come only from {@code painting} when it is not null. */ + public static Handle create(MinecraftServer server, String dimensionId, String pack, String packDimensionKey, long seed, + ModdedToolPainting painting) { ModdedStartup.requirePackForWorldCreation(pack); ModdedServerAccess serverAccess = requireAccess(); synchronized (LOCK) { @@ -144,7 +147,7 @@ public final class ModdedDimensionManager { } try { - Handle handle = inject(server, serverAccess, dimensionId, key, pack, packDimensionKey, seed); + Handle handle = inject(server, serverAccess, dimensionId, key, pack, packDimensionKey, seed, painting); HANDLES.put(dimensionId, handle); ModdedIrisLog.info("Iris injected runtime dimension '{}' (pack={} dim={} seed={})", dimensionId, pack, packDimensionKey, seed); return handle; @@ -155,6 +158,10 @@ public final class ModdedDimensionManager { } } + public static Handle create(MinecraftServer server, String dimensionId, String pack, String packDimensionKey, long seed) { + return create(server, dimensionId, pack, packDimensionKey, seed, null); + } + public static Handle createPersistent(MinecraftServer server, String dimensionId, String pack, String packDimensionKey, long seed) { ModdedDimensionRegistryStore.PersistentDimension previous = ModdedDimensionRegistryStore.get(server, dimensionId); @@ -545,13 +552,15 @@ public final class ModdedDimensionManager { } } - private static Handle inject(MinecraftServer server, ModdedServerAccess serverAccess, String dimensionId, ResourceKey key, String pack, String packDimensionKey, long seed) { + private static Handle inject(MinecraftServer server, ModdedServerAccess serverAccess, String dimensionId, ResourceKey key, String pack, String packDimensionKey, long seed, + ModdedToolPainting painting) { RegistryAccess registryAccess = server.registryAccess(); Holder dimensionType = resolveDimensionType(registryAccess, pack, packDimensionKey); Holder plains = registryAccess.lookupOrThrow(Registries.BIOME).getOrThrow(Biomes.PLAINS); FixedBiomeSource biomeSource = new FixedBiomeSource(plains); String generatorRef = pack.equals(packDimensionKey) ? pack : pack + ":" + packDimensionKey; IrisModdedChunkGenerator generator = new IrisModdedChunkGenerator(biomeSource, generatorRef); + generator.paintWith(painting); generator.repoint(pack, packDimensionKey, seed); LevelStem stem = new LevelStem(dimensionType, generator); diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineBootstrap.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineBootstrap.java index b606831a8..5bb3f0401 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineBootstrap.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/ModdedEngineBootstrap.java @@ -38,6 +38,10 @@ import art.arcane.iris.modded.command.ModdedPregenBossBar; import art.arcane.iris.modded.command.ModdedPregenJob; import art.arcane.iris.modded.command.ModdedStudioCommands; import art.arcane.iris.modded.command.ModdedWandService; +import art.arcane.iris.modded.structure.ModdedPlatformStructures; +import art.arcane.iris.modded.toolworld.ModdedToolWorldService; +import art.arcane.iris.core.tooling.ToolWorldsHost; +import com.volmit.tooling.PlatformStructures; import art.arcane.iris.modded.service.ModdedChunkUpdateService; import art.arcane.iris.modded.service.ModdedEngineMaintenanceService; import art.arcane.iris.modded.service.ModdedEntitySpawnService; @@ -156,6 +160,7 @@ public final class ModdedEngineBootstrap { } public static void levelUnloaded(ServerLevel level) { + ModdedToolWorldService.levelUnloaded(level); if (!(level.getChunkSource().getGenerator() instanceof IrisModdedChunkGenerator generator)) { return; } @@ -450,11 +455,15 @@ public final class ModdedEngineBootstrap { createdServices.register(ModdedChunkUpdateService.class, new ModdedChunkUpdateService()); createdServices.register(ModdedEntitySpawnService.class, new ModdedEntitySpawnService()); createdServices.register(ModdedTreeFellerService.class, new ModdedTreeFellerService()); + ModdedToolWorldService toolWorlds = createdServices.register( + ModdedToolWorldService.class, new ModdedToolWorldService()); bindService(PreservationRegistry.class, preservation, rollback); bindService(EngineEffectsProvider.class, (EngineEffectsProvider) ModdedEngineEffects::new, rollback); bindService(EnginePlatformHooks.class, studioHotloadService, rollback); + bindService(ToolWorldsHost.class, toolWorlds, rollback); + bindService(PlatformStructures.class, new ModdedPlatformStructures(), rollback); bindService(EngineWorldManagerProvider.class, (EngineWorldManagerProvider) (Engine engine) -> new ModdedWorldManager(engine), rollback); diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandHelp.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandHelp.java index 32bba30ca..7a08b6a00 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandHelp.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandHelp.java @@ -85,7 +85,6 @@ final class ModdedCommandHelp { Entry.group("pack", ModdedHelpMessages.GROUP_PACK_PACK_VALIDATION_AND_MAINTENANCE, "pk"), Entry.group("world", ModdedHelpMessages.GROUP_WORLD_RUNTIME_IRIS_DIMENSION_CREATION_REMOVAL_AND_STATUS, "w"), Entry.group("datapack", ModdedHelpMessages.GROUP_DATAPACK_WORLD_DATAPACK_INSTALL_AND_STATUS_HELPERS, "datapacks", "dp"), - Entry.group("structure", ModdedHelpMessages.GROUP_STRUCTURE_IRIS_STRUCTURE_IMPORT_AND_CAPTURE_TOOLS, "struct", "str"), Entry.command(ToolingCommands.BRANCH, " ", ModdedHelpMessages.COMMAND_MODULE_RUN_A_MODULE_COMMAND_OR_LIST_THEM, ToolingCommands.BRANCH_ALIAS), Entry.command("goldenhash", "[radius] [threads] [capture|verify]", ModdedHelpMessages.COMMAND_GOLDENHASH_GENERATE_DETERMINISTIC_BLOCK_HASHES_FOR_PARITY_TESTING, "gold"), Entry.group("developer", ModdedHelpMessages.GROUP_DEVELOPER_DEVELOPER_DIAGNOSTICS_NETWORK_INTERFACES_REGION_FILE_SCAN, "dev") @@ -185,12 +184,6 @@ final class ModdedCommandHelp { )); SECTIONS.put("datapacks", SECTIONS.get("datapack")); SECTIONS.put("dp", SECTIONS.get("datapack")); - SECTIONS.put("structure", List.of( - Entry.command("import", "", ModdedHelpMessages.COMMAND_IMPORT_EXPLAIN_BUKKIT_STRUCTURE_IMPORT_WORKFLOW, "import-all", "reimport", "imp", "all"), - Entry.command("capture", "", ModdedHelpMessages.COMMAND_CAPTURE_EXPLAIN_BUKKIT_STRUCTURE_CAPTURE_WORKFLOW, "cap") - )); - SECTIONS.put("struct", SECTIONS.get("structure")); - SECTIONS.put("str", SECTIONS.get("structure")); SECTIONS.put("developer", List.of( Entry.command("network", "", ModdedHelpMessages.COMMAND_NETWORK_LIST_NETWORK_INTERFACES_AND_THEIR_ADDRESSES, "ip") )); diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandTree.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandTree.java index 6e1c3f5e5..ba0090057 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandTree.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedCommandTree.java @@ -147,9 +147,6 @@ final class ModdedCommandTree { root.then(ModdedDatapackCommands.tree("datapack")); root.then(ModdedDatapackCommands.tree("datapacks")); root.then(ModdedDatapackCommands.tree("dp")); - root.then(ModdedStructureCommands.tree("structure")); - root.then(ModdedStructureCommands.tree("struct")); - root.then(ModdedStructureCommands.tree("str")); root.then(ModdedDeveloperCommands.tree("developer")); root.then(ModdedDeveloperCommands.tree("dev")); root.then(ModdedModuleBranch.tree(ToolingCommands.BRANCH)); diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStructureCommands.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStructureCommands.java deleted file mode 100644 index d7f5a52d0..000000000 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStructureCommands.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * 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.modded.command; - -import com.mojang.brigadier.arguments.StringArgumentType; -import com.mojang.brigadier.builder.LiteralArgumentBuilder; -import com.mojang.brigadier.context.CommandContext; -import net.minecraft.commands.CommandSourceStack; -import net.minecraft.commands.Commands; - -/** - * The {@code /iris structure} literals that only explain the Bukkit-only import and capture. The structure module's own - * commands ({@code list}, {@code info}, {@code verify}) are under {@code /iris module structure}. - */ -public final class ModdedStructureCommands { - private static final String IMPORT_EXPLANATION = "Structure import rebuilds vanilla & datapack structures as editable Iris resources through Bukkit/NMS template managers; run /iris structure import on a Bukkit server against this pack, then copy the pack folder over."; - private static final String CAPTURE_EXPLANATION = "Structure capture generates each structure in a throwaway Bukkit scratch world to read its blocks; it requires the Bukkit plugin (v26 NMS binding)."; - - private ModdedStructureCommands() { - } - - public static LiteralArgumentBuilder tree(String name) { - LiteralArgumentBuilder root = Commands.literal(name).requires(ModdedCommandTree.GATE); - - root.executes((CommandContext context) -> ModdedCommandHelp.send(context.getSource(), name)); - - root.then(message("import", IMPORT_EXPLANATION)); - root.then(message("import-all", IMPORT_EXPLANATION)); - root.then(message("reimport", IMPORT_EXPLANATION)); - root.then(message("imp", IMPORT_EXPLANATION)); - root.then(message("all", IMPORT_EXPLANATION)); - root.then(message("capture", CAPTURE_EXPLANATION)); - root.then(message("cap", CAPTURE_EXPLANATION)); - - return root; - } - - private static LiteralArgumentBuilder message(String name, String text) { - return Commands.literal(name) - .executes((CommandContext context) -> { - IrisModdedCommands.fail(context.getSource(), text); - return 0; - }) - .then(Commands.argument("args", StringArgumentType.greedyString()) - .executes((CommandContext context) -> { - IrisModdedCommands.fail(context.getSource(), text); - return 0; - })); - } -} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java index e2731467d..08f142c7a 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedStudioCommands.java @@ -34,6 +34,7 @@ import art.arcane.iris.modded.ModdedDimensionManager; import art.arcane.iris.modded.ModdedEngineBootstrap; import art.arcane.iris.modded.ModdedScheduler; import art.arcane.iris.modded.ModdedWorkspaceGenerator; +import art.arcane.iris.modded.toolworld.ModdedToolWorldService; import art.arcane.iris.util.common.parallel.BurstExecutor; import art.arcane.iris.util.common.parallel.MultiBurst; import art.arcane.volmlib.util.collection.KMap; @@ -56,6 +57,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; @@ -329,10 +331,16 @@ public final class ModdedStudioCommands { UUID owner = player == null ? CONSOLE_OWNER : player.getUUID(); String dimensionId = player == null ? studioConsoleDimensionId() : studioDimensionId(player); MinecraftServer server = source.getServer(); + Optional toolWorldRefusal = ModdedToolWorldService.studioChangeRefusal(); + if (toolWorldRefusal.isPresent()) { + IrisModdedCommands.fail(source, toolWorldRefusal.get()); + return 0; + } IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_STUDIO_SEED, MessageArgument.untrusted("pack", pack), MessageArgument.untrusted("seed", seed))); CompletableFuture transition = TRANSITIONS.submit( owner, - () -> openTransition(source, server, owner, dimensionId, pack, seed)); + () -> ModdedToolWorldService.closeForStudioChange(Optional.ofNullable(player)) + .thenCompose(ignored -> openTransition(source, server, owner, dimensionId, pack, seed))); reportOpenFailure(source, server, dimensionId, pack, transition); return 1; } @@ -531,7 +539,13 @@ public final class ModdedStudioCommands { ServerPlayer player = source.getPlayer(); MinecraftServer server = source.getServer(); UUID owner = player == null ? CONSOLE_OWNER : player.getUUID(); - TRANSITIONS.submit(owner, () -> closeTransition(source, server, owner)); + Optional toolWorldRefusal = ModdedToolWorldService.studioChangeRefusal(); + if (toolWorldRefusal.isPresent()) { + IrisModdedCommands.fail(source, toolWorldRefusal.get()); + return 0; + } + TRANSITIONS.submit(owner, () -> ModdedToolWorldService.closeForStudioChange(Optional.ofNullable(player)) + .thenCompose(ignored -> closeTransition(source, server, owner))); return 1; } diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedToolingSender.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedToolingSender.java index b7ee7ca70..0e5656549 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedToolingSender.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedToolingSender.java @@ -22,6 +22,8 @@ import art.arcane.iris.core.tooling.SenderWorld; import art.arcane.iris.core.tooling.ServedPack; import art.arcane.iris.core.tooling.ToolingSender; import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.modded.toolworld.ModdedToolWorldService; +import com.volmit.tooling.world.ToolPlayer; import net.minecraft.commands.CommandSourceStack; import net.minecraft.network.chat.Component; @@ -29,13 +31,14 @@ import java.util.Optional; /** * A modded source of a tooling command. It reads the world of the source when it is built, on the server thread that - * received the command, and delivers messages on the server thread. A modded platform has no studio. + * received the command, and delivers messages on the server thread. A player sends as a tool player, which is how a + * tool world opens for them; the console is none. */ -final class ModdedToolingSender implements ToolingSender { +public final class ModdedToolingSender implements ToolingSender { private final CommandSourceStack source; private final Optional world; - ModdedToolingSender(CommandSourceStack source) { + public ModdedToolingSender(CommandSourceStack source) { this.source = source; this.world = Optional.ofNullable(IrisModdedCommands.engineFor(source.getLevel())) .filter(engine -> !engine.isClosed()) @@ -70,6 +73,11 @@ final class ModdedToolingSender implements ToolingSender { return Optional.ofNullable(source.getEntity()).filter(type::isInstance).map(type::cast); } + @Override + public Optional player() { + return Optional.ofNullable(source.getPlayer()).map(ModdedToolWorldService::toolPlayerOf); + } + @Override public boolean isOperator() { return ModdedCommandTree.GATE.test(source); diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/AbstractContainerMenuToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/AbstractContainerMenuToolMixin.java new file mode 100644 index 000000000..944e43564 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/AbstractContainerMenuToolMixin.java @@ -0,0 +1,47 @@ +/* + * 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.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldHooks; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.ContainerInput; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** Clicks in the inventory of a container block of a tool world are put to the tool; closing one tells it the contents may have changed. */ +@Mixin(AbstractContainerMenu.class) +public abstract class AbstractContainerMenuToolMixin { + @Inject(method = "clicked", at = @At("HEAD"), cancellable = true) + private void iris$askAboutContainerClick(int slot, int button, ContainerInput input, Player player, CallbackInfo info) { + if (player instanceof ServerPlayer serverPlayer + && !ToolWorldHooks.containerClickAllowed(serverPlayer, (AbstractContainerMenu) (Object) this)) { + info.cancel(); + ((AbstractContainerMenu) (Object) this).sendAllDataToRemote(); + } + } + + @Inject(method = "removed", at = @At("RETURN")) + private void iris$tellAboutClosedContainer(Player player, CallbackInfo info) { + ToolWorldHooks.containerClosed(player, (AbstractContainerMenu) (Object) this); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/BlockItemToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/BlockItemToolMixin.java new file mode 100644 index 000000000..d8bbdece6 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/BlockItemToolMixin.java @@ -0,0 +1,64 @@ +/* + * 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.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldGuard; +import art.arcane.iris.modded.toolworld.ToolWorldHooks; +import com.volmit.tooling.world.BlockChange.Cause; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.context.BlockPlaceContext; +import net.minecraft.world.level.block.state.BlockState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +/** A player placing a block in a tool world: the tool is asked about the block before it is placed, once. */ +@Mixin(BlockItem.class) +public abstract class BlockItemToolMixin { + @Shadow + public abstract BlockPlaceContext updatePlacementContext(BlockPlaceContext context); + + @Shadow + protected abstract BlockState getPlacementState(BlockPlaceContext context); + + @Inject(method = "place", at = @At("HEAD"), cancellable = true) + private void iris$askAboutPlacement(BlockPlaceContext context, CallbackInfoReturnable result) { + if (!ToolWorldGuard.isToolWorld(context.getLevel())) { + return; + } + BlockPlaceContext updated = updatePlacementContext(context); + if (updated == null) { + ToolWorldGuard.enter(context.getLevel(), Cause.PLACE, context.getPlayer(), true); + return; + } + if (!ToolWorldHooks.placeAllowed(context.getLevel(), context.getPlayer(), updated.getClickedPos(), getPlacementState(updated))) { + result.setReturnValue(InteractionResult.FAIL); + return; + } + ToolWorldGuard.enter(context.getLevel(), Cause.PLACE, context.getPlayer(), true); + } + + @Inject(method = "place", at = @At("RETURN")) + private void iris$endPlacement(BlockPlaceContext context, CallbackInfoReturnable result) { + ToolWorldGuard.exit(context.getLevel()); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/BrewingStandToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/BrewingStandToolMixin.java new file mode 100644 index 000000000..aa40413ce --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/BrewingStandToolMixin.java @@ -0,0 +1,41 @@ +/* + * 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.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldHooks; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BrewingStandBlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** A brewing stand of a tool world works only while the tool lets machines work there. */ +@Mixin(BrewingStandBlockEntity.class) +public abstract class BrewingStandToolMixin { + @Inject(method = "serverTick", at = @At("HEAD"), cancellable = true) + private static void iris$askAboutBrewingStand(Level level, BlockPos position, BlockState state, + BrewingStandBlockEntity stand, CallbackInfo info) { + if (!ToolWorldHooks.machineAllowed(level, position)) { + info.cancel(); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/BucketItemToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/BucketItemToolMixin.java new file mode 100644 index 000000000..165fa6ef4 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/BucketItemToolMixin.java @@ -0,0 +1,71 @@ +/* + * 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.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldGuard; +import art.arcane.iris.modded.toolworld.ToolWorldHooks; +import com.volmit.tooling.world.BlockChange.Cause; +import net.minecraft.core.BlockPos; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.BucketItem; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.BlockHitResult; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +/** + * Buckets in a tool world. Filling a bucket changes the block it is aimed at, so each change in its use is put to the tool as + * a bucket change. Emptying one is put to the tool before the fluid is placed, once. + */ +@Mixin(BucketItem.class) +public abstract class BucketItemToolMixin { + @Inject(method = "use", at = @At("HEAD")) + private void iris$beginBucketUse(Level level, Player player, InteractionHand hand, CallbackInfoReturnable result) { + ToolWorldGuard.enter(level, Cause.BUCKET, player, false); + } + + @Inject(method = "use", at = @At("RETURN")) + private void iris$endBucketUse(Level level, Player player, InteractionHand hand, CallbackInfoReturnable result) { + ToolWorldGuard.exit(level); + } + + @Inject(method = "emptyContents", at = @At("HEAD"), cancellable = true) + private void iris$askAboutEmptying(LivingEntity user, Level level, BlockPos position, BlockHitResult hit, + CallbackInfoReturnable result) { + if (!ToolWorldGuard.isToolWorld(level)) { + return; + } + if (!ToolWorldHooks.bucketEmptyAllowed(level, user, position)) { + result.setReturnValue(false); + return; + } + ToolWorldGuard.enter(level, Cause.BUCKET, user, true); + } + + @Inject(method = "emptyContents", at = @At("RETURN")) + private void iris$endEmptying(LivingEntity user, Level level, BlockPos position, BlockHitResult hit, + CallbackInfoReturnable result) { + ToolWorldGuard.exit(level); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/CommandsToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/CommandsToolMixin.java new file mode 100644 index 000000000..fc8ca310a --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/CommandsToolMixin.java @@ -0,0 +1,38 @@ +/* + * 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.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldHooks; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** A command a player types in a tool world, or anyone types while one is open, is put to the tool before it runs. */ +@Mixin(Commands.class) +public abstract class CommandsToolMixin { + @Inject(method = "performPrefixedCommand", at = @At("HEAD"), cancellable = true) + private void iris$askAboutCommand(CommandSourceStack source, String command, CallbackInfo info) { + if (!ToolWorldHooks.commandAllowed(source, command)) { + info.cancel(); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/CrafterToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/CrafterToolMixin.java new file mode 100644 index 000000000..d003a82ec --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/CrafterToolMixin.java @@ -0,0 +1,40 @@ +/* + * 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.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldHooks; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.block.CrafterBlock; +import net.minecraft.world.level.block.state.BlockState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** A crafter of a tool world crafts only while the tool lets machines work there. */ +@Mixin(CrafterBlock.class) +public abstract class CrafterToolMixin { + @Inject(method = "dispenseFrom", at = @At("HEAD"), cancellable = true) + private void iris$askAboutCrafter(BlockState state, ServerLevel level, BlockPos position, CallbackInfo info) { + if (!ToolWorldHooks.machineAllowed(level, position)) { + info.cancel(); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/DispenserToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/DispenserToolMixin.java new file mode 100644 index 000000000..abb3d029c --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/DispenserToolMixin.java @@ -0,0 +1,40 @@ +/* + * 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.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldHooks; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.block.DispenserBlock; +import net.minecraft.world.level.block.state.BlockState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** A dispenser or dropper of a tool world fires only while the tool lets machines work there. */ +@Mixin(DispenserBlock.class) +public abstract class DispenserToolMixin { + @Inject(method = "dispenseFrom", at = @At("HEAD"), cancellable = true) + private void iris$askAboutDispenser(ServerLevel level, BlockState state, BlockPos position, CallbackInfo info) { + if (!ToolWorldHooks.machineAllowed(level, position)) { + info.cancel(); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/EntityToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/EntityToolMixin.java new file mode 100644 index 000000000..838e2ec67 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/EntityToolMixin.java @@ -0,0 +1,39 @@ +/* + * 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.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldGuard; +import net.minecraft.core.BlockPos; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.block.Portal; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** A tool world has no portals: nothing standing in one is taken anywhere. */ +@Mixin(Entity.class) +public abstract class EntityToolMixin { + @Inject(method = "setAsInsidePortal", at = @At("HEAD"), cancellable = true) + private void iris$keepToolWorldFreeOfPortals(Portal portal, BlockPos position, CallbackInfo info) { + if (ToolWorldGuard.isToolWorld(((Entity) (Object) this).level())) { + info.cancel(); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/FurnaceToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/FurnaceToolMixin.java new file mode 100644 index 000000000..c9fa834b7 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/FurnaceToolMixin.java @@ -0,0 +1,41 @@ +/* + * 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.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldHooks; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** A furnace of a tool world works only while the tool lets machines work there. */ +@Mixin(AbstractFurnaceBlockEntity.class) +public abstract class FurnaceToolMixin { + @Inject(method = "serverTick", at = @At("HEAD"), cancellable = true) + private static void iris$askAboutFurnace(ServerLevel level, BlockPos position, BlockState state, + AbstractFurnaceBlockEntity furnace, CallbackInfo info) { + if (!ToolWorldHooks.machineAllowed(level, position)) { + info.cancel(); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/LevelChunkToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/LevelChunkToolMixin.java new file mode 100644 index 000000000..0549bdd6b --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/LevelChunkToolMixin.java @@ -0,0 +1,39 @@ +/* + * 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.modded.mixin; + +import art.arcane.iris.modded.toolworld.ModdedToolWorldService; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.chunk.LevelChunk; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** A chunk that becomes live in a tool world is told to the tool. */ +@Mixin(LevelChunk.class) +public abstract class LevelChunkToolMixin { + @Inject(method = "setLoaded", at = @At("RETURN")) + private void iris$tellAboutLoadedChunk(boolean loaded, CallbackInfo info) { + LevelChunk chunk = (LevelChunk) (Object) this; + if (loaded && chunk.getLevel() instanceof ServerLevel level) { + ModdedToolWorldService.chunkLoaded(level, chunk.getPos().x(), chunk.getPos().z()); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/LevelToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/LevelToolMixin.java new file mode 100644 index 000000000..41cfd3d25 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/LevelToolMixin.java @@ -0,0 +1,43 @@ +/* + * 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.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldGuard; +import net.minecraft.core.BlockPos; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +/** Every change to a block of a tool world passes the tool world guard, which is where a tool world stays frozen. */ +@Mixin(Level.class) +public abstract class LevelToolMixin { + @Inject( + method = "setBlock(Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;II)Z", + at = @At("HEAD"), + cancellable = true) + private void iris$guardToolWorldBlock(BlockPos position, BlockState state, int flags, int recursionLeft, + CallbackInfoReturnable result) { + if (!ToolWorldGuard.setBlockAllowed((Level) (Object) this, position, state)) { + result.setReturnValue(false); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/NaturalSpawnerToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/NaturalSpawnerToolMixin.java new file mode 100644 index 000000000..75e8877f4 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/NaturalSpawnerToolMixin.java @@ -0,0 +1,43 @@ +/* + * 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.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldGuard; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.MobCategory; +import net.minecraft.world.level.NaturalSpawner; +import net.minecraft.world.level.chunk.LevelChunk; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.List; + +/** Nothing spawns naturally in a tool world. */ +@Mixin(NaturalSpawner.class) +public abstract class NaturalSpawnerToolMixin { + @Inject(method = "spawnForChunk", at = @At("HEAD"), cancellable = true) + private static void iris$keepToolWorldFreeOfMobs(ServerLevel level, LevelChunk chunk, NaturalSpawner.SpawnState state, + List categories, CallbackInfo info) { + if (ToolWorldGuard.isToolWorld(level)) { + info.cancel(); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/PistonBaseBlockToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/PistonBaseBlockToolMixin.java new file mode 100644 index 000000000..c3dff1779 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/PistonBaseBlockToolMixin.java @@ -0,0 +1,54 @@ +/* + * 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.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldGuard; +import art.arcane.iris.modded.toolworld.ToolWorldHooks; +import com.volmit.tooling.world.BlockChange.Cause; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.piston.PistonBaseBlock; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +/** A piston in a tool world asks the tool about every block it moves before it moves any, so it never moves half a structure. */ +@Mixin(PistonBaseBlock.class) +public abstract class PistonBaseBlockToolMixin { + @Inject(method = "moveBlocks", at = @At("HEAD"), cancellable = true) + private void iris$askAboutPiston(Level level, BlockPos position, Direction direction, boolean extending, + CallbackInfoReturnable result) { + if (!ToolWorldGuard.isToolWorld(level)) { + return; + } + if (!ToolWorldHooks.pistonMoveAllowed(level, position, direction, extending)) { + result.setReturnValue(false); + return; + } + ToolWorldGuard.enter(level, Cause.PISTON, null, true); + } + + @Inject(method = "moveBlocks", at = @At("RETURN")) + private void iris$endPiston(Level level, BlockPos position, Direction direction, boolean extending, + CallbackInfoReturnable result) { + ToolWorldGuard.exit(level); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/SaplingBlockToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/SaplingBlockToolMixin.java new file mode 100644 index 000000000..6ba3a2a8f --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/SaplingBlockToolMixin.java @@ -0,0 +1,45 @@ +/* + * 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.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldGuard; +import com.volmit.tooling.world.BlockChange.Cause; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.block.SaplingBlock; +import net.minecraft.world.level.block.state.BlockState; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** A sapling growing into a tree in a tool world changes blocks as growth. */ +@Mixin(SaplingBlock.class) +public abstract class SaplingBlockToolMixin { + @Inject(method = "advanceTree", at = @At("HEAD")) + private void iris$beginTreeGrowth(ServerLevel level, BlockPos position, BlockState state, RandomSource random, CallbackInfo info) { + ToolWorldGuard.enter(level, Cause.GROWTH, null, false); + } + + @Inject(method = "advanceTree", at = @At("RETURN")) + private void iris$endTreeGrowth(ServerLevel level, BlockPos position, BlockState state, RandomSource random, CallbackInfo info) { + ToolWorldGuard.exit(level); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerExplosionToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerExplosionToolMixin.java new file mode 100644 index 000000000..e8b4ce8c7 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerExplosionToolMixin.java @@ -0,0 +1,48 @@ +/* + * 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.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldGuard; +import com.volmit.tooling.world.BlockChange.Cause; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.ServerExplosion; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +/** An explosion in a tool world puts each block it would destroy to the tool as an explosion change. */ +@Mixin(ServerExplosion.class) +public abstract class ServerExplosionToolMixin { + @Shadow + @Final + private ServerLevel level; + + @Inject(method = "explode", at = @At("HEAD")) + private void iris$beginExplosion(CallbackInfoReturnable result) { + ToolWorldGuard.enter(level, Cause.EXPLOSION, null, false); + } + + @Inject(method = "explode", at = @At("RETURN")) + private void iris$endExplosion(CallbackInfoReturnable result) { + ToolWorldGuard.exit(level); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerGamePacketListenerToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerGamePacketListenerToolMixin.java new file mode 100644 index 000000000..33ebb5f3b --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerGamePacketListenerToolMixin.java @@ -0,0 +1,41 @@ +/* + * 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.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldHooks; +import net.minecraft.network.protocol.game.ServerboundSwingPacket; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** A swing of the arm is the left click at nothing the tool hears about, unless it is aimed at a block. */ +@Mixin(ServerGamePacketListenerImpl.class) +public abstract class ServerGamePacketListenerToolMixin { + @Shadow + public ServerPlayer player; + + @Inject(method = "handleAnimate", at = @At("HEAD")) + private void iris$tellAboutSwing(ServerboundSwingPacket packet, CallbackInfo info) { + ToolWorldHooks.leftClickAir(player, packet.getHand()); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerLevelToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerLevelToolMixin.java new file mode 100644 index 000000000..832776e24 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerLevelToolMixin.java @@ -0,0 +1,86 @@ +/* + * 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.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldGuard; +import com.volmit.tooling.world.BlockChange.Cause; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.level.material.Fluid; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +/** + * The ticks of a tool world. Each kind of tick names the cause of the block changes inside it, so the tool is asked about + * them as that cause; and the tool world keeps its weather off. + */ +@Mixin(ServerLevel.class) +public abstract class ServerLevelToolMixin { + @Inject(method = "tickFluid", at = @At("HEAD")) + private void iris$beginFluidTick(BlockPos position, Fluid fluid, CallbackInfo info) { + ToolWorldGuard.enter((ServerLevel) (Object) this, Cause.FLUID, null, false); + } + + @Inject(method = "tickFluid", at = @At("RETURN")) + private void iris$endFluidTick(BlockPos position, Fluid fluid, CallbackInfo info) { + ToolWorldGuard.exit((ServerLevel) (Object) this); + } + + @Inject(method = "tickBlock", at = @At("HEAD")) + private void iris$beginBlockTick(BlockPos position, Block block, CallbackInfo info) { + ToolWorldGuard.enter((ServerLevel) (Object) this, null, null, false); + } + + @Inject(method = "tickBlock", at = @At("RETURN")) + private void iris$endBlockTick(BlockPos position, Block block, CallbackInfo info) { + ToolWorldGuard.exit((ServerLevel) (Object) this); + } + + @Inject(method = "tickChunk", at = @At("HEAD")) + private void iris$beginRandomTick(LevelChunk chunk, int randomTickSpeed, CallbackInfo info) { + ToolWorldGuard.enter((ServerLevel) (Object) this, null, null, false); + } + + @Inject(method = "tickChunk", at = @At("RETURN")) + private void iris$endRandomTick(LevelChunk chunk, int randomTickSpeed, CallbackInfo info) { + ToolWorldGuard.exit((ServerLevel) (Object) this); + } + + @Inject(method = "tickNonPassenger", at = @At("HEAD")) + private void iris$beginEntityTick(Entity entity, CallbackInfo info) { + ToolWorldGuard.enter((ServerLevel) (Object) this, Cause.ENTITY, entity, false); + } + + @Inject(method = "tickNonPassenger", at = @At("RETURN")) + private void iris$endEntityTick(Entity entity, CallbackInfo info) { + ToolWorldGuard.exit((ServerLevel) (Object) this); + } + + @Inject(method = "advanceWeatherCycle", at = @At("HEAD"), cancellable = true) + private void iris$keepToolWorldWeatherOff(CallbackInfo info) { + if (ToolWorldGuard.isToolWorld((ServerLevel) (Object) this)) { + info.cancel(); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerPlayerGameModeToolMixin.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerPlayerGameModeToolMixin.java new file mode 100644 index 000000000..b7e3e4de7 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/mixin/ServerPlayerGameModeToolMixin.java @@ -0,0 +1,130 @@ +/* + * 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.modded.mixin; + +import art.arcane.iris.modded.toolworld.ToolWorldGuard; +import art.arcane.iris.modded.toolworld.ToolWorldHooks; +import com.volmit.tooling.world.BlockChange.Cause; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.level.ServerPlayerGameMode; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.BlockHitResult; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +/** + * What a player does with their hands in a tool world: the tool is asked about a click before it happens, and about a block + * that is broken before it breaks. What a click that the tool allows then changes is let through, since the tool allowed it. + */ +@Mixin(ServerPlayerGameMode.class) +public abstract class ServerPlayerGameModeToolMixin { + @Shadow + protected ServerLevel level; + + @Shadow + @Final + protected ServerPlayer player; + + @Inject(method = "destroyBlock", at = @At("HEAD"), cancellable = true) + private void iris$askAboutBreaking(BlockPos position, CallbackInfoReturnable result) { + if (!ToolWorldGuard.isToolWorld(level)) { + return; + } + if (!ToolWorldHooks.breakAllowed(level, player, position)) { + result.setReturnValue(false); + return; + } + ToolWorldGuard.enter(level, Cause.BREAK, player, true); + } + + @Inject(method = "destroyBlock", at = @At("RETURN")) + private void iris$endBreaking(BlockPos position, CallbackInfoReturnable result) { + ToolWorldGuard.exit(level); + } + + @Inject(method = "useItemOn", at = @At("HEAD"), cancellable = true) + private void iris$askAboutUsingOnBlock(ServerPlayer user, Level world, ItemStack stack, InteractionHand hand, BlockHitResult hit, + CallbackInfoReturnable result) { + if (!ToolWorldGuard.isToolWorld(world)) { + return; + } + if (!ToolWorldHooks.rightClickBlockAllowed(user, hand, stack, hit)) { + result.setReturnValue(InteractionResult.FAIL); + return; + } + ToolWorldGuard.enter(world, null, user, true); + } + + @Inject(method = "useItemOn", at = @At("RETURN")) + private void iris$endUsingOnBlock(ServerPlayer user, Level world, ItemStack stack, InteractionHand hand, BlockHitResult hit, + CallbackInfoReturnable result) { + ToolWorldGuard.exit(world); + } + + @Inject(method = "useItem", at = @At("HEAD"), cancellable = true) + private void iris$askAboutUsing(ServerPlayer user, Level world, ItemStack stack, InteractionHand hand, + CallbackInfoReturnable result) { + if (!ToolWorldGuard.isToolWorld(world)) { + return; + } + if (!ToolWorldHooks.rightClickAirAllowed(user, hand, stack)) { + result.setReturnValue(InteractionResult.FAIL); + return; + } + ToolWorldGuard.enter(world, null, user, true); + } + + @Inject(method = "useItem", at = @At("RETURN")) + private void iris$endUsing(ServerPlayer user, Level world, ItemStack stack, InteractionHand hand, + CallbackInfoReturnable result) { + ToolWorldGuard.exit(world); + } + + @Inject(method = "handleBlockBreakAction", at = @At("HEAD"), cancellable = true) + private void iris$askAboutLeftClick(BlockPos position, ServerboundPlayerActionPacket.Action action, Direction face, + int maxBuildHeight, int sequence, CallbackInfo info) { + if (!ToolWorldGuard.isToolWorld(level)) { + return; + } + boolean startsDigging = action == ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK; + if (startsDigging && !ToolWorldHooks.leftClickBlockAllowed(player, position, face, sequence)) { + info.cancel(); + return; + } + ToolWorldGuard.enter(level, null, player, true); + } + + @Inject(method = "handleBlockBreakAction", at = @At("RETURN")) + private void iris$endLeftClick(BlockPos position, ServerboundPlayerActionPacket.Action action, Direction face, + int maxBuildHeight, int sequence, CallbackInfo info) { + ToolWorldGuard.exit(level); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/ModdedCaptureArea.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/ModdedCaptureArea.java new file mode 100644 index 000000000..e84081305 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/ModdedCaptureArea.java @@ -0,0 +1,189 @@ +/* + * 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.modded.structure; + +import art.arcane.iris.core.tooling.ToolingSender; +import art.arcane.iris.modded.ModdedDimensionManager; +import art.arcane.iris.modded.ModdedPlatformWorld; +import art.arcane.iris.modded.ModdedStructureHooks; +import art.arcane.iris.modded.command.ModdedPackCommands; +import art.arcane.iris.modded.toolworld.ModdedToolPainting; +import art.arcane.iris.modded.toolworld.ToolBlocks; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.CapturedStructure; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.Sender; +import com.volmit.tooling.TemplateBlock; +import net.minecraft.core.BlockPos; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.block.Blocks; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Supplier; + +/** + * A scratch level that structures are generated in, one after another: an empty runtime dimension of an installed pack, so + * what is read back is the structure's own blocks. The level lives on the server thread, so each step runs there while + * the caller, a tool's worker, waits. + */ +final class ModdedCaptureArea implements PlatformStructures.CaptureArea { + private static final String DIMENSION_PREFIX = "irisworldgen:capture_"; + private static final long SCRATCH_SEED = 1337L; + private static final long STEP_TIMEOUT_SECONDS = 30L; + private static final long OPEN_TIMEOUT_SECONDS = 120L; + private static final int CELL_STRIDE = 128; + private static final int CELL_COLUMNS = 8; + + private final MinecraftServer server; + private final String dimensionId; + private final ServerLevel level; + private int nextCell; + + private ModdedCaptureArea(MinecraftServer server, String dimensionId, ServerLevel level) { + this.server = server; + this.dimensionId = dimensionId; + this.level = level; + } + + /** Opens the area; empty when the pack to make it from, or the level itself, could not be had, which the sender has been told. */ + static Optional open(MinecraftServer server, Sender sender) { + Optional pack = packFor(sender); + if (pack.isEmpty()) { + sender.error("A structure capture needs an installed pack to make its scratch world from"); + return Optional.empty(); + } + String dimensionId = DIMENSION_PREFIX + UUID.randomUUID().toString().replace("-", ""); + try { + ModdedDimensionManager.Handle handle = onServerThread(server, () -> ModdedDimensionManager.create( + server, dimensionId, pack.get(), pack.get(), SCRATCH_SEED, new ModdedToolPainting((x, z, canvas) -> { })), + OPEN_TIMEOUT_SECONDS); + return Optional.of(new ModdedCaptureArea(server, dimensionId, handle.level())); + } catch (IllegalStateException failure) { + sender.error("The scratch world for structure capture could not be made: " + failure.getMessage()); + return Optional.empty(); + } + } + + private static Optional packFor(Sender sender) { + if (sender instanceof ToolingSender tooling && tooling.world().isPresent()) { + return Optional.of(tooling.world().get().pack().name()); + } + File[] packs = ModdedPackCommands.packsRoot().listFiles(File::isDirectory); + if (packs == null) { + return Optional.empty(); + } + for (File pack : packs) { + if (new File(pack, "dimensions/" + pack.getName() + ".json").isFile()) { + return Optional.of(pack.getName()); + } + } + return Optional.empty(); + } + + @Override + public Optional capture(ResourceId structure, long seed, int maxSpan) { + int cellIndex = nextCell++; + int originX = (cellIndex % CELL_COLUMNS) * CELL_STRIDE; + int originZ = (cellIndex / CELL_COLUMNS) * CELL_STRIDE; + int anchorChunkX = (originX + CELL_STRIDE / 2) >> 4; + int anchorChunkZ = (originZ + CELL_STRIDE / 2) >> 4; + String key = structure.toString(); + try { + return Optional.ofNullable(onServerThread(server, + () -> placeAndRead(key, anchorChunkX, anchorChunkZ, seed, maxSpan), STEP_TIMEOUT_SECONDS)); + } catch (IllegalStateException failure) { + throw new IllegalStateException("Structure capture failed for '" + key + "' at chunk " + anchorChunkX + "," + + anchorChunkZ + ": " + failure.getMessage(), failure); + } + } + + private CapturedStructure placeAndRead(String key, int anchorChunkX, int anchorChunkZ, long seed, int maxSpan) { + int[] box = new ModdedStructureHooks(() -> server) + .placeStructure(new ModdedPlatformWorld(level), anchorChunkX, anchorChunkZ, key, seed, maxSpan); + if (box == null) { + return null; + } + int width = box[3] - box[0] + 1; + int height = box[4] - box[1] + 1; + int depth = box[5] - box[2] + 1; + if (width <= 0 || height <= 0 || depth <= 0) { + return null; + } + List blocks = new ArrayList<>(); + for (int dx = 0; dx < width; dx++) { + for (int dy = 0; dy < height; dy++) { + for (int dz = 0; dz < depth; dz++) { + BlockPos at = new BlockPos(box[0] + dx, box[1] + dy, box[2] + dz); + if (level.getBlockState(at).is(Blocks.AIR)) { + continue; + } + blocks.add(blockOf(at, new BlockPosition(dx, dy, dz))); + } + } + } + return blocks.isEmpty() ? null : new CapturedStructure(new BlockPosition(width, height, depth), blocks); + } + + private TemplateBlock blockOf(BlockPos at, BlockPosition relative) { + BlockState state = ToolBlocks.apiStateOf(level.getBlockState(at)); + return TemplateBlock.of(relative, state, ToolBlocks.blockEntityOf(level, at)); + } + + @Override + public void close() { + try { + onServerThread(server, () -> ModdedDimensionManager.remove(server, dimensionId, true), STEP_TIMEOUT_SECONDS); + } catch (IllegalStateException failure) { + throw new IllegalStateException("The scratch world for structure capture could not be removed: " + failure.getMessage(), failure); + } + } + + private static T onServerThread(MinecraftServer server, Supplier task, long timeoutSeconds) { + CompletableFuture result = new CompletableFuture<>(); + server.execute(() -> { + try { + result.complete(task.get()); + } catch (Throwable failure) { + result.completeExceptionally(failure); + } + }); + try { + return result.get(timeoutSeconds, TimeUnit.SECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("interrupted while waiting for the server thread", interrupted); + } catch (ExecutionException failed) { + Throwable cause = failed.getCause(); + throw new IllegalStateException(cause.getMessage() == null ? cause.getClass().getSimpleName() : cause.getMessage(), cause); + } catch (TimeoutException timedOut) { + throw new IllegalStateException("the server thread did not finish within " + timeoutSeconds + " seconds", timedOut); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/ModdedPlatformStructures.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/ModdedPlatformStructures.java new file mode 100644 index 000000000..712affa94 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/ModdedPlatformStructures.java @@ -0,0 +1,178 @@ +/* + * 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.modded.structure; + +import art.arcane.iris.modded.ModdedEngineBootstrap; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.JigsawStructureInfo; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.Sender; +import com.volmit.tooling.StructureAccessException; +import com.volmit.tooling.StructureTemplate; +import com.volmit.tooling.TemplatePool; +import net.minecraft.core.Holder; +import net.minecraft.core.Registry; +import net.minecraft.core.RegistryAccess; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.level.levelgen.structure.Structure; +import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool; +import net.minecraft.world.level.levelgen.structure.structures.JigsawStructure; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Locale; +import java.util.Optional; +import java.util.TreeSet; + +/** + * The structures of a modded server as the tools read them: templates through the server's template manager, and + * structures, structure sets and template pools through its registries. Vanilla classes, so nothing is reflected. + */ +public final class ModdedPlatformStructures implements PlatformStructures { + private static final String TEMPLATE_FOLDER = "structure"; + private static final String TEMPLATE_FILE_SUFFIX = ".nbt"; + private static final String MAX_DEPTH_FIELD = "maxDepth"; + private static final String MAX_DISTANCE_FIELD = "maxDistanceFromCenter"; + + @Override + public List templates() { + MinecraftServer server = server(); + List found = new ArrayList<>(); + for (Identifier file : server.getResourceManager() + .listResources(TEMPLATE_FOLDER, location -> location.getPath().endsWith(TEMPLATE_FILE_SUFFIX)).keySet()) { + String path = file.getPath().substring(TEMPLATE_FOLDER.length() + 1, + file.getPath().length() - TEMPLATE_FILE_SUFFIX.length()); + if (!path.isEmpty()) { + found.add(Identifier.fromNamespaceAndPath(file.getNamespace(), path)); + } + } + return idsOf(found); + } + + @Override + public Optional template(ResourceId id) { + return server().getStructureManager().get(identifierOf(id)).flatMap(TemplateReading::read); + } + + @Override + public List structures() { + return idsOf(registries().lookupOrThrow(Registries.STRUCTURE).keySet()); + } + + @Override + public List structureSets() { + return idsOf(registries().lookupOrThrow(Registries.STRUCTURE_SET).keySet()); + } + + @Override + public Optional jigsaw(ResourceId structureKey) { + RegistryAccess registries = registries(); + Structure structure = registries.lookupOrThrow(Registries.STRUCTURE).getValue(identifierOf(structureKey)); + if (!(structure instanceof JigsawStructure jigsaw)) { + return Optional.empty(); + } + Identifier startPool = poolKeyOf(registries.lookupOrThrow(Registries.TEMPLATE_POOL), jigsaw.getStartPool()) + .orElseThrow(() -> new StructureAccessException("Could not resolve the start pool key for " + structureKey, false)); + return Optional.of(jigsawInfoOf(structureKey, jigsaw, startPool, ModdedEngineBootstrap.loader().minecraftVersion())); + } + + static JigsawStructureInfo jigsawInfoOf(ResourceId structureKey, JigsawStructure jigsaw, Identifier startPool, String gameVersion) { + return new JigsawStructureInfo( + ResourceId.parse(startPool.toString()), + PrivateFields.readInt(jigsaw, MAX_DEPTH_FIELD), + PrivateFields.read(jigsaw, MAX_DISTANCE_FIELD, JigsawStructure.MaxDistance.class).horizontal(), + gameVersion, + shuffleSeedOf(structureKey)); + } + + /** The hash a key has on Bukkit, so a structure shuffles its pool the same on every platform. */ + static long shuffleSeedOf(ResourceId structureKey) { + return 31 * structureKey.namespace().hashCode() + structureKey.path().hashCode(); + } + + @Override + public Optional pool(ResourceId poolKey) { + MinecraftServer server = server(); + Registry registry = server.registryAccess().lookupOrThrow(Registries.TEMPLATE_POOL); + StructureTemplatePool pool = registry.getValue(identifierOf(poolKey)); + if (pool == null) { + return Optional.empty(); + } + Optional fallback = Optional.empty(); + Optional fallbackFailure = Optional.empty(); + try { + fallback = poolKeyOf(registry, pool.getFallback()).map(key -> ResourceId.parse(key.toString())); + } catch (RuntimeException failure) { + fallbackFailure = Optional.of(PoolReading.failureDetail(failure)); + } + List members = new ArrayList<>(); + pool.getTemplates().forEach(pair -> members.add(PoolReading.memberOf(pair, server.getStructureManager()))); + return Optional.of(new TemplatePool(members, fallback, fallbackFailure)); + } + + private static Optional poolKeyOf(Registry registry, Holder holder) { + Optional> key = holder.unwrapKey(); + if (key.isPresent()) { + return Optional.of(key.get().identifier()); + } + return Optional.ofNullable(registry.getKey(holder.value())); + } + + @Override + public boolean supportsCapture() { + return true; + } + + @Override + public Optional openCaptureArea(Sender sender) { + return ModdedCaptureArea.open(server(), sender); + } + + private static MinecraftServer server() { + MinecraftServer server = ModdedEngineBootstrap.currentServer(); + if (server == null) { + throw new StructureAccessException("No server is running", true); + } + return server; + } + + private static RegistryAccess registries() { + return server().registryAccess(); + } + + private static Identifier identifierOf(ResourceId id) { + return Identifier.fromNamespaceAndPath(id.namespace(), id.path()); + } + + private static List idsOf(Collection keys) { + TreeSet ids = new TreeSet<>(); + for (Identifier key : keys) { + try { + ids.add(ResourceId.parse(key.toString().toLowerCase(Locale.ROOT))); + } catch (IllegalArgumentException invalidKey) { + continue; + } + } + return new ArrayList<>(ids); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/PoolReading.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/PoolReading.java new file mode 100644 index 000000000..a418a7dd5 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/PoolReading.java @@ -0,0 +1,144 @@ +/* + * 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.modded.structure; + +import com.mojang.datafixers.util.Pair; +import com.volmit.geometry.BlockFace; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.StructureAccessException; +import com.volmit.tooling.TemplatePool; +import net.minecraft.core.BlockPos; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.block.JigsawBlock; +import net.minecraft.world.level.block.Rotation; +import net.minecraft.world.level.levelgen.structure.pools.ListPoolElement; +import net.minecraft.world.level.levelgen.structure.pools.SinglePoolElement; +import net.minecraft.world.level.levelgen.structure.pools.StructurePoolElement; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Optional; +import java.util.function.LongSupplier; + +/** The members of a vanilla template pool: their weights, templates and jigsaw connectors. */ +final class PoolReading { + private static final String ALIGNED_JOINT = "ALIGN"; + private static final String FINAL_STATE_NBT_KEY = "final_state"; + + private PoolReading() { + } + + /** The member of a pool for the pair the pool lists it as: its element and weight. */ + static TemplatePool.Member memberOf(Pair pair, StructureTemplateManager templates) { + StructurePoolElement element = pair.getFirst(); + if (element == null) { + return new TemplatePool.Absent(); + } + int weight = pair.getSecond() == null ? 1 : Math.max(1, pair.getSecond()); + Resolution resolution = resolve(element); + String type = resolution.physical() == null ? element.getClass().getSimpleName() : resolution.physical().getClass().getSimpleName(); + Optional template = resolution.physical() instanceof SinglePoolElement single + ? Optional.of(ResourceId.parse(single.getTemplateLocation().toString().toLowerCase(Locale.ROOT))) + : Optional.empty(); + return new TemplatePool.Element(weight, type, template, resolution.listLevels(), resolution.omittedElements(), + shuffleSeeds -> connectorsOf(element, templates, shuffleSeeds)); + } + + /** The first element that is no list, and how many lists and further elements were passed to reach it. */ + private record Resolution(StructurePoolElement physical, int listLevels, int omittedElements) { + } + + private static Resolution resolve(StructurePoolElement element) { + if (!(element instanceof ListPoolElement list)) { + return new Resolution(element, 0, 0); + } + List elements = list.getElements(); + if (elements.isEmpty()) { + return new Resolution(null, 1, 0); + } + Resolution primary = resolve(elements.getFirst()); + return new Resolution(primary.physical(), primary.listLevels() + 1, primary.omittedElements() + elements.size() - 1); + } + + private static TemplatePool.Connectors connectorsOf(StructurePoolElement element, StructureTemplateManager templates, + LongSupplier shuffleSeeds) { + try { + List blocks = element.getShuffledJigsawBlocks( + templates, BlockPos.ZERO, Rotation.NONE, RandomSource.create(shuffleSeeds.getAsLong())); + if (blocks == null) { + return new TemplatePool.Connectors(TemplatePool.Availability.NO_COLLECTION, List.of()); + } + List connectors = new ArrayList<>(); + for (StructureTemplate.JigsawBlockInfo jigsaw : blocks) { + connectors.add(connectorOf(jigsaw)); + } + return new TemplatePool.Connectors(TemplatePool.Availability.READ, connectors); + } catch (RuntimeException failure) { + throw new StructureAccessException(failureDetail(failure), true, failure); + } + } + + private static TemplatePool.Connector connectorOf(StructureTemplate.JigsawBlockInfo jigsaw) { + try { + return connectorFrom(jigsaw); + } catch (RuntimeException failure) { + return new TemplatePool.UnreadableConnector(failureDetail(failure)); + } + } + + private static TemplatePool.JigsawConnector connectorFrom(StructureTemplate.JigsawBlockInfo jigsaw) { + StructureTemplate.StructureBlockInfo info = jigsaw.info(); + BlockPos at = info.pos(); + String poolId = jigsaw.pool().identifier().toString(); + Optional finalState = info.nbt() == null ? Optional.empty() + : info.nbt().getString(FINAL_STATE_NBT_KEY).filter(state -> !state.isBlank()); + return new TemplatePool.JigsawConnector( + new BlockPosition(at.getX(), at.getY(), at.getZ()), + faceOf(JigsawBlock.getFrontFacing(info.state()).getName()), + faceOf(JigsawBlock.getTopFacing(info.state()).getName()), + poolId.isEmpty() ? Optional.empty() : Optional.of(ResourceId.parse(poolId)), + jigsaw.name().toString(), + jigsaw.target().toString(), + String.valueOf(jigsaw.jointType()).toUpperCase(Locale.ROOT).contains(ALIGNED_JOINT), + finalState, + jigsaw.selectionPriority(), + jigsaw.placementPriority()); + } + + private static BlockFace faceOf(String facing) { + return switch (facing) { + case "up" -> BlockFace.UP; + case "down" -> BlockFace.DOWN; + case "south" -> BlockFace.SOUTH; + case "east" -> BlockFace.EAST; + case "west" -> BlockFace.WEST; + default -> BlockFace.NORTH; + }; + } + + /** The message a failed read shows: the failure's message, else its class name. */ + static String failureDetail(Throwable failure) { + String message = failure.getMessage(); + return message == null || message.isBlank() ? failure.getClass().getSimpleName() : message; + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/PrivateFields.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/PrivateFields.java new file mode 100644 index 000000000..2f1689af7 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/PrivateFields.java @@ -0,0 +1,51 @@ +/* + * 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.modded.structure; + +import com.volmit.tooling.StructureAccessException; + +import java.lang.reflect.Field; +import java.util.List; + +/** + * Reads the few private fields of vanilla classes that the tools need. Minecraft ships with its own names, so the field + * names are the same on every loader; a field that is missing is a reading the platform cannot give, not a bug to hide. + */ +public final class PrivateFields { + private PrivateFields() { + } + + public static T read(Object owner, String name, Class type) { + try { + Field field = owner.getClass().getDeclaredField(name); + field.setAccessible(true); + return type.cast(field.get(owner)); + } catch (ReflectiveOperationException | RuntimeException failure) { + throw new StructureAccessException("Cannot read " + name + " of " + owner.getClass().getSimpleName() + ": " + failure, true, failure); + } + } + + public static List readList(Object owner, String name) { + return read(owner, name, List.class); + } + + public static int readInt(Object owner, String name) { + return read(owner, name, Integer.class); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/TemplateReading.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/TemplateReading.java new file mode 100644 index 000000000..fec03f5fd --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/structure/TemplateReading.java @@ -0,0 +1,99 @@ +/* + * 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.modded.structure; + +import art.arcane.iris.core.modules.BlockEntities; +import art.arcane.iris.modded.ModdedBlockState; +import art.arcane.iris.modded.ModdedIrisLog; +import art.arcane.iris.modded.ModdedTileData; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import com.volmit.tooling.TemplateBlock; +import net.minecraft.core.Vec3i; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtUtils; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** A vanilla structure template as a {@link com.volmit.tooling.StructureTemplate}: its size, and the blocks of its first palette. */ +final class TemplateReading { + private static final String FINAL_STATE_NBT_KEY = "final_state"; + private static final String PALETTES_FIELD = "palettes"; + private static final String ENTITIES_FIELD = "entityInfoList"; + + private TemplateReading() { + } + + /** The template; empty when it holds no palette. */ + static Optional read(StructureTemplate template) { + List palettes = PrivateFields.readList(template, PALETTES_FIELD); + if (palettes.isEmpty()) { + return Optional.empty(); + } + Vec3i size = template.getSize(); + List blocks = new ArrayList<>(); + for (StructureTemplate.StructureBlockInfo info : ((StructureTemplate.Palette) palettes.getFirst()).blocks()) { + blocks.add(blockOf(info)); + } + return Optional.of(new com.volmit.tooling.StructureTemplate( + new BlockPosition(size.getX(), size.getY(), size.getZ()), + palettes.size(), + PrivateFields.readList(template, ENTITIES_FIELD).size(), + blocks)); + } + + private static TemplateBlock blockOf(StructureTemplate.StructureBlockInfo info) { + BlockPosition position = new BlockPosition(info.pos().getX(), info.pos().getY(), info.pos().getZ()); + BlockState state = BlockState.parse(ModdedBlockState.serialize(info.state())); + if (info.state().is(Blocks.JIGSAW)) { + return new TemplateBlock(position, state, Optional.empty(), finalStateOf(info.nbt())); + } + if (info.state().is(Blocks.STRUCTURE_BLOCK) || info.state().is(Blocks.STRUCTURE_VOID)) { + return TemplateBlock.of(position, state, Optional.empty()); + } + return TemplateBlock.of(position, state, blockEntityOf(info)); + } + + private static Optional blockEntityOf(StructureTemplate.StructureBlockInfo info) { + CompoundTag nbt = info.nbt(); + if (nbt == null || !info.state().hasBlockEntity()) { + return Optional.empty(); + } + try { + String blockKey = BuiltInRegistries.BLOCK.getKey(info.state().getBlock()).toString(); + return Optional.of(BlockEntities.of(ModdedTileData.capture(blockKey, NbtUtils.structureToSnbt(nbt)))); + } catch (java.io.IOException | RuntimeException failure) { + ModdedIrisLog.error("Iris could not read the block entity of a template block at {}.", info.pos(), failure); + return Optional.empty(); + } + } + + private static Optional finalStateOf(CompoundTag nbt) { + if (nbt == null) { + return Optional.empty(); + } + return nbt.getString(FINAL_STATE_NBT_KEY).filter(finalState -> !finalState.isBlank()); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ChunkBuffer.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ChunkBuffer.java new file mode 100644 index 000000000..2c37de9d8 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ChunkBuffer.java @@ -0,0 +1,93 @@ +/* + * 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.modded.toolworld; + +import com.volmit.block.BlockState; +import com.volmit.object.BlockEntityData; +import com.volmit.tooling.world.ChunkCanvas; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** What one paint of a tool world chunk asked for, kept until it is written to a chunk. One buffer serves one paint on one thread. */ +final class ChunkBuffer implements ChunkCanvas { + private static final int CHUNK_SIZE = 16; + + /** A block entity asked for at chunk-local {@code x} and {@code z} and world {@code y}. */ + record Painted(int x, int y, int z, BlockEntityData data) { + } + + private final int minY; + private final int height; + private final net.minecraft.world.level.block.state.BlockState[] states; + private final List blockEntities = new ArrayList<>(); + + ChunkBuffer(int minY, int height) { + this.minY = minY; + this.height = height; + this.states = new net.minecraft.world.level.block.state.BlockState[CHUNK_SIZE * CHUNK_SIZE * height]; + } + + @Override + public int minY() { + return minY; + } + + @Override + public int maxY() { + return minY + height; + } + + @Override + public void set(int x, int y, int z, BlockState state) { + requireInside(x, y, z); + states[indexOf(x, y, z)] = ToolBlocks.minecraftStateOf(Objects.requireNonNull(state, "state")); + blockEntities.removeIf(painted -> painted.x() == x && painted.y() == y && painted.z() == z); + } + + @Override + public void set(int x, int y, int z, BlockState state, BlockEntityData data) { + Objects.requireNonNull(data, "data"); + set(x, y, z, state); + blockEntities.add(new Painted(x, y, z, data)); + } + + /** The state painted at chunk-local {@code x} and {@code z} and world {@code y}; null where nothing was painted. */ + net.minecraft.world.level.block.state.BlockState stateAt(int x, int y, int z) { + return states[indexOf(x, y, z)]; + } + + List blockEntities() { + return List.copyOf(blockEntities); + } + + private int indexOf(int x, int y, int z) { + return ((y - minY) * CHUNK_SIZE + z) * CHUNK_SIZE + x; + } + + private void requireInside(int x, int y, int z) { + if (x < 0 || x >= CHUNK_SIZE || z < 0 || z >= CHUNK_SIZE) { + throw new IllegalArgumentException("Chunk-local x and z are 0 to 15: " + x + ", " + z); + } + if (y < minY || y >= maxY()) { + throw new IllegalArgumentException("Y " + y + " is outside the world, " + minY + " up to " + maxY()); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolPainting.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolPainting.java new file mode 100644 index 000000000..a553ab990 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolPainting.java @@ -0,0 +1,178 @@ +/* + * 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.modded.toolworld; + +import art.arcane.iris.modded.ModdedIrisLog; +import com.volmit.tooling.world.ChunkPainter; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.EntityBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.ChunkAccess; +import net.minecraft.world.level.chunk.LevelChunk; +import net.minecraft.world.level.chunk.LevelChunkSection; +import net.minecraft.world.level.levelgen.Heightmap; + +import java.util.EnumSet; +import java.util.Objects; +import java.util.Set; + +/** + * The chunks of a tool world: whatever the tool's painter paints, and nothing else. The chunk generator of the world asks + * it to paint every chunk it generates, and the world asks it to paint again over a chunk that is live. + */ +public final class ModdedToolPainting { + private static final int CHUNK_SIZE = 16; + private static final int SECTION_SIZE = 16; + private static final int REPAINT_FLAGS = Block.UPDATE_CLIENTS | Block.UPDATE_KNOWN_SHAPE | Block.UPDATE_SUPPRESS_DROPS; + private static final Set PRIMED_HEIGHTMAPS = EnumSet.of( + Heightmap.Types.WORLD_SURFACE_WG, + Heightmap.Types.OCEAN_FLOOR_WG, + Heightmap.Types.MOTION_BLOCKING, + Heightmap.Types.MOTION_BLOCKING_NO_LEAVES); + + private final ChunkPainter painter; + + public ModdedToolPainting(ChunkPainter painter) { + this.painter = Objects.requireNonNull(painter, "painter"); + } + + /** Paints {@code chunk}, which the generator is filling and no player can see yet. */ + public ChunkAccess paint(ChunkAccess chunk, ServerLevel level) { + ChunkPos position = chunk.getPos(); + ChunkBuffer buffer = paintBuffer(position.x(), position.z(), chunk.getMinY(), chunk.getHeight()); + writeSections(chunk, buffer); + writeBlockEntities(chunk, level, buffer); + Heightmap.primeHeightmaps(chunk, PRIMED_HEIGHTMAPS); + return chunk; + } + + /** Paints again over a live chunk: changes what differs from the paint and sends it to the players watching. */ + void repaint(ServerLevel level, LevelChunk chunk) { + ChunkPos position = chunk.getPos(); + ChunkBuffer buffer = paintBuffer(position.x(), position.z(), chunk.getMinY(), chunk.getHeight()); + ToolWorldGuard.hostWrite(() -> { + rewriteDifferences(level, chunk, buffer); + rewriteBlockEntities(level, position, buffer); + }); + } + + private ChunkBuffer paintBuffer(int chunkX, int chunkZ, int minY, int height) { + ChunkBuffer buffer = new ChunkBuffer(minY, height); + try { + painter.paint(chunkX, chunkZ, buffer); + } catch (RuntimeException failure) { + ModdedIrisLog.error("A tool world painter failed at chunk {},{}.", chunkX, chunkZ, failure); + } + return buffer; + } + + private void writeSections(ChunkAccess chunk, ChunkBuffer buffer) { + int minY = buffer.minY(); + for (int y = minY; y < buffer.maxY(); ) { + int sectionIndex = chunk.getSectionIndex(y); + LevelChunkSection section = chunk.getSection(sectionIndex); + int sectionEnd = Math.min(minY + (sectionIndex + 1) * SECTION_SIZE, buffer.maxY()); + section.acquire(); + try { + writeSection(section, buffer, y, sectionEnd); + } finally { + section.release(); + } + y = sectionEnd; + } + } + + private void writeSection(LevelChunkSection section, ChunkBuffer buffer, int fromY, int toY) { + for (int y = fromY; y < toY; y++) { + for (int z = 0; z < CHUNK_SIZE; z++) { + for (int x = 0; x < CHUNK_SIZE; x++) { + BlockState state = buffer.stateAt(x, y, z); + if (state != null) { + section.setBlockState(x, y & (SECTION_SIZE - 1), z, state, false); + } + } + } + } + } + + private void writeBlockEntities(ChunkAccess chunk, ServerLevel level, ChunkBuffer buffer) { + ChunkPos position = chunk.getPos(); + for (int y = buffer.minY(); y < buffer.maxY(); y++) { + for (int z = 0; z < CHUNK_SIZE; z++) { + for (int x = 0; x < CHUNK_SIZE; x++) { + BlockState state = buffer.stateAt(x, y, z); + if (state != null && state.hasBlockEntity()) { + createDefaultBlockEntity(chunk, new BlockPos(position.getMinBlockX() + x, y, position.getMinBlockZ() + z), state); + } + } + } + } + for (ChunkBuffer.Painted painted : buffer.blockEntities()) { + BlockPos at = new BlockPos(position.getMinBlockX() + painted.x(), painted.y(), position.getMinBlockZ() + painted.z()); + try { + ToolBlocks.applyPaintedBlockEntity(chunk, level, at, buffer.stateAt(painted.x(), painted.y(), painted.z()), painted.data()); + } catch (RuntimeException failure) { + ModdedIrisLog.error("A tool world could not write a block entity at {}.", at, failure); + } + } + } + + private static void createDefaultBlockEntity(ChunkAccess chunk, BlockPos at, BlockState state) { + if (!(state.getBlock() instanceof EntityBlock entityBlock)) { + return; + } + BlockEntity blockEntity = entityBlock.newBlockEntity(at, state); + if (blockEntity != null) { + chunk.setBlockEntity(blockEntity); + } + } + + private void rewriteDifferences(ServerLevel level, LevelChunk chunk, ChunkBuffer buffer) { + ChunkPos position = chunk.getPos(); + BlockState air = Blocks.AIR.defaultBlockState(); + for (int y = buffer.minY(); y < buffer.maxY(); y++) { + for (int z = 0; z < CHUNK_SIZE; z++) { + for (int x = 0; x < CHUNK_SIZE; x++) { + BlockPos at = new BlockPos(position.getMinBlockX() + x, y, position.getMinBlockZ() + z); + BlockState painted = buffer.stateAt(x, y, z); + BlockState wanted = painted == null ? air : painted; + if (chunk.getBlockState(at) != wanted) { + level.setBlock(at, wanted, REPAINT_FLAGS); + } + } + } + } + } + + private void rewriteBlockEntities(ServerLevel level, ChunkPos position, ChunkBuffer buffer) { + for (ChunkBuffer.Painted painted : buffer.blockEntities()) { + BlockPos at = new BlockPos(position.getMinBlockX() + painted.x(), painted.y(), position.getMinBlockZ() + painted.z()); + try { + ToolBlocks.applyBlockEntity(level, at, painted.data()); + } catch (RuntimeException failure) { + ModdedIrisLog.error("A tool world could not write a block entity at {}.", at, failure); + } + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolPlayer.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolPlayer.java new file mode 100644 index 000000000..1403a7248 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolPlayer.java @@ -0,0 +1,289 @@ +/* + * 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.modded.toolworld; + +import art.arcane.iris.modded.ModdedDimensionManager; +import art.arcane.iris.modded.ModdedEngineBootstrap; +import art.arcane.iris.modded.command.ModdedToolingSender; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.Sender; +import com.volmit.tooling.world.Particle; +import com.volmit.tooling.world.ToolItem; +import com.volmit.tooling.world.ToolMenu; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolText; +import com.volmit.tooling.world.ToolWorld; +import net.minecraft.core.Holder; +import net.minecraft.core.particles.DustParticleOptions; +import net.minecraft.network.protocol.game.ClientboundSoundPacket; +import net.minecraft.resources.Identifier; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.sounds.SoundSource; +import net.minecraft.world.level.GameType; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; + +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +/** One online player as a tool sees them. It finds the player again by id each time, so it outlives a respawn. */ +final class ModdedToolPlayer implements ToolPlayer { + private static final String DEFAULT_SIDEBAR_TITLE = "Iris"; + + private final UUID id; + private final String name; + private final ToolPlayers players; + private final ToolMenus menus; + + ModdedToolPlayer(UUID id, String name, ToolPlayers players, ToolMenus menus) { + this.id = id; + this.name = name; + this.players = players; + this.menus = menus; + } + + private static MinecraftServer server() { + MinecraftServer server = ModdedEngineBootstrap.currentServer(); + if (server == null) { + throw new IllegalStateException("No server is running"); + } + return server; + } + + ServerPlayer player() { + ServerPlayer online = server().getPlayerList().getPlayer(id); + if (online == null) { + throw new IllegalStateException("Player " + name + " is not online"); + } + return online; + } + + private Optional onlinePlayer() { + return Optional.ofNullable(server().getPlayerList().getPlayer(id)); + } + + @Override + public UUID id() { + return id; + } + + @Override + public String name() { + return name; + } + + @Override + public Sender sender() { + return new ModdedToolingSender(player().createCommandSourceStack()); + } + + @Override + public Optional world() { + return onlinePlayer() + .filter(online -> online.level() instanceof ServerLevel) + .flatMap(online -> ToolWorldRegistry.INSTANCE.forLevel((ServerLevel) online.level())) + .map(world -> world); + } + + @Override + public BlockPosition position() { + return ToolBlocks.positionOf(player().blockPosition()); + } + + @Override + public float yaw() { + return player().getYRot(); + } + + @Override + public float pitch() { + return player().getXRot(); + } + + @Override + public boolean sneaking() { + return player().isShiftKeyDown(); + } + + @Override + public Optional targetBlock(int maxDistance) { + HitResult hit = player().pick(maxDistance, 1.0F, false); + if (hit.getType() != HitResult.Type.BLOCK) { + return Optional.empty(); + } + return Optional.of(ToolBlocks.positionOf(((BlockHitResult) hit).getBlockPos())); + } + + @Override + public void run(Runnable task) { + server().execute(task); + } + + @Override + public CompletableFuture teleport(ToolWorld world, double x, double y, double z, float yaw, float pitch) { + if (!(world instanceof ModdedToolWorld target)) { + return CompletableFuture.failedFuture(new IllegalArgumentException("Not a tool world of this platform: " + world)); + } + CompletableFuture arrived = new CompletableFuture<>(); + server().execute(() -> { + Optional online = onlinePlayer(); + if (online.isEmpty()) { + arrived.complete(false); + return; + } + ModdedDimensionManager.teleportAsync(online.get(), server(), target.level(), x, y, z) + .whenComplete((success, failure) -> server().execute(() -> faceAfterArrival(arrived, success, failure, target, yaw, pitch))); + }); + return arrived; + } + + private void faceAfterArrival(CompletableFuture arrived, Boolean success, Throwable failure, + ModdedToolWorld target, float yaw, float pitch) { + if (failure != null) { + arrived.completeExceptionally(failure); + return; + } + Optional online = onlinePlayer(); + if (Boolean.TRUE.equals(success) && online.isPresent()) { + ServerPlayer arrivedPlayer = online.get(); + arrivedPlayer.teleportTo(target.level(), arrivedPlayer.getX(), arrivedPlayer.getY(), arrivedPlayer.getZ(), + Set.of(), yaw, pitch, false); + } + arrived.complete(Boolean.TRUE.equals(success)); + } + + @Override + public void creative(boolean on) { + server().execute(() -> onlinePlayer().ifPresent(online -> { + if (on) { + players.rememberModeBeforeCreative(online); + online.setGameMode(GameType.CREATIVE); + return; + } + players.restoreGameMode(online); + })); + } + + @Override + public void message(ToolText text) { + server().execute(() -> onlinePlayer().ifPresent(online -> online.sendSystemMessage(ToolTexts.component(text)))); + } + + @Override + public void actionBar(ToolText text) { + server().execute(() -> onlinePlayer().ifPresent(online -> online.sendSystemMessage(ToolTexts.component(text), true))); + } + + @Override + public void sound(ResourceId sound, float volume, float pitch) { + server().execute(() -> onlinePlayer().ifPresent(online -> { + Holder event = Holder.direct(SoundEvent.createVariableRangeEvent(Identifier.parse(sound.toString()))); + online.connection.send(new ClientboundSoundPacket(event, SoundSource.MASTER, online.getX(), online.getY(), online.getZ(), + volume, pitch, online.level().getRandom().nextLong())); + })); + } + + @Override + public void sidebar(ToolText title, List lines) { + ToolText shown = title.isEmpty() ? ToolText.plain(DEFAULT_SIDEBAR_TITLE) : title; + server().execute(() -> onlinePlayer().ifPresent(online -> players.sidebars().show(online, shown, lines))); + } + + @Override + public void hideSidebar() { + server().execute(() -> onlinePlayer().ifPresent(online -> players.sidebars().hide(online))); + } + + @Override + public void particles(List dust) { + List specks = List.copyOf(dust); + server().execute(() -> onlinePlayer().ifPresent(online -> specks.forEach(speck -> showDust(online, speck)))); + } + + private static void showDust(ServerPlayer online, Particle speck) { + if (online.level() instanceof ServerLevel level) { + level.sendParticles(online, new DustParticleOptions(speck.rgb(), speck.size()), true, true, + speck.x(), speck.y(), speck.z(), 1, 0.0D, 0.0D, 0.0D, 0.0D); + } + } + + @Override + public boolean give(ToolItem item) { + var stack = ToolItems.create(item); + if (server().isSameThread()) { + return player().getInventory().add(stack); + } + server().execute(() -> onlinePlayer().ifPresent(online -> online.getInventory().add(stack))); + return true; + } + + @Override + public Optional held() { + return ToolItems.read(player().getInventory().getSelectedItem()); + } + + @Override + public void openMenu(ToolMenu menu) { + server().execute(() -> onlinePlayer().ifPresent(online -> menus.open(online, this, menu))); + } + + @Override + public void closeMenu() { + server().execute(() -> onlinePlayer().ifPresent(menus::close)); + } + + /** + * Sends the player to where they were before they entered a tool world, or to the spawn of the main world when that is + * not known any more, and gives back the game mode they had. Completes with whether they arrived. + */ + CompletableFuture returnToOrigin() { + CompletableFuture returned = new CompletableFuture<>(); + server().execute(() -> { + Optional online = onlinePlayer(); + if (online.isEmpty()) { + returned.complete(false); + return; + } + ServerPlayer leaving = online.get(); + menus.close(leaving); + players.sidebars().hide(leaving); + players.restoreGameMode(leaving); + players.destinationAfterToolWorld(leaving).whenComplete((success, failure) -> { + if (failure != null) { + returned.completeExceptionally(failure); + return; + } + returned.complete(Boolean.TRUE.equals(success)); + }); + }); + return returned; + } + + @Override + public String toString() { + return "tool player " + name; + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolWorld.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolWorld.java new file mode 100644 index 000000000..f90866159 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolWorld.java @@ -0,0 +1,322 @@ +/* + * 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.modded.toolworld; + +import art.arcane.iris.modded.ModdedDimensionManager; +import art.arcane.iris.modded.ModdedEngineBootstrap; +import art.arcane.iris.modded.ModdedIrisLog; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.geometry.ChunkPos; +import com.volmit.object.BlockEntityData; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolWorld; +import com.volmit.tooling.world.ToolWorldListener; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.chunk.LevelChunk; + +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; + +/** + * One tool world on a modded server: a runtime dimension of the pack whose chunks come from the tool's painter. It exists, + * registered, from before the level is made until the level is gone; {@link #bind} gives it the level once it exists. + * The server thread owns everything on a modded server, so a position is owned by whoever is on it. + */ +final class ModdedToolWorld implements ToolWorld { + private static final int SET_BLOCK_FLAGS = Block.UPDATE_CLIENTS | Block.UPDATE_KNOWN_SHAPE; + + private final String packName; + private final String name; + private final String dimensionId; + private final ToolWorldListener listener; + private final ModdedToolPainting painting; + private final ToolPlayers players; + private final AtomicBoolean closing = new AtomicBoolean(); + private final AtomicBoolean gone = new AtomicBoolean(); + private final CompletableFuture closed = new CompletableFuture<>(); + private volatile ServerLevel level; + + ModdedToolWorld(String packName, String name, String dimensionId, ToolWorldListener listener, + ModdedToolPainting painting, ToolPlayers players) { + this.packName = packName; + this.name = name; + this.dimensionId = dimensionId; + this.listener = listener; + this.painting = painting; + this.players = players; + } + + String packName() { + return packName; + } + + String dimensionId() { + return dimensionId; + } + + ModdedToolPainting painting() { + return painting; + } + + void bind(ServerLevel created) { + level = Objects.requireNonNull(created, "created"); + } + + boolean isBound() { + return level != null; + } + + ServerLevel level() { + ServerLevel bound = level; + if (bound == null) { + throw new IllegalStateException("The tool world " + name + " is not created yet"); + } + return bound; + } + + private static MinecraftServer server() { + MinecraftServer server = ModdedEngineBootstrap.currentServer(); + if (server == null) { + throw new IllegalStateException("No server is running"); + } + return server; + } + + @Override + public String name() { + return name; + } + + @Override + public int minY() { + return level().getMinY(); + } + + @Override + public int maxY() { + return level().getMinY() + level().getHeight(); + } + + @Override + public List players() { + return level().players().stream().map(players::of).toList(); + } + + @Override + public boolean owns(BlockPosition at) { + return server().isSameThread(); + } + + @Override + public void run(BlockPosition at, Runnable task) { + server().execute(() -> runGuarded(task, "task at " + at)); + } + + @Override + public CompletableFuture call(BlockPosition at, Supplier task) { + CompletableFuture result = new CompletableFuture<>(); + server().execute(() -> { + try { + result.complete(task.get()); + } catch (Throwable failure) { + result.completeExceptionally(failure); + } + }); + return result; + } + + @Override + public BlockState block(BlockPosition at) { + requireOwned(at); + return ToolBlocks.apiStateOf(level().getBlockState(ToolBlocks.blockPosOf(at))); + } + + @Override + public Optional blockEntity(BlockPosition at) { + requireOwned(at); + return ToolBlocks.blockEntityOf(level(), ToolBlocks.blockPosOf(at)); + } + + @Override + public void setBlock(BlockPosition at, BlockState state, Optional data) { + requireOwned(at); + ServerLevel target = level(); + ToolWorldGuard.hostWrite(() -> { + target.setBlock(ToolBlocks.blockPosOf(at), ToolBlocks.minecraftStateOf(state), SET_BLOCK_FLAGS); + data.ifPresent(entity -> ToolBlocks.applyBlockEntity(target, ToolBlocks.blockPosOf(at), entity)); + }); + } + + @Override + public boolean loaded(ChunkPos chunk) { + return level().getChunkSource().hasChunk(chunk.x(), chunk.z()); + } + + @Override + public CompletableFuture repaint(Collection chunks) { + if (isClosed()) { + return CompletableFuture.failedFuture(new IllegalStateException("Tool world " + name + " is closed")); + } + List distinct = chunks.stream().distinct().toList(); + CompletableFuture repainted = new CompletableFuture<>(); + server().execute(() -> { + try { + ServerLevel target = level(); + for (ChunkPos position : distinct) { + LevelChunk chunk = target.getChunk(position.x(), position.z()); + painting.repaint(target, chunk); + } + repainted.complete(null); + } catch (Throwable failure) { + repainted.completeExceptionally(failure); + } + }); + return repainted; + } + + @Override + public CompletableFuture close() { + if (!closing.compareAndSet(false, true)) { + return closed; + } + server().execute(this::sendPlayersBackThenRemove); + return closed; + } + + private void sendPlayersBackThenRemove() { + List> departures = level().players().stream() + .map(player -> players.playerOf(player).returnToOrigin()) + .toList(); + CompletableFuture.allOf(departures.toArray(CompletableFuture[]::new)) + .whenComplete((ignored, failure) -> server().execute(this::removeLevel)); + } + + private void removeLevel() { + try { + ModdedDimensionManager.remove(server(), dimensionId, true); + } catch (Throwable failure) { + unloaded(); + closed.completeExceptionally(failure); + return; + } + unloaded(); + closed.complete(null); + } + + /** Removes the level at once on the server thread, for a server that is stopping; players leave with it. */ + void shutDownNow(MinecraftServer server) { + closing.set(true); + try { + if (isBound()) { + ModdedDimensionManager.remove(server, dimensionId, true); + } + } catch (Throwable failure) { + ModdedIrisLog.error("Tool world {} could not be removed when Iris stopped.", name, failure); + } + unloaded(); + closed.complete(null); + } + + /** Minecraft unloaded the level, whoever asked: it is gone for the tool and for the host. */ + void unloaded() { + if (!gone.compareAndSet(false, true)) { + return; + } + ToolWorldRegistry.INSTANCE.unregister(this); + tell(ToolWorldListener::closed); + } + + /** Called by the opener when creating the level failed: nothing of it is left to unload. */ + void abandon() { + ToolWorldRegistry.INSTANCE.unregister(this); + } + + Optional closeRefusal() { + try { + return listener.closeRefusal(); + } catch (Throwable failure) { + ModdedIrisLog.error("The listener of tool world {} failed.", name, failure); + return Optional.empty(); + } + } + + CompletableFuture prepareReplacement(Optional requestedBy) { + try { + return listener.closing(requestedBy); + } catch (Throwable failure) { + ModdedIrisLog.error("The listener of tool world {} failed.", name, failure); + return CompletableFuture.completedFuture(null); + } + } + + /** The tool's listener asked, with {@code fallback} as the answer when it throws. Runs on the caller's thread. */ + boolean ask(Function question, boolean fallback) { + try { + return question.apply(listener); + } catch (Throwable failure) { + ModdedIrisLog.error("The listener of tool world {} failed.", name, failure); + return fallback; + } + } + + /** Tells the listener something. Runs on the caller's thread. */ + void tell(Consumer news) { + ask(toolListener -> { + news.accept(toolListener); + return true; + }, true); + } + + boolean isClosed() { + return closing.get() || gone.get(); + } + + private void requireOwned(BlockPosition at) { + if (isClosed()) { + throw new IllegalStateException("Tool world " + name + " is closed"); + } + if (!owns(at)) { + throw new IllegalStateException("The calling thread does not own " + at + " in tool world " + name); + } + level(); + } + + private void runGuarded(Runnable task, String what) { + try { + task.run(); + } catch (Throwable failure) { + ModdedIrisLog.error("A task of tool world {} failed: {}.", name, what, failure); + } + } + + @Override + public String toString() { + return "tool world " + name; + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolWorldService.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolWorldService.java new file mode 100644 index 000000000..7b165d75d --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolWorldService.java @@ -0,0 +1,128 @@ +/* + * 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.modded.toolworld; + +import art.arcane.iris.core.tooling.ToolWorldsHost; +import art.arcane.iris.modded.ModdedIrisLog; +import art.arcane.iris.modded.service.ModdedTickableService; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolWorlds; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; + +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/** + * Tool worlds on a modded server: the platform side of {@code com.volmit.tooling.world}. It hands each pack its + * {@link ToolWorlds} through {@link ToolWorldsHost}, looks at the players once a tick for what the tools hear about them, and + * closes every tool world when it stops. What vanilla code paths tell a tool world arrives through the mixins, which reach + * {@link ToolWorldGuard} and the static hooks here. + */ +public final class ModdedToolWorldService implements ModdedTickableService, ToolWorldsHost { + private static final long CLOSING_WAIT_SECONDS = 30L; + private static final ToolPlayers PLAYERS = new ToolPlayers(); + + static ToolPlayers players() { + return PLAYERS; + } + + /** The tool player for {@code player}, the same object for as long as the player is online. */ + public static ToolPlayer toolPlayerOf(ServerPlayer player) { + return PLAYERS.of(player); + } + + @Override + public ToolWorlds worldsOf(String packName) { + return new ModdedToolWorlds(packName, PLAYERS); + } + + @Override + public void onEnable() { + ToolWorldGuard.resetScopes(); + } + + @Override + public void onServerTick(MinecraftServer server) { + ToolWorldGuard.resetScopes(); + PLAYERS.track(server); + } + + @Override + public void onDisable() { + List open = ToolWorldRegistry.INSTANCE.all(); + awaitClosing(open); + MinecraftServer server = art.arcane.iris.modded.ModdedEngineBootstrap.currentServer(); + open.forEach(world -> world.shutDownNow(server)); + PLAYERS.clear(); + ToolWorldRegistry.INSTANCE.clear(); + } + + /** Lets every tool hear that its world is closing, as a replacement does, so it can save what it holds before the world is gone. */ + private static void awaitClosing(List open) { + CompletableFuture[] closing = open.stream() + .map(world -> world.prepareReplacement(Optional.empty())) + .toArray(CompletableFuture[]::new); + try { + CompletableFuture.allOf(closing).get(CLOSING_WAIT_SECONDS, TimeUnit.SECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } catch (ExecutionException | TimeoutException notReady) { + ModdedIrisLog.error("A tool world was not ready to close when Iris stopped.", notReady); + } + } + + /** Why a studio change must not close the tool worlds now; the first refusal of a tool wins. */ + public static Optional studioChangeRefusal() { + return ToolWorldRegistry.INSTANCE.all().stream() + .map(ModdedToolWorld::closeRefusal) + .flatMap(Optional::stream) + .findFirst(); + } + + /** Closes every tool world for a studio that replaces them or is closed: each tool finishes its work first. */ + public static CompletableFuture closeForStudioChange(Optional by) { + Optional requestedBy = by.map(PLAYERS::of); + List open = ToolWorldRegistry.INSTANCE.all(); + CompletableFuture[] closing = open.stream() + .map(world -> world.prepareReplacement(requestedBy)) + .toArray(CompletableFuture[]::new); + return CompletableFuture.allOf(closing).thenCompose(ignored -> CompletableFuture.allOf( + open.stream().map(ModdedToolWorld::close).toArray(CompletableFuture[]::new))); + } + + /** Minecraft unloaded {@code level}: if it was a tool world, it is gone for the tool. */ + public static void levelUnloaded(ServerLevel level) { + if (ToolWorldRegistry.INSTANCE.hasWorlds()) { + ToolWorldRegistry.INSTANCE.forLevel(level).ifPresent(ModdedToolWorld::unloaded); + } + } + + /** A chunk of {@code level} is live: tells the tool when the level is a tool world. */ + public static void chunkLoaded(ServerLevel level, int chunkX, int chunkZ) { + if (ToolWorldRegistry.INSTANCE.hasWorlds()) { + ToolWorldRegistry.INSTANCE.forLevel(level).ifPresent(world -> world.tell(listener -> listener.chunkLoaded(chunkX, chunkZ))); + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolWorlds.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolWorlds.java new file mode 100644 index 000000000..040d4edba --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ModdedToolWorlds.java @@ -0,0 +1,98 @@ +/* + * 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.modded.toolworld; + +import art.arcane.iris.modded.ModdedDimensionManager; +import art.arcane.iris.modded.ModdedEngineBootstrap; +import art.arcane.iris.modded.command.ModdedPackCommands; +import com.volmit.tooling.world.ToolWorld; +import com.volmit.tooling.world.ToolWorldDenied; +import com.volmit.tooling.world.ToolWorldSpec; +import com.volmit.tooling.world.ToolWorlds; +import net.minecraft.server.MinecraftServer; + +import java.io.File; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +/** + * The tool worlds of one pack on a modded server. A tool world is made through the runtime dimensions the studio uses, with + * the tool's painter installed before the level exists, so that even the first chunk is the tool's. + */ +final class ModdedToolWorlds implements ToolWorlds { + static final String DIMENSION_NAMESPACE = "irisworldgen"; + private static final String DIMENSION_PREFIX = "tool_"; + private static final long TOOL_WORLD_SEED = 1337L; + + private final String packName; + private final ToolPlayers players; + + ModdedToolWorlds(String packName, ToolPlayers players) { + this.packName = packName; + this.players = players; + } + + @Override + public CompletableFuture open(ToolWorldSpec spec) { + MinecraftServer server = ModdedEngineBootstrap.currentServer(); + if (server == null) { + return CompletableFuture.failedFuture(new IllegalStateException("No server is running")); + } + Optional denial = packDenial(); + if (denial.isPresent()) { + return CompletableFuture.failedFuture(new ToolWorldDenied(denial.get())); + } + String dimensionId = DIMENSION_NAMESPACE + ":" + DIMENSION_PREFIX + UUID.randomUUID().toString().replace("-", ""); + ModdedToolWorld world = new ModdedToolWorld(packName, spec.name(), dimensionId, spec.listener(), + new ModdedToolPainting(spec.painter()), players); + if (!ToolWorldRegistry.INSTANCE.register(world)) { + return CompletableFuture.failedFuture(new IllegalStateException( + "A tool world called " + spec.name() + " is open already in pack " + packName)); + } + CompletableFuture opened = new CompletableFuture<>(); + server.execute(() -> create(server, world, opened)); + return opened; + } + + private void create(MinecraftServer server, ModdedToolWorld world, CompletableFuture opened) { + try { + ModdedDimensionManager.Handle handle = ModdedDimensionManager.create( + server, world.dimensionId(), packName, packName, TOOL_WORLD_SEED, world.painting()); + world.bind(handle.level()); + opened.complete(world); + } catch (Throwable failure) { + world.abandon(); + opened.completeExceptionally(failure); + } + } + + private Optional packDenial() { + File dimension = new File(new File(ModdedPackCommands.packsRoot(), packName), "dimensions/" + packName + ".json"); + if (!dimension.isFile()) { + return Optional.of("Pack " + packName + " is not installed with dimensions/" + packName + ".json"); + } + return Optional.empty(); + } + + @Override + public Optional find(String name) { + return ToolWorldRegistry.INSTANCE.forName(packName, name).filter(ModdedToolWorld::isBound).map(world -> world); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolBlocks.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolBlocks.java new file mode 100644 index 000000000..f48bce566 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolBlocks.java @@ -0,0 +1,160 @@ +/* + * 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.modded.toolworld; + +import art.arcane.iris.core.modules.BlockEntities; +import art.arcane.iris.core.modules.PlatformBlockStates; +import art.arcane.iris.engine.object.prefab.TileData; +import art.arcane.iris.modded.ModdedBlockState; +import art.arcane.iris.modded.ModdedTileData; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockFace; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtUtils; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.EntityBlock; +import net.minecraft.world.level.block.entity.BlockEntity; + +import java.util.Optional; + +/** Blocks, positions and block entities between the tool world api and Minecraft. */ +public final class ToolBlocks { + private static final int SILENT_BLOCK_FLAGS = net.minecraft.world.level.block.Block.UPDATE_CLIENTS + | net.minecraft.world.level.block.Block.UPDATE_KNOWN_SHAPE + | net.minecraft.world.level.block.Block.UPDATE_SUPPRESS_DROPS; + private static final PlatformBlockStates PLATFORM_STATES = new PlatformBlockStates(ToolBlocks::platformStateOf); + + private ToolBlocks() { + } + + static BlockPosition positionOf(BlockPos position) { + return new BlockPosition(position.getX(), position.getY(), position.getZ()); + } + + static BlockPos blockPosOf(BlockPosition position) { + return new BlockPos(position.x(), position.y(), position.z()); + } + + /** The complete state of {@code state}, with every property. */ + public static BlockState apiStateOf(net.minecraft.world.level.block.state.BlockState state) { + return BlockState.parse(ModdedBlockState.serialize(state)); + } + + /** + * The platform's state for {@code state}. + * + * @throws IllegalArgumentException when the platform has no such block or property + */ + static net.minecraft.world.level.block.state.BlockState minecraftStateOf(BlockState state) { + return (net.minecraft.world.level.block.state.BlockState) PLATFORM_STATES.toPlatform(state).nativeHandle(); + } + + private static PlatformBlockState platformStateOf(String key) { + PlatformBlockState state = B.getStateOrNull(key, false); + if (state == null) { + throw new IllegalArgumentException("The platform has no block state " + key); + } + return state; + } + + static Optional faceOf(Direction direction) { + return direction == null ? Optional.empty() : Optional.of(BlockFace.valueOf(direction.name())); + } + + /** The block entity at {@code position}, in Iris's tile format; empty for a block without one. */ + public static Optional blockEntityOf(ServerLevel level, BlockPos position) { + BlockEntity blockEntity = level.getBlockEntity(position); + if (blockEntity == null) { + return Optional.empty(); + } + try { + CompoundTag tag = blockEntity.saveWithFullMetadata(level.registryAccess()); + String blockKey = BuiltInRegistries.BLOCK.getKey(blockEntity.getBlockState().getBlock()).toString(); + TileData tile = ModdedTileData.capture(blockKey, NbtUtils.structureToSnbt(tag)); + return Optional.of(BlockEntities.of(tile)); + } catch (java.io.IOException failure) { + throw new java.io.UncheckedIOException("Cannot read the block entity at " + position, failure); + } + } + + /** + * Writes {@code data} into the block entity at {@code position}, which holds the block it was made for already; makes + * the block entity when the block has none yet. + * + * @throws IllegalArgumentException when the block cannot take it, or the data is not in the format Iris stores + */ + static void applyBlockEntity(Level level, BlockPos position, BlockEntityData data) { + ModdedTileData tile = tileOf(data); + net.minecraft.world.level.block.state.BlockState state = level.getBlockState(position); + net.minecraft.world.level.block.state.BlockState adjusted = tile.adjustBlockState(state); + if (adjusted != state) { + level.setBlock(position, adjusted, SILENT_BLOCK_FLAGS); + state = adjusted; + } + BlockEntity blockEntity = level.getBlockEntity(position); + if (blockEntity == null && state.getBlock() instanceof EntityBlock entityBlock) { + blockEntity = entityBlock.newBlockEntity(position, state); + } + if (blockEntity == null || !tile.isApplicable(state, blockEntity)) { + throw new IllegalArgumentException("The block " + state + " at " + position + + " cannot take block entity data of " + tile.getMaterialKey()); + } + level.setBlockEntity(blockEntity); + applyTile(tile, blockEntity, level); + } + + /** Makes the block entity of a block painted into a chunk that is not live yet. */ + static void applyPaintedBlockEntity(net.minecraft.world.level.chunk.ChunkAccess chunk, ServerLevel level, BlockPos position, + net.minecraft.world.level.block.state.BlockState state, BlockEntityData data) { + ModdedTileData tile = tileOf(data); + if (!(state.getBlock() instanceof EntityBlock entityBlock)) { + throw new IllegalArgumentException("The block " + state + " has no block entity for " + tile.getMaterialKey()); + } + BlockEntity blockEntity = entityBlock.newBlockEntity(position, state); + if (blockEntity == null || !tile.isApplicable(state, blockEntity)) { + throw new IllegalArgumentException("The block " + state + " cannot take block entity data of " + tile.getMaterialKey()); + } + chunk.setBlockEntity(blockEntity); + applyTile(tile, blockEntity, level); + } + + private static void applyTile(ModdedTileData tile, BlockEntity blockEntity, Level level) { + try { + tile.apply(blockEntity, (ServerLevel) level); + } catch (Exception failure) { + throw new IllegalArgumentException("The block entity data of " + tile.getMaterialKey() + " was rejected", failure); + } + } + + private static ModdedTileData tileOf(BlockEntityData data) { + TileData tile = BlockEntities.tileOf(data); + if (tile instanceof ModdedTileData moddedTile) { + return moddedTile; + } + throw new IllegalArgumentException("Not block entity data of this platform: " + tile.getMaterialKey()); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolItems.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolItems.java new file mode 100644 index 000000000..09e9d7781 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolItems.java @@ -0,0 +1,100 @@ +/* + * 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.modded.toolworld; + +import com.volmit.resource.ResourceId; +import com.volmit.tooling.world.ToolItem; +import com.volmit.tooling.world.ToolText; +import net.minecraft.core.component.DataComponents; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.Identifier; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.component.CustomData; +import net.minecraft.world.item.component.ItemLore; + +import java.util.List; +import java.util.Optional; + +/** + * {@link ToolItem}s as item stacks. The payload is a string in the custom data component of the stack; its presence is what + * makes a stack a tool item, so an empty payload is stored as an empty string. + */ +final class ToolItems { + static final String PAYLOAD_KEY = "iris_tool_payload"; + + private ToolItems() { + } + + /** + * A new stack of {@code item}. + * + * @throws IllegalArgumentException when the platform has no such item + */ + static ItemStack create(ToolItem item) { + Item type = BuiltInRegistries.ITEM.getOptional(Identifier.parse(item.item().toString())) + .filter(found -> found != Items.AIR) + .orElseThrow(() -> new IllegalArgumentException("The platform has no item " + item.item())); + ItemStack stack = new ItemStack(type); + if (!item.name().isEmpty()) { + stack.set(DataComponents.CUSTOM_NAME, ToolTexts.itemComponent(item.name())); + } + if (!item.lore().isEmpty()) { + stack.set(DataComponents.LORE, new ItemLore(item.lore().stream().map(ToolTexts::itemComponent).toList())); + } + if (item.glowing()) { + stack.set(DataComponents.ENCHANTMENT_GLINT_OVERRIDE, true); + } + CompoundTag data = new CompoundTag(); + data.putString(PAYLOAD_KEY, item.payload()); + stack.set(DataComponents.CUSTOM_DATA, CustomData.of(data)); + return stack; + } + + /** The tool item {@code stack} is; empty for nothing, air or a stack without the tool payload. */ + static Optional read(ItemStack stack) { + if (stack == null || stack.isEmpty()) { + return Optional.empty(); + } + CustomData data = stack.get(DataComponents.CUSTOM_DATA); + if (data == null) { + return Optional.empty(); + } + Optional payload = data.copyTag().getString(PAYLOAD_KEY); + if (payload.isEmpty()) { + return Optional.empty(); + } + Component name = stack.get(DataComponents.CUSTOM_NAME); + ItemLore lore = stack.get(DataComponents.LORE); + return Optional.of(new ToolItem( + ResourceId.parse(BuiltInRegistries.ITEM.getKey(stack.getItem()).toString()), + name == null ? ToolText.EMPTY : plain(name), + lore == null ? List.of() : lore.lines().stream().map(ToolItems::plain).toList(), + Boolean.TRUE.equals(stack.get(DataComponents.ENCHANTMENT_GLINT_OVERRIDE)), + payload.get())); + } + + private static ToolText plain(Component component) { + String text = component.getString(); + return text.isEmpty() ? ToolText.EMPTY : ToolText.plain(text); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolMenus.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolMenus.java new file mode 100644 index 000000000..318632f02 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolMenus.java @@ -0,0 +1,179 @@ +/* + * 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.modded.toolworld; + +import art.arcane.iris.modded.ModdedIrisLog; +import com.volmit.tooling.world.MenuButton; +import com.volmit.tooling.world.MenuClick; +import com.volmit.tooling.world.ToolMenu; +import com.volmit.tooling.world.ToolPlayer; +import net.minecraft.core.component.DataComponents; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.Container; +import net.minecraft.world.SimpleContainer; +import net.minecraft.world.SimpleMenuProvider; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.ChestMenu; +import net.minecraft.world.inventory.ContainerInput; +import net.minecraft.world.inventory.MenuType; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** The chest menus tools open for players: a server-side chest whose slots are cancelled and routed to the menu's buttons. */ +final class ToolMenus { + private static final int SLOTS_PER_ROW = ToolMenu.SLOTS_PER_ROW; + private static final int RIGHT_BUTTON = 1; + private static final List> TYPES_BY_ROWS = List.of( + MenuType.GENERIC_9x1, MenuType.GENERIC_9x2, MenuType.GENERIC_9x3, + MenuType.GENERIC_9x4, MenuType.GENERIC_9x5, MenuType.GENERIC_9x6); + + private final Map screens = new ConcurrentHashMap<>(); + + /** Opens {@code menu} for {@code viewer}, replacing the one they had. Runs on the server thread. */ + void open(ServerPlayer holder, ToolPlayer viewer, ToolMenu menu) { + Screen open = screens.get(holder.getUUID()); + Component title = ToolTexts.component(menu.title()); + if (open != null && open.showsSameFrame(menu, title) && holder.containerMenu == open) { + open.refill(viewer, menu); + return; + } + close(holder); + holder.openMenu(new SimpleMenuProvider( + (id, inventory, player) -> created(id, inventory, holder, viewer, menu, title), title)); + } + + private ChestMenu created(int id, Inventory inventory, ServerPlayer holder, ToolPlayer viewer, ToolMenu menu, Component title) { + Screen screen = new Screen(id, inventory, menu, title, () -> screens.remove(holder.getUUID())); + screen.refill(viewer, menu); + screens.put(holder.getUUID(), screen); + return screen; + } + + /** Closes the player's menu; does nothing when none is open. Runs on the server thread. */ + void close(ServerPlayer holder) { + Screen open = screens.get(holder.getUUID()); + if (open != null && holder.containerMenu == open) { + holder.closeContainer(); + } + screens.remove(holder.getUUID(), open); + } + + void forget(UUID playerId) { + screens.remove(playerId); + } + + private static final class Screen extends ChestMenu { + private final int rows; + private final Component title; + private final Container container; + private final Runnable forgotten; + private volatile Runnable onClose; + private volatile Map buttons = Map.of(); + private volatile ToolPlayer viewer; + + private Screen(int id, Inventory inventory, ToolMenu menu, Component title, Runnable forgotten) { + this(id, inventory, menu, title, forgotten, new SimpleContainer(menu.rows() * SLOTS_PER_ROW)); + } + + private Screen(int id, Inventory inventory, ToolMenu menu, Component title, Runnable forgotten, Container container) { + super(TYPES_BY_ROWS.get(menu.rows() - 1), id, inventory, container, menu.rows()); + this.rows = menu.rows(); + this.title = title; + this.container = container; + this.forgotten = forgotten; + this.onClose = menu.onClose(); + } + + private boolean showsSameFrame(ToolMenu menu, Component otherTitle) { + return rows == menu.rows() && title.equals(otherTitle); + } + + /** Puts the buttons of {@code menu} in, telling the menu it replaces that it closed. */ + private void refill(ToolPlayer by, ToolMenu menu) { + Runnable replaced = onClose; + onClose = menu.onClose(); + viewer = by; + Map placed = new ConcurrentHashMap<>(); + for (int slot = 0; slot < rows * SLOTS_PER_ROW; slot++) { + container.setItem(slot, filler()); + } + for (MenuButton button : menu.buttons()) { + container.setItem(button.slot(), ToolItems.create(button.icon())); + placed.put(button.slot(), button); + } + buttons = placed; + if (replaced != onClose) { + guarded(replaced, "menu close handler"); + } + broadcastChanges(); + } + + private static ItemStack filler() { + ItemStack pane = new ItemStack(Items.STAINED_GLASS_PANE.black()); + pane.set(DataComponents.CUSTOM_NAME, Component.literal(" ")); + return pane; + } + + @Override + public void clicked(int slot, int button, ContainerInput input, Player player) { + MenuButton pressed = slot >= 0 ? buttons.get(slot) : null; + sendAllDataToRemote(); + if (pressed == null || viewer == null) { + return; + } + MenuClick click = clickOf(input, button); + if (click == null) { + return; + } + guarded(() -> pressed.action().accept(click), "menu button"); + } + + private MenuClick clickOf(ContainerInput input, int button) { + boolean right = button == RIGHT_BUTTON; + return switch (input) { + case PICKUP -> new MenuClick(viewer, right, false); + case QUICK_MOVE -> new MenuClick(viewer, right, true); + case CLONE -> new MenuClick(viewer, false, false, true); + default -> null; + }; + } + + @Override + public void removed(Player player) { + super.removed(player); + forgotten.run(); + guarded(onClose, "menu close handler"); + } + + private static void guarded(Runnable task, String what) { + try { + task.run(); + } catch (RuntimeException failure) { + ModdedIrisLog.error("A tool failed in the {}.", what, failure); + } + } + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolPlayers.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolPlayers.java new file mode 100644 index 000000000..b91b5dc37 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolPlayers.java @@ -0,0 +1,222 @@ +/* + * 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.modded.toolworld; + +import art.arcane.iris.modded.ModdedDimensionManager; +import com.volmit.geometry.BlockPosition; +import com.volmit.tooling.world.ToolPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.levelgen.Heightmap; + +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.Map; + +/** + * The tool players of a modded server, and what the host remembers about them: where they came from, the game mode they had + * before the tool made them creative, and which tool world they were last seen in. Presence is found by looking at every + * player once a tick, because Minecraft tells loaders nothing common about arrivals, departures and steps. + */ +final class ToolPlayers { + private static final double TELEPORT_DISTANCE_BLOCKS = 10.0D; + + /** Where a player stood before they entered a tool world. */ + private record Origin(ResourceKey dimension, double x, double y, double z, float yaw, float pitch) { + static Origin of(ServerPlayer player) { + return new Origin(player.level().dimension(), player.getX(), player.getY(), player.getZ(), player.getYRot(), player.getXRot()); + } + } + + /** What the last look at a player saw. */ + private static final class Seen { + private ModdedToolWorld world; + private BlockPosition block; + private boolean sneaking; + private double x; + private double y; + private double z; + private Origin lastOutsideToolWorlds; + } + + private final ToolMenus menus = new ToolMenus(); + private final ToolSidebars sidebars = new ToolSidebars(); + private final Map known = new ConcurrentHashMap<>(); + private final Map origins = new ConcurrentHashMap<>(); + private final Map modesBeforeCreative = new ConcurrentHashMap<>(); + private final Map seen = new ConcurrentHashMap<>(); + + ToolSidebars sidebars() { + return sidebars; + } + + ModdedToolPlayer playerOf(ServerPlayer player) { + return known.computeIfAbsent(player.getUUID(), + id -> new ModdedToolPlayer(id, player.getScoreboardName(), this, menus)); + } + + ToolPlayer of(ServerPlayer player) { + return playerOf(player); + } + + void rememberModeBeforeCreative(ServerPlayer player) { + modesBeforeCreative.putIfAbsent(player.getUUID(), player.gameMode()); + } + + void restoreGameMode(ServerPlayer player) { + GameType before = modesBeforeCreative.remove(player.getUUID()); + if (before != null) { + player.setGameMode(before); + } + } + + /** Sends the player to where they came from, or to the spawn of the main world when that is not known or is a tool world. */ + CompletableFuture destinationAfterToolWorld(ServerPlayer player) { + MinecraftServer server = player.level().getServer(); + Origin origin = origins.remove(player.getUUID()); + ServerLevel back = origin == null ? null : server.getLevel(origin.dimension()); + if (back == null || ToolWorldRegistry.INSTANCE.forLevel(back).isPresent()) { + return teleportToMainSpawn(player, server); + } + return ModdedDimensionManager.teleportAsync(player, server, back, origin.x(), origin.y(), origin.z()) + .thenApply(arrived -> faceAfterReturn(player, back, origin, arrived)); + } + + private static boolean faceAfterReturn(ServerPlayer player, ServerLevel back, Origin origin, Boolean arrived) { + if (Boolean.TRUE.equals(arrived)) { + player.teleportTo(back, player.getX(), player.getY(), player.getZ(), Set.of(), origin.yaw(), origin.pitch(), false); + } + return Boolean.TRUE.equals(arrived); + } + + private static CompletableFuture teleportToMainSpawn(ServerPlayer player, MinecraftServer server) { + ServerLevel main = server.overworld(); + BlockPos spawn = main.getRespawnData().pos(); + int spawnY = main.getHeight(Heightmap.Types.MOTION_BLOCKING, spawn.getX(), spawn.getZ()); + return ModdedDimensionManager.teleportAsync(player, server, main, spawn.getX() + 0.5D, spawnY, spawn.getZ() + 0.5D); + } + + /** Looks at every player once, and tells the tool worlds what changed since the last look. Runs on the server thread. */ + void track(MinecraftServer server) { + if (!ToolWorldRegistry.INSTANCE.hasWorlds() && seen.isEmpty()) { + return; + } + Set online = new java.util.HashSet<>(); + for (ServerPlayer player : server.getPlayerList().getPlayers()) { + online.add(player.getUUID()); + trackOne(player); + } + seen.keySet().removeIf(id -> !online.contains(id) && playerLeftServer(id)); + } + + private boolean playerLeftServer(UUID id) { + Seen last = seen.get(id); + ModdedToolPlayer player = known.remove(id); + if (last != null && last.world != null && player != null) { + last.world.tell(listener -> listener.left(player)); + } + origins.remove(id); + modesBeforeCreative.remove(id); + menus.forget(id); + sidebars.forget(id); + return true; + } + + private void trackOne(ServerPlayer player) { + Seen last = seen.computeIfAbsent(player.getUUID(), id -> new Seen()); + Optional now = player.level() instanceof ServerLevel level + ? ToolWorldRegistry.INSTANCE.forLevel(level) : Optional.empty(); + ModdedToolWorld current = now.orElse(null); + if (last.world != current) { + changedWorld(player, last, current); + } else if (current != null) { + moved(player, last, current); + } + if (current == null) { + last.lastOutsideToolWorlds = Origin.of(player); + } + remember(player, last, current); + } + + private void changedWorld(ServerPlayer player, Seen last, ModdedToolWorld current) { + ModdedToolPlayer toolPlayer = playerOf(player); + ModdedToolWorld before = last.world; + if (before == null) { + origins.put(player.getUUID(), last.lastOutsideToolWorlds != null ? last.lastOutsideToolWorlds : Origin.of(player)); + } + if (before != null) { + before.tell(listener -> listener.left(toolPlayer)); + } + if (current == null) { + restoreGameMode(player); + origins.remove(player.getUUID()); + sidebars.hide(player); + return; + } + BlockPosition arrival = ToolBlocks.positionOf(player.blockPosition()); + current.tell(listener -> listener.entered(toolPlayer)); + current.tell(listener -> listener.teleported(toolPlayer, arrival)); + } + + private void moved(ServerPlayer player, Seen last, ModdedToolWorld current) { + ModdedToolPlayer toolPlayer = playerOf(player); + BlockPosition block = ToolBlocks.positionOf(player.blockPosition()); + if (!block.equals(last.block)) { + double dx = player.getX() - last.x; + double dy = player.getY() - last.y; + double dz = player.getZ() - last.z; + boolean teleport = dx * dx + dy * dy + dz * dz > TELEPORT_DISTANCE_BLOCKS * TELEPORT_DISTANCE_BLOCKS; + current.tell(listener -> { + if (teleport) { + listener.teleported(toolPlayer, block); + } else { + listener.moved(toolPlayer, block); + } + }); + } + if (player.isShiftKeyDown() != last.sneaking) { + boolean sneaking = player.isShiftKeyDown(); + current.tell(listener -> listener.sneakToggled(toolPlayer, sneaking)); + } + } + + private static void remember(ServerPlayer player, Seen last, ModdedToolWorld current) { + last.world = current; + last.block = ToolBlocks.positionOf(player.blockPosition()); + last.sneaking = player.isShiftKeyDown(); + last.x = player.getX(); + last.y = player.getY(); + last.z = player.getZ(); + } + + void clear() { + known.clear(); + origins.clear(); + modesBeforeCreative.clear(); + seen.clear(); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolSidebars.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolSidebars.java new file mode 100644 index 000000000..92a44950d --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolSidebars.java @@ -0,0 +1,84 @@ +/* + * 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.modded.toolworld; + +import com.volmit.tooling.world.ToolText; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.numbers.BlankFormat; +import net.minecraft.network.protocol.game.ClientboundResetScorePacket; +import net.minecraft.network.protocol.game.ClientboundSetDisplayObjectivePacket; +import net.minecraft.network.protocol.game.ClientboundSetObjectivePacket; +import net.minecraft.network.protocol.game.ClientboundSetScorePacket; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.scores.DisplaySlot; +import net.minecraft.world.scores.Objective; +import net.minecraft.world.scores.Scoreboard; +import net.minecraft.world.scores.criteria.ObjectiveCriteria; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * The sidebar a tool shows one player: a scoreboard objective in the sidebar slot that only that player's client is told + * about, so the server's own scoreboard and other players are left alone. + */ +final class ToolSidebars { + private static final String OBJECTIVE_NAME = "iris_tool"; + private static final String LINE_OWNER_PREFIX = "iris_tool_line_"; + + private final Map shownLines = new ConcurrentHashMap<>(); + + /** Shows {@code title} over {@code lines}, replacing the sidebar the player had. Runs on the server thread. */ + void show(ServerPlayer player, ToolText title, List lines) { + Objective objective = objective(ToolTexts.component(title)); + boolean shownBefore = shownLines.containsKey(player.getUUID()); + player.connection.send(new ClientboundSetObjectivePacket(objective, + shownBefore ? ClientboundSetObjectivePacket.METHOD_CHANGE : ClientboundSetObjectivePacket.METHOD_ADD)); + player.connection.send(new ClientboundSetDisplayObjectivePacket(DisplaySlot.SIDEBAR, objective)); + for (int index = 0; index < lines.size(); index++) { + player.connection.send(new ClientboundSetScorePacket(LINE_OWNER_PREFIX + index, OBJECTIVE_NAME, + lines.size() - index, Optional.of(ToolTexts.component(lines.get(index))), Optional.of(BlankFormat.INSTANCE))); + } + for (int stale = lines.size(); stale < shownLines.getOrDefault(player.getUUID(), 0); stale++) { + player.connection.send(new ClientboundResetScorePacket(LINE_OWNER_PREFIX + stale, OBJECTIVE_NAME)); + } + shownLines.put(player.getUUID(), lines.size()); + } + + /** Takes the sidebar away; does nothing when none is shown. Runs on the server thread. */ + void hide(ServerPlayer player) { + if (shownLines.remove(player.getUUID()) == null) { + return; + } + player.connection.send(new ClientboundSetObjectivePacket(objective(Component.empty()), + ClientboundSetObjectivePacket.METHOD_REMOVE)); + } + + void forget(UUID playerId) { + shownLines.remove(playerId); + } + + private static Objective objective(Component title) { + return new Objective(new Scoreboard(), OBJECTIVE_NAME, ObjectiveCriteria.DUMMY, title, + ObjectiveCriteria.RenderType.INTEGER, false, BlankFormat.INSTANCE); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolTexts.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolTexts.java new file mode 100644 index 000000000..3cf899503 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolTexts.java @@ -0,0 +1,88 @@ +/* + * 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.modded.toolworld; + +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolText; +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.network.chat.Style; + +import java.util.EnumMap; +import java.util.Map; + +/** {@link ToolText} as the components Minecraft shows. */ +final class ToolTexts { + private static final Map COLORS = new EnumMap<>(Map.ofEntries( + Map.entry(TextColor.BLACK, ChatFormatting.BLACK), + Map.entry(TextColor.DARK_BLUE, ChatFormatting.DARK_BLUE), + Map.entry(TextColor.DARK_GREEN, ChatFormatting.DARK_GREEN), + Map.entry(TextColor.DARK_AQUA, ChatFormatting.DARK_AQUA), + Map.entry(TextColor.DARK_RED, ChatFormatting.DARK_RED), + Map.entry(TextColor.DARK_PURPLE, ChatFormatting.DARK_PURPLE), + Map.entry(TextColor.GOLD, ChatFormatting.GOLD), + Map.entry(TextColor.GRAY, ChatFormatting.GRAY), + Map.entry(TextColor.DARK_GRAY, ChatFormatting.DARK_GRAY), + Map.entry(TextColor.BLUE, ChatFormatting.BLUE), + Map.entry(TextColor.GREEN, ChatFormatting.GREEN), + Map.entry(TextColor.AQUA, ChatFormatting.AQUA), + Map.entry(TextColor.RED, ChatFormatting.RED), + Map.entry(TextColor.LIGHT_PURPLE, ChatFormatting.LIGHT_PURPLE), + Map.entry(TextColor.YELLOW, ChatFormatting.YELLOW), + Map.entry(TextColor.WHITE, ChatFormatting.WHITE))); + + private ToolTexts() { + } + + /** Chat, action bar, titles and sidebar lines: unstyled spans keep the platform's own look. */ + static Component component(ToolText text) { + return build(text, false); + } + + /** Item names and lore: vanilla shows them in italics unless told not to, so a span is italic only when it asks to be. */ + static Component itemComponent(ToolText text) { + return build(text, true); + } + + private static Component build(ToolText text, boolean explicitItalics) { + MutableComponent whole = Component.empty(); + for (ToolText.Span span : text.spans()) { + whole.append(Component.literal(span.text()).setStyle(styleOf(span, explicitItalics))); + } + return whole; + } + + private static Style styleOf(ToolText.Span span, boolean explicitItalics) { + Style style = Style.EMPTY; + if (span.color() != null) { + style = style.withColor(COLORS.get(span.color())); + } + if (span.bold()) { + style = style.withBold(true); + } + if (span.italic() || explicitItalics) { + style = style.withItalic(span.italic()); + } + if (span.strikethrough()) { + style = style.withStrikethrough(true); + } + return style; + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolWorldGuard.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolWorldGuard.java new file mode 100644 index 000000000..221a4bfdd --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolWorldGuard.java @@ -0,0 +1,187 @@ +/* + * 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.modded.toolworld; + +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.tooling.world.BlockChange; +import com.volmit.tooling.world.BlockChange.Cause; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolUse; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.tags.BlockTags; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.BonemealableBlock; + +import java.util.List; +import java.util.Optional; + +/** + * Where the vanilla code paths of a tool world ask the tool. Every change to a block of a tool world passes + * {@link #setBlockAllowed}: the host's own writes pass, a change inside a {@link Scope} that names its cause is put to the + * tool as that cause, and a change nobody named a cause for is refused, so the world stays frozen where Bukkit would not + * have been asked. The scopes are entered by the mixins at the places vanilla starts a kind of change. + */ +public final class ToolWorldGuard { + private static final ThreadLocal CURRENT = new ThreadLocal<>(); + private static final ThreadLocal HOST_WRITES = ThreadLocal.withInitial(() -> 0); + + private ToolWorldGuard() { + } + + /** What a thread is doing to a tool world, which tells its block changes apart. */ + private static final class Scope { + private final Level level; + private final Cause cause; + private final Entity actor; + private final boolean approved; + private final Scope previous; + + private Scope(Level level, Cause cause, Entity actor, boolean approved, Scope previous) { + this.level = level; + this.cause = cause; + this.actor = actor; + this.approved = approved; + this.previous = previous; + } + } + + /** Whether {@code level} is a tool world. Cheap enough to ask for every block change of every world. */ + public static boolean isToolWorld(Level level) { + return ToolWorldRegistry.INSTANCE.hasWorlds() && level instanceof ServerLevel serverLevel + && ToolWorldRegistry.INSTANCE.forLevel(serverLevel).isPresent(); + } + + /** Runs the host's own write to a tool world, which no tool is asked about. */ + static void hostWrite(Runnable write) { + HOST_WRITES.set(HOST_WRITES.get() + 1); + try { + write.run(); + } finally { + HOST_WRITES.set(HOST_WRITES.get() - 1); + } + } + + /** + * Starts a kind of change in {@code level}. A {@code null} cause is told apart per block by what changes, as a random tick + * does. {@code approved} lets everything inside through, for what the tool was asked about already. + * + * @return whether {@code level} is a tool world, which is whether {@link #exit} must follow + */ + public static boolean enter(Level level, Cause cause, Entity actor, boolean approved) { + if (!isToolWorld(level)) { + return false; + } + CURRENT.set(new Scope(level, cause, actor, approved, CURRENT.get())); + return true; + } + + /** Ends the innermost scope of {@code level}; does nothing for a level that is no tool world. */ + public static void exit(Level level) { + Scope scope = CURRENT.get(); + if (scope != null && scope.level == level) { + CURRENT.set(scope.previous); + } + } + + /** Drops scopes a failed call left behind. */ + public static void resetScopes() { + CURRENT.remove(); + HOST_WRITES.remove(); + } + + /** Whether the block at {@code position} of {@code level} may become {@code newState} now. */ + public static boolean setBlockAllowed(Level level, BlockPos position, net.minecraft.world.level.block.state.BlockState newState) { + if (!isToolWorld(level) || HOST_WRITES.get() > 0) { + return true; + } + Scope scope = CURRENT.get(); + if (scope == null || scope.level != level) { + return false; + } + if (scope.approved) { + return true; + } + net.minecraft.world.level.block.state.BlockState old = level.getBlockState(position); + if (old == newState) { + return true; + } + Cause cause = scope.cause != null ? scope.cause : classifyTickChange(old, newState); + Optional placed = cause == Cause.PLACE ? Optional.of(ToolBlocks.apiStateOf(newState)) : Optional.empty(); + return allowed(level, cause, actorPlayer(scope.actor), List.of(ToolBlocks.positionOf(position)), placed); + } + + private static Cause classifyTickChange(net.minecraft.world.level.block.state.BlockState old, + net.minecraft.world.level.block.state.BlockState replacement) { + if (old.is(BlockTags.FIRE) || replacement.is(BlockTags.FIRE)) { + return Cause.FIRE; + } + if (old.getBlock() instanceof BonemealableBlock) { + return Cause.GROWTH; + } + return Cause.PHYSICS; + } + + /** Whether the tool lets a change of {@code cause} to {@code positions} happen; changes outside tool worlds are none of the host's business. */ + public static boolean allowed(Level level, Cause cause, Optional player, List positions, + Optional placed) { + return allowed(level, cause, player, positions, positions, placed); + } + + public static boolean allowed(Level level, Cause cause, Optional player, List positions, + List changed, Optional placed) { + Optional world = worldOf(level); + if (world.isEmpty()) { + return true; + } + BlockChange change = new BlockChange(cause, positions, changed, player, placed); + return world.get().ask(listener -> listener.blockChanging(change), false); + } + + /** Whether the tool lets {@code player} use their hand as {@code use} describes. */ + public static boolean usingAllowed(ServerPlayer player, ToolUse use) { + Optional world = worldOf(player.level()); + if (world.isEmpty()) { + return true; + } + ToolPlayer toolPlayer = ModdedToolWorldService.players().of(player); + return world.get().ask(listener -> listener.used(toolPlayer, use), false); + } + + public static Optional toolPlayerOf(Entity entity) { + return actorPlayer(entity); + } + + static Optional worldOf(Level level) { + if (!ToolWorldRegistry.INSTANCE.hasWorlds() || !(level instanceof ServerLevel serverLevel)) { + return Optional.empty(); + } + return ToolWorldRegistry.INSTANCE.forLevel(serverLevel); + } + + private static Optional actorPlayer(Entity actor) { + if (actor instanceof ServerPlayer player) { + return Optional.of(ModdedToolWorldService.players().of(player)); + } + return Optional.empty(); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolWorldHooks.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolWorldHooks.java new file mode 100644 index 000000000..8facbaaed --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolWorldHooks.java @@ -0,0 +1,239 @@ +/* + * 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.modded.toolworld; + +import art.arcane.iris.modded.structure.PrivateFields; +import com.volmit.geometry.BlockPosition; +import com.volmit.tooling.world.BlockChange.Cause; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolUse; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.network.protocol.game.ClientboundBlockUpdatePacket; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.CompoundContainer; +import net.minecraft.world.Container; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.LivingEntity; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.inventory.Slot; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.piston.PistonStructureResolver; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.HitResult; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** What the mixins ask of a tool world for each kind of thing a player or the world does; all of it answers "allowed" outside tool worlds. */ +public final class ToolWorldHooks { + private static final String COMMAND_PREFIX = "/"; + private static final double LEFT_CLICK_REACH_BLOCKS = 5.0D; + + private ToolWorldHooks() { + } + + // What players do with their hands. + + public static boolean rightClickBlockAllowed(ServerPlayer player, InteractionHand hand, ItemStack stack, BlockHitResult hit) { + if (!ToolWorldGuard.isToolWorld(player.level())) { + return true; + } + return ToolWorldGuard.usingAllowed(player, new ToolUse(handOf(hand), ToolUse.Action.RIGHT_CLICK_BLOCK, + ToolItems.read(stack), Optional.of(ToolBlocks.positionOf(hit.getBlockPos())), ToolBlocks.faceOf(hit.getDirection()))); + } + + public static boolean rightClickAirAllowed(ServerPlayer player, InteractionHand hand, ItemStack stack) { + if (!ToolWorldGuard.isToolWorld(player.level())) { + return true; + } + return ToolWorldGuard.usingAllowed(player, new ToolUse(handOf(hand), ToolUse.Action.RIGHT_CLICK_AIR, + ToolItems.read(stack), Optional.empty(), Optional.empty())); + } + + /** Asks the tool about a left click on a block; a refusal puts the block back on the player's screen. */ + public static boolean leftClickBlockAllowed(ServerPlayer player, BlockPos at, Direction face, int sequence) { + if (!ToolWorldGuard.isToolWorld(player.level())) { + return true; + } + ToolUse use = new ToolUse(ToolUse.Hand.MAIN, ToolUse.Action.LEFT_CLICK_BLOCK, + ToolItems.read(player.getMainHandItem()), Optional.of(ToolBlocks.positionOf(at)), ToolBlocks.faceOf(face)); + if (ToolWorldGuard.usingAllowed(player, use)) { + return true; + } + player.connection.send(new ClientboundBlockUpdatePacket(at, player.level().getBlockState(at))); + player.connection.ackBlockChangesUpTo(sequence); + return false; + } + + /** Tells the tool about a swing at nothing; a swing at a block is the left click on the block. */ + public static void leftClickAir(ServerPlayer player, InteractionHand hand) { + if (!ToolWorldGuard.isToolWorld(player.level())) { + return; + } + HitResult target = player.pick(LEFT_CLICK_REACH_BLOCKS, 1.0F, false); + if (target.getType() == HitResult.Type.BLOCK) { + return; + } + ToolWorldGuard.usingAllowed(player, new ToolUse(handOf(hand), ToolUse.Action.LEFT_CLICK_AIR, + ToolItems.read(player.getItemInHand(hand)), Optional.empty(), Optional.empty())); + } + + private static ToolUse.Hand handOf(InteractionHand hand) { + return hand == InteractionHand.OFF_HAND ? ToolUse.Hand.OFF : ToolUse.Hand.MAIN; + } + + // Block changes a player starts. + + public static boolean placeAllowed(Level level, Entity actor, BlockPos at, BlockState placed) { + if (!ToolWorldGuard.isToolWorld(level)) { + return true; + } + Optional state = placed == null ? Optional.empty() : Optional.of(ToolBlocks.apiStateOf(placed)); + return ToolWorldGuard.allowed(level, Cause.PLACE, ToolWorldGuard.toolPlayerOf(actor), List.of(ToolBlocks.positionOf(at)), state); + } + + public static boolean breakAllowed(Level level, ServerPlayer actor, BlockPos at) { + return ToolWorldGuard.allowed(level, Cause.BREAK, ToolWorldGuard.toolPlayerOf(actor), List.of(ToolBlocks.positionOf(at)), Optional.empty()); + } + + public static boolean bucketEmptyAllowed(Level level, LivingEntity actor, BlockPos at) { + return ToolWorldGuard.allowed(level, Cause.BUCKET, ToolWorldGuard.toolPlayerOf(actor), List.of(ToolBlocks.positionOf(at)), Optional.empty()); + } + + // Pistons. + + /** Asks about each block a piston moves and the block each of them enters and leaves, and about the piston itself. */ + public static boolean pistonMoveAllowed(Level level, BlockPos piston, Direction direction, boolean extending) { + if (!ToolWorldGuard.isToolWorld(level)) { + return true; + } + PistonStructureResolver resolver = new PistonStructureResolver(level, piston, direction, extending); + if (!resolver.resolve()) { + return true; + } + List moved = new ArrayList<>(resolver.getToPush()); + moved.addAll(resolver.getToDestroy()); + List checked = new ArrayList<>(); + List changed = new ArrayList<>(); + changed.add(ToolBlocks.positionOf(piston)); + changed.add(ToolBlocks.positionOf(piston.relative(direction))); + for (BlockPos block : moved) { + checked.add(ToolBlocks.positionOf(block)); + checked.add(ToolBlocks.positionOf(block.relative(direction))); + checked.add(ToolBlocks.positionOf(block.relative(direction.getOpposite()))); + changed.add(ToolBlocks.positionOf(block)); + changed.add(ToolBlocks.positionOf(block.relative(direction))); + } + if (checked.isEmpty()) { + return true; + } + return ToolWorldGuard.allowed(level, Cause.PISTON, Optional.empty(), + checked.stream().distinct().toList(), changed.stream().distinct().toList(), Optional.empty()); + } + + // Containers and machines. + + public static boolean containerClickAllowed(ServerPlayer player, AbstractContainerMenu menu) { + if (!ToolWorldGuard.isToolWorld(player.level())) { + return true; + } + List blocks = containerBlocks(menu); + if (blocks.isEmpty()) { + return true; + } + return ToolWorldGuard.allowed(player.level(), Cause.CONTAINER, ToolWorldGuard.toolPlayerOf(player), blocks, Optional.empty()); + } + + /** Tells the tool that the inventory of a container block was closed, which may have changed what is in it. */ + public static void containerClosed(Entity closer, AbstractContainerMenu menu) { + Optional world = ToolWorldGuard.worldOf(closer.level()); + if (world.isEmpty() || !(closer instanceof ServerPlayer player)) { + return; + } + Optional toolPlayer = ToolWorldGuard.toolPlayerOf(player); + for (BlockPosition block : containerBlocks(menu)) { + world.get().tell(listener -> listener.containerChanged(toolPlayer, block)); + } + } + + /** The blocks the container inventory of {@code menu} is made of: none for a player's or a menu, two for a double chest. */ + private static List containerBlocks(AbstractContainerMenu menu) { + List blocks = new ArrayList<>(2); + for (Slot slot : menu.slots) { + addBlocksOf(blocks, slot.container); + } + return blocks; + } + + private static void addBlocksOf(List blocks, Container container) { + if (container instanceof CompoundContainer compound) { + addBlocksOf(blocks, PrivateFields.read(compound, "container1", Container.class)); + addBlocksOf(blocks, PrivateFields.read(compound, "container2", Container.class)); + return; + } + if (container instanceof BlockEntity blockEntity) { + BlockPosition at = ToolBlocks.positionOf(blockEntity.getBlockPos()); + if (!blocks.contains(at)) { + blocks.add(at); + } + } + } + + public static boolean machineAllowed(Level level, BlockPos at) { + if (!ToolWorldGuard.isToolWorld(level)) { + return true; + } + return ToolWorldGuard.allowed(level, Cause.MACHINE, Optional.empty(), List.of(ToolBlocks.positionOf(at)), Optional.empty()); + } + + // Commands. + + /** Asks the tool world a player stands in about their command; a command from anywhere else is every tool world's to hear. */ + public static boolean commandAllowed(CommandSourceStack source, String typed) { + if (!ToolWorldRegistry.INSTANCE.hasWorlds()) { + return true; + } + String line = typed.startsWith(COMMAND_PREFIX) ? typed.substring(COMMAND_PREFIX.length()) : typed; + ServerPlayer player = source.getPlayer(); + if (player != null) { + return playerCommandAllowed(player, line); + } + return ToolWorldRegistry.INSTANCE.all().stream().allMatch(world -> world.ask(listener -> listener.command(Optional.empty(), line), true)); + } + + private static boolean playerCommandAllowed(ServerPlayer player, String line) { + if (!(player.level() instanceof ServerLevel level)) { + return true; + } + Optional world = ToolWorldRegistry.INSTANCE.forLevel(level); + if (world.isEmpty()) { + return true; + } + ToolPlayer toolPlayer = ModdedToolWorldService.toolPlayerOf(player); + return world.get().ask(listener -> listener.command(Optional.of(toolPlayer), line), true); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolWorldRegistry.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolWorldRegistry.java new file mode 100644 index 000000000..0e67ed898 --- /dev/null +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/toolworld/ToolWorldRegistry.java @@ -0,0 +1,72 @@ +/* + * 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.modded.toolworld; + +import net.minecraft.server.level.ServerLevel; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +/** The tool worlds that exist, from before their level is made until it is gone. */ +final class ToolWorldRegistry { + static final ToolWorldRegistry INSTANCE = new ToolWorldRegistry(); + + private final Map byDimensionId = new ConcurrentHashMap<>(); + + private ToolWorldRegistry() { + } + + /** Whether any tool world exists; the mixins ask this first so a server with none pays one read. */ + boolean hasWorlds() { + return !byDimensionId.isEmpty(); + } + + /** Registers {@code world}; false when its pack has a tool world of that name already. */ + synchronized boolean register(ModdedToolWorld world) { + if (forName(world.packName(), world.name()).isPresent()) { + return false; + } + byDimensionId.put(world.dimensionId(), world); + return true; + } + + void unregister(ModdedToolWorld world) { + byDimensionId.remove(world.dimensionId(), world); + } + + Optional forLevel(ServerLevel level) { + return Optional.ofNullable(byDimensionId.get(level.dimension().identifier().toString())); + } + + Optional forName(String packName, String name) { + return byDimensionId.values().stream() + .filter(world -> world.packName().equals(packName) && world.name().equals(name)) + .findFirst(); + } + + List all() { + return List.copyOf(byDimensionId.values()); + } + + void clear() { + byDimensionId.clear(); + } +} diff --git a/adapters/modded-common/src/main/resources/irisworldgen.entity.mixins.json b/adapters/modded-common/src/main/resources/irisworldgen.entity.mixins.json index e7b5a28e2..be27aaf09 100644 --- a/adapters/modded-common/src/main/resources/irisworldgen.entity.mixins.json +++ b/adapters/modded-common/src/main/resources/irisworldgen.entity.mixins.json @@ -4,9 +4,27 @@ "package": "art.arcane.iris.modded.mixin", "compatibilityLevel": "JAVA_21", "mixins": [ + "AbstractContainerMenuToolMixin", + "BlockItemToolMixin", + "BrewingStandToolMixin", + "BucketItemToolMixin", + "CommandsToolMixin", + "CrafterToolMixin", + "DispenserToolMixin", "EntityPersistenceMixin", + "EntityToolMixin", + "FurnaceToolMixin", + "LevelChunkToolMixin", + "LevelToolMixin", "LivingEntityLootMixin", "MobAwarenessMixin", + "NaturalSpawnerToolMixin", + "PistonBaseBlockToolMixin", + "SaplingBlockToolMixin", + "ServerExplosionToolMixin", + "ServerGamePacketListenerToolMixin", + "ServerLevelToolMixin", + "ServerPlayerGameModeToolMixin", "StructureTemplatePaletteConcurrencyMixin" ], "injectors": { diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedCommandParityTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedCommandParityTest.java index 50a8fc86b..e4cea7a35 100644 --- a/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedCommandParityTest.java +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedCommandParityTest.java @@ -162,7 +162,7 @@ public class IrisModdedCommandParityTest { assertNotNull("iris", iris.getCommand()); for (String category : new String[]{"help", "find", "goto", "pregen", "pregenerate", "object", "o", "edit", "studio", "std", "s", "pack", "pk", "world", "w", "datapack", "datapacks", "dp", - "structure", "struct", "str", "developer", "dev", "module", "m"}) { + "developer", "dev", "module", "m"}) { assertNotNull(category, child(iris, category).getCommand()); } } @@ -174,9 +174,6 @@ public class IrisModdedCommandParityTest { for (CommandNode node : iris.getChildren()) { assertTrue(node.getName() + " must be a literal", node instanceof LiteralCommandNode); } - for (CommandNode node : child(iris, "structure").getChildren()) { - assertTrue("structure " + node.getName() + " must be a literal", node instanceof LiteralCommandNode); - } for (String branch : new String[]{"module", "m"}) { CommandNode module = child(iris, branch); assertNotNull(branch + " lists the mounted commands on its own", module.getCommand()); @@ -225,9 +222,13 @@ public class IrisModdedCommandParityTest { } @Test - public void structureHelpListsOnlyImportAndCapture() { - assertEquals(List.of("import", "import-all", "reimport", "imp", "all", "capture", "cap"), - ModdedCommandHelp.documentedWords("structure")); + public void structureImportAndCaptureAreModuleCommandsAndHaveNoLiteralsOfTheirOwn() { + CommandNode iris = irisNode(); + + for (String structure : new String[]{"structure", "struct", "str"}) { + assertNull(structure, iris.getChild(structure)); + } + assertFalse(ModdedCommandHelp.sections().contains("structure")); } private static CommandNode child( diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedStructureCommandTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedStructureCommandTest.java index 5db627235..8595657c4 100644 --- a/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedStructureCommandTest.java +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/command/IrisModdedStructureCommandTest.java @@ -281,10 +281,9 @@ public class IrisModdedStructureCommandTest { @Test public void structureListInfoAndVerifyBelongToTheStructureModule() throws IOException { - String source = source("ModdedStructureCommands.java"); + Path staticTree = commonSourceRoot().resolve("art/arcane/iris/modded/command/ModdedStructureCommands.java"); - assertFalse(source.contains("Commands.literal(\"list\")")); - assertFalse(source.contains("verifyTree(")); + assertFalse(Files.exists(staticTree)); } private String source(String fileName) throws IOException { diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/structure/PlatformStructuresVanillaTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/structure/PlatformStructuresVanillaTest.java new file mode 100644 index 000000000..cfd4b14eb --- /dev/null +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/structure/PlatformStructuresVanillaTest.java @@ -0,0 +1,171 @@ +/* + * 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.modded.structure; + +import com.mojang.datafixers.util.Pair; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.JigsawStructureInfo; +import com.volmit.tooling.StructureTemplate; +import com.volmit.tooling.TemplateBlock; +import com.volmit.tooling.TemplatePool; +import net.minecraft.SharedConstants; +import net.minecraft.core.HolderLookup; +import net.minecraft.core.registries.Registries; +import net.minecraft.data.registries.VanillaRegistries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.IntTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.NbtUtils; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.Bootstrap; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.world.level.levelgen.structure.pools.StructurePoolElement; +import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool; +import net.minecraft.world.level.levelgen.structure.structures.JigsawStructure; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** The records the tools read from vanilla data: the values the Bukkit host reads from the same data. */ +public class PlatformStructuresVanillaTest { + private static final String VILLAGE = "minecraft:village_plains"; + private static final String VILLAGE_START_POOL = "minecraft:village/plains/town_centers"; + private static final int VILLAGE_DEPTH = 6; + private static final int VILLAGE_DISTANCE = 80; + + private static HolderLookup.Provider vanilla; + + @BeforeClass + public static void bootstrapMinecraftRegistries() { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + vanilla = VanillaRegistries.createLookup(); + } + + private static ListTag intsOf(int... values) { + ListTag list = new ListTag(); + for (int value : values) { + list.add(IntTag.valueOf(value)); + } + return list; + } + + private static CompoundTag blockOf(int state, int x, CompoundTag nbt) { + CompoundTag block = new CompoundTag(); + block.put("pos", intsOf(x, 0, 0)); + block.putInt("state", state); + if (nbt != null) { + block.put("nbt", nbt); + } + return block; + } + + /** A template of a stone block and a jigsaw block whose final state is oak planks, in the form a template file stores. */ + private static CompoundTag templateTag() { + CompoundTag finalState = new CompoundTag(); + finalState.putString("final_state", "minecraft:oak_planks"); + finalState.putString("id", "minecraft:jigsaw"); + finalState.putString("name", "minecraft:empty"); + finalState.putString("target", "minecraft:empty"); + finalState.putString("pool", "minecraft:empty"); + finalState.putString("joint", "rollable"); + ListTag palette = new ListTag(); + palette.add(NbtUtils.writeBlockState(Blocks.STONE.defaultBlockState())); + palette.add(NbtUtils.writeBlockState(Blocks.JIGSAW.defaultBlockState())); + ListTag blocks = new ListTag(); + blocks.add(blockOf(0, 0, null)); + blocks.add(blockOf(1, 1, finalState)); + CompoundTag tag = new CompoundTag(); + tag.put("size", intsOf(2, 1, 1)); + tag.put("palette", palette); + tag.put("blocks", blocks); + tag.put("entities", new ListTag()); + return tag; + } + + private static T registered(ResourceKey> registry, String key) { + return vanilla.lookupOrThrow(registry) + .getOrThrow(ResourceKey.create(registry, Identifier.parse(key))).value(); + } + + @Test + public void aVanillaJigsawStructureReadsAsItsStartPoolDepthAndDistance() { + JigsawStructure village = (JigsawStructure) registered(Registries.STRUCTURE, VILLAGE); + Identifier startPool = village.getStartPool().unwrapKey().orElseThrow().identifier(); + + JigsawStructureInfo info = ModdedPlatformStructures.jigsawInfoOf(ResourceId.parse(VILLAGE), village, startPool, "26.2"); + + assertEquals(ResourceId.parse(VILLAGE_START_POOL), info.startPool()); + assertEquals(VILLAGE_DEPTH, info.maxDepth()); + assertEquals(VILLAGE_DISTANCE, info.maxDistance()); + assertEquals("26.2", info.gameVersion()); + } + + @Test + public void theShuffleSeedIsTheHashBukkitGivesTheSameKey() { + long bukkitHash = 31 * "minecraft".hashCode() + "village_plains".hashCode(); + + assertEquals(bukkitHash, ModdedPlatformStructures.shuffleSeedOf(ResourceId.parse(VILLAGE))); + } + + @Test + public void aVanillaPoolReadsAsWeightedElementsWithTheirTemplates() { + StructureTemplatePool pool = registered(Registries.TEMPLATE_POOL, VILLAGE_START_POOL); + + assertTrue("pool " + pool + " has " + pool.getTemplates().size(), !pool.getTemplates().isEmpty()); + for (Pair pair : pool.getTemplates()) { + TemplatePool.Member member = PoolReading.memberOf(pair, null); + TemplatePool.Element element = (TemplatePool.Element) member; + assertEquals(Math.max(1, pair.getSecond()), element.weight()); + assertEquals("minecraft", element.template().orElseThrow().namespace()); + assertTrue("template of " + element, element.template().orElseThrow().path().startsWith("village/plains/")); + } + } + + @Test + public void aTemplateReadsAsItsSizeBlocksAndJigsawFinalState() throws Exception { + net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate template = + new net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate(); + template.load(BuiltInRegistries.BLOCK, templateTag()); + + StructureTemplate read = TemplateReading.read(template).orElseThrow(); + + assertEquals(new BlockPosition(2, 1, 1), read.size()); + assertEquals(1, read.paletteCount()); + assertEquals(0, read.entityCount()); + assertEquals(2, read.blocks().size()); + TemplateBlock stone = read.blocks().get(0); + assertEquals(new BlockPosition(0, 0, 0), stone.position()); + assertEquals(BlockState.parse("minecraft:stone"), stone.state()); + assertEquals(Optional.empty(), stone.jigsawFinalState()); + TemplateBlock jigsaw = read.blocks().get(1); + assertEquals(new BlockPosition(1, 0, 0), jigsaw.position()); + assertEquals(BlockState.parse("minecraft:jigsaw[orientation=north_up]"), jigsaw.state()); + assertEquals(Optional.of("minecraft:oak_planks"), jigsaw.jigsawFinalState()); + assertEquals(Optional.empty(), jigsaw.blockEntity()); + } +} diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/toolworld/ToolItemsTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/toolworld/ToolItemsTest.java new file mode 100644 index 000000000..fa4613c2f --- /dev/null +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/toolworld/ToolItemsTest.java @@ -0,0 +1,50 @@ +/* + * 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.modded.toolworld; + +import com.volmit.resource.ResourceId; +import com.volmit.tooling.world.ToolItem; +import com.volmit.tooling.world.ToolText; +import net.minecraft.SharedConstants; +import net.minecraft.server.Bootstrap; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertThrows; + +/** + * Making and reading a stack needs the item components a running server binds, which a bootstrapped registry does not have; + * that round trip is checked in the game. + */ +public class ToolItemsTest { + @BeforeClass + public static void bootstrapMinecraftRegistries() { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + } + + @Test + public void anItemThePlatformLacksIsRefused() { + ToolItem missing = new ToolItem(ResourceId.parse("iris:no_such_item"), ToolText.EMPTY, List.of(), false, ""); + + assertThrows(IllegalArgumentException.class, () -> ToolItems.create(missing)); + } +} diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/modded/toolworld/ToolTextsTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/modded/toolworld/ToolTextsTest.java new file mode 100644 index 000000000..d98d28cb3 --- /dev/null +++ b/adapters/modded-common/src/test/java/art/arcane/iris/modded/toolworld/ToolTextsTest.java @@ -0,0 +1,67 @@ +/* + * 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.modded.toolworld; + +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolText; +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.Style; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class ToolTextsTest { + private static final ToolText STYLED = ToolText.builder() + .gray("Size: ") + .append(new ToolText.Span("16", TextColor.WHITE, true, false, true)) + .append("plain") + .build(); + + @Test + public void chatKeepsTheColourAndStylesOfEachSpanAndNothingElse() { + List parts = ToolTexts.component(STYLED).getSiblings(); + + assertEquals(3, parts.size()); + assertEquals(Style.EMPTY.withColor(ChatFormatting.GRAY), parts.get(0).getStyle()); + assertEquals(Style.EMPTY.withColor(ChatFormatting.WHITE).withBold(true).withStrikethrough(true), parts.get(1).getStyle()); + assertEquals(Style.EMPTY, parts.get(2).getStyle()); + assertEquals("Size: 16plain", ToolTexts.component(STYLED).getString()); + } + + @Test + public void itemTextIsNeverItalicUnlessTheSpanAsksForIt() { + ToolText text = ToolText.builder() + .gold("Wand") + .append(new ToolText.Span("slanted", null, false, true, false)) + .build(); + + List parts = ToolTexts.itemComponent(text).getSiblings(); + + assertEquals(Style.EMPTY.withColor(ChatFormatting.GOLD).withItalic(false), parts.get(0).getStyle()); + assertEquals(Style.EMPTY.withItalic(true), parts.get(1).getStyle()); + } + + @Test + public void emptyTextIsAnEmptyComponent() { + assertEquals("", ToolTexts.component(ToolText.EMPTY).getString()); + } +} diff --git a/adapters/modded-common/src/test/java/art/arcane/iris/nativegen/NativeStructureVacuumParityTest.java b/adapters/modded-common/src/test/java/art/arcane/iris/nativegen/NativeStructureVacuumParityTest.java index d058f39f8..b3af804d7 100644 --- a/adapters/modded-common/src/test/java/art/arcane/iris/nativegen/NativeStructureVacuumParityTest.java +++ b/adapters/modded-common/src/test/java/art/arcane/iris/nativegen/NativeStructureVacuumParityTest.java @@ -1,6 +1,7 @@ package art.arcane.iris.nativegen; import art.arcane.iris.engine.framework.NativeStartMemo; +import art.arcane.iris.engine.mantle.components.StructureModule; import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting; import net.minecraft.SharedConstants; import net.minecraft.core.BlockPos; @@ -55,7 +56,7 @@ public class NativeStructureVacuumParityTest { Map blocks = flatTerrain(area); Map original = new HashMap<>(blocks); - NativeStructureFitting.builtInModules().beforePieces(NativeStructureFitBridge.chunk(world(blocks), area, + NativeStructureFitting.ofModules(new StructureModule()).beforePieces(NativeStructureFitBridge.chunk(world(blocks), area, List.of(new NativeStructureFitBridge.FitTarget("test:vacuum", start, new NativeStartMemo("{\"terrain\":{\"mode\":\"VACUUM\"}}"))), (x, z) -> SURFACE_Y)); diff --git a/api/CONTRACTS.md b/api/CONTRACTS.md index f3d719707..0dd7444be 100644 --- a/api/CONTRACTS.md +++ b/api/CONTRACTS.md @@ -30,24 +30,25 @@ types that carry them and lists what the Iris adapter still owes. | Area a stage writes | `reach(blocks)`, `reach(PackReach)`, `writesMantle(...)` on stage definitions, `PackSettings` (with `resources()`, for a reach that depends on the size of the pack's objects), host `StageReach`, `ResolvedStage.reachBlocks`, `PipelineReach` | | Settings described for studio | `@Desc`, `@Required`, `@MinNumber`, `@MaxNumber`, `@MinItems`, `@Snippet`, `@Ref`/`Reference`, `@ResourceRef`, `FeatureRegistry.registerSettings`, host `LoadedPack.schema()` (`PackSchema`, `FeatureSchema`, `ObjectType`, `SchemaOption`, `ValueKind` with `HostKind`), `ModuleHost.describingHostTypesIn` | | Geometry and mantle registration | `FeatureRegistry`, host `ModuleRegistry`, `FeatureCatalog` | -| Block states and palettes | `BlockState`, `BlockRegistry` (`resolve(BlockSpec)`, `find(key)`, `blockEntity`, `hasTrait`, `oreFor`, `rotate(state, BlockTurn)`, `merge`, `withPropertyIfAccepted`, `matches`), `BlockTurn`, `BlockTrait` (with `STORAGE`), `BlockSpec`, `PaletteSpec` and `PaletteSampler` (`BlockRegistry.palette`) | +| Block states and palettes | `BlockState`, `BlockRegistry` (`resolve(BlockSpec)`, `find(key)`, `blockEntity`, `hasTrait`, `oreFor`, `rotate(state, BlockTurn)`, `tryRotate(state, BlockTurn)` (empty for a block that cannot face the turn, where `rotate` answers air), `merge`, `withPropertyIfAccepted`, `matches`), `BlockTurn`, `BlockTrait` (with `STORAGE`), `BlockSpec`, `PaletteSpec` and `PaletteSampler` (`BlockRegistry.palette`) | | A pack's objects | `PlaceableObject` (`name`, size, `center`, `geometry`), `PackObjects` (`object`, `sizeOf`, `scaled` with `ScaleMethod`, `smartBored`, `build`), `PackResources.objects()` | -| Placing through the pack's placement graph | `Placements.place(PlacementRun)` (`PackWorld.placements()`), `PlacementRun` (request, name, settings JSON, area, terrain, input, seed), `PlacementTerrain` (`recordPlacement` / `placementAt` with a `PlacementRecord`), `StructureVolumes`, `PlacedMarker`, `PlacementOutcome`; stages read `PlacementContext.placementTerrain()` and `input(type)`; mantle stages get a terrain from `MantleGenerationContext.placementTerrain()`; `RunningWorld.placementAt` reads what a placement recorded; `FeatureRegistry.registerPlacementType` names the type packs write placements as (host `FeatureCatalog.placementType()`, `PackSchema.placementType()`) | +| Placing through the pack's placement graph | `Placements.place(PlacementRun)` (`PackWorld.placements()`), `PlacementRun` (request, name, settings JSON, area, terrain, input, seed), `PlacementTerrain` (`recordPlacement` / `placementAt` with a `PlacementRecord`; `clearBlock` / `clearAttached` take a block, or its block entity, record and markers, back), `StructureVolumes`, `PlacedMarker`, `PlacementOutcome`; stages read `PlacementContext.placementTerrain()` and `input(type)`; mantle stages get a terrain from `MantleGenerationContext.placementTerrain()`; `RunningWorld.placementAt` reads what a placement recorded; `FeatureRegistry.registerPlacementType` names the type packs write placements as (host `FeatureCatalog.placementType()`, `PackSchema.placementType()`) | | Noise from pack-described styles | `NoiseStyle`, `StyledRange`, `PackResources.noise()`, `NoiseFactory`, `NoiseSampler` | | Values in settings | `BlockSpec`, `PaletteSpec`, `NoiseStyle`, `StyledRange`, `Range`, `BlockPosition`, `JigsawOverrides`, `Object` as `ValueKind.AnyKind` | -| Decisions over and fit of the platform's own structures | service `VanillaStructures` (`rule`, `starts`, `shift`, `reach`, `beforePieces`, `afterPieces`, `setup`), `VanillaStructureRule`, `VanillaStructureContext`, `VanillaStructureStart`, `VanillaStructureStartContext`, `VanillaStructureSetup`, `PlatformStart`, `StartMemo`, `StartReach`, `StructureFit` (`Start`, `Piece`, `ColumnVisitor`), `DecorationStep`, `TerrainAdaptation`, `PieceKind`, `TemplateCells`, `world.BlockAccess`, host `FeatureCatalog.registrations(service)` | +| Decisions over and fit of the platform's own structures | service `VanillaStructures` (`rule`, `starts`, `shift`, `reach`, `beforePieces`, `afterPieces`, `setup`), `VanillaStructureRule`, `VanillaStructureContext` (`world()`, empty when the host asks before any world exists), `VanillaStructureStart`, `VanillaStructureStartContext`, `VanillaStructureSetup`, `PlatformStart`, `StartMemo`, `StartReach`, `StructureFit` (`Start`, `Piece`, `ColumnVisitor`), `DecorationStep`, `TerrainAdaptation`, `PieceKind`, `TemplateCells`, `world.BlockAccess`, host `FeatureCatalog.registrations(service)` | | Pack-scoped resolution | `ResourceId` (`ofPackKey`, `ofPlatformKey`), `ContentKey`, `PackResources` (`find(kind, id)`, `require`, `ids(kind)`, `idOf`; kinds `BIOMES`, `REGIONS`, `OBJECTS`, `EXPRESSIONS`, `IMAGE_MAPS`), `PackBiome`, `PackRegion` (their children and biome lists are `Weighted` entries; `Weighted.pick` walks them the way the host does), `PackExpression`, `PackImageMap` | | Module-owned pack resources | `ResourceKind`, `FeatureRegistry.registerResourceKind`, `@ResourceRef`, host `ModuleHost.reservingFolders`, `FeatureCatalog.resourceKinds()`, `ResourceKindSchema`, `ValueKind.ResourceReferenceKind` | | Module-owned pack checks | `Validator`, `ValidationContext`, `Problem`, `Severity`, `Subject`, `FeatureRegistry.registerValidator`, host `FeatureCatalog.validators()` | | Per-world module state | `PackWorld` (`state`), `InvocationContext.world()`, host `WorldStates` | | Module lifecycle across loads, hotloads and reloads | `ModuleLifecycle`, `PackContext`, `FeatureRegistry.registerLifecycle`, host `FeatureCatalog.lifecycles()`, `LifecycleRunner` | -| Host questions answered by modules | `@Service`, `Providers`, `FeatureRegistry.registerService`, host `FeatureCatalog.services(type)` / `service(type)`; services `ObjectsAt`, `StructureLocator` (`LocateResult`, `startedStructures`, `locatableStarts`, `locateStart`, `ChunkFilter`), `SaplingGrowth`, `Loot` (with `shuffleSeed`), `BlockDrops`, `EntitySpawns`, `CaveBiomes`, `ProtectedFloor`, `AmbientEffects`, `VanillaFeatures` (`DecorationStep`); values `ItemDrop`, `EntitySpec`, `ItemRegistry` (`PackResources.items()`) | +| Host questions answered by modules | `@Service`, `Providers`, `FeatureRegistry.registerService`, host `FeatureCatalog.services(type)` / `service(type)`; modules ask each other with `PackWorld.services(type)`, `ValidationContext.services(type)` and `ToolPack.services(type)` and `PackResources.services(type)` (empty by default; host `ModuleWorld` forwards to the host's world); services `DatapackStructureImport` (`importAll`, `DatapackImportReport`), `ObjectsAt`, `StructureLocator` (`LocateResult`, `startedStructures`, `locatableStarts`, `locateStart`, `ChunkFilter`), `SaplingGrowth`, `Loot` (with `shuffleSeed`), `BlockDrops`, `EntitySpawns`, `CaveBiomes`, `ProtectedFloor`, `AmbientEffects`, `VanillaFeatures` (`DecorationStep`); values `ItemDrop`, `EntitySpec`, `ItemRegistry` (`PackResources.items()`) | | Terrain and settings sampling | `TerrainSampler`, `BiomeSample`, `TerrainSample`, `FeatureSettings` | | Dense chunk output | `Hunk`, `GenerationContext.blocks`, reference `ArrayHunk` | | Positions, boxes and faces | `com.volmit.geometry`: `BlockPosition`, `BlockBox`, `BlockFace` | | Sparse geometry | `GeneratedObject` | | Studio views of what a module builds | `com.volmit.tooling`: `ModuleSetup.tooling()` (`ToolingRegistry.registerView`), sealed `StudioView` (`SceneView` with `SceneEntry`, `BakeRun` (`Stage`), `BlockParts`, `PatternView` with `PatternEntry`, `PatternArea`, `BlockPattern`), `EditableSceneView` (`SceneFile`, `SceneCreation`, `NodeGraph`, `GraphNode` with `Link`, `NodeSettings`, `Edits`, `Addition`), `JsonText`, `JsonPath` (`Key`, `Index`), host `StudioViewRegistration` | -| Commands of a module | `com.volmit.tooling`: `ToolingRegistry.registerCommand`, immutable `Command` (`named`, `alias`, `describe`, `child`, `argument`, `runs`, `openToEveryone`), typed `Argument` (`word`, `text`, `integer`, `decimal`, `flag`, `choice`, `resource`, `registered`, `orElse`, `suggesting`), `CommandAction`, `CommandContext` (`get`, `sender`, `pack`, `world`, `platform`), plain-text `Sender`, `ToolPack` (`edit` with `PackEdit`, `outputFolder`, `objects` with `ObjectCodec`), host `CommandRegistration` in `FeatureCatalog.commands()` | +| Commands of a module | `com.volmit.tooling`: `ToolingRegistry.registerCommand`, immutable `Command` (`named`, `alias`, `describe`, `child`, `argument`, `runs`, `openToEveryone`), typed `Argument` (`word`, `text`, `integer`, `decimal`, `flag`, `choice`, `resource`, `registered`, `reading` with `Argument.Reader`, `orElse`, `suggesting`), `CommandAction`, `CommandContext` (`get`, `sender`, `pack`, `world`, `platform`, `platformStructures`), plain-text `Sender` (with `player()`), `PlatformStructures` (`templates`, `template` answering `StructureTemplate`, `structures`, `structureSets`, `jigsaw` answering `JigsawStructureInfo`, `pool` answering `TemplatePool` with `Member`, `Element`, `ConnectorSource`, `Connectors` and `JigsawConnector`, `supportsCapture`, `openCaptureArea` answering a closable `CaptureArea` whose `capture` answers `CapturedStructure`; `TemplateBlock`; readers throw `StructureAccessException`), `ToolPack` (`edit` with `PackEdit`, `outputFolder`, `objects` with `ObjectCodec`, `worlds`, `services`), host `CommandRegistration` in `FeatureCatalog.commands()` | +| Worlds a tool opens | `com.volmit.tooling.world`, exposed to pack modules by host `ExposedPackages`: `ToolWorlds` (`open`, `find`) with `ToolWorldSpec`, `ChunkPainter` and `ChunkCanvas`, `ToolWorld` (`players`, `owns`, `run`, `call`, `block`, `blockEntity`, `setBlock`, `loaded`, `repaint`, `close`), `ToolPlayer` (`targetBlock`, `teleport`, `creative`, `message`, `actionBar`, `sound`, `sidebar`, `particles`, `give` answering whether the item fitted, `held`, `openMenu`), `ToolWorldDenied` (what `open` completes with when the host refuses for a reason the user can fix; a tool reports the message and logs no stack trace), `ToolText` with `TextColor` (styled text, spans in a colour with bold, italic and strikethrough: item names and lore, menu titles, sidebar, chat and action bar; the host shows each span in its colour and style, an empty sidebar title keeps the platform's, and an item read back has plain text), `ToolItem`, `ToolMenu` with `MenuButton` and `MenuClick`, `Particle`, `ToolWorldListener` (`entered`, `left`, `teleported` for every arrival other than walking, at the time of the teleport, `moved`, `sneakToggled`, `used` with `ToolUse`, `blockChanging` with `BlockChange.Cause` and `BlockChange.changed`, `containerChanged` for a closed container inventory or a furnace or brewing stand that started, `command`, `chunkLoaded`, `closeRefusal`, `closing`, `closed`), `com.volmit.geometry.ChunkPos`; a tool world takes the pack's studio slot, so the host asks `closeRefusal` before it closes the world for another studio, the studio close command or a server stop, and waits for `closing` when another studio replaces it; every Y is the world's own; implemented by each platform adapter (Bukkit, and the modded adapters on the server thread) | | Buffered placement writes | `PlacementRequest`, `PlacementAccess`, host-owned `PlacementEdit` | | Typed generation and persistent storage | `mantle` package | @@ -239,7 +240,8 @@ running Iris is the pack publisher's responsibility. - Answer `PackWorld.running()` for a world the host runs, empty for a tool's world. Its `layout()` covers every column of the world (not one chunk), with the same values chunk stages read; its `settings()` are the settings at a column and a biome's declarations as chunk stages see them; `highest` is the platform's highest block now; `caveFloors` are - the cave floor markers of a chunk, in heights above the bottom; `sky()` is empty until the platform has the world. + the cave floor markers of a chunk, in heights above the bottom; `carvedAt` is the void the cave carver planned at a + block, empty where none was or when the host cannot read it; `sky()` is empty until the platform has the world. - Call the hooks with `LifecycleRunner`: `packLoaded` once per pack snapshot before its first world starts, `worldStarted` before the world generates anything, `warmUp` after it (on a thread of your choice, and wait for it before the world's first generation; report a failure naming the module and carry on), `worldStopped` when it stops. On a hotload, and when the pack's diff --git a/api/DESIGN.md b/api/DESIGN.md index eb9bed68b..da5b2752d 100644 --- a/api/DESIGN.md +++ b/api/DESIGN.md @@ -326,7 +326,8 @@ the part then gets the same `Class` objects the modules registered, where a sibl defines into a `ClassCastException`. The caller opens and closes it; closing it never closes the pack's loader. `ExposedPackages` carves out every `com.volmit.tooling.` package like `com.volmit.host`: only a part sees a -platform's tooling api. `com.volmit.tooling` itself, the neutral api, stays exposed. Enabling parts lazily, mounting their +platform's tooling api. `com.volmit.tooling` itself, the neutral api, stays exposed, and so does +`com.volmit.tooling.world`, the one neutral subpackage (Tool worlds). Enabling parts lazily, mounting their commands and listeners, and disabling them belongs to the platform adapter, not to the host. ### Namespaces @@ -1136,7 +1137,7 @@ each world a state store and tells modules when worlds start and stop. seeds its existing worlds were generated with, and every other id by the specification. - **The running world.** `PackWorld.running()` is the world as it runs now, for services and lifecycle hooks, which have no chunk to ask: the layout over every column as a `TerrainSampler`, the settings at a column and of a biome as - `FeatureSettings`, the highest block now, the cave floors the mantle marked, the sky (time and weather), the platform's + `FeatureSettings`, the highest block now, the cave floors the mantle marked, the void the cave carver planned at a block (`carvedAt`), the sky (time and weather), the platform's loot tables and whether it is a debug world. It reuses the chunk vocabulary instead of a second one: Iris's built-ins read the same through a facade (`LiveWorld`, with its own `Level`, `BiomeKind` and `Sky`), now deleted. Empty for a tool's world, which nothing runs. Which biome a block "is in" (cave below the surface, else surface) stays a module @@ -1236,6 +1237,12 @@ from a sapling, which drops a block has. A module answers such questions through - **Lookup.** The host asks the pack's catalog: `services(type)` for every provider, `service(type)` for the one provider of a `ONE` service. Looking up a type that is not marked fails, and so does `service` for a service that may have several providers. +- **Modules ask each other.** `PackWorld`, `ValidationContext` and `ToolPack` carry the same `services(type)`, so a + module reaches another module's service without a host extension. It returns the providers only, unscoped: the caller + passes the world it holds, and the provider's log is the host's concern when the host calls it, not the caller's. + `service(type)` for a `ONE` service is not repeated there, since `services(type).stream().findFirst()` says the same + and the api keeps one lookup. `PackResources.services(type)` is the same for code that holds only the resources (a + locator listing structures asks the modules that own the kinds), and is empty where the host cannot ask. - **Threading.** The host may call a provider from any thread, several at once. A provider that searches long (`StructureLocator.locate`) is called off the server's main thread. - **Loot, drops, entities, trees.** `Loot` (`ALL`) asks in two steps, which tables a container draws from and what a @@ -1310,11 +1317,11 @@ A module jar sees three things besides the JDK and its own pack's jars, and noth question, and none hands out an engine. **The extension point.** A built-in reaches its facade through one door: `PackWorld.extension(type)` for what belongs to -a world (Iris's structure host), `InvocationContext.extension(type)` for what belongs to one invocation (the +a world, `InvocationContext.extension(type)` for what belongs to one invocation (the platform chunk Iris generates), and `PackSettings.extension(type)` for what is worked out from a pack's settings before any world exists (how far a feature reaches). Each returns an `Optional`, empty by default, so a host offers what it has and a module states what it requires: -`world.extension(StructureHost.class).orElseThrow()`. Why one door: +`world.extension(Facade.class).orElseThrow()`. Why one door: - **No thread-locals.** Facades used to be bound to the current thread (`IrisChunk.current()`, `ObjectPlacement.current()`), which only worked while the host's own code had bound them and broke silently on another thread. The context a stage @@ -1337,7 +1344,7 @@ Iris's own built-ins hold to this at compile time: IrisModule is a build of its `com.volmit:iris-api`, VolmLib, Gson and the JDK, never `iris-host` or Iris, and its jar passes `ModuleJarCheck` before Iris bundles it. Iris depends on IrisModule, not the reverse. What the built-ins cannot do through the API they ask through the facades of item 3, which Iris implements; the classes that need Iris itself (the layout model, the -structure placer behind `StructureHost`) are Iris's and live there. +placement service) are Iris's and live there. ### Iris extensions, with the reason each is not api yet @@ -1352,10 +1359,6 @@ API now: `world.running()`, `world.seed(purpose)`, `TerrainSampler`, `FeatureSet the placement's JSON. Iris still reads it when it places an object itself with the pack's rules: the jigsaw placer, the structure place commands and its tests (`ModuleObjectPlacement`). Pasting an object is not one of them: a paste writes the object's blocks turned by a fixed angle (`IrisObject.paste`). It goes when the structures move into their module. -- **`StructureHost`** (world). Iris's structure assembler, locator and placer, and the loot tables of a structure for the - loot of its pieces. The structure model (structures, pools, pieces) is `iris:structure`'s own resource kinds, which Iris - registers with its own modules because its jigsaw studio reads them. Its surface is already API vocabulary; it goes when - the placer can write through the API. - **Random parameters (`RNG`) in these facades and `loot.LootResolver`**. They are the legacy streams existing worlds were generated from. They go when a world format change lets them be stage streams. @@ -1406,6 +1409,55 @@ the typed arguments; parsing, completion, permission and threads are the host's. required one, and anything after a rest-of-line argument when the tree is built. Two modules claiming one root name or alias fail the pack load, naming both. +## Tool worlds + +`com.volmit.tooling.world` is what an in-world tool, the jigsaw studio first, needs from a platform and nothing more. +It exists so the tool lives in a module and runs on every platform: a tool that imported Bukkit could not. + +- **The world is a studio world with a painter.** The host opens a studio world of the tool's pack and swaps its + generation for a `ChunkPainter`. That keeps one way to create, load, unload and delete worlds per platform, and the + platform's own height range, instead of a second kind of world. The cost is that heights are the pack dimension's. +- **Platform Y.** A tool world is not a `PackWorld`: it is the platform's world as players see it, so positions use the + world's own Y, and `minY()`/`maxY()` say its range. Converting to the height above the bottom would make every + position a tool shows a player disagree with the coordinates on their screen. +- **Painters are pure, listeners are threaded.** A painter is called from generation threads, so it reads shared state + only. A listener is called on the thread that owns the player or the position, so a module never needs a lock for + platform state, and `owns`/`run`/`call` exist for the rest. Splitting a world by region is the platform's right + (Folia); the api makes it visible instead of pretending to one thread. +- **Cancel by return value.** `blockChanging`, `used` and `command` return whether to allow. The host maps every platform + event onto `BlockChange.Cause` and cancels on `false`, so a tool freezes a bay or lets edits through without knowing which + event it was. The default for blocks is frozen: a world that forgets to answer cannot be damaged. +- **The host keeps the boring guarantees.** No natural spawning, weather, daylight, portals, vanilla structures or + features; players go back where they came from on close; the world is deleted on close and what is left is deleted at + the next start; an item's payload survives. A tool that had to do these itself would do them differently on every + platform. +- **Items, menus, sidebars are values.** `ToolItem`, `ToolMenu` and the sidebar lines are plain data the host draws with + its own widgets (VolmLib windows and scoreboards on Bukkit). Their text is `ToolText`: spans of a named colour + (`TextColor`) and a few styles, so no colour codes or components cross the api, and the host maps the spans onto + whatever its platform draws text with. +- **The platform's structures are one capability.** Registries, resource managers and structure managers differ by + platform and version, and some are reached only by reflection. `PlatformStructures` is the one door for the tools that + import them, and answers in api types (`BlockState`, `BlockEntityData`, `ResourceId`), so an importer holds only + model-building logic. Capturing a structure needs a scratch area that has to be removed, so it is a `CaptureArea` the + tool closes, and not a call that leaves the area to the platform. A platform without the capability gives + `CommandContext.platformStructures()` empty and the tool says so. +- **A platform may not have it.** `ToolWorlds.open` then returns a failed future and `Sender.player()` is empty, so a tool + tells its user instead of failing at class loading. The package is exposed to pack modules, unlike the platform + packages below `com.volmit.tooling`. +- **A refusal is not a fault.** `ToolWorldDenied` is how a host says no for a reason the user can fix (a pack with + blocking errors); a tool prints its message and logs nothing, so a mistake of the pack's author does not look like a bug + of the tool. +- **Answers a tool needs back.** `ToolPlayer.give` says whether the item fitted, because a menu that hands out a tool the + player never got would look like it worked; `targetBlock` exists because only the platform can ray-trace against the + blocks the player sees. `teleported` and `containerChanged` report what no `blockChanging` announces, so a tool that + protects an area hears every way in and every inventory that changed. +- **Importing a datapack is a service.** `DatapackStructureImport` (`FIRST`) lets the host, which installs datapacks and + knows nothing about jigsaw, hand the structures it found to whichever module turns them into pack resources. A pack + without a provider leaves them pending, like a retryable failure, and `DatapackImportReport.retryRequired` tells the + host which kind of failure it saw. +- **Reading a command word.** `Argument.reading` exists for a value that only the command's module can check, such as a + resource of a kind a neighbouring module registered; the built-in argument types cover what the host can check itself. + ## Not implemented - Host wiring, which lives in Iris: JSON decoding and validation, rendering `PackSchema` into Iris's schema and diff --git a/api/README.md b/api/README.md index cee336e72..c5493fb30 100644 --- a/api/README.md +++ b/api/README.md @@ -259,6 +259,9 @@ PackBiome dunes = resources.require(PackResources.BIOMES, resources.idOf("desert list, set or array of them, and studio completes the kind's keys. Packs write the key either way; a `ResourceId` field holds the pack's id of it. Built-in kinds may read into a class the host describes itself, as built-in settings may hold one. +- `PackResources.services(type)` gives the providers of a service that the pack's modules registered, for code that holds + only the resources, such as a locator listing structures. It asks the modules that own a kind what the kind means, as + `PackWorld.services` does; it is empty where the host cannot ask, and the list does not change for the snapshot. ``` Resource kind example:castle/keep of module example:castle from modules/castle.jar reads folder 'biomes', which the host reads itself; give the kind a folder of its own @@ -294,6 +297,9 @@ if (!outcome.isPlaced()) { `PlacementRecord`: the object's id, the module's number for this placement of it and, for a piece of a structure, the structure's id. A module may wrap the terrain to hold or filter writes; a mantle stage gets one for its invocation from `MantleGenerationContext.placementTerrain()`. +- `clearBlock(x, y, z)` takes a block a placement wrote back, so the terrain shows through; the block entity, placement + record and markers kept beside it stay until `clearAttached(x, y, z)` takes them back, whether or not a block is still + written there. A terrain that cannot take them back throws `UnsupportedOperationException`. - `name` labels the placement (the object's key). `settings` is the placement as the pack wrote it, a JSON object: the host reads from it the settings other modules declare at `Level.PLACEMENT`, so their stages see them like those of any other level. The module that owns the placement type declares it once in `setup`, with the JSON names of its own @@ -464,13 +470,19 @@ final class RuinsObjects implements ObjectsAt { values in what they return are `Optional`s. - A service that answers about the world as it runs, outside any chunk, reads `world.running()`: the layout over every column (`layout()`, a `TerrainSampler`), the settings at a column and what a biome declares (`settings()`), the - highest block now, the cave floors the mantle marked, the time and weather (`sky()`, empty until the platform has + highest block now, the cave floors the mantle marked, the void the cave carver planned at a block (`carvedAt`, in + heights above the bottom; empty where none was, when the chunk keeps no generation data any more and on a platform + that cannot read it), the time and weather (`sky()`, empty until the platform has the world), the platform's loot tables and whether the world is a debug (studio) world. It is empty for a tool's world, which nothing runs. - Each service says how several providers combine, with `@Service(Providers.X)`: `ALL` (the host asks every provider and combines the answers), `FIRST` (the host asks in order until one answers) or `ONE` (at most one provider per pack; a second fails the pack load, naming both modules). Providers are in module id order, each module's in registration order. +- A module asks another module's service with `services(type)`, on the `PackWorld` a stage or service gets, on the + `ValidationContext` a validator gets and on the `ToolPack` a command gets. It returns the pack's providers in that + order, empty when no module provides the service, and fails with `IllegalArgumentException` for an interface that is + not a `@Service`. Pass the world you hold to the provider's methods. | Service | Providers | What the host asks | | --- | --- | --- | @@ -484,6 +496,7 @@ final class RuinsObjects implements ObjectsAt { | `ProtectedFloor` | `ONE` | Whether the lowest layer of the world (height 0) belongs to the module that shapes the terrain, such as a bedrock floor it writes itself. The host then discards the blocks other placements and stages write there. Asked once per world; no provider protects nothing. | | `AmbientEffects` | `ALL` | The effects due for a player standing at a position: a `Sound`, `Particles`, `Command`s and a `Potion` per `Effect`, every random choice already made (offsets, scatter, duration). The host asks now and then, carries out the parts the platform has, and keeps a stronger potion effect the player already has. | | `VanillaStructures` | `ALL` | Rules, starts, shifts and reaches for the platform's own structures, fitting the terrain to the starts in one chunk through the `BlockAccess` the host hands over, and finding the starts a module makes of them (see Vanilla structures). | +| `DatapackStructureImport` | `FIRST` | Turns the structures and templates a datapack brought into editable resources of the pack once the host installed it (`importAll`, answering a `DatapackImportReport` of imported, skipped and failed sources, the bundles that landed and whether a failure may pass on a retry). Re-importing a source replaces what an earlier import made of it; with no provider the host leaves the datapack's structures pending. | | `VanillaFeatures` | `ALL` | Whether the platform runs its own placed features (ores, trees, plants, springs) over a world's terrain, and which decoration steps (`DecorationStep`) and features it skips there. Off unless a module turns it on; any module may refuse a step or a feature. Asked once per world, step and feature. | ``` @@ -567,6 +580,9 @@ private void info(CommandContext context) { constant written in lower case with `-`), `resource` (an id of a `ResourceKind` in the pack) and `registered` (an id in one of the platform's registries, by `Reference`). `orElse` makes an argument optional; an optional argument may not come before a required one. `suggesting` adds completions. Read a value with `context.get(argument)`. + `Argument.reading(name, reader)` takes one word and turns it into any value with a `Reader`, which throws + `IllegalArgumentException` saying why it cannot, for a value only the command's module can check, such as a resource of + a kind its neighbour registers; it completes nothing until `suggesting` gives it candidates. - The host resolves the pack before it parses the line: `pack=` taken out of the arguments, else the pack of the sender's world, else the pack of the sender's open studio, else it fails with `Name a pack: pack=`. A command exists only for packs whose jars contain its module. `context.pack()` is that pack, `context.world()` the sender's @@ -582,6 +598,76 @@ private void info(CommandContext context) { and writes pack objects in the host's object format (`ObjectCodec`). - A root command's name and each alias are root names. One that another module of the pack took fails the pack load, naming both modules. A host without commands, such as a build check, accepts the registration and ignores it. +- `Sender.player()` is the sender as a `ToolPlayer` (see Tool worlds), empty for the console and on a platform without + tool worlds. +- `CommandContext.platformStructures()` is the platform's structures for the tools that turn them into pack resources, + empty on a platform that has none. `PlatformStructures` lists the registered structures and structure sets and the + loadable templates (`templates`, `template`, `structures`, `structureSets`), reads a registered jigsaw structure and a + template pool (`jigsaw` answering `JigsawStructureInfo`, `pool` answering `TemplatePool` with its members, fallback and + the connectors of each element), and generates structures that have no template in a throwaway area + (`supportsCapture`, `openCaptureArea`: a closable `CaptureArea` places one structure after another in a scratch area + and `capture(structure, seed, maxSpan)` reads each back, empty when the box is wider or taller than `maxSpan`, and + `close` removes the area). A template or a captured structure is a list of `TemplateBlock` with + `BlockState` and `BlockEntityData`. A reader throws `StructureAccessException` when the platform's registries cannot be + read, and says whether asking again may help. + +## Tool worlds + +A tool that shows or edits what it builds in a world, such as a jigsaw studio, opens a tool world through +`ToolPack.worlds()`, in `com.volmit.tooling.world`. The package is neutral, so the same tool runs on every platform that +implements it; a platform without tool worlds answers with a failed future. +A host that refuses to open a world for a reason the user or the pack's author can fix, such as a pack with blocking +errors, completes `open` with `ToolWorldDenied`; its message is for the user, so a tool reports it and logs no stack trace. + +```java +ToolWorlds worlds = context.pack().worlds(); +ChunkPainter painter = (chunkX, chunkZ, canvas) -> { + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + canvas.set(x, canvas.minY() + 1, z, BlockState.parse("minecraft:smooth_stone")); + } + } +}; +worlds.open(new ToolWorldSpec("scratch", painter, new ToolWorldListener() { })) + .thenAccept(world -> context.sender().player().ifPresent(player -> + player.teleport(world, 8, world.minY() + 2, 8, 0, 0))); +``` + +- The world's chunks come only from the `ChunkPainter`, which the host calls from its generation threads, several at once, + and again for `ToolWorld.repaint`. A painter keeps no per-call state and does not keep the `ChunkCanvas`. Block entities + go through `canvas.set(..., BlockEntityData)` and are applied once the chunk is live. +- It is a studio world of the tool's pack with generation swapped for the painter, so its height range is the pack + dimension's (`minY()`, `maxY()`). Every Y in this package is the world's own Y, not the height above the bottom that + `PackWorld` counts. There is no natural mob spawning, weather, daylight cycle, portal, vanilla structure or feature. +- `ToolWorldListener` is how the tool hears about the world: players entering, leaving and moving to another block, + sneaking, using their hand (`ToolUse`), commands, loaded chunks, and every change to blocks (`BlockChange` with a + `Cause`). Each method returns `true` to allow or `false` to cancel where it decides, and `blockChanging` freezes the + world unless the tool overrides it. Calls come on the thread that owns the player or the position, and must return + quickly. +- A tool world takes the pack's studio slot: opening another studio, the studio close command and a server stop go + through the world. `closeRefusal()` lets the tool veto such a close with a message (an unsaved edit, a running + save), and `closing(by)` lets it finish its work before another studio replaces it; the host closes the world when + that future completes. +- On a platform that splits a world across threads (Folia), `ToolWorld.owns(at)` says whether the calling thread may + touch the block, `run`/`call` get a task there, and `block`, `blockEntity` and `setBlock` fail with + `IllegalStateException` elsewhere. `ToolPlayer` readers are valid on the player's own thread (`ToolPlayer.run`); its + changing methods are safe from any thread. +- `ToolPlayer` also gives items (`ToolItem`, whose payload the host keeps on the item), a chest-style menu (`ToolMenu` + of `MenuButton`s), chat messages, an action bar, a sidebar, sounds and dust `Particle`s. `give` answers whether the item + fitted; one that did not is neither given nor dropped. `targetBlock(maxDistance)` is the block the player looks at, + fluids not counting. `ToolWorld.close()` sends every player back to where they came + from and deletes the world. +- Styled text is `ToolText`, a list of spans with a `TextColor` (the sixteen named colours; none keeps the platform's + default) and bold, italic and strikethrough. Build it with `ToolText.builder().gray("Size: ").white("16x16x16").build()` + or `ToolText.plain`/`ToolText.colored`; `plainText()` drops the style. Item names and lore, menu titles, sidebar lines, + the action bar and `ToolPlayer.message` take it; an empty sidebar title keeps the platform's own. Text of a span is + shown as it is, so it needs no escaping. An item the host reads back carries its name and lore as plain text. +- `ToolWorldListener` also hears `teleported(player, to)` whenever a player arrives by other means than walking (join, + world change, respawn, a teleport or portal by anyone, inside the world too), at the time it happens, after `entered` + for a player coming in; `containerChanged(player, at)` when a container's inventory was closed or a furnace or brewing + stand started working, which no `blockChanging` announced; and `blockChanging` carries in `BlockChange.positions` what + a protected area is checked against and in `BlockChange.changed` the blocks whose content changes, which differ for a + piston. `ToolWorld.loaded(chunk)` asks the platform whether a chunk is loaded. ## Module jars @@ -686,8 +772,8 @@ The host loads a part through its own class loader, `ToolingPartLoader`, a child classes from the same jar copy, hands the platform's api packages to the platform's loader and everything else to the pack's loader, so a part gets the same `Class` objects the modules registered. The adapter opens it (`LoadedPack.openToolingPart`) and closes it before the pack; closing it leaves the pack's loader open. The generation -loader never sees `com.volmit.tooling.`, the platform parts of the tooling api; `com.volmit.tooling` itself stays -visible. +loader never sees `com.volmit.tooling.`, the platform parts of the tooling api; `com.volmit.tooling` itself and +the neutral `com.volmit.tooling.world` stay visible. ## Settings for studio @@ -880,6 +966,8 @@ Every method has a default that changes nothing, so a provider implements only w structure, `JigsawOverrides` for jigsaw structures and a `StartMemo`. The context gives the world (`PackWorld`) and a `TerrainSampler` over the chunk. Answer from the world and chunk only: the host asks again when it locates structures and when it checks starts it finds in the world. + `VanillaStructureContext.world()` is the world a rule decides for, empty when the host asks before any world exists, + such as for the setup of a dimension; a rule that needs the world answers its default then. - `shift(start, context)`: how many blocks one of the platform's own starts moves up or down before the host publishes it. A `PlatformStart` gives its bounds, whether the platform generates it underground, whether the host aligns it itself (ocean monuments to the sea, desert and jungle temples to the terrain; a shift then applies on top), diff --git a/api/api/src/main/java/com/volmit/block/BlockRegistry.java b/api/api/src/main/java/com/volmit/block/BlockRegistry.java index 16f8c9b77..eb7419acf 100644 --- a/api/api/src/main/java/com/volmit/block/BlockRegistry.java +++ b/api/api/src/main/java/com/volmit/block/BlockRegistry.java @@ -68,6 +68,17 @@ public interface BlockRegistry { */ BlockState rotate(BlockState state, BlockTurn turn); + /** + * Like {@link #rotate}, but says when the block cannot face the way it is turned instead of answering air, so a + * caller can tell a block that was dropped from air that stayed air. The default asks {@link #rotate} and takes air + * from a block that is not air for a block that was dropped. + */ + default Optional tryRotate(BlockState state, BlockTurn turn) { + BlockState turned = rotate(state, turn); + boolean dropped = hasTrait(turned, BlockTrait.AIR) && !hasTrait(state, BlockTrait.AIR); + return dropped ? Optional.empty() : Optional.of(turned); + } + /** {@code update} laid over {@code base}: the platform's merge of two states of one block, such as the sides of a * fence, wall or pane; {@code update} when the platform does not merge them. */ diff --git a/api/api/src/main/java/com/volmit/geometry/ChunkPos.java b/api/api/src/main/java/com/volmit/geometry/ChunkPos.java new file mode 100644 index 000000000..fe2329c08 --- /dev/null +++ b/api/api/src/main/java/com/volmit/geometry/ChunkPos.java @@ -0,0 +1,14 @@ +package com.volmit.geometry; + +import java.util.Objects; + +/** A chunk column, by chunk coordinates: block X and Z divided by 16, rounded down. */ +public record ChunkPos(int x, int z) { + private static final int CHUNK_SHIFT = 4; + + /** The chunk that contains {@code block}. */ + public static ChunkPos containing(BlockPosition block) { + Objects.requireNonNull(block, "block"); + return new ChunkPos(block.x() >> CHUNK_SHIFT, block.z() >> CHUNK_SHIFT); + } +} diff --git a/api/api/src/main/java/com/volmit/placement/PlacementTerrain.java b/api/api/src/main/java/com/volmit/placement/PlacementTerrain.java index 826886ca9..7f7dd89c7 100644 --- a/api/api/src/main/java/com/volmit/placement/PlacementTerrain.java +++ b/api/api/src/main/java/com/volmit/placement/PlacementTerrain.java @@ -48,6 +48,26 @@ public interface PlacementTerrain { */ void recordPlacement(int x, int y, int z, PlacementRecord placement); + /** + * Takes back the block written at the position, so the terrain shows through there. The block entity, placement + * record and markers kept beside it stay ({@link #clearAttached}). + * + * @throws UnsupportedOperationException when this terrain cannot take blocks back + */ + default void clearBlock(int x, int y, int z) { + throw new UnsupportedOperationException("This terrain cannot take blocks back"); + } + + /** + * Takes back the block entity, placement record and markers the host kept beside the block, whether or not a block + * is still written there. + * + * @throws UnsupportedOperationException when this terrain cannot take them back + */ + default void clearAttached(int x, int y, int z) { + throw new UnsupportedOperationException("This terrain cannot take what is kept beside a block back"); + } + /** The placement recorded at the block ({@link #recordPlacement}); empty when none is. */ Optional placementAt(int x, int y, int z); diff --git a/api/api/src/main/java/com/volmit/resource/PackResources.java b/api/api/src/main/java/com/volmit/resource/PackResources.java index 5215ba9d9..8ebc774de 100644 --- a/api/api/src/main/java/com/volmit/resource/PackResources.java +++ b/api/api/src/main/java/com/volmit/resource/PackResources.java @@ -69,6 +69,13 @@ public interface PackResources { return ResourceId.ofPackKey(packId().namespace(), key); } + /** The providers of {@code service} that the pack's modules registered, in module id order, so a module that holds only the + * resources, such as a locator listing structures, can ask the modules that own the kinds. Empty by default. + */ + default List services(Class service) { + return List.of(); + } + /** {@link #find} for a resource that must exist: a missing one throws NoSuchElementException naming kind and id. */ default T require(ResourceKind kind, ResourceId id) { return find(kind, id).orElseThrow(() -> new NoSuchElementException("Missing " + kind.id() + " resource: " + id)); diff --git a/api/api/src/main/java/com/volmit/tooling/Argument.java b/api/api/src/main/java/com/volmit/tooling/Argument.java index 26f14218c..375d8bd56 100644 --- a/api/api/src/main/java/com/volmit/tooling/Argument.java +++ b/api/api/src/main/java/com/volmit/tooling/Argument.java @@ -117,6 +117,15 @@ public final class Argument { }); } + /** One word that {@code reader} turns into the value, for a value only the command's module can check, such as a resource + * of a kind its module's neighbour registers. {@code reader} fails with an IllegalArgumentException that says why; the + * argument completes nothing until {@link #suggesting} gives it candidates. + */ + public static Argument reading(String name, Reader reader) { + Objects.requireNonNull(reader, "reader"); + return of(name, false, reader::read, (partial, context) -> List.of()); + } + /** An id registered in the platform's {@code registry}, such as {@link Reference#STRUCTURE}; completes * {@link PlatformRegistries#ids}. Written as the platform writes it, {@code minecraft:village_plains}, or without the * {@code minecraft:} namespace. @@ -244,6 +253,12 @@ public final class Argument { return registry.name().toLowerCase(Locale.ROOT).replace('_', ' '); } + /** Turns the word a sender typed into the argument's value. */ + @FunctionalInterface + public interface Reader { + T read(String text, CommandContext context); + } + private interface Parser { T parse(String text, CommandContext context); } diff --git a/api/api/src/main/java/com/volmit/tooling/CapturedStructure.java b/api/api/src/main/java/com/volmit/tooling/CapturedStructure.java new file mode 100644 index 000000000..2cb3c0182 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/CapturedStructure.java @@ -0,0 +1,18 @@ +package com.volmit.tooling; + +import com.volmit.geometry.BlockPosition; +import java.util.List; +import java.util.Objects; + +/** + * A structure the platform generated in a scratch area and read back. + * + * @param size the width, height and depth of the box the structure filled + * @param blocks every block in that box that is not plain air, with positions from the box's corner + */ +public record CapturedStructure(BlockPosition size, List blocks) { + public CapturedStructure { + Objects.requireNonNull(size, "size"); + blocks = List.copyOf(blocks); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/CommandContext.java b/api/api/src/main/java/com/volmit/tooling/CommandContext.java index 47b8ca570..a79f64633 100644 --- a/api/api/src/main/java/com/volmit/tooling/CommandContext.java +++ b/api/api/src/main/java/com/volmit/tooling/CommandContext.java @@ -30,4 +30,7 @@ public interface CommandContext { /** The platform's registries; empty when the host runs without a platform. */ Optional platform(); + + /** The structures the platform registers and the templates it loads; empty on a platform that does not offer them. */ + Optional platformStructures(); } diff --git a/api/api/src/main/java/com/volmit/tooling/DatapackImportReport.java b/api/api/src/main/java/com/volmit/tooling/DatapackImportReport.java new file mode 100644 index 000000000..5312a9eeb --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/DatapackImportReport.java @@ -0,0 +1,23 @@ +package com.volmit.tooling; + +import com.volmit.resource.ResourceId; +import java.util.Map; +import java.util.Objects; +import java.util.TreeMap; + +/** What {@link DatapackStructureImport#importAll} did. + * + * @param total the sources it tried + * @param imported the sources it imported + * @param skipped the sources it left as they were + * @param failed the sources it could not import + * @param importedBundles the bundle each fully imported source ended up as, by bundle name + * @param retryRequired whether a failure may pass when the import runs again, as opposed to the source being invalid + */ +public record DatapackImportReport(int total, int imported, int skipped, int failed, Map importedBundles, + boolean retryRequired) { + public DatapackImportReport { + Objects.requireNonNull(importedBundles, "importedBundles"); + importedBundles = java.util.Collections.unmodifiableMap(new TreeMap<>(importedBundles)); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/DatapackStructureImport.java b/api/api/src/main/java/com/volmit/tooling/DatapackStructureImport.java new file mode 100644 index 000000000..48cef1006 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/DatapackStructureImport.java @@ -0,0 +1,19 @@ +package com.volmit.tooling; + +import com.volmit.resource.ResourceId; +import com.volmit.service.Providers; +import com.volmit.service.Service; +import java.util.Collection; + +/** Turns the structures and templates a datapack brought into editable resources of the pack, once the host installed the + * datapack. A module that owns a kind of structure provides it; the host asks the pack's first provider and, when the pack has + * none, leaves the datapack's structures pending. Re-importing a source replaces what an earlier import made of it. + */ +@Service(Providers.FIRST) +public interface DatapackStructureImport { + /** Imports {@code structures} (ids of the platform's registered structures) and {@code templates} (ids of its structure + * templates) into {@code pack}, reporting progress to {@code sender}. A source that fails does not stop the others. + */ + DatapackImportReport importAll(ToolPack pack, PlatformStructures platform, Sender sender, + Collection structures, Collection templates); +} diff --git a/api/api/src/main/java/com/volmit/tooling/JigsawStructureInfo.java b/api/api/src/main/java/com/volmit/tooling/JigsawStructureInfo.java new file mode 100644 index 000000000..2f61f1c64 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/JigsawStructureInfo.java @@ -0,0 +1,23 @@ +package com.volmit.tooling; + +import com.volmit.resource.ResourceId; +import java.util.Objects; + +/** + * What a registered jigsaw structure says about itself. + * + * @param startPool the template pool the structure starts from + * @param maxDepth how many pieces deep the structure grows + * @param maxDistance how far from its centre the structure may reach, in blocks; the horizontal reach when the platform + * keeps a horizontal and a vertical one + * @param gameVersion the platform's own version string, which tools record as where the structure came from + * @param shuffleSeed what the platform seeds its shuffle of the connectors of this structure's pool elements with, so + * that reading the same structure twice lists them in the same order + */ +public record JigsawStructureInfo(ResourceId startPool, int maxDepth, int maxDistance, String gameVersion, + long shuffleSeed) { + public JigsawStructureInfo { + Objects.requireNonNull(startPool, "startPool"); + Objects.requireNonNull(gameVersion, "gameVersion"); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/PlatformStructures.java b/api/api/src/main/java/com/volmit/tooling/PlatformStructures.java new file mode 100644 index 000000000..4df13c77b --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/PlatformStructures.java @@ -0,0 +1,63 @@ +package com.volmit.tooling; + +import com.volmit.resource.ResourceId; +import java.util.List; +import java.util.Optional; + +/** + * The structures a platform registers and the templates it loads, for the tools that turn them into pack resources. + * A command reaches it as {@link CommandContext#platformStructures()}, which is empty on a platform without it. Every + * method may take a while and reads the running server, so a tool calls them from its worker thread and never + * from the platform's main or region thread. + * + *

Each reader that cannot answer because the platform's registries cannot be read throws a + * {@link StructureAccessException}; a reader that answers empty means the platform has no such thing. + */ +public interface PlatformStructures { + /** The ids of the structure templates the platform can load, such as {@code minecraft:village/plains/houses/plains_small_house_1}, in id order. */ + List templates(); + + /** The template {@code id}; empty when the platform has none or it holds no palette. */ + Optional template(ResourceId id); + + /** The ids of the structures the platform registers, in id order. */ + List structures(); + + /** The ids of the structure sets the platform registers, in id order. */ + List structureSets(); + + /** What {@code structure} says about itself; empty when it is no jigsaw structure or is not registered. */ + Optional jigsaw(ResourceId structure); + + /** The template pool {@code pool}; empty when it is not registered. */ + Optional pool(ResourceId pool); + + /** Whether the platform can generate a structure in a scratch area and read it back, which {@link #openCaptureArea} needs. */ + boolean supportsCapture(); + + /** + * Opens a throwaway area to generate structures in, for the structures that have no template. Close it when the + * captures are done; it is removed then. + * + * @param sender where the platform reports what it does while it opens and removes the area + * @return the area; empty when it could not be opened, which the platform has told the sender + */ + Optional openCaptureArea(Sender sender); + + /** A throwaway area structures are generated in, one after another. */ + interface CaptureArea extends AutoCloseable { + /** + * Generates {@code structure} in the next free spot of the area and reads it back. + * + * @param seed what the platform generates the structure with + * @param maxSpan the widest and tallest box, in blocks, the platform reads back + * @return the structure; empty when it placed nothing capturable here, such as one wider than {@code maxSpan} + * @throws IllegalStateException when the platform could not place it, with the reason + */ + Optional capture(ResourceId structure, long seed, int maxSpan); + + /** Removes the area. */ + @Override + void close(); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/Sender.java b/api/api/src/main/java/com/volmit/tooling/Sender.java index d387eec39..b77b8d731 100644 --- a/api/api/src/main/java/com/volmit/tooling/Sender.java +++ b/api/api/src/main/java/com/volmit/tooling/Sender.java @@ -1,5 +1,6 @@ package com.volmit.tooling; +import com.volmit.tooling.world.ToolPlayer; import java.util.Optional; /** @@ -21,4 +22,7 @@ public interface Sender { /** The platform's own sender as {@code type}, such as a Bukkit {@code Player}; empty when it is not one. For platform parts. */ Optional extension(Class type); + + /** The sender as a player of the platform; empty for the console, a command block, or a platform without tool worlds. */ + Optional player(); } diff --git a/api/api/src/main/java/com/volmit/tooling/StructureAccessException.java b/api/api/src/main/java/com/volmit/tooling/StructureAccessException.java new file mode 100644 index 000000000..ae4900049 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/StructureAccessException.java @@ -0,0 +1,28 @@ +package com.volmit.tooling; + +/** + * What a {@link PlatformStructures} reader throws when the platform cannot answer, such as a server version whose + * registries it cannot read. The message is written for the sender who ran the tool, so a tool shows it as it is. + */ +public final class StructureAccessException extends RuntimeException { + private final boolean retryable; + + /** + * @param message what went wrong, as the sender should read it + * @param retryable whether asking again later may succeed, as for a registry that was not ready yet + */ + public StructureAccessException(String message, boolean retryable) { + super(message); + this.retryable = retryable; + } + + public StructureAccessException(String message, boolean retryable, Throwable cause) { + super(message, cause); + this.retryable = retryable; + } + + /** Whether asking again later may succeed. */ + public boolean retryable() { + return retryable; + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/StructureTemplate.java b/api/api/src/main/java/com/volmit/tooling/StructureTemplate.java new file mode 100644 index 000000000..18c9251ec --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/StructureTemplate.java @@ -0,0 +1,20 @@ +package com.volmit.tooling; + +import com.volmit.geometry.BlockPosition; +import java.util.List; +import java.util.Objects; + +/** + * A structure template the platform loads, such as a vanilla {@code .nbt}: its size and the blocks of its first palette. + * + * @param size the template's width, height and depth in blocks + * @param paletteCount how many palettes the template has; only the first is in {@code blocks} + * @param entityCount how many entities the template holds, which tools do not read + * @param blocks the blocks of the first palette, with positions from the template's corner + */ +public record StructureTemplate(BlockPosition size, int paletteCount, int entityCount, List blocks) { + public StructureTemplate { + Objects.requireNonNull(size, "size"); + blocks = List.copyOf(blocks); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/TemplateBlock.java b/api/api/src/main/java/com/volmit/tooling/TemplateBlock.java new file mode 100644 index 000000000..c002c45eb --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/TemplateBlock.java @@ -0,0 +1,33 @@ +package com.volmit.tooling; + +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import java.util.Objects; +import java.util.Optional; + +/** + * One block of a {@link StructureTemplate} or {@link CapturedStructure}. + * + * @param position where the block is, from the template's corner + * @param state the block as the platform stores it; a jigsaw block is the jigsaw block itself + * @param blockEntity the block entity data of a block that has some; empty for a jigsaw block, which tools resolve + * through {@code jigsawFinalState} + * @param jigsawFinalState what a jigsaw block turns into when its piece is placed: the {@code final_state} the block + * names, as the platform writes it; empty for any other block and for a jigsaw block that names + * none + */ +public record TemplateBlock(BlockPosition position, BlockState state, Optional blockEntity, + Optional jigsawFinalState) { + public TemplateBlock { + Objects.requireNonNull(position, "position"); + Objects.requireNonNull(state, "state"); + Objects.requireNonNull(blockEntity, "blockEntity"); + Objects.requireNonNull(jigsawFinalState, "jigsawFinalState"); + } + + /** A block with no jigsaw final state. */ + public static TemplateBlock of(BlockPosition position, BlockState state, Optional blockEntity) { + return new TemplateBlock(position, state, blockEntity, Optional.empty()); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/TemplatePool.java b/api/api/src/main/java/com/volmit/tooling/TemplatePool.java new file mode 100644 index 000000000..81d3b5597 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/TemplatePool.java @@ -0,0 +1,154 @@ +package com.volmit.tooling; + +import com.volmit.geometry.BlockFace; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.function.LongSupplier; + +/** + * A jigsaw template pool the platform registers: what its entries are and where it falls back to. + * + * @param members the entries in the order the platform lists them, every one of them, so the count is the + * pool's own size + * @param fallback the pool used when none of the entries fits; empty when it has none + * @param fallbackFailure why the fallback could not be read, when it could not; the fallback is then empty + */ +public record TemplatePool(List members, Optional fallback, Optional fallbackFailure) { + public TemplatePool { + members = List.copyOf(members); + Objects.requireNonNull(fallback, "fallback"); + Objects.requireNonNull(fallbackFailure, "fallbackFailure"); + } + + /** One entry of a pool. */ + public sealed interface Member permits Absent, Unreadable, Element { + } + + /** An entry that holds no element. */ + public record Absent() implements Member { + } + + /** Which part of an entry could not be read. */ + public enum Part { + /** The element and its weight. */ + ENTRY, + /** Where the element's template is. */ + TEMPLATE_LOCATION + } + + /** + * An entry the platform could not read. + * + * @param part what could not be read + * @param detail why, as the platform reports it + */ + public record Unreadable(Part part, String detail) implements Member { + public Unreadable { + Objects.requireNonNull(part, "part"); + Objects.requireNonNull(detail, "detail"); + } + } + + /** + * One element of a pool with its weight. + * + * @param weight how likely the element is among the entries; at least 1 + * @param type the platform's name for the kind of element, such as {@code SinglePoolElement}, which tells an + * empty element from one a tool cannot convert when {@code template} is empty + * @param template the template the element places; when the platform wraps several elements in a list, the + * first one that places a template; empty for an element that places none + * @param listLevels how many list elements wrap the one {@code template} came from + * @param omittedElements how many elements those lists held besides the one {@code template} came from + * @param connectors reads the jigsaw connectors of the element + */ + public record Element(int weight, String type, Optional template, int listLevels, int omittedElements, + ConnectorSource connectors) implements Member { + public Element { + Objects.requireNonNull(type, "type"); + Objects.requireNonNull(template, "template"); + Objects.requireNonNull(connectors, "connectors"); + } + } + + /** Reads the jigsaw connectors of one pool element. */ + @FunctionalInterface + public interface ConnectorSource { + /** + * The connectors of the element, in the order the platform shuffles them with a seed. + * + * @param shuffleSeeds gives the seed to shuffle with; the platform asks only when it shuffles, so the caller's + * random sequence advances once for each element that has connectors to shuffle + * @throws StructureAccessException when the platform cannot read the connectors at all + */ + Connectors read(LongSupplier shuffleSeeds); + } + + /** Whether the platform could list an element's connectors. */ + public enum Availability { + READ, + /** The platform's version has no way to list them. */ + UNAVAILABLE, + /** The platform answered with no list. */ + NO_COLLECTION + } + + /** + * The connectors of an element. + * + * @param availability whether {@code connectors} were listed + * @param connectors one entry for each jigsaw block, in the platform's shuffled order + */ + public record Connectors(Availability availability, List connectors) { + public Connectors { + Objects.requireNonNull(availability, "availability"); + connectors = List.copyOf(connectors); + } + } + + /** One jigsaw block of an element. */ + public sealed interface Connector permits JigsawConnector, UnreadableConnector { + } + + /** + * A jigsaw block the platform could not convert. + * + * @param detail why, as the platform reports it + */ + public record UnreadableConnector(String detail) implements Connector { + public UnreadableConnector { + Objects.requireNonNull(detail, "detail"); + } + } + + /** + * A jigsaw block. + * + * @param position where it is, from the element's corner + * @param front the side it connects through + * @param top the side its top faces, which fixes the roll of a rollable joint + * @param pool the pool it pulls its next piece from; empty when it names none + * @param name the name other blocks target + * @param target the name of the blocks it connects to + * @param aligned whether the joint keeps the pieces aligned rather than letting them roll + * @param finalState the block it turns into once it connects, as the platform writes block states; empty when + * the block names none + * @param selectionPriority which block is tried first + * @param placementPriority which connected piece is expanded first + */ + public record JigsawConnector(BlockPosition position, BlockFace front, BlockFace top, Optional pool, + String name, String target, boolean aligned, Optional finalState, + int selectionPriority, int placementPriority) implements Connector { + public JigsawConnector { + Objects.requireNonNull(position, "position"); + Objects.requireNonNull(front, "front"); + Objects.requireNonNull(top, "top"); + Objects.requireNonNull(pool, "pool"); + Objects.requireNonNull(name, "name"); + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(finalState, "finalState"); + } + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/ToolPack.java b/api/api/src/main/java/com/volmit/tooling/ToolPack.java index 073e2d8c0..794f51863 100644 --- a/api/api/src/main/java/com/volmit/tooling/ToolPack.java +++ b/api/api/src/main/java/com/volmit/tooling/ToolPack.java @@ -3,8 +3,10 @@ package com.volmit.tooling; import com.volmit.ModuleLog; import com.volmit.config.PackSettings; import com.volmit.resource.PackResources; +import com.volmit.tooling.world.ToolWorlds; import java.io.IOException; import java.nio.file.Path; +import java.util.List; /** * A pack as tools see it: its current resources, its folder, and the one way to change files in it. Tools are file tools, @@ -32,4 +34,17 @@ public interface ToolPack { /** The log of the module that asked. */ ModuleLog log(); + + /** The worlds this pack's tools open on the platform. */ + ToolWorlds worlds(); + + /** + * The providers of {@code service} that the pack's modules registered, in module id order and each module's in the + * order it registered them; empty when no module provides it. This is how a module asks another module's service, + * such as a structure tool asking who knows a structure. + * + * @param service an interface marked {@link com.volmit.service.Service} + * @throws IllegalArgumentException when {@code service} is not such an interface + */ + List services(Class service); } diff --git a/api/api/src/main/java/com/volmit/tooling/world/BlockChange.java b/api/api/src/main/java/com/volmit/tooling/world/BlockChange.java new file mode 100644 index 000000000..027fd2aa8 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/BlockChange.java @@ -0,0 +1,73 @@ +package com.volmit.tooling.world; + +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +/** + * Something that is about to change blocks in a tool world, handed to {@link ToolWorldListener#blockChanging}. + * + * @param cause what is changing them + * @param positions the blocks a protected area is checked against: the block a player breaks or places, the blocks an + * explosion would destroy one at a time, the blocks a piston moves with the blocks they leave and + * enter. Empty only when {@code changed} is not, such as a piston that moves nothing. + * @param changed the blocks whose content changes, which a tool may want to save; the same as {@code positions} + * unless the cause touches other blocks than it is checked against, as a piston does with its own block + * @param player the player behind it, when there is one + * @param placed the state being placed, for {@link Cause#PLACE} and {@link Cause#BUCKET}; empty when it is not known + */ +public record BlockChange( + Cause cause, + List positions, + List changed, + Optional player, + Optional placed +) { + /** What changes a block. */ + public enum Cause { + /** A player places a block. */ + PLACE, + /** A player breaks a block. */ + BREAK, + /** A player fills or empties a bucket. */ + BUCKET, + /** A block forms, fades or spreads by itself, such as ice, snow, grass or coral. */ + PHYSICS, + /** Water or lava flows. */ + FLUID, + /** A plant or a sapling grows. */ + GROWTH, + /** A block burns. */ + FIRE, + /** Redstone power changes; cancelling keeps the old power. */ + REDSTONE, + /** A piston pushes or pulls blocks. */ + PISTON, + /** An explosion destroys blocks. */ + EXPLOSION, + /** A mob or a falling block changes a block. */ + ENTITY, + /** A player or a hopper changes what a container block holds. */ + CONTAINER, + /** A furnace, a brewing stand, a crafter or a dispenser works. */ + MACHINE + } + + public BlockChange { + Objects.requireNonNull(cause, "cause"); + positions = List.copyOf(positions); + changed = List.copyOf(changed); + if (positions.isEmpty() && changed.isEmpty()) { + throw new IllegalArgumentException("A block change names at least one block"); + } + Objects.requireNonNull(player, "player"); + Objects.requireNonNull(placed, "placed"); + } + + /** A change that is checked against the blocks it changes. */ + public BlockChange(Cause cause, List positions, Optional player, Optional placed) { + this(cause, positions, positions, player, placed); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/ChunkCanvas.java b/api/api/src/main/java/com/volmit/tooling/world/ChunkCanvas.java new file mode 100644 index 000000000..7b97bb5b1 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/ChunkCanvas.java @@ -0,0 +1,30 @@ +package com.volmit.tooling.world; + +import com.volmit.block.BlockState; +import com.volmit.object.BlockEntityData; + +/** + * The chunk a {@link ChunkPainter} paints: blocks only, with the host's own block-entity handling behind it. A canvas + * starts empty (air) and is valid only while {@link ChunkPainter#paint} runs; the host never lets a painter keep it. + * + *

X and Z are local to the chunk, 0 to 15. Y is the world's own Y, from {@link #minY()} up to but not including + * {@link #maxY()}, as {@link ToolWorld#minY()} and {@link ToolWorld#maxY()} report it. A coordinate outside these + * ranges throws {@link IllegalArgumentException}. + */ +public interface ChunkCanvas { + /** The lowest Y a block can have in this world. */ + int minY(); + + /** The first Y above the world; the highest block has Y {@code maxY() - 1}. */ + int maxY(); + + /** Puts {@code state} at the position, replacing what the painter put there before. */ + void set(int x, int y, int z, BlockState state); + + /** + * Puts {@code state} at the position with {@code data} as its block entity, such as the contents of a chest or the + * lines of a sign. The host applies the entity once the chunk is live; a state that has no block entity on the + * platform ignores the data. Data in a format the host does not read fails with {@link IllegalArgumentException}. + */ + void set(int x, int y, int z, BlockState state, BlockEntityData data); +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/ChunkPainter.java b/api/api/src/main/java/com/volmit/tooling/world/ChunkPainter.java new file mode 100644 index 000000000..f1efb3636 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/ChunkPainter.java @@ -0,0 +1,16 @@ +package com.volmit.tooling.world; + +/** + * Where the chunks of a tool world come from: the host asks it for every chunk it generates, and for the ones + * {@link ToolWorld#repaint} names. Nothing else shapes a tool world's terrain. + * + *

The host calls {@code paint} from its generation threads, several at once, and again for a chunk whenever it + * repaints it, so a painter holds no per-call state and reads what it paints from state that is safe to read from any + * thread. It must return quickly and must not call back into the {@link ToolWorld} that is waiting for it. A painter + * that throws leaves its chunk empty and the failure in the host's log. + */ +@FunctionalInterface +public interface ChunkPainter { + /** Paints chunk {@code chunkX}, {@code chunkZ} onto {@code canvas}. */ + void paint(int chunkX, int chunkZ, ChunkCanvas canvas); +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/MenuButton.java b/api/api/src/main/java/com/volmit/tooling/world/MenuButton.java new file mode 100644 index 000000000..2f8f97a22 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/MenuButton.java @@ -0,0 +1,21 @@ +package com.volmit.tooling.world; + +import java.util.Objects; +import java.util.function.Consumer; + +/** + * One slot of a {@link ToolMenu}. + * + * @param slot the slot counted along the rows from the top left, 0 to 8 in the first row, 9 to 17 in the second + * @param icon what the slot shows + * @param action called on the player's thread for every click on the slot; it must return quickly + */ +public record MenuButton(int slot, ToolItem icon, Consumer action) { + public MenuButton { + if (slot < 0) { + throw new IllegalArgumentException("A menu slot is not negative: " + slot); + } + Objects.requireNonNull(icon, "icon"); + Objects.requireNonNull(action, "action"); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/MenuClick.java b/api/api/src/main/java/com/volmit/tooling/world/MenuClick.java new file mode 100644 index 000000000..520ee7233 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/MenuClick.java @@ -0,0 +1,20 @@ +package com.volmit.tooling.world; + +import java.util.Objects; + +/** + * A click on a {@link MenuButton}. A left click has {@code right} false; holding shift is {@code shift}; the middle + * mouse button is {@code middle}, with {@code right} and {@code shift} false. + * + * @param player the player who clicked + */ +public record MenuClick(ToolPlayer player, boolean right, boolean shift, boolean middle) { + public MenuClick { + Objects.requireNonNull(player, "player"); + } + + /** A left or right click, with or without shift. */ + public MenuClick(ToolPlayer player, boolean right, boolean shift) { + this(player, right, shift, false); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/Particle.java b/api/api/src/main/java/com/volmit/tooling/world/Particle.java new file mode 100644 index 000000000..0faa57655 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/Particle.java @@ -0,0 +1,21 @@ +package com.volmit.tooling.world; + +/** + * One dust particle at a position of a tool world, for {@link ToolPlayer#particles}. The position is in world + * coordinates with the world's own Y. + * + * @param rgb the colour as {@code 0xRRGGBB} + * @param size the size of the speck, above zero + */ +public record Particle(double x, double y, double z, int rgb, float size) { + private static final int MAX_RGB = 0xFFFFFF; + + public Particle { + if (rgb < 0 || rgb > MAX_RGB) { + throw new IllegalArgumentException("A particle colour is 0xRRGGBB: " + Integer.toHexString(rgb)); + } + if (!(size > 0)) { + throw new IllegalArgumentException("A particle size is above zero: " + size); + } + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/TextColor.java b/api/api/src/main/java/com/volmit/tooling/world/TextColor.java new file mode 100644 index 000000000..aa643f065 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/TextColor.java @@ -0,0 +1,35 @@ +package com.volmit.tooling.world; + +/** + * The sixteen named colours of Minecraft text, in the order of their formatting codes. Every platform shows them the same + * way, so a tool picks a colour by name and the host maps it. + */ +public enum TextColor { + BLACK('0'), + DARK_BLUE('1'), + DARK_GREEN('2'), + DARK_AQUA('3'), + DARK_RED('4'), + DARK_PURPLE('5'), + GOLD('6'), + GRAY('7'), + DARK_GRAY('8'), + BLUE('9'), + GREEN('a'), + AQUA('b'), + RED('c'), + LIGHT_PURPLE('d'), + YELLOW('e'), + WHITE('f'); + + private final char code; + + TextColor(char code) { + this.code = code; + } + + /** The character that follows the formatting sign in Minecraft's legacy codes, such as {@code 'a'} for green. */ + public char code() { + return code; + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/ToolItem.java b/api/api/src/main/java/com/volmit/tooling/world/ToolItem.java new file mode 100644 index 000000000..77117f7a9 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolItem.java @@ -0,0 +1,29 @@ +package com.volmit.tooling.world; + +import com.volmit.resource.ResourceId; +import java.util.List; +import java.util.Objects; + +/** + * An item a tool hands to a player, or a menu shows as an icon: the platform's item, a name and lore, and a payload the + * host keeps on the item. The host guarantees the payload survives on the item, as a string in the item's persistent + * data on Bukkit and as custom data on modded platforms, and hands it back through {@link ToolPlayer#held()} and + * {@link ToolUse#item()}. A tool tells its own items apart by their payload. + * + *

The host shows the name and the lore the way the platform shows text a plugin sets on an item, in the colours of + * the {@link ToolText}. An item the host reads back from a player carries its name and lore as plain text. + * + * @param item the platform's item, such as {@code minecraft:stick} + * @param name the display name; empty keeps the item's own name + * @param lore the lines under the name + * @param glowing whether the item shows the enchantment glint + * @param payload what the tool keeps on the item; empty for nothing + */ +public record ToolItem(ResourceId item, ToolText name, List lore, boolean glowing, String payload) { + public ToolItem { + Objects.requireNonNull(item, "item"); + Objects.requireNonNull(name, "name"); + Objects.requireNonNull(payload, "payload"); + lore = List.copyOf(lore); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/ToolMenu.java b/api/api/src/main/java/com/volmit/tooling/world/ToolMenu.java new file mode 100644 index 000000000..284a3342e --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolMenu.java @@ -0,0 +1,41 @@ +package com.volmit.tooling.world; + +import java.util.HashSet; +import java.util.List; +import java.util.Objects; + +/** + * A chest-style menu a tool opens for a player with {@link ToolPlayer#openMenu}. Menus are the host's own inventory + * windows, so they work the same on every platform; a tool that wants another page opens a new menu from a click. + * + * @param title the title; the host shortens it to what the window can show + * @param rows the number of rows, 1 to {@value #MAX_ROWS} + * @param buttons the slots that do something; the others show a filler. No slot is used twice and every slot is inside + * the rows. + * @param onClose called on the player's thread when the menu closes for any reason: the player closed it, the world + * closed, or the tool closed or replaced it. Null stands for nothing to do. + */ +public record ToolMenu(ToolText title, int rows, List buttons, Runnable onClose) { + public static final int MAX_ROWS = 6; + public static final int SLOTS_PER_ROW = 9; + + public ToolMenu { + Objects.requireNonNull(title, "title"); + if (rows < 1 || rows > MAX_ROWS) { + throw new IllegalArgumentException("A menu has 1 to " + MAX_ROWS + " rows: " + rows); + } + buttons = List.copyOf(buttons); + var used = new HashSet(); + for (var button : buttons) { + if (button.slot() >= rows * SLOTS_PER_ROW) { + throw new IllegalArgumentException("Slot " + button.slot() + " is outside a menu of " + rows + " rows"); + } + if (!used.add(button.slot())) { + throw new IllegalArgumentException("Slot " + button.slot() + " is used twice"); + } + } + if (onClose == null) { + onClose = () -> { }; + } + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/ToolPlayer.java b/api/api/src/main/java/com/volmit/tooling/world/ToolPlayer.java new file mode 100644 index 000000000..6e63f8f28 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolPlayer.java @@ -0,0 +1,99 @@ +package com.volmit.tooling.world; + +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.Sender; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +/** + * A player as a tool sees them. Positions are block positions of the world the player stands in, with that world's own Y. + * + *

Threads. The readers ({@link #world}, {@link #position}, {@link #yaw}, {@link #pitch}, {@link #sneaking}, + * {@link #held}) are valid only on the thread that owns the player, which is where every {@link ToolWorldListener} call + * about them and every {@link #run} task runs. The methods that change the player ({@link #teleport} and the ones + * below it) are safe from any thread: the host moves the change onto the owning thread. A player stays one object for + * as long as they are online, though {@link #id()} is the safer key for a map. + */ +public interface ToolPlayer { + UUID id(); + + /** The player's name as the platform shows it. */ + String name(); + + /** The player as a command sender; its messages are plain text, delivered on the thread the platform needs. For styled text use {@link #message}. */ + Sender sender(); + + /** The tool world the player stands in; empty when they stand in another world, even another pack's tool world. */ + Optional world(); + + BlockPosition position(); + + /** The direction the player faces, in degrees, as the platform counts them. */ + float yaw(); + + float pitch(); + + boolean sneaking(); + + /** + * The block the player looks at within {@code maxDistance} blocks, fluids not counting; empty when they look at none. + * Like the other readers, valid only on the thread that owns the player. + */ + Optional targetBlock(int maxDistance); + + /** Runs {@code task} on the thread that owns the player: at once when the caller is that thread, else later. */ + void run(Runnable task); + + /** + * Moves the player to the position in {@code world} and completes with whether they arrived. The host remembers + * where a player came from when they enter a tool world from outside one, and {@link ToolWorld#close()} sends them + * back there. + */ + CompletableFuture teleport(ToolWorld world, double x, double y, double z, float yaw, float pitch); + + /** + * Puts the player in creative mode when {@code on}, remembering the mode they had; turns it off by restoring that + * mode. The host also restores it when it sends the player out of a tool world. + */ + void creative(boolean on); + + /** Sends {@code text} to the player's chat, in its colours. */ + void message(ToolText text); + + /** Shows {@code text} above the hotbar. */ + void actionBar(ToolText text); + + /** Plays {@code sound}, such as {@code minecraft:block.note_block.pling}, to this player only, where they stand. */ + void sound(ResourceId sound, float volume, float pitch); + + /** + * Shows a sidebar with {@code title} and {@code lines}, top to bottom, replacing the one this player has from a tool. + * An empty title keeps the platform's own sidebar title. The sidebar goes away when the player leaves the tool world. + */ + void sidebar(ToolText title, List lines); + + /** Removes the sidebar {@link #sidebar} showed. */ + void hideSidebar(); + + /** Shows dust particles to this player only. Positions are in the world the player stands in. */ + void particles(List dust); + + /** + * Puts {@code item} in the player's inventory, in the first free slot, and returns whether it fitted. An item that did + * not fit is not given and not dropped. Called off the player's own thread, the item is given later and the answer + * is true. + */ + boolean give(ToolItem item); + + /** The tool item in the player's main hand; empty when the held item is not one, which is when it carries no payload. */ + Optional held(); + + /** Opens {@code menu} for the player, closing the menu they had open. */ + void openMenu(ToolMenu menu); + + /** Closes the menu a tool opened for the player; does nothing when none is open. */ + void closeMenu(); +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/ToolText.java b/api/api/src/main/java/com/volmit/tooling/world/ToolText.java new file mode 100644 index 000000000..942d865e3 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolText.java @@ -0,0 +1,188 @@ +package com.volmit.tooling.world; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * Styled text a tool shows a player: item names and lore, menu titles, sidebars, the action bar and chat. It is a list of + * spans, each a piece of text with its own colour and style, so the text carries no formatting codes and a platform shows + * it with its own text components. A value is immutable. + * + *

Build it with {@link #builder()}, or use {@link #plain(String)} and {@link #colored(TextColor, String)} for one span. + * Text of a span is shown as it is: a formatting sign in it is just a character. + * + * @param spans the pieces in order + */ +public record ToolText(List spans) { + /** Nothing at all. */ + public static final ToolText EMPTY = new ToolText(List.of()); + + public ToolText { + spans = List.copyOf(spans); + } + + /** + * A piece of text in one style. + * + * @param text what is shown, never empty + * @param color the colour; null leaves the platform's default colour for that kind of text + * @param bold whether the text is bold + * @param italic whether the text is italic + * @param strikethrough whether the text has a line through it + */ + public record Span(String text, TextColor color, boolean bold, boolean italic, boolean strikethrough) { + public Span { + Objects.requireNonNull(text, "text"); + if (text.isEmpty()) { + throw new IllegalArgumentException("A span has text"); + } + } + + /** A span in {@code color} and no other style. */ + public static Span of(TextColor color, String text) { + return new Span(text, color, false, false, false); + } + + boolean sameStyle(Span other) { + return color == other.color && bold == other.bold && italic == other.italic + && strikethrough == other.strikethrough; + } + } + + /** One span in the platform's default colour. */ + public static ToolText plain(String text) { + return builder().append(text).build(); + } + + /** One span in {@code color}. */ + public static ToolText colored(TextColor color, String text) { + return builder().append(color, text).build(); + } + + public static Builder builder() { + return new Builder(); + } + + /** The text without any style, as one string. */ + public String plainText() { + StringBuilder text = new StringBuilder(); + for (Span span : spans) { + text.append(span.text()); + } + return text.toString(); + } + + public boolean isEmpty() { + return spans.isEmpty(); + } + + /** Builds a {@link ToolText} span by span. Empty text is skipped, and neighbours of one style become one span. */ + @SuppressWarnings("UnusedReturnValue") + public static final class Builder { + private final List spans = new ArrayList<>(); + + private Builder() { + } + + /** Adds {@code text} in the platform's default colour; empty text adds nothing. */ + public Builder append(String text) { + Objects.requireNonNull(text, "text"); + return text.isEmpty() ? this : append(new Span(text, null, false, false, false)); + } + + /** Adds {@code text} in {@code color}; empty text adds nothing. */ + public Builder append(TextColor color, String text) { + Objects.requireNonNull(color, "color"); + Objects.requireNonNull(text, "text"); + return text.isEmpty() ? this : append(Span.of(color, text)); + } + + /** Adds {@code span}, joined to the span before it when they share a style. */ + public Builder append(Span span) { + Objects.requireNonNull(span, "span"); + if (!spans.isEmpty() && spans.getLast().sameStyle(span)) { + Span last = spans.removeLast(); + spans.add(new Span(last.text() + span.text(), last.color(), last.bold(), last.italic(), + last.strikethrough())); + return this; + } + spans.add(span); + return this; + } + + public Builder append(ToolText text) { + Objects.requireNonNull(text, "text"); + text.spans().forEach(this::append); + return this; + } + + public Builder black(String text) { + return append(TextColor.BLACK, text); + } + + public Builder darkBlue(String text) { + return append(TextColor.DARK_BLUE, text); + } + + public Builder darkGreen(String text) { + return append(TextColor.DARK_GREEN, text); + } + + public Builder darkAqua(String text) { + return append(TextColor.DARK_AQUA, text); + } + + public Builder darkRed(String text) { + return append(TextColor.DARK_RED, text); + } + + public Builder darkPurple(String text) { + return append(TextColor.DARK_PURPLE, text); + } + + public Builder gold(String text) { + return append(TextColor.GOLD, text); + } + + public Builder gray(String text) { + return append(TextColor.GRAY, text); + } + + public Builder darkGray(String text) { + return append(TextColor.DARK_GRAY, text); + } + + public Builder blue(String text) { + return append(TextColor.BLUE, text); + } + + public Builder green(String text) { + return append(TextColor.GREEN, text); + } + + public Builder aqua(String text) { + return append(TextColor.AQUA, text); + } + + public Builder red(String text) { + return append(TextColor.RED, text); + } + + public Builder lightPurple(String text) { + return append(TextColor.LIGHT_PURPLE, text); + } + + public Builder yellow(String text) { + return append(TextColor.YELLOW, text); + } + + public Builder white(String text) { + return append(TextColor.WHITE, text); + } + + public ToolText build() { + return new ToolText(spans); + } + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/ToolUse.java b/api/api/src/main/java/com/volmit/tooling/world/ToolUse.java new file mode 100644 index 000000000..26e2352b1 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolUse.java @@ -0,0 +1,36 @@ +package com.volmit.tooling.world; + +import com.volmit.geometry.BlockFace; +import com.volmit.geometry.BlockPosition; +import java.util.Objects; +import java.util.Optional; + +/** + * A player using their hand in a tool world, handed to {@link ToolWorldListener#used}. + * + * @param hand the hand that was used + * @param action what the player did + * @param item the tool item in that hand; empty when the item is not one + * @param block the block clicked; empty for a click in the air + * @param face the face of the block clicked; empty for a click in the air + */ +public record ToolUse(Hand hand, Action action, Optional item, Optional block, Optional face) { + public enum Hand { MAIN, OFF } + + public enum Action { + LEFT_CLICK_AIR, + LEFT_CLICK_BLOCK, + RIGHT_CLICK_AIR, + RIGHT_CLICK_BLOCK, + /** Stepping on a pressure plate, trampling farmland, touching a tripwire. */ + PHYSICAL + } + + public ToolUse { + Objects.requireNonNull(hand, "hand"); + Objects.requireNonNull(action, "action"); + Objects.requireNonNull(item, "item"); + Objects.requireNonNull(block, "block"); + Objects.requireNonNull(face, "face"); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/ToolWorld.java b/api/api/src/main/java/com/volmit/tooling/world/ToolWorld.java new file mode 100644 index 000000000..f8effaffe --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolWorld.java @@ -0,0 +1,87 @@ +package com.volmit.tooling.world; + +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.geometry.ChunkPos; +import com.volmit.object.BlockEntityData; +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +/** + * One open tool world. Every position here is a block of the world itself: X and Z are world coordinates and Y is the + * world's own Y, from {@link #minY()} up to but not including {@link #maxY()}. That is not the height above the + * dimension's bottom that {@link com.volmit.world.PackWorld} uses. + * + *

Threads. A host may split a world across threads, one for each region of it, as Folia does. {@link #owns} tells + * whether the calling thread owns a position; reading and writing blocks is allowed only there, and {@link #run} and + * {@link #call} get a task onto the owning thread from any other. Everything else here is safe from any thread. + */ +public interface ToolWorld { + /** The name the tool gave in {@link ToolWorldSpec#name()}. Still answers after the world closed. */ + String name(); + + /** The lowest Y of the world. */ + int minY(); + + /** The first Y above the world. */ + int maxY(); + + /** The players standing in this world now, a snapshot. */ + List players(); + + /** Whether the calling thread owns the block at {@code at}, so that it may read and write it. */ + boolean owns(BlockPosition at); + + /** + * Runs {@code task} on the thread that owns {@code at}: at once when the caller is that thread, else later. A + * task that throws is logged by the host. + */ + void run(BlockPosition at, Runnable task); + + /** Runs {@code task} like {@link #run} and completes with its result, or fails with what it threw. */ + CompletableFuture call(BlockPosition at, Supplier task); + + /** + * The block at {@code at}. The state is complete, with every property. + * + * @throws IllegalStateException when the calling thread does not own {@code at}, or the world closed + */ + BlockState block(BlockPosition at); + + /** + * The block entity at {@code at}; empty when the block has none. + * + * @throws IllegalStateException when the calling thread does not own {@code at}, or the world closed + */ + Optional blockEntity(BlockPosition at); + + /** + * Replaces the block at {@code at} with {@code state} and {@code data} as its block entity, without block updates + * or {@link ToolWorldListener#blockChanging} calls, since the tool is the one changing it. Empty data leaves the + * new block with the platform's default entity, if its state has one. + * + * @throws IllegalStateException when the calling thread does not own {@code at}, or the world closed + */ + void setBlock(BlockPosition at, BlockState state, Optional data); + + /** Whether the platform has {@code chunk} loaded right now. Safe from any thread; a tool treats it as a hint. */ + boolean loaded(ChunkPos chunk); + + /** + * Runs the painter again for {@code chunks}, writes the differences into the live chunks and sends them to the + * players. Block entities the painter sets replace those of the chunk. The future completes on a host thread when + * every chunk is written, and fails if one could not be; chunks written before the failure stay written. + */ + CompletableFuture repaint(Collection chunks); + + /** + * Closes the world: sends every player back to where they were before they entered a tool world, restoring their + * game mode, then unloads the world and deletes its files. {@link ToolWorldListener#closed()} is called once it + * is unloaded. Closing a closed world completes at once. The future fails when the world could not be unloaded or + * deleted; the host then deletes what is left when it starts next. + */ + CompletableFuture close(); +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/ToolWorldDenied.java b/api/api/src/main/java/com/volmit/tooling/world/ToolWorldDenied.java new file mode 100644 index 000000000..168b08adf --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolWorldDenied.java @@ -0,0 +1,13 @@ +package com.volmit.tooling.world; + +/** A host refused to open a tool world for a reason its message tells the user and the pack's author can fix, such as a pack + * with blocking errors. {@link ToolWorlds#open} completes with it; it is not a fault, so a tool reports the message and logs no + * stack trace. + */ +public final class ToolWorldDenied extends RuntimeException { + private static final long serialVersionUID = 1L; + + public ToolWorldDenied(String message) { + super(message); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/ToolWorldListener.java b/api/api/src/main/java/com/volmit/tooling/world/ToolWorldListener.java new file mode 100644 index 000000000..2c325f65f --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolWorldListener.java @@ -0,0 +1,102 @@ +package com.volmit.tooling.world; + +import com.volmit.geometry.BlockPosition; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +/** + * What a tool hears about its world. Every method has a default that does nothing, so a tool implements only the ones + * it needs. + * + *

Threads. A call runs on the thread that owns the player or the position it is about, and the host waits for it: + * return quickly, and hand slow work to another thread. The host calls only for the tool's own world. A listener that + * throws is logged by the host and counts as having answered with the method's default. + * + *

The methods that return a boolean decide whether the host lets the thing happen: {@code false} cancels it. + */ +public interface ToolWorldListener { + /** A player came into the world: joined the server in it, teleported or changed world into it, or respawned in it. Once for each stay. */ + default void entered(ToolPlayer player) { + } + + /** A player left the world: quit, teleported or changed world out of it. Once for each stay. */ + default void left(ToolPlayer player) { + } + + /** + * A player arrived at a position of the world by other means than walking: they joined the server in it, changed + * world into it, respawned in it, or were teleported into it or inside it by anyone, such as a command, another + * plugin or a portal. It is told at the time of the teleport, with the position they arrive at, and for a player + * coming in after {@link #entered}. A player teleported out only hears {@link #left}. The default treats it as + * {@link #moved}. + */ + default void teleported(ToolPlayer player, BlockPosition to) { + moved(player, to); + } + + /** A player moved to another block of the world; not called for moves inside one block. */ + default void moved(ToolPlayer player, BlockPosition to) { + } + + /** A player started or stopped sneaking. */ + default void sneakToggled(ToolPlayer player, boolean sneaking) { + } + + /** A player used their hand. Return {@code false} to cancel what the platform would do with it, such as opening a container or placing a block. */ + default boolean used(ToolPlayer player, ToolUse use) { + return true; + } + + /** Something is about to change blocks. Return {@code false} to cancel it. The default freezes the world. */ + default boolean blockChanging(BlockChange change) { + return false; + } + + /** + * A command is about to run: {@code line} is what was typed without the leading slash. {@code sender} is empty for the + * console, which is asked on behalf of every tool world that is open. Return {@code false} to cancel it. + */ + default boolean command(Optional sender, String line) { + return true; + } + + /** + * What is inside a container or a machine changed without a block changing: a player closed a container block's + * inventory, a furnace started smelting, a brewing stand started brewing. It is told after the fact and cannot be + * cancelled; {@link #blockChanging} with {@link BlockChange.Cause#CONTAINER} or {@link BlockChange.Cause#MACHINE} + * decides the changes that can be. + * + * @param player the player behind it, when there is one + * @param at the block of the container or machine + */ + default void containerChanged(Optional player, BlockPosition at) { + } + + /** A chunk of the world finished loading, painted or read back. */ + default void chunkLoaded(int chunkX, int chunkZ) { + } + + /** + * Whether the host may close the world now, asked before the host closes it for any reason other than the tool's own + * {@link ToolWorld#close()}: another studio opening, the studio close command, the server stopping. A tool world takes + * the pack's studio slot, so those paths go through the world. Return a message for the user to veto the close, such + * as "autosave is still running"; empty lets it happen. Asked on any thread, and must return quickly. + */ + default Optional closeRefusal() { + return Optional.empty(); + } + + /** + * Another studio wants this world's slot. Get the world ready to close, such as finishing a save, and complete the + * future when it is ready; the host then closes the world. Complete it exceptionally to refuse, with a message for the + * user. {@code by} is the player who asked, empty when the console did. Called on any thread; the future may complete + * on any thread. + */ + default CompletableFuture closing(Optional by) { + return CompletableFuture.completedFuture(null); + } + + /** The world was unloaded and is gone; nothing can be done with it any more. */ + default void closed() { + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/ToolWorldSpec.java b/api/api/src/main/java/com/volmit/tooling/world/ToolWorldSpec.java new file mode 100644 index 000000000..096e5268e --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolWorldSpec.java @@ -0,0 +1,29 @@ +package com.volmit.tooling.world; + +import java.util.Objects; +import java.util.regex.Pattern; + +/** + * What a tool asks {@link ToolWorlds#open} for: a world of the tool's pack whose chunks come only from {@code painter}, + * and who hears about it. + * + *

The host opens it as a studio world of the tool's pack with its generation swapped for the painter, so its height + * range is the pack dimension's; {@link ToolWorld#minY()} and {@link ToolWorld#maxY()} report it. + * + * @param name the tool's name for the world, unique among the open tool worlds of the pack: lower case letters, + * digits, {@code _} and {@code -}, starting with a letter or a digit. It is not the platform's world name. + * @param painter the only source of the world's chunks + * @param listener told about the players, blocks and commands of the world + */ +public record ToolWorldSpec(String name, ChunkPainter painter, ToolWorldListener listener) { + private static final Pattern NAME = Pattern.compile("[a-z0-9][a-z0-9_-]*"); + + public ToolWorldSpec { + Objects.requireNonNull(name, "name"); + Objects.requireNonNull(painter, "painter"); + Objects.requireNonNull(listener, "listener"); + if (!NAME.matcher(name).matches()) { + throw new IllegalArgumentException("A tool world name is lower case letters, digits, '_' and '-': " + name); + } + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/ToolWorlds.java b/api/api/src/main/java/com/volmit/tooling/world/ToolWorlds.java new file mode 100644 index 000000000..ed8740457 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolWorlds.java @@ -0,0 +1,28 @@ +package com.volmit.tooling.world; + +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +/** + * The tool worlds of one pack: worlds a tool opens to show or edit what it builds, such as a jigsaw studio. Reached + * through {@link com.volmit.tooling.ToolPack#worlds()}. A platform without tool worlds still answers: {@link #open} + * then returns a failed future and {@link #find} an empty result. + * + *

Safe to call from any thread, the server's main thread included. + */ +public interface ToolWorlds { + /** + * Opens a world whose chunks come only from {@code spec.painter()}. The future completes, on a host thread, when + * players can enter the world. It fails with {@link IllegalStateException} when a tool world of that name is open + * already, with {@link ToolWorldDenied} when the host refuses the pack a world (its message says why), and with the + * cause when the platform cannot create the world; a failed open leaves no world behind. + * The host closes every tool world it still has open when it shuts down: it hears {@link ToolWorldListener#closing} + * of each and waits for it before {@link ToolWorldListener#closed}. + * + *

A tool world has no natural mob spawning, weather, daylight cycle, portals, vanilla structures or features. + */ + CompletableFuture open(ToolWorldSpec spec); + + /** The open tool world of this pack called {@code name}; empty when none is open or it closed. */ + Optional find(String name); +} diff --git a/api/api/src/main/java/com/volmit/validation/ValidationContext.java b/api/api/src/main/java/com/volmit/validation/ValidationContext.java index 0f6231898..d7b73ea2d 100644 --- a/api/api/src/main/java/com/volmit/validation/ValidationContext.java +++ b/api/api/src/main/java/com/volmit/validation/ValidationContext.java @@ -4,6 +4,7 @@ import com.volmit.config.PackSettings; import com.volmit.resource.PackResources; import com.volmit.resource.PlatformRegistries; +import java.util.List; import java.util.Optional; /** The pack one {@link Validator} checks, as the host would load it, and where it reports what it finds. Valid @@ -25,6 +26,16 @@ public interface ValidationContext { */ Optional platform(); + /** + * The providers of {@code service} that the pack's modules registered, in module id order and each module's in the + * order it registered them; empty when no module provides it. This is how a validator asks another module, such as + * whether a module knows a structure the pack names. + * + * @param service an interface marked {@link com.volmit.service.Service} + * @throws IllegalArgumentException when {@code service} is not such an interface + */ + List services(Class service); + /** Records {@code problem}. An {@link Severity#ERROR} stops the pack from loading once every validator has run. */ void report(Problem problem); } diff --git a/api/api/src/main/java/com/volmit/vanilla/VanillaStructureContext.java b/api/api/src/main/java/com/volmit/vanilla/VanillaStructureContext.java index ecde18518..391db9cbe 100644 --- a/api/api/src/main/java/com/volmit/vanilla/VanillaStructureContext.java +++ b/api/api/src/main/java/com/volmit/vanilla/VanillaStructureContext.java @@ -2,6 +2,9 @@ package com.volmit.vanilla; import com.volmit.config.PackSettings; import com.volmit.resource.PackResources; +import com.volmit.world.PackWorld; + +import java.util.Optional; /** The world a {@link com.volmit.service.VanillaStructures} provider decides for. Valid only while the provider runs. */ public interface VanillaStructureContext { @@ -10,4 +13,9 @@ public interface VanillaStructureContext { /** The module settings the world's dimension declares: its own, and every region and biome it can reach. */ PackSettings settings(); + + /** The world the provider decides for; empty when it decides before any world exists, such as for the setup of a dimension. */ + default Optional world() { + return Optional.empty(); + } } diff --git a/api/api/src/main/java/com/volmit/world/PackWorld.java b/api/api/src/main/java/com/volmit/world/PackWorld.java index 9d583db44..7eb92dc4d 100644 --- a/api/api/src/main/java/com/volmit/world/PackWorld.java +++ b/api/api/src/main/java/com/volmit/world/PackWorld.java @@ -6,6 +6,7 @@ import com.volmit.placement.Placements; import com.volmit.random.WorldRandom; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; +import java.util.List; import java.util.Optional; import java.util.function.Function; @@ -87,4 +88,15 @@ public interface PackWorld { default Optional extension(Class type) { return Optional.empty(); } + + /** + * The providers of {@code service} that the pack's modules registered, in module id order and each module's in the + * order it registered them; empty when no module provides it. This is how a module asks another module's service, + * such as a placement asking who builds a structure. A provider takes the world as the first argument of its + * methods, so pass this one. The list does not change while the world runs. + * + * @param service an interface marked {@link com.volmit.service.Service} + * @throws IllegalArgumentException when {@code service} is not such an interface + */ + List services(Class service); } diff --git a/api/api/src/main/java/com/volmit/world/RunningWorld.java b/api/api/src/main/java/com/volmit/world/RunningWorld.java index 720f9ef35..d5a094f9e 100644 --- a/api/api/src/main/java/com/volmit/world/RunningWorld.java +++ b/api/api/src/main/java/com/volmit/world/RunningWorld.java @@ -3,6 +3,7 @@ package com.volmit.world; import com.volmit.config.FeatureSettings; import com.volmit.data.SavedKey; import com.volmit.geometry.BlockPosition; +import com.volmit.mantle.CarvedVoid; import com.volmit.placement.PlacementRecord; import com.volmit.resource.ResourceId; import java.util.List; @@ -43,6 +44,15 @@ public interface RunningWorld { */ Optional placementAt(int worldX, int y, int worldZ); + /** + * The void the cave carver planned at the block, as the world holds it now; empty where none was, or when the block's + * chunk keeps no generation data any more, and on a platform that cannot read it. Y is the height above the + * dimension's bottom. + */ + default Optional carvedAt(int worldX, int y, int worldZ) { + return Optional.empty(); + } + /** * The value the module keeps with this world across restarts under {@code key}: the host's one instance of it for * the world, read from the world's storage the first time anyone asks (or {@code key.initial()} when none was diff --git a/api/api/src/test/java/com/volmit/tooling/PlatformStructuresTest.java b/api/api/src/test/java/com/volmit/tooling/PlatformStructuresTest.java new file mode 100644 index 000000000..e1ee5b737 --- /dev/null +++ b/api/api/src/test/java/com/volmit/tooling/PlatformStructuresTest.java @@ -0,0 +1,48 @@ +package com.volmit.tooling; + +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockFace; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PlatformStructuresTest { + @Test + void aTemplateKeepsItsOwnCopyOfItsBlocks() { + var blocks = new ArrayList<>(List.of(TemplateBlock.of( + new BlockPosition(0, 0, 0), BlockState.parse("minecraft:stone"), Optional.empty()))); + var template = new StructureTemplate(new BlockPosition(1, 1, 1), 1, 0, blocks); + + blocks.clear(); + + assertEquals(1, template.blocks().size()); + assertThrows(UnsupportedOperationException.class, () -> template.blocks().clear()); + } + + @Test + void aPoolListsEveryMemberWhetherTheToolCanReadItOrNot() { + var unreadable = new TemplatePool.Unreadable(TemplatePool.Part.ENTRY, "no weight"); + var element = new TemplatePool.Element(3, "SinglePoolElement", + Optional.of(ResourceId.parse("minecraft:village/house")), 0, 0, + seeds -> new TemplatePool.Connectors(TemplatePool.Availability.READ, List.of( + new TemplatePool.JigsawConnector(new BlockPosition(1, 2, 3), BlockFace.NORTH, BlockFace.UP, + Optional.empty(), "minecraft:door", "minecraft:door", false, Optional.empty(), 0, 0)))); + var pool = new TemplatePool(List.of(new TemplatePool.Absent(), unreadable, element), Optional.empty(), Optional.empty()); + + assertEquals(3, pool.members().size()); + assertEquals(1, element.connectors().read(() -> 7L).connectors().size()); + } + + @Test + void anAccessFailureSaysWhetherAskingAgainMayHelp() { + assertTrue(new StructureAccessException("registry not ready", true).retryable()); + assertEquals("no such member", new StructureAccessException("no such member", false).getMessage()); + } +} diff --git a/api/api/src/test/java/com/volmit/tooling/world/ToolWorldRecordsTest.java b/api/api/src/test/java/com/volmit/tooling/world/ToolWorldRecordsTest.java new file mode 100644 index 000000000..c4c85edec --- /dev/null +++ b/api/api/src/test/java/com/volmit/tooling/world/ToolWorldRecordsTest.java @@ -0,0 +1,184 @@ +package com.volmit.tooling.world; + +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.geometry.ChunkPos; +import com.volmit.resource.ResourceId; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class ToolWorldRecordsTest { + private static final ResourceId STICK = ResourceId.parse("minecraft:stick"); + private static final ToolItem ICON = new ToolItem(STICK, ToolText.plain("Tool"), List.of(ToolText.plain("line")), false, ""); + + @Test + void aChunkIsTheBlockCoordinatesDividedBySixteenRoundedDown() { + assertEquals(new ChunkPos(0, 0), ChunkPos.containing(new BlockPosition(15, 70, 0))); + assertEquals(new ChunkPos(1, -1), ChunkPos.containing(new BlockPosition(16, 0, -1))); + assertEquals(new ChunkPos(-2, -1), ChunkPos.containing(new BlockPosition(-17, 0, -16))); + } + + @Test + void aToolWorldNameIsLowerCaseWordsOfLettersDigitsUnderscoresAndDashes() { + ChunkPainter painter = (x, z, canvas) -> { }; + var listener = new ToolWorldListener() { }; + + assertEquals("jigsaw-1_a", new ToolWorldSpec("jigsaw-1_a", painter, listener).name()); + assertThrows(IllegalArgumentException.class, () -> new ToolWorldSpec("Jigsaw", painter, listener)); + assertThrows(IllegalArgumentException.class, () -> new ToolWorldSpec("two words", painter, listener)); + assertThrows(IllegalArgumentException.class, () -> new ToolWorldSpec("", painter, listener)); + assertThrows(IllegalArgumentException.class, () -> new ToolWorldSpec("-dash", painter, listener)); + assertThrows(NullPointerException.class, () -> new ToolWorldSpec("name", null, listener)); + assertThrows(NullPointerException.class, () -> new ToolWorldSpec("name", painter, null)); + } + + @Test + void aListenerThatSaysNothingAboutClosingLetsTheWorldCloseAtOnce() { + var listener = new ToolWorldListener() { }; + + assertEquals(java.util.Optional.empty(), listener.closeRefusal()); + assertEquals(true, listener.closing(java.util.Optional.empty()).isDone()); + assertEquals(false, listener.closing(java.util.Optional.empty()).isCompletedExceptionally()); + } + + @Test + void aToolItemKeepsItsOwnCopyOfTheLore() { + var lore = new ArrayList<>(List.of(ToolText.plain("one"))); + var item = new ToolItem(STICK, ToolText.plain("Name"), lore, true, "payload"); + lore.add(ToolText.plain("two")); + + assertEquals(List.of(ToolText.plain("one")), item.lore()); + assertThrows(UnsupportedOperationException.class, () -> item.lore().add(ToolText.plain("three"))); + assertThrows(NullPointerException.class, () -> new ToolItem(STICK, ToolText.plain("Name"), List.of(), false, null)); + } + + @Test + void textIsSpansOfColourAndStyleAndAdjoiningSpansOfOneStyleJoin() { + var text = ToolText.builder().gray("Capacity: ").gray("16x16x16").white(" now").append(" plain").build(); + + assertEquals(3, text.spans().size()); + assertEquals("Capacity: 16x16x16 now plain", text.plainText()); + assertEquals(new ToolText.Span("Capacity: 16x16x16", TextColor.GRAY, false, false, false), text.spans().getFirst()); + assertNull(text.spans().getLast().color()); + } + + @Test + void emptyTextAddsNoSpanAndPlainTextOfNothingIsEmpty() { + var text = ToolText.builder().red("").append("").build(); + + assertTrue(text.isEmpty()); + assertEquals("", text.plainText()); + assertEquals(ToolText.EMPTY, text); + assertThrows(IllegalArgumentException.class, () -> new ToolText.Span("", null, false, false, false)); + } + + @Test + void textKeepsItsOwnCopyOfTheSpans() { + var spans = new ArrayList<>(List.of(ToolText.Span.of(TextColor.RED, "a"))); + var text = new ToolText(spans); + spans.add(ToolText.Span.of(TextColor.RED, "b")); + + assertEquals("a", text.plainText()); + assertThrows(UnsupportedOperationException.class, () -> text.spans().add(ToolText.Span.of(TextColor.RED, "c"))); + } + + @Test + void theSixteenColoursHaveTheirFormattingCodes() { + var codes = new StringBuilder(); + for (TextColor color : TextColor.values()) { + codes.append(color.code()); + } + + assertEquals("0123456789abcdef", codes.toString()); + } + + @Test + void aMenuHasOneToSixRowsAndEveryButtonInsideThemOnItsOwnSlot() { + var button = new MenuButton(17, ICON, click -> { }); + + assertEquals(1, new ToolMenu(ToolText.plain("t"),1, List.of(new MenuButton(8, ICON, click -> { })), null).rows()); + assertEquals(2, new ToolMenu(ToolText.plain("t"),2, List.of(button), null).rows()); + assertThrows(IllegalArgumentException.class, () -> new ToolMenu(ToolText.plain("t"),0, List.of(), null)); + assertThrows(IllegalArgumentException.class, () -> new ToolMenu(ToolText.plain("t"),7, List.of(), null)); + assertThrows(IllegalArgumentException.class, () -> new ToolMenu(ToolText.plain("t"),1, List.of(button), null), "slot 17 is in the second row"); + assertThrows(IllegalArgumentException.class, + () -> new ToolMenu(ToolText.plain("t"),2, List.of(button, new MenuButton(17, ICON, click -> { })), null)); + assertThrows(IllegalArgumentException.class, () -> new MenuButton(-1, ICON, click -> { })); + } + + @Test + void aMenuWithoutAnOnCloseHasOneThatDoesNothing() { + var closed = new AtomicBoolean(); + var withHandler = new ToolMenu(ToolText.plain("t"),1, List.of(), () -> closed.set(true)); + var without = new ToolMenu(ToolText.plain("t"),1, List.of(), null); + + without.onClose().run(); + assertFalse(closed.get()); + withHandler.onClose().run(); + assertTrue(closed.get()); + } + + @Test + void aBlockChangeNamesAtLeastOneBlock() { + var position = new BlockPosition(1, 2, 3); + var change = new BlockChange(BlockChange.Cause.PLACE, List.of(position), Optional.empty(), + Optional.of(BlockState.parse("minecraft:stone"))); + + assertEquals(List.of(position), change.positions()); + assertThrows(IllegalArgumentException.class, + () -> new BlockChange(BlockChange.Cause.BREAK, List.of(), Optional.empty(), Optional.empty())); + } + + @Test + void whatAChangeChangesIsWhatItIsCheckedAgainstUnlessSaidOtherwise() { + var position = new BlockPosition(1, 2, 3); + var aside = new BlockPosition(4, 5, 6); + + assertEquals(List.of(position), new BlockChange(BlockChange.Cause.PLACE, List.of(position), Optional.empty(), Optional.empty()).changed()); + var piston = new BlockChange(BlockChange.Cause.PISTON, List.of(), List.of(aside), Optional.empty(), Optional.empty()); + assertEquals(List.of(), piston.positions()); + assertEquals(List.of(aside), piston.changed()); + assertThrows(IllegalArgumentException.class, + () -> new BlockChange(BlockChange.Cause.PISTON, List.of(), List.of(), Optional.empty(), Optional.empty())); + } + + @Test + void aTeleportIsAMoveToAListenerThatDoesNotCareAndNothingToCareAboutInContainers() { + var moves = new ArrayList(); + var listener = new ToolWorldListener() { + @Override + public void moved(ToolPlayer player, BlockPosition to) { + moves.add(to); + } + }; + var to = new BlockPosition(7, 8, 9); + + listener.teleported(null, to); + listener.containerChanged(Optional.empty(), to); + + assertEquals(List.of(to), moves); + } + + @Test + void aListenerThatImplementsNothingFreezesTheWorldAndAllowsEverythingElse() { + var listener = new ToolWorldListener() { }; + var change = new BlockChange(BlockChange.Cause.PISTON, List.of(new BlockPosition(0, 0, 0)), Optional.empty(), Optional.empty()); + + assertFalse(listener.blockChanging(change)); + assertTrue(listener.command(Optional.empty(), "gamemode creative")); + } + + @Test + void aParticleHasAnRgbColourAndAPositiveSize() { + assertEquals(0xFF00FF, new Particle(0, 0, 0, 0xFF00FF, 1.5F).rgb()); + assertThrows(IllegalArgumentException.class, () -> new Particle(0, 0, 0, 0x1000000, 1F)); + assertThrows(IllegalArgumentException.class, () -> new Particle(0, 0, 0, -1, 1F)); + assertThrows(IllegalArgumentException.class, () -> new Particle(0, 0, 0, 0, 0F)); + assertThrows(IllegalArgumentException.class, () -> new Particle(0, 0, 0, 0, Float.NaN)); + } +} diff --git a/api/host/src/main/java/com/volmit/host/ExposedPackages.java b/api/host/src/main/java/com/volmit/host/ExposedPackages.java index f26fbad4b..7cc7d39df 100644 --- a/api/host/src/main/java/com/volmit/host/ExposedPackages.java +++ b/api/host/src/main/java/com/volmit/host/ExposedPackages.java @@ -13,7 +13,8 @@ import java.util.TreeSet; * {@code com.volmitx}. The host side of IrisApi, {@code com.volmit.host}, lies inside the API's * root package but is never exposed: it loads and runs modules, and no module may reach it. The * platform packages of the tooling api, {@code com.volmit.tooling.}, are never exposed either: - * only a tooling part may use them. The neutral {@code com.volmit.tooling} stays exposed. + * only a tooling part may use them. The neutral {@code com.volmit.tooling} stays exposed, and so does the world api for + * tools, {@code com.volmit.tooling.world}, which every platform implements. */ final class ExposedPackages { /** The root package of the Iris API. Module classes must not use it. */ @@ -22,6 +23,9 @@ final class ExposedPackages { static final String HOST_PACKAGE = ExposedPackages.class.getPackageName(); /** The neutral tooling api. Each platform's own api is a subpackage of it, such as {@code com.volmit.tooling.bukkit}. */ static final String TOOLING_PACKAGE = API_PACKAGE + ".tooling"; + /** The world api for tools, which every platform implements; it is neutral, so modules see it. */ + static final String TOOL_WORLD_PACKAGE = TOOLING_PACKAGE + ".world"; + private static final PackageName TOOL_WORLD = new PackageName(TOOL_WORLD_PACKAGE); private static final PackageName API = new PackageName(API_PACKAGE); private static final PackageName HOST = new PackageName(HOST_PACKAGE); private static final PackageName TOOLING = new PackageName(TOOLING_PACKAGE); @@ -77,9 +81,12 @@ final class ExposedPackages { return !HOST.contains(dottedName) && packages.stream().anyMatch(name -> name.contains(dottedName)); } - /** Whether the package lies below {@code com.volmit.tooling}, where each platform's api has its package. */ + /** Whether the package lies below {@code com.volmit.tooling}, where each platform's api has its package. The + * platform-neutral world api for tools, {@code com.volmit.tooling.world}, lies there too but is not a platform's. + */ private static boolean isToolingPlatformPackage(String packageName) { - return TOOLING.contains(packageName); + boolean isToolWorldApi = packageName.equals(TOOL_WORLD_PACKAGE) || TOOL_WORLD.contains(packageName); + return TOOLING.contains(packageName) && !isToolWorldApi; } /** What precedes the last separator: the package of a class name, or the directory of a resource path. */ diff --git a/api/host/src/main/java/com/volmit/host/ModuleWorld.java b/api/host/src/main/java/com/volmit/host/ModuleWorld.java index 4a8b0fc56..ea13d72de 100644 --- a/api/host/src/main/java/com/volmit/host/ModuleWorld.java +++ b/api/host/src/main/java/com/volmit/host/ModuleWorld.java @@ -4,8 +4,10 @@ import com.volmit.ModuleLog; import com.volmit.config.PackSettings; import com.volmit.placement.Placements; import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import com.volmit.world.PackWorld; import com.volmit.world.RunningWorld; +import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Function; @@ -36,6 +38,11 @@ final class ModuleWorld implements PackWorld { return world.seed(); } + @Override + public long seed(ResourceId purpose) { + return world.seed(purpose); + } + @Override public PackResources resources() { return world.resources(); @@ -72,6 +79,11 @@ final class ModuleWorld implements PackWorld { return world.extension(type); } + @Override + public List services(Class service) { + return world.services(service); + } + @Override public ModuleLog log() { return log; diff --git a/api/host/src/test/java/com/volmit/host/ExposedPackagesTest.java b/api/host/src/test/java/com/volmit/host/ExposedPackagesTest.java index 7113e7a65..3e14a2c3d 100644 --- a/api/host/src/test/java/com/volmit/host/ExposedPackagesTest.java +++ b/api/host/src/test/java/com/volmit/host/ExposedPackagesTest.java @@ -42,6 +42,8 @@ class ExposedPackagesTest { assertTrue(exposed.exposes("com.volmit.tooling.Command$Builder")); assertFalse(exposed.exposes("com.volmit.tooling.bukkit.BukkitToolPart")); assertFalse(exposed.exposes("com.volmit.tooling.modded.deep.ModdedToolPart")); + assertTrue(exposed.exposes("com.volmit.tooling.world.ToolWorld"), "the world api for tools is neutral"); + assertFalse(exposed.exposes("com.volmit.tooling.worldly.BukkitToolPart")); assertTrue(exposed.exposes("com.volmit.toolingx.Other")); assertTrue(exposed.exposes("com.volmit.tool.bukkit.Other")); } diff --git a/api/host/src/test/java/com/volmit/host/ExtensionsTest.java b/api/host/src/test/java/com/volmit/host/ExtensionsTest.java index e9b0a50ec..674fdeafa 100644 --- a/api/host/src/test/java/com/volmit/host/ExtensionsTest.java +++ b/api/host/src/test/java/com/volmit/host/ExtensionsTest.java @@ -12,6 +12,7 @@ import com.volmit.hunk.Hunk; import com.volmit.mantle.Mantle; import com.volmit.placement.Placements; import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import com.volmit.stage.Pipeline; import com.volmit.stage.Stage; import com.volmit.support.TestContexts; @@ -73,6 +74,18 @@ class ExtensionsTest { assertEquals(Optional.of(new WorldOffer("iris")), view.extension(WorldOffer.class)); } + @Test + void aModulesViewOfAWorldAnswersTheSeedPurposesTheHostAnswers() { + var world = new OfferingWorld(new WorldOffer("iris")); + PackWorld view = ModuleWorld.of(world, ModuleLogs.discarding()); + + assertEquals(HOST_SEED, view.seed(HOST_SEED_PURPOSE), "the host decides the seed of a purpose it knows"); + assertEquals(world.seed(ResourceId.parse("test:other")), view.seed(ResourceId.parse("test:other"))); + } + + private static final ResourceId HOST_SEED_PURPOSE = ResourceId.parse("test:host-seed"); + private static final long HOST_SEED = 31337L; + private static final class OfferingWorld implements PackWorld { private final WorldStates states = new WorldStates(); private final WorldOffer offer; @@ -82,12 +95,14 @@ class ExtensionsTest { } public long seed() { return TestContexts.SEED; } + @Override public long seed(ResourceId purpose) { return purpose.equals(HOST_SEED_PURPOSE) ? HOST_SEED : PackWorld.super.seed(purpose); } public PackResources resources() { throw new AssertionError("Unused resources"); } public PackSettings settings() { throw new AssertionError("Unused settings"); } public int minWorldY() { return 0; } public Optional running() { return Optional.empty(); } public Placements placements() { throw new AssertionError("Unused placements"); } public T state(Class type, Function create) { return states.state(type, () -> create.apply(this)); } + public List services(Class service) { return List.of(); } public ModuleLog log() { return ModuleLogs.discarding(); } @Override diff --git a/api/host/src/test/java/com/volmit/host/PackWorldServicesTest.java b/api/host/src/test/java/com/volmit/host/PackWorldServicesTest.java new file mode 100644 index 000000000..e67e229f6 --- /dev/null +++ b/api/host/src/test/java/com/volmit/host/PackWorldServicesTest.java @@ -0,0 +1,81 @@ +package com.volmit.host; + +import com.volmit.IrisModule; +import com.volmit.FeatureRegistry; +import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; +import com.volmit.service.Providers; +import com.volmit.service.Service; +import com.volmit.support.TestWorld; +import com.volmit.world.PackWorld; +import java.util.List; +import java.util.function.Consumer; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +/** A module asks another module's service through the world: {@code PackWorld.services}, which the validation context and + * the tool pack answer the same way. + */ +class PackWorldServicesTest { + @Service(Providers.ALL) + interface Greeting { String greet(); } + @Service(Providers.ONE) + interface Clock { long now(); } + interface NotAService { void run(); } + + private static void registerAs(ModuleRegistry registry, String moduleId, Consumer registrations) { + ModuleSetups.run(DiscoveredModule.builtIn(new IrisModule() { + public ModuleInfo info() { return ModuleInfo.of(moduleId, "Test module " + moduleId, "1"); } + public void setup(ModuleSetup setup) { registrations.accept(setup.registry()); } + }), new StageGraphBuilder(), registry); + } + + private static FeatureCatalog catalogOf(Greeting zeta, Greeting alphaFirst, Greeting alphaSecond) { + var registry = new ModuleRegistry(); + registerAs(registry, "test:zeta", services -> services.registerService(Greeting.class, zeta)); + registerAs(registry, "test:alpha", services -> { + services.registerService(Greeting.class, alphaFirst); + services.registerService(Greeting.class, alphaSecond); + }); + return registry.freeze(); + } + + @Test + void aWorldAnswersWithTheProvidersOfItsPacksModulesInModuleIdOrder() { + Greeting zeta = () -> "zeta"; + Greeting alphaFirst = () -> "alpha 1"; + Greeting alphaSecond = () -> "alpha 2"; + try (var world = new TestWorld(catalogOf(zeta, alphaFirst, alphaSecond))) { + assertEquals(List.of(alphaFirst, alphaSecond, zeta), world.services(Greeting.class)); + } + } + + @Test + void aServiceNobodyProvidesHasNoProviders() { + try (var world = new TestWorld(catalogOf(() -> "zeta", () -> "alpha 1", () -> "alpha 2"))) { + assertEquals(List.of(), world.services(Clock.class)); + } + } + + @Test + void anInterfaceThatIsNotAServiceIsRefused() { + try (var world = new TestWorld(catalogOf(() -> "zeta", () -> "alpha 1", () -> "alpha 2"))) { + assertThrows(IllegalArgumentException.class, () -> world.services(NotAService.class)); + } + } + + @Test + void theViewAModuleGetsOfAWorldAnswersLikeTheWorld() { + Greeting zeta = () -> "zeta"; + Greeting alphaFirst = () -> "alpha 1"; + Greeting alphaSecond = () -> "alpha 2"; + var catalog = catalogOf(zeta, alphaFirst, alphaSecond); + try (var world = new TestWorld(catalog)) { + PackWorld view = catalog.registrations(Greeting.class).getFirst().scope(world); + + assertNotSame(world, view); + assertEquals(world.services(Greeting.class), view.services(Greeting.class)); + assertEquals(List.of(alphaFirst, alphaSecond, zeta), view.services(Greeting.class)); + } + } +} diff --git a/api/host/src/test/java/com/volmit/support/TestWorld.java b/api/host/src/test/java/com/volmit/support/TestWorld.java index 4b33fde34..15cd5aa14 100644 --- a/api/host/src/test/java/com/volmit/support/TestWorld.java +++ b/api/host/src/test/java/com/volmit/support/TestWorld.java @@ -4,27 +4,38 @@ import com.volmit.IrisFeature; import com.volmit.ModuleLog; import com.volmit.config.PackSettings; import com.volmit.config.SettingsStack; +import com.volmit.host.FeatureCatalog; import com.volmit.host.ModuleLogs; import com.volmit.host.WorldStates; import com.volmit.placement.Placements; import com.volmit.resource.PackResources; import com.volmit.world.PackWorld; import com.volmit.world.RunningWorld; +import java.util.List; import java.util.Optional; import java.util.function.Function; -/** A world for tests: the test seed, no resources, no declared settings, and a real state store. */ +/** A world for tests: the test seed, no resources, no declared settings, a real state store, and the service providers of + * a catalog when it is given one. + */ public final class TestWorld implements PackWorld, AutoCloseable { private final WorldStates states; private final ModuleLog log; + private final FeatureCatalog catalog; public TestWorld() { - this(new WorldStates(), ModuleLogs.discarding()); + this(null); } - private TestWorld(WorldStates states, ModuleLog log) { + /** A world whose services are those {@code catalog} holds. */ + public TestWorld(FeatureCatalog catalog) { + this(new WorldStates(), ModuleLogs.discarding(), catalog); + } + + private TestWorld(WorldStates states, ModuleLog log, FeatureCatalog catalog) { this.states = states; this.log = log; + this.catalog = catalog; } @Override @@ -70,6 +81,11 @@ public final class TestWorld implements PackWorld, AutoCloseable { return states.state(type, () -> create.apply(this)); } + @Override + public List services(Class service) { + return catalog == null ? List.of() : catalog.services(service); + } + @Override public ModuleLog log() { return log; diff --git a/build.gradle b/build.gradle index c35babb1b..22bf50a30 100644 --- a/build.gradle +++ b/build.gradle @@ -124,6 +124,9 @@ nmsBindings.each { key, value -> testImplementation('junit:junit:4.13.2') testImplementation('org.mockito:mockito-core:5.23.0') testImplementation(project(':core')) + testCompileOnly('com.volmit:iris-api') + // The runtime contract of the host's reflection over template pools runs against this binding's own classes. + testImplementation(project(':adapters:bukkit:plugin')) testCompileOnly(volmLibCoordinate) { transitive = false } diff --git a/core/build.gradle b/core/build.gradle index 8773af562..2f24b52dc 100644 --- a/core/build.gradle +++ b/core/build.gradle @@ -318,7 +318,8 @@ List dependencyBuildMetadata = [ // what its own Bukkit jar leaves out of VolmLib, which only Iris knows. String builtinModulesJarName = 'iris-builtins.jar' // The packages pack modules may use besides the IrisApi; IrisModuleHost.EXPOSED_PACKAGES lists the same. -List builtinExposedPackages = ['art.arcane.iris.builtin', 'art.arcane.volmlib', 'com.google.gson'] +List builtinExposedPackages = ['art.arcane.iris.builtin', 'art.arcane.iris.core.structure.authoring', 'art.arcane.volmlib', + 'com.google.gson'] Provider bundledBuiltinModulesJar = layout.buildDirectory.file("builtin-modules/${builtinModulesJarName}") configurations { diff --git a/core/purity-allowlist.txt b/core/purity-allowlist.txt index 96dede65b..904dc2f35 100644 --- a/core/purity-allowlist.txt +++ b/core/purity-allowlist.txt @@ -61,22 +61,13 @@ art/arcane/iris/core/service/BoardSVC.java art/arcane/iris/core/service/EntityRiseSVC.java art/arcane/iris/core/service/ExternalDataSVC.java art/arcane/iris/core/service/GlobalCacheSVC.java -art/arcane/iris/core/service/JigsawStudioMarkerParser.java -art/arcane/iris/core/service/JigsawStudioMenuController.java -art/arcane/iris/core/service/JigsawStudioPreviewRenderer.java -art/arcane/iris/core/service/JigsawStudioService.java -art/arcane/iris/core/service/JigsawStudioToolCodec.java art/arcane/iris/core/service/MultiverseSVC.java art/arcane/iris/core/service/ObjectSVC.java art/arcane/iris/core/service/ObjectStudioSaveService.java art/arcane/iris/core/service/PackDownloadProgressReporter.java art/arcane/iris/core/service/StudioSVC.java art/arcane/iris/core/service/TreeSVC.java -art/arcane/iris/core/structure/BulkStructureImporter.java art/arcane/iris/core/structure/FeatureImporter.java -art/arcane/iris/core/structure/StructureCaptureImporter.java -art/arcane/iris/core/structure/StructureImporter.java -art/arcane/iris/core/structure/VillageImporter.java art/arcane/iris/core/tools/IrisConverter.java art/arcane/iris/core/tools/IrisCreator.java art/arcane/iris/core/tools/IrisPackBenchmarking.java @@ -115,7 +106,6 @@ art/arcane/iris/engine/platform/BukkitChunkGenerator.java art/arcane/iris/engine/platform/DummyBiomeProvider.java art/arcane/iris/engine/platform/DummyChunkGenerator.java art/arcane/iris/engine/platform/EngineBukkitOps.java -art/arcane/iris/engine/platform/studio/generators/JigsawStudioGenerator.java art/arcane/iris/engine/platform/studio/generators/ObjectStudioGenerator.java art/arcane/iris/platform/bukkit/BukkitBiome.java art/arcane/iris/platform/bukkit/BukkitBlockResolution.java diff --git a/core/src/main/java/art/arcane/iris/core/datapack/DatapackIngestService.java b/core/src/main/java/art/arcane/iris/core/datapack/DatapackIngestService.java index e7f997811..3f8d6d2e3 100644 --- a/core/src/main/java/art/arcane/iris/core/datapack/DatapackIngestService.java +++ b/core/src/main/java/art/arcane/iris/core/datapack/DatapackIngestService.java @@ -20,6 +20,7 @@ package art.arcane.iris.core.datapack; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.IrisServices; import art.arcane.iris.platform.bukkit.BukkitPlatform; import art.arcane.iris.core.IrisStartupValidation; import art.arcane.iris.core.IrisSettings; @@ -29,8 +30,15 @@ import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.nms.MinecraftVersion; import art.arcane.iris.core.project.IrisProject; import art.arcane.iris.core.project.IrisCodeWorkspace; -import art.arcane.iris.core.structure.BulkStructureImporter; -import art.arcane.iris.core.structure.StructureImporter; +import art.arcane.iris.core.modules.IrisModuleHost; +import art.arcane.iris.core.modules.PackServices; +import art.arcane.iris.core.tooling.IrisToolPack; +import art.arcane.iris.core.tooling.VolmitToolSender; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.DatapackImportReport; +import com.volmit.tooling.DatapackStructureImport; +import com.volmit.tooling.PlatformStructures; +import art.arcane.iris.core.structure.authoring.StructureBundleNames; import art.arcane.iris.core.structure.authoring.StructureKey; import art.arcane.iris.core.structure.authoring.StructureSource; import art.arcane.iris.core.structure.authoring.StructureTransactionWriter; @@ -76,6 +84,7 @@ import java.nio.file.attribute.BasicFileAttributes; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; @@ -96,6 +105,7 @@ import java.util.stream.Stream; public final class DatapackIngestService { private static final String USER_AGENT = "VolmitSoftware/Iris (datapack-ingest)"; + private static final String NO_STRUCTURE_IMPORT_KEY = "datapack-structure-import-missing:"; private static final String FINDER_METADATA = ".DS_Store"; private static final String OVERRIDES_STRIPPED_MARKER = ".iris-overrides-stripped"; private static final String OWNERSHIP_MARKER = ".iris-managed.json"; @@ -3299,19 +3309,30 @@ public final class DatapackIngestService { } attemptedPacks++; try { - BulkStructureImporter.Report report = BulkStructureImporter.importManagedDatapackStructures( - data, - StructureImporter.Mode.OVERWRITE, - BukkitPlatform.console(), - structureKeys, - templateKeys + Optional structureImport = PackServices.of(data) + .providers(DatapackStructureImport.class).stream().findFirst(); + if (structureImport.isEmpty()) { + IrisLogging.warnOnce(NO_STRUCTURE_IMPORT_KEY + data.getDataFolder().getAbsolutePath(), + "Pack '%s' has no module that imports datapack structures; they stay pending until it has one.", + data.getDataFolder().getPath()); + failedUrls.addAll(pendingUrls); + reconcileFailedImportInventories(root, manifest, data, targetId, pendingUrls, entriesByUrl); + continue; + } + DatapackImportReport report = structureImport.get().importAll( + new IrisToolPack(data, IrisModuleHost.hostLog()), + IrisServices.get(PlatformStructures.class), + new VolmitToolSender(BukkitPlatform.console()), + resourceIds(structureKeys), + resourceIds(templateKeys) ); + Map importedBundles = bundleKeys(report); Set successfulPendingUrls = new HashSet<>(pendingUrls); Set incompleteUrls = new HashSet<>(); for (String pendingUrl : pendingUrls) { Entry entry = entriesByUrl.get(pendingUrl); Map desired = importBundleInventory(entry); - if (!report.successfulBundles().entrySet().containsAll(desired.entrySet())) { + if (!importedBundles.entrySet().containsAll(desired.entrySet())) { successfulPendingUrls.remove(pendingUrl); incompleteUrls.add(pendingUrl); failedUrls.add(pendingUrl); @@ -3613,13 +3634,23 @@ public final class DatapackIngestService { return bundles; } + private static List resourceIds(Collection keys) { + return keys.stream().map(ResourceId::ofPlatformKey).toList(); + } + + private static Map bundleKeys(DatapackImportReport report) { + Map bundles = new TreeMap<>(); + report.importedBundles().forEach((bundle, source) -> bundles.put(bundle, source.toString())); + return bundles; + } + static Map importBundleInventory(Entry entry) { Map bundles = new TreeMap<>(); for (String structureKey : copyList(entry.structureKeys)) { - bundles.put("iris:" + StructureImporter.deriveName(structureKey), structureKey); + bundles.put(StructureBundleNames.ofStructure(structureKey), structureKey); } for (String templateKey : copyList(entry.templateKeys)) { - bundles.put("iris:" + BulkStructureImporter.templateNameFor(templateKey), templateKey); + bundles.put(StructureBundleNames.ofTemplate(templateKey), templateKey); } return bundles; } diff --git a/core/src/main/java/art/arcane/iris/core/localization/BukkitRuntimeMessages.java b/core/src/main/java/art/arcane/iris/core/localization/BukkitRuntimeMessages.java index 9a76c4a2a..4d0986228 100644 --- a/core/src/main/java/art/arcane/iris/core/localization/BukkitRuntimeMessages.java +++ b/core/src/main/java/art/arcane/iris/core/localization/BukkitRuntimeMessages.java @@ -46,50 +46,6 @@ public final class BukkitRuntimeMessages { public static final TextKey COMMAND_PACK_MESSAGE_2 = text("iris.bukkit.runtime.commandpack.message_2"); public static final PluralKey COMMAND_PACK_MORE_WARNING_S = plural("iris.bukkit.runtime.commandpack.more_warning_s"); public static final LinesKey COMMAND_DEVELOPER_UPDATE_WORLD_WARNING = lines("iris.bukkit.runtime.commanddeveloper.update_world_warning"); - public static final TextKey BULK_STRUCTURE_IMPORTER_IMPORTING_VANILLA_DATAPACK_STRUCTURES_MODE_INCLUDENONJIGSAW = text("iris.bukkit.runtime.bulkstructureimporter.importing_vanilla_datapack_structures_mode_includenonjigsaw"); - public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_INVALID_KEY = text("iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key"); - public static final TextKey BULK_STRUCTURE_IMPORTER_JIGSAW = text("iris.bukkit.runtime.bulkstructureimporter.jigsaw"); - public static final TextKey BULK_STRUCTURE_IMPORTER_SINGLE = text("iris.bukkit.runtime.bulkstructureimporter.single"); - public static final TextKey BULK_STRUCTURE_IMPORTER_SKIP_NO_SINGLE_TEMPLATE_NBT_VANILLA_BUILDS_THIS_CODE_FROM_SEPARATE_PIECE = text("iris.bukkit.runtime.bulkstructureimporter.skip_no_single_template_nbt_vanilla_builds_this_code_from_separate_piece"); - public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL = text("iris.bukkit.runtime.bulkstructureimporter.fail"); - public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_2 = text("iris.bukkit.runtime.bulkstructureimporter.fail_2"); - public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_3 = text("iris.bukkit.runtime.bulkstructureimporter.fail_3"); - public static final TextKey BULK_STRUCTURE_IMPORTER_BULK_IMPORT_COMPLETE_IMPORTED_SKIPPED_FAILED_TOTAL = text("iris.bukkit.runtime.bulkstructureimporter.bulk_import_complete_imported_skipped_failed_total"); - public static final TextKey BULK_STRUCTURE_IMPORTER_BUILDING_SINGLE_TEMPLATE_STRUCTURES_FROM_IMPORTED_PIECES_ONE_VARIANT_PLACED_PER_GENERATION = text("iris.bukkit.runtime.bulkstructureimporter.building_single_template_structures_from_imported_pieces_one_variant_placed_per_generation"); - public static final TextKey BULK_STRUCTURE_IMPORTER_GROUP_VARIANTS = text("iris.bukkit.runtime.bulkstructureimporter.group_variants"); - public static final TextKey BULK_STRUCTURE_IMPORTER_SKIP = text("iris.bukkit.runtime.bulkstructureimporter.skip"); - public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_4 = text("iris.bukkit.runtime.bulkstructureimporter.fail_4"); - public static final TextKey BULK_STRUCTURE_IMPORTER_SINGLE_TEMPLATE_STRUCTURES_BUILT_SKIPPED_FAILED = text("iris.bukkit.runtime.bulkstructureimporter.single_template_structures_built_skipped_failed"); - public static final TextKey BULK_STRUCTURE_IMPORTER_FAILED_ENUMERATE_STRUCTURE_TEMPLATES_VIA_SERVER_RESOURCEMANAGER = text("iris.bukkit.runtime.bulkstructureimporter.failed_enumerate_structure_templates_via_server_resourcemanager"); - public static final TextKey BULK_STRUCTURE_IMPORTER_NO_STRUCTURE_TEMPLATES_WERE_FOUND_UNDER_STRUCTURE_RESOURCE_PATH = text("iris.bukkit.runtime.bulkstructureimporter.no_structure_templates_were_found_under_structure_resource_path"); - public static final TextKey BULK_STRUCTURE_IMPORTER_IMPORTING_STRUCTURE_TEMPLATES_MODE = text("iris.bukkit.runtime.bulkstructureimporter.importing_structure_templates_mode"); - public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_INVALID_KEY_2 = text("iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_2"); - public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_5 = text("iris.bukkit.runtime.bulkstructureimporter.fail_5"); - public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_6 = text("iris.bukkit.runtime.bulkstructureimporter.fail_6"); - public static final TextKey BULK_STRUCTURE_IMPORTER_IMPORTED_SKIPPED_FAILED = text("iris.bukkit.runtime.bulkstructureimporter.imported_skipped_failed"); - public static final TextKey BULK_STRUCTURE_IMPORTER_TEMPLATE_IMPORT_COMPLETE_IMPORTED_SKIPPED_FAILED_TOTAL = text("iris.bukkit.runtime.bulkstructureimporter.template_import_complete_imported_skipped_failed_total"); - public static final TextKey BULK_STRUCTURE_IMPORTER_NO_DATAPACK_NON_MINECRAFT_STRUCTURES_ARE_REGISTERED_INGEST_DATAPACK_RESTART_FIRST_THEN = text("iris.bukkit.runtime.bulkstructureimporter.no_datapack_non_minecraft_structures_are_registered_ingest_datapack_restart_first_then"); - public static final TextKey BULK_STRUCTURE_IMPORTER_IMPORTING_DATAPACK_STRUCTURES_MODE = text("iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structures_mode"); - public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_INVALID_KEY_3 = text("iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_3"); - public static final TextKey BULK_STRUCTURE_IMPORTER_JIGSAW_2 = text("iris.bukkit.runtime.bulkstructureimporter.jigsaw_2"); - public static final TextKey BULK_STRUCTURE_IMPORTER_SINGLE_2 = text("iris.bukkit.runtime.bulkstructureimporter.single_2"); - public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_7 = text("iris.bukkit.runtime.bulkstructureimporter.fail_7"); - public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_8 = text("iris.bukkit.runtime.bulkstructureimporter.fail_8"); - public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_9 = text("iris.bukkit.runtime.bulkstructureimporter.fail_9"); - public static final TextKey BULK_STRUCTURE_IMPORTER_IMPORTING_DATAPACK_STRUCTURE_TEMPLATES = text("iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structure_templates"); - public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_10 = text("iris.bukkit.runtime.bulkstructureimporter.fail_10"); - public static final TextKey BULK_STRUCTURE_IMPORTER_FAIL_11 = text("iris.bukkit.runtime.bulkstructureimporter.fail_11"); - public static final TextKey BULK_STRUCTURE_IMPORTER_COULD_NOT_ENUMERATE_DATAPACK_TEMPLATES_VIA_SERVER_RESOURCEMANAGER = text("iris.bukkit.runtime.bulkstructureimporter.could_not_enumerate_datapack_templates_via_server_resourcemanager"); - public static final TextKey BULK_STRUCTURE_IMPORTER_DATAPACK_STRUCTURE_IMPORT_COMPLETE_IMPORTED_SKIPPED_FAILED = text("iris.bukkit.runtime.bulkstructureimporter.datapack_structure_import_complete_imported_skipped_failed"); - public static final TextKey STRUCTURE_CAPTURE_IMPORTER_STRUCTURE_CAPTURE_IS_NOT_SUPPORTED_BY_ACTIVE_NMS_BINDING_SKIPPING_CAPTURE_PASS = text("iris.bukkit.runtime.structurecaptureimporter.structure_capture_is_not_supported_by_active_nms_binding_skipping_capture_pass"); - public static final TextKey STRUCTURE_CAPTURE_IMPORTER_NO_CODE_GENERATED_STRUCTURES_LEFT_CAPTURE_EVERYTHING_IS_ALREADY_IMPORTED_AS_STRUCTURE = text("iris.bukkit.runtime.structurecaptureimporter.no_code_generated_structures_left_capture_everything_is_already_imported_as_structure"); - public static final TextKey STRUCTURE_CAPTURE_IMPORTER_CAPTURING_CODE_GENERATED_STRUCTURES_NO_NBT_TEMPLATE_INTO_SCRATCH_WORLD_SKIPPING_ANY = text("iris.bukkit.runtime.structurecaptureimporter.capturing_code_generated_structures_no_nbt_template_into_scratch_world_skipping_any"); - public static final TextKey STRUCTURE_CAPTURE_IMPORTER_SKIP_DID_NOT_PLACE_CAPTURABLE_STRUCTURE_HERE_TOO_LARGE_WRONG_DIMENSION_NO = text("iris.bukkit.runtime.structurecaptureimporter.skip_did_not_place_capturable_structure_here_too_large_wrong_dimension_no"); - public static final TextKey STRUCTURE_CAPTURE_IMPORTER_FAIL = text("iris.bukkit.runtime.structurecaptureimporter.fail"); - public static final TextKey STRUCTURE_CAPTURE_IMPORTER_CAPTURE_OBJECTS_IOB_X_X = text("iris.bukkit.runtime.structurecaptureimporter.capture_objects_iob_x_x"); - public static final TextKey STRUCTURE_CAPTURE_IMPORTER_FAIL_2 = text("iris.bukkit.runtime.structurecaptureimporter.fail_2"); - public static final TextKey STRUCTURE_CAPTURE_IMPORTER_CAPTURED_SKIPPED_FAILED = text("iris.bukkit.runtime.structurecaptureimporter.captured_skipped_failed"); - public static final TextKey STRUCTURE_CAPTURE_IMPORTER_STRUCTURE_CAPTURE_COMPLETE_CAPTURED_SKIPPED_FAILED_TOTAL = text("iris.bukkit.runtime.structurecaptureimporter.structure_capture_complete_captured_skipped_failed_total"); public static final TextKey FEATURE_IMPORTER_NO_VANILLA_TREE_OBJECT_FEATURES_ARE_EXPOSED_BY_ACTIVE_NMS_BINDING_IMPORTING = text("iris.bukkit.runtime.featureimporter.no_vanilla_tree_object_features_are_exposed_by_active_nms_binding_importing"); public static final TextKey FEATURE_IMPORTER_IMPORTING_VANILLA_TREE_OBJECT_FEATURES_VARIANTS_EACH_INTO_SCRATCH_WORLD = text("iris.bukkit.runtime.featureimporter.importing_vanilla_tree_object_features_variants_each_into_scratch_world"); public static final TextKey FEATURE_IMPORTER_OBJ_OBJECTS_VANILLA = text("iris.bukkit.runtime.featureimporter.obj_objects_vanilla"); diff --git a/core/src/main/java/art/arcane/iris/core/modules/CarvedVoids.java b/core/src/main/java/art/arcane/iris/core/modules/CarvedVoids.java index b6ba9e0de..95f4fc4da 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/CarvedVoids.java +++ b/core/src/main/java/art/arcane/iris/core/modules/CarvedVoids.java @@ -175,6 +175,10 @@ final class CarvedVoids implements MantleLayer { } private CarvedVoid toApi(MatterCavern cavern) { + return toApi(cavern, ids); + } + + static CarvedVoid toApi(MatterCavern cavern, PackResourceIds ids) { CarvedVoid plain = switch (cavern.getLiquid()) { case LIQUID_FLUID -> CarvedVoid.FLUID; case LIQUID_LAVA -> CarvedVoid.LAVA; diff --git a/core/src/main/java/art/arcane/iris/core/modules/FitlessWorld.java b/core/src/main/java/art/arcane/iris/core/modules/FitlessWorld.java new file mode 100644 index 000000000..944f55b4f --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/FitlessWorld.java @@ -0,0 +1,122 @@ +package art.arcane.iris.core.modules; + +import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.config.PackSettings; +import com.volmit.host.ModuleLogs; +import com.volmit.item.ItemRegistry; +import com.volmit.noise.NoiseFactory; +import com.volmit.object.PackObjects; +import com.volmit.placement.Placements; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.resource.ResourceKind; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Function; + +/** + * The world a fit has outside any world: a start fitted with its memo needs nothing of a world but the noise its + * terrain carving draws on, which comes from plain styles. Everything else a fit could ask of a world fails, saying why. + */ +final class FitlessWorld implements PackWorld, PackResources { + private static final String OUTSIDE_A_WORLD = "The built-in modules fit outside a world here: a start needs its memo" + + " and a fit without palettes"; + private static final ResourceId PACK = ResourceId.parse("iris:fitless"); + + private final UUID snapshot = UUID.randomUUID(); + private final NoiseFactory noise = IrisNoiseFactory.standalone(); + + @Override + public long seed() { + throw outsideAWorld(); + } + + @Override + public PackResources resources() { + return this; + } + + @Override + public PackSettings settings() { + throw outsideAWorld(); + } + + @Override + public int minWorldY() { + throw outsideAWorld(); + } + + @Override + public Optional running() { + return Optional.empty(); + } + + @Override + public T state(Class type, Function create) { + throw outsideAWorld(); + } + + @Override + public Placements placements() { + throw outsideAWorld(); + } + + @Override + public ModuleLog log() { + return ModuleLogs.discarding(); + } + + @Override + public List services(Class service) { + throw outsideAWorld(); + } + + @Override + public ResourceId packId() { + return PACK; + } + + @Override + public UUID snapshotId() { + return snapshot; + } + + @Override + public BlockRegistry blocks() { + throw outsideAWorld(); + } + + @Override + public ItemRegistry items() { + throw outsideAWorld(); + } + + @Override + public NoiseFactory noise() { + return noise; + } + + @Override + public PackObjects objects() { + throw outsideAWorld(); + } + + @Override + public Optional find(ResourceKind kind, ResourceId id) { + throw outsideAWorld(); + } + + @Override + public List ids(ResourceKind kind) { + throw outsideAWorld(); + } + + private static IllegalStateException outsideAWorld() { + return new IllegalStateException(OUTSIDE_A_WORLD); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisBlockRegistry.java b/core/src/main/java/art/arcane/iris/core/modules/IrisBlockRegistry.java index 348127eff..6821f3ccd 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisBlockRegistry.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisBlockRegistry.java @@ -148,8 +148,14 @@ final class IrisBlockRegistry implements BlockRegistry { /** A block that cannot face the way it is turned is dropped, as Iris drops it: it becomes air. */ @Override public BlockState rotate(BlockState state, BlockTurn turn) { + return tryRotate(state, turn).orElse(PlatformBlockStates.AIR); + } + + /** Empty exactly when the platform has no state for the turned block, which is when Iris drops it. */ + @Override + public Optional tryRotate(BlockState state, BlockTurn turn) { PlatformBlockState rotated = BlockStateRotation.rotate(turn, platformState(state)); - return rotated == null ? PlatformBlockStates.AIR : apiState(rotated); + return rotated == null ? Optional.empty() : Optional.of(apiState(rotated)); } @Override diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisModuleHost.java b/core/src/main/java/art/arcane/iris/core/modules/IrisModuleHost.java index 32c295f81..b249be06a 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisModuleHost.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisModuleHost.java @@ -19,7 +19,6 @@ package art.arcane.iris.core.modules; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.mantle.components.StructureModule; import art.arcane.iris.spi.IrisPlatforms; import com.volmit.IrisModule; import com.volmit.ModuleLog; @@ -52,8 +51,14 @@ public final class IrisModuleHost { * and Gson, which every platform Iris runs on provides. */ public static final List SHARED_LIBRARY_PACKAGES = List.of("art.arcane.volmlib", "com.google.gson"); + /** + * The structure file transactions Iris's datapack ingest and the jigsaw module's tools both run, which each would + * otherwise see as a copy of its own; exposed with its subpackages. + */ + public static final String STRUCTURE_FILES_PACKAGE = "art.arcane.iris.core.structure.authoring"; /** Every package pack modules may use besides the IrisApi. {@code exposedHostPackages} in IrisModule's build lists the same. */ - public static final List EXPOSED_PACKAGES = Stream.concat(Stream.of(BUILT_IN_API_PACKAGE), SHARED_LIBRARY_PACKAGES.stream()).toList(); + public static final List EXPOSED_PACKAGES = Stream.concat(Stream.of(BUILT_IN_API_PACKAGE, STRUCTURE_FILES_PACKAGE), + SHARED_LIBRARY_PACKAGES.stream()).toList(); /** * The ids of the built-in modules that ship in the built-ins jar ({@code iris-builtins.jar}, listed in * {@code IrisModule/builtin-modules.txt}) instead of being compiled into Iris. Every pack loads them from the jar Iris @@ -62,9 +67,15 @@ public final class IrisModuleHost { public static final List JAR_MODULE_IDS = List.of("iris:post", "iris:perfection", "iris:matter", "iris:loot", "iris:spawn", "iris:prepare", "iris:anchor", "iris:validate", "iris:bore", "iris:blocks", "iris:stilt", "iris:vacuum", "iris:snow", "iris:vanilla-features", "iris:carve", "iris:deposit", "iris:decorant", "iris:terrain", "iris:objects", - "iris:floating"); - /** Iris's pack object model: built-in settings may hold these classes, which Iris reads and describes itself. */ - public static final String HOST_TYPE_PACKAGE = "art.arcane.iris.engine.object"; + "iris:floating", "iris:structure", "iris:jigsaw"); + /** + * Iris's pack object model: built-in settings may hold these classes, which Iris reads and describes itself. The + * structure model (engine.object.structure) is not among them: it speaks the api's vocabulary and its module describes it. + */ + public static final String[] HOST_TYPE_PACKAGES = Stream.of("annotations", "compatibility", "image", "material", "noise", + "placement", "prefab", "runtime", "terrain", "value", "world") + .map(subpackage -> "art.arcane.iris.engine.object." + subpackage) + .toArray(String[]::new); private static final String[] JAR_COPY_FOLDER = {"cache", "module-jars"}; private static final String BUNDLED_JAR_RESOURCE = "/" + MissingBuiltInModules.JAR_NAME; private static final String BUNDLED_JAR_TEMPORARY_PREFIX = "iris-built-in-modules-"; @@ -84,11 +95,10 @@ public final class IrisModuleHost { /** * Modules Iris registers itself, not from the built-ins jar: those that are Iris (they write the layout's platform - * biomes, record the platform's custom blocks and answer for Iris's structure model) and {@code iris:structure}, whose - * resources Iris's jigsaw studio reads as the same classes. A pack never replaces them. + * biomes and record the platform's custom blocks). A pack never replaces them. */ private static List hostModules() { - return List.of(new BiomeModule(), new CustomModule(), new StructureModule(), new StructureModelModule()); + return List.of(new BiomeModule(), new CustomModule()); } /** Iris's own log, labelled {@code [iris]}, for host code that calls module classes outside any module's stage, service or hook. */ @@ -98,14 +108,14 @@ public final class IrisModuleHost { /** Whether {@code type} is one of Iris's own classes that built-in settings may hold. */ public static boolean isHostType(Class type) { - return type.getName().startsWith(HOST_TYPE_PACKAGE + "."); + return Stream.of(HOST_TYPE_PACKAGES).anyMatch(hostPackage -> type.getName().startsWith(hostPackage + ".")); } private static ModuleHost build() { return ModuleHost.of(builtInModules()) .exposing(EXPOSED_PACKAGES.toArray(String[]::new)) .reservingFields(ModuleTargets.reservedFields()) - .describingHostTypesIn(HOST_TYPE_PACKAGE) + .describingHostTypesIn(HOST_TYPE_PACKAGES) .reservingFolders(IrisData.ownFolderNames().toArray(String[]::new)) .bundlingJars(bundledJars()) .copyingJarsTo(jarCopyRoot()) diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisNoiseFactory.java b/core/src/main/java/art/arcane/iris/core/modules/IrisNoiseFactory.java index 1c7c480df..345fc1905 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisNoiseFactory.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisNoiseFactory.java @@ -49,6 +49,11 @@ final class IrisNoiseFactory implements NoiseFactory { this.resources = resources; } + /** Noise with no pack behind it: the plain styles, but no expressions and no image maps. */ + static IrisNoiseFactory standalone() { + return new IrisNoiseFactory(null, null); + } + @Override public NoiseSampler sampler(NoiseStyle style, long seed) { IrisGeneratorStyle iris = styles.computeIfAbsent(style, unbuilt -> IrisValues.generatorStyle(unbuilt, resources)); diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java b/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java index e58251356..b1afa6f37 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisPackResources.java @@ -167,6 +167,11 @@ public final class IrisPackResources implements PackResources { return kindOf(kind).ids(); } + @Override + public List services(Class service) { + return PackServices.of(data).providers(service); + } + /** * The ids of the resources of the kind {@code kindId} names, for Iris's own tools that list a module's resources * without the module's class for them, which the plugin's classes cannot reach when the kind ships in a module jar. diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisPackSettings.java b/core/src/main/java/art/arcane/iris/core/modules/IrisPackSettings.java index 9f19e9a38..cc1911621 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisPackSettings.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisPackSettings.java @@ -19,7 +19,6 @@ package art.arcane.iris.core.modules; import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.builtin.structure.StructureHost; import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.dimension.IrisDimension; @@ -40,8 +39,8 @@ import java.util.Optional; /** * The settings an engine's pack declares, for working out mantle stage reaches when the pack loads and for vanilla * structure hooks: the engine's dimension, then every region it can reach, then every biome. Iris's built-in modules - * decide from Iris's own pack data instead of module settings; they reach it through the object, floating and structure - * hosts the settings offer as {@linkplain #extension extensions}. + * decide from Iris's own pack data instead of module settings; they reach it through the engine the settings offer as an + * {@linkplain #extension extension}. */ public final class IrisPackSettings implements PackSettings { static final String DIMENSION = "dimension"; @@ -71,15 +70,9 @@ public final class IrisPackSettings implements PackSettings { return HostExtensions.as(type, offered(type)); } - /** The engine is offered only for the structure built-ins, which drive Iris's structure locator themselves. */ + /** The engine is offered only for the built-ins that read Iris's own pack data. */ private Object offered(Class type) { - if (type == Engine.class) { - return engine; - } - if (type == StructureHost.class) { - return new IrisStructureHost(engine, IrisApiLogger.hostLog()); - } - return null; + return type == Engine.class ? engine : null; } @Override diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java b/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java index 154055c67..0475f381f 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java @@ -18,14 +18,17 @@ package art.arcane.iris.core.modules; -import art.arcane.iris.builtin.structure.StructureHost; +import art.arcane.iris.builtin.structure.StructureVerifier; +import art.arcane.iris.builtin.structure.StructureSeeds; import art.arcane.iris.engine.framework.Engine; import com.volmit.ModuleLog; import com.volmit.config.PackSettings; import com.volmit.host.WorldStates; import com.volmit.placement.Placements; +import com.volmit.resource.ResourceId; import com.volmit.world.PackWorld; import com.volmit.world.RunningWorld; +import java.util.List; import java.util.Optional; import java.util.function.Function; @@ -33,7 +36,7 @@ import java.util.function.Function; * One Iris world as modules see it: an engine runtime generating with one snapshot of its pack's resources, and the * state modules keep for it. {@link ModuleWorlds} makes one when the runtime is built and a new one whenever the * pack's resources reload under it. Iris's built-in modules reach what they need of Iris through its - * {@linkplain #extension extensions}: the structure host. + * {@linkplain #extension extensions}: the engine and the structure verifier. */ public final class IrisPackWorld implements PackWorld { private final Engine engine; @@ -42,7 +45,7 @@ public final class IrisPackWorld implements PackWorld { private final ModuleLog log; private final IrisRunningWorld running; private final Placements placements; - private final IrisStructureHost structureHost; + private final StructureVerifier structureVerifier; IrisPackWorld(Engine engine) { this.engine = engine; @@ -51,7 +54,7 @@ public final class IrisPackWorld implements PackWorld { this.log = IrisApiLogger.hostLog(); this.placements = new IrisPlacements(engine.getData(), engine, () -> this); this.running = new IrisRunningWorld(engine, log); - this.structureHost = new IrisStructureHost(engine, log); + this.structureVerifier = (context, radiusChunks) -> StructureVerification.run(engine, context, radiusChunks); } @Override @@ -69,6 +72,14 @@ public final class IrisPackWorld implements PackWorld { return engine.getSeedManager().getSeed(); } + @Override + public long seed(ResourceId purpose) { + if (StructureSeeds.PLACEMENT.equals(purpose)) { + return engine.getSeedManager().getMantle(); + } + return PackWorld.super.seed(purpose); + } + @Override public IrisPackResources resources() { @@ -77,7 +88,7 @@ public final class IrisPackWorld implements PackWorld { @Override public int minWorldY() { - return engine.getWorld().minHeight(); + return engine.getMinHeight(); } @Override @@ -100,6 +111,11 @@ public final class IrisPackWorld implements PackWorld { return states.state(type, () -> create.apply(this)); } + @Override + public List services(Class service) { + return PackServices.of(engine.getData()).providers(service); + } + @Override public ModuleLog log() { return log; @@ -115,8 +131,8 @@ public final class IrisPackWorld implements PackWorld { if (type == Engine.class) { return engine; } - if (type == StructureHost.class) { - return structureHost; + if (type == StructureVerifier.class) { + return structureVerifier; } return null; } diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisRunningWorld.java b/core/src/main/java/art/arcane/iris/core/modules/IrisRunningWorld.java index 23a06abee..f5c77730e 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisRunningWorld.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisRunningWorld.java @@ -24,11 +24,13 @@ import art.arcane.iris.spi.PlatformWorld; import art.arcane.iris.util.common.scheduling.J; import art.arcane.volmlib.util.mantle.runtime.MantleChunk; import art.arcane.volmlib.util.matter.Matter; +import art.arcane.volmlib.util.matter.MatterCavern; import art.arcane.volmlib.util.matter.slices.MarkerMatter; import com.volmit.ModuleLog; import com.volmit.config.FeatureSettings; import com.volmit.data.SavedKey; import com.volmit.geometry.BlockPosition; +import com.volmit.mantle.CarvedVoid; import com.volmit.placement.PlacementRecord; import com.volmit.resource.ResourceId; import com.volmit.world.RunningWorld; @@ -139,6 +141,12 @@ final class IrisRunningWorld implements RunningWorld { } } + @Override + public Optional carvedAt(int worldX, int y, int worldZ) { + MatterCavern cavern = engine.getMantle().getMantle().get(worldX, y, worldZ, MatterCavern.class); + return Optional.ofNullable(cavern).map(carved -> CarvedVoids.toApi(carved, packIds())); + } + @Override public boolean debug() { return engine.isStudio(); diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisStructureHost.java b/core/src/main/java/art/arcane/iris/core/modules/IrisStructureHost.java deleted file mode 100644 index 89de8d425..000000000 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisStructureHost.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * 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.builtin.structure.StructureHost; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.structure.StructureResources; -import art.arcane.iris.engine.mantle.components.StructurePlacing; -import art.arcane.iris.engine.object.structure.IrisStructure; -import com.volmit.ModuleLog; -import com.volmit.generation.InvocationContext; -import com.volmit.resource.ResourceId; - -import java.util.List; -import java.util.Optional; - -/** Iris's {@link StructureHost}: the engine's {@link StructurePlacing}, one per engine runtime, places and sizes its structures. */ -final class IrisStructureHost implements StructureHost { - private final Engine engine; - private final ModuleLog log; - - IrisStructureHost(Engine engine, ModuleLog log) { - this.engine = engine; - this.log = log; - } - - @Override - public void placeChunk(InvocationContext context) { - IrisMantleChunk chunk = context.extension(IrisMantleChunk.class).orElseThrow(); - placing().place(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); - } - - @Override - public int reach() { - return placing().reach(); - } - - @Override - public Optional> lootTables(ResourceId structureId) { - IrisPackResources resources = engine.getData().getPackResources(); - IrisStructure structure = StructureResources.structure(resources, resources.keyOf(structureId)); - if (structure == null) { - return Optional.empty(); - } - if (structure.getLoot() == null) { - return Optional.of(List.of()); - } - return Optional.of(structure.getLoot().stream().filter(table -> table != null && !table.isBlank()).toList()); - } - - private StructurePlacing placing() { - return engine.getGeneration().state(StructurePlacing.class, generating -> new StructurePlacing(generating, log)); - } -} 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 455064e89..130a921fb 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 @@ -90,6 +90,11 @@ public final class IrisValidationContext implements ValidationContext { return platform; } + @Override + public List services(Class service) { + return PackServices.of(data).providers(service); + } + @Override public void report(Problem problem) { problems.add(Objects.requireNonNull(problem, "problem")); diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleObjectPlacement.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleObjectPlacement.java index 9f831a32d..09d6bc87f 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleObjectPlacement.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleObjectPlacement.java @@ -99,7 +99,7 @@ public final class ModuleObjectPlacement { } long worldSeed = rng.nextLong(); try (ToolWorld toolWorld = new ToolWorld(worldSeed, data.getPackResources(), new PackDeclaredSettings(data), - world -> new IrisPlacements(data, null, () -> world))) { + PackServices.of(data), world -> new IrisPlacements(data, null, () -> world))) { return run.placeIn(toolWorld, terrain); } } diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleStructureFitting.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleStructureFitting.java index 68184f221..c2a74d456 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleStructureFitting.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleStructureFitting.java @@ -28,6 +28,7 @@ import art.arcane.iris.engine.framework.nativefit.NativeFitStart; import art.arcane.iris.engine.framework.nativefit.NativeFitTrait; import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting; import art.arcane.iris.engine.framework.nativefit.NativeTemplateCells; +import com.volmit.IrisModule; import com.volmit.block.BlockState; import com.volmit.block.BlockTrait; import com.volmit.host.DiscoveredModule; @@ -62,6 +63,7 @@ import java.util.Optional; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; +import java.util.stream.Stream; /** * The pack's {@link VanillaStructures} providers fitting the platform's starts into a chunk: the platform code's view @@ -92,14 +94,16 @@ public final class ModuleStructureFitting implements NativeStructureFitting { () -> engine.getGeneration().world()); } - /** The built-in modules' registrations only: their stage graph needs the modules of the built-ins jar too. */ - public static NativeStructureFitting builtInModules() { + /** + * Iris's own modules' and {@code modules}' registrations only, whose classes the caller names because they ship in the + * built-ins jar: their stage graph needs the rest of the jar too. + */ + public static NativeStructureFitting ofModules(IrisModule... modules) { ModuleRegistry registry = new ModuleRegistry(); - IrisModuleHost.builtInModules().forEach(module -> ModuleSetups.run(DiscoveredModule.builtIn(module), new StageGraphBuilder(), registry)); - return new ModuleStructureFitting(registry.freeze().registrations(VanillaStructures.class), () -> { - throw new IllegalStateException("The built-in modules fit outside a world here: a start needs its memo" - + " and a fit without palettes"); - }); + Stream.concat(IrisModuleHost.builtInModules().stream(), Stream.of(modules)) + .forEach(module -> ModuleSetups.run(DiscoveredModule.builtIn(module), new StageGraphBuilder(), registry)); + FitlessWorld fitless = new FitlessWorld(); + return new ModuleStructureFitting(registry.freeze().registrations(VanillaStructures.class), () -> fitless); } @Override diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleVanillaStructures.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleVanillaStructures.java index 85bd455d9..c0efc8183 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleVanillaStructures.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleVanillaStructures.java @@ -54,6 +54,7 @@ import java.util.OptionalInt; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; +import java.util.function.Supplier; /** * What the pack's modules want for the platform's own structures, asked through their {@link VanillaStructures} @@ -77,7 +78,8 @@ public final class ModuleVanillaStructures { private ModuleVanillaStructures(Engine engine, PackResources snapshot) { this.snapshot = snapshot; this.providers = providersOf(engine.getData()); - this.world = new World(snapshot, new IrisPackSettings(engine)); + this.world = new World(snapshot, new IrisPackSettings(engine), + () -> Optional.of(engine.getGeneration().world())); } /** The combined rule of the pack's modules for the platform structure {@code structureKey} in {@code engine}'s world. */ @@ -139,7 +141,7 @@ public final class ModuleVanillaStructures { /** The combined setup of the pack's modules for {@code dimension} of the pack {@code data} serves, before any world exists. */ public static VanillaStructureSetup setupFor(IrisData data, IrisDimension dimension) { - VanillaStructureContext context = new World(data.getPackResources(), new DimensionSettings(data, dimension)); + VanillaStructureContext context = new World(data.getPackResources(), new DimensionSettings(data, dimension), Optional::empty); VanillaStructureSetup combined = VanillaStructureSetup.UNCHANGED; for (ServiceRegistration registration : providersOf(data)) { combined = combined.and(ask(registration, "setting up the vanilla structures of dimension " + dimension.getLoadKey(), @@ -241,7 +243,12 @@ public final class ModuleVanillaStructures { } /** The world the providers decide for: the engine's pack snapshot and the settings its dimension reaches. */ - private record World(PackResources resources, PackSettings settings) implements VanillaStructureContext { + private record World(PackResources resources, PackSettings settings, Supplier> worldSource) + implements VanillaStructureContext { + @Override + public Optional world() { + return worldSource.get(); + } } private record StartContext(PackWorld world, TerrainSampler terrain) implements VanillaStructureStartContext { diff --git a/core/src/main/java/art/arcane/iris/core/modules/ObjectGeometry.java b/core/src/main/java/art/arcane/iris/core/modules/ObjectGeometry.java index f7aeca794..6ccfd8da6 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ObjectGeometry.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ObjectGeometry.java @@ -56,6 +56,24 @@ public final class ObjectGeometry { } } + /** + * Like {@link #of}, but the bounds are the size the object file declares around its center, not the box of its blocks, + * so the file can be written again at the size it had. + */ + public static GeneratedObject ofDeclared(IrisObject object) { + object.readLock.lock(); + try { + int centerX = object.w / 2; + int centerY = object.h / 2; + int centerZ = object.d / 2; + BlockBox declared = new BlockBox(-centerX, -centerY, -centerZ, + object.w - centerX, object.h - centerY, object.d - centerZ); + return new GeneratedObject(declared, CENTER, blocksOf(object), List.of()); + } finally { + object.readLock.unlock(); + } + } + private static List blocksOf(IrisObject object) { Map blocks = new LinkedHashMap<>(); for (Map.Entry entry : object.blocks) { diff --git a/core/src/main/java/art/arcane/iris/core/modules/PackDeclaredSettings.java b/core/src/main/java/art/arcane/iris/core/modules/PackDeclaredSettings.java index ef659c349..227d53d96 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/PackDeclaredSettings.java +++ b/core/src/main/java/art/arcane/iris/core/modules/PackDeclaredSettings.java @@ -28,9 +28,11 @@ import com.volmit.config.PackSettings; import com.volmit.config.SettingsStack; import com.volmit.resource.PackResources; +import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Optional; /** * The settings a whole pack declares, for validators: every dimension of the pack, then every region, then every @@ -51,6 +53,12 @@ final class PackDeclaredSettings implements PackSettings { return data.getPackResources(); } + /** The pack's folder is offered as a {@link File}, for checks that read the files of the pack as written. */ + @Override + public Optional extension(Class type) { + return HostExtensions.as(type, type == File.class ? data.getDataFolder() : null); + } + @Override public SettingsStack declared(Class featureType) { List> entries = new ArrayList<>(); diff --git a/core/src/main/java/art/arcane/iris/core/modules/PackServices.java b/core/src/main/java/art/arcane/iris/core/modules/PackServices.java new file mode 100644 index 000000000..cb0f252f5 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/PackServices.java @@ -0,0 +1,49 @@ +/* + * 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.loader.IrisData; + +import java.util.List; +import java.util.Objects; + +/** + * The service providers of one pack's modules, as {@code PackWorld.services}, {@code ValidationContext.services} and + * {@code ToolPack.services} answer them. Asking a pack whose modules fail to load throws its {@link PackModulesException}. + */ +@FunctionalInterface +public interface PackServices { + /** + * Every provider of {@code service}, in module id order; empty when no module provides it. + * + * @throws IllegalArgumentException when {@code service} is not an interface marked as a service + */ + List providers(Class service); + + /** The providers of the modules of the pack {@code data} holds, looked up whenever they are asked for. */ + static PackServices of(IrisData data) { + Objects.requireNonNull(data, "data"); + return new PackServices() { + @Override + public List providers(Class service) { + return data.getModules().pack().catalog().services(service); + } + }; + } +} diff --git a/core/src/main/java/art/arcane/iris/core/modules/PlacerTerrain.java b/core/src/main/java/art/arcane/iris/core/modules/PlacerTerrain.java index 428601a1b..af9e0dddc 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/PlacerTerrain.java +++ b/core/src/main/java/art/arcane/iris/core/modules/PlacerTerrain.java @@ -120,6 +120,19 @@ final class PlacerTerrain implements PlacementTerrain { } } + @Override + public void clearBlock(int x, int y, int z) { + placer.clearBlock(x, y, z); + if (written != null) { + written.remove(new BlockPosition(x, y, z)); + } + } + + @Override + public void clearAttached(int x, int y, int z) { + placer.clearAttached(x, y, z); + } + @Override public boolean isCarved(int x, int y, int z) { return placer.isCarved(x, y, z); diff --git a/core/src/main/java/art/arcane/iris/core/modules/StructureAssemblies.java b/core/src/main/java/art/arcane/iris/core/modules/StructureAssemblies.java deleted file mode 100644 index 77fed47dd..000000000 --- a/core/src/main/java/art/arcane/iris/core/modules/StructureAssemblies.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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.loader.IrisData; -import art.arcane.iris.engine.framework.StructureAssembler; -import art.arcane.iris.engine.object.structure.IrisStructure; -import art.arcane.iris.engine.object.value.IrisPosition; - -/** - * Structure assembly for Iris's own tools, the commands and studio, which run outside any module's stage, service or hook and so - * log as Iris itself. - */ -public final class StructureAssemblies { - private StructureAssemblies() { - } - - /** The assembler of {@code structure}, compiled from the pack {@code data} serves, for a start at {@code origin}. */ - public static StructureAssembler forData(IrisData data, IrisStructure structure, IrisPosition origin) { - return StructureAssembler.forData(data, structure, origin, IrisModuleHost.hostLog()); - } -} 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 deleted file mode 100644 index 9bc980943..000000000 --- a/core/src/main/java/art/arcane/iris/core/modules/StructureCommands.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * 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 module 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 deleted file mode 100644 index 2ea29608b..000000000 --- a/core/src/main/java/art/arcane/iris/core/modules/StructureModelModule.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * 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.structure.StructureLocating; -import art.arcane.iris.engine.framework.structure.StructureResources; -import art.arcane.iris.engine.framework.structure.StructureValidator; -import art.arcane.iris.engine.framework.structure.StructureVanillaStructures; -import com.volmit.IrisModule; -import com.volmit.ModuleInfo; -import com.volmit.ModuleSetup; -import com.volmit.service.StructureLocator; -import com.volmit.service.VanillaStructures; - -/** - * Module {@code iris:structure-model}: the parts of Iris's jigsaw structures that still need Iris itself. The structures, - * jigsaw pools and jigsaw pieces are resource kinds of {@code iris:structure} ({@link StructureResources}). - *

- * It checks them with {@link StructureValidator} wherever Iris validates a pack. It lets Iris find its structures - * through {@link StructureLocating}; a world's structure index lives in the - * world's state, so a reload of the pack's structure files, which starts a new world, builds it again. - *

- * It decides over the platform's own structures through its {@link VanillaStructures} provider - * ({@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 module structure list|info|verify} ({@link StructureCommands}) through the tooling api. - */ -public final class StructureModelModule implements IrisModule { - private static final String VERSION = "built-in"; - - @Override - public ModuleInfo info() { - return ModuleInfo.of("iris:structure-model", "Structure model", VERSION); - } - - @Override - public void setup(ModuleSetup setup) { - var registry = setup.registry(); - 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 index 2dfc61935..cfd3e315a 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/StructureVerification.java +++ b/core/src/main/java/art/arcane/iris/core/modules/StructureVerification.java @@ -18,14 +18,13 @@ package art.arcane.iris.core.modules; +import art.arcane.iris.builtin.structure.StructureVerifier; 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; @@ -36,17 +35,12 @@ import java.util.TreeSet; /** * {@code /iris module 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. + * Native eligibility is decided without the platform's blocking locate. The command is {@code iris:structure}'s; the world + * offers this to it as its {@link StructureVerifier}. */ 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; @@ -64,15 +58,8 @@ final class StructureVerification { 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..."); + static void run(Engine engine, CommandContext context, int radiusChunks) { + context.sender().info("Verifying structures within " + radiusChunks + " chunks of the world origin..."); new StructureVerification(engine, context, radiusChunks).report(); } diff --git a/core/src/main/java/art/arcane/iris/core/modules/ToolWorld.java b/core/src/main/java/art/arcane/iris/core/modules/ToolWorld.java index 5188401ae..a00e15775 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ToolWorld.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ToolWorld.java @@ -27,6 +27,7 @@ import com.volmit.resource.PackResources; import com.volmit.world.PackWorld; import com.volmit.world.RunningWorld; +import java.util.List; import java.util.Optional; import java.util.function.Function; @@ -42,12 +43,15 @@ final class ToolWorld implements PackWorld, AutoCloseable { private final WorldStates states; private final ModuleLog log; private final Placements placements; + private final PackServices services; - /** {@code placements} makes the placements of the new world. */ - ToolWorld(long seed, PackResources resources, PackSettings settings, Function placements) { + /** {@code placements} makes the placements of the new world; {@code services} are those of the pack's modules. */ + ToolWorld(long seed, PackResources resources, PackSettings settings, PackServices services, + Function placements) { this.seeds = new SeedManager(seed); this.resources = resources; this.settings = settings; + this.services = services; this.states = new WorldStates(); this.log = IrisApiLogger.hostLog(); this.placements = placements.apply(this); @@ -91,6 +95,11 @@ final class ToolWorld implements PackWorld, AutoCloseable { return states.state(type, () -> create.apply(this)); } + @Override + public List services(Class service) { + return services.providers(service); + } + @Override public ModuleLog log() { return log; diff --git a/core/src/main/java/art/arcane/iris/core/pack/ModuleResourceClosure.java b/core/src/main/java/art/arcane/iris/core/pack/ModuleResourceClosure.java index 322914944..44d7b1393 100644 --- a/core/src/main/java/art/arcane/iris/core/pack/ModuleResourceClosure.java +++ b/core/src/main/java/art/arcane/iris/core/pack/ModuleResourceClosure.java @@ -23,13 +23,13 @@ import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.loader.IrisRegistrant; import art.arcane.iris.core.modules.IrisPackResources; import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.volmlib.util.io.IO; import art.arcane.volmlib.util.json.JSONObject; import com.google.gson.Gson; import com.volmit.config.ResourceRef; import com.volmit.host.ResourceKindRegistration; import com.volmit.object.GeneratedObject; +import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceKind; import java.io.File; @@ -62,15 +62,21 @@ public final class ModuleResourceClosure { private final IrisData data; private final Map, ResourceKind> kindsByType = new HashMap<>(); + private final Class structureType; private final Map, Map> found = new LinkedHashMap<>(); private final Set visited = java.util.Collections.newSetFromMap(new IdentityHashMap<>()); private final Set objectKeys = new TreeSet<>(); public ModuleResourceClosure(IrisData data) { this.data = data; + Class structures = null; for (ResourceKindRegistration registration : data.getModules().pack().catalog().resourceKinds()) { kindsByType.put(registration.kind().type(), registration.kind()); + if (registration.kind().id().equals(IrisStructureRef.KIND)) { + structures = registration.kind().type(); + } } + this.structureType = structures; } /** Adds the resources that the module settings of {@code owner} reference, and those they reference. */ @@ -118,6 +124,15 @@ public final class ModuleResourceClosure { return kind == null || !found.containsKey(kind) ? List.of() : new ArrayList<>(new TreeMap<>(found.get(kind)).keySet()); } + /** The keys of the resources found of the kind {@code kindId}, in key order, for a kind whose class Iris cannot name. */ + public List keysOf(ResourceId kindId) { + return kindsByType.values().stream() + .filter(kind -> kind.id().equals(kindId)) + .findFirst() + .map(kind -> found.containsKey(kind) ? new ArrayList<>(new TreeMap<>(found.get(kind)).keySet()) : new ArrayList()) + .orElseGet(ArrayList::new); + } + /** * The keys of the pack objects that what was found references, in key order. Objects are Iris's own files, not a * module kind, so the export copies them itself. @@ -165,13 +180,13 @@ public final class ModuleResourceClosure { } /** The class of the resources the field names by key, or null when it names none. */ - private static Class referencedType(Field field) { + private Class referencedType(Field field) { ResourceRef reference = field.getAnnotation(ResourceRef.class); if (reference != null) { return reference.value(); } if (field.isAnnotationPresent(IrisStructureRef.class)) { - return IrisStructure.class; + return structureType; } RegistryListResource registry = field.getAnnotation(RegistryListResource.class); return registry == null ? null : registry.value(); diff --git a/core/src/main/java/art/arcane/iris/core/project/SchemaBuilder.java b/core/src/main/java/art/arcane/iris/core/project/SchemaBuilder.java index f371cbe39..afb0c75d2 100644 --- a/core/src/main/java/art/arcane/iris/core/project/SchemaBuilder.java +++ b/core/src/main/java/art/arcane/iris/core/project/SchemaBuilder.java @@ -33,7 +33,6 @@ import art.arcane.iris.engine.object.image.IrisImageMap; import art.arcane.iris.engine.object.noise.NoiseStyle; import art.arcane.iris.engine.object.noise.expression.IrisExpression; import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.framework.ListFunction; @@ -491,7 +490,7 @@ public class SchemaBuilder { if (field.isEmpty() || !field.get().isAnnotationPresent(IrisStructureRef.class)) { return; } - putPackResourceRef(property, IrisStructure.class); + completeResourceReference(property, IrisStructureRef.KIND); } private static Optional declaredField(String typeName, String fieldName) { diff --git a/core/src/main/java/art/arcane/iris/core/runtime/StudioOpenCoordinator.java b/core/src/main/java/art/arcane/iris/core/runtime/StudioOpenCoordinator.java index 35b523d05..0747f3cb8 100644 --- a/core/src/main/java/art/arcane/iris/core/runtime/StudioOpenCoordinator.java +++ b/core/src/main/java/art/arcane/iris/core/runtime/StudioOpenCoordinator.java @@ -97,6 +97,16 @@ public final class StudioOpenCoordinator { return closeWorldCoordinated(provider, worldName, world, true, project); } + /** + * Unloads a tool world and deletes its files, reserving the world mutation lock like a studio close. Players must be + * gone from it already; any that remain are sent to the spawn of another world. + */ + public CompletableFuture closeToolWorld(World world, IrisProject project) { + Objects.requireNonNull(world, "world"); + PlatformChunkGenerator provider = IrisToolbelt.access(world); + return closeWorldCoordinated(provider, IrisWorldStorage.logicalName(world), world, true, project); + } + public CompletableFuture teleportPlayerToProject( IrisProject project, Player player @@ -782,7 +792,7 @@ public final class StudioOpenCoordinator { } String transientName = TransientWorldCleanupSupport.transientStudioBaseWorldName( child.getFileName().toString()); - if (transientName != null) { + if (transientName != null && !StudioPainterSlots.isInstalled(transientName)) { worldNames.add(transientName); } } @@ -932,7 +942,7 @@ public final class StudioOpenCoordinator { false, true, IrisCreator.DatapackPreparation.REUSE_LOADED_RUNTIME_IF_READY), - JIGSAW( + TOOL( false, false, IrisCreator.DatapackPreparation.REUSE_LOADED_RUNTIME_IF_READY); @@ -962,7 +972,7 @@ public final class StudioOpenCoordinator { } public boolean prepareGeneratorState() { - return this != JIGSAW; + return this != TOOL; } public IrisCreator.DatapackPreparation datapackPreparation() { diff --git a/core/src/main/java/art/arcane/iris/core/runtime/StudioPainterSlots.java b/core/src/main/java/art/arcane/iris/core/runtime/StudioPainterSlots.java new file mode 100644 index 000000000..3d019e9c3 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/runtime/StudioPainterSlots.java @@ -0,0 +1,96 @@ +/* + * 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.runtime; + +import com.volmit.object.BlockEntityData; +import com.volmit.tooling.world.ChunkPainter; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Consumer; + +/** + * Which studio worlds are painted by a tool instead of generated from their pack, keyed by the logical name of the + * world. A tool world installs its slot before the world is created, so the first chunk the world generates is already + * the tool's, and removes it when the world closes. The world's generator reads the slot on every chunk, so a slot that + * is installed or removed takes effect at the next chunk. + */ +public final class StudioPainterSlots { + private static final Map SLOTS = new ConcurrentHashMap<>(); + + private StudioPainterSlots() { + } + + /** + * A tool's claim on one world: the painter, and where the block entities it painted go. They go to + * {@code blockEntities} because they can only be applied once the chunk is live, which is later than the paint. + */ + public record Slot(ChunkPainter painter, Consumer blockEntities) { + public Slot { + Objects.requireNonNull(painter, "painter"); + Objects.requireNonNull(blockEntities, "blockEntities"); + } + } + + /** The block entities one paint of chunk {@code chunkX}, {@code chunkZ} asked for; never empty. */ + public record PaintedChunk(int chunkX, int chunkZ, List blockEntities) { + public PaintedChunk { + blockEntities = List.copyOf(blockEntities); + } + } + + /** A block entity at chunk-local {@code x} and {@code z} and world {@code y}. */ + public record PaintedBlockEntity(int x, int y, int z, BlockEntityData data) { + public PaintedBlockEntity { + Objects.requireNonNull(data, "data"); + } + } + + /** + * Makes the world called {@code worldName} a painted one. + * + * @throws IllegalStateException when a tool painted that world already + */ + public static void install(String worldName, Slot slot) { + Objects.requireNonNull(worldName, "worldName"); + Objects.requireNonNull(slot, "slot"); + if (SLOTS.putIfAbsent(worldName, slot) != null) { + throw new IllegalStateException("The world " + worldName + " is painted by a tool already"); + } + } + + /** The slot of the world called {@code worldName}; empty for a world generated from its pack. */ + public static Optional slotOf(String worldName) { + return worldName == null ? Optional.empty() : Optional.ofNullable(SLOTS.get(worldName)); + } + + public static boolean isInstalled(String worldName) { + return slotOf(worldName).isPresent(); + } + + /** Gives the world back to its pack. Does nothing for a world nobody painted. */ + public static void remove(String worldName) { + if (worldName != null) { + SLOTS.remove(worldName); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/runtime/StudioSlotOccupant.java b/core/src/main/java/art/arcane/iris/core/runtime/StudioSlotOccupant.java new file mode 100644 index 000000000..fa2f4481f --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/runtime/StudioSlotOccupant.java @@ -0,0 +1,52 @@ +/* + * 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.runtime; + +import art.arcane.iris.core.project.IrisProject; + +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +/** + * A tool world that holds the studio slot, the way an open studio project does: opening another studio, the studio + * close command and a server stop go through it. The studio service asks it, and the platform's tool world answers for + * the tool that owns the world. + */ +public interface StudioSlotOccupant { + /** + * The studio project the world is, which the studio service shows to every command that asks for the open studio: it + * is open while the world is and carries the world's generator, as the project of any other studio does. + */ + IrisProject project(); + + /** A message that vetoes closing the world now; empty lets it close. */ + Optional closeRefusal(); + + /** + * Gets the world ready to be replaced by another studio, such as finishing a save. Completes when the world may be + * closed, or fails with the message to show the user. + * + * @param requestedBy the player who asked for the replacement; empty when the console did + */ + CompletableFuture prepareReplacement(Optional requestedBy); + + /** Closes the world and sends its players back; completes when it is unloaded and deleted. */ + CompletableFuture close(); +} diff --git a/core/src/main/java/art/arcane/iris/core/service/BoardSVC.java b/core/src/main/java/art/arcane/iris/core/service/BoardSVC.java index fe177d1aa..88247c8a0 100644 --- a/core/src/main/java/art/arcane/iris/core/service/BoardSVC.java +++ b/core/src/main/java/art/arcane/iris/core/service/BoardSVC.java @@ -31,6 +31,7 @@ import art.arcane.volmlib.util.board.Board; import art.arcane.volmlib.util.board.BoardProvider; import art.arcane.volmlib.util.board.BoardSettings; import art.arcane.volmlib.util.board.ScoreDirection; +import com.volmit.tooling.world.ToolText; import art.arcane.volmlib.util.format.Form; import art.arcane.iris.util.common.plugin.IrisService; import art.arcane.iris.util.common.scheduling.J; @@ -60,11 +61,10 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Pattern; public class BoardSVC implements IrisService, BoardProvider { - private static final String SEPARATOR = "&7&m-------------------"; private static final Pattern LEGACY_COLOR = Pattern.compile("(?i)\\u00a7[0-9A-FK-ORX]"); private final Map boards = new ConcurrentHashMap<>(); - private final Map jigsawContexts = new ConcurrentHashMap<>(); + private final Map toolSidebars = new ConcurrentHashMap<>(); private final Map yieldedWorlds = new ConcurrentHashMap<>(); private final Set hiddenPlayers = ConcurrentHashMap.newKeySet(); private volatile BoardSettings settings; @@ -117,7 +117,7 @@ public class BoardSVC implements IrisService, BoardProvider { board.cancel(); } boards.clear(); - jigsawContexts.clear(); + toolSidebars.clear(); yieldedWorlds.clear(); hiddenPlayers.clear(); settings = null; @@ -136,7 +136,7 @@ public class BoardSVC implements IrisService, BoardProvider { @EventHandler(priority = EventPriority.HIGHEST) public void on(PlayerQuitEvent e) { remove(e.getPlayer()); - jigsawContexts.remove(e.getPlayer().getUniqueId()); + toolSidebars.remove(e.getPlayer().getUniqueId()); yieldedWorlds.remove(e.getPlayer().getUniqueId()); clearPlayerPreference(e.getPlayer().getUniqueId()); } @@ -163,43 +163,55 @@ public class BoardSVC implements IrisService, BoardProvider { } if (!isEligibleWorld(p)) { - jigsawContexts.remove(playerId); + toolSidebars.remove(playerId); remove(p); return; } PlayerBoard playerBoard = boards.computeIfAbsent(p, PlayerBoard::new); - JigsawStudioBoardContext jigsawContext = currentJigsawContext(p); - if (jigsawContext != null) { - playerBoard.showJigsaw(jigsawContext); + ToolSidebar toolSidebar = currentToolSidebar(p); + if (toolSidebar != null) { + playerBoard.showTool(toolSidebar); } else { playerBoard.showOrdinary(); } } - public void applyJigsawContext(Player player, JigsawStudioBoardContext context) { - Objects.requireNonNull(player, "Jigsaw Studio board player"); - Objects.requireNonNull(context, "Jigsaw Studio board context"); + /** + * What a tool shows a player in a tool world: a title and styled lines, top to bottom, for as long as the player + * stays in {@code worldId}. An empty title keeps the Iris board title. + */ + public record ToolSidebar(UUID worldId, ToolText title, List lines) { + public ToolSidebar { + Objects.requireNonNull(worldId, "worldId"); + Objects.requireNonNull(title, "title"); + lines = List.copyOf(lines); + } + } + + public void applyToolSidebar(Player player, ToolSidebar sidebar) { + Objects.requireNonNull(player, "Tool sidebar player"); + Objects.requireNonNull(sidebar, "Tool sidebar"); if (!J.isOwnedByCurrentRegion(player)) { - J.runEntity(player, () -> applyJigsawContext(player, context)); + J.runEntity(player, () -> applyToolSidebar(player, sidebar)); return; } if (!player.isOnline()) { return; } - jigsawContexts.put(player.getUniqueId(), context); - if (context.worldId().equals(player.getWorld().getUID())) { + toolSidebars.put(player.getUniqueId(), sidebar); + if (sidebar.worldId().equals(player.getWorld().getUID())) { updatePlayer(player); } } - public void clearJigsawContext(Player player) { - Objects.requireNonNull(player, "Jigsaw Studio board player"); + public void clearToolSidebar(Player player) { + Objects.requireNonNull(player, "Tool sidebar player"); if (!J.isOwnedByCurrentRegion(player)) { - J.runEntity(player, () -> clearJigsawContext(player)); + J.runEntity(player, () -> clearToolSidebar(player)); return; } - jigsawContexts.remove(player.getUniqueId()); + toolSidebars.remove(player.getUniqueId()); updatePlayer(player); } @@ -211,7 +223,7 @@ public class BoardSVC implements IrisService, BoardProvider { } PlayerBoard previousBoard = boards.get(player); boolean alreadyOrdinary = previousBoard != null && previousBoard.isOrdinary(); - jigsawContexts.remove(player.getUniqueId()); + toolSidebars.remove(player.getUniqueId()); updatePlayer(player); PlayerBoard playerBoard = boards.get(player); if (alreadyOrdinary && playerBoard == previousBoard) { @@ -247,6 +259,10 @@ public class BoardSVC implements IrisService, BoardProvider { @Override public String getTitle(Player player) { + PlayerBoard board = boards.get(player); + if (board != null && board.view == BoardView.TOOL && !board.title.isEmpty()) { + return board.title; + } return IrisLanguage.text(BukkitUiMessages.SCOREBOARD_TITLE); } @@ -275,45 +291,6 @@ public class BoardSVC implements IrisService, BoardProvider { && generator.getEngine() != null; } - static List jigsawLines(JigsawStudioBoardContext context) { - Objects.requireNonNull(context, "Jigsaw Studio board context"); - List lines = new ArrayList<>(11); - lines.add(SEPARATOR); - lines.add("&dJigsaw Studio"); - lines.add("&bStructure&7: " + untrustedBoardValue(context.structureKey())); - if (!context.insideWorkcell()) { - lines.add("&bMode&7: " + context.modeDisplayName()); - lines.add(SEPARATOR); - lines.add("&eWalk into a workcell"); - if (!context.controlHint().isEmpty()) { - lines.add("&7" + untrustedBoardValue(context.controlHint())); - } - lines.add(SEPARATOR); - return List.copyOf(lines); - } - - lines.add("&bWorkcell&7: " + untrustedBoardValue(context.workcellName())); - if (!context.workcellRole().isEmpty() && !context.workcellRole().equals(context.workcellName())) { - lines.add("&bRole&7: " + untrustedBoardValue(context.workcellRole())); - } - lines.add("&bVariant&7: " + untrustedBoardValue( - context.variantName().isEmpty() ? "None" : context.variantName())); - lines.add("&bState&7: " + context.state().displayName()); - lines.add(SEPARATOR); - if (!context.controlHint().isEmpty()) { - lines.add("&e" + untrustedBoardValue(context.controlHint())); - } - lines.add(SEPARATOR); - return List.copyOf(lines); - } - - static boolean shouldRenderJigsaw( - JigsawStudioBoardContext previous, - JigsawStudioBoardContext next - ) { - return !Objects.equals(previous, next); - } - static String untrustedBoardValue(String value) { String normalized = value == null ? "" : value.replace('\n', ' ').replace('\r', ' '); return LEGACY_COLOR.matcher(normalized).replaceAll("") @@ -342,19 +319,50 @@ public class BoardSVC implements IrisService, BoardProvider { } } - private JigsawStudioBoardContext currentJigsawContext(Player player) { - JigsawStudioBoardContext context = jigsawContexts.get(player.getUniqueId()); - if (context == null || !context.worldId().equals(player.getWorld().getUID())) { + private ToolSidebar currentToolSidebar(Player player) { + ToolSidebar sidebar = toolSidebars.get(player.getUniqueId()); + if (sidebar == null || !sidebar.worldId().equals(player.getWorld().getUID())) { return null; } - return context; + return sidebar; + } + + static List toolLines(ToolSidebar sidebar) { + return sidebar.lines().stream().map(BoardSVC::boardLine).toList(); + } + + /** + * {@code text} in the board's {@code &} codes: each span starts with its colour and styles, a span without a colour + * resets after another, and the text of a span cannot carry codes of its own. + */ + static String boardLine(ToolText text) { + StringBuilder line = new StringBuilder(); + for (ToolText.Span span : text.spans()) { + if (span.color() != null) { + line.append('&').append(span.color().code()); + } else if (!line.isEmpty()) { + line.append("&r"); + } + if (span.bold()) { + line.append("&l"); + } + if (span.italic()) { + line.append("&o"); + } + if (span.strikethrough()) { + line.append("&m"); + } + line.append(untrustedBoardValue(span.text())); + } + return line.toString(); } public class PlayerBoard { private final Player player; private final Board board; private volatile List lines; - private volatile JigsawStudioBoardContext jigsawContext; + private volatile ToolSidebar toolSidebar; + private volatile String title; private volatile BoardView view; private volatile boolean cancelled; private volatile boolean ordinaryTickScheduled; @@ -363,7 +371,8 @@ public class BoardSVC implements IrisService, BoardProvider { this.player = player; this.board = new Board(player, settings); this.lines = List.of(); - this.jigsawContext = null; + this.toolSidebar = null; + this.title = ""; this.view = BoardView.NONE; this.cancelled = false; this.ordinaryTickScheduled = false; @@ -379,7 +388,7 @@ public class BoardSVC implements IrisService, BoardProvider { } boolean switched = view != BoardView.ORDINARY; view = BoardView.ORDINARY; - jigsawContext = null; + toolSidebar = null; if (switched) { updateOrdinary(); board.update(); @@ -399,7 +408,7 @@ public class BoardSVC implements IrisService, BoardProvider { return !cancelled && view == BoardView.ORDINARY; } - private void showJigsaw(JigsawStudioBoardContext context) { + private void showTool(ToolSidebar sidebar) { if (cancelled) { return; } @@ -407,12 +416,13 @@ public class BoardSVC implements IrisService, BoardProvider { yieldBoard(player, this); return; } - if (view == BoardView.JIGSAW && !shouldRenderJigsaw(jigsawContext, context)) { + if (view == BoardView.TOOL && sidebar.equals(toolSidebar)) { return; } - view = BoardView.JIGSAW; - jigsawContext = context; - lines = jigsawLines(context); + view = BoardView.TOOL; + toolSidebar = sidebar; + title = boardLine(sidebar.title()); + lines = toolLines(sidebar); board.update(); } @@ -444,9 +454,9 @@ public class BoardSVC implements IrisService, BoardProvider { cancel(); return; } - JigsawStudioBoardContext context = currentJigsawContext(player); - if (context != null) { - showJigsaw(context); + ToolSidebar sidebar = currentToolSidebar(player); + if (sidebar != null) { + showTool(sidebar); return; } if (!board.ownsScoreboardAssignment()) { @@ -534,6 +544,6 @@ public class BoardSVC implements IrisService, BoardProvider { private enum BoardView { NONE, ORDINARY, - JIGSAW + TOOL } } diff --git a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioBoardContext.java b/core/src/main/java/art/arcane/iris/core/service/JigsawStudioBoardContext.java deleted file mode 100644 index 4e04ceb5f..000000000 --- a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioBoardContext.java +++ /dev/null @@ -1,56 +0,0 @@ -package art.arcane.iris.core.service; - -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; - -import java.util.Objects; -import java.util.UUID; - -public record JigsawStudioBoardContext( - UUID worldId, - UUID requestId, - String structureKey, - JigsawStudioMode mode, - String workcellRole, - String workcellName, - String variantName, - JigsawStudioBoardState state, - String controlHint -) { - public JigsawStudioBoardContext { - worldId = Objects.requireNonNull(worldId, "Jigsaw Studio board world ID"); - requestId = Objects.requireNonNull(requestId, "Jigsaw Studio board request ID"); - structureKey = requireText(structureKey, "structure key"); - mode = Objects.requireNonNull(mode, "Jigsaw Studio board mode"); - workcellRole = optionalText(workcellRole); - workcellName = optionalText(workcellName); - variantName = optionalText(variantName); - state = Objects.requireNonNull(state, "Jigsaw Studio board state"); - controlHint = optionalText(controlHint); - if (workcellName.isEmpty() && (!workcellRole.isEmpty() || !variantName.isEmpty())) { - throw new IllegalArgumentException("Jigsaw Studio board variants require a workcell"); - } - } - - public boolean insideWorkcell() { - return !workcellName.isEmpty(); - } - - public String modeDisplayName() { - return switch (mode) { - case PLANAR_JIGSAW -> "Planar"; - case SPATIAL_JIGSAW -> "Spatial"; - }; - } - - private static String requireText(String value, String name) { - String normalized = optionalText(value); - if (normalized.isEmpty()) { - throw new IllegalArgumentException("Jigsaw Studio board " + name + " cannot be blank"); - } - return normalized; - } - - private static String optionalText(String value) { - return value == null ? "" : value.trim(); - } -} diff --git a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioToolCodec.java b/core/src/main/java/art/arcane/iris/core/service/JigsawStudioToolCodec.java deleted file mode 100644 index 48a208d84..000000000 --- a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioToolCodec.java +++ /dev/null @@ -1,150 +0,0 @@ -package art.arcane.iris.core.service; - -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolAction; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolPayload; - -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.persistence.PersistentDataContainer; -import org.bukkit.persistence.PersistentDataType; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.UUID; - -public final class JigsawStudioToolCodec { - static final NamespacedKey SCHEMA_KEY = new NamespacedKey("iris", "jigsaw_tool_schema"); - static final NamespacedKey ACTION_KEY = new NamespacedKey("iris", "jigsaw_tool_action"); - static final NamespacedKey REQUEST_KEY = new NamespacedKey("iris", "jigsaw_tool_request"); - static final NamespacedKey WORKCELL_KEY = new NamespacedKey("iris", "jigsaw_tool_workcell"); - static final NamespacedKey PIECE_KEY = new NamespacedKey("iris", "jigsaw_tool_piece"); - static final NamespacedKey POOL_KEY = new NamespacedKey("iris", "jigsaw_tool_pool"); - static final NamespacedKey ENTRY_INDEX_KEY = new NamespacedKey("iris", "jigsaw_tool_entry_index"); - static final NamespacedKey AMOUNT_KEY = new NamespacedKey("iris", "jigsaw_tool_amount"); - - public ItemStack create(JigsawStudioToolPayload payload) { - ItemStack tool = new ItemStack(Material.STICK); - bind(tool, payload); - return tool; - } - - public void bind(ItemStack tool, JigsawStudioToolPayload payload) { - ItemStack item = Objects.requireNonNull(tool, "Jigsaw Studio tool item"); - JigsawStudioToolPayload binding = requireCurrentSchema(payload); - if (item.getType() != Material.STICK) { - throw new IllegalArgumentException("Jigsaw Studio tools must use a stick"); - } - ItemMeta meta = item.getItemMeta(); - if (meta == null) { - throw new IllegalStateException("Jigsaw Studio tool stick has no item metadata"); - } - write(meta.getPersistentDataContainer(), binding); - meta.setDisplayName(ChatColor.AQUA + "Jigsaw Studio: " + binding.action().displayName()); - meta.setLore(lore(binding)); - if (!item.setItemMeta(meta)) { - throw new IllegalStateException("Jigsaw Studio tool metadata was rejected"); - } - } - - public Optional decode(ItemStack tool) { - if (tool == null || tool.getType() != Material.STICK || !tool.hasItemMeta()) { - return Optional.empty(); - } - ItemMeta meta = tool.getItemMeta(); - return meta == null ? Optional.empty() : decode(meta.getPersistentDataContainer()); - } - - public boolean isTool(ItemStack tool) { - return decode(tool).isPresent(); - } - - void write(PersistentDataContainer container, JigsawStudioToolPayload payload) { - PersistentDataContainer data = Objects.requireNonNull( - container, - "Jigsaw Studio tool persistent data"); - JigsawStudioToolPayload binding = requireCurrentSchema(payload); - data.set(SCHEMA_KEY, PersistentDataType.INTEGER, binding.schemaVersion()); - data.set(ACTION_KEY, PersistentDataType.STRING, binding.action().name()); - data.set(REQUEST_KEY, PersistentDataType.STRING, binding.requestId().toString()); - data.set(WORKCELL_KEY, PersistentDataType.STRING, binding.workcellId()); - data.set(PIECE_KEY, PersistentDataType.STRING, binding.pieceKey()); - data.set(POOL_KEY, PersistentDataType.STRING, binding.poolKey()); - data.set(ENTRY_INDEX_KEY, PersistentDataType.INTEGER, binding.entryIndex()); - data.set(AMOUNT_KEY, PersistentDataType.INTEGER, binding.amount()); - } - - Optional decode(PersistentDataContainer container) { - if (container == null) { - return Optional.empty(); - } - Integer schemaVersion = container.get(SCHEMA_KEY, PersistentDataType.INTEGER); - String actionName = container.get(ACTION_KEY, PersistentDataType.STRING); - String requestValue = container.get(REQUEST_KEY, PersistentDataType.STRING); - if (schemaVersion == null - || schemaVersion != JigsawStudioToolPayload.CURRENT_SCHEMA_VERSION - || actionName == null - || requestValue == null) { - return Optional.empty(); - } - try { - JigsawStudioToolAction action = JigsawStudioToolAction.valueOf(actionName); - UUID requestId = UUID.fromString(requestValue); - String workcellId = optionalString(container, WORKCELL_KEY); - String pieceKey = optionalString(container, PIECE_KEY); - String poolKey = optionalString(container, POOL_KEY); - Integer entryIndex = container.get(ENTRY_INDEX_KEY, PersistentDataType.INTEGER); - Integer amount = container.get(AMOUNT_KEY, PersistentDataType.INTEGER); - return Optional.of(new JigsawStudioToolPayload( - schemaVersion, - action, - requestId, - workcellId, - pieceKey, - poolKey, - entryIndex == null ? JigsawStudioToolPayload.NO_ENTRY_INDEX : entryIndex, - amount == null ? 0 : amount)); - } catch (IllegalArgumentException exception) { - return Optional.empty(); - } - } - - private static JigsawStudioToolPayload requireCurrentSchema(JigsawStudioToolPayload payload) { - JigsawStudioToolPayload binding = Objects.requireNonNull(payload, "Jigsaw Studio tool payload"); - if (binding.schemaVersion() != JigsawStudioToolPayload.CURRENT_SCHEMA_VERSION) { - throw new IllegalArgumentException("Unsupported Jigsaw Studio tool schema " - + binding.schemaVersion()); - } - return binding; - } - - private static String optionalString(PersistentDataContainer container, NamespacedKey key) { - String value = container.get(key, PersistentDataType.STRING); - return value == null ? "" : value; - } - - private static List lore(JigsawStudioToolPayload payload) { - List lore = new ArrayList<>(); - if (!payload.workcellId().isEmpty()) { - lore.add(ChatColor.GRAY + "Workcell: " + payload.workcellId()); - } - if (!payload.pieceKey().isEmpty()) { - lore.add(ChatColor.GRAY + "Variant: " + payload.pieceKey()); - } - if (!payload.poolKey().isEmpty()) { - lore.add(ChatColor.GRAY + "Pool: " + payload.poolKey() - + (payload.entryIndex() < 0 ? "" : " [" + payload.entryIndex() + "]")); - } - if (payload.amount() != 0) { - lore.add(ChatColor.GRAY + "Amount: " + payload.amount()); - } - lore.add(payload.action().destructive() - ? ChatColor.RED + "Right-click twice to confirm" - : ChatColor.YELLOW + "Right-click to use"); - return List.copyOf(lore); - } -} diff --git a/core/src/main/java/art/arcane/iris/core/service/StudioSVC.java b/core/src/main/java/art/arcane/iris/core/service/StudioSVC.java index a34d916e6..86e03102e 100644 --- a/core/src/main/java/art/arcane/iris/core/service/StudioSVC.java +++ b/core/src/main/java/art/arcane/iris/core/service/StudioSVC.java @@ -42,9 +42,9 @@ import art.arcane.iris.core.project.IrisPackageCompiler; import art.arcane.iris.core.project.IrisCodeWorkspace; import art.arcane.iris.core.project.IrisProjectCopier; import art.arcane.iris.core.runtime.StudioOpenCoordinator; +import art.arcane.iris.core.runtime.StudioSlotOccupant; import art.arcane.iris.core.runtime.TransientWorldCleanupSupport; import art.arcane.iris.core.runtime.WorldDeletionQueue; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioActivation; import art.arcane.iris.core.tools.IrisToolbelt; import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.iris.engine.object.world.dimension.IrisDimension; @@ -100,6 +100,7 @@ public class StudioSVC implements IrisService { private final StudioTransitionQueue studioTransitions = new StudioTransitionQueue(); private final Object downloadAdmissionMonitor = new Object(); private volatile IrisProject activeProject; + private volatile StudioSlotOccupant activeToolWorld; private volatile CompletableFuture activeOpen; private PackDownloadExecution activeDownload; private boolean downloadAdmissionOpen; @@ -125,8 +126,9 @@ public class StudioSVC implements IrisService { boolean stopping = IrisToolbelt.isServerStopping(); LinkedHashSet worldNamesToDelete = new LinkedHashSet<>(TransientWorldCleanupSupport.collectTransientStudioWorldNames(IrisWorldStorage.levelRoot())); - if (activeProject != null) { - PlatformChunkGenerator activeProvider = activeProject.getActiveProvider(); + IrisProject openProject = currentProject(); + if (openProject != null) { + PlatformChunkGenerator activeProvider = openProject.getActiveProvider(); if (activeProvider != null) { String activeWorldName = IrisWorldStorage.logicalName( WorldIdentity.parse(activeProvider.getTarget().getWorld().identity())); @@ -475,13 +477,20 @@ public class StudioSVC implements IrisService { } public boolean isProjectOpen() { - return activeProject != null && activeProject.isOpen(); + IrisProject project = currentProject(); + return project != null && project.isOpen(); + } + + /** The studio project in the slot: the project of the open tool world, or the one opened as a project. */ + private IrisProject currentProject() { + StudioSlotOccupant toolWorld = activeToolWorld; + return toolWorld == null ? activeProject : toolWorld.project(); } public CompletableFuture teleportToActiveProject(Player player) { Player target = Objects.requireNonNull(player, "Studio teleport player"); return studioTransitions.submit(() -> { - IrisProject project = activeProject; + IrisProject project = currentProject(); if (project == null || !project.isOpen()) { return CompletableFuture.failedFuture(new IllegalStateException( "No active Studio project is available for teleport.")); @@ -511,11 +520,28 @@ public class StudioSVC implements IrisService { } } - private static BrokenPackException reportPackAdmissionFailure( + public static BrokenPackException reportPackAdmissionFailure( VolmitSender sender, String dimm, StudioOpenCoordinator.StudioOpenKind openKind ) { + PackAdmission admission = admitPack(dimm, openKind); + admission.messages().forEach(sender::sendMessage); + return admission.failure(); + } + + /** Why a studio of the pack {@code dimm} may not open, as the lines {@link #reportPackAdmissionFailure} would send; empty when it may. */ + public static Optional packAdmissionDenial(String dimm, StudioOpenCoordinator.StudioOpenKind openKind) { + PackAdmission admission = admitPack(dimm, openKind); + return admission.failure() == null ? Optional.empty() : Optional.of(String.join("\n", admission.messages())); + } + + /** Whether the pack may open a studio, and the messages that tell its sender so; {@code failure} is null when it may. */ + private record PackAdmission(BrokenPackException failure, List messages) { + } + + private static PackAdmission admitPack(String dimm, StudioOpenCoordinator.StudioOpenKind openKind) { + List messages = new ArrayList<>(); boolean force = openKind == StudioOpenCoordinator.StudioOpenKind.FORCED_STANDARD; Optional unforcedStartupDenial = ServerConfigurator.worldCreationDenialReason(false); Optional startupDenial = ServerConfigurator.worldCreationDenialReason(force); @@ -528,20 +554,20 @@ public class StudioSVC implements IrisService { packName, startupDenial, validation); if (failure == null) { if (force && unforcedStartupDenial.isPresent()) { - sender.sendMessage("Force-opening Studio with the currently loaded registry state. The open may fail; restart remains required."); + messages.add("Force-opening Studio with the currently loaded registry state. The open may fail; restart remains required."); } - return null; + return new PackAdmission(null, messages); } if (startupDenial.isPresent()) { - sender.sendMessage(startupDenial.get()); - return failure; + messages.add(startupDenial.get()); + return new PackAdmission(failure, messages); } - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STUDIO_S_V_C_CANNOT_OPEN_STUDIO_PACK_HAS_BLOCKING_ERRORS, MessageArgument.untrusted("dimm", String.valueOf(dimm)))); + messages.add(IrisLanguage.text(BukkitRuntimeMessages.STUDIO_S_V_C_CANNOT_OPEN_STUDIO_PACK_HAS_BLOCKING_ERRORS, MessageArgument.untrusted("dimm", String.valueOf(dimm)))); for (String reason : failure.getReasons()) { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STUDIO_S_V_C_MESSAGE, MessageArgument.untrusted("reason", String.valueOf(reason)))); + messages.add(IrisLanguage.text(BukkitRuntimeMessages.STUDIO_S_V_C_MESSAGE, MessageArgument.untrusted("reason", String.valueOf(reason)))); } - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STUDIO_S_V_C_FIX_PACK_RUN_IRIS_PACK_VALIDATE_REVALIDATE, MessageArgument.untrusted("dimm", String.valueOf(packName)))); - return failure; + messages.add(IrisLanguage.text(BukkitRuntimeMessages.STUDIO_S_V_C_FIX_PACK_RUN_IRIS_PACK_VALIDATE_REVALIDATE, MessageArgument.untrusted("dimm", String.valueOf(packName)))); + return new PackAdmission(failure, messages); } static void retainPackRestartRequirement(PackDownloader.PackInstallResult result) { @@ -603,91 +629,6 @@ public class StudioSVC implements IrisService { }); } - public CompletableFuture openTracked( - VolmitSender sender, - long seed, - String dimension, - StudioOpenCoordinator.StudioOpenKind openKind, - Runnable beforeOpen, - Consumer onDone - ) { - long requestedAtNanos = System.nanoTime(); - BrokenPackException failure = reportPackAdmissionFailure(sender, dimension, openKind); - if (failure != null) { - return CompletableFuture.failedFuture(failure); - } - return studioTransitions.submit(() -> replaceActiveProjectTracked( - sender, - seed, - dimension, - Objects.requireNonNull(openKind, "Studio open kind"), - Objects.requireNonNull(beforeOpen, "Studio before-open callback"), - Objects.requireNonNull(onDone, "Studio open completion callback"), - requestedAtNanos)); - } - - private CompletableFuture replaceActiveProjectTracked( - VolmitSender sender, - long seed, - String dimension, - StudioOpenCoordinator.StudioOpenKind openKind, - Runnable beforeOpen, - Consumer onDone, - long requestedAtNanos - ) { - return closeActiveProject().thenCompose(closeResult -> { - if (closeResult == null) { - return CompletableFuture.failedFuture( - new IllegalStateException("Studio close completed without a result.")); - } - if (closeResult.failureCause() != null) { - return CompletableFuture.failedFuture(closeResult.failureCause()); - } - beforeOpen.run(); - return beginStudioOpenTracked( - sender, - seed, - dimension, - openKind, - onDone, - requestedAtNanos); - }); - } - - private CompletableFuture beginStudioOpenTracked( - VolmitSender sender, - long seed, - String dimension, - StudioOpenCoordinator.StudioOpenKind openKind, - Consumer onDone, - long requestedAtNanos - ) { - IrisProject project = new IrisProject(new File(getWorkspaceFolder(), dimension)); - activeProject = project; - CompletableFuture opening; - try { - opening = project.open(sender, seed, openKind, onDone, requestedAtNanos); - } catch (IrisException exception) { - if (activeProject == project) { - activeProject = null; - } - return CompletableFuture.failedFuture(exception); - } - - activeOpen = opening; - return opening.thenApply(result -> Objects.requireNonNull( - result, - "Studio open completed without a result.")) - .whenComplete((result, throwable) -> { - if (activeOpen == opening) { - activeOpen = null; - } - if (throwable != null && activeProject == project && !project.isOpen()) { - activeProject = null; - } - }); - } - private CompletableFuture replaceActiveProject( VolmitSender sender, long seed, @@ -791,19 +732,13 @@ public class StudioSVC implements IrisService { CompletableFuture closeActiveProjectForReplacement( VolmitSender sender ) { - IrisProject project = activeProject; - if (project == null) { + StudioSlotOccupant toolWorld = activeToolWorld; + if (toolWorld == null || !sender.isPlayer()) { return closeActiveProject(); } - JigsawStudioActivation.Request request = JigsawStudioActivation.getRequest(project.getName()); - if (request == null || !sender.isPlayer()) { - return closeActiveProject(); - } - UUID ownerId = sender.player().getUniqueId(); - return JigsawStudioService.get() - .awaitCloseForReplacement(request.requestId(), ownerId) + return toolWorld.prepareReplacement(Optional.of(sender.player().getUniqueId())) .thenCompose(ignored -> { - if (activeProject != project) { + if (activeToolWorld != toolWorld) { return CompletableFuture.failedFuture(new IllegalStateException( "The active Studio project changed while replacement was waiting to close.")); } @@ -811,7 +746,62 @@ public class StudioSVC implements IrisService { }); } + /** + * Gives the studio slot to a tool world: closes what holds the slot now, then runs {@code opening}, which creates the + * world. The slot is free again when the opening fails, or when the world is {@link #releaseStudioSlot gone}. + */ + public CompletableFuture occupyStudioSlot( + StudioSlotOccupant occupant, + Supplier> opening + ) { + Objects.requireNonNull(occupant, "Studio slot occupant"); + Objects.requireNonNull(opening, "Studio slot opening"); + return studioTransitions.submit(() -> closeActiveProject().thenCompose(closeResult -> { + if (closeResult == null) { + return CompletableFuture.failedFuture( + new IllegalStateException("Studio close completed without a result.")); + } + if (closeResult.failureCause() != null) { + return CompletableFuture.failedFuture(closeResult.failureCause()); + } + activeToolWorld = occupant; + return opening.get().handle((opened, failure) -> { + if (failure == null) { + return null; + } + releaseStudioSlot(occupant); + throw failure instanceof java.util.concurrent.CompletionException completion + ? completion + : new java.util.concurrent.CompletionException(failure); + }); + })); + } + + /** Frees the studio slot when {@code occupant} still holds it. */ + public void releaseStudioSlot(StudioSlotOccupant occupant) { + if (activeToolWorld == occupant) { + activeToolWorld = null; + } + } + + private CompletableFuture closeToolWorld(StudioSlotOccupant toolWorld) { + Optional refusal = toolWorld.closeRefusal(); + if (refusal.isPresent()) { + return CompletableFuture.failedFuture(new IllegalStateException(refusal.get())); + } + return toolWorld.close().handle((ignored, failure) -> { + if (failure == null) { + releaseStudioSlot(toolWorld); + } + return new StudioOpenCoordinator.StudioCloseResult(null, failure == null, failure == null, false, failure); + }); + } + private CompletableFuture closeActiveProject() { + StudioSlotOccupant toolWorld = activeToolWorld; + if (toolWorld != null) { + return closeToolWorld(toolWorld); + } IrisProject project = activeProject; if (project == null) { return CompletableFuture.completedFuture(new StudioOpenCoordinator.StudioCloseResult( @@ -823,15 +813,6 @@ public class StudioSVC implements IrisService { )); } - JigsawStudioActivation.Request jigsawRequest = JigsawStudioActivation.getRequest(project.getName()); - if (jigsawRequest != null) { - String protectionFailure = JigsawStudioService.get() - .closeProtectionFailure(jigsawRequest.requestId()); - if (protectionFailure != null) { - return CompletableFuture.failedFuture(new IllegalStateException(protectionFailure)); - } - } - IrisLogging.debug("Closing Active Project"); CompletableFuture closing = project.close(); return closing.whenComplete((result, throwable) -> { @@ -1537,12 +1518,12 @@ public class StudioSVC implements IrisService { } public IrisProject getActiveProject() { - return activeProject; + return currentProject(); } public void updateWorkspace() { if (isProjectOpen()) { - new IrisCodeWorkspace(activeProject).updateWorkspace(); + new IrisCodeWorkspace(currentProject()).updateWorkspace(); } } } diff --git a/core/src/main/java/art/arcane/iris/core/structure/BulkStructureImporter.java b/core/src/main/java/art/arcane/iris/core/structure/BulkStructureImporter.java deleted file mode 100644 index 53a1854d2..000000000 --- a/core/src/main/java/art/arcane/iris/core/structure/BulkStructureImporter.java +++ /dev/null @@ -1,676 +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.structure; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.nms.INMS; -import art.arcane.iris.util.common.format.C; -import art.arcane.iris.util.common.plugin.VolmitSender; -import art.arcane.volmlib.util.collection.KList; -import org.bukkit.Bukkit; -import org.bukkit.NamespacedKey; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; -import java.util.TreeSet; -import java.util.function.Predicate; - -import art.arcane.iris.core.localization.BukkitRuntimeMessages; -import art.arcane.iris.core.localization.IrisLanguage; -import art.arcane.volmlib.util.localization.MessageArgument; -public final class BulkStructureImporter { - public record Report( - int total, - int imported, - int skipped, - int failed, - Map successfulBundles, - boolean retryRequired, - Set captureCandidates - ) { - public Report(int total, int imported, int skipped, int failed) { - this(total, imported, skipped, failed, Map.of(), false, Set.of()); - } - - public Report(int total, int imported, int skipped, int failed, Map successfulBundles) { - this(total, imported, skipped, failed, successfulBundles, false, Set.of()); - } - - public Report(int total, int imported, int skipped, int failed, - Map successfulBundles, boolean retryRequired) { - this(total, imported, skipped, failed, successfulBundles, retryRequired, Set.of()); - } - - public Report { - successfulBundles = Collections.unmodifiableMap(new TreeMap<>(successfulBundles)); - captureCandidates = Collections.unmodifiableSet(new TreeSet<>(captureCandidates)); - } - } - - private BulkStructureImporter() { - } - - public static Report importAllVanilla(IrisData data, StructureImporter.Mode mode, boolean includeNonJigsaw, VolmitSender sender) { - KList keys = INMS.get().getStructureKeys(); - List vanilla = new ArrayList<>(); - for (String k : keys) { - if (k != null && !k.isBlank()) { - vanilla.add(k); - } - } - Collections.sort(vanilla); - - int total = vanilla.size(); - int imported = 0; - int skipped = 0; - int failed = 0; - TreeSet captureCandidates = new TreeSet<>(); - - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_IMPORTING_VANILLA_DATAPACK_STRUCTURES_MODE_INCLUDENONJIGSAW, MessageArgument.untrusted("total", String.valueOf(total)), MessageArgument.untrusted("mode", String.valueOf(mode)), MessageArgument.untrusted("includeNonJigsaw", String.valueOf(includeNonJigsaw)))); - - for (String keyString : vanilla) { - NamespacedKey nk = NamespacedKey.fromString(keyString.toLowerCase()); - if (nk == null) { - failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_INVALID_KEY, MessageArgument.untrusted("keyString", String.valueOf(keyString)))); - continue; - } - String name = StructureImporter.deriveName(nk); - - try { - VillageImporter.Result jigsaw = VillageImporter.importVillage(data, nk, name, mode); - if (jigsaw.success()) { - imported++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_JIGSAW, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("name", String.valueOf(name)))); - continue; - } - - String message = jigsaw.message() == null ? "" : jigsaw.message(); - if (message.contains("is not a jigsaw structure")) { - if (!includeNonJigsaw) { - skipped++; - continue; - } - StructureImporter.Result single = StructureImporter.importStructure(data, nk, name, mode); - if (single.success()) { - imported++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_SINGLE, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("name", String.valueOf(name)))); - } else if (single.message() != null && single.message().startsWith("Skipped")) { - skipped++; - } else if (isCaptureCandidate(message, single.message())) { - skipped++; - captureCandidates.add(nk.toString()); - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_SKIP_NO_SINGLE_TEMPLATE_NBT_VANILLA_BUILDS_THIS_CODE_FROM_SEPARATE_PIECE, MessageArgument.untrusted("keyString", String.valueOf(keyString)))); - } else { - failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("message", String.valueOf(single.message())))); - } - continue; - } - - if (message.startsWith("Skipped")) { - skipped++; - continue; - } - - failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_2, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("message", String.valueOf(message)))); - } catch (Throwable e) { - failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_3, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("error", String.valueOf(e.getMessage())))); - } - } - - StructureIndexService.write(data); - - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_BULK_IMPORT_COMPLETE_IMPORTED_SKIPPED_FAILED_TOTAL, MessageArgument.untrusted("imported", String.valueOf(imported)), MessageArgument.untrusted("skipped", String.valueOf(skipped)), MessageArgument.untrusted("failed", String.valueOf(failed)), MessageArgument.untrusted("total", String.valueOf(total)))); - return new Report(total, imported, skipped, failed, Map.of(), false, captureCandidates); - } - - public static Report importTemplateGroups(IrisData data, StructureImporter.Mode mode, VolmitSender sender) { - String[][] groups = { - {"shipwreck", "minecraft:shipwreck", "shipwreck"}, - {"ruined_portal", "minecraft:ruined_portal", "ruined_portal"}, - {"ocean_ruin", "minecraft:ocean_ruin_cold", "underwater_ruin"}, - {"nether_fossil", "minecraft:nether_fossil", "nether_fossils"}, - }; - - int imported = 0; - int skipped = 0; - int failed = 0; - - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_BUILDING_SINGLE_TEMPLATE_STRUCTURES_FROM_IMPORTED_PIECES_ONE_VARIANT_PLACED_PER_GENERATION)); - for (String[] g : groups) { - try { - StructureImporter.Result result = StructureImporter.importTemplateGroup(data, g[0], g[1], g[2], mode); - if (result.success()) { - imported++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_GROUP_VARIANTS, MessageArgument.untrusted("value", String.valueOf(g[1])), MessageArgument.untrusted("value2", String.valueOf(g[0])), MessageArgument.untrusted("blocks", String.valueOf(result.blocks())))); - } else if (result.message() != null && result.message().startsWith("Skipped")) { - skipped++; - } else { - skipped++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_SKIP, MessageArgument.untrusted("value", String.valueOf(g[0])), MessageArgument.untrusted("message", String.valueOf(result.message())))); - } - } catch (Throwable e) { - failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_4, MessageArgument.untrusted("value", String.valueOf(g[0])), MessageArgument.untrusted("error", String.valueOf(e.getMessage())))); - } - } - - StructureIndexService.write(data); - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_SINGLE_TEMPLATE_STRUCTURES_BUILT_SKIPPED_FAILED, MessageArgument.untrusted("imported", String.valueOf(imported)), MessageArgument.untrusted("skipped", String.valueOf(skipped)), MessageArgument.untrusted("failed", String.valueOf(failed)))); - return new Report(groups.length, imported, skipped, failed); - } - - public static Report importAllTemplates(IrisData data, StructureImporter.Mode mode, VolmitSender sender) { - List templateKeys; - try { - templateKeys = enumerateTemplateKeys(); - } catch (Throwable e) { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAILED_ENUMERATE_STRUCTURE_TEMPLATES_VIA_SERVER_RESOURCEMANAGER, MessageArgument.untrusted("e", String.valueOf(e)))); - return enumerationFailureReport(); - } - - List all = new ArrayList<>(); - for (String key : templateKeys) { - if (key != null && !key.isBlank()) { - all.add(key); - } - } - Collections.sort(all); - - int total = all.size(); - int imported = 0; - int skipped = 0; - int failed = 0; - - if (total == 0) { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_NO_STRUCTURE_TEMPLATES_WERE_FOUND_UNDER_STRUCTURE_RESOURCE_PATH)); - return new Report(0, 0, 0, 0); - } - - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_IMPORTING_STRUCTURE_TEMPLATES_MODE, MessageArgument.untrusted("total", String.valueOf(total)), MessageArgument.untrusted("mode", String.valueOf(mode)))); - - for (String keyString : all) { - NamespacedKey nk = NamespacedKey.fromString(keyString.toLowerCase()); - if (nk == null) { - failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_INVALID_KEY_2, MessageArgument.untrusted("keyString", String.valueOf(keyString)))); - continue; - } - String name = templateNameFor(keyString); - - try { - StructureImporter.Result result = StructureImporter.importStructure(data, nk, name, mode, true); - if (result.success()) { - imported++; - } else if (result.message() != null && result.message().startsWith("Skipped")) { - skipped++; - } else { - failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_5, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("message", String.valueOf(result.message())))); - } - } catch (Throwable e) { - failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_6, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("error", String.valueOf(e.getMessage())))); - } - - int processed = imported + skipped + failed; - if (processed % 50 == 0) { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_IMPORTED_SKIPPED_FAILED, MessageArgument.untrusted("processed", String.valueOf(processed)), MessageArgument.untrusted("total", String.valueOf(total)), MessageArgument.untrusted("imported", String.valueOf(imported)), MessageArgument.untrusted("skipped", String.valueOf(skipped)), MessageArgument.untrusted("failed", String.valueOf(failed)))); - } - } - - StructureIndexService.write(data); - - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_TEMPLATE_IMPORT_COMPLETE_IMPORTED_SKIPPED_FAILED_TOTAL, MessageArgument.untrusted("imported", String.valueOf(imported)), MessageArgument.untrusted("skipped", String.valueOf(skipped)), MessageArgument.untrusted("failed", String.valueOf(failed)), MessageArgument.untrusted("total", String.valueOf(total)))); - return new Report(total, imported, skipped, failed); - } - - public static Report importDatapackStructures(IrisData data, StructureImporter.Mode mode, VolmitSender sender) { - return importDatapackStructures( - data, - mode, - sender, - null, - null, - StructureImporter.Ownership.EDITABLE - ); - } - - public static Report importManagedDatapackStructures( - IrisData data, - StructureImporter.Mode mode, - VolmitSender sender, - Set allowedStructureKeys, - Set allowedTemplateKeys - ) { - return importDatapackStructures( - data, - mode, - sender, - allowedStructureKeys, - allowedTemplateKeys, - StructureImporter.Ownership.MANAGED_DATAPACK - ); - } - - private static Report importDatapackStructures( - IrisData data, - StructureImporter.Mode mode, - VolmitSender sender, - Set allowedStructureKeys, - Set allowedTemplateKeys, - StructureImporter.Ownership ownership - ) { - KList keys = INMS.get().getStructureKeys(); - KeySelection structureSelection = selectDatapackKeys(keys, allowedStructureKeys); - List datapack = structureSelection.present(); - - int structureAttempts = structureSelection.total(); - int templateAttempts = 0; - int imported = 0; - int skipped = 0; - int failed = structureSelection.missing().size(); - boolean retryRequired = false; - Map successfulBundles = new TreeMap<>(); - - if (structureAttempts == 0) { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_NO_DATAPACK_NON_MINECRAFT_STRUCTURES_ARE_REGISTERED_INGEST_DATAPACK_RESTART_FIRST_THEN)); - } else { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_IMPORTING_DATAPACK_STRUCTURES_MODE, MessageArgument.untrusted("total", String.valueOf(structureAttempts)), MessageArgument.untrusted("mode", String.valueOf(mode)))); - for (String missingKey : structureSelection.missing()) { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_8, MessageArgument.untrusted("keyString", missingKey), MessageArgument.untrusted("message", "allowed structure key is absent from the live registry"))); - } - for (String keyString : datapack) { - NamespacedKey nk = NamespacedKey.fromString(keyString.toLowerCase()); - if (nk == null) { - failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_INVALID_KEY_3, MessageArgument.untrusted("keyString", String.valueOf(keyString)))); - continue; - } - String name = StructureImporter.deriveName(nk); - - try { - VillageImporter.Result jigsaw = VillageImporter.importVillage( - data, - nk, - name, - mode, - ownership - ); - if (jigsaw.success()) { - imported++; - successfulBundles.put(bundleKey(name), keyString); - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_JIGSAW_2, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("name", String.valueOf(name)))); - continue; - } - retryRequired |= jigsaw.retryableFailure(); - - String message = jigsaw.message() == null ? "" : jigsaw.message(); - if (message.contains("is not a jigsaw structure")) { - StructureImporter.Result single = StructureImporter.importStructure( - data, - nk, - name, - mode, - false, - ownership - ); - if (single.success()) { - imported++; - successfulBundles.put(bundleKey(name), keyString); - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_SINGLE_2, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("name", String.valueOf(name)))); - } else if (single.message() != null && single.message().startsWith("Skipped")) { - skipped++; - } else if (single.message() != null && single.message().contains("No loadable structure NBT")) { - skipped++; - } else { - failed++; - retryRequired |= single.retryableFailure(); - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_7, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("message", String.valueOf(single.message())))); - } - continue; - } - - if (message.startsWith("Skipped")) { - skipped++; - continue; - } - - failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_8, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("message", String.valueOf(message)))); - } catch (Throwable e) { - failed++; - retryRequired = true; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_9, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("error", String.valueOf(e.getMessage())))); - } - } - } - - if (allowedTemplateKeys == null || !allowedTemplateKeys.isEmpty()) { - List templateKeys = List.of(); - boolean enumerationSucceeded = false; - try { - templateKeys = enumerateTemplateKeys(); - enumerationSucceeded = true; - } catch (Throwable e) { - templateAttempts++; - failed++; - retryRequired = true; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_COULD_NOT_ENUMERATE_DATAPACK_TEMPLATES_VIA_SERVER_RESOURCEMANAGER, MessageArgument.untrusted("error", String.valueOf(e.getMessage())))); - } - if (enumerationSucceeded) { - KeySelection templateSelection = selectDatapackKeys(templateKeys, allowedTemplateKeys); - List datapackTemplates = templateSelection.present(); - templateAttempts += templateSelection.total(); - failed += templateSelection.missing().size(); - for (String missingKey : templateSelection.missing()) { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_10, MessageArgument.untrusted("keyString", missingKey), MessageArgument.untrusted("message", "allowed template key is absent from the live server resources"))); - } - if (!datapackTemplates.isEmpty()) { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_IMPORTING_DATAPACK_STRUCTURE_TEMPLATES, MessageArgument.untrusted("size", String.valueOf(datapackTemplates.size())))); - for (String keyString : datapackTemplates) { - NamespacedKey nk = NamespacedKey.fromString(keyString.toLowerCase()); - if (nk == null) { - failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_INVALID_KEY_2, MessageArgument.untrusted("keyString", String.valueOf(keyString)))); - continue; - } - String name = templateNameFor(keyString); - try { - StructureImporter.Result result = StructureImporter.importStructure( - data, - nk, - name, - mode, - true, - ownership - ); - if (result.success()) { - imported++; - successfulBundles.put(bundleKey(name), keyString); - } else if (result.message() != null && result.message().startsWith("Skipped")) { - skipped++; - } else { - failed++; - retryRequired |= result.retryableFailure(); - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_10, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("message", String.valueOf(result.message())))); - } - } catch (Throwable e) { - failed++; - retryRequired = true; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_FAIL_11, MessageArgument.untrusted("keyString", String.valueOf(keyString)), MessageArgument.untrusted("error", String.valueOf(e.getMessage())))); - } - } - } - } - } - - StructureIndexService.write(data); - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.BULK_STRUCTURE_IMPORTER_DATAPACK_STRUCTURE_IMPORT_COMPLETE_IMPORTED_SKIPPED_FAILED, MessageArgument.untrusted("imported", String.valueOf(imported)), MessageArgument.untrusted("skipped", String.valueOf(skipped)), MessageArgument.untrusted("failed", String.valueOf(failed)))); - return datapackReport( - structureAttempts, - templateAttempts, - imported, - skipped, - failed, - successfulBundles, - retryRequired); - } - - static boolean isAllowedDatapackKey(String key, Set allowedKeys) { - return allowedKeys == null ? !key.startsWith("minecraft:") : allowedKeys.contains(key); - } - - static boolean isCaptureCandidate(String jigsawMessage, String singleMessage) { - return jigsawMessage != null - && jigsawMessage.contains("is not a jigsaw structure") - && singleMessage != null - && singleMessage.contains("No loadable structure NBT"); - } - - static KeySelection selectDatapackKeys(Iterable discoveredKeys, Set allowedKeys) { - TreeSet discovered = normalizeKeys(discoveredKeys); - TreeSet present = new TreeSet<>(); - TreeSet missing = new TreeSet<>(); - if (allowedKeys == null) { - for (String key : discovered) { - if (isAllowedDatapackKey(key, null)) { - present.add(key); - } - } - } else { - TreeSet allowed = normalizeKeys(allowedKeys); - for (String key : allowed) { - if (discovered.contains(key)) { - present.add(key); - } else { - missing.add(key); - } - } - } - return new KeySelection(new ArrayList<>(present), new ArrayList<>(missing)); - } - - static Report datapackReport( - int structureAttempts, - int templateAttempts, - int imported, - int skipped, - int failed, - Map successfulBundles - ) { - return new Report(structureAttempts + templateAttempts, imported, skipped, failed, successfulBundles); - } - - static Report datapackReport( - int structureAttempts, - int templateAttempts, - int imported, - int skipped, - int failed, - Map successfulBundles, - boolean retryRequired - ) { - return new Report( - structureAttempts + templateAttempts, - imported, - skipped, - failed, - successfulBundles, - retryRequired); - } - - static Report enumerationFailureReport() { - return new Report(1, 0, 0, 1, Map.of(), true); - } - - public static String templateNameFor(String key) { - int colon = key.indexOf(':'); - String namespace = colon >= 0 ? key.substring(0, colon) : "minecraft"; - String path = colon >= 0 ? key.substring(colon + 1) : key; - String safePath = path.toLowerCase().replaceAll("[^a-z0-9_/-]", "_"); - while (safePath.contains("//")) { - safePath = safePath.replace("//", "/"); - } - if (safePath.startsWith("/")) { - safePath = safePath.substring(1); - } - return "minecraft".equals(namespace) ? safePath : namespace + "/" + safePath; - } - - private static List enumerateTemplateKeys() throws Exception { - Object craftServer = Bukkit.getServer(); - Object dedicated = invoke(craftServer, "getHandle"); - Object server = invoke(dedicated, "getServer"); - Object resourceManager = resolveResourceManager(server); - if (resourceManager == null) { - throw new IllegalStateException("Could not resolve the server ResourceManager via reflection"); - } - - Method listResources = null; - for (Method m : resourceManager.getClass().getMethods()) { - if (m.getName().equals("listResources") && m.getParameterCount() == 2 - && m.getParameterTypes()[0] == String.class - && m.getParameterTypes()[1] == Predicate.class - && Map.class.isAssignableFrom(m.getReturnType())) { - listResources = m; - break; - } - } - if (listResources == null) { - throw new NoSuchMethodException("listResources(String, Predicate) on " + resourceManager.getClass().getName()); - } - listResources.setAccessible(true); - - Predicate endsWithNbt = location -> { - String path = identifierPath(location); - return path != null && path.endsWith(".nbt"); - }; - - Object resultMap = listResources.invoke(resourceManager, "structure", endsWithNbt); - TreeSet keys = new TreeSet<>(); - if (resultMap instanceof Map map) { - for (Object location : map.keySet()) { - String namespace = identifierNamespace(location); - String path = identifierPath(location); - if (namespace == null || path == null) { - continue; - } - String stripped = path; - if (stripped.startsWith("structure/")) { - stripped = stripped.substring("structure/".length()); - } - if (stripped.endsWith(".nbt")) { - stripped = stripped.substring(0, stripped.length() - ".nbt".length()); - } - if (stripped.isEmpty()) { - continue; - } - keys.add(namespace + ":" + stripped); - } - } - return new ArrayList<>(keys); - } - - private static Object resolveResourceManager(Object server) { - try { - Class resourceManagerClass = Class.forName("net.minecraft.server.packs.resources.ResourceManager"); - Method getter = null; - for (Method m : server.getClass().getMethods()) { - if (m.getName().equals("getResourceManager") && m.getParameterCount() == 0 - && resourceManagerClass.isAssignableFrom(m.getReturnType())) { - getter = m; - break; - } - } - if (getter == null) { - for (Method m : server.getClass().getMethods()) { - if (m.getParameterCount() == 0 && resourceManagerClass.isAssignableFrom(m.getReturnType())) { - getter = m; - break; - } - } - } - if (getter == null) { - return null; - } - getter.setAccessible(true); - return getter.invoke(server); - } catch (Throwable e) { - return null; - } - } - - private static TreeSet normalizeKeys(Iterable keys) { - TreeSet normalized = new TreeSet<>(); - for (String key : keys) { - if (key == null || key.isBlank()) { - continue; - } - normalized.add(key.trim().toLowerCase(Locale.ROOT)); - } - return normalized; - } - - private static String bundleKey(String name) { - return "iris:" + name; - } - - private static String identifierNamespace(Object location) { - try { - Method m = location.getClass().getMethod("getNamespace"); - m.setAccessible(true); - Object value = m.invoke(location); - return value == null ? null : value.toString(); - } catch (Throwable e) { - return null; - } - } - - private static String identifierPath(Object location) { - try { - Method m = location.getClass().getMethod("getPath"); - m.setAccessible(true); - Object value = m.invoke(location); - return value == null ? null : value.toString(); - } catch (Throwable e) { - return null; - } - } - - private static Object invoke(Object target, String method) throws Exception { - Class c = target.getClass(); - while (c != null) { - for (Method m : c.getDeclaredMethods()) { - if (m.getName().equals(method) && m.getParameterCount() == 0) { - m.setAccessible(true); - return m.invoke(target); - } - } - c = c.getSuperclass(); - } - for (Method m : target.getClass().getMethods()) { - if (m.getName().equals(method) && m.getParameterCount() == 0) { - m.setAccessible(true); - return m.invoke(target); - } - } - throw new NoSuchMethodException(method + " on " + target.getClass().getName()); - } - - record KeySelection(List present, List missing) { - KeySelection { - present = List.copyOf(present); - missing = List.copyOf(missing); - } - - int total() { - return present.size() + missing.size(); - } - } -} diff --git a/core/src/main/java/art/arcane/iris/core/structure/FeatureImporter.java b/core/src/main/java/art/arcane/iris/core/structure/FeatureImporter.java index 1ce06782e..cf792e827 100644 --- a/core/src/main/java/art/arcane/iris/core/structure/FeatureImporter.java +++ b/core/src/main/java/art/arcane/iris/core/structure/FeatureImporter.java @@ -23,6 +23,7 @@ import art.arcane.iris.core.ServerConfigurator; import art.arcane.iris.core.WorldCreatorCompat; import art.arcane.iris.core.lifecycle.LifecycleOperationCoordinator; import art.arcane.iris.core.lifecycle.WorldLifecycleService; +import art.arcane.iris.core.structure.authoring.StructureBundleNames; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.nms.INMS; import art.arcane.iris.core.pack.AtomicDirectoryPublisher; @@ -189,7 +190,7 @@ public final class FeatureImporter { if (key.isBlank()) { continue; } - rows.add(new Row(group, key, BulkStructureImporter.templateNameFor(key))); + rows.add(new Row(group, key, StructureBundleNames.templateName(key))); } rows.sort(Comparator.comparing(r -> r.group() + "/" + r.safeName())); return rows; diff --git a/core/src/main/java/art/arcane/iris/core/structure/StructureCaptureImporter.java b/core/src/main/java/art/arcane/iris/core/structure/StructureCaptureImporter.java deleted file mode 100644 index 3b12a0dd1..000000000 --- a/core/src/main/java/art/arcane/iris/core/structure/StructureCaptureImporter.java +++ /dev/null @@ -1,261 +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.structure; - -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.nms.INMS; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.util.common.format.C; -import art.arcane.iris.util.common.plugin.VolmitSender; -import art.arcane.iris.util.common.scheduling.J; -import art.arcane.volmlib.util.collection.KList; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.Block; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import java.util.TreeSet; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; - -import art.arcane.iris.core.localization.BukkitRuntimeMessages; -import art.arcane.iris.core.localization.IrisLanguage; -import art.arcane.volmlib.util.localization.MessageArgument; -public final class StructureCaptureImporter { - public record Report(int total, int imported, int skipped, int failed) { - } - - private static final int MAX_SPAN = 48; - private static final int CELL_STRIDE = 128; - private static final int CELL_COLUMNS = 8; - private static final long REGION_TIMEOUT_SECONDS = 30L; - - private StructureCaptureImporter() { - } - - public static Report importAllStructures(IrisData data, StructureImporter.Mode mode, VolmitSender sender) { - return importStructures(data, mode, sender, null); - } - - public static Report importStructures(IrisData data, StructureImporter.Mode mode, VolmitSender sender, - Set allowedStructureKeys) { - StructureImporter.Mode activeMode = mode == null ? StructureImporter.Mode.ADD_ONLY : mode; - if (!INMS.get().supportsStructureCapture()) { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STRUCTURE_CAPTURE_IMPORTER_STRUCTURE_CAPTURE_IS_NOT_SUPPORTED_BY_ACTIVE_NMS_BINDING_SKIPPING_CAPTURE_PASS)); - return new Report(0, 0, 0, 0); - } - - KList keys = INMS.get().getStructureKeys(); - if (keys == null || keys.isEmpty()) { - return new Report(0, 0, 0, 0); - } - - ArrayList targets = new ArrayList<>(); - for (String key : selectCaptureKeys(keys, allowedStructureKeys)) { - String name = StructureImporter.deriveName(key); - File structureFile = new File(data.getDataFolder(), "structures/" + name + ".json"); - if (structureFile.exists() && activeMode != StructureImporter.Mode.OVERWRITE) { - continue; - } - targets.add(key); - } - - int total = targets.size(); - if (total == 0) { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STRUCTURE_CAPTURE_IMPORTER_NO_CODE_GENERATED_STRUCTURES_LEFT_CAPTURE_EVERYTHING_IS_ALREADY_IMPORTED_AS_STRUCTURE)); - return new Report(0, 0, 0, 0); - } - - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STRUCTURE_CAPTURE_IMPORTER_CAPTURING_CODE_GENERATED_STRUCTURES_NO_NBT_TEMPLATE_INTO_SCRATCH_WORLD_SKIPPING_ANY, MessageArgument.untrusted("total", String.valueOf(total)), MessageArgument.untrusted("MAXSPAN", String.valueOf(MAX_SPAN)))); - - World scratch = FeatureImporter.createScratchWorld(sender); - if (scratch == null) { - return new Report(total, 0, 0, total); - } - - int imported = 0; - int skipped = 0; - int failed = 0; - int cellIndex = 0; - - try { - for (String key : targets) { - String name = StructureImporter.deriveName(key); - try { - IrisObject object = captureOne(scratch, key, cellIndex++); - if (object == null || object.getBlocks().isEmpty()) { - skipped++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STRUCTURE_CAPTURE_IMPORTER_SKIP_DID_NOT_PLACE_CAPTURABLE_STRUCTURE_HERE_TOO_LARGE_WRONG_DIMENSION_NO, MessageArgument.untrusted("key", String.valueOf(key)))); - continue; - } - object.shrinkwrap(); - StructureImporter.Result result = StructureImporter.writeSinglePieceStructure( - data, name, key, object, "CENTER_HEIGHT", activeMode); - if (!result.success()) { - failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STRUCTURE_CAPTURE_IMPORTER_FAIL, MessageArgument.untrusted("key", String.valueOf(key)), MessageArgument.untrusted("message", String.valueOf(result.message())))); - continue; - } - imported++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STRUCTURE_CAPTURE_IMPORTER_CAPTURE_OBJECTS_IOB_X_X, MessageArgument.untrusted("key", String.valueOf(key)), MessageArgument.untrusted("name", String.valueOf(name)), MessageArgument.untrusted("w", String.valueOf(object.getW())), MessageArgument.untrusted("h", String.valueOf(object.getH())), MessageArgument.untrusted("d", String.valueOf(object.getD())))); - } catch (Throwable e) { - failed++; - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STRUCTURE_CAPTURE_IMPORTER_FAIL_2, MessageArgument.untrusted("key", String.valueOf(key)), MessageArgument.untrusted("error", String.valueOf(e.getMessage())))); - IrisLogging.reportError(e); - } - - int processed = imported + skipped + failed; - if (processed % 10 == 0) { - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STRUCTURE_CAPTURE_IMPORTER_CAPTURED_SKIPPED_FAILED, MessageArgument.untrusted("processed", String.valueOf(processed)), MessageArgument.untrusted("total", String.valueOf(total)), MessageArgument.untrusted("imported", String.valueOf(imported)), MessageArgument.untrusted("skipped", String.valueOf(skipped)), MessageArgument.untrusted("failed", String.valueOf(failed)))); - } - } - } finally { - FeatureImporter.destroyScratchWorld(scratch, sender); - } - - sender.sendMessage(IrisLanguage.text(BukkitRuntimeMessages.STRUCTURE_CAPTURE_IMPORTER_STRUCTURE_CAPTURE_COMPLETE_CAPTURED_SKIPPED_FAILED_TOTAL, MessageArgument.untrusted("imported", String.valueOf(imported)), MessageArgument.untrusted("skipped", String.valueOf(skipped)), MessageArgument.untrusted("failed", String.valueOf(failed)), MessageArgument.untrusted("total", String.valueOf(total)))); - return new Report(total, imported, skipped, failed); - } - - static List selectCaptureKeys(Iterable keys, Set allowedStructureKeys) { - TreeSet allowed = null; - if (allowedStructureKeys != null) { - allowed = normalizeKeys(allowedStructureKeys); - } - TreeSet selected = new TreeSet<>(); - for (String key : keys) { - if (key == null || key.isBlank()) { - continue; - } - String normalized = key.trim().toLowerCase(Locale.ROOT); - if (allowed == null || allowed.contains(normalized)) { - selected.add(normalized); - } - } - return new ArrayList<>(selected); - } - - private static TreeSet normalizeKeys(Iterable keys) { - TreeSet normalized = new TreeSet<>(); - for (String key : keys) { - if (key == null || key.isBlank()) { - continue; - } - normalized.add(key.trim().toLowerCase(Locale.ROOT)); - } - return normalized; - } - - private static IrisObject captureOne(World world, String key, int cellIndex) { - int originX = (cellIndex % CELL_COLUMNS) * CELL_STRIDE; - int originZ = (cellIndex / CELL_COLUMNS) * CELL_STRIDE; - int anchorChunkX = (originX + CELL_STRIDE / 2) >> 4; - int anchorChunkZ = (originZ + CELL_STRIDE / 2) >> 4; - long seed = key.hashCode() * 0x9E3779B97F4A7C15L + cellIndex * 0x100000001B3L + 0x5DEECE66DL; - - AtomicReference objectRef = new AtomicReference<>(); - AtomicReference errorRef = new AtomicReference<>(); - CountDownLatch latch = new CountDownLatch(1); - - boolean scheduled = J.runRegion(world, anchorChunkX, anchorChunkZ, () -> { - try { - int[] box = INMS.get().placeStructure(world, anchorChunkX, anchorChunkZ, key, seed, MAX_SPAN); - if (box == null) { - return; - } - int width = box[3] - box[0] + 1; - int height = box[4] - box[1] + 1; - int depth = box[5] - box[2] + 1; - if (width <= 0 || height <= 0 || depth <= 0) { - return; - } - IrisObject object = new IrisObject(width, height, depth); - boolean any = false; - for (int dx = 0; dx < width; dx++) { - for (int dy = 0; dy < height; dy++) { - for (int dz = 0; dz < depth; dz++) { - Block block = world.getBlockAt(box[0] + dx, box[1] + dy, box[2] + dz); - if (block.getType() == Material.AIR) { - continue; - } - object.setUnsigned(dx, dy, dz, block, false); - any = true; - } - } - } - if (any) { - objectRef.set(object); - } - - int minCX = box[0] >> 4; - int maxCX = box[3] >> 4; - int minCZ = box[2] >> 4; - int maxCZ = box[5] >> 4; - for (int cx = minCX; cx <= maxCX; cx++) { - for (int cz = minCZ; cz <= maxCZ; cz++) { - try { - world.unloadChunk(cx, cz, false); - } catch (Throwable ignored) { - } - } - } - } catch (Throwable e) { - errorRef.set(e); - } finally { - latch.countDown(); - } - }); - - if (!scheduled) { - throw captureFailure(key, anchorChunkX, anchorChunkZ, - "region task was not accepted", null); - } - - try { - if (!latch.await(REGION_TIMEOUT_SECONDS, TimeUnit.SECONDS)) { - throw captureFailure(key, anchorChunkX, anchorChunkZ, - "region task did not complete within " + REGION_TIMEOUT_SECONDS + " seconds", null); - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw captureFailure(key, anchorChunkX, anchorChunkZ, - "interrupted while waiting for the region task", e); - } - - Throwable error = errorRef.get(); - if (error != null) { - throw captureFailure(key, anchorChunkX, anchorChunkZ, - "platform placement failed", error); - } - return objectRef.get(); - } - - static IllegalStateException captureFailure(String key, int chunkX, int chunkZ, - String detail, Throwable cause) { - String message = "Structure capture failed for '" + key + "' at chunk " - + chunkX + "," + chunkZ + ": " + detail; - return cause == null ? new IllegalStateException(message) : new IllegalStateException(message, cause); - } -} diff --git a/core/src/main/java/art/arcane/iris/core/structure/VillageImporter.java b/core/src/main/java/art/arcane/iris/core/structure/VillageImporter.java deleted file mode 100644 index 78c4a2d9e..000000000 --- a/core/src/main/java/art/arcane/iris/core/structure/VillageImporter.java +++ /dev/null @@ -1,1266 +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.structure; - -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.structure.authoring.StructureBackend; -import art.arcane.iris.core.structure.authoring.StructureCapability; -import art.arcane.iris.core.structure.authoring.StructureKey; -import art.arcane.iris.core.structure.authoring.StructureLoss; -import art.arcane.iris.core.structure.authoring.StructureResourceBundle; -import art.arcane.iris.core.structure.authoring.StructureSource; -import art.arcane.iris.core.structure.authoring.StructureWriteMode; -import art.arcane.iris.core.structure.authoring.StructureWriteResult; -import art.arcane.iris.engine.framework.structure.StructureGraphValidationException; -import art.arcane.iris.engine.framework.structure.StructureResourceBundleGraphCompiler; -import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.spi.IrisLogging; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import org.bukkit.Bukkit; -import org.bukkit.NamespacedKey; -import org.bukkit.structure.Structure; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Deque; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -public final class VillageImporter { - private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); - private static final Set PRINTED_FAILURE_SIGNATURES = ConcurrentHashMap.newKeySet(); - - public record Result( - boolean success, - String message, - int pools, - int pieces, - List losses, - boolean retryableFailure - ) { - public Result(boolean success, String message, int pools, int pieces, List losses) { - this(success, message, pools, pieces, losses, false); - } - - public Result { - losses = List.copyOf(losses); - } - } - - private VillageImporter() { - } - - public static Result importVillage(IrisData data, NamespacedKey structureKey, String name, StructureImporter.Mode mode) { - return importVillage(data, structureKey, name, mode, StructureImporter.Ownership.EDITABLE); - } - - static Result importVillage( - IrisData data, - NamespacedKey structureKey, - String name, - StructureImporter.Mode mode, - StructureImporter.Ownership ownership - ) { - StructureImporter.Mode activeMode = mode == null ? StructureImporter.Mode.ADD_ONLY : mode; - List losses = new ArrayList<>(); - boolean retryableFailure = false; - Object server; - Object registryAccess; - Object structureManager; - String writeNote = ""; - try { - Object craftServer = Bukkit.getServer(); - Object dedicated = invoke(craftServer, "getHandle"); - server = invoke(dedicated, "getServer"); - registryAccess = resolveRegistryAccess(server); - structureManager = invoke(server, "getStructureManager"); - } catch (Throwable e) { - reportFailure(e); - return failed("Failed to access server registries via reflection: " + e, losses, true); - } - if (registryAccess == null) { - return failed("Could not resolve RegistryAccess from the server", losses, true); - } - - Object startPool; - int maxDepth; - int maxDistanceFromCenter; - try { - Object structureRegistry = lookupRegistry(registryAccess, "STRUCTURE"); - Object structure = registryGet(structureRegistry, structureKey); - if (structure == null) { - return failed("No structure registered for key " + structureKey, losses); - } - if (!structure.getClass().getName().endsWith("JigsawStructure")) { - return failed("Structure " + structureKey + " is not a jigsaw structure (" - + structure.getClass().getSimpleName() + "); use 'import' for single-template structures", losses); - } - Object startPoolHolder = invoke(structure, "getStartPool"); - startPool = unwrapHolder(startPoolHolder); - maxDepth = readIntMember(structure, "maxDepth"); - maxDistanceFromCenter = readIntMember(structure, "maxDistanceFromCenter"); - } catch (Throwable e) { - reportFailure(e); - return failed("Failed to read jigsaw structure graph: " + e, losses, true); - } - - Object templatePoolRegistry; - java.util.Random random; - try { - templatePoolRegistry = lookupRegistry(registryAccess, "TEMPLATE_POOL"); - random = new java.util.Random(structureKey.hashCode()); - } catch (Throwable e) { - reportFailure(e); - return failed("Failed to access TEMPLATE_POOL registry: " + e, losses, true); - } - - String startPoolKey; - try { - startPoolKey = registryKeyOf(templatePoolRegistry, startPool); - } catch (Throwable e) { - reportFailure(e); - return failed("Could not resolve the start pool key for " + structureKey + ": " + e, losses, true); - } - if (startPoolKey == null) { - return failed("Could not resolve the start pool key for " + structureKey, losses); - } - - Set visitedPools = new HashSet<>(); - Deque poolQueue = new ArrayDeque<>(); - poolQueue.add(startPoolKey); - - Map> emittedPools = new LinkedHashMap<>(); - Map> emittedPieces = new LinkedHashMap<>(); - Map emittedObjects = new LinkedHashMap<>(); - Map importedTemplates = new LinkedHashMap<>(); - Set capabilities = new HashSet<>(); - capabilities.add(StructureCapability.BLOCKS); - capabilities.add(StructureCapability.CONNECTORS); - capabilities.add(StructureCapability.IRIS_PLACEMENT); - List fatalErrors = new ArrayList<>(); - losses.add(StructureLoss.warning( - StructureCapability.NATIVE_PLACEMENT, - "native_placement_settings_not_imported", - "Native jigsaw placement settings other than the start pool, maximum depth, and maximum distance are not represented by the Iris assembly.")); - int pieceBlocks = 0; - int emittedPoolMembers = 0; - - while (!poolQueue.isEmpty()) { - String poolKey = poolQueue.poll(); - if (!visitedPools.add(poolKey)) { - continue; - } - Object pool; - try { - pool = registryGetByKey(templatePoolRegistry, poolKey); - } catch (Throwable e) { - reportFailure(e); - retryableFailure = true; - fatalErrors.add("pool " + poolKey + ": " + e.getMessage()); - continue; - } - if (pool == null) { - fatalErrors.add("pool " + poolKey + " is not registered"); - continue; - } - - String irisPoolName = poolName(name, poolKey); - List pieceEntries = new ArrayList<>(); - - String fallbackKey = null; - try { - Object fallbackHolder = invoke(pool, "getFallback"); - Object fallbackPool = unwrapHolder(fallbackHolder); - fallbackKey = registryKeyOf(templatePoolRegistry, fallbackPool); - } catch (Throwable e) { - reportFailure(e); - retryableFailure = true; - losses.add(StructureLoss.warning( - StructureCapability.CONNECTORS, - "fallback_pool_not_imported", - "The fallback for source pool " + poolKey + " could not be resolved: " + failureDetail(e)) - .affecting("jigsaw-pools/" + irisPoolName + ".json")); - } - if (fallbackKey != null && !fallbackKey.equals(poolKey)) { - poolQueue.add(fallbackKey); - } - - List templates; - try { - templates = (List) invoke(pool, "getTemplates"); - } catch (Throwable e) { - reportFailure(e); - retryableFailure = true; - fatalErrors.add("templates " + poolKey + ": " + e.getMessage()); - templates = List.of(); - } - - for (Object pair : templates) { - Object element; - int weight; - try { - element = invoke(pair, "getFirst"); - Object second = invoke(pair, "getSecond"); - weight = second instanceof Number ? Math.max(1, ((Number) second).intValue()) : 1; - } catch (Throwable e) { - reportFailure(e); - retryableFailure = true; - losses.add(StructureLoss.warning( - StructureCapability.LIST_ELEMENTS, - "pool_entry_not_imported", - "A source entry in pool " + poolKey + " could not be read: " + failureDetail(e)) - .affecting("jigsaw-pools/" + irisPoolName + ".json")); - continue; - } - if (element == null) { - continue; - } - PoolElementResolution elementResolution; - try { - elementResolution = resolvePoolElement(element); - } catch (Throwable e) { - reportFailure(e); - retryableFailure = true; - losses.add(StructureLoss.warning( - StructureCapability.BLOCKS, - "template_location_not_imported", - "A source template location in pool " + poolKey + " could not be read: " + failureDetail(e)) - .affecting("jigsaw-pools/" + irisPoolName + ".json")); - continue; - } - if (elementResolution.omittedElements() > 0) { - losses.add(listElementFallbackLoss(elementResolution, poolKey) - .affecting("jigsaw-pools/" + irisPoolName + ".json")); - } - Object physicalElement = elementResolution.physicalElement(); - String templateLocation = elementResolution.templateLocation(); - if (templateLocation == null) { - String elementType = physicalElement == null - ? element.getClass().getSimpleName() - : physicalElement.getClass().getSimpleName(); - if (elementType.endsWith("EmptyPoolElement")) { - pieceEntries.add(emptyPoolEntry(weight)); - emittedPoolMembers++; - } else { - StructureCapability unsupportedCapability = unsupportedCapability(elementType); - losses.add(StructureLoss.warning( - unsupportedCapability, - "unsupported_pool_element", - "Skipped unsupported " + elementType + " in source pool " + poolKey + ".") - .affecting("jigsaw-pools/" + irisPoolName + ".json")); - } - continue; - } - NamespacedKey pieceNbtKey = NamespacedKey.fromString(templateLocation.toLowerCase()); - if (pieceNbtKey == null) { - fatalErrors.add("invalid piece key " + templateLocation + " in pool " + poolKey); - continue; - } - String irisPieceName = pieceName(name, templateLocation); - - ImportedTemplate importedTemplate = importedTemplates.get(irisPieceName); - if (importedTemplate == null) { - Structure sourceTemplate; - try { - sourceTemplate = Bukkit.getStructureManager().loadStructure(pieceNbtKey); - } catch (Throwable e) { - reportFailure(e); - retryableFailure = true; - fatalErrors.add(templateLocation + ": failed to load structure template: " + failureDetail(e)); - continue; - } - if (sourceTemplate == null || sourceTemplate.getPalettes().isEmpty()) { - fatalErrors.add(templateLocation + ": no loadable structure template was registered"); - continue; - } - - StructureImporter.CapturedStructure captured; - try { - captured = StructureImporter.captureStructure(sourceTemplate); - } catch (Throwable e) { - reportFailure(e); - retryableFailure = true; - fatalErrors.add(templateLocation + ": failed to capture structure template: " + failureDetail(e)); - continue; - } - for (StructureLoss loss : captured.losses()) { - losses.add(loss.affecting("objects/" + irisPieceName + ".iob")); - } - - Connectors result = readConnectors(element, structureManager, random, name, irisPieceName); - retryableFailure |= result.retryableFailure(); - importedTemplate = new ImportedTemplate( - captured.object(), - captured.blocks(), - captured.nonAirBlocks(), - result.json(), - captured.capabilities()); - importedTemplates.put(irisPieceName, importedTemplate); - poolQueue.addAll(result.targetPoolKeys()); - losses.addAll(result.losses()); - } - - PoolMemberNormalization normalization = normalizePoolMember( - poolKey, - irisPoolName, - poolKey.equals(startPoolKey), - templates.size(), - fallbackKey, - templateLocation, - irisPieceName, - weight, - importedTemplate.nonAirBlocks(), - importedTemplate.connectors()); - losses.addAll(normalization.losses()); - if (!emittedPieces.containsKey(irisPieceName)) { - pieceBlocks += importedTemplate.emittedBlocks(normalization); - capabilities.addAll(importedTemplate.emittedCapabilities(normalization)); - if (normalization.disposition() == PoolMemberDisposition.PHYSICAL) { - emittedObjects.put(irisPieceName, importedTemplate.object()); - emittedPieces.put(irisPieceName, pieceJson( - irisPieceName, - importedTemplate.connectors(), - importedTemplate.nonAirBlocks())); - } - } - if (!normalization.poolEntry().isEmpty()) { - pieceEntries.add(normalization.poolEntry()); - emittedPoolMembers++; - } - } - - Map poolJson = new LinkedHashMap<>(); - poolJson.put("pieces", pieceEntries); - if (fallbackKey != null && !fallbackKey.equals(poolKey)) { - poolJson.put("fallback", poolName(name, fallbackKey)); - } - emittedPools.put(irisPoolName, poolJson); - } - - if (!fatalErrors.isEmpty()) { - return failed("Failed to capture the complete graph for " + structureKey + ": " + fatalErrors.getFirst() - + (fatalErrors.size() == 1 ? "" : " (" + (fatalErrors.size() - 1) + " more)"), losses, - retryableFailure); - } - if (emittedPoolMembers == 0) { - return failed("Imported 0 attachable or empty pool members for " + structureKey, losses); - } - for (StructureLoss loss : losses) { - if (loss.capability() == StructureCapability.CONNECTORS) { - capabilities.remove(StructureCapability.CONNECTORS); - break; - } - } - - try { - StructureKey sourceKey = StructureKey.parse(structureKey.toString()); - StructureSource.Kind sourceKind = structureKey.getNamespace().equals("minecraft") - ? StructureSource.Kind.VANILLA : StructureSource.Kind.DATAPACK; - StructureSource source = new StructureSource(sourceKind, sourceKey, Bukkit.getBukkitVersion(), ""); - Map objectResources = new LinkedHashMap<>(); - for (Map.Entry entry : emittedObjects.entrySet()) { - objectResources.put(entry.getKey(), serialize(entry.getValue())); - } - Map rootStructure = structureJson( - structureKey.toString(), - poolName(name, startPoolKey), - maxDepth, - maxDistanceFromCenter); - StructureResourceBundle bundle = buildBundle( - new StructureKey("iris", name), - source, - objectResources, - emittedPieces, - emittedPools, - rootStructure, - capabilities, - losses); - StructureResourceBundleGraphCompiler.requireViable(bundle); - StructureWriteMode writeMode = activeMode == StructureImporter.Mode.OVERWRITE - ? StructureWriteMode.OVERWRITE : StructureWriteMode.ADD_ONLY; - StructureWriteResult writeResult = ownership.write(data, bundle, writeMode); - reportWriteFailure(writeResult); - if (!writeResult.successful()) { - return new Result(false, writeFailureMessage(name, writeResult), emittedPools.size(), - emittedPieces.size(), losses, writeResult.failure().isPresent()); - } - if (writeResult.committed()) { - data.invalidateStructureResources(); - } - writeNote = writeResultNote(writeResult); - } catch (StructureGraphValidationException e) { - return new Result(false, "Failed writing jigsaw resources for '" + name + "': " + e.getMessage(), - emittedPools.size(), emittedPieces.size(), losses, retryableFailure); - } catch (Throwable e) { - reportFailure(e); - return new Result(false, "Failed writing jigsaw resources for '" + name + "': " + e, - emittedPools.size(), emittedPieces.size(), losses, true); - } - - String msg = "Imported jigsaw structure " + structureKey + " as '" + name + "': " + emittedPieces.size() + " pieces, " + emittedPools.size() + " pools, " + pieceBlocks + " blocks"; - if (!losses.isEmpty()) { - msg += " (" + losses.size() + " fidelity warning(s) recorded)"; - } - return new Result(true, msg + writeNote, emittedPools.size(), emittedPieces.size(), losses); - } - - static StructureResourceBundle buildBundle( - StructureKey bundleKey, - StructureSource source, - Map objects, - Map> pieces, - Map> pools, - Map structure, - Set capabilities, - List losses - ) { - StructureResourceBundle.Builder bundle = StructureResourceBundle.builder(bundleKey) - .source(source) - .backend(StructureBackend.IRIS_ASSEMBLY) - .capabilities(capabilities) - .losses(losses); - for (Map.Entry entry : objects.entrySet()) { - bundle.resource("objects/" + entry.getKey() + ".iob", entry.getValue()); - } - for (Map.Entry> entry : pieces.entrySet()) { - bundle.textResource("jigsaw-pieces/" + entry.getKey() + ".json", GSON.toJson(entry.getValue())); - } - for (Map.Entry> entry : pools.entrySet()) { - bundle.textResource("jigsaw-pools/" + entry.getKey() + ".json", GSON.toJson(entry.getValue())); - } - bundle.textResource("structures/" + bundleKey.path() + ".json", GSON.toJson(structure)); - return bundle.build(); - } - - private record Connectors( - List> json, - Set targetPoolKeys, - List losses, - boolean retryableFailure - ) { - } - - record ImportedTemplate( - IrisObject object, - int blocks, - int nonAirBlocks, - List> connectors, - List capabilities - ) { - ImportedTemplate { - connectors = List.copyOf(connectors); - capabilities = List.copyOf(capabilities); - } - - int emittedBlocks(PoolMemberNormalization normalization) { - return normalization.disposition() == PoolMemberDisposition.PHYSICAL ? blocks : 0; - } - - List emittedCapabilities(PoolMemberNormalization normalization) { - return normalization.disposition() == PoolMemberDisposition.PHYSICAL ? capabilities : List.of(); - } - } - - enum PoolMemberDisposition { - PHYSICAL, - EMPTY, - OMITTED - } - - record PoolMemberNormalization( - PoolMemberDisposition disposition, - Map poolEntry, - List losses - ) { - PoolMemberNormalization { - poolEntry = Collections.unmodifiableMap(new LinkedHashMap<>(poolEntry)); - losses = List.copyOf(losses); - } - } - - private static Connectors readConnectors( - Object element, - Object structureManager, - java.util.Random random, - String baseName, - String pieceName - ) { - List> connectors = new ArrayList<>(); - Set targets = new HashSet<>(); - List losses = new ArrayList<>(); - boolean retryableFailure = false; - String affectedResource = "jigsaw-pieces/" + pieceName + ".json"; - try { - Object zero = staticField("net.minecraft.core.BlockPos", "ZERO"); - Object rotationNone = staticField("net.minecraft.world.level.block.Rotation", "NONE"); - Method m = findMethod4(element.getClass(), "getShuffledJigsawBlocks"); - if (m == null) { - losses.add(StructureLoss.warning( - StructureCapability.CONNECTORS, - "connector_extraction_unavailable", - "The source pool element does not expose jigsaw connector extraction on this server version.") - .affecting(affectedResource)); - return new Connectors(connectors, targets, losses, false); - } - m.setAccessible(true); - Object random0 = freshRandomSource(random); - List blocks = (List) m.invoke(element, structureManager, zero, rotationNone, random0); - if (blocks == null) { - losses.add(StructureLoss.warning( - StructureCapability.CONNECTORS, - "connector_extraction_returned_null", - "The source pool element returned no connector collection.") - .affecting(affectedResource)); - return new Connectors(connectors, targets, losses, false); - } - for (Object jigsaw : blocks) { - String[] rawPoolKey = new String[1]; - try { - Map connector = connectorFrom(jigsaw, baseName, rawPoolKey); - connectors.add(connector); - if (rawPoolKey[0] != null && !rawPoolKey[0].isEmpty()) { - targets.add(rawPoolKey[0]); - } - } catch (Throwable e) { - reportFailure(e); - retryableFailure = true; - losses.add(StructureLoss.warning( - StructureCapability.CONNECTORS, - "connector_not_imported", - "A source jigsaw connector could not be converted: " + failureDetail(e)) - .affecting(affectedResource)); - } - } - } catch (Throwable e) { - reportFailure(e); - retryableFailure = true; - losses.add(StructureLoss.warning( - StructureCapability.CONNECTORS, - "connector_extraction_failed", - "Source jigsaw connectors could not be extracted: " + failureDetail(e)) - .affecting(affectedResource)); - } - return new Connectors(connectors, targets, losses, retryableFailure); - } - - private static Map connectorFrom(Object jigsaw, String baseName, String[] rawPoolKeyOut) throws Exception { - Object info = invoke(jigsaw, "info"); - Object pos = invoke(info, "pos"); - Object blockState = invoke(info, "state"); - int x = readInt(pos, "getX"); - int y = readInt(pos, "getY"); - int z = readInt(pos, "getZ"); - - Object poolKey = invoke(jigsaw, "pool"); - String poolId = identifierString(invoke(poolKey, "identifier")); - Object nameId = invoke(jigsaw, "name"); - Object targetId = invoke(jigsaw, "target"); - Object jointType = invoke(jigsaw, "jointType"); - - String front = frontFacing(blockState); - String top = topFacing(blockState); - rawPoolKeyOut[0] = poolId; - - ConnectorMetadata metadata = readConnectorMetadata(jigsaw, info); - return connectorJson( - x, - y, - z, - front, - top, - poolId, - baseName, - identifierString(nameId), - identifierString(targetId), - jointType, - metadata - ); - } - - static Map connectorJson( - int x, - int y, - int z, - String front, - String top, - String poolId, - String baseName, - String nameId, - String targetId, - Object jointType, - ConnectorMetadata metadata - ) { - Map connector = new LinkedHashMap<>(); - Map position = new LinkedHashMap<>(); - position.put("x", x); - position.put("y", y); - position.put("z", z); - connector.put("position", position); - connector.put("direction", irisDirection(front)); - connector.put("top", irisDirection(top)); - connector.put("pool", poolId == null ? "" : poolName(baseName, poolId)); - connector.put("name", nameId); - connector.put("targetName", targetId); - connector.put("joint", jointType != null && jointType.toString().toUpperCase().contains("ALIGN") ? "ALIGNED" : "ROLLABLE"); - connector.put("finalState", metadata.finalState()); - connector.put("selectionPriority", metadata.selectionPriority()); - connector.put("placementPriority", metadata.placementPriority()); - return connector; - } - - static ConnectorMetadata readConnectorMetadata(Object jigsaw, Object info) throws Exception { - Object nbt = invoke(info, "nbt"); - String finalState = readNbtString(nbt, "final_state"); - String normalizedFinalState = finalState == null || finalState.isBlank() - ? "minecraft:air" - : StructureImporter.normalizeJigsawFinalState(finalState); - return new ConnectorMetadata( - normalizedFinalState, - readIntAccessor(jigsaw, "selectionPriority"), - readIntAccessor(jigsaw, "placementPriority") - ); - } - - private static String readNbtString(Object nbt, String key) throws Exception { - if (nbt == null) { - return null; - } - Method method = findMethod(nbt.getClass(), "getString", 1); - if (method == null) { - throw new NoSuchMethodException("getString(String) on " + nbt.getClass().getName()); - } - method.setAccessible(true); - Object value = method.invoke(nbt, key); - if (value instanceof String string) { - return string; - } - if (value instanceof Optional optional) { - return optional.isPresent() ? String.valueOf(optional.get()) : null; - } - return value == null ? null : String.valueOf(value); - } - - private static int readIntAccessor(Object value, String accessor) throws Exception { - Method method = findMethod(value.getClass(), accessor); - if (method == null) { - throw new NoSuchMethodException(accessor + "() on " + value.getClass().getName()); - } - method.setAccessible(true); - Object result = method.invoke(value); - if (result instanceof Number number) { - return number.intValue(); - } - throw new IllegalStateException(accessor + " on " + value.getClass().getName() + " is not numeric"); - } - - private static String frontFacing(Object blockState) throws Exception { - Class jigsawBlock = Class.forName("net.minecraft.world.level.block.JigsawBlock"); - Method getFront = jigsawBlock.getMethod("getFrontFacing", Class.forName("net.minecraft.world.level.block.state.BlockState")); - Object direction = getFront.invoke(null, blockState); - if (direction == null) { - return "north"; - } - Method getName = direction.getClass().getMethod("getName"); - getName.setAccessible(true); - return String.valueOf(getName.invoke(direction)).toLowerCase(); - } - - private static String topFacing(Object blockState) throws Exception { - Class jigsawBlock = Class.forName("net.minecraft.world.level.block.JigsawBlock"); - Method getTop = jigsawBlock.getMethod("getTopFacing", Class.forName("net.minecraft.world.level.block.state.BlockState")); - Object direction = getTop.invoke(null, blockState); - if (direction == null) { - return "up"; - } - Method getName = direction.getClass().getMethod("getName"); - getName.setAccessible(true); - return String.valueOf(getName.invoke(direction)).toLowerCase(); - } - - private static String irisDirection(String front) { - return switch (front) { - case "up" -> "UP_POSITIVE_Y"; - case "down" -> "DOWN_NEGATIVE_Y"; - case "south" -> "SOUTH_POSITIVE_Z"; - case "east" -> "EAST_POSITIVE_X"; - case "west" -> "WEST_NEGATIVE_X"; - default -> "NORTH_NEGATIVE_Z"; - }; - } - - private static String templateLocationOf(Object element) throws Exception { - Method m = findMethod(element.getClass(), "getTemplateLocation"); - if (m == null) { - return null; - } - m.setAccessible(true); - Object id = m.invoke(element); - return identifierString(id); - } - - static PoolElementResolution resolvePoolElement(Object element) throws Exception { - if (element == null) { - return new PoolElementResolution(null, null, 0, 0); - } - if (!element.getClass().getSimpleName().endsWith("ListPoolElement")) { - return new PoolElementResolution(element, templateLocationOf(element), 0, 0); - } - Object rawElements = invoke(element, "getElements"); - if (!(rawElements instanceof List elements)) { - throw new IllegalStateException("getElements on " + element.getClass().getName() + " is not a list"); - } - if (elements.isEmpty()) { - return new PoolElementResolution(null, null, 1, 0); - } - PoolElementResolution primary = resolvePoolElement(elements.getFirst()); - return new PoolElementResolution( - primary.physicalElement(), - primary.templateLocation(), - primary.listLevels() + 1, - primary.omittedElements() + elements.size() - 1 - ); - } - - static StructureLoss listElementFallbackLoss(PoolElementResolution resolution, String poolKey) { - int omitted = resolution.omittedElements(); - String elementLabel = omitted == 1 ? "element" : "elements"; - String levelLabel = resolution.listLevels() == 1 ? "list level" : "nested list levels"; - return StructureLoss.warning( - StructureCapability.LIST_ELEMENTS, - "list_pool_overlays_not_imported", - "Converted the first physical template from a ListPoolElement in source pool " + poolKey - + " and omitted " + omitted + " colocated " + elementLabel - + ", including their processors, across " + resolution.listLevels() + " " + levelLabel + "." - ); - } - - private static Object resolveRegistryAccess(Object server) { - try { - Class frozen = Class.forName("net.minecraft.core.RegistryAccess$Frozen"); - for (Method m : server.getClass().getMethods()) { - if (m.getParameterCount() == 0 && frozen.isAssignableFrom(m.getReturnType())) { - m.setAccessible(true); - Object o = m.invoke(server); - if (o != null) { - return o; - } - } - } - Class ra = Class.forName("net.minecraft.core.RegistryAccess"); - for (Method m : server.getClass().getMethods()) { - if (m.getParameterCount() == 0 && ra.isAssignableFrom(m.getReturnType())) { - m.setAccessible(true); - Object o = m.invoke(server); - if (o != null) { - return o; - } - } - } - } catch (Throwable e) { - reportFailure(e); - } - return null; - } - - private static Object lookupRegistry(Object registryAccess, String registryName) throws Exception { - Class registries = Class.forName("net.minecraft.core.registries.Registries"); - Object resourceKey = registries.getField(registryName).get(null); - Class registryClass = Class.forName("net.minecraft.core.Registry"); - Method registryOverload = null; - for (Method m : registryAccess.getClass().getMethods()) { - if (m.getName().equals("lookupOrThrow") && m.getParameterCount() == 1 - && m.getParameterTypes()[0].getName().endsWith("ResourceKey") - && registryClass.isAssignableFrom(m.getReturnType())) { - registryOverload = m; - break; - } - } - if (registryOverload == null) { - for (Method m : registryAccess.getClass().getMethods()) { - if (m.getName().equals("lookupOrThrow") && m.getParameterCount() == 1 - && m.getParameterTypes()[0].getName().endsWith("ResourceKey")) { - registryOverload = m; - break; - } - } - } - if (registryOverload == null) { - throw new NoSuchMethodException("lookupOrThrow(ResourceKey) on " + registryAccess.getClass().getName()); - } - registryOverload.setAccessible(true); - return registryOverload.invoke(registryAccess, resourceKey); - } - - private static Object registryGet(Object registry, NamespacedKey key) throws Exception { - Object id = identifierOf(key); - for (Method m : registry.getClass().getMethods()) { - if (m.getName().equals("getValue") && m.getParameterCount() == 1 && m.getParameterTypes()[0].getName().endsWith("Identifier")) { - m.setAccessible(true); - return m.invoke(registry, id); - } - } - for (Method m : registry.getClass().getMethods()) { - if (m.getName().equals("getOptional") && m.getParameterCount() == 1 && m.getParameterTypes()[0].getName().endsWith("Identifier")) { - m.setAccessible(true); - return unwrapOptional(m.invoke(registry, id)); - } - } - return null; - } - - private static Object registryGetByKey(Object registry, String key) throws Exception { - NamespacedKey nk = NamespacedKey.fromString(key.toLowerCase()); - if (nk == null) { - return null; - } - return registryGet(registry, nk); - } - - private static String registryKeyOf(Object registry, Object value) throws Exception { - if (value == null) { - return null; - } - for (Method m : registry.getClass().getMethods()) { - if (m.getName().equals("getKey") && m.getParameterCount() == 1) { - m.setAccessible(true); - Object id = m.invoke(registry, value); - String s = identifierString(id); - if (s != null) { - return s; - } - } - } - return null; - } - - private static Object identifierOf(NamespacedKey key) throws Exception { - Class identifier = Class.forName("net.minecraft.resources.Identifier"); - try { - Method fromNamespaceAndPath = identifier.getMethod("fromNamespaceAndPath", String.class, String.class); - return fromNamespaceAndPath.invoke(null, key.getNamespace(), key.getKey()); - } catch (NoSuchMethodException e) { - Method withDefaultNamespace = identifier.getMethod("parse", String.class); - return withDefaultNamespace.invoke(null, key.toString()); - } - } - - private static String identifierString(Object id) { - if (id == null) { - return null; - } - try { - Method getNamespace = id.getClass().getMethod("getNamespace"); - Method getPath = id.getClass().getMethod("getPath"); - getNamespace.setAccessible(true); - getPath.setAccessible(true); - return getNamespace.invoke(id) + ":" + getPath.invoke(id); - } catch (Throwable e) { - return id.toString(); - } - } - - private static Object unwrapHolder(Object holder) { - if (holder == null) { - return null; - } - try { - Method value = findMethod(holder.getClass(), "value"); - if (value != null) { - value.setAccessible(true); - return value.invoke(holder); - } - } catch (Throwable ignored) { - } - return holder; - } - - private static Object unwrapOptional(Object opt) { - if (opt == null) { - return null; - } - if (opt instanceof java.util.Optional o) { - return o.orElse(null); - } - return opt; - } - - static int readIntMember(Object value, String memberName) throws Exception { - Class type = value.getClass(); - while (type != null) { - try { - Field field = type.getDeclaredField(memberName); - field.setAccessible(true); - return coerceInt(field.get(value), memberName, value); - } catch (NoSuchFieldException ignored) { - type = type.getSuperclass(); - } - } - Method method = findMethod(value.getClass(), memberName); - if (method != null) { - method.setAccessible(true); - return coerceInt(method.invoke(value), memberName, value); - } - throw new NoSuchFieldException(memberName + " on " + value.getClass().getName()); - } - - /** - * Members that are plain numbers on one server build are wrapper objects on another - * (JigsawStructure.maxDistanceFromCenter became a MaxDistance{horizontal, vertical} record). - * Numbers pass through; a wrapper contributes its horizontal component, else its largest - * integral component, so a distance bound is never under-read. - */ - private static int coerceInt(Object member, String memberName, Object owner) throws Exception { - if (member instanceof Number n) { - return n.intValue(); - } - if (member == null) { - throw new NoSuchFieldException(memberName + " on " + owner.getClass().getName() + " is null"); - } - Method horizontal = findMethod(member.getClass(), "horizontal"); - if (horizontal != null && Number.class.isAssignableFrom(boxedType(horizontal.getReturnType()))) { - horizontal.setAccessible(true); - return ((Number) horizontal.invoke(member)).intValue(); - } - Integer widest = null; - for (Field component : member.getClass().getDeclaredFields()) { - if (Modifier.isStatic(component.getModifiers()) - || !Number.class.isAssignableFrom(boxedType(component.getType()))) { - continue; - } - component.setAccessible(true); - Object componentValue = component.get(member); - if (componentValue instanceof Number n && (widest == null || n.intValue() > widest)) { - widest = n.intValue(); - } - } - if (widest != null) { - return widest; - } - throw new NoSuchFieldException(memberName + " on " + owner.getClass().getName() - + " is a " + member.getClass().getName() + " with no integral component"); - } - - private static Class boxedType(Class type) { - return type == int.class ? Integer.class : type; - } - - private static int readInt(Object o, String method) throws Exception { - Method m = o.getClass().getMethod(method); - m.setAccessible(true); - return ((Number) m.invoke(o)).intValue(); - } - - private static Object staticField(String className, String fieldName) throws Exception { - Class c = Class.forName(className); - Field f = c.getField(fieldName); - return f.get(null); - } - - private static Object invoke(Object target, String method) throws Exception { - Method m = findMethod(target.getClass(), method); - if (m == null) { - throw new NoSuchMethodException(method + " on " + target.getClass().getName()); - } - m.setAccessible(true); - return m.invoke(target); - } - - private static Method findMethod(Class type, String name) { - Class c = type; - while (c != null) { - for (Method m : c.getDeclaredMethods()) { - if (m.getName().equals(name) && m.getParameterCount() == 0) { - return m; - } - } - c = c.getSuperclass(); - } - for (Method m : type.getMethods()) { - if (m.getName().equals(name) && m.getParameterCount() == 0) { - return m; - } - } - return null; - } - - private static Method findMethod4(Class type, String name) { - return findMethod(type, name, 4); - } - - private static Method findMethod(Class type, String name, int parameterCount) { - Class c = type; - while (c != null) { - for (Method m : c.getDeclaredMethods()) { - if (m.getName().equals(name) && m.getParameterCount() == parameterCount) { - return m; - } - } - c = c.getSuperclass(); - } - for (Method m : type.getMethods()) { - if (m.getName().equals(name) && m.getParameterCount() == parameterCount) { - return m; - } - } - return null; - } - - private static Object freshRandomSource(java.util.Random random) throws Exception { - Class randomSource = Class.forName("net.minecraft.util.RandomSource"); - Method create = randomSource.getMethod("create", long.class); - return create.invoke(null, random.nextLong()); - } - - static String poolName(String base, String poolKey) { - StructureKey key = StructureKey.parse(poolKey); - return base + "/pool/" + key.namespace() + "/" + key.path(); - } - - static String pieceName(String base, String templateLocation) { - StructureKey key = StructureKey.parse(templateLocation); - return base + "/piece/" + key.namespace() + "/" + key.path(); - } - - static Map pieceJson( - String pieceName, - List> connectors, - int nonAirBlocks - ) { - Map piece = new LinkedHashMap<>(); - piece.put("object", pieceName); - piece.put("connectors", connectors); - piece.put("rotatable", true); - if (nonAirBlocks == 0) { - piece.put("collidable", false); - } - return piece; - } - - static PoolMemberNormalization normalizePoolMember( - String sourcePoolKey, - String irisPoolName, - boolean startPoolMember, - int sourcePoolMembershipCount, - String sourceFallbackKey, - String templateLocation, - String irisPieceName, - int weight, - int nonAirBlocks, - List> connectors - ) { - if (!connectors.isEmpty() || startPoolMember) { - return new PoolMemberNormalization( - PoolMemberDisposition.PHYSICAL, - piecePoolEntry(irisPieceName, weight), - List.of()); - } - if (sourceFallbackKey != null - && !sourceFallbackKey.isBlank() - && !sourceFallbackKey.equals(sourcePoolKey)) { - return new PoolMemberNormalization( - PoolMemberDisposition.PHYSICAL, - piecePoolEntry(irisPieceName, weight), - List.of()); - } - String affectedResource = "jigsaw-pools/" + irisPoolName + ".json"; - if (nonAirBlocks == 0 && sourcePoolMembershipCount == 1) { - StructureLoss loss = StructureLoss.warning( - StructureCapability.IRIS_PLACEMENT, - "connectorless_all_air_member_normalized_empty", - "Source pool member " + templateLocation + " in " + sourcePoolKey - + " captured no non-air blocks and exposed no jigsaw connectors;" - + " its singleton membership was normalized to an explicit empty Iris pool entry" - + fallbackContext(sourcePoolKey, sourceFallbackKey) + ".") - .affecting(affectedResource); - return new PoolMemberNormalization( - PoolMemberDisposition.EMPTY, - emptyPoolEntry(weight), - List.of(loss)); - } - if (nonAirBlocks == 0) { - StructureLoss loss = StructureLoss.warning( - StructureCapability.IRIS_PLACEMENT, - "connectorless_all_air_mixed_member_omitted", - "Source pool member " + templateLocation + " in " + sourcePoolKey - + " captured no non-air blocks and exposed no jigsaw connectors;" - + " it was omitted from the mixed " + sourcePoolMembershipCount + "-member pool" - + fallbackContext(sourcePoolKey, sourceFallbackKey) - + ", changing source selection weights and RNG consumption.") - .affecting(affectedResource); - return new PoolMemberNormalization( - PoolMemberDisposition.OMITTED, - Map.of(), - List.of(loss)); - } - StructureLoss loss = StructureLoss.warning( - StructureCapability.BLOCKS, - "connectorless_non_air_member_omitted", - "Source pool member " + templateLocation + " in " + sourcePoolKey - + " captured " + nonAirBlocks + " non-air block(s) but exposed no jigsaw connectors;" - + " it was omitted because it cannot attach to the Iris assembly graph" - + fallbackContext(sourcePoolKey, sourceFallbackKey) - + ", changing source selection weights and RNG consumption while dropping those blocks.") - .affecting(affectedResource); - return new PoolMemberNormalization( - PoolMemberDisposition.OMITTED, - Map.of(), - List.of(loss)); - } - - private static String fallbackContext(String sourcePoolKey, String sourceFallbackKey) { - if (sourceFallbackKey == null || sourceFallbackKey.isBlank()) { - return " with no source fallback"; - } - if (sourceFallbackKey.equals(sourcePoolKey)) { - return " with its source self-fallback"; - } - return " before source fallback " + sourceFallbackKey; - } - - static Map emptyPoolEntry(int weight) { - Map entry = new LinkedHashMap<>(); - entry.put("empty", true); - entry.put("weight", weight); - return entry; - } - - static Map piecePoolEntry(String pieceName, int weight) { - Map entry = new LinkedHashMap<>(); - entry.put("piece", pieceName); - entry.put("weight", weight); - return entry; - } - - static Map structureJson( - String source, - String startPool, - int maxDepth, - int maxDistanceFromCenter - ) { - Map root = new LinkedHashMap<>(); - root.put("startPool", startPool); - root.put("maxDepth", Math.max(1, Math.min(30, maxDepth))); - int maxSizeChunks = Math.max(1, Math.min(32, (Math.max(1, maxDistanceFromCenter) + 15) / 16)); - root.put("maxSizeChunks", maxSizeChunks); - root.put("placeMode", "STRUCTURE_PIECE"); - root.put("branchFailurePolicy", IrisJigsawBranchFailurePolicy.TERMINATE_BRANCH.name()); - root.put("vanillaSource", source); - return root; - } - - private static StructureCapability unsupportedCapability(String elementType) { - if (elementType.endsWith("ListPoolElement")) { - return StructureCapability.LIST_ELEMENTS; - } - if (elementType.endsWith("FeaturePoolElement")) { - return StructureCapability.FEATURE_ELEMENTS; - } - return StructureCapability.BLOCKS; - } - - private static byte[] serialize(IrisObject object) throws IOException { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - object.write(output); - return output.toByteArray(); - } - - private static Result failed(String message, List losses) { - return new Result(false, message, 0, 0, losses); - } - - private static Result failed(String message, List losses, boolean retryableFailure) { - return new Result(false, message, 0, 0, losses, retryableFailure); - } - - private static void reportFailure(Throwable failure) { - IrisLogging.reportError(failure); - if (shouldPrintFullTrace(failure)) { - } - } - - /** - * True the first time a failure signature is seen. A bulk import repeats the same failure once - * per registered structure, so printing every trace buries the boot log in hundreds of copies - * of one problem; the per-structure "[fail] key: message" line still reports each occurrence. - */ - static boolean shouldPrintFullTrace(Throwable failure) { - if (failure == null) { - return false; - } - StackTraceElement[] trace = failure.getStackTrace(); - String signature = failure.getClass().getName() + '|' + failure.getMessage() - + '|' + (trace.length == 0 ? "" : trace[0].toString()); - return PRINTED_FAILURE_SIGNATURES.add(signature); - } - - static void resetFailureLogState() { - PRINTED_FAILURE_SIGNATURES.clear(); - } - - private static void reportWriteFailure(StructureWriteResult result) { - result.failure().ifPresent(VillageImporter::reportFailure); - } - - private static String writeResultNote(StructureWriteResult result) { - return result.status() == StructureWriteResult.Status.COMMITTED_CLEANUP_REQUIRED - ? " (committed; staging cleanup is required, see console)" : ""; - } - - private static String writeFailureMessage(String name, StructureWriteResult result) { - if (result.status() == StructureWriteResult.Status.ADD_ONLY_CONFLICT) { - return "Skipped (add-only): '" + name + "' already exists"; - } - if (!result.conflicts().isEmpty()) { - StructureWriteResult.Conflict conflict = result.conflicts().getFirst(); - return "Import conflict for '" + name + "': " + conflict.relativePath() + " is " - + conflict.reason().name().toLowerCase() + ". Existing authored files were preserved."; - } - String failure = result.failure().map(VillageImporter::failureDetail).orElse(result.status().name()); - return "Failed writing jigsaw import for '" + name + "': " + failure; - } - - private static String failureDetail(Throwable failure) { - String message = failure.getMessage(); - return message == null || message.isBlank() ? failure.getClass().getSimpleName() : message; - } - - record ConnectorMetadata(String finalState, int selectionPriority, int placementPriority) { - } - - record PoolElementResolution( - Object physicalElement, - String templateLocation, - int listLevels, - int omittedElements - ) { - } -} diff --git a/core/src/main/java/art/arcane/iris/core/tooling/CommandRun.java b/core/src/main/java/art/arcane/iris/core/tooling/CommandRun.java index 4139c3252..919b2bfc0 100644 --- a/core/src/main/java/art/arcane/iris/core/tooling/CommandRun.java +++ b/core/src/main/java/art/arcane/iris/core/tooling/CommandRun.java @@ -20,6 +20,7 @@ package art.arcane.iris.core.tooling; import com.volmit.resource.PlatformRegistries; import com.volmit.tooling.Argument; import com.volmit.tooling.CommandContext; +import com.volmit.tooling.PlatformStructures; import com.volmit.tooling.Sender; import com.volmit.tooling.ToolPack; import com.volmit.world.PackWorld; @@ -34,13 +35,16 @@ final class CommandRun implements CommandContext { private final ToolPack pack; private final Optional world; private final Optional platform; + private final Optional platformStructures; private final Map, Object> values = new IdentityHashMap<>(); - CommandRun(Sender sender, ToolPack pack, Optional world, Optional platform) { + CommandRun(Sender sender, ToolPack pack, Optional world, Optional platform, + Optional platformStructures) { this.sender = sender; this.pack = pack; this.world = world; this.platform = platform; + this.platformStructures = platformStructures; } void put(Argument argument, T value) { @@ -78,4 +82,9 @@ final class CommandRun implements CommandContext { public Optional platform() { return platform; } + + @Override + public Optional platformStructures() { + return platformStructures; + } } diff --git a/core/src/main/java/art/arcane/iris/core/tooling/IrisObjectCodec.java b/core/src/main/java/art/arcane/iris/core/tooling/IrisObjectCodec.java index fd78d7cd5..47f56357b 100644 --- a/core/src/main/java/art/arcane/iris/core/tooling/IrisObjectCodec.java +++ b/core/src/main/java/art/arcane/iris/core/tooling/IrisObjectCodec.java @@ -62,7 +62,7 @@ public final class IrisObjectCodec implements ObjectCodec { } catch (Throwable failure) { throw new IOException("Cannot read an " + EXTENSION + " object: " + failure.getMessage(), failure); } - return ObjectGeometry.of(object); + return ObjectGeometry.ofDeclared(object); } /** Iris keys an object's blocks by their offset from its center, so the local positions are the keys. */ diff --git a/core/src/main/java/art/arcane/iris/core/tooling/IrisToolPack.java b/core/src/main/java/art/arcane/iris/core/tooling/IrisToolPack.java index 921cbb796..4cbb36704 100644 --- a/core/src/main/java/art/arcane/iris/core/tooling/IrisToolPack.java +++ b/core/src/main/java/art/arcane/iris/core/tooling/IrisToolPack.java @@ -20,19 +20,23 @@ package art.arcane.iris.core.tooling; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.modules.IrisValidationContext; +import art.arcane.iris.core.modules.PackServices; import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.IrisServices; import com.volmit.ModuleLog; import com.volmit.config.PackSettings; import com.volmit.resource.PackResources; import com.volmit.tooling.ObjectCodec; import com.volmit.tooling.PackEdit; import com.volmit.tooling.ToolPack; +import com.volmit.tooling.world.ToolWorlds; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.List; import java.util.Objects; /** @@ -101,6 +105,17 @@ public final class IrisToolPack implements ToolPack { return log; } + @Override + public ToolWorlds worlds() { + ToolWorldsHost host = IrisServices.getOrNull(ToolWorldsHost.class); + return host == null ? UnsupportedToolWorlds.INSTANCE : host.worldsOf(data.getDataFolder().getName()); + } + + @Override + public List services(Class service) { + return PackServices.of(data).providers(service); + } + @Override public String toString() { return "pack " + data.getDataFolder().getName(); diff --git a/core/src/main/java/art/arcane/iris/core/tooling/StructureIndexOnStart.java b/core/src/main/java/art/arcane/iris/core/tooling/StructureIndexOnStart.java new file mode 100644 index 000000000..6305582ab --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/tooling/StructureIndexOnStart.java @@ -0,0 +1,60 @@ +/* + * 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.tooling; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.IrisModuleHost; +import art.arcane.iris.core.structure.authoring.StructureIndexService; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.spi.IrisServices; +import com.volmit.tooling.PlatformStructures; + +import java.io.File; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** Writes a pack's structure index once, when the first engine of the pack starts and the platform can list its structures. */ +public final class StructureIndexOnStart { + private static final Set GENERATED = ConcurrentHashMap.newKeySet(); + + private StructureIndexOnStart() { + } + + /** The index file; null when it was written before, or the platform does not list its structures yet, or writing failed. */ + public static File writeOnce(IrisData data) { + PlatformStructures platform = IrisServices.getOrNull(PlatformStructures.class); + if (data == null || platform == null) { + return null; + } + + File dataFolder = data.getDataFolder(); + String key = dataFolder == null ? null : dataFolder.getAbsolutePath(); + if (key == null || !GENERATED.add(key)) { + return null; + } + + try { + return StructureIndexService.write(new IrisToolPack(data, IrisModuleHost.hostLog()), platform); + } catch (Throwable e) { + GENERATED.remove(key); + IrisLogging.reportError(e); + return null; + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/tooling/ToolWorldsHost.java b/core/src/main/java/art/arcane/iris/core/tooling/ToolWorldsHost.java new file mode 100644 index 000000000..9f723f5dc --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/tooling/ToolWorldsHost.java @@ -0,0 +1,30 @@ +/* + * 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.tooling; + +import com.volmit.tooling.world.ToolWorlds; + +/** + * The tool worlds a platform adapter offers, bound with {@code IrisServices} by an adapter that has them. A platform + * that binds none answers {@link UnsupportedToolWorlds}. + */ +public interface ToolWorldsHost { + /** The tool worlds of the pack in the folder {@code packName}, which tools reach through {@code ToolPack.worlds()}. */ + ToolWorlds worldsOf(String packName); +} diff --git a/core/src/main/java/art/arcane/iris/core/tooling/ToolingCommands.java b/core/src/main/java/art/arcane/iris/core/tooling/ToolingCommands.java index a200cb784..4a040df63 100644 --- a/core/src/main/java/art/arcane/iris/core/tooling/ToolingCommands.java +++ b/core/src/main/java/art/arcane/iris/core/tooling/ToolingCommands.java @@ -20,10 +20,12 @@ package art.arcane.iris.core.tooling; import art.arcane.iris.core.modules.IrisValidationContext; import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.spi.IrisServices; import com.volmit.host.CommandRegistration; import com.volmit.resource.PlatformRegistries; import com.volmit.tooling.Argument; import com.volmit.tooling.Command; +import com.volmit.tooling.PlatformStructures; import com.volmit.world.PackWorld; import java.util.ArrayList; @@ -55,11 +57,18 @@ public final class ToolingCommands { private final PackDirectory packs; private final Executor workers; private final Supplier> platform; + private final Supplier> platformStructures; public ToolingCommands(PackDirectory packs, Executor workers, Supplier> platform) { + this(packs, workers, platform, Optional::empty); + } + + public ToolingCommands(PackDirectory packs, Executor workers, Supplier> platform, + Supplier> platformStructures) { this.packs = packs; this.workers = workers; this.platform = platform; + this.platformStructures = platformStructures; } /** The dispatcher of the bound platform, with daemon worker threads created as commands need them. */ @@ -70,7 +79,8 @@ public final class ToolingCommands { worker.setDaemon(true); return worker; }); - return new ToolingCommands(PackDirectory.ofBoundPlatform(), workers, IrisValidationContext::boundPlatformRegistries); + return new ToolingCommands(PackDirectory.ofBoundPlatform(), workers, IrisValidationContext::boundPlatformRegistries, + () -> Optional.ofNullable(IrisServices.getOrNull(PlatformStructures.class))); } /** Whether {@code word} opens the module branch of the {@code /iris} root, {@code module} or its alias {@code m}. */ @@ -223,7 +233,8 @@ public final class ToolingCommands { } private CommandRun contextOf(ToolingSender sender, ResolvedPack pack, LocatedCommand located) { - return new CommandRun(sender, pack.served().toolPack(located.root().module().log()), pack.world(), platform.get()); + return new CommandRun(sender, pack.served().toolPack(located.root().module().log()), pack.world(), platform.get(), + platformStructures.get()); } private static void parseArguments(LocatedCommand located, CommandRun context) throws CommandFailure { diff --git a/core/src/main/java/art/arcane/iris/core/tooling/UnsupportedToolWorlds.java b/core/src/main/java/art/arcane/iris/core/tooling/UnsupportedToolWorlds.java new file mode 100644 index 000000000..cb4114aed --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/tooling/UnsupportedToolWorlds.java @@ -0,0 +1,47 @@ +/* + * 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.tooling; + +import com.volmit.tooling.world.ToolWorld; +import com.volmit.tooling.world.ToolWorldSpec; +import com.volmit.tooling.world.ToolWorlds; + +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +/** The tool worlds of a platform that has none: nothing opens and nothing is found. */ +public final class UnsupportedToolWorlds implements ToolWorlds { + public static final String MESSAGE = "Tool worlds are not supported on this platform yet"; + public static final UnsupportedToolWorlds INSTANCE = new UnsupportedToolWorlds(); + + private UnsupportedToolWorlds() { + } + + @Override + public CompletableFuture open(ToolWorldSpec spec) { + Objects.requireNonNull(spec, "spec"); + return CompletableFuture.failedFuture(new UnsupportedOperationException(MESSAGE)); + } + + @Override + public Optional find(String name) { + return Optional.empty(); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/tooling/VolmitToolSender.java b/core/src/main/java/art/arcane/iris/core/tooling/VolmitToolSender.java new file mode 100644 index 000000000..0e294efa8 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/tooling/VolmitToolSender.java @@ -0,0 +1,68 @@ +/* + * 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.tooling; + +import art.arcane.iris.util.common.format.C; +import art.arcane.iris.util.common.plugin.VolmitSender; +import com.volmit.tooling.Sender; +import com.volmit.tooling.world.ToolPlayer; + +import java.util.Optional; + +/** + * An Iris {@link VolmitSender}, such as the console, as a tool {@link Sender}, for core code that runs tools without a + * command. It is never a player, because only a command's sender knows its tool player. + */ +public final class VolmitToolSender implements Sender { + private final VolmitSender messages; + + public VolmitToolSender(VolmitSender messages) { + this.messages = messages; + } + + @Override + public String name() { + return messages.getS().getName(); + } + + @Override + public void info(String message) { + messages.sendMessage(C.WHITE + message); + } + + @Override + public void success(String message) { + messages.sendMessage(C.GREEN + message); + } + + @Override + public void error(String message) { + messages.sendMessage(C.RED + message); + } + + @Override + public Optional extension(Class type) { + return type.isInstance(messages.getS()) ? Optional.of(type.cast(messages.getS())) : Optional.empty(); + } + + @Override + public Optional player() { + return Optional.empty(); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/IrisEngine.java b/core/src/main/java/art/arcane/iris/engine/IrisEngine.java index 274d20e1b..ab83c43e1 100644 --- a/core/src/main/java/art/arcane/iris/engine/IrisEngine.java +++ b/core/src/main/java/art/arcane/iris/engine/IrisEngine.java @@ -46,7 +46,7 @@ import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.IrisServices; import art.arcane.iris.core.nms.container.BlockPos; import art.arcane.iris.core.nms.container.Pair; -import art.arcane.iris.core.structure.StructureIndexService; +import art.arcane.iris.core.tooling.StructureIndexOnStart; import art.arcane.iris.engine.mantle.EngineMantle; import art.arcane.iris.util.common.data.B; import art.arcane.iris.util.common.plugin.VolmitSender; @@ -225,7 +225,7 @@ public class IrisEngine implements Engine { IrisLogging.debug("[IrisEngine timing] loadPrefetch=" + (M.ms() - _t0) + "ms"); logStudioInitializationPhase("load_prefetch", phaseStartedAt, false); try { - StructureIndexService.writeOnce(getData()); + StructureIndexOnStart.writeOnce(getData()); } catch (Throwable e) { IrisLogging.reportError(e); } diff --git a/core/src/main/java/art/arcane/iris/engine/framework/StructurePlacementScope.java b/core/src/main/java/art/arcane/iris/engine/framework/StructurePlacementScope.java deleted file mode 100644 index bc99627de..000000000 --- a/core/src/main/java/art/arcane/iris/engine/framework/StructurePlacementScope.java +++ /dev/null @@ -1,115 +0,0 @@ -package art.arcane.iris.engine.framework; - -import art.arcane.iris.builtin.structure.StructurePlacement; -import art.arcane.iris.builtin.structure.StructurePlacementSettings; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.engine.IrisComplex; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.volmlib.util.collection.KList; - -import java.util.Collections; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Objects; -import java.util.Set; - -/** - * The structure placements that apply at a chunk: its biome's, its cave biome's cave-anchored ones, its region's and - * the dimension's. Each world keeps which of those levels declare placements at all, so chunks skip the biome and - * region lookups a pack never needs. - */ -public final class StructurePlacementScope { - private StructurePlacementScope() { - } - - /** The placements {@code owner} declares in its {@code "structures"} settings; empty for none. */ - public static List placementsOf(IrisRegistrant owner) { - if (owner == null) { - return List.of(); - } - return owner.getModuleSettings().find(StructurePlacementSettings.class) - .map(StructurePlacementSettings::placements) - .orElse(List.of()); - } - - public static KList placementsAt(Engine engine, int chunkX, int chunkZ) { - Engine activeEngine = Objects.requireNonNull(engine, "Structure placement scope requires an engine"); - IrisComplex complex = activeEngine.getComplex(); - int blockX = (chunkX << 4) + 8; - int blockZ = (chunkZ << 4) + 8; - KList placements = new KList<>(); - Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); - ScopeIndex index = scopeIndex(activeEngine); - if (complex != null) { - if (index.biome()) { - IrisBiome biome = complex.getTrueBiomeStream().get(blockX, blockZ); - addUnique(placements, seen, placementsOf(biome)); - } - if (index.caveBiome()) { - IrisBiome caveBiome = complex.getCaveBiomeStream().get(blockX, blockZ); - addCaveUnique(placements, seen, placementsOf(caveBiome)); - } - if (index.region()) { - IrisRegion region = complex.getRegionStream().get(blockX, blockZ); - addUnique(placements, seen, placementsOf(region)); - } - } - if (index.dimension()) { - addUnique(placements, seen, placementsOf(activeEngine.getDimension())); - } - return placements; - } - - private static ScopeIndex scopeIndex(Engine engine) { - return engine.getGeneration().state(ScopeIndex.class, StructurePlacementScope::buildScopeIndex); - } - - private static ScopeIndex buildScopeIndex(Engine engine) { - boolean biome = false; - boolean caveBiome = false; - KList allBiomes = engine.getAllBiomes(); - if (allBiomes == null) { - biome = true; - caveBiome = true; - } else { - for (IrisBiome candidate : allBiomes) { - List structures = placementsOf(candidate); - if (structures.isEmpty()) { - continue; - } - biome = true; - caveBiome |= structures.stream().anyMatch(placement -> placement.resolvedAnchor().isCave()); - } - } - boolean region = false; - if (engine.getDimension() != null) { - KList allRegions = engine.getDimension().getAllRegions(engine); - region = allRegions == null - || allRegions.stream().anyMatch(candidate -> !placementsOf(candidate).isEmpty()); - } - boolean dimension = !placementsOf(engine.getDimension()).isEmpty(); - return new ScopeIndex(biome, caveBiome, region, dimension); - } - - private static void addUnique(KList destination, Set seen, - List source) { - for (StructurePlacement placement : source) { - if (placement != null && seen.add(placement)) { - destination.add(placement); - } - } - } - - private static void addCaveUnique(KList destination, Set seen, - List source) { - for (StructurePlacement placement : source) { - if (placement != null && placement.resolvedAnchor().isCave() && seen.add(placement)) { - destination.add(placement); - } - } - } - - private record ScopeIndex(boolean biome, boolean caveBiome, boolean region, boolean dimension) { - } -} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeStructureFitting.java b/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeStructureFitting.java index 27d660cb9..92c40d0f7 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeStructureFitting.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/nativefit/NativeStructureFitting.java @@ -2,6 +2,7 @@ package art.arcane.iris.engine.framework.nativefit; import art.arcane.iris.core.modules.ModuleStructureFitting; import art.arcane.iris.engine.framework.Engine; +import com.volmit.IrisModule; /** * The pack's modules fitting a chunk's structure starts into the terrain, around the platform placing their pieces: @@ -17,11 +18,11 @@ public interface NativeStructureFitting { } /** - * Iris's built-in modules outside any world, for starts whose fit their memo records and whose fit uses no palette; + * Iris's own modules and {@code modules} outside any world, for starts whose fit their memo records and whose fit uses no palette; * a fit that needs the world or the pack's resources fails. For tools and tests that drive the platform side alone. */ - static NativeStructureFitting builtInModules() { - return ModuleStructureFitting.builtInModules(); + static NativeStructureFitting ofModules(IrisModule... modules) { + return ModuleStructureFitting.ofModules(modules); } /** One chunk's fit, between its starts' placements. */ 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 deleted file mode 100644 index 80bf6b758..000000000 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureValidator.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * 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.Problem; -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; -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}), 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 { - 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); - 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. - */ - 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/core/src/main/java/art/arcane/iris/engine/mantle/MantleWriter.java b/core/src/main/java/art/arcane/iris/engine/mantle/MantleWriter.java index 21d3b4aac..4d595a736 100644 --- a/core/src/main/java/art/arcane/iris/engine/mantle/MantleWriter.java +++ b/core/src/main/java/art/arcane/iris/engine/mantle/MantleWriter.java @@ -43,6 +43,8 @@ import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.matter.Matter; import art.arcane.volmlib.util.matter.MatterCavern; import art.arcane.volmlib.util.matter.MatterSlice; +import art.arcane.volmlib.util.matter.MatterStructurePOI; +import art.arcane.iris.engine.framework.TreeBlockMaterial; import art.arcane.iris.util.project.noise.CNG; import art.arcane.iris.util.common.scheduling.J; import lombok.AccessLevel; @@ -428,6 +430,14 @@ public class MantleWriter implements IObjectPlacer, AutoCloseable { matter.getSlice(type).set(x & 15, y & 15, z & 15, null); } + /** Takes back the placement marker, tree material, block entity and point of interest kept beside the block. */ + public void clearAttached(int x, int y, int z) { + clearData(x, y, z, String.class); + clearData(x, y, z, TreeBlockMaterial.class); + clearData(x, y, z, TileWrapper.class); + clearData(x, y, z, MatterStructurePOI.class); + } + private static void clearDeferredPlacement(Matter matter, int x, int y, int z) { if (matter.hasSlice(Identifier.class)) { matter.getSlice(Identifier.class).set(x & 15, y & 15, z & 15, null); diff --git a/core/src/main/java/art/arcane/iris/engine/object/placement/IObjectPlacer.java b/core/src/main/java/art/arcane/iris/engine/object/placement/IObjectPlacer.java index 07eefa63e..feffe851d 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/placement/IObjectPlacer.java +++ b/core/src/main/java/art/arcane/iris/engine/object/placement/IObjectPlacer.java @@ -58,4 +58,12 @@ public interface IObjectPlacer { @Nullable T getData(int xx, int yy, int zz, Class t); Engine getEngine(); + + default void clearBlock(int x, int y, int z) { + throw new UnsupportedOperationException("This placer cannot take blocks back"); + } + + default void clearAttached(int x, int y, int z) { + throw new UnsupportedOperationException("This placer cannot take what is kept beside a block back"); + } } diff --git a/core/src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java b/core/src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java index 4316224ee..29cf576c0 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java +++ b/core/src/main/java/art/arcane/iris/engine/object/prefab/IrisObject.java @@ -22,7 +22,9 @@ import com.volmit.object.PlaceableObject; import com.volmit.object.ScaleMethod; import art.arcane.iris.engine.object.placement.IObjectPlacer; import art.arcane.iris.engine.object.value.IrisPosition; +import art.arcane.iris.core.modules.BlockEntities; import art.arcane.iris.core.modules.ObjectGeometry; +import art.arcane.iris.core.modules.PlatformBlockStates; import art.arcane.iris.core.loader.IrisRegistrant; import art.arcane.volmlib.util.cache.AtomicCache; import art.arcane.iris.platform.bukkit.BukkitBlockState; @@ -36,6 +38,9 @@ import art.arcane.volmlib.util.math.IrisVector; import art.arcane.volmlib.util.math.Vector3i; import art.arcane.iris.util.common.plugin.VolmitSender; import art.arcane.volmlib.util.collection.KList; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; import com.volmit.object.GeneratedObject; import lombok.EqualsAndHashCode; import lombok.Getter; @@ -49,8 +54,11 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; @@ -288,6 +296,124 @@ public class IrisObject extends IrisRegistrant implements PlaceableObject { return written; } + /** + * Stores {@code state} at the unsigned position, as the platform builds it from its key. + */ + public void setUnsignedState(int x, int y, int z, BlockState state) { + setUnsigned(x, y, z, B.getState(state.key())); + } + + /** Stores {@code data} as the block entity at the unsigned position. */ + public void setUnsignedBlockEntity(int x, int y, int z, BlockEntityData data) { + setUnsignedTile(x, y, z, BlockEntities.tileOf(data)); + } + + /** + * The stored blocks and block entities as IrisApi values at their unsigned positions, in storage order, for tools that + * edit an object's contents without the platform's block types. A block Iris cannot read is cave air, as Iris places + * it. Hand the edited values back through {@link #fromApiContents}. + */ + public ApiContents apiContents() { + readLock.lock(); + try { + PlatformBlockStates conversion = new PlatformBlockStates(B::getState); + Map apiBlocks = new LinkedHashMap<>(); + Set customBlocks = new LinkedHashSet<>(); + Set blocksNeedingEntity = new LinkedHashSet<>(); + for (Map.Entry entry : blocks) { + BlockPosition position = unsignedPositionOf(entry.getKey()); + PlatformBlockState stored = entry.getValue(); + apiBlocks.put(position, stored == null ? ApiContents.UNREADABLE_BLOCK : conversion.toApi(stored)); + if (stored != null && stored.isCustom()) { + customBlocks.add(position); + } + if (stored != null && stored.hasTileEntity()) { + blocksNeedingEntity.add(position); + } + } + Map apiEntities = new LinkedHashMap<>(); + for (Map.Entry entry : states) { + apiEntities.put(unsignedPositionOf(entry.getKey()), BlockEntities.of(entry.getValue())); + } + return new ApiContents(conversion, apiBlocks, apiEntities, customBlocks, blocksNeedingEntity); + } finally { + readLock.unlock(); + } + } + + /** + * An object of the given size holding {@code contents}, which came from {@link #apiContents} of some object and may + * have been edited since. A block that was read from the platform is written back as that same platform state. + */ + public static IrisObject fromApiContents(int w, int h, int d, ApiContents contents) { + IrisObject object = new IrisObject(w, h, d); + contents.blocks().forEach((position, state) -> + object.setUnsigned(position.x(), position.y(), position.z(), contents.platformStateOf(state))); + contents.blockEntities().forEach((position, entity) -> + object.setUnsignedBlockEntity(position.x(), position.y(), position.z(), entity)); + return object; + } + + private BlockPosition unsignedPositionOf(IrisBlockVector signed) { + return new BlockPosition( + signed.getBlockX() + center.getBlockX(), + signed.getBlockY() + center.getBlockY(), + signed.getBlockZ() + center.getBlockZ()); + } + + /** + * The contents of an object as IrisApi values, at unsigned positions. + * + * @param blocks the stored blocks, which a tool may change; an edited map goes back through {@link #with} + * @param blockEntities the stored block entities + * @param customBlocks where the stored block is a custom-content block that only the platform can place + * @param blocksNeedingEntity where the stored block is of a kind that carries a block entity + */ + public static final class ApiContents { + private static final BlockState UNREADABLE_BLOCK = BlockState.parse("minecraft:cave_air"); + + private final PlatformBlockStates conversion; + private final Map blocks; + private final Map blockEntities; + private final Set customBlocks; + private final Set blocksNeedingEntity; + + private ApiContents(PlatformBlockStates conversion, Map blocks, + Map blockEntities, Set customBlocks, + Set blocksNeedingEntity) { + this.conversion = conversion; + this.blocks = blocks; + this.blockEntities = blockEntities; + this.customBlocks = customBlocks; + this.blocksNeedingEntity = blocksNeedingEntity; + } + + public Map blocks() { + return blocks; + } + + public Map blockEntities() { + return blockEntities; + } + + public Set customBlocks() { + return customBlocks; + } + + public Set blocksNeedingEntity() { + return blocksNeedingEntity; + } + + /** These contents with other blocks and block entities, such as a resized copy; the platform states stay the same ones. */ + public ApiContents with(Map blocks, Map blockEntities) { + return new ApiContents(conversion, blocks, blockEntities, customBlocks, blocksNeedingEntity); + } + + private PlatformBlockState platformStateOf(BlockState state) { + return conversion.toPlatform(state); + } + } + /** This object as IrisApi geometry, read once until its blocks change. */ public GeneratedObject getGeometry() { return geometry.aquireOrThrow(() -> ObjectGeometry.of(this)); diff --git a/core/src/main/java/art/arcane/iris/engine/platform/BukkitChunkGenerator.java b/core/src/main/java/art/arcane/iris/engine/platform/BukkitChunkGenerator.java index 3c9509f81..9700a0119 100644 --- a/core/src/main/java/art/arcane/iris/engine/platform/BukkitChunkGenerator.java +++ b/core/src/main/java/art/arcane/iris/engine/platform/BukkitChunkGenerator.java @@ -28,6 +28,7 @@ import java.util.concurrent.Semaphore; import art.arcane.iris.spi.IrisServices; import art.arcane.iris.platform.bukkit.BukkitPlatform; import art.arcane.iris.core.IrisSettings; +import art.arcane.iris.core.IrisWorldStorage; import art.arcane.iris.core.IrisWorlds; import art.arcane.iris.core.gui.PregeneratorJob; import art.arcane.iris.core.loader.IrisData; @@ -35,8 +36,7 @@ import art.arcane.iris.core.nms.INMS; import art.arcane.iris.core.project.PackHotloadFolder; import art.arcane.iris.core.project.PackHotloadGuard; import art.arcane.iris.core.runtime.ObjectStudioActivation; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioActivation; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioSession; +import art.arcane.iris.core.runtime.StudioPainterSlots; import art.arcane.iris.core.service.StudioSVC; import art.arcane.iris.core.tools.IrisToolbelt; import art.arcane.iris.engine.IrisEngine; @@ -53,7 +53,7 @@ import art.arcane.iris.engine.object.world.dimension.IrisDimensionRuntimeContrac import art.arcane.iris.engine.object.world.IrisWorld; import art.arcane.iris.engine.object.runtime.StudioMode; import art.arcane.iris.engine.platform.studio.StudioGenerator; -import art.arcane.iris.engine.platform.studio.generators.JigsawStudioGenerator; +import art.arcane.iris.engine.platform.studio.generators.PainterStudioGenerator; import art.arcane.iris.platform.bukkit.BukkitWorldBinding; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisPlatforms; @@ -92,6 +92,7 @@ import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Objects; +import java.util.Optional; import java.util.Random; import java.util.UUID; import java.util.concurrent.TimeUnit; @@ -129,8 +130,8 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun private volatile Engine engine; private volatile Looper hotloader; private volatile StudioMode lastMode; - private volatile UUID lastJigsawStudioRequestId; - private volatile boolean jigsawStudioActive; + private volatile StudioPainterSlots.Slot lastPainterSlot; + private volatile boolean paintedStudioActive; private volatile DummyBiomeProvider dummyBiomeProvider; private volatile Throwable initializationFailure; private volatile IrisDimension validatedDimension; @@ -158,7 +159,7 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun } }); this.initializationFailure = null; - this.jigsawStudioActive = false; + this.paintedStudioActive = false; this.validatedDimension = null; this.validatedWorldContract = null; this.closing = false; @@ -343,23 +344,14 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun private void setupEngine() { lastMode = StudioMode.NORMAL; - lastJigsawStudioRequestId = null; + lastPainterSlot = null; EngineTarget engineTarget = getTarget(); - String packKey = engineTarget.getDimension().getLoadKey(); - JigsawStudioActivation.Request request = studio - ? JigsawStudioActivation.getGeneratorRequest(packKey) - : null; - JigsawStudioSession session = request == null - ? null - : JigsawStudioActivation.getGeneratorSession(packKey); - jigsawStudioActive = request != null - && session != null - && session.sessionId().equals(request.requestId()); + paintedStudioActive = paintedStudioSlot().isPresent(); IrisEngine createdEngine = new IrisEngine( engineTarget, - selectInitializationMode(studio, jigsawStudioActive)); + selectInitializationMode(studio, paintedStudioActive)); createdEngine.setNativeStructureVolumeQueriesEnabled(shouldGenerateNativeStructures( - jigsawStudioActive, + paintedStudioActive, studioEntryBootstrapActive.get(), initializationFailure != null)); engine = createdEngine; @@ -367,11 +359,11 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun targetCache.reset(); } - static IrisEngine.InitializationMode selectInitializationMode(boolean studio, boolean jigsawStudioActive) { + static IrisEngine.InitializationMode selectInitializationMode(boolean studio, boolean paintedStudioActive) { if (!studio) { return IrisEngine.InitializationMode.RUNTIME; } - return jigsawStudioActive + return paintedStudioActive ? IrisEngine.InitializationMode.JIGSAW_STUDIO : IrisEngine.InitializationMode.STUDIO; } @@ -435,7 +427,7 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun getWorld().setRawWorldSeed(world.getSeed()); setupEngine(); setup.set(true); - this.hotloader = shouldRunStudioHotload(studio, closing, jigsawStudioActive) ? new Looper() { + this.hotloader = shouldRunStudioHotload(studio, closing, paintedStudioActive) ? new Looper() { @Override protected long loop() { Engine activeEngine = engine; @@ -587,7 +579,7 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun Engine activeEngine = engine; if (activeEngine instanceof IrisEngine irisEngine) { irisEngine.setNativeStructureVolumeQueriesEnabled(shouldGenerateNativeStructures( - jigsawStudioActive, + paintedStudioActive, false, initializationFailure != null)); } @@ -598,13 +590,13 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun return studioEntryBootstrapActive.get(); } - public boolean isJigsawStudioActive() { - return jigsawStudioActive; + public boolean isPaintedStudioActive() { + return paintedStudioActive; } @Override public void hotload() { - if (!shouldRunStudioHotload(isStudio(), closing, jigsawStudioActive)) { + if (!shouldRunStudioHotload(isStudio(), closing, paintedStudioActive)) { return; } @@ -612,7 +604,7 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun } private void hotloadFromWatcher() { - if (!shouldRunStudioHotload(isStudio(), closing, jigsawStudioActive)) { + if (!shouldRunStudioHotload(isStudio(), closing, paintedStudioActive)) { return; } withExclusiveControlFuture(() -> getEngine().hotload(), 30L, TimeUnit.SECONDS).join(); @@ -627,8 +619,8 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun return withExclusiveControlFuture(activeEngine::hotloadComplex, acquisitionTimeout, unit); } - static boolean shouldRunStudioHotload(boolean studio, boolean closing, boolean jigsawStudioActive) { - return studio && !closing && !jigsawStudioActive; + static boolean shouldRunStudioHotload(boolean studio, boolean closing, boolean paintedStudioActive) { + return studio && !closing && !paintedStudioActive; } public GenerationStagePermit acquireGenerationStage(String operation) { @@ -956,24 +948,8 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun } private void computeStudioGenerator() { - String packKey = getEngine().getDimension().getLoadKey(); - JigsawStudioActivation.Request jigsawRequest = studio - ? JigsawStudioActivation.getGeneratorRequest(packKey) - : null; - if (jigsawRequest != null) { - JigsawStudioSession session = JigsawStudioActivation.getGeneratorSession(packKey); - if (session != null && session.sessionId().equals(jigsawRequest.requestId())) { - if (!jigsawRequest.requestId().equals(lastJigsawStudioRequestId)) { - setStudioGenerator(new JigsawStudioGenerator(getEngine(), jigsawRequest, session)); - lastJigsawStudioRequestId = jigsawRequest.requestId(); - lastMode = null; - } - return; - } - } - if (lastJigsawStudioRequestId != null) { - lastJigsawStudioRequestId = null; - lastMode = null; + if (installPaintedStudioGenerator()) { + return; } // Gson nulls unknown enum names, so a pack carrying a removed or typo'd studioMode must not NPE the generator. // Pack-declared studio modes are studio-only: a shipped pack that forgot to reset @@ -990,6 +966,31 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun } } + private Optional paintedStudioSlot() { + if (!studio || world.identity() == null) { + return Optional.empty(); + } + return StudioPainterSlots.slotOf(IrisWorldStorage.logicalName(WorldIdentity.parse(world.identity()))); + } + + /** Makes the generator the tool's painter while a slot is installed for this world; false when none is. */ + private boolean installPaintedStudioGenerator() { + Optional slot = paintedStudioSlot(); + if (slot.isEmpty()) { + if (lastPainterSlot != null) { + lastPainterSlot = null; + lastMode = null; + } + return false; + } + if (slot.get() != lastPainterSlot) { + setStudioGenerator(new PainterStudioGenerator(slot.get())); + lastPainterSlot = slot.get(); + lastMode = null; + } + return true; + } + @NotNull @Override public List getDefaultPopulators(@NotNull World world) { @@ -1014,17 +1015,17 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun @Override public boolean shouldGenerateStructures() { return shouldGenerateNativeStructures( - jigsawStudioActive, + paintedStudioActive, studioEntryBootstrapActive.get(), initializationFailure != null); } static boolean shouldGenerateNativeStructures( - boolean jigsawStudioActive, + boolean paintedStudioActive, boolean studioEntryBootstrapActive, boolean initializationFailed ) { - return !jigsawStudioActive && !studioEntryBootstrapActive && !initializationFailed; + return !paintedStudioActive && !studioEntryBootstrapActive && !initializationFailed; } @Override diff --git a/core/src/main/java/art/arcane/iris/engine/platform/studio/TerrainChunkCanvas.java b/core/src/main/java/art/arcane/iris/engine/platform/studio/TerrainChunkCanvas.java new file mode 100644 index 000000000..524d62b65 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/platform/studio/TerrainChunkCanvas.java @@ -0,0 +1,102 @@ +/* + * 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.platform.studio; + +import art.arcane.iris.core.modules.PlatformBlockStates; +import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedBlockEntity; +import art.arcane.iris.engine.data.chunk.TerrainChunk; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import com.volmit.block.BlockState; +import com.volmit.object.BlockEntityData; +import com.volmit.tooling.world.ChunkCanvas; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.function.Function; + +/** + * The canvas of one paint of a tool world: block states go into a {@link TerrainChunk}, and the block entities the + * painter asks for are kept to be applied once the chunk is live. One canvas serves one paint on one thread. + */ +public final class TerrainChunkCanvas implements ChunkCanvas { + private static final int CHUNK_SIZE = 16; + + private final TerrainChunk chunk; + private final PlatformBlockStates states; + private final List blockEntities = new ArrayList<>(); + + /** {@code platformStates} turns a block state key into the platform's state; it fails for a key the platform lacks. */ + public TerrainChunkCanvas(TerrainChunk chunk, Function platformStates) { + this.chunk = Objects.requireNonNull(chunk, "chunk"); + this.states = new PlatformBlockStates(Objects.requireNonNull(platformStates, "platformStates")); + } + + /** A canvas over {@code chunk} that resolves block states through the platform Iris is bound to. */ + public static TerrainChunkCanvas onPlatform(TerrainChunk chunk) { + return new TerrainChunkCanvas(chunk, TerrainChunkCanvas::platformState); + } + + private static PlatformBlockState platformState(String key) { + PlatformBlockState state = B.getStateOrNull(key, false); + if (state == null) { + throw new IllegalArgumentException("The platform has no block state " + key); + } + return state; + } + + @Override + public int minY() { + return chunk.getMinHeight(); + } + + @Override + public int maxY() { + return chunk.getMaxHeight(); + } + + @Override + public void set(int x, int y, int z, BlockState state) { + requireInside(x, y, z); + chunk.setBlock(x, y, z, states.toPlatform(Objects.requireNonNull(state, "state"))); + blockEntities.removeIf(painted -> painted.x() == x && painted.y() == y && painted.z() == z); + } + + @Override + public void set(int x, int y, int z, BlockState state, BlockEntityData data) { + Objects.requireNonNull(data, "data"); + set(x, y, z, state); + blockEntities.add(new PaintedBlockEntity(x, y, z, data)); + } + + /** The block entities painted so far, one for each position that still holds the block it was painted with. */ + public List blockEntities() { + return List.copyOf(blockEntities); + } + + private void requireInside(int x, int y, int z) { + if (x < 0 || x >= CHUNK_SIZE || z < 0 || z >= CHUNK_SIZE) { + throw new IllegalArgumentException("Chunk-local x and z are 0 to 15: " + x + ", " + z); + } + if (y < minY() || y >= maxY()) { + throw new IllegalArgumentException("Y " + y + " is outside the world, " + minY() + " up to " + maxY()); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/platform/studio/generators/PainterStudioGenerator.java b/core/src/main/java/art/arcane/iris/engine/platform/studio/generators/PainterStudioGenerator.java new file mode 100644 index 000000000..324632e8b --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/platform/studio/generators/PainterStudioGenerator.java @@ -0,0 +1,76 @@ +/* + * 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.platform.studio.generators; + +import art.arcane.iris.core.runtime.StudioPainterSlots; +import art.arcane.iris.engine.data.chunk.TerrainChunk; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.GenerationSessionLease; +import art.arcane.iris.engine.framework.WrongEngineBroException; +import art.arcane.iris.engine.platform.studio.StudioGenerator; +import art.arcane.iris.engine.platform.studio.TerrainChunkCanvas; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.util.project.context.IrisContext; + +import java.util.Objects; +import java.util.function.Function; + +/** Generates the chunks of a tool world: whatever the world's {@link StudioPainterSlots.Slot} paints, and nothing else. */ +public final class PainterStudioGenerator implements StudioGenerator { + private static final String LEASE_OPERATION = "bukkit_tool_world_paint"; + + private final StudioPainterSlots.Slot slot; + private final Function canvases; + + public PainterStudioGenerator(StudioPainterSlots.Slot slot) { + this(slot, TerrainChunkCanvas::onPlatform); + } + + PainterStudioGenerator(StudioPainterSlots.Slot slot, Function canvases) { + this.slot = Objects.requireNonNull(slot, "slot"); + this.canvases = Objects.requireNonNull(canvases, "canvases"); + } + + /** The slot this generator paints for; a world whose slot changed needs a new generator. */ + public StudioPainterSlots.Slot slot() { + return slot; + } + + @Override + public void generateChunk(Engine engine, TerrainChunk terrainChunk, int chunkX, int chunkZ) + throws WrongEngineBroException { + try (GenerationSessionLease lease = engine.acquireGenerationLease(LEASE_OPERATION); + IrisContext.Scope ignored = IrisContext.open(engine, lease.sessionId(), null)) { + paint(terrainChunk, chunkX, chunkZ); + } + } + + /** Paints the chunk into {@code terrainChunk}; a painter that throws leaves the chunk as far as it got. */ + void paint(TerrainChunk terrainChunk, int chunkX, int chunkZ) { + TerrainChunkCanvas canvas = canvases.apply(terrainChunk); + try { + slot.painter().paint(chunkX, chunkZ, canvas); + } catch (RuntimeException failure) { + IrisLogging.reportError("A tool world painter failed at chunk " + chunkX + "," + chunkZ + ".", failure); + } + if (!canvas.blockEntities().isEmpty()) { + slot.blockEntities().accept(new StudioPainterSlots.PaintedChunk(chunkX, chunkZ, canvas.blockEntities())); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/IrisStructureHandler.java b/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/IrisStructureHandler.java deleted file mode 100644 index faac8e8e7..000000000 --- a/core/src/main/java/art/arcane/iris/util/common/director/specialhandlers/IrisStructureHandler.java +++ /dev/null @@ -1,58 +0,0 @@ -package art.arcane.iris.util.common.director.specialhandlers; - -import art.arcane.iris.engine.framework.structure.StructureResources; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.modules.PackModulesException; -import art.arcane.iris.core.pack.PackDirectoryResolver; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.util.common.director.DirectorParameterHandler; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.director.exceptions.DirectorParsingException; - -import java.io.File; -import java.util.LinkedHashSet; -import java.util.Set; - -public final class IrisStructureHandler implements DirectorParameterHandler { - @Override - public KList getPossibilities() { - Set keys = new LinkedHashSet<>(); - IrisData activeData = data(); - if (activeData != null) { - addStructureKeys(keys, activeData); - } - for (File pack : PackDirectoryResolver.listVisiblePackDirectories( - IrisPlatforms.get().packsFolder())) { - addStructureKeys(keys, IrisData.get(pack)); - } - return new KList<>(keys); - } - - @Override - public String toString(String value) { - return value == null ? "" : value; - } - - @Override - public String parse(String input, boolean force) throws DirectorParsingException { - for (String option : getPossibilities(input)) { - if (option.equalsIgnoreCase(input)) { - return option; - } - } - throw new DirectorParsingException("Unable to find Iris structure \"" + input + "\""); - } - - @Override - public boolean supports(Class type) { - return type == String.class; - } - - /** A pack whose modules fail to load has no structures to offer; its failure was reported when it loaded. */ - private static void addStructureKeys(Set keys, IrisData data) { - try { - keys.addAll(StructureResources.structureKeys(data.getPackResources())); - } catch (PackModulesException ignored) { - } - } -} diff --git a/core/src/main/resources/languages/de_DE.json b/core/src/main/resources/languages/de_DE.json index 1eb0c4dca..7d4100f6c 100644 --- a/core/src/main/resources/languages/de_DE.json +++ b/core/src/main/resources/languages/de_DE.json @@ -1008,50 +1008,6 @@ "§cWenn du die Risiken verstanden und eine Sicherungskopie erstellt hast:", "§c/iris developer update-world {world} {pack} confirm=true" ], - "iris.bukkit.runtime.bulkstructureimporter.importing_vanilla_datapack_structures_mode_includenonjigsaw": "§aImportiere §f{total}§a Strukturen aus vanilla und Datapacks (mode={mode}, includeNonJigsaw={includeNonJigsaw})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key": "§c[Fehler] {keyString}: ungültiger Schlüssel", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.skip_no_single_template_nbt_vanilla_builds_this_code_from_separate_piece": "§e[übersprungen] {keyString}: kein NBT mit einer einzelnen Vorlage – vanilla erzeugt diese Struktur im Code oder aus getrennten Teilvorlagen, die im Vorlagendurchlauf importiert werden; es gibt keine einzelne Struktur zu importieren.", - "iris.bukkit.runtime.bulkstructureimporter.fail": "§c[Fehler] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_2": "§c[Fehler] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_3": "§c[Fehler] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.bulk_import_complete_imported_skipped_failed_total": "§aMassenimport abgeschlossen: §f{imported}§a importiert, §f{skipped}§a übersprungen, §f{failed}§a fehlgeschlagen (§f{total}§a insgesamt).", - "iris.bukkit.runtime.bulkstructureimporter.building_single_template_structures_from_imported_pieces_one_variant_placed_per_generation": "§aErstelle Strukturen mit einzelner Vorlage aus importierten Teilen (pro Generierung wird eine Variante platziert)...", - "iris.bukkit.runtime.bulkstructureimporter.group_variants": "§7[Gruppe] {value} -> {value2} ({blocks} Varianten)", - "iris.bukkit.runtime.bulkstructureimporter.skip": "§e[übersprungen] {value}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_4": "§c[Fehler] {value}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.single_template_structures_built_skipped_failed": "§aStrukturen mit einzelner Vorlage: §f{imported}§a erstellt, §f{skipped}§a übersprungen, §f{failed}§a fehlgeschlagen.", - "iris.bukkit.runtime.bulkstructureimporter.failed_enumerate_structure_templates_via_server_resourcemanager": "§cStrukturvorlagen konnten nicht über den ResourceManager des Servers ermittelt werden: {e}", - "iris.bukkit.runtime.bulkstructureimporter.no_structure_templates_were_found_under_structure_resource_path": "§eUnter dem Ressourcenpfad 'structure' wurden keine Strukturvorlagen gefunden.", - "iris.bukkit.runtime.bulkstructureimporter.importing_structure_templates_mode": "§aImportiere §f{total}§a Strukturvorlagen (mode={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_2": "§c[Fehler] {keyString}: ungültiger Schlüssel", - "iris.bukkit.runtime.bulkstructureimporter.fail_5": "§c[Fehler] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_6": "§c[Fehler] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.imported_skipped_failed": "§7...{processed}/{total} ({imported} importiert, {skipped} übersprungen, {failed} fehlgeschlagen)", - "iris.bukkit.runtime.bulkstructureimporter.template_import_complete_imported_skipped_failed_total": "§aVorlagenimport abgeschlossen: §f{imported}§a importiert, §f{skipped}§a übersprungen, §f{failed}§a fehlgeschlagen (§f{total}§a insgesamt).", - "iris.bukkit.runtime.bulkstructureimporter.no_datapack_non_minecraft_structures_are_registered_ingest_datapack_restart_first_then": "§eEs sind keine Datapack-Strukturen außerhalb von Minecraft registriert. Importiere zuerst ein Datapack, starte den Server neu und führe diesen Vorgang anschließend erneut aus.", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structures_mode": "§aImportiere §f{total}§a Datapack-Strukturen (mode={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_3": "§c[Fehler] {keyString}: ungültiger Schlüssel", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw_2": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single_2": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.fail_7": "§c[Fehler] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_8": "§c[Fehler] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_9": "§c[Fehler] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structure_templates": "§aImportiere §f{size}§a Datapack-Strukturvorlagen...", - "iris.bukkit.runtime.bulkstructureimporter.fail_10": "§c[Fehler] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_11": "§c[Fehler] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.could_not_enumerate_datapack_templates_via_server_resourcemanager": "§eDatapack-Vorlagen konnten nicht über den ResourceManager des Servers ermittelt werden: {error}", - "iris.bukkit.runtime.bulkstructureimporter.datapack_structure_import_complete_imported_skipped_failed": "§aImport der Datapack-Strukturen abgeschlossen: §f{imported}§a importiert, §f{skipped}§a übersprungen, §f{failed}§a fehlgeschlagen.", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_is_not_supported_by_active_nms_binding_skipping_capture_pass": "§eDie aktive NMS-Anbindung unterstützt keine Strukturerfassung; der Erfassungsdurchlauf wird übersprungen.", - "iris.bukkit.runtime.structurecaptureimporter.no_code_generated_structures_left_capture_everything_is_already_imported_as_structure": "§7Es sind keine codegenerierten Strukturen mehr zu erfassen (alle wurden bereits als Struktur importiert).", - "iris.bukkit.runtime.structurecaptureimporter.capturing_code_generated_structures_no_nbt_template_into_scratch_world_skipping_any": "§aErfasse §f{total}§a codegenerierte Strukturen ohne NBT-Vorlage in einer temporären Arbeitswelt; Strukturen mit mehr als {MAXSPAN} Blöcken Breite oder Höhe werden übersprungen...", - "iris.bukkit.runtime.structurecaptureimporter.skip_did_not_place_capturable_structure_here_too_large_wrong_dimension_no": "§e[übersprungen] {key}: Hier wurde keine erfassbare Struktur platziert (zu groß, falsche Dimension oder keine gültige Platzierung in einer flachen Welt). Sie wird weiterhin von vanilla generiert.", - "iris.bukkit.runtime.structurecaptureimporter.fail": "§c[Fehler] {key}: {message}", - "iris.bukkit.runtime.structurecaptureimporter.capture_objects_iob_x_x": "§7[Erfassung] {key} -> objects/{name}.iob ({w}x{h}x{d})", - "iris.bukkit.runtime.structurecaptureimporter.fail_2": "§c[Fehler] {key}: {error}", - "iris.bukkit.runtime.structurecaptureimporter.captured_skipped_failed": "§7...{processed}/{total} ({imported} erfasst, {skipped} übersprungen, {failed} fehlgeschlagen)", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_complete_captured_skipped_failed_total": "§aStrukturerfassung abgeschlossen: §f{imported}§a erfasst, §f{skipped}§a übersprungen, §f{failed}§a fehlgeschlagen (§f{total}§a insgesamt).", "iris.bukkit.runtime.featureimporter.no_vanilla_tree_object_features_are_exposed_by_active_nms_binding_importing": "§eDie aktive NMS-Anbindung stellt keine Baum-/Objekt-Features aus vanilla bereit; es werden nur Strukturen importiert.", "iris.bukkit.runtime.featureimporter.importing_vanilla_tree_object_features_variants_each_into_scratch_world": "§aImportiere §f{total}§a Baum-/Objekt-Features aus vanilla mit jeweils §f{wantVariants}§a Varianten in eine temporäre Arbeitswelt...", "iris.bukkit.runtime.featureimporter.obj_objects_vanilla": "§7[Objekt] {key} -> objects/vanilla/{group}/{safeName} ({written})", diff --git a/core/src/main/resources/languages/es_ES.json b/core/src/main/resources/languages/es_ES.json index 210fb6efe..0616f327e 100644 --- a/core/src/main/resources/languages/es_ES.json +++ b/core/src/main/resources/languages/es_ES.json @@ -1008,50 +1008,6 @@ "§cAhora que conoces los riesgos y has creado una copia de seguridad:", "§c/iris developer update-world {world} {pack} confirm=true" ], - "iris.bukkit.runtime.bulkstructureimporter.importing_vanilla_datapack_structures_mode_includenonjigsaw": "§aImportando §f{total}§a estructuras vanilla y de datapacks (mode={mode}, includeNonJigsaw={includeNonJigsaw})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key": "§c[fallo] {keyString}: llave inválida", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.skip_no_single_template_nbt_vanilla_builds_this_code_from_separate_piece": "§e[omitido] {keyString}: no hay una plantilla NBT única; vanilla la construye mediante código o plantillas de piezas separadas (importadas durante la fase de plantillas), así que no hay nada que importar como una sola estructura.", - "iris.bukkit.runtime.bulkstructureimporter.fail": "§c[fallo] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_2": "§c[fallo] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_3": "§c[fallo] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.bulk_import_complete_imported_skipped_failed_total": "§aImportación masiva completada: §f{imported}§a importadas, §f{skipped}§a omitidas, §f{failed}§a fallidas (§f{total}§a en total).", - "iris.bukkit.runtime.bulkstructureimporter.building_single_template_structures_from_imported_pieces_one_variant_placed_per_generation": "§aCreando estructuras de una sola plantilla a partir de las piezas importadas (se coloca una variante en cada generación)...", - "iris.bukkit.runtime.bulkstructureimporter.group_variants": "§7[group] {value} -> {value2} ({blocks} variantes)", - "iris.bukkit.runtime.bulkstructureimporter.skip": "§e[omitido] {value}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_4": "§c[fallo] {value}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.single_template_structures_built_skipped_failed": "§aEstructuras de una plantilla: §f{imported}§a creadas, §f{skipped}§a omitidas, §f{failed}§a fallidas.", - "iris.bukkit.runtime.bulkstructureimporter.failed_enumerate_structure_templates_via_server_resourcemanager": "§cNo se pudieron enumerar las plantillas de estructuras mediante el ResourceManager del servidor: {e}", - "iris.bukkit.runtime.bulkstructureimporter.no_structure_templates_were_found_under_structure_resource_path": "§eNo se encontraron plantillas de estructuras en la ruta de recursos 'structure'.", - "iris.bukkit.runtime.bulkstructureimporter.importing_structure_templates_mode": "§aImportando §f{total}§a plantillas de estructuras (mode={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_2": "§c[fallo] {keyString}: llave inválida", - "iris.bukkit.runtime.bulkstructureimporter.fail_5": "§c[fallo] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_6": "§c[fallo] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.imported_skipped_failed": "§7...{processed}/{total} ({imported} importadas, {skipped} omitidas, {failed} fallidas)", - "iris.bukkit.runtime.bulkstructureimporter.template_import_complete_imported_skipped_failed_total": "§aImportación de plantillas completada: §f{imported}§a importadas, §f{skipped}§a omitidas, §f{failed}§a fallidas (§f{total}§a en total).", - "iris.bukkit.runtime.bulkstructureimporter.no_datapack_non_minecraft_structures_are_registered_ingest_datapack_restart_first_then": "§eNo hay estructuras de datapacks (ajenas a minecraft) registradas. Ingiere un datapack, reinicia y vuelve a ejecutar esta operación.", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structures_mode": "§aImportando §f{total}§a estructuras de datapacks (mode={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_3": "§c[fallo] {keyString}: llave inválida", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw_2": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single_2": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.fail_7": "§c[fallo] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_8": "§c[fallo] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_9": "§c[fallo] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structure_templates": "§aImportando §f{size}§a plantillas de estructuras de datapacks...", - "iris.bukkit.runtime.bulkstructureimporter.fail_10": "§c[fallo] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_11": "§c[fallo] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.could_not_enumerate_datapack_templates_via_server_resourcemanager": "§eNo se pudieron enumerar las plantillas de datapacks mediante el ResourceManager del servidor: {error}", - "iris.bukkit.runtime.bulkstructureimporter.datapack_structure_import_complete_imported_skipped_failed": "§aImportación de estructuras del datapack completada: §f{imported}§a importadas, §f{skipped}§a omitidas, §f{failed}§a fallidas.", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_is_not_supported_by_active_nms_binding_skipping_capture_pass": "§eLa vinculación NMS activa no admite la captura de estructuras; se omitirá la fase de captura.", - "iris.bukkit.runtime.structurecaptureimporter.no_code_generated_structures_left_capture_everything_is_already_imported_as_structure": "§7No quedan estructuras generadas por código que capturar (todas ya se importaron como estructuras).", - "iris.bukkit.runtime.structurecaptureimporter.capturing_code_generated_structures_no_nbt_template_into_scratch_world_skipping_any": "§aCapturando §f{total}§a estructuras generadas por código (sin plantilla NBT) en un mundo temporal (se omitirán las que superen {MAXSPAN} bloques de ancho o alto)...", - "iris.bukkit.runtime.structurecaptureimporter.skip_did_not_place_capturable_structure_here_too_large_wrong_dimension_no": "§e[omitido] {key}: no se colocó aquí ninguna estructura capturable (es demasiado grande, pertenece a otra dimensión o no tiene una colocación válida en un mundo plano). Seguirá generándose mediante vanilla.", - "iris.bukkit.runtime.structurecaptureimporter.fail": "§c[fallo] {key}: {message}", - "iris.bukkit.runtime.structurecaptureimporter.capture_objects_iob_x_x": "§7[capture] {key} -> objects/{name}.iob ({w}x{h}x{d})", - "iris.bukkit.runtime.structurecaptureimporter.fail_2": "§c[fallo] {key}: {error}", - "iris.bukkit.runtime.structurecaptureimporter.captured_skipped_failed": "§7...{processed}/{total} ({imported} capturadas, {skipped} omitidas, {failed} fallidas)", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_complete_captured_skipped_failed_total": "§aCaptura de estructuras completada: §f{imported}§a capturadas, §f{skipped}§a omitidas, §f{failed}§a fallidas (§f{total}§a en total).", "iris.bukkit.runtime.featureimporter.no_vanilla_tree_object_features_are_exposed_by_active_nms_binding_importing": "§eLa vinculación NMS activa no expone ninguna funcionalidad vanilla de árboles u objetos (solo se importarán estructuras).", "iris.bukkit.runtime.featureimporter.importing_vanilla_tree_object_features_variants_each_into_scratch_world": "§aImportando §f{total}§a funcionalidades vanilla de árboles u objetos (§f{wantVariants}§a variantes de cada una) en un mundo temporal...", "iris.bukkit.runtime.featureimporter.obj_objects_vanilla": "§7[obj] {key} -> objects/vanilla/{group}/{safeName} ({written})", diff --git a/core/src/main/resources/languages/fi_FI.json b/core/src/main/resources/languages/fi_FI.json index 6bc7d0dba..ff92b21a4 100644 --- a/core/src/main/resources/languages/fi_FI.json +++ b/core/src/main/resources/languages/fi_FI.json @@ -1008,50 +1008,6 @@ "§cKun ymmärrät riskit ja olet tehnyt varmuuskopion:", "§c/iris developer update-world {world} {pack} confirm=true" ], - "iris.bukkit.runtime.bulkstructureimporter.importing_vanilla_datapack_structures_mode_includenonjigsaw": "§aTuo §f{total}§a vanilla & datapakettirakenteet (tila ={mode}, includeNonJigsaw={includeNonJigsaw})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key": "§c[virhe] {keyString}: virheellinen avain", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.skip_no_single_template_nbt_vanilla_builds_this_code_from_separate_piece": "§e[ohitettu] {keyString}: ei yksilevyistä NBT - vanilla rakentaa tämän koodilla tai erillisistä kappalemalleista (tuotu mallien kautta); ei mitään tuotavaa yhtenä rakenteena.", - "iris.bukkit.runtime.bulkstructureimporter.fail": "§c[virhe] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_2": "§c[virhe] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_3": "§c[virhe] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.bulk_import_complete_imported_skipped_failed_total": "§aIrtotuonti valmis: §f{imported}§a tuonti, §f{skipped}§a ohitettu, §f{failed}§a epäonnistui (§f{total}§a yhteensä).", - "iris.bukkit.runtime.bulkstructureimporter.building_single_template_structures_from_imported_pieces_one_variant_placed_per_generation": "§aYksirunkoisten rakenteiden rakentaminen tuontikappaleista (yksi muunnos/sukupolvet)...", - "iris.bukkit.runtime.bulkstructureimporter.group_variants": "§7[group] {value} -> {value2} ({blocks} variantit)", - "iris.bukkit.runtime.bulkstructureimporter.skip": "§e[ohitettu] {value}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_4": "§c[virhe] {value}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.single_template_structures_built_skipped_failed": "§ayksirunkoiset rakenteet: §f{imported}§a rakennettu, §f{skipped}§a ohitettu, §f{failed}§a Epäonnistui.", - "iris.bukkit.runtime.bulkstructureimporter.failed_enumerate_structure_templates_via_server_resourcemanager": "§cRakennemalleja ei voitu laskea palvelimen kautta ResourceManager: {e}", - "iris.bukkit.runtime.bulkstructureimporter.no_structure_templates_were_found_under_structure_resource_path": "§e\"Rakennus\"-resurssireitistä ei löytynyt rakennemalleja.", - "iris.bukkit.runtime.bulkstructureimporter.importing_structure_templates_mode": "§aTuo §f{total}§a rakennemallit (muoto ={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_2": "§c[virhe] {keyString}: virheellinen avain", - "iris.bukkit.runtime.bulkstructureimporter.fail_5": "§c[virhe] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_6": "§c[virhe] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.imported_skipped_failed": "§7...{processed}/{total} ({imported} tuonti, {skipped} ohitettu, {failed} epäonnistui)", - "iris.bukkit.runtime.bulkstructureimporter.template_import_complete_imported_skipped_failed_total": "§aMallin tuonti valmis: §f{imported}§a tuonti, §f{skipped}§a ohitettu, §f{failed}§a epäonnistui (§f{total}§a yhteensä).", - "iris.bukkit.runtime.bulkstructureimporter.no_datapack_non_minecraft_structures_are_registered_ingest_datapack_restart_first_then": "§eDatapack (ei-miina) rakenteita ei ole rekisteröity. Aloita datapaketti ja käynnistä se uudelleen.", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structures_mode": "§aTuo §f{total}§a datapakettirakenteet (tila ={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_3": "§c[virhe] {keyString}: virheellinen avain", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw_2": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single_2": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.fail_7": "§c[virhe] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_8": "§c[virhe] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_9": "§c[virhe] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structure_templates": "§aTuo §f{size}§a tietopaketin rakennemallit...", - "iris.bukkit.runtime.bulkstructureimporter.fail_10": "§c[virhe] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_11": "§c[virhe] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.could_not_enumerate_datapack_templates_via_server_resourcemanager": "§eDatapakettimalleja ei voitu luetella palvelimen kautta ResourceManager: {error}", - "iris.bukkit.runtime.bulkstructureimporter.datapack_structure_import_complete_imported_skipped_failed": "§aDatapack-rakenteen tuonti valmis: §f{imported}§a tuonti, §f{skipped}§a ohitettu, §f{failed}§a Epäonnistui.", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_is_not_supported_by_active_nms_binding_skipping_capture_pass": "§eAktiivinen rakennekaappaus ei tue NMS sidonta; vangitsemispassin ohittaminen.", - "iris.bukkit.runtime.structurecaptureimporter.no_code_generated_structures_left_capture_everything_is_already_imported_as_structure": "§7Ei koodattuja rakenteita, jotka voitaisiin kaapata (kaikki on jo tuotu maahan rakenteena).", - "iris.bukkit.runtime.structurecaptureimporter.capturing_code_generated_structures_no_nbt_template_into_scratch_world_skipping_any": "§aKaappaus §f{total}§a Koodin aiheuttamat rakenteet (ei NBT malli) osaksi naarmu maailmaan (slipping mitään laajempaa / taller kuin {MAXSPAN} lohkot)...", - "iris.bukkit.runtime.structurecaptureimporter.skip_did_not_place_capturable_structure_here_too_large_wrong_dimension_no": "§e[ohitettu] {key}: ei sijoittanut kaapattava rakenne täällä (liian suuri, väärä ulottuvuus, tai ei voimassa sijoitus litteässä maailmassa). Se on vanillaa.", - "iris.bukkit.runtime.structurecaptureimporter.fail": "§c[virhe] {key}: {message}", - "iris.bukkit.runtime.structurecaptureimporter.capture_objects_iob_x_x": "§7[capture] {key} -> objects/{name}.iob ({w}x{h}x{d})", - "iris.bukkit.runtime.structurecaptureimporter.fail_2": "§c[virhe] {key}: {error}", - "iris.bukkit.runtime.structurecaptureimporter.captured_skipped_failed": "§7...{processed}/{total} ({imported} kiinni, {skipped} ohitettu, {failed} epäonnistui)", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_complete_captured_skipped_failed_total": "§aRakenne kaapattu: §f{imported}§a kiinni, §f{skipped}§a ohitettu, §f{failed}§a epäonnistui (§f{total}§a yhteensä).", "iris.bukkit.runtime.featureimporter.no_vanilla_tree_object_features_are_exposed_by_active_nms_binding_importing": "§eAktiivinen puu/kohde ei altistu vanillapuulle. NMS sitova (vain tuontirakenteet).", "iris.bukkit.runtime.featureimporter.importing_vanilla_tree_object_features_variants_each_into_scratch_world": "§aTuo §f{total}§a vanillapuun/kohteen ominaisuudet (§f{wantVariants}§a variantteja kukin) osaksi naarmu maailma...", "iris.bukkit.runtime.featureimporter.obj_objects_vanilla": "§7[obj] {key} -> objects/vanilla/{group}/{safeName} ({written})", diff --git a/core/src/main/resources/languages/fr_FR.json b/core/src/main/resources/languages/fr_FR.json index 2035230c4..f22c49ecc 100644 --- a/core/src/main/resources/languages/fr_FR.json +++ b/core/src/main/resources/languages/fr_FR.json @@ -1008,50 +1008,6 @@ "§cMaintenant que vous connaissez les risques et avez créé une sauvegarde :", "§c/iris developer update-world {world} {pack} confirm=true" ], - "iris.bukkit.runtime.bulkstructureimporter.importing_vanilla_datapack_structures_mode_includenonjigsaw": "§aImportation de §f{total}§a structures vanilla et de datapacks (mode={mode}, includeNonJigsaw={includeNonJigsaw})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key": "§c[échec] {keyString}: clé invalide", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.skip_no_single_template_nbt_vanilla_builds_this_code_from_separate_piece": "§e[ignoré] {keyString} : aucun modèle NBT unique ; vanilla construit cette structure dans le code ou à partir de modèles de pièces distincts (importés lors de la phase des modèles), donc rien ne peut être importé comme structure unique.", - "iris.bukkit.runtime.bulkstructureimporter.fail": "§c[échec] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_2": "§c[échec] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_3": "§c[échec] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.bulk_import_complete_imported_skipped_failed_total": "§aImportation en masse terminée : §f{imported}§a importées, §f{skipped}§a ignorées, §f{failed}§a échecs (§f{total}§a au total).", - "iris.bukkit.runtime.bulkstructureimporter.building_single_template_structures_from_imported_pieces_one_variant_placed_per_generation": "§aCréation de structures à modèle unique depuis les pièces importées (une variante est placée à chaque génération)...", - "iris.bukkit.runtime.bulkstructureimporter.group_variants": "§7[group] {value} -> {value2} ({blocks} variantes)", - "iris.bukkit.runtime.bulkstructureimporter.skip": "§e[ignoré] {value}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_4": "§c[échec] {value}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.single_template_structures_built_skipped_failed": "§aStructures à modèle unique : §f{imported}§a créées, §f{skipped}§a ignorées, §f{failed}§a échecs.", - "iris.bukkit.runtime.bulkstructureimporter.failed_enumerate_structure_templates_via_server_resourcemanager": "§cImpossible d'énumérer les modèles de structure via le serveur ResourceManager: {e}", - "iris.bukkit.runtime.bulkstructureimporter.no_structure_templates_were_found_under_structure_resource_path": "§eAucun modèle de structure trouvé dans le chemin de ressources 'structure'.", - "iris.bukkit.runtime.bulkstructureimporter.importing_structure_templates_mode": "§aImportation de §f{total}§a modèles de structures (mode={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_2": "§c[échec] {keyString}: clé invalide", - "iris.bukkit.runtime.bulkstructureimporter.fail_5": "§c[échec] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_6": "§c[échec] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.imported_skipped_failed": "§7...{processed}/{total} ({imported} importées, {skipped} ignorées, {failed} échecs)", - "iris.bukkit.runtime.bulkstructureimporter.template_import_complete_imported_skipped_failed_total": "§aImportation des modèles terminée : §f{imported}§a importés, §f{skipped}§a ignorés, §f{failed}§a échecs (§f{total}§a au total).", - "iris.bukkit.runtime.bulkstructureimporter.no_datapack_non_minecraft_structures_are_registered_ingest_datapack_restart_first_then": "§eAucune structure de datapack (hors minecraft) n'est enregistrée. Ingérez un datapack, redémarrez, puis relancez cette opération.", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structures_mode": "§aImportation de §f{total}§a structures de datapacks (mode={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_3": "§c[échec] {keyString}: clé invalide", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw_2": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single_2": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.fail_7": "§c[échec] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_8": "§c[échec] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_9": "§c[échec] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structure_templates": "§aImportation de §f{size}§a modèles de structures de datapacks...", - "iris.bukkit.runtime.bulkstructureimporter.fail_10": "§c[échec] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_11": "§c[échec] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.could_not_enumerate_datapack_templates_via_server_resourcemanager": "§eImpossible d'énumérer les modèles de datapacks via le ResourceManager du serveur : {error}", - "iris.bukkit.runtime.bulkstructureimporter.datapack_structure_import_complete_imported_skipped_failed": "§aImportation des structures du datapack terminée : §f{imported}§a importées, §f{skipped}§a ignorées, §f{failed}§a échecs.", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_is_not_supported_by_active_nms_binding_skipping_capture_pass": "§eLa liaison NMS active ne prend pas en charge la capture des structures ; la phase de capture sera ignorée.", - "iris.bukkit.runtime.structurecaptureimporter.no_code_generated_structures_left_capture_everything_is_already_imported_as_structure": "§7Il ne reste aucune structure générée par le code à capturer (toutes ont déjà été importées comme structures).", - "iris.bukkit.runtime.structurecaptureimporter.capturing_code_generated_structures_no_nbt_template_into_scratch_world_skipping_any": "§aCapture de §f{total}§a structures générées par le code (sans modèle NBT) dans un monde temporaire (celles qui dépassent {MAXSPAN} blocs de largeur ou de hauteur seront ignorées)...", - "iris.bukkit.runtime.structurecaptureimporter.skip_did_not_place_capturable_structure_here_too_large_wrong_dimension_no": "§e[ignoré] {key} : aucune structure capturable n'a été placée ici (trop grande, mauvaise dimension ou aucun placement valide dans un monde plat). Elle restera générée par vanilla.", - "iris.bukkit.runtime.structurecaptureimporter.fail": "§c[échec] {key}: {message}", - "iris.bukkit.runtime.structurecaptureimporter.capture_objects_iob_x_x": "§7[capture] {key} -> objects/{name}.iob ({w}x{h}x{d})", - "iris.bukkit.runtime.structurecaptureimporter.fail_2": "§c[échec] {key}: {error}", - "iris.bukkit.runtime.structurecaptureimporter.captured_skipped_failed": "§7...{processed}/{total} ({imported} capturées, {skipped} ignorées, {failed} échecs)", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_complete_captured_skipped_failed_total": "§aCapture des structures terminée : §f{imported}§a capturées, §f{skipped}§a ignorées, §f{failed}§a échecs (§f{total}§a au total).", "iris.bukkit.runtime.featureimporter.no_vanilla_tree_object_features_are_exposed_by_active_nms_binding_importing": "§eLa liaison NMS active n'expose aucune fonctionnalité vanilla d'arbre ou d'objet (seules les structures seront importées).", "iris.bukkit.runtime.featureimporter.importing_vanilla_tree_object_features_variants_each_into_scratch_world": "§aImportation de §f{total}§a fonctionnalités vanilla d'arbres ou d'objets (§f{wantVariants}§a variantes chacune) dans un monde temporaire...", "iris.bukkit.runtime.featureimporter.obj_objects_vanilla": "§7[obj] {key} -> objects/vanilla/{group}/{safeName} ({written})", diff --git a/core/src/main/resources/languages/he_IL.json b/core/src/main/resources/languages/he_IL.json index fe7e19569..84c960a99 100644 --- a/core/src/main/resources/languages/he_IL.json +++ b/core/src/main/resources/languages/he_IL.json @@ -1008,50 +1008,6 @@ "§cלאחר שהבנת את הסיכונים ויצרת גיבוי:", "§c/iris developer update-world {world} {pack} confirm=true" ], - "iris.bukkit.runtime.bulkstructureimporter.importing_vanilla_datapack_structures_mode_includenonjigsaw": "§aיבוא §f{total}§a vanilla & מאגרי מידע (Mode={mode}, includeNonJigsaw={includeNonJigsaw})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key": "§c[כשל] {keyString}מפתח לא חוקי", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.skip_no_single_template_nbt_vanilla_builds_this_code_from_separate_piece": "§e[דילוג] {keyString}אף פעם אחת NBT - vanilla בונה את זה בקוד או מתבניות נייר נפרדות (מדווחים באמצעות תבניות לעבור); שום דבר לייבא כמבנה אחד.", - "iris.bukkit.runtime.bulkstructureimporter.fail": "§c[כשל] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_2": "§c[כשל] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_3": "§c[כשל] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.bulk_import_complete_imported_skipped_failed_total": "§aייבוא בוץ מלא: §f{imported}§a מיובא, §f{skipped}§a מדלג, §f{failed}§a נכשל (§f{total}§a בסך הכל).", - "iris.bukkit.runtime.bulkstructureimporter.building_single_template_structures_from_imported_pieces_one_variant_placed_per_generation": "§aבניית מבנים חד-פעמיים מחתיכות מיובאות (גרסה אחת שהוצבה לדור)...", - "iris.bukkit.runtime.bulkstructureimporter.group_variants": "§7[קבוצה] {value} -> {value2} ({blocks} גרסאות)", - "iris.bukkit.runtime.bulkstructureimporter.skip": "§e[דילוג] {value}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_4": "§c[כשל] {value}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.single_template_structures_built_skipped_failed": "§aמבנים חד-זמנית: §f{imported}§a נבנה, §f{skipped}§a מדלג, §f{failed}§a נכשל.", - "iris.bukkit.runtime.bulkstructureimporter.failed_enumerate_structure_templates_via_server_resourcemanager": "§cנכשל לספור תבניות מבנה באמצעות השרת ResourceManager: {e}", - "iris.bukkit.runtime.bulkstructureimporter.no_structure_templates_were_found_under_structure_resource_path": "§eלא נמצאו תבניות מבנה תחת נתיב משאבים \"מבנה\".", - "iris.bukkit.runtime.bulkstructureimporter.importing_structure_templates_mode": "§aיבוא §f{total}§a תבניות מבנה (Mode={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_2": "§c[כשל] {keyString}מפתח לא חוקי", - "iris.bukkit.runtime.bulkstructureimporter.fail_5": "§c[כשל] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_6": "§c[כשל] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.imported_skipped_failed": "§7...{processed}/{total} ({imported} מיובא, {skipped} מדלג, {failed} נכשל)", - "iris.bukkit.runtime.bulkstructureimporter.template_import_complete_imported_skipped_failed_total": "§aיבוא תבנית שלם: §f{imported}§a מיובא, §f{skipped}§a מדלג, §f{failed}§a נכשל (§f{total}§a בסך הכל).", - "iris.bukkit.runtime.bulkstructureimporter.no_datapack_non_minecraft_structures_are_registered_ingest_datapack_restart_first_then": "§eלא רשומים מבני datapack (non-minecraft). יש לטעון datapack ולהפעיל מחדש תחילה, ואז להריץ זאת שוב.", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structures_mode": "§aיבוא §f{total}§a מאגרי מידע (Mode={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_3": "§c[כשל] {keyString}מפתח לא חוקי", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw_2": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single_2": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.fail_7": "§c[כשל] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_8": "§c[כשל] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_9": "§c[כשל] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structure_templates": "§aיבוא §f{size}§a תבניות בנייה...", - "iris.bukkit.runtime.bulkstructureimporter.fail_10": "§c[כשל] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_11": "§c[כשל] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.could_not_enumerate_datapack_templates_via_server_resourcemanager": "§eלא ניתן למנות תבניות איסוף נתונים באמצעות השרת ResourceManager: {error}", - "iris.bukkit.runtime.bulkstructureimporter.datapack_structure_import_complete_imported_skipped_failed": "§aמבנה ה-Datapack יושלם: §f{imported}§a מיובא, §f{skipped}§a מדלג, §f{failed}§a נכשל.", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_is_not_supported_by_active_nms_binding_skipping_capture_pass": "§eכיבוש המבנה אינו נתמך על ידי הפעילים NMS מחייב; לדלג על מעבר הלכידת.", - "iris.bukkit.runtime.structurecaptureimporter.no_code_generated_structures_left_capture_everything_is_already_imported_as_structure": "§7לא נותרו מבנים מקודמים ללכידת (כל דבר כבר ייבא כמבנה).", - "iris.bukkit.runtime.structurecaptureimporter.capturing_code_generated_structures_no_nbt_template_into_scratch_world_skipping_any": "§aתגית: לכידה §f{total}§a מבנים מהונדסים (לא NBT תבנית) לתוך עולם שריטה (מעלה כל רחבה / אלטר מאשר {MAXSPAN} בלוקים)...", - "iris.bukkit.runtime.structurecaptureimporter.skip_did_not_place_capturable_structure_here_too_large_wrong_dimension_no": "§e[דילוג] {key}לא היה כאן מבנה לוכד (ממד גדול מדי, שגוי או שום מיקום חוקי בעולם שטוח). נשאר Vanilla-generated.", - "iris.bukkit.runtime.structurecaptureimporter.fail": "§c[כשל] {key}: {message}", - "iris.bukkit.runtime.structurecaptureimporter.capture_objects_iob_x_x": "§7[לכוד] {key} -> objects/{name}.iob ({w}x{h}x{d})", - "iris.bukkit.runtime.structurecaptureimporter.fail_2": "§c[כשל] {key}: {error}", - "iris.bukkit.runtime.structurecaptureimporter.captured_skipped_failed": "§7...{processed}/{total} ({imported} נתפס, {skipped} מדלג, {failed} נכשל)", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_complete_captured_skipped_failed_total": "§aמבנה שלם: §f{imported}§a נתפס, §f{skipped}§a מדלג, §f{failed}§a נכשל (§f{total}§a בסך הכל).", "iris.bukkit.runtime.featureimporter.no_vanilla_tree_object_features_are_exposed_by_active_nms_binding_importing": "§eאין עץ vanilla /object נחשפים על ידי פעיל NMS מחייב (מציג מבנים בלבד).", "iris.bukkit.runtime.featureimporter.importing_vanilla_tree_object_features_variants_each_into_scratch_world": "§aיבוא §f{total}§a עץ vanilla / object תכונות (§f{wantVariants}§a גרסאות לכל אחד) לתוך עולם שריטות...", "iris.bukkit.runtime.featureimporter.obj_objects_vanilla": "§7[obj] {key} -> objects/vanilla/{group}/{safeName} ({written})", diff --git a/core/src/main/resources/languages/it_IT.json b/core/src/main/resources/languages/it_IT.json index 2f9d34e4a..3a872f7d1 100644 --- a/core/src/main/resources/languages/it_IT.json +++ b/core/src/main/resources/languages/it_IT.json @@ -1008,50 +1008,6 @@ "§cDopo aver compreso i rischi e creato un backup:", "§c/iris developer update-world {world} {pack} confirm=true" ], - "iris.bukkit.runtime.bulkstructureimporter.importing_vanilla_datapack_structures_mode_includenonjigsaw": "§aImportazione di §f{total}§a strutture vanilla e datapack (mode={mode}, includeNonJigsaw={includeNonJigsaw})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key": "§c[errore] {keyString}: chiave non valida", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.skip_no_single_template_nbt_vanilla_builds_this_code_from_separate_piece": "§e[ignorato] {keyString}: nessun NBT con modello singolo; vanilla crea questa struttura nel codice o da modelli di parti separate, importati durante il passaggio dei modelli. Non esiste una singola struttura da importare.", - "iris.bukkit.runtime.bulkstructureimporter.fail": "§c[errore] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_2": "§c[errore] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_3": "§c[errore] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.bulk_import_complete_imported_skipped_failed_total": "§aImportazione in blocco completata: §f{imported}§a importate, §f{skipped}§a ignorate, §f{failed}§a non riuscite (§f{total}§a totali).", - "iris.bukkit.runtime.bulkstructureimporter.building_single_template_structures_from_imported_pieces_one_variant_placed_per_generation": "§aCreazione di strutture con modello singolo dalle parti importate (una variante collocata per ogni generazione)...", - "iris.bukkit.runtime.bulkstructureimporter.group_variants": "§7[gruppo] {value} -> {value2} ({blocks} varianti)", - "iris.bukkit.runtime.bulkstructureimporter.skip": "§e[ignorato] {value}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_4": "§c[errore] {value}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.single_template_structures_built_skipped_failed": "§aStrutture con modello singolo: §f{imported}§a create, §f{skipped}§a ignorate, §f{failed}§a non riuscite.", - "iris.bukkit.runtime.bulkstructureimporter.failed_enumerate_structure_templates_via_server_resourcemanager": "§cImpossibile enumerare i modelli di struttura tramite il ResourceManager del server: {e}", - "iris.bukkit.runtime.bulkstructureimporter.no_structure_templates_were_found_under_structure_resource_path": "§eNessun modello di struttura trovato nel percorso di risorse 'structure'.", - "iris.bukkit.runtime.bulkstructureimporter.importing_structure_templates_mode": "§aImportazione di §f{total}§a modelli di struttura (mode={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_2": "§c[errore] {keyString}: chiave non valida", - "iris.bukkit.runtime.bulkstructureimporter.fail_5": "§c[errore] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_6": "§c[errore] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.imported_skipped_failed": "§7...{processed}/{total} ({imported} importate, {skipped} ignorate, {failed} non riuscite)", - "iris.bukkit.runtime.bulkstructureimporter.template_import_complete_imported_skipped_failed_total": "§aImportazione dei modelli completata: §f{imported}§a importati, §f{skipped}§a ignorati, §f{failed}§a non riusciti (§f{total}§a totali).", - "iris.bukkit.runtime.bulkstructureimporter.no_datapack_non_minecraft_structures_are_registered_ingest_datapack_restart_first_then": "§eNon sono registrate strutture datapack esterne a Minecraft. Importa prima un datapack, riavvia il server e poi ripeti l'operazione.", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structures_mode": "§aImportazione di §f{total}§a strutture datapack (mode={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_3": "§c[errore] {keyString}: chiave non valida", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw_2": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single_2": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.fail_7": "§c[errore] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_8": "§c[errore] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_9": "§c[errore] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structure_templates": "§aImportazione di §f{size}§a modelli di struttura datapack...", - "iris.bukkit.runtime.bulkstructureimporter.fail_10": "§c[errore] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_11": "§c[errore] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.could_not_enumerate_datapack_templates_via_server_resourcemanager": "§eImpossibile enumerare i modelli datapack tramite il ResourceManager del server: {error}", - "iris.bukkit.runtime.bulkstructureimporter.datapack_structure_import_complete_imported_skipped_failed": "§aImportazione delle strutture datapack completata: §f{imported}§a importate, §f{skipped}§a ignorate, §f{failed}§a non riuscite.", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_is_not_supported_by_active_nms_binding_skipping_capture_pass": "§eIl collegamento NMS attivo non supporta l'acquisizione delle strutture; il relativo passaggio verrà ignorato.", - "iris.bukkit.runtime.structurecaptureimporter.no_code_generated_structures_left_capture_everything_is_already_imported_as_structure": "§7Non restano strutture generate dal codice da acquisire (sono già state tutte importate come strutture).", - "iris.bukkit.runtime.structurecaptureimporter.capturing_code_generated_structures_no_nbt_template_into_scratch_world_skipping_any": "§aAcquisizione di §f{total}§a strutture generate dal codice senza modello NBT in un mondo di lavoro temporaneo; verranno ignorate quelle più larghe o alte di {MAXSPAN} blocchi...", - "iris.bukkit.runtime.structurecaptureimporter.skip_did_not_place_capturable_structure_here_too_large_wrong_dimension_no": "§e[ignorato] {key}: qui non è stata collocata una struttura acquisibile (troppo grande, dimensione errata o nessun posizionamento valido in un mondo piatto). Continuerà a essere generata da vanilla.", - "iris.bukkit.runtime.structurecaptureimporter.fail": "§c[errore] {key}: {message}", - "iris.bukkit.runtime.structurecaptureimporter.capture_objects_iob_x_x": "§7[acquisizione] {key} -> objects/{name}.iob ({w}x{h}x{d})", - "iris.bukkit.runtime.structurecaptureimporter.fail_2": "§c[errore] {key}: {error}", - "iris.bukkit.runtime.structurecaptureimporter.captured_skipped_failed": "§7...{processed}/{total} ({imported} acquisite, {skipped} ignorate, {failed} non riuscite)", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_complete_captured_skipped_failed_total": "§aAcquisizione delle strutture completata: §f{imported}§a acquisite, §f{skipped}§a ignorate, §f{failed}§a non riuscite (§f{total}§a totali).", "iris.bukkit.runtime.featureimporter.no_vanilla_tree_object_features_are_exposed_by_active_nms_binding_importing": "§eIl collegamento NMS attivo non espone feature albero/oggetto di vanilla; verranno importate solo le strutture.", "iris.bukkit.runtime.featureimporter.importing_vanilla_tree_object_features_variants_each_into_scratch_world": "§aImportazione di §f{total}§a feature albero/oggetto di vanilla, con §f{wantVariants}§a varianti ciascuna, in un mondo di lavoro temporaneo...", "iris.bukkit.runtime.featureimporter.obj_objects_vanilla": "§7[oggetto] {key} -> objects/vanilla/{group}/{safeName} ({written})", diff --git a/core/src/main/resources/languages/ja-JP.json b/core/src/main/resources/languages/ja-JP.json index 3af895dba..0ba0ea1df 100644 --- a/core/src/main/resources/languages/ja-JP.json +++ b/core/src/main/resources/languages/ja-JP.json @@ -1008,50 +1008,6 @@ "§cリスクを理解し、バックアップを作成したら実行してください:", "§c/iris developer update-world {world} {pack} confirm=true" ], - "iris.bukkit.runtime.bulkstructureimporter.importing_vanilla_datapack_structures_mode_includenonjigsaw": "§aバニラおよびデータパック構造物 §f{total}§a 件をインポートしています(mode={mode}、includeNonJigsaw={includeNonJigsaw})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key": "§c[失敗] {keyString}: 無効なキー", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.skip_no_single_template_nbt_vanilla_builds_this_code_from_separate_piece": "§e[スキップ] {keyString}: 単一テンプレートの NBT がありません。バニラはコードまたは個別のピーステンプレートから構築します(テンプレート処理でインポート済み)。単一構造物としてインポートする対象はありません。", - "iris.bukkit.runtime.bulkstructureimporter.fail": "§c[失敗] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_2": "§c[失敗] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_3": "§c[失敗] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.bulk_import_complete_imported_skipped_failed_total": "§a一括インポート完了: §f{imported}§a 件をインポート、§f{skipped}§a 件をスキップ、§f{failed}§a 件が失敗(合計 §f{total}§a 件)。", - "iris.bukkit.runtime.bulkstructureimporter.building_single_template_structures_from_imported_pieces_one_variant_placed_per_generation": "§aインポートしたピースから単一テンプレート構造物を構築しています(生成ごとに 1 バリアントを配置)...", - "iris.bukkit.runtime.bulkstructureimporter.group_variants": "§7[group] {value} -> {value2} ({blocks} バリアント)", - "iris.bukkit.runtime.bulkstructureimporter.skip": "§e[スキップ] {value}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_4": "§c[失敗] {value}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.single_template_structures_built_skipped_failed": "§a単一テンプレート構造物: §f{imported}§a 件を構築、§f{skipped}§a 件をスキップ、§f{failed}§a 件が失敗しました。", - "iris.bukkit.runtime.bulkstructureimporter.failed_enumerate_structure_templates_via_server_resourcemanager": "§cサーバーの ResourceManager から構造物テンプレートを列挙できませんでした: {e}", - "iris.bukkit.runtime.bulkstructureimporter.no_structure_templates_were_found_under_structure_resource_path": "§e'structure' リソースパスに構造物テンプレートがありません。", - "iris.bukkit.runtime.bulkstructureimporter.importing_structure_templates_mode": "§a構造物テンプレート §f{total}§a 件をインポートしています(mode={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_2": "§c[失敗] {keyString}: 無効なキー", - "iris.bukkit.runtime.bulkstructureimporter.fail_5": "§c[失敗] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_6": "§c[失敗] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.imported_skipped_failed": "§7...{processed}/{total}(インポート {imported}、スキップ {skipped}、失敗 {failed})", - "iris.bukkit.runtime.bulkstructureimporter.template_import_complete_imported_skipped_failed_total": "§aテンプレートのインポート完了: §f{imported}§a 件をインポート、§f{skipped}§a 件をスキップ、§f{failed}§a 件が失敗(合計 §f{total}§a 件)。", - "iris.bukkit.runtime.bulkstructureimporter.no_datapack_non_minecraft_structures_are_registered_ingest_datapack_restart_first_then": "§edatapack(non-minecraft)の構造物が登録されていません。先に datapack を取り込んで再起動してから、もう一度実行してください。", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structures_mode": "§aデータパック構造物 §f{total}§a 件をインポートしています(mode={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_3": "§c[失敗] {keyString}: 無効なキー", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw_2": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single_2": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.fail_7": "§c[失敗] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_8": "§c[失敗] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_9": "§c[失敗] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structure_templates": "§aデータパック構造物テンプレート §f{size}§a 件をインポートしています...", - "iris.bukkit.runtime.bulkstructureimporter.fail_10": "§c[失敗] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_11": "§c[失敗] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.could_not_enumerate_datapack_templates_via_server_resourcemanager": "§eサーバーの ResourceManager からデータパックテンプレートを列挙できませんでした: {error}", - "iris.bukkit.runtime.bulkstructureimporter.datapack_structure_import_complete_imported_skipped_failed": "§aデータパック構造物のインポート完了: §f{imported}§a 件をインポート、§f{skipped}§a 件をスキップ、§f{failed}§a 件が失敗しました。", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_is_not_supported_by_active_nms_binding_skipping_capture_pass": "§e現在の NMS バインディングは構造物キャプチャに対応していないため、キャプチャ処理をスキップします。", - "iris.bukkit.runtime.structurecaptureimporter.no_code_generated_structures_left_capture_everything_is_already_imported_as_structure": "§7キャプチャ対象のコード生成構造物は残っていません(すべて構造物としてインポート済みです)。", - "iris.bukkit.runtime.structurecaptureimporter.capturing_code_generated_structures_no_nbt_template_into_scratch_world_skipping_any": "§aコード生成構造物(NBT テンプレートなし)§f{total}§a 件を作業用ワールドでキャプチャしています(幅または高さが {MAXSPAN} ブロックを超えるものはスキップ)...", - "iris.bukkit.runtime.structurecaptureimporter.skip_did_not_place_capturable_structure_here_too_large_wrong_dimension_no": "§e[スキップ] {key}: キャプチャ可能な構造物を配置できませんでした(大きすぎる、ディメンションが違う、またはフラットワールドに有効な配置場所がない)。バニラ生成のままにします。", - "iris.bukkit.runtime.structurecaptureimporter.fail": "§c[失敗] {key}: {message}", - "iris.bukkit.runtime.structurecaptureimporter.capture_objects_iob_x_x": "§7[キャプチャ] {key} -> objects/{name}.iob ({w}x{h}x{d})", - "iris.bukkit.runtime.structurecaptureimporter.fail_2": "§c[失敗] {key}: {error}", - "iris.bukkit.runtime.structurecaptureimporter.captured_skipped_failed": "§7...{processed}/{total}(キャプチャ {imported}、スキップ {skipped}、失敗 {failed})", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_complete_captured_skipped_failed_total": "§a構造物キャプチャ完了: §f{imported}§a 件をキャプチャ、§f{skipped}§a 件をスキップ、§f{failed}§a 件が失敗(合計 §f{total}§a 件)。", "iris.bukkit.runtime.featureimporter.no_vanilla_tree_object_features_are_exposed_by_active_nms_binding_importing": "§e現在の NMS バインディングではバニラの木またはオブジェクト機能を取得できません(構造物のみインポートします)。", "iris.bukkit.runtime.featureimporter.importing_vanilla_tree_object_features_variants_each_into_scratch_world": "§aバニラの木またはオブジェクト機能 §f{total}§a 件(各 §f{wantVariants}§a バリアント)を作業用ワールドにインポートしています...", "iris.bukkit.runtime.featureimporter.obj_objects_vanilla": "§7[obj] {key} -> objects/vanilla/{group}/{safeName} ({written})", diff --git a/core/src/main/resources/languages/ko_KR.json b/core/src/main/resources/languages/ko_KR.json index 2fb5b822e..cac65e2c8 100644 --- a/core/src/main/resources/languages/ko_KR.json +++ b/core/src/main/resources/languages/ko_KR.json @@ -1008,50 +1008,6 @@ "§c당신은 위험의 인식이며, 백업을했다 :", "§c/iris developer update-world {world} {pack} confirm=true" ], - "iris.bukkit.runtime.bulkstructureimporter.importing_vanilla_datapack_structures_mode_includenonjigsaw": "§a관련 상품 §f{total}§a 바닐라 & datapack 구조 (mode={mode}, includeNonJigsaw={includeNonJigsaw})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key": "§c[실패] {keyString}: 잘못된 키", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.skip_no_single_template_nbt_vanilla_builds_this_code_from_separate_piece": "§e[건너뜀] {keyString}: 단일 템플릿 없음 NBT - 바닐라는 코드 또는 별도의 조각 템플릿 ( 템플렛 패스를 통해 전달); 하나의 구조로 가져 오기에 아무것도.", - "iris.bukkit.runtime.bulkstructureimporter.fail": "§c[실패] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_2": "§c[실패] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_3": "§c[실패] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.bulk_import_complete_imported_skipped_failed_total": "§a일괄 가져오기 완료: §f{imported}§a개 가져옴, §f{skipped}§a개 건너뜀, §f{failed}§a개 실패(전체 §f{total}§a개).", - "iris.bukkit.runtime.bulkstructureimporter.building_single_template_structures_from_imported_pieces_one_variant_placed_per_generation": "§a가져온 조각으로 단일 템플릿 구조물을 만드는 중(생성마다 변형 하나 배치)...", - "iris.bukkit.runtime.bulkstructureimporter.group_variants": "§7[group] {value} -> {value2} ({blocks} 변형)", - "iris.bukkit.runtime.bulkstructureimporter.skip": "§e[건너뜀] {value}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_4": "§c[실패] {value}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.single_template_structures_built_skipped_failed": "§a단일 템플릿 구조: §f{imported}§a 내장, §f{skipped}§a 건너뛰기, §f{failed}§a 실패.", - "iris.bukkit.runtime.bulkstructureimporter.failed_enumerate_structure_templates_via_server_resourcemanager": "§c서버를 통해 구조 템플릿을 열거 ResourceManager: {e}", - "iris.bukkit.runtime.bulkstructureimporter.no_structure_templates_were_found_under_structure_resource_path": "§e구조 템플릿은 'structure' 리소스 경로에서 찾을 수 없습니다.", - "iris.bukkit.runtime.bulkstructureimporter.importing_structure_templates_mode": "§a관련 상품 §f{total}§a 구조 템플릿 (mode={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_2": "§c[실패] {keyString}: 잘못된 키", - "iris.bukkit.runtime.bulkstructureimporter.fail_5": "§c[실패] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_6": "§c[실패] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.imported_skipped_failed": "§7...{processed}/{total} (가져옴 {imported}, 건너뜀 {skipped}, 실패 {failed})", - "iris.bukkit.runtime.bulkstructureimporter.template_import_complete_imported_skipped_failed_total": "§a템플릿 가져오기 완료: §f{imported}§a개 가져옴, §f{skipped}§a개 건너뜀, §f{failed}§a개 실패(전체 §f{total}§a개).", - "iris.bukkit.runtime.bulkstructureimporter.no_datapack_non_minecraft_structures_are_registered_ingest_datapack_restart_first_then": "§e등록된 datapack(non-minecraft) 구조물이 없습니다. 먼저 datapack을 수집하고 재시작한 다음 이 명령을 다시 실행하세요.", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structures_mode": "§a관련 상품 §f{total}§a datapack 구조 (mode={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_3": "§c[실패] {keyString}: 잘못된 키", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw_2": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single_2": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.fail_7": "§c[실패] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_8": "§c[실패] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_9": "§c[실패] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structure_templates": "§a관련 상품 §f{size}§a datapack 구조 템플릿...", - "iris.bukkit.runtime.bulkstructureimporter.fail_10": "§c[실패] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_11": "§c[실패] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.could_not_enumerate_datapack_templates_via_server_resourcemanager": "§e서버를 통해 datapack 템플릿을 열거 할 수 없습니다. ResourceManager: {error}", - "iris.bukkit.runtime.bulkstructureimporter.datapack_structure_import_complete_imported_skipped_failed": "§a데이터 팩 구조물 가져오기 완료: §f{imported}§a개 가져옴, §f{skipped}§a개 건너뜀, §f{failed}§a개 실패.", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_is_not_supported_by_active_nms_binding_skipping_capture_pass": "§eStructure 캡처는 활성에서 지원되지 않습니다. NMS 바인딩; 캡처 패스를 건너.", - "iris.bukkit.runtime.structurecaptureimporter.no_code_generated_structures_left_capture_everything_is_already_imported_as_structure": "§7캡처할 코드 생성 구조물이 없습니다(모두 이미 구조물로 가져왔습니다).", - "iris.bukkit.runtime.structurecaptureimporter.capturing_code_generated_structures_no_nbt_template_into_scratch_world_skipping_any": "§a코드 생성 구조물 §f{total}§a개(NBT 템플릿 없음)를 임시 세계에 캡처하는 중({MAXSPAN}블록보다 너비/높이가 큰 항목은 건너뜀)...", - "iris.bukkit.runtime.structurecaptureimporter.skip_did_not_place_capturable_structure_here_too_large_wrong_dimension_no": "§e[건너뜀] {key}: 여기에 캡처 가능 구조를 배치하지 않았다 (큰, 잘못된 차원 또는 평평한 세계에 유효한 배치 없음). 숙박 약관", - "iris.bukkit.runtime.structurecaptureimporter.fail": "§c[실패] {key}: {message}", - "iris.bukkit.runtime.structurecaptureimporter.capture_objects_iob_x_x": "§7[캡처] {key} -> objects/{name}.iob ({w}x{h}x{d})", - "iris.bukkit.runtime.structurecaptureimporter.fail_2": "§c[실패] {key}: {error}", - "iris.bukkit.runtime.structurecaptureimporter.captured_skipped_failed": "§7...{processed}/{total} ({imported} 캡처, {skipped} 건너뛰기, {failed} 실패)", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_complete_captured_skipped_failed_total": "§a구조 캡처 완료: §f{imported}§a 캡처, §f{skipped}§a 건너뛰기, §f{failed}§a 실패 (§f{total}§a 전체).", "iris.bukkit.runtime.featureimporter.no_vanilla_tree_object_features_are_exposed_by_active_nms_binding_importing": "§e활성 NMS 바인딩이 노출하는 vanilla 트리/객체 기능이 없습니다(구조물만 가져옵니다).", "iris.bukkit.runtime.featureimporter.importing_vanilla_tree_object_features_variants_each_into_scratch_world": "§a관련 상품 §f{total}§a 바닐라 트리/부드 기능 (§f{wantVariants}§a 변형) 스크래치 세계로...", "iris.bukkit.runtime.featureimporter.obj_objects_vanilla": "§7[obj] {key} -> objects/vanilla/{group}/{safeName} ({written})", diff --git a/core/src/main/resources/languages/lt_LT.json b/core/src/main/resources/languages/lt_LT.json index 8f0e6a4a0..756674a03 100644 --- a/core/src/main/resources/languages/lt_LT.json +++ b/core/src/main/resources/languages/lt_LT.json @@ -1008,50 +1008,6 @@ "§cKai suprantate riziką ir turite atsarginę kopiją:", "§c/iris developer update-world {world} {pack} confirm=true" ], - "iris.bukkit.runtime.bulkstructureimporter.importing_vanilla_datapack_structures_mode_includenonjigsaw": "§aImportuojama §f{total}§a vanilla & duomenų kaupimo struktūros (režimas ={mode}, includeNonJigsaw={includeNonJigsaw})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key": "§c[klaida] {keyString}: neteisingas raktas", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.skip_no_single_template_nbt_vanilla_builds_this_code_from_separate_piece": "§e[praleista] {keyString}: nėra vieno šablono NBT - vanilla stato šį kodą arba iš atskirų dalių šablonus (importuoti per šablonų praeiti); nieko importuoti kaip vieną struktūrą.", - "iris.bukkit.runtime.bulkstructureimporter.fail": "§c[klaida] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_2": "§c[klaida] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_3": "§c[klaida] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.bulk_import_complete_imported_skipped_failed_total": "§aNesupakuotų prekių importas baigtas: §f{imported}§a importuotos, §f{skipped}§a praleista, §f{failed}§a nepavyko (§f{total}§a iš viso).", - "iris.bukkit.runtime.bulkstructureimporter.building_single_template_structures_from_imported_pieces_one_variant_placed_per_generation": "§aPastato vieno šablono struktūros iš importuotų vienetų (po vieną variantą kiekvienai kartai)...", - "iris.bukkit.runtime.bulkstructureimporter.group_variants": "§7[group] {value} -> {value2} ({blocks} variantai)", - "iris.bukkit.runtime.bulkstructureimporter.skip": "§e[praleista] {value}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_4": "§c[klaida] {value}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.single_template_structures_built_skipped_failed": "§aVieno šablono struktūros: §f{imported}§a pastatytas, §f{skipped}§a praleista, §f{failed}§a Nepavyko.", - "iris.bukkit.runtime.bulkstructureimporter.failed_enumerate_structure_templates_via_server_resourcemanager": "§cNepavyko surašyti struktūros šablonų per serverį ResourceManager: {e}", - "iris.bukkit.runtime.bulkstructureimporter.no_structure_templates_were_found_under_structure_resource_path": "§eIšteklių kelyje \"struktūra\" nerasta struktūros šablonų.", - "iris.bukkit.runtime.bulkstructureimporter.importing_structure_templates_mode": "§aImportuojama §f{total}§a struktūros šablonai (režimas ={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_2": "§c[klaida] {keyString}: neteisingas raktas", - "iris.bukkit.runtime.bulkstructureimporter.fail_5": "§c[klaida] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_6": "§c[klaida] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.imported_skipped_failed": "§7...{processed}/{total} ({imported} importuotos, {skipped} praleista, {failed} nepavyko)", - "iris.bukkit.runtime.bulkstructureimporter.template_import_complete_imported_skipped_failed_total": "§a@ info: tooltip §f{imported}§a importuotos, §f{skipped}§a praleista, §f{failed}§a nepavyko (§f{total}§a iš viso).", - "iris.bukkit.runtime.bulkstructureimporter.no_datapack_non_minecraft_structures_are_registered_ingest_datapack_restart_first_then": "§eNeregistruojamos jokios duomenų saugyklos (ne- mikrofonas) struktūros. Paskutinis duomenų ir iš naujo pirmą kartą, tada paleisti tai dar kartą.", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structures_mode": "§aImportuojama §f{total}§a duomenų kaupimo struktūros (režimas ={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_3": "§c[klaida] {keyString}: neteisingas raktas", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw_2": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single_2": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.fail_7": "§c[klaida] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_8": "§c[klaida] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_9": "§c[klaida] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structure_templates": "§aImportuojama §f{size}§a duomenų rinkinio struktūros šablonai...", - "iris.bukkit.runtime.bulkstructureimporter.fail_10": "§c[klaida] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_11": "§c[klaida] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.could_not_enumerate_datapack_templates_via_server_resourcemanager": "§eNepavyko per serverį surašyti datapack šablonų ResourceManager: {error}", - "iris.bukkit.runtime.bulkstructureimporter.datapack_structure_import_complete_imported_skipped_failed": "§aDatapack struktūros importas baigtas: §f{imported}§a importuotos, §f{skipped}§a praleista, §f{failed}§a Nepavyko.", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_is_not_supported_by_active_nms_binding_skipping_capture_pass": "§eStruktūros fiksavimas nepalaikomas aktyviu NMS privalomas; praleidžia surinkimo praeiti.", - "iris.bukkit.runtime.structurecaptureimporter.no_code_generated_structures_left_capture_everything_is_already_imported_as_structure": "§7Nėra kogeneracinių struktūrų, kurias būtų galima užfiksuoti (viskas jau importuojama kaip struktūra).", - "iris.bukkit.runtime.structurecaptureimporter.capturing_code_generated_structures_no_nbt_template_into_scratch_world_skipping_any": "§aGaudymas §f{total}§a koduoti sukurti statiniai (ne NBT šabloną) į įbrėžimų pasaulyje (praleisti bet platesnę / aukštesnę nei {MAXSPAN} blokai)...", - "iris.bukkit.runtime.structurecaptureimporter.skip_did_not_place_capturable_structure_here_too_large_wrong_dimension_no": "§e[praleista] {key}: nepadėjo apkabinama struktūra čia (per didelis, neteisingas dimensija, arba nėra tinkamas išdėstymas plokščiame pasaulyje). Status vanilla-generated.", - "iris.bukkit.runtime.structurecaptureimporter.fail": "§c[klaida] {key}: {message}", - "iris.bukkit.runtime.structurecaptureimporter.capture_objects_iob_x_x": "§7[capture] {key} -> objects/{name}.iob ({w}x{h}x{d})", - "iris.bukkit.runtime.structurecaptureimporter.fail_2": "§c[klaida] {key}: {error}", - "iris.bukkit.runtime.structurecaptureimporter.captured_skipped_failed": "§7...{processed}/{total} ({imported} užfiksuoti, {skipped} praleista, {failed} nepavyko)", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_complete_captured_skipped_failed_total": "§aStruktūros fiksavimas baigtas: §f{imported}§a užfiksuoti, §f{skipped}§a praleista, §f{failed}§a nepavyko (§f{total}§a iš viso).", "iris.bukkit.runtime.featureimporter.no_vanilla_tree_object_features_are_exposed_by_active_nms_binding_importing": "§eAktyvusis neturi vanilla medžio / objekto savybių NMS privalomas (tik importuojančios struktūros).", "iris.bukkit.runtime.featureimporter.importing_vanilla_tree_object_features_variants_each_into_scratch_world": "§aImportuojama §f{total}§a vanilla medžio / objekto ypatybės (§f{wantVariants}§a variantų kiekvienas) į įbrėžimų pasaulyje...", "iris.bukkit.runtime.featureimporter.obj_objects_vanilla": "§7[obj] {key} -> objects/vanilla/{group}/{safeName} ({written})", diff --git a/core/src/main/resources/languages/nl_NL.json b/core/src/main/resources/languages/nl_NL.json index 890b3e5f1..7670dc702 100644 --- a/core/src/main/resources/languages/nl_NL.json +++ b/core/src/main/resources/languages/nl_NL.json @@ -1008,50 +1008,6 @@ "§cWanneer je de risico's begrijpt en een back-up hebt gemaakt:", "§c/iris developer update-world {world} {pack} confirm=true" ], - "iris.bukkit.runtime.bulkstructureimporter.importing_vanilla_datapack_structures_mode_includenonjigsaw": "§aImporteren §f{total}§a vanilla & datapack structuren (mode={mode}, includeNonJigsaw={includeNonJigsaw})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key": "§c[fout] {keyString}: ongeldige sleutel", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.skip_no_single_template_nbt_vanilla_builds_this_code_from_separate_piece": "§e[overgeslagen] {keyString}: geen enkel template NBT - vanilla bouwt dit in code of uit afzonderlijke stuk templates (geïmporteerd via de sjablonen pas); niets te importeren als één structuur.", - "iris.bukkit.runtime.bulkstructureimporter.fail": "§c[fout] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_2": "§c[fout] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_3": "§c[fout] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.bulk_import_complete_imported_skipped_failed_total": "§aBulkinvoer voltooid: §f{imported}§a ingevoerd, §f{skipped}§a overgeslagen, §f{failed}§a mislukt (§f{total}§a Totaal).", - "iris.bukkit.runtime.bulkstructureimporter.building_single_template_structures_from_imported_pieces_one_variant_placed_per_generation": "§aBouwen van enkelwandige structuren uit geïmporteerde stukken (één variant geplaatst per generatie)...", - "iris.bukkit.runtime.bulkstructureimporter.group_variants": "§7[group] {value} -> {value2} ({blocks} varianten)", - "iris.bukkit.runtime.bulkstructureimporter.skip": "§e[overgeslagen] {value}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_4": "§c[fout] {value}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.single_template_structures_built_skipped_failed": "§aéénplaatconstructies: §f{imported}§a gebouwd, §f{skipped}§a overgeslagen, §f{failed}§a mislukt.", - "iris.bukkit.runtime.bulkstructureimporter.failed_enumerate_structure_templates_via_server_resourcemanager": "§cOpsomming van structuursjablonen via de server mislukt ResourceManager: {e}", - "iris.bukkit.runtime.bulkstructureimporter.no_structure_templates_were_found_under_structure_resource_path": "§eEr werden geen structuursjablonen gevonden onder het 'structure' resource pad.", - "iris.bukkit.runtime.bulkstructureimporter.importing_structure_templates_mode": "§aImporteren §f{total}§a structuursjablonen (modus={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_2": "§c[fout] {keyString}: ongeldige sleutel", - "iris.bukkit.runtime.bulkstructureimporter.fail_5": "§c[fout] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_6": "§c[fout] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.imported_skipped_failed": "§7...{processed}/{total} ({imported} ingevoerd, {skipped} overgeslagen, {failed} faalde)", - "iris.bukkit.runtime.bulkstructureimporter.template_import_complete_imported_skipped_failed_total": "§aSjabloon importeren voltooid: §f{imported}§a ingevoerd, §f{skipped}§a overgeslagen, §f{failed}§a mislukt (§f{total}§a Totaal).", - "iris.bukkit.runtime.bulkstructureimporter.no_datapack_non_minecraft_structures_are_registered_ingest_datapack_restart_first_then": "§eEr zijn geen datapack (niet-mijnbouw) structuren geregistreerd. Installeer eerst een datapack en start dit opnieuw op.", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structures_mode": "§aImporteren §f{total}§a datapack structuren (mode={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_3": "§c[fout] {keyString}: ongeldige sleutel", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw_2": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single_2": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.fail_7": "§c[fout] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_8": "§c[fout] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_9": "§c[fout] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structure_templates": "§aImporteren §f{size}§a templates voor gegevenspackstructuur...", - "iris.bukkit.runtime.bulkstructureimporter.fail_10": "§c[fout] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_11": "§c[fout] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.could_not_enumerate_datapack_templates_via_server_resourcemanager": "§eKon datapack sjablonen niet opnoemen via de server ResourceManager: {error}", - "iris.bukkit.runtime.bulkstructureimporter.datapack_structure_import_complete_imported_skipped_failed": "§aDatapack structuur import voltooid: §f{imported}§a ingevoerd, §f{skipped}§a overgeslagen, §f{failed}§a mislukt.", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_is_not_supported_by_active_nms_binding_skipping_capture_pass": "§eStructuur capture wordt niet ondersteund door de actieve NMS binding; de vangstpas overslaan.", - "iris.bukkit.runtime.structurecaptureimporter.no_code_generated_structures_left_capture_everything_is_already_imported_as_structure": "§7Geen code-gegenereerde structuren meer te vangen (alles is al als structuur geïmporteerd).", - "iris.bukkit.runtime.structurecaptureimporter.capturing_code_generated_structures_no_nbt_template_into_scratch_world_skipping_any": "§aVangen §f{total}§a code-gegenereerde structuren (geen NBT sjabloon) in een kraswereld (een breder/vertaler overslaan dan {MAXSPAN} blokken)...", - "iris.bukkit.runtime.structurecaptureimporter.skip_did_not_place_capturable_structure_here_too_large_wrong_dimension_no": "§e[overgeslagen] {key}: heeft hier geen captureerbare structuur geplaatst (te groot, verkeerde dimensie of geen geldige plaatsing in een platte wereld). Blijft vanilla gegenereerd.", - "iris.bukkit.runtime.structurecaptureimporter.fail": "§c[fout] {key}: {message}", - "iris.bukkit.runtime.structurecaptureimporter.capture_objects_iob_x_x": "§7[capture] {key} -> objects/{name}.iob ({w}x{h}x{d})", - "iris.bukkit.runtime.structurecaptureimporter.fail_2": "§c[fout] {key}: {error}", - "iris.bukkit.runtime.structurecaptureimporter.captured_skipped_failed": "§7...{processed}/{total} ({imported} gevangen, {skipped} overgeslagen, {failed} faalde)", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_complete_captured_skipped_failed_total": "§aStructuuropvang voltooid: §f{imported}§a gevangen, §f{skipped}§a overgeslagen, §f{failed}§a mislukt (§f{total}§a Totaal).", "iris.bukkit.runtime.featureimporter.no_vanilla_tree_object_features_are_exposed_by_active_nms_binding_importing": "§eGeen vanillaboom/object eigenschappen worden blootgesteld door de actieve NMS binding (alleen invoerstructuren).", "iris.bukkit.runtime.featureimporter.importing_vanilla_tree_object_features_variants_each_into_scratch_world": "§aImporteren §f{total}§a vanillaboom/objectkenmerken (§f{wantVariants}§a varianten elk) in een kraswereld...", "iris.bukkit.runtime.featureimporter.obj_objects_vanilla": "§7[obj] {key} -> objects/vanilla/{group}/{safeName} ({written})", diff --git a/core/src/main/resources/languages/pl_PL.json b/core/src/main/resources/languages/pl_PL.json index fddcc9ff4..3e2098b25 100644 --- a/core/src/main/resources/languages/pl_PL.json +++ b/core/src/main/resources/languages/pl_PL.json @@ -1008,50 +1008,6 @@ "§cGdy rozumiesz ryzyko i masz wykonaną kopię zapasową:", "§c/iris developer update-world {world} {pack} confirm=true" ], - "iris.bukkit.runtime.bulkstructureimporter.importing_vanilla_datapack_structures_mode_includenonjigsaw": "§aPrzywóz §f{total}§a vanilla & struktury datapack (tryb ={mode}, includeNonJigsaw={includeNonJigsaw})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key": "§c[błąd] {keyString}: nieprawidłowy klucz", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.skip_no_single_template_nbt_vanilla_builds_this_code_from_separate_piece": "§e[pominiędo] {keyString}: brak pojedynczego szablonu NBT - vanilla buduje do w kodzie lub z osobnych szablonów (importowanych za pomocą przejścia szablonu); nic do importu jako jedna struktura.", - "iris.bukkit.runtime.bulkstructureimporter.fail": "§c[błąd] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_2": "§c[błąd] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_3": "§c[błąd] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.bulk_import_complete_imported_skipped_failed_total": "§aImport luzem zakończony: §f{imported}§a przywożone, §f{skipped}§a pominięte, §f{failed}§a nieudany (§f{total}§a ogółem).", - "iris.bukkit.runtime.bulkstructureimporter.building_single_template_structures_from_imported_pieces_one_variant_placed_per_generation": "§aBudownictwo jedno- szablonów konstrukcji z importowanych sztuk (jeden wariant umieszczony na pokolenie)...", - "iris.bukkit.runtime.bulkstructureimporter.group_variants": "§7[group] {value} -> {value2} ({blocks} warianty)", - "iris.bukkit.runtime.bulkstructureimporter.skip": "§e[pominięto] {value}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_4": "§c[błąd] {value}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.single_template_structures_built_skipped_failed": "§aStruktura pojedynczego szablonu: §f{imported}§a zbudowany, §f{skipped}§a pominięte, §f{failed}§a Nie udało się.", - "iris.bukkit.runtime.bulkstructureimporter.failed_enumerate_structure_templates_via_server_resourcemanager": "§cNie udało się zapisać szablonów struktury za pośrednictwem serwera ResourceManager: {e}", - "iris.bukkit.runtime.bulkstructureimporter.no_structure_templates_were_found_under_structure_resource_path": "§eNie znaleziono żadnych szablonów struktury w ścieżce zasobów \"struktura\".", - "iris.bukkit.runtime.bulkstructureimporter.importing_structure_templates_mode": "§aPrzywóz §f{total}§a szablony struktury (tryb ={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_2": "§c[błąd] {keyString}: nieprawidłowy klucz", - "iris.bukkit.runtime.bulkstructureimporter.fail_5": "§c[błąd] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_6": "§c[błąd] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.imported_skipped_failed": "§7...{processed}/{total} ({imported} przywożone, {skipped} pominięte, {failed} nieudany)", - "iris.bukkit.runtime.bulkstructureimporter.template_import_complete_imported_skipped_failed_total": "§aImport szablonu zakończony: §f{imported}§a przywożone, §f{skipped}§a pominięte, §f{failed}§a nieudany (§f{total}§a ogółem).", - "iris.bukkit.runtime.bulkstructureimporter.no_datapack_non_minecraft_structures_are_registered_ingest_datapack_restart_first_then": "§eNie rejestruje się żadnych struktur datapack (nieminecraft). Zainwestuj datapack i uruchom ponownie, a następnie uruchom to jeszcze raz.", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structures_mode": "§aPrzywóz §f{total}§a struktury datapack (tryb ={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_3": "§c[błąd] {keyString}: nieprawidłowy klucz", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw_2": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single_2": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.fail_7": "§c[błąd] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_8": "§c[błąd] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_9": "§c[błąd] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structure_templates": "§aPrzywóz §f{size}§a szablony struktury datapack...", - "iris.bukkit.runtime.bulkstructureimporter.fail_10": "§c[błąd] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_11": "§c[błąd] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.could_not_enumerate_datapack_templates_via_server_resourcemanager": "§eNie można zapisać szablonów datapack za pośrednictwem serwera ResourceManager: {error}", - "iris.bukkit.runtime.bulkstructureimporter.datapack_structure_import_complete_imported_skipped_failed": "§aZaimportowanie struktury Datapack zakończone: §f{imported}§a przywożone, §f{skipped}§a pominięte, §f{failed}§a Nie udało się.", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_is_not_supported_by_active_nms_binding_skipping_capture_pass": "§eUchwyt struktury nie jest obsługiwany przez aktywny NMS ominąć przepustkę.", - "iris.bukkit.runtime.structurecaptureimporter.no_code_generated_structures_left_capture_everything_is_already_imported_as_structure": "§7Nie ma struktur generowanych przez kod do wychwytywania (wszystko jest już importowane jako struktura).", - "iris.bukkit.runtime.structurecaptureimporter.capturing_code_generated_structures_no_nbt_template_into_scratch_world_skipping_any": "§aChwytanie §f{total}§a Konstrukcje generowane kodowo (nie NBT szablon) do świata zarysowań (pomijając szersze / wyższe niż {MAXSPAN} bloki)...", - "iris.bukkit.runtime.structurecaptureimporter.skip_did_not_place_capturable_structure_here_too_large_wrong_dimension_no": "§e[pominięto] {key}: nie umieścił tutaj struktury uchwytnej (zbyt duży, zły wymiar lub brak poprawnego umieszczenia w płaskim świecie). Stays vanilla-generowane.", - "iris.bukkit.runtime.structurecaptureimporter.fail": "§c[błąd] {key}: {message}", - "iris.bukkit.runtime.structurecaptureimporter.capture_objects_iob_x_x": "§7[capture] {key} -> objects/{name}.iob ({w}x{h}x{d})", - "iris.bukkit.runtime.structurecaptureimporter.fail_2": "§c[błąd] {key}: {error}", - "iris.bukkit.runtime.structurecaptureimporter.captured_skipped_failed": "§7...{processed}/{total} ({imported} schwytany, {skipped} pominięte, {failed} nieudany)", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_complete_captured_skipped_failed_total": "§aUchwyt struktury zakończony: §f{imported}§a schwytany, §f{skipped}§a pominięte, §f{failed}§a nieudany (§f{total}§a ogółem).", "iris.bukkit.runtime.featureimporter.no_vanilla_tree_object_features_are_exposed_by_active_nms_binding_importing": "§eŻadne drzewo vanilla / obiekt nie są narażone przez aktywny NMS wiążące (tylko struktury przywozu).", "iris.bukkit.runtime.featureimporter.importing_vanilla_tree_object_features_variants_each_into_scratch_world": "§aPrzywóz §f{total}§a funkcje drzewa vanillago / obiektu (§f{wantVariants}§a warianty każdy) w świat zadrapania...", "iris.bukkit.runtime.featureimporter.obj_objects_vanilla": "§7[obj] {key} -> objects/vanilla/{group}/{safeName} ({written})", diff --git a/core/src/main/resources/languages/pt_PT.json b/core/src/main/resources/languages/pt_PT.json index 16b7261d7..8ed6152c7 100644 --- a/core/src/main/resources/languages/pt_PT.json +++ b/core/src/main/resources/languages/pt_PT.json @@ -1008,50 +1008,6 @@ "§cQuando compreender os riscos e tiver criado uma cópia de segurança:", "§c/iris developer update-world {world} {pack} confirm=true" ], - "iris.bukkit.runtime.bulkstructureimporter.importing_vanilla_datapack_structures_mode_includenonjigsaw": "§aImportação §f{total}§a vanilla & estruturas do pacote de dados (modo={mode}, includeNonJigsaw={includeNonJigsaw})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key": "§c[falha] {keyString}: chave inválida", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.skip_no_single_template_nbt_vanilla_builds_this_code_from_separate_piece": "§e[ignorado] {keyString}: não template único NBT - vanilla constrói isso em código ou a partir de modelos separados (importados através dos modelos passam); nada a importar como uma estrutura.", - "iris.bukkit.runtime.bulkstructureimporter.fail": "§c[falha] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_2": "§c[falha] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_3": "§c[falha] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.bulk_import_complete_imported_skipped_failed_total": "§aImportação em massa concluída: §f{imported}§a importadas, §f{skipped}§a Saltou, §f{failed}§a falhou (§f{total}§a total)", - "iris.bukkit.runtime.bulkstructureimporter.building_single_template_structures_from_imported_pieces_one_variant_placed_per_generation": "§aConstrução de estruturas monotempladas a partir de peças importadas (uma variante colocada por geração)...", - "iris.bukkit.runtime.bulkstructureimporter.group_variants": "§7[group] {value} -> {value2} ({blocks} variantes)", - "iris.bukkit.runtime.bulkstructureimporter.skip": "§e[ignorado] {value}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_4": "§c[falha] {value}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.single_template_structures_built_skipped_failed": "§aEstruturas monotempladas: §f{imported}§a construído, §f{skipped}§a Saltou, §f{failed}§a falhou.", - "iris.bukkit.runtime.bulkstructureimporter.failed_enumerate_structure_templates_via_server_resourcemanager": "§cFalha ao enumerar modelos de estrutura através do servidor ResourceManager: {e}", - "iris.bukkit.runtime.bulkstructureimporter.no_structure_templates_were_found_under_structure_resource_path": "§eNão foram encontrados modelos de estrutura no caminho do recurso 'estrutura'.", - "iris.bukkit.runtime.bulkstructureimporter.importing_structure_templates_mode": "§aImportação §f{total}§a modelos de estrutura (modo={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_2": "§c[falha] {keyString}: chave inválida", - "iris.bukkit.runtime.bulkstructureimporter.fail_5": "§c[falha] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_6": "§c[falha] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.imported_skipped_failed": "§7...{processed}/{total} ({imported} importadas, {skipped} Saltou, {failed} falhou)", - "iris.bukkit.runtime.bulkstructureimporter.template_import_complete_imported_skipped_failed_total": "§aImportação do modelo concluída: §f{imported}§a importadas, §f{skipped}§a Saltou, §f{failed}§a falhou (§f{total}§a total)", - "iris.bukkit.runtime.bulkstructureimporter.no_datapack_non_minecraft_structures_are_registered_ingest_datapack_restart_first_then": "§eNão estão registadas estruturas de datapack (não-minecraft). Ingera um pacote de dados e reinicie primeiro, depois execute isto novamente.", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structures_mode": "§aImportação §f{total}§a estruturas do pacote de dados (modo={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_3": "§c[falha] {keyString}: chave inválida", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw_2": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single_2": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.fail_7": "§c[falha] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_8": "§c[falha] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_9": "§c[falha] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structure_templates": "§aImportação §f{size}§a modelos de estrutura do datapack...", - "iris.bukkit.runtime.bulkstructureimporter.fail_10": "§c[falha] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_11": "§c[falha] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.could_not_enumerate_datapack_templates_via_server_resourcemanager": "§eNão foi possível enumerar modelos de datapack através do servidor ResourceManager: {error}", - "iris.bukkit.runtime.bulkstructureimporter.datapack_structure_import_complete_imported_skipped_failed": "§aImportação da estrutura do pacote de dados completa: §f{imported}§a importadas, §f{skipped}§a Saltou, §f{failed}§a falhou.", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_is_not_supported_by_active_nms_binding_skipping_capture_pass": "§eA captura da estrutura não é suportada pelo ativo NMS ending; pulando o passe de captura.", - "iris.bukkit.runtime.structurecaptureimporter.no_code_generated_structures_left_capture_everything_is_already_imported_as_structure": "§7Não restam estruturas geradas por código para capturar (tudo já é importado como uma estrutura).", - "iris.bukkit.runtime.structurecaptureimporter.capturing_code_generated_structures_no_nbt_template_into_scratch_world_skipping_any": "§aCaptura §f{total}§a estruturas geradas por código (não NBT template) em um mundo de arranhões (spipping qualquer maior / mais alto do que {MAXSPAN} blocos)...", - "iris.bukkit.runtime.structurecaptureimporter.skip_did_not_place_capturable_structure_here_too_large_wrong_dimension_no": "§e[ignorado] {key}: não colocou uma estrutura capturável aqui (dimensão demasiado grande, errada, ou nenhuma colocação válida em um mundo plano). Continua a gerar vanilla.", - "iris.bukkit.runtime.structurecaptureimporter.fail": "§c[falha] {key}: {message}", - "iris.bukkit.runtime.structurecaptureimporter.capture_objects_iob_x_x": "§7[capture] {key} -> objects/{name}.iob ({w}x{h}x{d})", - "iris.bukkit.runtime.structurecaptureimporter.fail_2": "§c[falha] {key}: {error}", - "iris.bukkit.runtime.structurecaptureimporter.captured_skipped_failed": "§7...{processed}/{total} ({imported} capturados, {skipped} Saltou, {failed} falhou)", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_complete_captured_skipped_failed_total": "§aCaptura de estrutura completa: §f{imported}§a capturados, §f{skipped}§a Saltou, §f{failed}§a falhou (§f{total}§a total)", "iris.bukkit.runtime.featureimporter.no_vanilla_tree_object_features_are_exposed_by_active_nms_binding_importing": "§eNenhuma característica de vanilla/objeto é exposta pelo ativo NMS ligação (apenas estruturas de importação).", "iris.bukkit.runtime.featureimporter.importing_vanilla_tree_object_features_variants_each_into_scratch_world": "§aImportação §f{total}§a características da árvore de vanilla/objecto (§f{wantVariants}§a variantes cada) em um mundo arranhado...", "iris.bukkit.runtime.featureimporter.obj_objects_vanilla": "§7[obj] {key} -> objects/vanilla/{group}/{safeName} ({written})", diff --git a/core/src/main/resources/languages/ru_RU.json b/core/src/main/resources/languages/ru_RU.json index 1d3b7bb98..da430174a 100644 --- a/core/src/main/resources/languages/ru_RU.json +++ b/core/src/main/resources/languages/ru_RU.json @@ -1008,50 +1008,6 @@ "§cКогда вы понимаете риски и создали резервную копию:", "§c/iris developer update-world {world} {pack} confirm=true" ], - "iris.bukkit.runtime.bulkstructureimporter.importing_vanilla_datapack_structures_mode_includenonjigsaw": "§aимпортировать §f{total}§a vanilla & структуры пакета данных (режим ={mode}, includeNonJigsaw={includeNonJigsaw})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key": "§c[ошибка] {keyString}Недействительный ключ", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.skip_no_single_template_nbt_vanilla_builds_this_code_from_separate_piece": "§e[пропуск] {keyString}Нет единого шаблона NBT Ваниль строит это в коде или из отдельных шаблонов (импортируется через проход шаблонов); ничего не импортировать как одну структуру.", - "iris.bukkit.runtime.bulkstructureimporter.fail": "§c[ошибка] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_2": "§c[ошибка] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_3": "§c[ошибка] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.bulk_import_complete_imported_skipped_failed_total": "§aПолный импорт: §f{imported}§a импортный, §f{skipped}§a пропущенный, §f{failed}§a не удалось (§f{total}§a Всего).", - "iris.bukkit.runtime.bulkstructureimporter.building_single_template_structures_from_imported_pieces_one_variant_placed_per_generation": "§aСтроительство одношаблонных конструкций из импортных деталей (один вариант размещается на поколение)...", - "iris.bukkit.runtime.bulkstructureimporter.group_variants": "§7[группа] {value} -> {value2} ({blocks} варианты)", - "iris.bukkit.runtime.bulkstructureimporter.skip": "§e[пропуск] {value}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_4": "§c[ошибка] {value}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.single_template_structures_built_skipped_failed": "§aОдношаблонные структуры: §f{imported}§a построенный, §f{skipped}§a пропущенный, §f{failed}§a провалился.", - "iris.bukkit.runtime.bulkstructureimporter.failed_enumerate_structure_templates_via_server_resourcemanager": "§cНе удалось перечислить шаблоны структуры через сервер ResourceManager: {e}", - "iris.bukkit.runtime.bulkstructureimporter.no_structure_templates_were_found_under_structure_resource_path": "§eПод «структурным» ресурсным путем не было найдено шаблонов структуры.", - "iris.bukkit.runtime.bulkstructureimporter.importing_structure_templates_mode": "§aимпортировать §f{total}§a Структурные шаблоны (режим ={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_2": "§c[ошибка] {keyString}Недействительный ключ", - "iris.bukkit.runtime.bulkstructureimporter.fail_5": "§c[ошибка] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_6": "§c[ошибка] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.imported_skipped_failed": "§7...{processed}/{total} ({imported} импортный, {skipped} пропущенный, {failed} не удалось)", - "iris.bukkit.runtime.bulkstructureimporter.template_import_complete_imported_skipped_failed_total": "§aПолный импорт шаблонов: §f{imported}§a импортный, §f{skipped}§a пропущенный, §f{failed}§a не удалось (§f{total}§a Всего).", - "iris.bukkit.runtime.bulkstructureimporter.no_datapack_non_minecraft_structures_are_registered_ingest_datapack_restart_first_then": "§eСтруктуры datapack (non-minecraft) не зарегистрированы. Сначала загрузите datapack и перезапустите сервер, затем выполните команду снова.", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structures_mode": "§aимпортировать §f{total}§a структуры пакета данных (режим ={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_3": "§c[ошибка] {keyString}Недействительный ключ", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw_2": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single_2": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.fail_7": "§c[ошибка] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_8": "§c[ошибка] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_9": "§c[ошибка] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structure_templates": "§aимпортировать §f{size}§a шаблоны структуры пакета данных...", - "iris.bukkit.runtime.bulkstructureimporter.fail_10": "§c[ошибка] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_11": "§c[ошибка] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.could_not_enumerate_datapack_templates_via_server_resourcemanager": "§eНевозможно перечислить шаблоны пакетов данных через сервер ResourceManager: {error}", - "iris.bukkit.runtime.bulkstructureimporter.datapack_structure_import_complete_imported_skipped_failed": "§aИмпорт структуры пакета данных завершен: §f{imported}§a импортный, §f{skipped}§a пропущенный, §f{failed}§a провалился.", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_is_not_supported_by_active_nms_binding_skipping_capture_pass": "§eЗахват структуры не поддерживается активным NMS переплетение; пропуск прохода захвата.", - "iris.bukkit.runtime.structurecaptureimporter.no_code_generated_structures_left_capture_everything_is_already_imported_as_structure": "§7Никаких кодовых структур не осталось для захвата (все уже импортировано как структура).", - "iris.bukkit.runtime.structurecaptureimporter.capturing_code_generated_structures_no_nbt_template_into_scratch_world_skipping_any": "§aзахватывать §f{total}§a кодовые структуры (не NBT Шаблон) в царапина мир (пропуск любой шире / тише, чем {MAXSPAN} блоки)...", - "iris.bukkit.runtime.structurecaptureimporter.skip_did_not_place_capturable_structure_here_too_large_wrong_dimension_no": "§e[пропуск] {key}Не помещал здесь захватываемую структуру (слишком большое, неправильное измерение или отсутствие правильного размещения в плоском мире). Остается vanillaным.", - "iris.bukkit.runtime.structurecaptureimporter.fail": "§c[ошибка] {key}: {message}", - "iris.bukkit.runtime.structurecaptureimporter.capture_objects_iob_x_x": "§7[захват] {key} -> objects/{name}.iob ({w}x{h}x{d})", - "iris.bukkit.runtime.structurecaptureimporter.fail_2": "§c[ошибка] {key}: {error}", - "iris.bukkit.runtime.structurecaptureimporter.captured_skipped_failed": "§7...{processed}/{total} ({imported} захваченный, {skipped} пропущенный, {failed} не удалось)", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_complete_captured_skipped_failed_total": "§aСтруктура захвата полная: §f{imported}§a захваченный, §f{skipped}§a пропущенный, §f{failed}§a не удалось (§f{total}§a Всего).", "iris.bukkit.runtime.featureimporter.no_vanilla_tree_object_features_are_exposed_by_active_nms_binding_importing": "§eНи одно vanillaное дерево / объект не подвергается воздействию активного NMS Связывание (только импортные структуры).", "iris.bukkit.runtime.featureimporter.importing_vanilla_tree_object_features_variants_each_into_scratch_world": "§aимпортировать §f{total}§a vanillaное дерево/объектные особенности (§f{wantVariants}§a Варианты каждый) в царапина мир...", "iris.bukkit.runtime.featureimporter.obj_objects_vanilla": "§7[obj] {key} -> objects/vanilla/{group}/{safeName} ({written})", diff --git a/core/src/main/resources/languages/tr_TR.json b/core/src/main/resources/languages/tr_TR.json index ae7b3d832..b048bc511 100644 --- a/core/src/main/resources/languages/tr_TR.json +++ b/core/src/main/resources/languages/tr_TR.json @@ -1008,50 +1008,6 @@ "§cRiskleri anladığınızdan ve yedek aldığınızdan eminseniz:", "§c/iris developer update-world {world} {pack} confirm=true" ], - "iris.bukkit.runtime.bulkstructureimporter.importing_vanilla_datapack_structures_mode_includenonjigsaw": "§aİthalat §f{total}§a vanilla & Datapack yapıları (mode= ={mode}, includeNonJigsaw={includeNonJigsaw})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key": "§c[hata] {keyString}:", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.skip_no_single_template_nbt_vanilla_builds_this_code_from_separate_piece": "§e[atlandı] {keyString}: Tek-template NBT - vanilla bunu kodda ya da ayrı parça şablonlarından inşa eder (Resimler üzerinden transfer edilir); bir yapı olarak ithal etmek için hiçbir şey.", - "iris.bukkit.runtime.bulkstructureimporter.fail": "§c[hata] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_2": "§c[hata] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_3": "§c[hata] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.bulk_import_complete_imported_skipped_failed_total": "§aBulk import tamamlandı: §f{imported}§a ithal, §f{skipped}§a atladı, §f{failed}§a başarısız (§f{total}§a Toplam).", - "iris.bukkit.runtime.bulkstructureimporter.building_single_template_structures_from_imported_pieces_one_variant_placed_per_generation": "§aTek katlı yapılar ithal parçalardan inşa etmek (bir nesile yerleştirilen bir değişken)...", - "iris.bukkit.runtime.bulkstructureimporter.group_variants": "§7[group] {value} -> {value2} ({blocks} varyantlar)", - "iris.bukkit.runtime.bulkstructureimporter.skip": "§e[atlandı] {value}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_4": "§c[hata] {value}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.single_template_structures_built_skipped_failed": "§aSingle-template yapıları: §f{imported}§a inşa edilmiş, §f{skipped}§a atladı, §f{failed}§a başarısız oldu.", - "iris.bukkit.runtime.bulkstructureimporter.failed_enumerate_structure_templates_via_server_resourcemanager": "§csunucu aracılığıyla yapı şablonlarını en aza indirmek için başarısız oldu ResourceManager: {e}", - "iris.bukkit.runtime.bulkstructureimporter.no_structure_templates_were_found_under_structure_resource_path": "§eYapı şablonları ‘yapı’ kaynak yolu altında bulunamadı.", - "iris.bukkit.runtime.bulkstructureimporter.importing_structure_templates_mode": "§aİthalat §f{total}§a Yapı şablonları (mode={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_2": "§c[hata] {keyString}:", - "iris.bukkit.runtime.bulkstructureimporter.fail_5": "§c[hata] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_6": "§c[hata] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.imported_skipped_failed": "§7...{processed}/{total} ({imported} ithal, {skipped} atladı, {failed} başarısız oldu)", - "iris.bukkit.runtime.bulkstructureimporter.template_import_complete_imported_skipped_failed_total": "§aŞablon ithalatı tamamlandı: §f{imported}§a ithal, §f{skipped}§a atladı, §f{failed}§a başarısız (§f{total}§a Toplam).", - "iris.bukkit.runtime.bulkstructureimporter.no_datapack_non_minecraft_structures_are_registered_ingest_datapack_restart_first_then": "§eHiçbir veri paketi (ilk-minecraft) yapılar kayıtlı değildir. Bir veri paketini alın ve ilk önce yeniden başlayın.", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structures_mode": "§aİthalat §f{total}§a Datapack yapıları (mode= ={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_3": "§c[hata] {keyString}:", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw_2": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single_2": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.fail_7": "§c[hata] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_8": "§c[hata] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_9": "§c[hata] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structure_templates": "§aİthalat §f{size}§a veri paketi yapısı şablonları...", - "iris.bukkit.runtime.bulkstructureimporter.fail_10": "§c[hata] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_11": "§c[hata] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.could_not_enumerate_datapack_templates_via_server_resourcemanager": "§eSunucu aracılığıyla veri paketi şablonları istenmeyebilir ResourceManager: {error}", - "iris.bukkit.runtime.bulkstructureimporter.datapack_structure_import_complete_imported_skipped_failed": "§aDatapack structure import Tamam: §f{imported}§a ithal, §f{skipped}§a atladı, §f{failed}§a başarısız oldu.", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_is_not_supported_by_active_nms_binding_skipping_capture_pass": "§eYapı yakalama aktif tarafından desteklenmez NMS bağlayıcı; yakalama geçişini atlayın.", - "iris.bukkit.runtime.structurecaptureimporter.no_code_generated_structures_left_capture_everything_is_already_imported_as_structure": "§7Hiçbir kodlanmış yapılar yakalamaya bırakılır (her şey zaten bir yapı olarak ithal edilir).", - "iris.bukkit.runtime.structurecaptureimporter.capturing_code_generated_structures_no_nbt_template_into_scratch_world_skipping_any": "§aCapturing§f{total}§aKodlanmış yapılar (hayır)NBTŞablon) bir çizik dünyaya (daha genişleyen herhangi bir daha/Daha uzun{MAXSPAN}bloklar...", - "iris.bukkit.runtime.structurecaptureimporter.skip_did_not_place_capturable_structure_here_too_large_wrong_dimension_no": "§e[atlandı] {key}: Burada capturable bir yapı yoktu (çok büyük, yanlış boyut veya düz bir dünyada geçerli yerleştirme yok). Yemek vanilla - üretilir.", - "iris.bukkit.runtime.structurecaptureimporter.fail": "§c[hata] {key}: {message}", - "iris.bukkit.runtime.structurecaptureimporter.capture_objects_iob_x_x": "§7[capture] {key} -> objects/{name}.iob ({w}x{h}x{d})", - "iris.bukkit.runtime.structurecaptureimporter.fail_2": "§c[hata] {key}: {error}", - "iris.bukkit.runtime.structurecaptureimporter.captured_skipped_failed": "§7...{processed}/{total} ({imported} Yakalandı, {skipped} atladı, {failed} başarısız oldu)", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_complete_captured_skipped_failed_total": "§aYapı yakalama tamamlandı: §f{imported}§a Yakalandı, §f{skipped}§a atladı, §f{failed}§a başarısız (§f{total}§a Toplam).", "iris.bukkit.runtime.featureimporter.no_vanilla_tree_object_features_are_exposed_by_active_nms_binding_importing": "§eHiçbir vanilla ağacı /object özellikleri aktif olarak maruz bırakılır NMS Bağlanma (yalnızca)", "iris.bukkit.runtime.featureimporter.importing_vanilla_tree_object_features_variants_each_into_scratch_world": "§aİthalat §f{total}§a vanilla tree/object features (§f{wantVariants}§a Her bir şekilde) sıfır dünyaya...", "iris.bukkit.runtime.featureimporter.obj_objects_vanilla": "§7[obj] {key} -> objects/vanilla/{group}/{safeName} ({written})", diff --git a/core/src/main/resources/languages/vi_VI.json b/core/src/main/resources/languages/vi_VI.json index cffa0d123..75508143d 100644 --- a/core/src/main/resources/languages/vi_VI.json +++ b/core/src/main/resources/languages/vi_VI.json @@ -1008,50 +1008,6 @@ "§cKhi bạn đã hiểu rủi ro và tạo bản sao lưu:", "§c/iris developer update-world {world} {pack} confirm=true" ], - "iris.bukkit.runtime.bulkstructureimporter.importing_vanilla_datapack_structures_mode_includenonjigsaw": "§aNhập §f{total}§a Name & cấu trúc gói dữ liệu (mode={mode}, includeNonJigsaw={includeNonJigsaw})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key": "§c[lỗi] {keyString}: khóa không hợp lệ", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.skip_no_single_template_nbt_vanilla_builds_this_code_from_separate_piece": "§e[bỏ qua] {keyString}: NBT -oni xây dựng nó bằng mã hoặc từ các mẫu riêng biệt (được nhập qua các mẫu); không có gì để nhập như một cấu trúc.", - "iris.bukkit.runtime.bulkstructureimporter.fail": "§c[lỗi] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_2": "§c[lỗi] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_3": "§c[lỗi] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.bulk_import_complete_imported_skipped_failed_total": "§aĐã nhập xong: §f{imported}§a Nhập khẩu, §f{skipped}§a bỏ qua, §f{failed}§a lỗi (§f{total}§a Tổng cộng).", - "iris.bukkit.runtime.bulkstructureimporter.building_single_template_structures_from_imported_pieces_one_variant_placed_per_generation": "§aXây dựng cấu trúc thái dương đơn từ các mảnh nhập khẩu (một biến thể được đặt trên mỗi thế hệ)...", - "iris.bukkit.runtime.bulkstructureimporter.group_variants": "§7[group] {value} -> {value2} ({blocks} biến thế)", - "iris.bukkit.runtime.bulkstructureimporter.skip": "§e[bỏ qua] {value}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_4": "§c[lỗi] {value}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.single_template_structures_built_skipped_failed": "§aCác cấu trúc thái đơn: §f{imported}§a Xây dựng, §f{skipped}§a bỏ qua, §f{failed}§a bị lỗi.", - "iris.bukkit.runtime.bulkstructureimporter.failed_enumerate_structure_templates_via_server_resourcemanager": "§cLỗi liệt kê các mẫu cấu trúc thông qua máy chủ ResourceManager: {e}", - "iris.bukkit.runtime.bulkstructureimporter.no_structure_templates_were_found_under_structure_resource_path": "§eKhông tìm thấy mẫu cấu trúc nào dưới đường dẫn tài nguyên « cơ cấu ».", - "iris.bukkit.runtime.bulkstructureimporter.importing_structure_templates_mode": "§aNhập §f{total}§a mẫu cấu trúc (mode={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_2": "§c[lỗi] {keyString}: khóa không hợp lệ", - "iris.bukkit.runtime.bulkstructureimporter.fail_5": "§c[lỗi] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_6": "§c[lỗi] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.imported_skipped_failed": "§7...{processed}/{total} ({imported} Nhập khẩu, {skipped} bỏ qua, {failed} bị lỗi)", - "iris.bukkit.runtime.bulkstructureimporter.template_import_complete_imported_skipped_failed_total": "§aComment §f{imported}§a Nhập khẩu, §f{skipped}§a bỏ qua, §f{failed}§a lỗi (§f{total}§a Tổng cộng).", - "iris.bukkit.runtime.bulkstructureimporter.no_datapack_non_minecraft_structures_are_registered_ingest_datapack_restart_first_then": "§eKhông có tập dữ liệu nào (không phải của tôi) được đăng ký. Hãy khởi động lại dữ liệu trước, rồi chạy lại lần nữa.", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structures_mode": "§aNhập §f{total}§a cấu trúc gói dữ liệu (mode={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_3": "§c[lỗi] {keyString}: khóa không hợp lệ", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw_2": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single_2": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.fail_7": "§c[lỗi] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_8": "§c[lỗi] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_9": "§c[lỗi] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structure_templates": "§aNhập §f{size}§a Comment...", - "iris.bukkit.runtime.bulkstructureimporter.fail_10": "§c[lỗi] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_11": "§c[lỗi] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.could_not_enumerate_datapack_templates_via_server_resourcemanager": "§eKhông thể liệt kê các mẫu dữ liệu qua máy chủ ResourceManager: {error}", - "iris.bukkit.runtime.bulkstructureimporter.datapack_structure_import_complete_imported_skipped_failed": "§aComment §f{imported}§a Nhập khẩu, §f{skipped}§a bỏ qua, §f{failed}§a bị lỗi.", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_is_not_supported_by_active_nms_binding_skipping_capture_pass": "§eBắt giữ cấu trúc không được hỗ trợ bởi các hoạt động NMS ràng buộc, bỏ qua việc bắt giữ.", - "iris.bukkit.runtime.structurecaptureimporter.no_code_generated_structures_left_capture_everything_is_already_imported_as_structure": "§7Không còn cấu trúc mã hóa nào để lấy (mọi thứ đã được nhập vào như một cấu trúc).", - "iris.bukkit.runtime.structurecaptureimporter.capturing_code_generated_structures_no_nbt_template_into_scratch_world_skipping_any": "§aBắt buộc §f{total}§a Cấu trúc mã hóa (không có NBT Biểu mẫu) thành một thế giới bị trầy xước (đi vào bất cứ thế giới rộng hơn/taller nào so với {MAXSPAN} khối)...", - "iris.bukkit.runtime.structurecaptureimporter.skip_did_not_place_capturable_structure_here_too_large_wrong_dimension_no": "§e[bỏ qua] {key}▪ Không đặt một cấu trúc quan trọng ở đây (quá lớn, sai kích thước hoặc không có vị trí thích hợp trong một thế giới phẳng). Vẫn sản xuất vanilla.", - "iris.bukkit.runtime.structurecaptureimporter.fail": "§c[lỗi] {key}: {message}", - "iris.bukkit.runtime.structurecaptureimporter.capture_objects_iob_x_x": "§7[capture] {key} -> objects/{name}.iob ({w}x{h}x{d})", - "iris.bukkit.runtime.structurecaptureimporter.fail_2": "§c[lỗi] {key}: {error}", - "iris.bukkit.runtime.structurecaptureimporter.captured_skipped_failed": "§7...{processed}/{total} ({imported} Đã bị bắt, {skipped} bỏ qua, {failed} bị lỗi)", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_complete_captured_skipped_failed_total": "§aHoàn tất ghi hình cấu trúc: §f{imported}§a Đã bị bắt, §f{skipped}§a bỏ qua, §f{failed}§a lỗi (§f{total}§a Tổng cộng).", "iris.bukkit.runtime.featureimporter.no_vanilla_tree_object_features_are_exposed_by_active_nms_binding_importing": "§eName NMS Liên kết (chỉ đưa vào các cấu trúc).", "iris.bukkit.runtime.featureimporter.importing_vanilla_tree_object_features_variants_each_into_scratch_world": "§aNhập §f{total}§a Các tính năng của cây van-ni- a/ dễ theo dõi (§f{wantVariants}§a biến thể mỗi) thành một thế giới cũ...", "iris.bukkit.runtime.featureimporter.obj_objects_vanilla": "§7[obj] {key} -> objects/vanilla/{group}/{safeName} ({written})", diff --git a/core/src/main/resources/languages/zh_CN.json b/core/src/main/resources/languages/zh_CN.json index 3d8910502..0993fa643 100644 --- a/core/src/main/resources/languages/zh_CN.json +++ b/core/src/main/resources/languages/zh_CN.json @@ -1008,50 +1008,6 @@ "§c现在,你意识到了风险, 并做了一个备份:", "§c/iris developer update-world {world} {pack} confirm=true" ], - "iris.bukkit.runtime.bulkstructureimporter.importing_vanilla_datapack_structures_mode_includenonjigsaw": "§a导入 §f{total}§a 原版 & 数据包结构(模式={mode}, includeNonJigsaw={includeNonJigsaw})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key": "§c[失败] {keyString}无效的密钥", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.skip_no_single_template_nbt_vanilla_builds_this_code_from_separate_piece": "§e[跳过] {keyString}: 无单调 NBT - 原版用代码或从单独的块模板(通过模板通过导入)中构建它;不作为一个结构导入。", - "iris.bukkit.runtime.bulkstructureimporter.fail": "§c[失败] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_2": "§c[失败] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_3": "§c[失败] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.bulk_import_complete_imported_skipped_failed_total": "§a批量导入完成 : §f{imported}§a 进口 §f{skipped}§a 跳过 §f{failed}§a 失败 (§f{total}§a 总计)。", - "iris.bukkit.runtime.bulkstructureimporter.building_single_template_structures_from_imported_pieces_one_variant_placed_per_generation": "§a从进口的部件建造单层结构(每代放置一个变体)...", - "iris.bukkit.runtime.bulkstructureimporter.group_variants": "§7[组] {value} -> {value2} ({blocks} 变体)", - "iris.bukkit.runtime.bulkstructureimporter.skip": "§e[跳过] {value}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_4": "§c[失败] {value}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.single_template_structures_built_skipped_failed": "§a单调结构: §f{imported}§a 建造, §f{skipped}§a 跳过 §f{failed}§a 失败 。", - "iris.bukkit.runtime.bulkstructureimporter.failed_enumerate_structure_templates_via_server_resourcemanager": "§c通过服务器列出结构模板失败 ResourceManager: {e}", - "iris.bukkit.runtime.bulkstructureimporter.no_structure_templates_were_found_under_structure_resource_path": "§e在“ 结构” 资源路径下找不到结构模板 。", - "iris.bukkit.runtime.bulkstructureimporter.importing_structure_templates_mode": "§a导入 §f{total}§a 结构模板(模式={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_2": "§c[失败] {keyString}无效的密钥", - "iris.bukkit.runtime.bulkstructureimporter.fail_5": "§c[失败] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_6": "§c[失败] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.imported_skipped_failed": "§7...{processed}/{total} ({imported} 进口 {skipped} 跳过 {failed} 失败)", - "iris.bukkit.runtime.bulkstructureimporter.template_import_complete_imported_skipped_failed_total": "§a模板导入完成 : §f{imported}§a 进口 §f{skipped}§a 跳过 §f{failed}§a 失败 (§f{total}§a 总计)。", - "iris.bukkit.runtime.bulkstructureimporter.no_datapack_non_minecraft_structures_are_registered_ingest_datapack_restart_first_then": "§e没有登记数据包(非矿物)结构。 获取一个数据包并首先重新启动, 然后再次运行 。", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structures_mode": "§a导入 §f{total}§a 数据包结构(模式={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_3": "§c[失败] {keyString}无效的密钥", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw_2": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single_2": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.fail_7": "§c[失败] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_8": "§c[失败] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_9": "§c[失败] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structure_templates": "§a导入 §f{size}§a 数据包结构模板...", - "iris.bukkit.runtime.bulkstructureimporter.fail_10": "§c[失败] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_11": "§c[失败] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.could_not_enumerate_datapack_templates_via_server_resourcemanager": "§e无法通过服务器列出数据包模板 ResourceManager: {error}", - "iris.bukkit.runtime.bulkstructureimporter.datapack_structure_import_complete_imported_skipped_failed": "§a数据包结构导入完成 : §f{imported}§a 进口 §f{skipped}§a 跳过 §f{failed}§a 失败 。", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_is_not_supported_by_active_nms_binding_skipping_capture_pass": "§e结构捕捉不被活动者支持 NMS 绑定; 跳过捕获通道。", - "iris.bukkit.runtime.structurecaptureimporter.no_code_generated_structures_left_capture_everything_is_already_imported_as_structure": "§7没有代码生成的结构留待捕捉(所有东西已经作为结构导入).", - "iris.bukkit.runtime.structurecaptureimporter.capturing_code_generated_structures_no_nbt_template_into_scratch_world_skipping_any": "§a隐藏§f{total}§a代码生成结构( 无)NBT切换到一个划痕世界(吸取更大的/高过{MAXSPAN}块)...", - "iris.bukkit.runtime.structurecaptureimporter.skip_did_not_place_capturable_structure_here_too_large_wrong_dimension_no": "§e[跳过] {key}:没有在此放置一个可封顶结构(太大,错误的维度,或者在一个平坦的世界中没有有效的放置). 留原版生成.", - "iris.bukkit.runtime.structurecaptureimporter.fail": "§c[失败] {key}: {message}", - "iris.bukkit.runtime.structurecaptureimporter.capture_objects_iob_x_x": "§7[捕获] {key} -> objects/{name}.iob ({w}x{h}x{d})", - "iris.bukkit.runtime.structurecaptureimporter.fail_2": "§c[失败] {key}: {error}", - "iris.bukkit.runtime.structurecaptureimporter.captured_skipped_failed": "§7...{processed}/{total} ({imported} 被俘获, {skipped} 跳过 {failed} 失败)", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_complete_captured_skipped_failed_total": "§a结构捕捉完成 : §f{imported}§a 被俘获, §f{skipped}§a 跳过 §f{failed}§a 失败 (§f{total}§a 总计)。", "iris.bukkit.runtime.featureimporter.no_vanilla_tree_object_features_are_exposed_by_active_nms_binding_importing": "§e活动者未暴露原版树/物体特征 NMS 约束(仅导入结构)。", "iris.bukkit.runtime.featureimporter.importing_vanilla_tree_object_features_variants_each_into_scratch_world": "§a导入 §f{total}§a 原版树/物体特征(§f{wantVariants}§a 每个变体)进入刮伤世界...", "iris.bukkit.runtime.featureimporter.obj_objects_vanilla": "§7[obj] {key} -> objects/vanilla/{group}/{safeName} ({written})", diff --git a/core/src/main/resources/languages/zh_TW.json b/core/src/main/resources/languages/zh_TW.json index d0a72ae4d..64445626a 100644 --- a/core/src/main/resources/languages/zh_TW.json +++ b/core/src/main/resources/languages/zh_TW.json @@ -1008,50 +1008,6 @@ "§c現在,你意識到了風險, 並做了一個備份:", "§c/iris developer update-world {world} {pack} confirm=true" ], - "iris.bukkit.runtime.bulkstructureimporter.importing_vanilla_datapack_structures_mode_includenonjigsaw": "§a匯入 §f{total}§a 原版 & 資料包結構(模式={mode}, includeNonJigsaw={includeNonJigsaw})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key": "§c[失敗] {keyString}無效的金鑰", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.skip_no_single_template_nbt_vanilla_builds_this_code_from_separate_piece": "§e[略過] {keyString}: 無單調 NBT - 原版用程式碼或從單獨的塊模板(透過模板透過匯入)中構建它;不作為一個結構匯入。", - "iris.bukkit.runtime.bulkstructureimporter.fail": "§c[失敗] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_2": "§c[失敗] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_3": "§c[失敗] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.bulk_import_complete_imported_skipped_failed_total": "§a批次匯入完成 : §f{imported}§a 進口 §f{skipped}§a 跳過 §f{failed}§a 失敗 (§f{total}§a 總計)。", - "iris.bukkit.runtime.bulkstructureimporter.building_single_template_structures_from_imported_pieces_one_variant_placed_per_generation": "§a從進口的部件建造單層結構(每代放置一個變體)...", - "iris.bukkit.runtime.bulkstructureimporter.group_variants": "§7[組] {value} -> {value2} ({blocks} 變體)", - "iris.bukkit.runtime.bulkstructureimporter.skip": "§e[略過] {value}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_4": "§c[失敗] {value}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.single_template_structures_built_skipped_failed": "§a單調結構: §f{imported}§a 建造, §f{skipped}§a 跳過 §f{failed}§a 失敗 。", - "iris.bukkit.runtime.bulkstructureimporter.failed_enumerate_structure_templates_via_server_resourcemanager": "§c透過伺服器列出結構模板失敗 ResourceManager: {e}", - "iris.bukkit.runtime.bulkstructureimporter.no_structure_templates_were_found_under_structure_resource_path": "§e在“ 結構” 資源路徑下找不到結構模板 。", - "iris.bukkit.runtime.bulkstructureimporter.importing_structure_templates_mode": "§a匯入 §f{total}§a 結構模板(模式={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_2": "§c[失敗] {keyString}無效的金鑰", - "iris.bukkit.runtime.bulkstructureimporter.fail_5": "§c[失敗] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_6": "§c[失敗] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.imported_skipped_failed": "§7...{processed}/{total} ({imported} 進口 {skipped} 跳過 {failed} 失敗)", - "iris.bukkit.runtime.bulkstructureimporter.template_import_complete_imported_skipped_failed_total": "§a模板匯入完成 : §f{imported}§a 進口 §f{skipped}§a 跳過 §f{failed}§a 失敗 (§f{total}§a 總計)。", - "iris.bukkit.runtime.bulkstructureimporter.no_datapack_non_minecraft_structures_are_registered_ingest_datapack_restart_first_then": "§e沒有登記資料包(非礦物)結構。 獲取一個資料包並首先重新啟動, 然後再次執行 。", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structures_mode": "§a匯入 §f{total}§a 資料包結構(模式={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_3": "§c[失敗] {keyString}無效的金鑰", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw_2": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single_2": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.fail_7": "§c[失敗] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_8": "§c[失敗] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_9": "§c[失敗] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structure_templates": "§a匯入 §f{size}§a 資料包結構模板...", - "iris.bukkit.runtime.bulkstructureimporter.fail_10": "§c[失敗] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_11": "§c[失敗] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.could_not_enumerate_datapack_templates_via_server_resourcemanager": "§e無法透過伺服器列出資料包模板 ResourceManager: {error}", - "iris.bukkit.runtime.bulkstructureimporter.datapack_structure_import_complete_imported_skipped_failed": "§a資料包結構匯入完成 : §f{imported}§a 進口 §f{skipped}§a 跳過 §f{failed}§a 失敗 。", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_is_not_supported_by_active_nms_binding_skipping_capture_pass": "§e結構捕捉不被活動者支援 NMS 繫結; 跳過捕獲通道。", - "iris.bukkit.runtime.structurecaptureimporter.no_code_generated_structures_left_capture_everything_is_already_imported_as_structure": "§7沒有程式碼生成的結構留待捕捉(所有東西已經作為結構匯入).", - "iris.bukkit.runtime.structurecaptureimporter.capturing_code_generated_structures_no_nbt_template_into_scratch_world_skipping_any": "§a隱藏§f{total}§a代碼生成結構( 無)NBT切換到一個划痕世界(吸取更大的/高過{MAXSPAN}塊)...", - "iris.bukkit.runtime.structurecaptureimporter.skip_did_not_place_capturable_structure_here_too_large_wrong_dimension_no": "§e[略過] {key}:沒有在此放置一個可封頂結構(太大,錯誤的維度,或者在一個平坦的世界中沒有有效的放置). 留原版生成.", - "iris.bukkit.runtime.structurecaptureimporter.fail": "§c[失敗] {key}: {message}", - "iris.bukkit.runtime.structurecaptureimporter.capture_objects_iob_x_x": "§7[擷取] {key} -> objects/{name}.iob ({w}x{h}x{d})", - "iris.bukkit.runtime.structurecaptureimporter.fail_2": "§c[失敗] {key}: {error}", - "iris.bukkit.runtime.structurecaptureimporter.captured_skipped_failed": "§7...{processed}/{total} ({imported} 被俘獲, {skipped} 跳過 {failed} 失敗)", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_complete_captured_skipped_failed_total": "§a結構捕捉完成 : §f{imported}§a 被俘獲, §f{skipped}§a 跳過 §f{failed}§a 失敗 (§f{total}§a 總計)。", "iris.bukkit.runtime.featureimporter.no_vanilla_tree_object_features_are_exposed_by_active_nms_binding_importing": "§e活動者未暴露原版樹/物體特徵 NMS 約束(僅匯入結構)。", "iris.bukkit.runtime.featureimporter.importing_vanilla_tree_object_features_variants_each_into_scratch_world": "§a匯入 §f{total}§a 原版樹/物體特徵(§f{wantVariants}§a 每個變體)進入刮傷世界...", "iris.bukkit.runtime.featureimporter.obj_objects_vanilla": "§7[obj] {key} -> objects/vanilla/{group}/{safeName} ({written})", diff --git a/core/src/main/resources/messages/en_US.json b/core/src/main/resources/messages/en_US.json index caf46510c..817788de1 100644 --- a/core/src/main/resources/messages/en_US.json +++ b/core/src/main/resources/messages/en_US.json @@ -1031,50 +1031,6 @@ "§cNow that you are aware of the risks, and have made a back-up:", "§c/iris developer update-world {world} {pack} confirm=true" ], - "iris.bukkit.runtime.bulkstructureimporter.importing_vanilla_datapack_structures_mode_includenonjigsaw": "§aImporting §f{total}§a vanilla & datapack structures (mode={mode}, includeNonJigsaw={includeNonJigsaw})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key": "§c[fail] {keyString}: invalid key", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.skip_no_single_template_nbt_vanilla_builds_this_code_from_separate_piece": "§e[skip] {keyString}: no single-template NBT - vanilla builds this in code or from separate piece templates (imported via the templates pass); nothing to import as one structure.", - "iris.bukkit.runtime.bulkstructureimporter.fail": "§c[fail] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_2": "§c[fail] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_3": "§c[fail] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.bulk_import_complete_imported_skipped_failed_total": "§aBulk import complete: §f{imported}§a imported, §f{skipped}§a skipped, §f{failed}§a failed (§f{total}§a total).", - "iris.bukkit.runtime.bulkstructureimporter.building_single_template_structures_from_imported_pieces_one_variant_placed_per_generation": "§aBuilding single-template structures from imported pieces (one variant placed per generation)...", - "iris.bukkit.runtime.bulkstructureimporter.group_variants": "§7[group] {value} -> {value2} ({blocks} variants)", - "iris.bukkit.runtime.bulkstructureimporter.skip": "§e[skip] {value}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_4": "§c[fail] {value}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.single_template_structures_built_skipped_failed": "§aSingle-template structures: §f{imported}§a built, §f{skipped}§a skipped, §f{failed}§a failed.", - "iris.bukkit.runtime.bulkstructureimporter.failed_enumerate_structure_templates_via_server_resourcemanager": "§cFailed to enumerate structure templates via the server ResourceManager: {e}", - "iris.bukkit.runtime.bulkstructureimporter.no_structure_templates_were_found_under_structure_resource_path": "§eNo structure templates were found under the 'structure' resource path.", - "iris.bukkit.runtime.bulkstructureimporter.importing_structure_templates_mode": "§aImporting §f{total}§a structure templates (mode={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_2": "§c[fail] {keyString}: invalid key", - "iris.bukkit.runtime.bulkstructureimporter.fail_5": "§c[fail] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_6": "§c[fail] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.imported_skipped_failed": "§7...{processed}/{total} ({imported} imported, {skipped} skipped, {failed} failed)", - "iris.bukkit.runtime.bulkstructureimporter.template_import_complete_imported_skipped_failed_total": "§aTemplate import complete: §f{imported}§a imported, §f{skipped}§a skipped, §f{failed}§a failed (§f{total}§a total).", - "iris.bukkit.runtime.bulkstructureimporter.no_datapack_non_minecraft_structures_are_registered_ingest_datapack_restart_first_then": "§eNo datapack (non-minecraft) structures are registered. Ingest a datapack and restart first, then run this again.", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structures_mode": "§aImporting §f{total}§a datapack structures (mode={mode})...", - "iris.bukkit.runtime.bulkstructureimporter.fail_invalid_key_3": "§c[fail] {keyString}: invalid key", - "iris.bukkit.runtime.bulkstructureimporter.jigsaw_2": "§7[jigsaw] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.single_2": "§7[single] {keyString} -> {name}", - "iris.bukkit.runtime.bulkstructureimporter.fail_7": "§c[fail] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_8": "§c[fail] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_9": "§c[fail] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.importing_datapack_structure_templates": "§aImporting §f{size}§a datapack structure templates...", - "iris.bukkit.runtime.bulkstructureimporter.fail_10": "§c[fail] {keyString}: {message}", - "iris.bukkit.runtime.bulkstructureimporter.fail_11": "§c[fail] {keyString}: {error}", - "iris.bukkit.runtime.bulkstructureimporter.could_not_enumerate_datapack_templates_via_server_resourcemanager": "§eCould not enumerate datapack templates via the server ResourceManager: {error}", - "iris.bukkit.runtime.bulkstructureimporter.datapack_structure_import_complete_imported_skipped_failed": "§aDatapack structure import complete: §f{imported}§a imported, §f{skipped}§a skipped, §f{failed}§a failed.", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_is_not_supported_by_active_nms_binding_skipping_capture_pass": "§eStructure capture is not supported by the active NMS binding; skipping the capture pass.", - "iris.bukkit.runtime.structurecaptureimporter.no_code_generated_structures_left_capture_everything_is_already_imported_as_structure": "§7No code-generated structures left to capture (everything is already imported as a structure).", - "iris.bukkit.runtime.structurecaptureimporter.capturing_code_generated_structures_no_nbt_template_into_scratch_world_skipping_any": "§aCapturing §f{total}§a code-generated structures (no NBT template) into a scratch world (skipping any wider/taller than {MAXSPAN} blocks)...", - "iris.bukkit.runtime.structurecaptureimporter.skip_did_not_place_capturable_structure_here_too_large_wrong_dimension_no": "§e[skip] {key}: did not place a capturable structure here (too large, wrong dimension, or no valid placement in a flat world). Stays vanilla-generated.", - "iris.bukkit.runtime.structurecaptureimporter.fail": "§c[fail] {key}: {message}", - "iris.bukkit.runtime.structurecaptureimporter.capture_objects_iob_x_x": "§7[capture] {key} -> objects/{name}.iob ({w}x{h}x{d})", - "iris.bukkit.runtime.structurecaptureimporter.fail_2": "§c[fail] {key}: {error}", - "iris.bukkit.runtime.structurecaptureimporter.captured_skipped_failed": "§7...{processed}/{total} ({imported} captured, {skipped} skipped, {failed} failed)", - "iris.bukkit.runtime.structurecaptureimporter.structure_capture_complete_captured_skipped_failed_total": "§aStructure capture complete: §f{imported}§a captured, §f{skipped}§a skipped, §f{failed}§a failed (§f{total}§a total).", "iris.bukkit.runtime.featureimporter.no_vanilla_tree_object_features_are_exposed_by_active_nms_binding_importing": "§eNo vanilla tree/object features are exposed by the active NMS binding (importing structures only).", "iris.bukkit.runtime.featureimporter.importing_vanilla_tree_object_features_variants_each_into_scratch_world": "§aImporting §f{total}§a vanilla tree/object features (§f{wantVariants}§a variants each) into a scratch world...", "iris.bukkit.runtime.featureimporter.obj_objects_vanilla": "§7[obj] {key} -> objects/vanilla/{group}/{safeName} ({written})", diff --git a/core/src/test/java/art/arcane/iris/core/modules/BuiltInModulesJar.java b/core/src/test/java/art/arcane/iris/core/modules/BuiltInModulesJar.java index e07367e3c..31f82eab3 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/BuiltInModulesJar.java +++ b/core/src/test/java/art/arcane/iris/core/modules/BuiltInModulesJar.java @@ -45,6 +45,14 @@ public final class BuiltInModulesJar { return entryClasses(jar); } + /** {@link #writeInto} unless the pack has the jar already, for a test that writes a pack file by file. */ + public static void installInto(Path pack) throws IOException { + if (Files.exists(pack.resolve("modules").resolve(JAR_NAME))) { + return; + } + writeInto(pack); + } + private static List entryClasses(Path jar) throws IOException { try (JarFile file = new JarFile(jar.toFile())) { String entries = new String(file.getInputStream(file.getJarEntry(SERVICE_ENTRY)).readAllBytes(), StandardCharsets.UTF_8); diff --git a/core/src/test/java/art/arcane/iris/core/modules/BuiltInPack.java b/core/src/test/java/art/arcane/iris/core/modules/BuiltInPack.java index c8897a505..6e92b26fa 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/BuiltInPack.java +++ b/core/src/test/java/art/arcane/iris/core/modules/BuiltInPack.java @@ -31,7 +31,9 @@ import art.arcane.iris.engine.framework.vanillafeatures.VanillaFeaturesModule; import art.arcane.iris.engine.loot.LootModule; import art.arcane.iris.engine.modifier.CarveModule; import art.arcane.iris.engine.modifier.DepositModule; +import art.arcane.iris.engine.mantle.components.StructureModule; import art.arcane.iris.engine.modifier.FloatingModule; +import art.arcane.iris.modules.jigsaw.JigsawModule; import art.arcane.iris.engine.modifier.MatterModule; import art.arcane.iris.engine.modifier.PerfectionModule; import art.arcane.iris.engine.mantle.components.ObjectModule; @@ -78,7 +80,8 @@ public final class BuiltInPack { return List.of(new PostModule(), new PerfectionModule(), new MatterModule(), new LootModule(), new SpawnModule(), new PrepareModule(), new AnchorModule(), new ValidateModule(), new BoreModule(), new BlocksModule(), new StiltModule(), new VacuumModule(), new SnowModule(), new VanillaFeaturesModule(), new CarveModule(), - new DepositModule(), new DecorantModule(), new TerrainModule(), new ObjectModule(), new FloatingModule()); + new DepositModule(), new DecorantModule(), new TerrainModule(), new ObjectModule(), new FloatingModule(), + new StructureModule(), new JigsawModule()); } /** Every built-in module: Iris's own and the compiled-in copies of the jar's ({@link #jarModules()}). */ @@ -110,7 +113,7 @@ public final class BuiltInPack { LoadedPack pack = LoadedPack.load(packFolder, ModuleHost.of(modules) .exposing(IrisModuleHost.EXPOSED_PACKAGES.toArray(String[]::new)) .reservingFields(ModuleTargets.reservedFields()) - .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGE) + .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGES) .copyingJarsTo(folder.newFolder().toPath())); PackModuleSet moduleSet = mock(PackModuleSet.class); when(moduleSet.pack()).thenReturn(pack); diff --git a/core/src/test/java/art/arcane/iris/core/modules/CarveSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/CarveSettingsDecodingTest.java index 4fbb686d5..0e14c4aef 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/CarveSettingsDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/CarveSettingsDecodingTest.java @@ -71,7 +71,7 @@ public class CarveSettingsDecodingTest { packFolder = Path.of(CarveSettingsDecodingTest.class.getResource(PACK).toURI()); pack = LoadedPack.load(packFolder, ModuleHost.of(BuiltInPack.allBuiltIns()) .reservingFields(ModuleTargets.reservedFields()) - .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGE).copyingJarsTo(folder.newFolder("copies").toPath())); + .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGES).copyingJarsTo(folder.newFolder("copies").toPath())); decoder = new ModuleSettingsDecoder(pack.catalog(), packFolder, Gson::new); } diff --git a/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java b/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java index 87420678d..e59318277 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java +++ b/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java @@ -153,6 +153,11 @@ public final class CarveTestWorld implements PackWorld { return type.cast(known); } + @Override + public List services(Class service) { + return List.of(); + } + @Override public ModuleLog log() { return ModuleLogs.discarding(); diff --git a/core/src/test/java/art/arcane/iris/core/modules/ClasspathPack.java b/core/src/test/java/art/arcane/iris/core/modules/ClasspathPack.java new file mode 100644 index 000000000..5f7e8cb4c --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/modules/ClasspathPack.java @@ -0,0 +1,49 @@ +package art.arcane.iris.core.modules; + +import art.arcane.iris.core.loader.IrisData; +import com.volmit.host.LoadedPack; +import com.volmit.host.ModuleHost; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.io.IOException; + +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +/** + * A pack opened for validation whose built-in modules are the classes of the test class path, not the built-ins jar. + * Tests that call a built-in module's classes directly need this: a jar loads its own copy of every class, so what + * the pack serves would not be the classes the test names. + */ +public final class ClasspathPack { + private ClasspathPack() { + } + + /** {@code pack} opened for validation with {@link BuiltInPack#allBuiltIns()} as its modules; close it after the test. */ + public static IrisData open(File pack, TemporaryFolder folder) throws IOException { + return withClasspathModules(IrisData.openValidation(pack), pack, folder); + } + + /** Like {@link #open}, opened for a running world as {@link IrisData#openRuntime} does. */ + public static IrisData openRuntime(File pack, TemporaryFolder folder) throws IOException { + return withClasspathModules(IrisData.openRuntime(pack), pack, folder); + } + + private static IrisData withClasspathModules(IrisData opened, File pack, TemporaryFolder folder) throws IOException { + IrisData data = spy(opened); + LoadedPack loaded = LoadedPack.load(pack.toPath(), ModuleHost.of(BuiltInPack.allBuiltIns()) + .exposing(IrisModuleHost.EXPOSED_PACKAGES.toArray(String[]::new)) + .reservingFields(ModuleTargets.reservedFields()) + .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGES) + .copyingJarsTo(folder.newFolder().toPath())); + PackModuleSet modules = mock(PackModuleSet.class); + when(modules.pack()).thenReturn(loaded); + when(modules.settings()).thenReturn(new ModuleSettingsDecoder(loaded.catalog(), pack.toPath(), opened::getGson)); + doReturn(modules).when(data).getModules(); + data.invalidateStructureResources(); + return data; + } +} diff --git a/core/src/test/java/art/arcane/iris/core/modules/DecorantSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/DecorantSettingsDecodingTest.java index b2b8f3518..c6fc1c229 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/DecorantSettingsDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/DecorantSettingsDecodingTest.java @@ -59,7 +59,7 @@ public class DecorantSettingsDecodingTest { Path snippets = Files.createDirectories(packFolder.resolve("snippet/iris/decorant/decorator")); Files.writeString(snippets.resolve("bush.json"), "{\"chance\": 0.2, \"palette\": [{\"block\": \"minecraft:fern\"}]}"); pack = LoadedPack.load(packFolder, ModuleHost.of(BuiltInPack.allBuiltIns()) - .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGE).copyingJarsTo(folder.newFolder("copies").toPath())); + .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGES).copyingJarsTo(folder.newFolder("copies").toPath())); decoder = new ModuleSettingsDecoder(pack.catalog(), packFolder, Gson::new); } diff --git a/core/src/test/java/art/arcane/iris/core/modules/DepositSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/DepositSettingsDecodingTest.java index 23eafdf3b..c29f545c6 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/DepositSettingsDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/DepositSettingsDecodingTest.java @@ -63,7 +63,7 @@ public class DepositSettingsDecodingTest { Path snippets = Files.createDirectories(packFolder.resolve("snippet/iris/deposit/deposit")); Files.writeString(snippets.resolve("diamonds.json"), "{\"maxHeight\": 16, \"palette\": [{\"block\": \"minecraft:diamond_ore\"}]}"); pack = LoadedPack.load(packFolder, ModuleHost.of(BuiltInPack.allBuiltIns()) - .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGE).copyingJarsTo(folder.newFolder("copies").toPath())); + .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGES).copyingJarsTo(folder.newFolder("copies").toPath())); decoder = new ModuleSettingsDecoder(pack.catalog(), packFolder, Gson::new); } diff --git a/core/src/test/java/art/arcane/iris/core/modules/FloatingSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/FloatingSettingsDecodingTest.java index 0d07bfa8c..3f0d9675a 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/FloatingSettingsDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/FloatingSettingsDecodingTest.java @@ -68,7 +68,7 @@ public class FloatingSettingsDecodingTest { packFolder = Path.of(FloatingSettingsDecodingTest.class.getResource(PACK).toURI()); pack = LoadedPack.load(packFolder, ModuleHost.of(BuiltInPack.allBuiltIns()) .reservingFields(ModuleTargets.reservedFields()) - .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGE).copyingJarsTo(folder.newFolder("copies").toPath())); + .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGES).copyingJarsTo(folder.newFolder("copies").toPath())); decoder = new ModuleSettingsDecoder(pack.catalog(), packFolder, Gson::new); } diff --git a/core/src/test/java/art/arcane/iris/core/modules/IrisPackWorldConcurrencyTest.java b/core/src/test/java/art/arcane/iris/core/modules/IrisPackWorldConcurrencyTest.java index ad50ab1e1..2668ecbb7 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/IrisPackWorldConcurrencyTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/IrisPackWorldConcurrencyTest.java @@ -1,6 +1,6 @@ package art.arcane.iris.core.modules; -import art.arcane.iris.builtin.structure.StructureHost; +import art.arcane.iris.builtin.structure.StructureVerifier; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.Engine; import com.volmit.world.PackWorld; @@ -32,8 +32,8 @@ public class IrisPackWorldConcurrencyTest { } @Test - public void concurrentFirstCallersShareOneStructureHost() throws Exception { - assertEveryCallerGetsOneInstance(world -> world.extension(StructureHost.class).orElseThrow()); + public void concurrentFirstCallersShareOneStructureVerifier() throws Exception { + assertEveryCallerGetsOneInstance(world -> world.extension(StructureVerifier.class).orElseThrow()); } private static void assertEveryCallerGetsOneInstance(Function ask) throws Exception { diff --git a/core/src/test/java/art/arcane/iris/core/modules/IrisTestNoise.java b/core/src/test/java/art/arcane/iris/core/modules/IrisTestNoise.java new file mode 100644 index 000000000..3e28ec00d --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/modules/IrisTestNoise.java @@ -0,0 +1,22 @@ +package art.arcane.iris.core.modules; + +import art.arcane.iris.core.loader.IrisData; +import com.volmit.noise.NoiseFactory; + +import java.io.File; +import java.util.List; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** Iris's own noise factory over an empty pack, for tests that need the very noise generation reads. */ +public final class IrisTestNoise { + private IrisTestNoise() { + } + + public static NoiseFactory factory() { + IrisData data = mock(IrisData.class); + when(data.getDataFolder()).thenReturn(new File("test-pack")); + return new IrisNoiseFactory(data, new IrisPackResources(data, List::of)); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/modules/LootAndSpawnPackDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/LootAndSpawnPackDecodingTest.java index 73b20509a..a7b6343db 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/LootAndSpawnPackDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/LootAndSpawnPackDecodingTest.java @@ -82,7 +82,7 @@ public class LootAndSpawnPackDecodingTest { packFolder = Path.of(LootAndSpawnPackDecodingTest.class.getResource(PACK).toURI()); pack = LoadedPack.load(packFolder, ModuleHost.of(BuiltInPack.allBuiltIns()) .reservingFields(ModuleTargets.reservedFields()) - .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGE).copyingJarsTo(folder.newFolder("copies").toPath())); + .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGES).copyingJarsTo(folder.newFolder("copies").toPath())); decoder = new ModuleSettingsDecoder(pack.catalog(), packFolder, Gson::new); } diff --git a/core/src/test/java/art/arcane/iris/core/modules/ModuleResourceFixture.java b/core/src/test/java/art/arcane/iris/core/modules/ModuleResourceFixture.java index a0f066fd5..0ad43ed2d 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/ModuleResourceFixture.java +++ b/core/src/test/java/art/arcane/iris/core/modules/ModuleResourceFixture.java @@ -9,6 +9,8 @@ import com.volmit.host.LoadedPack; import com.volmit.host.ModuleRegistry; import com.volmit.host.ModuleSetups; import com.volmit.host.StageGraphBuilder; +import com.volmit.geometry.BlockBox; +import com.volmit.object.PackObjects; import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceKind; @@ -46,6 +48,8 @@ public final class ModuleResourceFixture { public static synchronized ModuleResourceFixture serve(IrisData data) { IrisPackResources resources = mock(IrisPackResources.class); when(data.getPackResources()).thenReturn(resources); + when(resources.objects()).thenReturn(mock(PackObjects.class)); + when(resources.services(any())).thenAnswer(invocation -> PackServices.of(data).providers((Class) invocation.getArgument(0))); when(resources.idOf(anyString())).thenAnswer(invocation -> idOf(invocation.getArgument(0))); when(resources.keyOf(any(ResourceId.class))).thenAnswer(invocation -> keyOf(invocation.getArgument(0))); when(resources.keyOf(any(ResourceKind.class), any(ResourceId.class))).thenAnswer(invocation -> keyOf(invocation.getArgument(1))); @@ -108,6 +112,12 @@ public final class ModuleResourceFixture { return this; } + /** Serves a pack object {@code key} declared {@code width} by {@code height} by {@code depth}. */ + public ModuleResourceFixture object(String key, int width, int height, int depth) { + when(resources.objects().sizeOf(idOf(key))).thenReturn(Optional.of(new BlockBox(0, 0, 0, width, height, depth))); + return this; + } + private static ResourceId idOf(String key) { return new ResourceId(NAMESPACE, key.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9_./-]", "_")); } diff --git a/core/src/test/java/art/arcane/iris/core/modules/ModuleSettingsDecoderTest.java b/core/src/test/java/art/arcane/iris/core/modules/ModuleSettingsDecoderTest.java index 6ce32cc00..ca23eb046 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/ModuleSettingsDecoderTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/ModuleSettingsDecoderTest.java @@ -126,7 +126,7 @@ public class ModuleSettingsDecoderTest { public void loadPack() throws IOException { packFolder = folder.newFolder("pack").toPath(); pack = LoadedPack.load(packFolder, ModuleHost.of(List.of(new MossModule())) - .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGE).copyingJarsTo(folder.newFolder("copies").toPath())); + .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGES).copyingJarsTo(folder.newFolder("copies").toPath())); decoder = new ModuleSettingsDecoder(pack.catalog(), packFolder, Gson::new); } diff --git a/core/src/test/java/art/arcane/iris/core/modules/OreSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/OreSettingsDecodingTest.java index e33a6ee14..670743e0c 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/OreSettingsDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/OreSettingsDecodingTest.java @@ -68,7 +68,7 @@ public class OreSettingsDecodingTest { packFolder = Path.of(OreSettingsDecodingTest.class.getResource(PACK).toURI()); pack = LoadedPack.load(packFolder, ModuleHost.of(BuiltInPack.allBuiltIns()) .reservingFields(ModuleTargets.reservedFields()) - .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGE).copyingJarsTo(folder.newFolder("copies").toPath())); + .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGES).copyingJarsTo(folder.newFolder("copies").toPath())); decoder = new ModuleSettingsDecoder(pack.catalog(), packFolder, Gson::new); } diff --git a/core/src/test/java/art/arcane/iris/core/modules/PackBeforeThePortDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/PackBeforeThePortDecodingTest.java index ca3afe94b..33beddf4b 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/PackBeforeThePortDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/PackBeforeThePortDecodingTest.java @@ -73,7 +73,7 @@ public class PackBeforeThePortDecodingTest { packFolder = Path.of(PackBeforeThePortDecodingTest.class.getResource(PACK).toURI()); pack = LoadedPack.load(packFolder, ModuleHost.of(BuiltInPack.allBuiltIns()) .reservingFields(ModuleTargets.reservedFields()) - .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGE).copyingJarsTo(folder.newFolder("copies").toPath())); + .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGES).copyingJarsTo(folder.newFolder("copies").toPath())); decoder = new ModuleSettingsDecoder(pack.catalog(), packFolder, Gson::new); } diff --git a/core/src/test/java/art/arcane/iris/core/modules/PackModuleJarNextToBuiltInsTest.java b/core/src/test/java/art/arcane/iris/core/modules/PackModuleJarNextToBuiltInsTest.java index acbdb854f..7e1e353c9 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/PackModuleJarNextToBuiltInsTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/PackModuleJarNextToBuiltInsTest.java @@ -79,7 +79,7 @@ public class PackModuleJarNextToBuiltInsTest { @Test public void aJarModuleWithTheIdOfACompiledInBuiltInFailsAsADuplicate() throws IOException { - String builtInId = new StructureModelModule().info().id().toString(); + String builtInId = new BiomeModule().info().id().toString(); Path packFolder = BuiltInPack.newPackFolder(folder); PackModuleJar.write(packFolder, "carve.jar", "pack.ported.Ported", Map.of("pack.ported.Ported", module("ported", "Ported", builtInId))); @@ -88,7 +88,7 @@ public class PackModuleJarNextToBuiltInsTest { () -> BuiltInPack.serve(mock(IrisData.class), folder, packFolder, List.of())); assertEquals("Duplicate module " + builtInId + " from " + Path.of("modules", "carve.jar") + " (pack.ported.Ported); already loaded from host classpath (" - + StructureModelModule.class.getName() + ")", failure.getMessage()); + + BiomeModule.class.getName() + ")", failure.getMessage()); } private static String module(String packageName, String className, String moduleId) { diff --git a/core/src/test/java/art/arcane/iris/core/modules/PackModuleResourceKindTest.java b/core/src/test/java/art/arcane/iris/core/modules/PackModuleResourceKindTest.java index 958e99f83..a68d661bf 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/PackModuleResourceKindTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/PackModuleResourceKindTest.java @@ -203,6 +203,7 @@ public class PackModuleResourceKindTest { private Path castlePack(String name) throws Exception { File pack = temporaryFolder.newFolder(name); + BuiltInModulesJar.installInto(pack.toPath()); write(pack.toPath(), "dimensions/main.json", "{\"regions\":[{\"region\":\"region\"}]}"); write(pack.toPath(), "regions/region.json", "{\"landBiomes\":[{\"biome\":\"biome\"}]}"); write(pack.toPath(), "biomes/biome.json", "{\"name\":\"Biome\"}"); diff --git a/core/src/test/java/art/arcane/iris/core/modules/StructurePlacementSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/StructurePlacementSettingsDecodingTest.java index 2453d2939..cea095b7d 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/StructurePlacementSettingsDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/StructurePlacementSettingsDecodingTest.java @@ -126,7 +126,7 @@ public class StructurePlacementSettingsDecodingTest { public void loadBuiltIns() throws IOException { Path packFolder = folder.newFolder("pack").toPath(); pack = LoadedPack.load(packFolder, ModuleHost.of(BuiltInPack.allBuiltIns()) - .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGE).copyingJarsTo(folder.newFolder("copies").toPath())); + .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGES).copyingJarsTo(folder.newFolder("copies").toPath())); decoder = new ModuleSettingsDecoder(pack.catalog(), packFolder, Gson::new); } diff --git a/core/src/test/java/art/arcane/iris/core/modules/StructureSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/StructureSettingsDecodingTest.java index cf598e598..302a00f5c 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/StructureSettingsDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/StructureSettingsDecodingTest.java @@ -68,7 +68,7 @@ public class StructureSettingsDecodingTest { public void loadBuiltIns() throws IOException { Path packFolder = folder.newFolder("pack").toPath(); pack = LoadedPack.load(packFolder, ModuleHost.of(BuiltInPack.allBuiltIns()) - .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGE).copyingJarsTo(folder.newFolder("copies").toPath())); + .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGES).copyingJarsTo(folder.newFolder("copies").toPath())); decoder = new ModuleSettingsDecoder(pack.catalog(), packFolder, Gson::new); } diff --git a/core/src/test/java/art/arcane/iris/core/modules/TerrainSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/TerrainSettingsDecodingTest.java index 23954e239..7de2a1349 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/TerrainSettingsDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/TerrainSettingsDecodingTest.java @@ -82,7 +82,7 @@ public class TerrainSettingsDecodingTest { packFolder = Path.of(TerrainSettingsDecodingTest.class.getResource(PACK).toURI()); pack = LoadedPack.load(packFolder, ModuleHost.of(BuiltInPack.allBuiltIns()) .reservingFields(ModuleTargets.reservedFields()) - .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGE).copyingJarsTo(folder.newFolder("copies").toPath())); + .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGES).copyingJarsTo(folder.newFolder("copies").toPath())); decoder = new ModuleSettingsDecoder(pack.catalog(), packFolder, Gson::new); } diff --git a/core/src/test/java/art/arcane/iris/core/modules/ToolWorldTest.java b/core/src/test/java/art/arcane/iris/core/modules/ToolWorldTest.java index 83b34c3dd..99864a709 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/ToolWorldTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/ToolWorldTest.java @@ -25,6 +25,8 @@ import com.volmit.resource.PackResources; import com.volmit.world.PackWorld; import org.junit.Test; +import java.util.List; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; @@ -48,7 +50,8 @@ public class ToolWorldTest { public void theWorldKeepsItsStateUntilItIsClosed() { PackResources resources = mock(PackResources.class); Tracked tracked; - try (ToolWorld world = new ToolWorld(SEED, resources, mock(PackSettings.class), ignored -> mock(Placements.class))) { + try (ToolWorld world = new ToolWorld(SEED, resources, mock(PackSettings.class), mock(PackServices.class), + ignored -> mock(Placements.class))) { tracked = world.state(Tracked.class, ignored -> new Tracked()); assertSame(tracked, world.state(Tracked.class, ignored -> new Tracked())); @@ -60,4 +63,22 @@ public class ToolWorldTest { assertTrue(tracked.closed); } + + @Test + public void theWorldAnswersServicesWithTheProvidersOfThePacksModules() { + Runnable provider = () -> { }; + PackServices services = new PackServices() { + @Override + @SuppressWarnings("unchecked") + public List providers(Class service) { + return service == Runnable.class ? (List) List.of(provider) : List.of(); + } + }; + + try (ToolWorld world = new ToolWorld(SEED, mock(PackResources.class), mock(PackSettings.class), services, + ignored -> mock(Placements.class))) { + assertEquals(List.of(provider), world.services(Runnable.class)); + assertEquals(List.of(), world.services(Comparable.class)); + } + } } diff --git a/core/src/test/java/art/arcane/iris/core/modules/VanillaFeaturesSettingsDecodingTest.java b/core/src/test/java/art/arcane/iris/core/modules/VanillaFeaturesSettingsDecodingTest.java index 37ed4a72d..a7d3f8123 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/VanillaFeaturesSettingsDecodingTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/VanillaFeaturesSettingsDecodingTest.java @@ -62,7 +62,7 @@ public class VanillaFeaturesSettingsDecodingTest { public void loadBuiltIns() throws IOException { Path packFolder = folder.newFolder("pack").toPath(); pack = LoadedPack.load(packFolder, ModuleHost.of(BuiltInPack.allBuiltIns()) - .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGE).copyingJarsTo(folder.newFolder("copies").toPath())); + .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGES).copyingJarsTo(folder.newFolder("copies").toPath())); decoder = new ModuleSettingsDecoder(pack.catalog(), packFolder, Gson::new); } diff --git a/core/src/test/java/art/arcane/iris/core/pack/ExportClosureComparisonTest.java b/core/src/test/java/art/arcane/iris/core/pack/ExportClosureComparisonTest.java index 7244a7aa2..d576ae244 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/ExportClosureComparisonTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/ExportClosureComparisonTest.java @@ -180,9 +180,9 @@ public class ExportClosureComparisonTest { biomes.forEach(closure::followSettingsOf); closure.follow(placements); Exported generic = new Exported( - new TreeSet<>(closure.keysOf(IrisStructure.class)), - new TreeSet<>(closure.keysOf(IrisJigsawPool.class)), - new TreeSet<>(closure.keysOf(IrisJigsawPiece.class)), + new TreeSet<>(closure.keysOf(StructureResources.STRUCTURES.id())), + new TreeSet<>(closure.keysOf(StructureResources.POOLS.id())), + new TreeSet<>(closure.keysOf(StructureResources.PIECES.id())), new TreeSet<>(closure.keysOf(LootTable.class)), new TreeSet<>(closure.objectKeys()), true, List.of()); diff --git a/core/src/test/java/art/arcane/iris/core/pack/PackValidatorImportedStructurePolicyTest.java b/core/src/test/java/art/arcane/iris/core/pack/PackValidatorImportedStructurePolicyTest.java index 0a3fa53df..2b89a5ae9 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/PackValidatorImportedStructurePolicyTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/PackValidatorImportedStructurePolicyTest.java @@ -84,6 +84,7 @@ public class PackValidatorImportedStructurePolicyTest { } private void write(File root, String relative, String content) throws Exception { + art.arcane.iris.core.modules.BuiltInModulesJar.installInto(root.toPath()); Path target = new File(root, relative).toPath(); Files.createDirectories(target.getParent()); Files.writeString(target, content, StandardCharsets.UTF_8); 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 a80ef362b..8a9c8359a 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 @@ -53,7 +53,13 @@ public class PackValidatorStructureGraphTest { write(pack, "structures/regional.json", "{}"); write(pack, "structures/library.json", "{}"); - assertEquals(Set.of("active", "regional"), StructureValidator.placedStructureKeys(pack)); + art.arcane.iris.core.loader.IrisData data = art.arcane.iris.core.loader.IrisData.openValidation(pack); + try { + assertEquals(Set.of("active", "regional"), StructureValidator.placedStructureKeys( + art.arcane.iris.core.modules.IrisValidationContext.forPack(data))); + } finally { + data.close(); + } } @Test @@ -263,6 +269,21 @@ public class PackValidatorStructureGraphTest { assertSingleErrorStartsWith("structures/castle.json: Structure 'castle' cannot be loaded: ", "structures/castle.json"); } + @Test + public void reportsAPoolBelowItsMinimumWeightByItsFieldAndNotOnlyAsMissing() throws Exception { + 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\",\"weight\":0}]}"); + write(pack, "jigsaw-pieces/castle/start.json", "{\"object\":\"castle/start\"}"); + writeObjectHeader(pack, "objects/castle/start.iob", 3, 9, 3); + + List errors = blockingErrors(pack); + + assertTrue(errors.toString(), errors.contains( + "jigsaw-pools/castle/start.json: Jigsaw pool 'castle/start' cannot be loaded: " + + "pieces[0].weight is 0; it must be at least 1")); + } + @Test public void reportsMalformedJigsawPoolJson() throws Exception { assertSingleErrorStartsWith("jigsaw-pools/castle/start.json: Jigsaw pool 'castle/start' cannot be loaded: ", @@ -548,6 +569,7 @@ public class PackValidatorStructureGraphTest { } private void write(File root, String relative, String content) throws Exception { + art.arcane.iris.core.modules.BuiltInModulesJar.installInto(root.toPath()); Path path = root.toPath().resolve(relative); Files.createDirectories(path.getParent()); Files.writeString(path, content, StandardCharsets.UTF_8); 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 26b0c8226..15feb2088 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 @@ -89,6 +89,7 @@ public class PackValidatorStructureTerrainBackendTest { } private void write(File root, String relativePath, String content) throws Exception { + art.arcane.iris.core.modules.BuiltInModulesJar.installInto(root.toPath()); Path path = root.toPath().resolve(relativePath); Files.createDirectories(path.getParent()); Files.writeString(path, content, StandardCharsets.UTF_8); diff --git a/core/src/test/java/art/arcane/iris/core/project/IrisImageMapSchemaTest.java b/core/src/test/java/art/arcane/iris/core/project/IrisImageMapSchemaTest.java index 238fd5b57..982796736 100644 --- a/core/src/test/java/art/arcane/iris/core/project/IrisImageMapSchemaTest.java +++ b/core/src/test/java/art/arcane/iris/core/project/IrisImageMapSchemaTest.java @@ -1,6 +1,6 @@ package art.arcane.iris.core.project; -import art.arcane.iris.core.modules.StructureModelModule; +import art.arcane.iris.modules.jigsaw.JigsawModule; import art.arcane.iris.engine.mantle.components.StructureModule; import art.arcane.iris.engine.object.noise.IrisGeneratorStyle; import art.arcane.iris.core.loader.IrisData; @@ -71,7 +71,7 @@ public class IrisImageMapSchemaTest { IrisData data = mock(IrisData.class); LoadedPack pack = mock(LoadedPack.class); PackModuleSet modules = mock(PackModuleSet.class); - when(pack.catalog()).thenReturn(ModuleResourceFixture.catalogOf(new StructureModelModule(), new StructureModule())); + when(pack.catalog()).thenReturn(ModuleResourceFixture.catalogOf(new JigsawModule(), new StructureModule())); when(modules.pack()).thenReturn(pack); when(data.getModules()).thenReturn(modules); ModuleResourceFixture.serve(data); diff --git a/core/src/test/java/art/arcane/iris/core/project/SchemaBuilderParityTest.java b/core/src/test/java/art/arcane/iris/core/project/SchemaBuilderParityTest.java index f826e269a..11a38a613 100644 --- a/core/src/test/java/art/arcane/iris/core/project/SchemaBuilderParityTest.java +++ b/core/src/test/java/art/arcane/iris/core/project/SchemaBuilderParityTest.java @@ -19,7 +19,7 @@ package art.arcane.iris.core.project; import art.arcane.iris.builtin.structure.StructureSettings; -import art.arcane.iris.core.modules.StructureModelModule; +import art.arcane.iris.modules.jigsaw.JigsawModule; import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.engine.mantle.components.StructureModule; import art.arcane.iris.core.loader.IrisData; @@ -516,7 +516,7 @@ public class SchemaBuilderParityTest { LoadedPack pack = mock(LoadedPack.class); PackModuleSet moduleSet = mock(PackModuleSet.class); when(pack.schema()).thenReturn(modules); - when(pack.catalog()).thenReturn(ModuleResourceFixture.catalogOf(new StructureModelModule(), new StructureModule())); + when(pack.catalog()).thenReturn(ModuleResourceFixture.catalogOf(new JigsawModule(), new StructureModule())); when(moduleSet.pack()).thenReturn(pack); when(data.getModules()).thenReturn(moduleSet); ModuleResourceFixture.serve(data); @@ -889,7 +889,7 @@ public class SchemaBuilderParityTest { try (LoadedPack pack = LoadedPack.load(Files.createDirectory(root.resolve("pack")), ModuleHost.of(modules) .exposing(IrisModuleHost.EXPOSED_PACKAGES.toArray(String[]::new)) - .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGE) + .describingHostTypesIn(IrisModuleHost.HOST_TYPE_PACKAGES) .copyingJarsTo(Files.createDirectory(root.resolve("copies"))))) { return pack.schema(); } diff --git a/core/src/test/java/art/arcane/iris/core/runtime/StudioOpenCoordinatorOpenKindTest.java b/core/src/test/java/art/arcane/iris/core/runtime/StudioOpenCoordinatorOpenKindTest.java index 3e8b9389f..d5a7ab7a8 100644 --- a/core/src/test/java/art/arcane/iris/core/runtime/StudioOpenCoordinatorOpenKindTest.java +++ b/core/src/test/java/art/arcane/iris/core/runtime/StudioOpenCoordinatorOpenKindTest.java @@ -60,8 +60,8 @@ public class StudioOpenCoordinatorOpenKindTest { } @Test - public void jigsawStudioLeavesWorkspaceClosedAndUsesItsDestinationTeleport() { - StudioOpenCoordinator.StudioOpenKind kind = StudioOpenCoordinator.StudioOpenKind.JIGSAW; + public void toolWorldsOpenLikeAJigsawStudioWithTheirOwnDestinationTeleport() { + StudioOpenCoordinator.StudioOpenKind kind = StudioOpenCoordinator.StudioOpenKind.TOOL; assertFalse(kind.openWorkspace()); assertFalse(kind.teleportThroughStandardEntry()); @@ -79,11 +79,11 @@ public class StudioOpenCoordinatorOpenKindTest { project, null, 1337L, - StudioOpenCoordinator.StudioOpenKind.JIGSAW, + StudioOpenCoordinator.StudioOpenKind.TOOL, null, null); - assertEquals(StudioOpenCoordinator.StudioOpenKind.JIGSAW, request.openKind()); + assertEquals(StudioOpenCoordinator.StudioOpenKind.TOOL, request.openKind()); assertTrue(request.requestedAtNanos() > 0L); } @@ -119,7 +119,7 @@ public class StudioOpenCoordinatorOpenKindTest { int serviceEnd = service.indexOf("public void open(VolmitSender", serviceStart); String serviceMethod = service.substring(serviceStart, serviceEnd); int transitionAdmission = serviceMethod.indexOf("studioTransitions.submit(() ->"); - int projectCapture = serviceMethod.indexOf("IrisProject project = activeProject"); + int projectCapture = serviceMethod.indexOf("IrisProject project = currentProject()"); int nativeDelegation = coordinatorMethod.indexOf( "WorldRuntimeControlService.get().teleportInMode(player, entry, GameMode.SPECTATOR)"); diff --git a/core/src/test/java/art/arcane/iris/core/runtime/StudioPainterSlotsTest.java b/core/src/test/java/art/arcane/iris/core/runtime/StudioPainterSlotsTest.java new file mode 100644 index 000000000..cb4b3a9aa --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/runtime/StudioPainterSlotsTest.java @@ -0,0 +1,67 @@ +package art.arcane.iris.core.runtime; + +import com.volmit.tooling.world.ChunkPainter; +import org.junit.After; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +public class StudioPainterSlotsTest { + private static final String WORLD = "iris-00000000-0000-0000-0000-000000000001"; + private static final String OTHER_WORLD = "iris-00000000-0000-0000-0000-000000000002"; + + private final ChunkPainter painter = (chunkX, chunkZ, canvas) -> { }; + + @After + public void removeSlots() { + StudioPainterSlots.remove(WORLD); + StudioPainterSlots.remove(OTHER_WORLD); + } + + @Test + public void aWorldIsPaintedFromTheMomentItsSlotIsInstalledUntilItIsRemoved() { + StudioPainterSlots.Slot slot = new StudioPainterSlots.Slot(painter, painted -> { }); + assertFalse(StudioPainterSlots.isInstalled(WORLD)); + + StudioPainterSlots.install(WORLD, slot); + + assertTrue(StudioPainterSlots.isInstalled(WORLD)); + assertSame(slot, StudioPainterSlots.slotOf(WORLD).orElseThrow()); + assertFalse("other worlds keep their pack", StudioPainterSlots.isInstalled(OTHER_WORLD)); + + StudioPainterSlots.remove(WORLD); + + assertFalse(StudioPainterSlots.isInstalled(WORLD)); + } + + @Test + public void aWorldHasOneSlotAtATime() { + StudioPainterSlots.install(WORLD, new StudioPainterSlots.Slot(painter, painted -> { })); + + assertThrows(IllegalStateException.class, + () -> StudioPainterSlots.install(WORLD, new StudioPainterSlots.Slot(painter, painted -> { }))); + } + + @Test + public void removingASlotThatIsNotThereOrAskingForANullNameIsHarmless() { + StudioPainterSlots.remove(WORLD); + StudioPainterSlots.remove(null); + + assertTrue(StudioPainterSlots.slotOf(null).isEmpty()); + assertTrue(StudioPainterSlots.slotOf(WORLD).isEmpty()); + } + + @Test + public void aPaintedChunkKeepsItsOwnCopyOfTheBlockEntities() { + List entities = new java.util.ArrayList<>(); + StudioPainterSlots.PaintedChunk chunk = new StudioPainterSlots.PaintedChunk(1, 2, entities); + entities.add(null); + + assertTrue(chunk.blockEntities().isEmpty()); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawPlanarTopologyTest.java b/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawPlanarTopologyTest.java index c0bc2dcdc..5fbade898 100644 --- a/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawPlanarTopologyTest.java +++ b/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawPlanarTopologyTest.java @@ -1,6 +1,6 @@ package art.arcane.iris.core.runtime.jigsaw; -import art.arcane.iris.engine.object.value.IrisPosition; +import com.volmit.geometry.BlockPosition; import org.junit.Test; import java.util.EnumMap; @@ -86,17 +86,17 @@ public class JigsawPlanarTopologyTest { new JigsawStudioPieceRules(0, 30, 0, 0, false), List.of()); JigsawStudioCellDimensions sourceDimensions = new JigsawStudioCellDimensions(3, 3, 5); - IrisPosition source = new IrisPosition(2, 1, 1); + BlockPosition source = new BlockPosition(2, 1, 1); - IrisPosition canonical = east.sourceToCanonicalPosition(source, sourceDimensions); - IrisPosition restored = east.canonicalToSourcePosition(canonical, sourceDimensions); + BlockPosition canonical = east.sourceToCanonicalPosition(source, sourceDimensions); + BlockPosition restored = east.canonicalToSourcePosition(canonical, sourceDimensions); assertEquals(new JigsawStudioCellDimensions(5, 3, 3), east.canonicalDimensions(sourceDimensions)); - assertEquals(1, canonical.getX()); - assertEquals(1, canonical.getY()); - assertEquals(0, canonical.getZ()); - assertEquals(source.getX(), restored.getX()); - assertEquals(source.getY(), restored.getY()); - assertEquals(source.getZ(), restored.getZ()); + assertEquals(1, canonical.x()); + assertEquals(1, canonical.y()); + assertEquals(0, canonical.z()); + assertEquals(source.x(), restored.x()); + assertEquals(source.y(), restored.y()); + assertEquals(source.z(), restored.z()); } } diff --git a/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphEditorResizeTest.java b/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphEditorResizeTest.java index 54f813d66..15f75f717 100644 --- a/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphEditorResizeTest.java +++ b/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphEditorResizeTest.java @@ -1,12 +1,13 @@ package art.arcane.iris.core.runtime.jigsaw; -import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.volmlib.util.math.IrisBlockVector; +import art.arcane.iris.core.structure.DeclaredObjects; +import art.arcane.iris.core.tooling.IrisObjectCodec; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.tooling.ObjectCodec; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; @@ -32,6 +33,8 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class JigsawStudioGraphEditorResizeTest { + private static final ObjectCodec CODEC = new IrisObjectCodec(); + @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); @@ -47,6 +50,7 @@ public class JigsawStudioGraphEditorResizeTest { JigsawStudioGraphEditor.VariantResizeResult result = JigsawStudioGraphEditor.resizePieceObject( packRoot, + CODEC, "resize/atomic", "resize/atomic/variants/corner/variant-2", new JigsawStudioCellDimensions(7, 4, 9)); @@ -55,12 +59,10 @@ public class JigsawStudioGraphEditorResizeTest { assertEquals(new JigsawStudioCellDimensions(16, 16, 16), result.previousDimensions()); assertEquals(new JigsawStudioCellDimensions(7, 4, 9), result.dimensions()); assertEquals(2, result.relocatedConnectors()); - assertEquals(new IrisBlockVector(16, 16, 16), IrisObject.sampleSize( - packRoot.resolve("objects/resize/atomic/corner.iob").toFile())); - assertEquals(new IrisBlockVector(7, 4, 9), IrisObject.sampleSize( - packRoot.resolve("objects/resize/atomic/variants/corner/variant-2.iob").toFile())); - assertEquals(new IrisBlockVector(16, 16, 16), IrisObject.sampleSize( - packRoot.resolve("objects/resize/atomic/end.iob").toFile())); + assertEquals(new BlockPosition(16, 16, 16), sizeOf(packRoot.resolve("objects/resize/atomic/corner.iob"))); + assertEquals(new BlockPosition(7, 4, 9), + sizeOf(packRoot.resolve("objects/resize/atomic/variants/corner/variant-2.iob"))); + assertEquals(new BlockPosition(16, 16, 16), sizeOf(packRoot.resolve("objects/resize/atomic/end.iob"))); JsonObject structure = readJson(packRoot.resolve("structures/resize/atomic.json")); JsonObject workcell = workcell(structure.getAsJsonArray("planarWorkcells"), "CORNER"); @@ -70,8 +72,8 @@ public class JigsawStudioGraphEditorResizeTest { JsonArray connectors = readJson(packRoot.resolve( "jigsaw-pieces/resize/atomic/variants/corner/variant-2.json")) .getAsJsonArray("connectors"); - assertEquals(new IrisPosition(3, 2, 0), connectorPosition(connectors, "NORTH_NEGATIVE_Z")); - assertEquals(new IrisPosition(6, 2, 4), connectorPosition(connectors, "EAST_POSITIVE_X")); + assertEquals(new BlockPosition(3, 2, 0), connectorPosition(connectors, "NORTH_NEGATIVE_Z")); + assertEquals(new BlockPosition(6, 2, 4), connectorPosition(connectors, "EAST_POSITIVE_X")); } @Test @@ -119,12 +121,11 @@ public class JigsawStudioGraphEditorResizeTest { @Test public void preservesCanonicalCoordinatesForRotatedVariantsAndMovesExplicitAirUnderlays() throws Exception { - IrisObject source = new IrisObject(7, 3, 5); - PlatformBlockState explicitAir = state("minecraft:air", true); - PlatformBlockState stone = state("minecraft:stone", false); - source.setUnsigned(6, 1, 2, explicitAir); - source.setUnsigned(4, 1, 1, stone); - IrisJigsawPiece piece = endPiece(IrisDirection.EAST_POSITIVE_X, new IrisPosition(6, 1, 2)); + BlockState explicitAir = new BlockState("minecraft:air"); + BlockState stone = new BlockState("minecraft:stone"); + JigsawStudioObject source = new JigsawStudioObject(7, 3, 5, + Map.of(new BlockPosition(6, 1, 2), explicitAir, new BlockPosition(4, 1, 1), stone), Map.of()); + IrisJigsawPiece piece = endPiece(JigsawDirection.EAST_POSITIVE_X, new BlockPosition(6, 1, 2)); JigsawStudioGraphEditor.PlanarPieceObjectResize result = JigsawStudioGraphEditor.resizePlanarPieceObject( @@ -134,22 +135,21 @@ public class JigsawStudioGraphEditorResizeTest { new JigsawStudioCellDimensions(9, 3, 11), "resize/rotated-east"); - IrisObject resized = result.object(); - assertEquals(11, resized.getW()); - assertEquals(3, resized.getH()); - assertEquals(9, resized.getD()); + JigsawStudioObject resized = result.object(); + assertEquals(11, resized.width()); + assertEquals(3, resized.height()); + assertEquals(9, resized.depth()); assertEquals(1, result.relocatedConnectors()); - assertEquals(new IrisPosition(10, 1, 4), piece.getConnectors().getFirst().getPosition()); - assertSame(explicitAir, blockAt(resized, 10, 1, 4)); - assertFalse(resized.getBlocks().containsKey(resized.getSigned(10, 1, 2))); - assertSame(stone, blockAt(resized, 8, 1, 1)); + assertEquals(new BlockPosition(10, 1, 4), piece.getConnectors().getFirst().getPosition()); + assertEquals(explicitAir, blockAt(resized, 10, 1, 4)); + assertFalse(resized.blocks().containsKey(new BlockPosition(10, 1, 2))); + assertEquals(stone, blockAt(resized, 8, 1, 1)); } @Test public void rejectsExplicitAirOutsideShrunkBoundsWithoutMutatingTheSource() { - IrisObject source = new IrisObject(8, 4, 8); - PlatformBlockState explicitAir = state("minecraft:air", true); - source.setUnsigned(7, 1, 1, explicitAir); + BlockState explicitAir = new BlockState("minecraft:air"); + JigsawStudioObject source = new JigsawStudioObject(8, 4, 8, Map.of(new BlockPosition(7, 1, 1), explicitAir), Map.of()); IrisJigsawPiece piece = new IrisJigsawPiece().setObject("resize/blank"); IOException failure = assertThrows( @@ -162,19 +162,18 @@ public class JigsawStudioGraphEditorResizeTest { "resize/blank")); assertTrue(failure.getMessage().contains("including explicit air")); - assertEquals(8, source.getW()); - assertSame(explicitAir, blockAt(source, 7, 1, 1)); + assertEquals(8, source.width()); + assertEquals(explicitAir, blockAt(source, 7, 1, 1)); } @Test public void rejectsConnectorDestinationCollisionsBeforeChangingThePiece() { - IrisObject source = new IrisObject(5, 3, 5); - PlatformBlockState underlay = state("minecraft:air", true); - PlatformBlockState collision = state("minecraft:stone", false); - source.setUnsigned(2, 1, 0, underlay); - source.setUnsigned(3, 1, 0, collision); - IrisPosition originalPosition = new IrisPosition(2, 1, 0); - IrisJigsawPiece piece = endPiece(IrisDirection.NORTH_NEGATIVE_Z, originalPosition.copy()); + BlockState underlay = new BlockState("minecraft:air"); + BlockState collision = new BlockState("minecraft:stone"); + JigsawStudioObject source = new JigsawStudioObject(5, 3, 5, + Map.of(new BlockPosition(2, 1, 0), underlay, new BlockPosition(3, 1, 0), collision), Map.of()); + BlockPosition originalPosition = new BlockPosition(2, 1, 0); + IrisJigsawPiece piece = endPiece(JigsawDirection.NORTH_NEGATIVE_Z, originalPosition); IOException failure = assertThrows( IOException.class, @@ -187,8 +186,8 @@ public class JigsawStudioGraphEditorResizeTest { assertTrue(failure.getMessage().contains("destination contains a stored block")); assertEquals(originalPosition, piece.getConnectors().getFirst().getPosition()); - assertSame(underlay, blockAt(source, 2, 1, 0)); - assertSame(collision, blockAt(source, 3, 1, 0)); + assertEquals(underlay, blockAt(source, 2, 1, 0)); + assertEquals(collision, blockAt(source, 3, 1, 0)); } private Path createPlanarProject(String structureKey) throws Exception { @@ -198,11 +197,11 @@ public class JigsawStudioGraphEditorResizeTest { JigsawStudioMode.PLANAR_JIGSAW, JigsawStudioCompatibilityTarget.IRIS_EXTENDED, new JigsawStudioCellDimensions(16, 16, 16)); - assertTrue(JigsawStudioProjectCreator.create(packRoot, options).successful()); + assertTrue(JigsawStudioProjectCreator.create(packRoot, CODEC, options).successful()); return packRoot; } - private static IrisJigsawPiece endPiece(IrisDirection direction, IrisPosition position) { + private static IrisJigsawPiece endPiece(JigsawDirection direction, BlockPosition position) { IrisJigsawPiece piece = new IrisJigsawPiece().setObject("resize/end"); piece.getConnectors().add(new IrisJigsawConnector() .setDirection(direction) @@ -220,15 +219,12 @@ public class JigsawStudioGraphEditorResizeTest { return sources; } - private static PlatformBlockState state(String key, boolean air) { - PlatformBlockState state = mock(PlatformBlockState.class); - when(state.key()).thenReturn(key); - when(state.isAir()).thenReturn(air); - return state; + private static BlockState blockAt(JigsawStudioObject object, int x, int y, int z) { + return object.blocks().get(new BlockPosition(x, y, z)); } - private static PlatformBlockState blockAt(IrisObject object, int x, int y, int z) { - return object.getBlocks().get(object.getSigned(x, y, z)); + private static BlockPosition sizeOf(Path objectFile) throws IOException { + return DeclaredObjects.sizeOf(CODEC.decode(Files.readAllBytes(objectFile))); } private static JsonObject readJson(Path path) throws IOException { @@ -245,14 +241,14 @@ public class JigsawStudioGraphEditorResizeTest { throw new AssertionError("Missing planar workcell " + archetype); } - private static IrisPosition connectorPosition(JsonArray connectors, String direction) { + private static BlockPosition connectorPosition(JsonArray connectors, String direction) { for (int index = 0; index < connectors.size(); index++) { JsonObject connector = connectors.get(index).getAsJsonObject(); if (!direction.equals(connector.get("direction").getAsString())) { continue; } JsonObject position = connector.getAsJsonObject("position"); - return new IrisPosition( + return new BlockPosition( position.get("x").getAsInt(), position.get("y").getAsInt(), position.get("z").getAsInt()); diff --git a/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphMapperTest.java b/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphMapperTest.java index 0282ed2dc..a22ad70c5 100644 --- a/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphMapperTest.java +++ b/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphMapperTest.java @@ -2,13 +2,13 @@ package art.arcane.iris.core.runtime.jigsaw; import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.loader.ResourceLoader; import art.arcane.iris.core.modules.ModuleResourceFixture; import art.arcane.iris.core.structure.authoring.StructureBackend; import art.arcane.iris.core.structure.authoring.StructureKey; import art.arcane.iris.core.structure.authoring.StructureOwnershipManifest; import art.arcane.iris.core.structure.authoring.StructureSource; -import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; +import art.arcane.iris.core.service.StudioToolPacks; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawMode; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; @@ -17,7 +17,6 @@ import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceRules; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcell; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype; -import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.volmlib.util.collection.KList; import org.junit.Rule; @@ -44,8 +43,8 @@ public class JigsawStudioGraphMapperTest { @Test public void horizontalConnectorsMapToPlanarTopology() { IrisJigsawPiece corner = new IrisJigsawPiece().setConnectors(new KList<>()); - corner.getConnectors().add(connector(IrisDirection.NORTH_NEGATIVE_Z)); - corner.getConnectors().add(connector(IrisDirection.EAST_POSITIVE_X)); + corner.getConnectors().add(connector(JigsawDirection.NORTH_NEGATIVE_Z)); + corner.getConnectors().add(connector(JigsawDirection.EAST_POSITIVE_X)); assertEquals(JigsawPlanarTopology.NORTH_EAST_CORNER, JigsawStudioGraphMapper.topologyOf(corner)); @@ -54,8 +53,8 @@ public class JigsawStudioGraphMapperTest { @Test public void verticalConnectorsDoNotChangePlanarMask() { IrisJigsawPiece end = new IrisJigsawPiece().setConnectors(new KList<>()); - end.getConnectors().add(connector(IrisDirection.WEST_NEGATIVE_X)); - end.getConnectors().add(connector(IrisDirection.UP_POSITIVE_Y)); + end.getConnectors().add(connector(JigsawDirection.WEST_NEGATIVE_X)); + end.getConnectors().add(connector(JigsawDirection.UP_POSITIVE_Y)); assertEquals(JigsawPlanarTopology.WEST_END, JigsawStudioGraphMapper.topologyOf(end)); @@ -72,7 +71,7 @@ public class JigsawStudioGraphMapperTest { start.getPieces().add(new IrisJigsawPieceEntry("village/end", 7)); start.getPieces().add(new IrisJigsawPieceEntry("village/east", 5)); resources.resource(StructureResources.POOLS, "village/start", start); - IrisJigsawPiece endPiece = planarPiece("village/end", IrisDirection.NORTH_NEGATIVE_Z) + IrisJigsawPiece endPiece = planarPiece("village/end", JigsawDirection.NORTH_NEGATIVE_Z) .setRules(new IrisJigsawPieceRules() .setMinimumDepth(1) .setMaximumDepth(4) @@ -82,13 +81,12 @@ public class JigsawStudioGraphMapperTest { endPiece.getThemes().add("spruce"); resources.resource(StructureResources.PIECES, "village/end", endPiece); resources.resource(StructureResources.PIECES, "village/east", planarPiece( - "village/east", IrisDirection.EAST_POSITIVE_X)); + "village/east", JigsawDirection.EAST_POSITIVE_X)); IrisStructure structure = new IrisStructure() .setStartPool("village/start") .setMode(IrisJigsawMode.PLANAR_JIGSAW); - JigsawStudioVariantCatalog catalog = JigsawStudioGraphMapper.catalog( - data, structure, JigsawStudioMode.PLANAR_JIGSAW); + JigsawStudioVariantCatalog catalog = planarCatalog(data, Path.of("pack"), "village/demo", structure); JigsawStudioVariant end = catalog.find("village/end").orElseThrow(); JigsawStudioVariant east = catalog.find("village/east").orElseThrow(); @@ -110,14 +108,13 @@ public class JigsawStudioGraphMapperTest { when(data.getDataFolder()).thenReturn(root.toFile()); ModuleResourceFixture resources = ModuleResourceFixture.serve(data); resources.resource(StructureResources.PIECES, "village/orphan", planarPiece( - "village/orphan", IrisDirection.NORTH_NEGATIVE_Z)); + "village/orphan", JigsawDirection.NORTH_NEGATIVE_Z)); resources.resource(StructureResources.PIECES, "village/incomplete", planarPiece( - "village/incomplete", IrisDirection.EAST_POSITIVE_X)); + "village/incomplete", JigsawDirection.EAST_POSITIVE_X)); IrisStructure structure = new IrisStructure() .setStartPool("village/start") .setMode(IrisJigsawMode.PLANAR_JIGSAW); - structure.setLoadKey("village/demo"); StructureKey key = new StructureKey("iris", "village/demo"); String hash = "0".repeat(64); StructureOwnershipManifest manifest = new StructureOwnershipManifest( @@ -135,8 +132,7 @@ public class JigsawStudioGraphMapperTest { Files.createDirectories(manifestPath.getParent()); Files.write(manifestPath, manifest.toJson()); - JigsawStudioVariantCatalog catalog = JigsawStudioGraphMapper.catalog( - data, structure, JigsawStudioMode.PLANAR_JIGSAW); + JigsawStudioVariantCatalog catalog = planarCatalog(data, root, "village/demo", structure); JigsawStudioVariant orphan = catalog.find("village/orphan").orElseThrow(); JigsawStudioVariant incomplete = catalog.find("village/incomplete").orElseThrow(); @@ -155,12 +151,11 @@ public class JigsawStudioGraphMapperTest { when(data.getDataFolder()).thenReturn(root.toFile()); ModuleResourceFixture resources = ModuleResourceFixture.serve(data); resources.resource(StructureResources.PIECES, "village/managed", planarPiece( - "village/managed", IrisDirection.NORTH_NEGATIVE_Z)); + "village/managed", JigsawDirection.NORTH_NEGATIVE_Z)); IrisStructure structure = new IrisStructure() .setStartPool("village/start") .setMode(IrisJigsawMode.PLANAR_JIGSAW); - structure.setLoadKey("village/managed"); StructureKey key = new StructureKey("iris", "village/managed"); String hash = "0".repeat(64); String sourcePath = "data/example/worldgen/template_pool/village/start.json"; @@ -188,10 +183,7 @@ public class JigsawStudioGraphMapperTest { Files.createDirectories(manifestPath.getParent()); Files.write(manifestPath, manifest.toJson()); - JigsawStudioVariantCatalog catalog = JigsawStudioGraphMapper.catalog( - data, - structure, - JigsawStudioMode.PLANAR_JIGSAW); + JigsawStudioVariantCatalog catalog = planarCatalog(data, root, "village/managed", structure); JigsawStudioVariant managed = catalog.find("village/managed").orElseThrow(); assertFalse(managed.owned()); @@ -203,9 +195,7 @@ public class JigsawStudioGraphMapperTest { @SuppressWarnings("unchecked") public void spatialLayoutExpandsToFitLargestReachableObject() { IrisData data = mock(IrisData.class); - ResourceLoader objectLoader = mock(ResourceLoader.class); - when(data.getObjectLoader()).thenReturn(objectLoader); - when(objectLoader.load("stronghold/tall-room")).thenReturn(new IrisObject(24, 32, 20)); + ModuleResourceFixture.serve(data).object("stronghold/tall-room", 24, 32, 20); JigsawStudioVariant variant = new JigsawStudioVariant( "stronghold/tall-room", "stronghold/tall-room", @@ -220,7 +210,7 @@ public class JigsawStudioGraphMapperTest { List.of()); JigsawStudioCellDimensions dimensions = JigsawStudioGraphMapper.expandSpatialDimensions( - data, + new JigsawStudioGraphMapper.Source(data.getPackResources(), Path.of("pack"), "stronghold"), new JigsawStudioVariantCatalog(List.of(variant)), new JigsawStudioCellDimensions(16, 16, 16)); @@ -231,16 +221,14 @@ public class JigsawStudioGraphMapperTest { @SuppressWarnings("unchecked") public void mapsAuthorLabelsAndCanonicalPerVariantDimensionsIndependently() { IrisData data = mock(IrisData.class); - ResourceLoader objectLoader = mock(ResourceLoader.class); ModuleResourceFixture resources = ModuleResourceFixture.serve(data); - when(data.getObjectLoader()).thenReturn(objectLoader); IrisJigsawPool start = new IrisJigsawPool().setPieces(new KList<>()); start.getPieces().add(new IrisJigsawPieceEntry("village/east-gate", 1)); resources.resource(StructureResources.POOLS, "village/start", start); - IrisJigsawPiece gate = planarPiece("village/east-gate", IrisDirection.EAST_POSITIVE_X) + IrisJigsawPiece gate = planarPiece("village/east-gate", JigsawDirection.EAST_POSITIVE_X) .setDisplayName("East Gatehouse"); resources.resource(StructureResources.PIECES, "village/east-gate", gate); - when(objectLoader.load("village/east-gate")).thenReturn(new IrisObject(7, 3, 5)); + resources.object("village/east-gate", 7, 3, 5); IrisStructure structure = new IrisStructure() .setStartPool("village/start") .setMode(IrisJigsawMode.PLANAR_JIGSAW); @@ -255,7 +243,7 @@ public class JigsawStudioGraphMapperTest { true)); } - JigsawStudioLayout layout = JigsawStudioGraphMapper.map(data, structure); + JigsawStudioLayout layout = map(data, structure); JigsawStudioBay workcell = layout.get(JigsawPlanarArchetype.END.stableId()); JigsawStudioVariant variant = layout.variantCatalog().find("village/east-gate").orElseThrow(); @@ -276,7 +264,7 @@ public class JigsawStudioGraphMapperTest { .setMode(IrisJigsawMode.SPATIAL_JIGSAW) .setSpatialWorkcellDisplayName("Stronghold Rooms"); - JigsawStudioBay workcell = JigsawStudioGraphMapper.map(data, structure) + JigsawStudioBay workcell = map(data, structure) .get(JigsawStudioLayout.SPATIAL_WORKCELL_ID); assertEquals("Spatial", workcell.canonicalDisplayName()); @@ -302,7 +290,7 @@ public class JigsawStudioGraphMapperTest { archetype != IrisJigsawWorkcellArchetype.TEE)); } - JigsawStudioLayout layout = JigsawStudioGraphMapper.map(data, structure); + JigsawStudioLayout layout = map(data, structure); assertEquals(new JigsawStudioCellDimensions(11, 9, 13), layout.get("workcell/corner").bounds().dimensions()); @@ -312,7 +300,16 @@ public class JigsawStudioGraphMapperTest { assertTrue(layout.variants(layout.get("workcell/tee")).isEmpty()); } - private static IrisJigsawPiece planarPiece(String objectKey, IrisDirection direction) { + private static JigsawStudioVariantCatalog planarCatalog(IrisData data, Path root, String structureKey, IrisStructure structure) { + return JigsawStudioGraphMapper.catalog(StudioToolPacks.toolPack(data.getPackResources()), root, structureKey, + structure, JigsawStudioMode.PLANAR_JIGSAW); + } + + private static JigsawStudioLayout map(IrisData data, IrisStructure structure) { + return JigsawStudioGraphMapper.map(StudioToolPacks.toolPack(data.getPackResources()), Path.of("pack"), "structure", structure); + } + + private static IrisJigsawPiece planarPiece(String objectKey, JigsawDirection direction) { IrisJigsawPiece piece = new IrisJigsawPiece() .setObject(objectKey) .setConnectors(new KList<>()); @@ -320,7 +317,7 @@ public class JigsawStudioGraphMapperTest { return piece; } - private static IrisJigsawConnector connector(IrisDirection direction) { + private static IrisJigsawConnector connector(JigsawDirection direction) { return new IrisJigsawConnector().setDirection(direction); } } diff --git a/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioManagedAuthoringGuardTest.java b/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioManagedAuthoringGuardTest.java index b07b5771d..f0d15626d 100644 --- a/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioManagedAuthoringGuardTest.java +++ b/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioManagedAuthoringGuardTest.java @@ -122,7 +122,7 @@ public class JigsawStudioManagedAuthoringGuardTest { JigsawStudioMode.PLANAR_JIGSAW, JigsawStudioCompatibilityTarget.IRIS_EXTENDED, new JigsawStudioCellDimensions(16, 16, 16)); - StructureWriteResult result = JigsawStudioProjectCreator.create(packRoot, options); + StructureWriteResult result = JigsawStudioProjectCreator.create(packRoot, new art.arcane.iris.core.tooling.IrisObjectCodec(), options); assertTrue(result.successful()); return packRoot; } diff --git a/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioPersistenceEditorsTest.java b/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioPersistenceEditorsTest.java index 273f3f5be..b63716b49 100644 --- a/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioPersistenceEditorsTest.java +++ b/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioPersistenceEditorsTest.java @@ -36,6 +36,8 @@ import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; public class JigsawStudioPersistenceEditorsTest { + private static final com.volmit.tooling.ObjectCodec CODEC = new art.arcane.iris.core.tooling.IrisObjectCodec(); + @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); @@ -129,7 +131,7 @@ public class JigsawStudioPersistenceEditorsTest { JigsawStudioMode.PLANAR_JIGSAW, JigsawStudioCompatibilityTarget.VANILLA_PORTABLE, new JigsawStudioCellDimensions(16, 16, 16)); - assertTrue(JigsawStudioProjectCreator.create(packRoot, options).successful()); + assertTrue(JigsawStudioProjectCreator.create(packRoot, CODEC, options).successful()); assertTrue(JigsawStudioStructureEditor.updateLimits( packRoot, @@ -184,6 +186,7 @@ public class JigsawStudioPersistenceEditorsTest { StructureWriteResult duplicated = JigsawStudioGraphEditor.duplicatePiece( packRoot, + CODEC, "variant/end", sourcePiece, targetPiece); @@ -243,6 +246,7 @@ public class JigsawStudioPersistenceEditorsTest { StructureWriteResult created = JigsawStudioGraphEditor.createBlankVariant( packRoot, + CODEC, "variant/cross", sourcePiece, targetPiece); @@ -455,7 +459,7 @@ public class JigsawStudioPersistenceEditorsTest { JigsawStudioMode.SPATIAL_JIGSAW, JigsawStudioCompatibilityTarget.IRIS_EXTENDED, new JigsawStudioCellDimensions(16, 16, 16)); - assertTrue(JigsawStudioProjectCreator.create(packRoot, options).successful()); + assertTrue(JigsawStudioProjectCreator.create(packRoot, CODEC, options).successful()); JigsawStudioGraphEditor.VariantFamilyCreation creation = JigsawStudioGraphEditor.duplicateActiveFamily( packRoot, @@ -479,7 +483,7 @@ public class JigsawStudioPersistenceEditorsTest { JigsawStudioMode.SPATIAL_JIGSAW, JigsawStudioCompatibilityTarget.IRIS_EXTENDED, new JigsawStudioCellDimensions(15, 15, 15)); - assertTrue(JigsawStudioProjectCreator.create(packRoot, options).successful()); + assertTrue(JigsawStudioProjectCreator.create(packRoot, CODEC, options).successful()); Map sources = new LinkedHashMap<>(); sources.put(JigsawStudioLayout.SPATIAL_WORKCELL_ID, "spatial/row/start"); @@ -537,7 +541,7 @@ public class JigsawStudioPersistenceEditorsTest { JigsawStudioMode.SPATIAL_JIGSAW, JigsawStudioCompatibilityTarget.IRIS_EXTENDED, new JigsawStudioCellDimensions(16, 16, 16)); - assertTrue(JigsawStudioProjectCreator.create(spatialRoot, spatialOptions).successful()); + assertTrue(JigsawStudioProjectCreator.create(spatialRoot, CODEC, spatialOptions).successful()); Path spatialObject = spatialRoot.resolve("objects/labels/spatial/start.iob"); byte[] spatialBefore = Files.readAllBytes(spatialObject); @@ -572,7 +576,7 @@ public class JigsawStudioPersistenceEditorsTest { JigsawStudioMode.PLANAR_JIGSAW, JigsawStudioCompatibilityTarget.IRIS_EXTENDED, new JigsawStudioCellDimensions(16, 16, 16)); - StructureWriteResult result = JigsawStudioProjectCreator.create(packRoot, options); + StructureWriteResult result = JigsawStudioProjectCreator.create(packRoot, CODEC, options); assertTrue(result.successful()); return packRoot; } diff --git a/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioProjectCreatorTest.java b/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioProjectCreatorTest.java index d3bd0df24..c3e6a45fe 100644 --- a/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioProjectCreatorTest.java +++ b/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioProjectCreatorTest.java @@ -8,7 +8,7 @@ import art.arcane.iris.engine.framework.structure.StructureAssemblyStatus; import art.arcane.iris.engine.framework.structure.StructureGraphCompilation; import art.arcane.iris.engine.framework.structure.StructureResourceBundleGraphCompiler; import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.value.IrisPosition; +import com.volmit.geometry.BlockPosition; import art.arcane.volmlib.util.math.IrisBlockVector; import art.arcane.volmlib.util.math.RNG; import com.google.gson.JsonObject; @@ -31,6 +31,8 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class JigsawStudioProjectCreatorTest { + private static final com.volmit.tooling.ObjectCodec CODEC = new art.arcane.iris.core.tooling.IrisObjectCodec(); + @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @@ -43,9 +45,9 @@ public class JigsawStudioProjectCreatorTest { JigsawStudioCompatibilityTarget.VANILLA_PORTABLE, new JigsawStudioCellDimensions(24, 12, 18)); - StructureResourceBundleGraphCompiler.requireViable(JigsawStudioProjectCreator.bundle(options)); + StructureResourceBundleGraphCompiler.requireViable(JigsawStudioProjectCreator.bundle(CODEC, options)); - StructureWriteResult created = JigsawStudioProjectCreator.create(temporaryDirectory, options); + StructureWriteResult created = JigsawStudioProjectCreator.create(temporaryDirectory, CODEC, options); assertTrue(created.successful()); assertTrue(Files.isRegularFile(temporaryDirectory.resolve("structures/settlement/test.json"))); @@ -99,7 +101,7 @@ public class JigsawStudioProjectCreatorTest { .getAsJsonObject().get("pool").getAsString()); assertTrue(cross.getAsJsonArray("themes").isEmpty()); - StructureWriteResult duplicate = JigsawStudioProjectCreator.create(temporaryDirectory, options); + StructureWriteResult duplicate = JigsawStudioProjectCreator.create(temporaryDirectory, CODEC, options); assertFalse(duplicate.successful()); assertEquals(StructureWriteResult.Status.ADD_ONLY_CONFLICT, duplicate.status()); @@ -153,7 +155,7 @@ public class JigsawStudioProjectCreatorTest { JigsawStudioCompatibilityTarget.IRIS_EXTENDED, new JigsawStudioCellDimensions(16, 16, 16)); - assertTrue(JigsawStudioProjectCreator.create(temporaryDirectory, options).successful()); + assertTrue(JigsawStudioProjectCreator.create(temporaryDirectory, CODEC, options).successful()); assertTrue(JigsawStudioStructureEditor.updateRequireCaps( temporaryDirectory, "caps/default", @@ -177,7 +179,7 @@ public class JigsawStudioProjectCreatorTest { JigsawStudioMode.PLANAR_JIGSAW, JigsawStudioCompatibilityTarget.IRIS_EXTENDED, new JigsawStudioCellDimensions(16, 16, 16)); - StructureResourceBundle source = JigsawStudioProjectCreator.bundle(options); + StructureResourceBundle source = JigsawStudioProjectCreator.bundle(CODEC, options); StructureResourceBundle.Builder builder = StructureResourceBundle.builder(source.key()) .source(source.source()) .backend(source.backend()) @@ -200,7 +202,7 @@ public class JigsawStudioProjectCreatorTest { for (long seed : List.of(0L, 1337L)) { StructureAssemblyResult result = StructureAssembler.forCompilation( compilation, - new IrisPosition(0, 64, 0)).assemble(new RNG(seed)); + new BlockPosition(0, 64, 0)).assemble(new RNG(seed)); assertEquals(result.detail(), StructureAssemblyStatus.COMPLETE, result.status()); } @@ -215,7 +217,7 @@ public class JigsawStudioProjectCreatorTest { JigsawStudioCompatibilityTarget.IRIS_EXTENDED, new JigsawStudioCellDimensions(15, 15, 15)); - StructureWriteResult result = JigsawStudioProjectCreator.create(temporaryDirectory, options); + StructureWriteResult result = JigsawStudioProjectCreator.create(temporaryDirectory, CODEC, options); assertTrue(result.successful()); JsonObject startPool = JsonParser.parseString(Files.readString( @@ -255,10 +257,10 @@ public class JigsawStudioProjectCreatorTest { .getAsJsonObject().getAsJsonObject("position").get("y").getAsInt()); StructureGraphCompilation compilation = StructureResourceBundleGraphCompiler.compile( - JigsawStudioProjectCreator.bundle(options)).getFirst(); + JigsawStudioProjectCreator.bundle(CODEC, options)).getFirst(); StructureAssemblyResult preview = StructureAssembler.forCompilation( compilation, - new IrisPosition(0, 0, 0)).assemble(new RNG(1337L)); + new BlockPosition(0, 0, 0)).assemble(new RNG(1337L)); assertEquals(preview.detail(), StructureAssemblyStatus.COMPLETE, preview.status()); assertTrue(preview.pieces().size() > 1); assertTrue(preview.pieces().size() <= 96); @@ -272,7 +274,7 @@ public class JigsawStudioProjectCreatorTest { JigsawStudioMode.PLANAR_JIGSAW, JigsawStudioCompatibilityTarget.IRIS_EXTENDED, new JigsawStudioCellDimensions(16, 16, 16)); - assertTrue(JigsawStudioProjectCreator.create(temporaryDirectory, options).successful()); + assertTrue(JigsawStudioProjectCreator.create(temporaryDirectory, CODEC, options).successful()); Path pool = temporaryDirectory.resolve("jigsaw-pools/settlement/test/pieces.json"); StructureWriteResult terminalPool = JigsawStudioGraphEditor.createPool( @@ -308,6 +310,7 @@ public class JigsawStudioProjectCreatorTest { assertTrue(JigsawStudioGraphEditor.createPiece( temporaryDirectory, + CODEC, "settlement/test", "settlement/test/pieces", "settlement/test/side", @@ -328,7 +331,7 @@ public class JigsawStudioProjectCreatorTest { temporaryDirectory, "settlement/test", "settlement/test/side", - new IrisPosition(8, 8, 0), + new BlockPosition(8, 8, 0), "village/road").successful()); JsonObject channeledPiece = JsonParser.parseString(Files.readString( temporaryDirectory.resolve("jigsaw-pieces/settlement/test/side.json"), @@ -362,10 +365,11 @@ public class JigsawStudioProjectCreatorTest { JigsawStudioMode.SPATIAL_JIGSAW, JigsawStudioCompatibilityTarget.IRIS_EXTENDED, new JigsawStudioCellDimensions(12, 10, 14)); - assertTrue(JigsawStudioProjectCreator.create(temporaryDirectory, options).successful()); + assertTrue(JigsawStudioProjectCreator.create(temporaryDirectory, CODEC, options).successful()); StructureWriteResult result = JigsawStudioGraphEditor.createPiece( temporaryDirectory, + CODEC, "stronghold/test", "stronghold/test/start", "stronghold/test/hall", @@ -413,6 +417,7 @@ public class JigsawStudioProjectCreatorTest { assertTrue(JigsawStudioGraphEditor.resizePieceObject( temporaryDirectory, + CODEC, "stronghold/test", "stronghold/test/hall", new JigsawStudioCellDimensions(16, 12, 18)).writeResult().successful()); @@ -444,9 +449,10 @@ public class JigsawStudioProjectCreatorTest { JigsawStudioMode.PLANAR_JIGSAW, JigsawStudioCompatibilityTarget.IRIS_EXTENDED, new JigsawStudioCellDimensions(10, 6, 14)); - assertTrue(JigsawStudioProjectCreator.create(temporaryDirectory, options).successful()); + assertTrue(JigsawStudioProjectCreator.create(temporaryDirectory, CODEC, options).successful()); assertTrue(JigsawStudioGraphEditor.createPiece( temporaryDirectory, + CODEC, "settlement/rectangular", "settlement/rectangular/pieces", "settlement/rectangular/east-end", @@ -461,6 +467,7 @@ public class JigsawStudioProjectCreatorTest { JigsawStudioGraphEditor.VariantResizeResult resized = JigsawStudioGraphEditor.resizePieceObject( temporaryDirectory, + CODEC, "settlement/rectangular", "settlement/rectangular/east-end", new JigsawStudioCellDimensions(12, 8, 18)); @@ -485,7 +492,7 @@ public class JigsawStudioProjectCreatorTest { JigsawStudioMode.PLANAR_JIGSAW, JigsawStudioCompatibilityTarget.IRIS_EXTENDED, new JigsawStudioCellDimensions(16, 16, 16)); - assertTrue(JigsawStudioProjectCreator.create(temporaryDirectory, options).successful()); + assertTrue(JigsawStudioProjectCreator.create(temporaryDirectory, CODEC, options).successful()); List pools = JigsawStudioGraphEditor.ownedPoolKeys( temporaryDirectory, @@ -498,6 +505,7 @@ public class JigsawStudioProjectCreatorTest { assertEquals("settlement/test/variants/end/variant-1", firstKey); assertTrue(JigsawStudioGraphEditor.duplicatePiece( temporaryDirectory, + CODEC, "settlement/test", "settlement/test/end", firstKey).successful()); diff --git a/core/src/test/java/art/arcane/iris/core/service/BoardSVCToolSidebarTest.java b/core/src/test/java/art/arcane/iris/core/service/BoardSVCToolSidebarTest.java new file mode 100644 index 000000000..f455ae43d --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/service/BoardSVCToolSidebarTest.java @@ -0,0 +1,49 @@ +package art.arcane.iris.core.service; + +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolText; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; + +public class BoardSVCToolSidebarTest { + private static final UUID WORLD = UUID.fromString("11111111-1111-1111-1111-111111111111"); + + @Test + public void aToolSidebarKeepsItsOwnCopyOfTheLines() { + List lines = new ArrayList<>(List.of(ToolText.plain("one"))); + BoardSVC.ToolSidebar sidebar = new BoardSVC.ToolSidebar(WORLD, ToolText.plain("Title"), lines); + lines.add(ToolText.plain("two")); + + assertEquals(List.of(ToolText.plain("one")), sidebar.lines()); + assertThrows(NullPointerException.class, () -> new BoardSVC.ToolSidebar(null, ToolText.plain("Title"), List.of())); + assertThrows(NullPointerException.class, () -> new BoardSVC.ToolSidebar(WORLD, null, List.of())); + } + + @Test + public void textOfASpanCannotCarryCodesOrMarkup() { + BoardSVC.ToolSidebar sidebar = new BoardSVC.ToolSidebar(WORLD, ToolText.EMPTY, + List.of(ToolText.plain("&cStructure§a"), ToolText.plain("line\nbreak"))); + + assertEquals(List.of("&cStructure‹red›", "line break"), BoardSVC.toolLines(sidebar)); + } + + @Test + public void spansBecomeTheBoardsCodesTheWayTheJigsawLinesWereWritten() { + ToolText separator = ToolText.builder() + .append(new ToolText.Span("-------------------", TextColor.GRAY, false, false, true)) + .build(); + ToolText value = ToolText.builder().aqua("Structure").gray(": village").build(); + ToolText mixed = ToolText.builder().yellow("Walk").append(" plain").build(); + + assertEquals("&7&m-------------------", BoardSVC.boardLine(separator)); + assertEquals("&bStructure&7: village", BoardSVC.boardLine(value)); + assertEquals("&eWalk&r plain", BoardSVC.boardLine(mixed)); + assertEquals("", BoardSVC.boardLine(ToolText.EMPTY)); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/service/FakeBlockRegistry.java b/core/src/test/java/art/arcane/iris/core/service/FakeBlockRegistry.java new file mode 100644 index 000000000..b2248cb7b --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/service/FakeBlockRegistry.java @@ -0,0 +1,61 @@ +package art.arcane.iris.core.service; + +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTurn; + +import java.util.Map; +import java.util.Optional; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** A block registry that knows every block by its key and turns the {@code facing} of the blocks that have one. */ +final class FakeBlockRegistry { + private static final String FACING = "facing"; + private static final Map FACING_DIRECTIONS = Map.of( + "north", new double[]{0, 0, -1}, + "east", new double[]{1, 0, 0}, + "south", new double[]{0, 0, 1}, + "west", new double[]{-1, 0, 0}); + + private FakeBlockRegistry() { + } + + static BlockRegistry create() { + BlockRegistry registry = mock(BlockRegistry.class); + when(registry.find(anyString())).thenAnswer(invocation -> + Optional.of(BlockState.parse(invocation.getArgument(0)))); + when(registry.rotate(any(), any())).thenAnswer(invocation -> + rotated(invocation.getArgument(0), invocation.getArgument(1))); + when(registry.tryRotate(any(), any())).thenAnswer(invocation -> + Optional.of(rotated(invocation.getArgument(0), invocation.getArgument(1)))); + return registry; + } + + static BlockState rotated(BlockState state, BlockTurn turn) { + String facing = state.properties().get(FACING); + if (facing == null) { + return state; + } + double[] direction = FACING_DIRECTIONS.get(facing); + BlockTurn.Direction turned = turn.turn(direction[0], direction[1], direction[2]); + return state.withProperty(FACING, nameOf(turned)); + } + + private static String nameOf(BlockTurn.Direction direction) { + String best = null; + double bestDot = -Double.MAX_VALUE; + for (Map.Entry candidate : FACING_DIRECTIONS.entrySet()) { + double[] vector = candidate.getValue(); + double dot = vector[0] * direction.x() + vector[2] * direction.z(); + if (dot > bestDot) { + bestDot = dot; + best = candidate.getKey(); + } + } + return best; + } +} diff --git a/core/src/test/java/art/arcane/iris/core/service/FakeStudioPack.java b/core/src/test/java/art/arcane/iris/core/service/FakeStudioPack.java new file mode 100644 index 000000000..0dff61061 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/service/FakeStudioPack.java @@ -0,0 +1,69 @@ +package art.arcane.iris.core.service; + +import art.arcane.iris.engine.framework.structure.StructureResources; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; +import com.volmit.block.BlockRegistry; +import com.volmit.geometry.BlockBox; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.GeneratedObject; +import com.volmit.object.PackObjects; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.ToolPack; + +import java.util.List; +import java.util.Optional; + +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** A pack whose pieces and objects a test sets by key, over a block registry that knows every block. */ +final class FakeStudioPack { + private static final String NAMESPACE = "test"; + + final ToolPack pack = mock(ToolPack.class); + final BlockRegistry blocks = FakeBlockRegistry.create(); + private final PackResources resources = mock(PackResources.class); + private final PackObjects objects = mock(PackObjects.class); + + FakeStudioPack() { + when(pack.resources()).thenReturn(resources); + when(resources.objects()).thenReturn(objects); + when(resources.blocks()).thenReturn(blocks); + when(resources.idOf(anyString())).thenAnswer(invocation -> idOf(invocation.getArgument(0))); + } + + FakeStudioPack piece(String key, IrisJigsawPiece piece) { + when(resources.find(StructureResources.PIECES, idOf(key))).thenReturn(Optional.of(piece)); + return this; + } + + /** An object without blocks of the given size, kept under {@code key}. */ + FakeStudioPack emptyObject(String key, int width, int height, int depth) { + when(objects.object(idOf(key))).thenReturn(Optional.of(new EmptyObject(width, height, depth))); + return this; + } + + private static ResourceId idOf(String key) { + return ResourceId.ofPackKey(NAMESPACE, key); + } + + private record EmptyObject(int width, int height, int depth) implements PlaceableObject { + @Override + public String name() { + return "empty"; + } + + @Override + public BlockPosition center() { + return new BlockPosition(width / 2, height / 2, depth / 2); + } + + @Override + public GeneratedObject geometry() { + return new GeneratedObject(new BlockBox(0, 0, 0, 0, 0, 0), new BlockPosition(0, 0, 0), List.of(), List.of()); + } + } +} diff --git a/core/src/test/java/art/arcane/iris/core/service/FakeToolPlayer.java b/core/src/test/java/art/arcane/iris/core/service/FakeToolPlayer.java new file mode 100644 index 000000000..b6887c376 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/service/FakeToolPlayer.java @@ -0,0 +1,204 @@ +package art.arcane.iris.core.service; + +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.Sender; +import com.volmit.tooling.world.Particle; +import com.volmit.tooling.world.ToolItem; +import com.volmit.tooling.world.ToolMenu; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolText; +import com.volmit.tooling.world.ToolWorld; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +/** A player who stands in one fake world and keeps everything a tool told them. */ +final class FakeToolPlayer implements ToolPlayer { + final List messages = new ArrayList<>(); + final List given = new ArrayList<>(); + final List texts = new ArrayList<>(); + final List> sidebars = new ArrayList<>(); + final List menus = new ArrayList<>(); + final List particles = new ArrayList<>(); + final List sounds = new ArrayList<>(); + final List waiting = new ArrayList<>(); + ToolWorld world; + BlockPosition position = new BlockPosition(0, 64, 0); + boolean sneaking; + boolean ownedElsewhere; + boolean inventoryFull; + int sidebarsHidden; + int menusClosed; + private final UUID id; + private final String name; + + FakeToolPlayer(UUID id, String name, ToolWorld world) { + this.id = id; + this.name = name; + this.world = world; + } + + @Override + public UUID id() { + return id; + } + + @Override + public String name() { + return name; + } + + @Override + public Sender sender() { + return new Sender() { + @Override + public String name() { + return name; + } + + @Override + public void info(String message) { + messages.add(message); + } + + @Override + public void success(String message) { + messages.add(message); + } + + @Override + public void error(String message) { + messages.add(message); + } + + @Override + public Optional extension(Class type) { + return Optional.empty(); + } + + @Override + public Optional player() { + return Optional.of(FakeToolPlayer.this); + } + }; + } + + @Override + public Optional world() { + return Optional.ofNullable(world); + } + + @Override + public BlockPosition position() { + return position; + } + + @Override + public float yaw() { + return 0; + } + + @Override + public float pitch() { + return 0; + } + + @Override + public boolean sneaking() { + return sneaking; + } + + @Override + public java.util.Optional targetBlock(int maxDistance) { + return java.util.Optional.empty(); + } + + @Override + public void run(Runnable task) { + if (ownedElsewhere) { + waiting.add(task); + return; + } + task.run(); + } + + /** Runs what waited for the player's thread, as that thread does. */ + void runWaiting() { + ownedElsewhere = false; + List tasks = List.copyOf(waiting); + waiting.clear(); + tasks.forEach(Runnable::run); + } + + @Override + public CompletableFuture teleport(ToolWorld target, double x, double y, double z, float yaw, float pitch) { + world = target; + position = new BlockPosition((int) Math.floor(x), (int) Math.floor(y), (int) Math.floor(z)); + return CompletableFuture.completedFuture(true); + } + + @Override + public void creative(boolean on) { + } + + @Override + public void message(ToolText text) { + texts.add(text); + messages.add(text.plainText()); + } + + @Override + public void actionBar(ToolText text) { + } + + @Override + public void sound(ResourceId sound, float volume, float pitch) { + sounds.add(new Sound(sound, volume, pitch)); + } + + record Sound(ResourceId id, float volume, float pitch) { + } + + @Override + public void sidebar(ToolText title, List lines) { + sidebars.add(lines); + } + + @Override + public void hideSidebar() { + sidebarsHidden++; + } + + @Override + public void particles(List dust) { + particles.addAll(dust); + } + + @Override + public boolean give(ToolItem item) { + if (inventoryFull) { + return false; + } + given.add(item); + return true; + } + + @Override + public Optional held() { + return given.isEmpty() ? Optional.empty() : Optional.of(given.getLast()); + } + + @Override + public void openMenu(ToolMenu menu) { + menus.add(menu); + } + + @Override + public void closeMenu() { + menusClosed++; + } +} diff --git a/core/src/test/java/art/arcane/iris/core/service/FakeToolWorld.java b/core/src/test/java/art/arcane/iris/core/service/FakeToolWorld.java new file mode 100644 index 000000000..1a991f610 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/service/FakeToolWorld.java @@ -0,0 +1,127 @@ +package art.arcane.iris.core.service; + +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.geometry.ChunkPos; +import com.volmit.object.BlockEntityData; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolWorld; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +/** A tool world that keeps its blocks in a map and runs every task at once, on the calling thread. */ +final class FakeToolWorld implements ToolWorld { + private static final BlockState AIR = BlockState.parse("minecraft:air"); + + final Map blocks = new HashMap<>(); + final Map entities = new HashMap<>(); + final List players = new ArrayList<>(); + final List repainted = new ArrayList<>(); + final List held = Collections.synchronizedList(new ArrayList<>()); + /** Every chunk is loaded except these. */ + final List unloadedChunks = Collections.synchronizedList(new ArrayList<>()); + volatile boolean schedulingFails; + volatile boolean holdTasks; + private final String name; + + FakeToolWorld(String name) { + this.name = name; + } + + @Override + public String name() { + return name; + } + + @Override + public int minY() { + return -64; + } + + @Override + public int maxY() { + return 320; + } + + @Override + public List players() { + return List.copyOf(players); + } + + @Override + public boolean owns(BlockPosition at) { + return !schedulingFails; + } + + @Override + public void run(BlockPosition at, Runnable task) { + if (holdTasks) { + held.add(task); + return; + } + task.run(); + } + + @Override + public CompletableFuture call(BlockPosition at, Supplier task) { + if (schedulingFails) { + return CompletableFuture.failedFuture(new IllegalStateException("not scheduled")); + } + if (holdTasks) { + CompletableFuture result = new CompletableFuture<>(); + held.add(() -> result.complete(task.get())); + return result; + } + return CompletableFuture.completedFuture(task.get()); + } + + /** Runs the tasks held back so far, the way the region thread gets to them. */ + void runHeld() { + List tasks; + synchronized (held) { + tasks = List.copyOf(held); + held.clear(); + } + tasks.forEach(Runnable::run); + } + + @Override + public BlockState block(BlockPosition at) { + return blocks.getOrDefault(at, AIR); + } + + @Override + public Optional blockEntity(BlockPosition at) { + return Optional.ofNullable(entities.get(at)); + } + + @Override + public void setBlock(BlockPosition at, BlockState state, Optional data) { + blocks.put(at, state); + data.ifPresentOrElse(entity -> entities.put(at, entity), () -> entities.remove(at)); + } + + @Override + public boolean loaded(ChunkPos chunk) { + return unloadedChunks.stream().noneMatch(chunk::equals); + } + + @Override + public CompletableFuture repaint(Collection chunks) { + repainted.addAll(chunks); + return CompletableFuture.completedFuture(null); + } + + @Override + public CompletableFuture close() { + return CompletableFuture.completedFuture(null); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioBlocksTest.java b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioBlocksTest.java new file mode 100644 index 000000000..840ad06df --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioBlocksTest.java @@ -0,0 +1,68 @@ +package art.arcane.iris.core.service; + +import art.arcane.iris.engine.framework.structure.assembly.PieceTurn; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import org.junit.Test; + +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +public class JigsawStudioBlocksTest { + private static final PieceTurn QUARTER_TURN = PieceTurn.aroundY(90); + + @Test + public void aBlockTheRegistryCannotTurnComesBackAsNothingNotAsAir() { + BlockRegistry registry = mock(BlockRegistry.class); + BlockState sign = BlockState.parse("minecraft:oak_sign"); + when(registry.tryRotate(any(), any())).thenReturn(Optional.empty()); + + assertNull(JigsawStudioBlocks.rotated(registry, sign, QUARTER_TURN)); + } + + @Test + public void airThatStaysAirIsNotABlockThatWasDropped() { + BlockRegistry registry = mock(BlockRegistry.class); + BlockState caveAir = BlockState.parse("minecraft:cave_air"); + when(registry.tryRotate(any(), any())).thenReturn(Optional.of(caveAir)); + + assertSame(caveAir, JigsawStudioBlocks.rotated(registry, caveAir, QUARTER_TURN)); + } + + @Test + public void aTurnThatTurnsNothingNeverAsksTheRegistry() { + BlockRegistry registry = mock(BlockRegistry.class); + BlockState stairs = BlockState.parse("minecraft:oak_stairs[facing=east]"); + + assertSame(stairs, JigsawStudioBlocks.rotated(registry, stairs, PieceTurn.NONE)); + verifyNoInteractions(registry); + } + + @Test + public void aWrittenBlockMatchesOnlyTheSameBlockWithEveryPropertyEqual() { + BlockState written = BlockState.parse("minecraft:chest[facing=east,type=single,waterlogged=false]"); + + assertTrue(JigsawStudioService.sameBlock( + BlockState.parse("minecraft:chest[facing=east,type=single,waterlogged=false]"), written)); + assertFalse(JigsawStudioService.sameBlock( + BlockState.parse("minecraft:chest[facing=east,type=single,waterlogged=true]"), written)); + assertFalse(JigsawStudioService.sameBlock(BlockState.parse("minecraft:chest"), written)); + assertFalse(JigsawStudioService.sameBlock(BlockState.parse("minecraft:trapped_chest"), written)); + } + + @Test + public void everyKindOfAirIsItsOwnBlockWhenMaterializationIsChecked() { + assertFalse(JigsawStudioService.sameBlock( + BlockState.parse("minecraft:cave_air"), BlockState.parse("minecraft:air"))); + assertEquals(BlockState.parse("minecraft:air"), JigsawStudioBlocks.AIR); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/service/BoardSVCJigsawContextTest.java b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioBoardContextTest.java similarity index 75% rename from core/src/test/java/art/arcane/iris/core/service/BoardSVCJigsawContextTest.java rename to core/src/test/java/art/arcane/iris/core/service/JigsawStudioBoardContextTest.java index 120618780..4f71d3530 100644 --- a/core/src/test/java/art/arcane/iris/core/service/BoardSVCJigsawContextTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioBoardContextTest.java @@ -1,6 +1,7 @@ package art.arcane.iris.core.service; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; +import com.volmit.tooling.world.ToolText; import org.junit.Test; import java.util.List; @@ -12,7 +13,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; -public class BoardSVCJigsawContextTest { +public class JigsawStudioBoardContextTest { @Test public void rendersWorkcellIdentityWithoutModeOrOrientationData() { JigsawStudioBoardContext context = context( @@ -23,7 +24,7 @@ public class BoardSVCJigsawContextTest { "Right-click the chest for variants" ); - List lines = BoardSVC.jigsawLines(context); + List lines = plain(context.sidebarLines()); assertEquals(List.of( "&7&m-------------------", @@ -35,6 +36,17 @@ public class BoardSVCJigsawContextTest { "&7&m-------------------", "&eRight-click the chest for variants", "&7&m-------------------" + ), context.sidebarLines().stream().map(BoardSVC::boardLine).toList()); + assertEquals(List.of( + "-------------------", + "Jigsaw Studio", + "Structure: village", + "Workcell: Corner", + "Variant: mossy", + "State: Unsaved", + "-------------------", + "Right-click the chest for variants", + "-------------------" ), lines); String rendered = String.join("\n", lines).toLowerCase(Locale.ROOT); assertFalse(rendered.contains("mode")); @@ -56,6 +68,16 @@ public class BoardSVCJigsawContextTest { "Use the workcell chest to choose a variant" ); + assertEquals(List.of( + "-------------------", + "Jigsaw Studio", + "Structure: village", + "Mode: Spatial", + "-------------------", + "Walk into a workcell", + "Use the workcell chest to choose a variant", + "-------------------" + ), plain(context.sidebarLines())); assertEquals(List.of( "&7&m-------------------", "&dJigsaw Studio", @@ -65,7 +87,7 @@ public class BoardSVCJigsawContextTest { "&eWalk into a workcell", "&7Use the workcell chest to choose a variant", "&7&m-------------------" - ), BoardSVC.jigsawLines(context)); + ), context.sidebarLines().stream().map(BoardSVC::boardLine).toList()); } @Test @@ -81,11 +103,11 @@ public class BoardSVCJigsawContextTest { JigsawStudioBoardState.SAVED, "Triple-sneak for controls"); - List lines = BoardSVC.jigsawLines(context); + List lines = plain(context.sidebarLines()); - assertTrue(lines.contains("&bWorkcell&7: Village Entrances")); - assertTrue(lines.contains("&bRole&7: End Cap")); - assertTrue(lines.contains("&bVariant&7: Grand Longhouse")); + assertTrue(lines.contains("Workcell: Village Entrances")); + assertTrue(lines.contains("Role: End Cap")); + assertTrue(lines.contains("Variant: Grand Longhouse")); } @Test @@ -105,10 +127,11 @@ public class BoardSVCJigsawContextTest { JigsawStudioBoardContext changedVariant = context(worldId, requestId, "ruined", JigsawStudioBoardState.SAVED); JigsawStudioBoardContext changedState = context(worldId, requestId, "mossy", JigsawStudioBoardState.UNSAVED); - assertFalse(BoardSVC.shouldRenderJigsaw(previous, equal)); - assertTrue(BoardSVC.shouldRenderJigsaw(previous, changedVariant)); - assertTrue(BoardSVC.shouldRenderJigsaw(previous, changedState)); - assertTrue(BoardSVC.shouldRenderJigsaw(null, previous)); + assertEquals(previous.sidebarLines(), equal.sidebarLines()); + assertFalse(previous.sidebarLines().equals(changedVariant.sidebarLines())); + assertFalse(previous.sidebarLines().equals(changedState.sidebarLines())); + assertEquals(previous, equal); + assertFalse(previous.equals(changedVariant)); } @Test @@ -154,6 +177,16 @@ public class BoardSVCJigsawContextTest { )); } + private static List plain(List lines) { + return lines.stream().map(ToolText::plainText).toList(); + } + + @Test + public void theSidebarKeepsThePlatformTitle() { + assertTrue(context(JigsawStudioMode.PLANAR_JIGSAW, "", "", JigsawStudioBoardState.SAVED, "") + .sidebarTitle().isEmpty()); + } + private JigsawStudioBoardContext context( JigsawStudioMode mode, String workcell, diff --git a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioLifecycleTest.java b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioLifecycleTest.java index 65bf2e3d6..f1e202fe2 100644 --- a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioLifecycleTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioLifecycleTest.java @@ -1,7 +1,5 @@ package art.arcane.iris.core.service; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioActivation; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBay; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget; @@ -11,103 +9,67 @@ import art.arcane.iris.core.runtime.jigsaw.JigsawStudioPieceRules; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioSession; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariant; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariantCatalog; -import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.platform.studio.generators.JigsawStudioGenerator; -import art.arcane.iris.util.common.scheduling.J; import art.arcane.volmlib.util.collection.KMap; -import org.bukkit.World; -import org.bukkit.event.entity.CreatureSpawnEvent; +import com.volmit.ModuleLog; import org.junit.After; import org.junit.Test; -import org.mockito.MockedStatic; import java.lang.reflect.Constructor; import java.lang.reflect.Field; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; -import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockStatic; public class JigsawStudioLifecycleTest { private static final UUID OWNER = UUID.fromString("11111111-1111-1111-1111-111111111111"); private static final UUID OTHER_OWNER = UUID.fromString("22222222-2222-2222-2222-222222222222"); + private static final long REPLACEMENT_WAIT_SECONDS = 10L; + + private final JigsawStudioService service = new JigsawStudioService(mock(ModuleLog.class)); + private final JigsawStudioRegistry registry = service.registry(); @After - public void clearLifecycle() { - JigsawStudioActivation.finishOpen(OWNER); - JigsawStudioActivation.finishOpen(OTHER_OWNER); - JigsawStudioActivation.deactivate("overworld"); + public void stopStudio() { + registry.finishOpen(OWNER); + registry.finishOpen(OTHER_OWNER); + registry.deactivate("overworld"); } @Test public void openingLeaseAndActivationOwnerAreCentralized() { - assertTrue(JigsawStudioActivation.tryBeginOpen(OWNER)); - assertFalse(JigsawStudioActivation.tryBeginOpen(OTHER_OWNER)); - JigsawStudioActivation.finishOpen(OTHER_OWNER); - assertEquals(OWNER, JigsawStudioActivation.openingOwnerId()); + assertTrue(registry.tryBeginOpen(OWNER)); + assertFalse(registry.tryBeginOpen(OTHER_OWNER)); + registry.finishOpen(OTHER_OWNER); + assertEquals(OWNER, registry.openingOwnerId()); - JigsawStudioActivation.Request request = activateOwnedStudio(); + JigsawStudioRequest request = activateOwnedStudio(); assertEquals(OWNER, request.ownerId()); - assertEquals(OWNER, JigsawStudioActivation.activeOwnerId()); - JigsawStudioActivation.finishOpen(OWNER); - assertNull(JigsawStudioActivation.openingOwnerId()); - assertFalse(JigsawStudioActivation.tryBeginOpen(OTHER_OWNER)); - } - - @Test - public void studioRejectsNaturalCreatureSpawns() { - assertTrue(JigsawStudioService.isNaturalStudioSpawn( - CreatureSpawnEvent.SpawnReason.NATURAL)); - assertFalse(JigsawStudioService.isNaturalStudioSpawn( - CreatureSpawnEvent.SpawnReason.CUSTOM)); - assertFalse(JigsawStudioService.isNaturalStudioSpawn( - CreatureSpawnEvent.SpawnReason.SPAWNER)); - } - - @Test - public void committedStudioActivationDisablesNaturalMobSpawning() throws IOException { - String source = Files.readString(Path.of( - "src/main/java/art/arcane/iris/core/service/JigsawStudioService.java")).replace("\r\n", "\n"); - int registerStart = source.indexOf("public void register("); - int commitStart = source.indexOf("public void activationCommitted(", registerStart); - int commitEnd = source.indexOf("public void markChunkGenerated(", commitStart); - int helperStart = source.indexOf("static void disableNaturalStudioSpawning(", commitEnd); - String register = source.substring(registerStart, commitStart); - String commit = source.substring(commitStart, commitEnd); - String helper = source.substring(helperStart); - - assertFalse(register.contains("disableNaturalStudioSpawning(world)")); - assertTrue(commit.contains("disableNaturalStudioSpawning(world)")); - assertTrue(helper.contains("setGameRule(GameRules.SPAWN_MOBS, false)")); + assertEquals(OWNER, registry.activeOwnerId()); + registry.finishOpen(OWNER); + assertNull(registry.openingOwnerId()); + assertFalse(registry.tryBeginOpen(OTHER_OWNER)); } @Test public void closeAuthorizationChecksOwnerDirtyStateAndSaveBarrierAtomically() { - assertTrue(JigsawStudioActivation.tryBeginOpen(OWNER)); - JigsawStudioActivation.Request request = activateOwnedStudio(); - JigsawStudioActivation.finishOpen(OWNER); - JigsawStudioSession session = JigsawStudioActivation.getSession(request.requestId()); - JigsawStudioService service = new JigsawStudioService(); + assertTrue(registry.tryBeginOpen(OWNER)); + JigsawStudioRequest request = activateOwnedStudio(); + registry.finishOpen(OWNER); + JigsawStudioSession session = registry.getSession(request.requestId()); assertEquals( JigsawStudioService.CloseStart.NOT_OWNER, @@ -147,62 +109,44 @@ public class JigsawStudioLifecycleTest { } @Test - public void ownerReplacementWaitsForAutosaveThenClaimsClose() { - assertTrue(JigsawStudioActivation.tryBeginOpen(OWNER)); - JigsawStudioActivation.Request request = activateOwnedStudio(); - JigsawStudioActivation.finishOpen(OWNER); - JigsawStudioSession session = JigsawStudioActivation.getSession(request.requestId()); - JigsawStudioService service = new JigsawStudioService(); + public void ownerReplacementWaitsForAutosaveThenClaimsClose() throws Exception { + assertTrue(registry.tryBeginOpen(OWNER)); + JigsawStudioRequest request = activateOwnedStudio(); + registry.finishOpen(OWNER); + JigsawStudioSession session = registry.getSession(request.requestId()); assertEquals( JigsawStudioSession.DirtyStatus.MARKED, session.markWorkcellDirty(JigsawStudioLayout.SPATIAL_WORKCELL_ID).status()); - AtomicReference retry = new AtomicReference<>(); - try (MockedStatic scheduling = mockStatic(J.class)) { - scheduling.when(() -> J.s(any(Runnable.class), eq(5))).thenAnswer(invocation -> { - retry.set(invocation.getArgument(0)); - return null; - }); - CompletableFuture readiness = service.awaitCloseForReplacement( - request.requestId(), OWNER); + CompletableFuture readiness = service.awaitCloseForReplacement(request.requestId(), OWNER); - assertFalse(readiness.isDone()); - assertTrue(retry.get() != null); - JigsawStudioSession.SaveStart save = session.beginSave( - JigsawStudioLayout.SPATIAL_WORKCELL_ID); - assertEquals(JigsawStudioSession.SaveStatus.STARTED, save.status()); - assertTrue(session.markWorkcellSaved(save.identity().orElseThrow())); - retry.get().run(); + assertFalse(readiness.isDone()); + JigsawStudioSession.SaveStart save = session.beginSave(JigsawStudioLayout.SPATIAL_WORKCELL_ID); + assertEquals(JigsawStudioSession.SaveStatus.STARTED, save.status()); + assertTrue(session.markWorkcellSaved(save.identity().orElseThrow())); - readiness.join(); - assertNull(service.closeProtectionFailure(request.requestId())); - } + readiness.get(REPLACEMENT_WAIT_SECONDS, TimeUnit.SECONDS); + assertNull(service.closeProtectionFailure(request.requestId())); } @Test public void nonOwnerReplacementFailsWithoutWaiting() { - assertTrue(JigsawStudioActivation.tryBeginOpen(OWNER)); - JigsawStudioActivation.Request request = activateOwnedStudio(); - JigsawStudioActivation.finishOpen(OWNER); - JigsawStudioService service = new JigsawStudioService(); + assertTrue(registry.tryBeginOpen(OWNER)); + JigsawStudioRequest request = activateOwnedStudio(); + registry.finishOpen(OWNER); - try (MockedStatic scheduling = mockStatic(J.class)) { - CompletableFuture readiness = service.awaitCloseForReplacement( - request.requestId(), OTHER_OWNER); + CompletableFuture readiness = service.awaitCloseForReplacement(request.requestId(), OTHER_OWNER); - assertTrue(readiness.isCompletedExceptionally()); - scheduling.verifyNoInteractions(); - } + assertTrue(readiness.isCompletedExceptionally()); } @Test public void lateJigsawGuiMutationKeepsCloseBehindTheFinalSnapshotAndAutosaveBarriers() throws ReflectiveOperationException { - assertTrue(JigsawStudioActivation.tryBeginOpen(OWNER)); - JigsawStudioActivation.Request request = activateOwnedStudio(); - JigsawStudioActivation.finishOpen(OWNER); - JigsawStudioSession session = JigsawStudioActivation.getSession(request.requestId()); - JigsawStudioService service = new JigsawStudioService(); + assertTrue(registry.tryBeginOpen(OWNER)); + JigsawStudioRequest request = activateOwnedStudio(); + registry.finishOpen(OWNER); + JigsawStudioSession session = registry.getSession(request.requestId()); KMap baseline = new KMap<>(); baseline.put("name", "iris:start"); KMap updated = new KMap<>(); @@ -214,21 +158,11 @@ public class JigsawStudioLifecycleTest { UUID.class, UUID.class, int.class, int.class, int.class); constructor.setAccessible(true); Object key = constructor.newInstance(request.requestId(), UUID.randomUUID(), 1, 64, 1); - Class studioType = Class.forName(JigsawStudioService.class.getName() + "$ActiveStudio"); - Constructor studioConstructor = studioType.getDeclaredConstructor( - UUID.class, - World.class, - Engine.class, - JigsawStudioGenerator.class, - ConcurrentHashMap.class, - Set.class, - AtomicLong.class); - studioConstructor.setAccessible(true); - World world = mock(World.class); - Object studio = studioConstructor.newInstance( + FakeToolWorld world = new FakeToolWorld("jigsaw-" + request.requestId()); + world.schedulingFails = true; + JigsawStudioService.ActiveStudio studio = new JigsawStudioService.ActiveStudio( UUID.randomUUID(), world, - mock(Engine.class), mock(JigsawStudioGenerator.class), new ConcurrentHashMap<>(), ConcurrentHashMap.newKeySet(), @@ -236,7 +170,7 @@ public class JigsawStudioLifecycleTest { Class watchType = Class.forName(JigsawStudioService.class.getName() + "$JigsawTileWatch"); Constructor watchConstructor = watchType.getDeclaredConstructor( keyType, - studioType, + JigsawStudioService.ActiveStudio.class, UUID.class, String.class, KMap.class, @@ -257,19 +191,11 @@ public class JigsawStudioLifecycleTest { Map watches = (Map) watchesField.get(service); watches.put(key, watch); - try (MockedStatic scheduling = mockStatic(J.class)) { - scheduling.when(() -> J.isOwnedByCurrentRegion(any(World.class), anyInt(), anyInt())) - .thenReturn(false); - scheduling.when(() -> J.runRegion( - any(World.class), anyInt(), anyInt(), any(Runnable.class))) - .thenReturn(false); - assertEquals( - JigsawStudioService.CloseStart.OPERATION_IN_PROGRESS, - service.tryBeginClose(request.requestId(), OWNER, false)); - assertTrue(service.closeProtectionFailure(request.requestId()).contains("finalizing")); - assertEquals(1, watches.size()); - scheduling.verify(() -> J.s(any(Runnable.class), eq(5))); - } + assertEquals( + JigsawStudioService.CloseStart.OPERATION_IN_PROGRESS, + service.tryBeginClose(request.requestId(), OWNER, false)); + assertTrue(service.closeProtectionFailure(request.requestId()).contains("finalizing")); + assertEquals(1, watches.size()); watches.clear(); assertEquals( @@ -282,10 +208,9 @@ public class JigsawStudioLifecycleTest { @Test public void exportLeaseSerializesSavesAndCloseAgainstThePinnedRequest() { - assertTrue(JigsawStudioActivation.tryBeginOpen(OWNER)); - JigsawStudioActivation.Request request = activateOwnedStudio(); - JigsawStudioActivation.finishOpen(OWNER); - JigsawStudioService service = new JigsawStudioService(); + assertTrue(registry.tryBeginOpen(OWNER)); + JigsawStudioRequest request = activateOwnedStudio(); + registry.finishOpen(OWNER); assertEquals( JigsawStudioService.ExportStart.NOT_OWNER, @@ -365,14 +290,14 @@ public class JigsawStudioLifecycleTest { assertEquals(end.stableId(), session.selectedBayId().orElseThrow()); } - private static JigsawStudioActivation.Request activateOwnedStudio() { - return JigsawStudioActivation.activate( + private JigsawStudioRequest activateOwnedStudio() { + return registry.activate( "overworld", "stronghold", JigsawStudioMode.SPATIAL_JIGSAW, JigsawStudioCompatibilityTarget.IRIS_EXTENDED, new JigsawStudioCellDimensions(16, 16, 16), - mock(IrisData.class), + StudioToolPacks.toolPack(), JigsawStudioLayout.create( JigsawStudioMode.SPATIAL_JIGSAW, new JigsawStudioCellDimensions(16, 16, 16), diff --git a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioMarkerParserTest.java b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioMarkerParserTest.java index 034c7d7a6..219370d40 100644 --- a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioMarkerParserTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioMarkerParserTest.java @@ -1,9 +1,8 @@ package art.arcane.iris.core.service; -import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint; -import org.bukkit.block.Orientation; import org.junit.Test; import java.util.LinkedHashMap; @@ -14,19 +13,24 @@ import static org.junit.Assert.assertThrows; public class JigsawStudioMarkerParserTest { @Test - public void mapsEveryBukkitJigsawOrientation() { - assertDirections(Orientation.DOWN_EAST, IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.EAST_POSITIVE_X); - assertDirections(Orientation.DOWN_NORTH, IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.NORTH_NEGATIVE_Z); - assertDirections(Orientation.DOWN_SOUTH, IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.SOUTH_POSITIVE_Z); - assertDirections(Orientation.DOWN_WEST, IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.WEST_NEGATIVE_X); - assertDirections(Orientation.UP_EAST, IrisDirection.UP_POSITIVE_Y, IrisDirection.EAST_POSITIVE_X); - assertDirections(Orientation.UP_NORTH, IrisDirection.UP_POSITIVE_Y, IrisDirection.NORTH_NEGATIVE_Z); - assertDirections(Orientation.UP_SOUTH, IrisDirection.UP_POSITIVE_Y, IrisDirection.SOUTH_POSITIVE_Z); - assertDirections(Orientation.UP_WEST, IrisDirection.UP_POSITIVE_Y, IrisDirection.WEST_NEGATIVE_X); - assertDirections(Orientation.WEST_UP, IrisDirection.WEST_NEGATIVE_X, IrisDirection.UP_POSITIVE_Y); - assertDirections(Orientation.EAST_UP, IrisDirection.EAST_POSITIVE_X, IrisDirection.UP_POSITIVE_Y); - assertDirections(Orientation.NORTH_UP, IrisDirection.NORTH_NEGATIVE_Z, IrisDirection.UP_POSITIVE_Y); - assertDirections(Orientation.SOUTH_UP, IrisDirection.SOUTH_POSITIVE_Z, IrisDirection.UP_POSITIVE_Y); + public void mapsEveryJigsawOrientation() { + assertDirections("down_east", JigsawDirection.DOWN_NEGATIVE_Y, JigsawDirection.EAST_POSITIVE_X); + assertDirections("down_north", JigsawDirection.DOWN_NEGATIVE_Y, JigsawDirection.NORTH_NEGATIVE_Z); + assertDirections("down_south", JigsawDirection.DOWN_NEGATIVE_Y, JigsawDirection.SOUTH_POSITIVE_Z); + assertDirections("down_west", JigsawDirection.DOWN_NEGATIVE_Y, JigsawDirection.WEST_NEGATIVE_X); + assertDirections("up_east", JigsawDirection.UP_POSITIVE_Y, JigsawDirection.EAST_POSITIVE_X); + assertDirections("up_north", JigsawDirection.UP_POSITIVE_Y, JigsawDirection.NORTH_NEGATIVE_Z); + assertDirections("up_south", JigsawDirection.UP_POSITIVE_Y, JigsawDirection.SOUTH_POSITIVE_Z); + assertDirections("up_west", JigsawDirection.UP_POSITIVE_Y, JigsawDirection.WEST_NEGATIVE_X); + assertDirections("west_up", JigsawDirection.WEST_NEGATIVE_X, JigsawDirection.UP_POSITIVE_Y); + assertDirections("east_up", JigsawDirection.EAST_POSITIVE_X, JigsawDirection.UP_POSITIVE_Y); + assertDirections("north_up", JigsawDirection.NORTH_NEGATIVE_Z, JigsawDirection.UP_POSITIVE_Y); + assertDirections("south_up", JigsawDirection.SOUTH_POSITIVE_Z, JigsawDirection.UP_POSITIVE_Y); + } + + @Test + public void rejectsAnOrientationNoJigsawHas() { + assertThrows(IllegalArgumentException.class, () -> JigsawStudioMarkerParser.directions("sideways")); } @Test @@ -37,13 +41,13 @@ public class JigsawStudioMarkerParserTest { nbt.put("placement_priority", 17L); IrisJigsawConnector connector = JigsawStudioMarkerParser.parse( - nbt, Orientation.NORTH_UP, 3, 5, 7); + nbt, "north_up", 3, 5, 7); - assertEquals(3, connector.getPosition().getX()); - assertEquals(5, connector.getPosition().getY()); - assertEquals(7, connector.getPosition().getZ()); - assertEquals(IrisDirection.NORTH_NEGATIVE_Z, connector.getDirection()); - assertEquals(IrisDirection.UP_POSITIVE_Y, connector.getTop()); + assertEquals(3, connector.getPosition().x()); + assertEquals(5, connector.getPosition().y()); + assertEquals(7, connector.getPosition().z()); + assertEquals(JigsawDirection.NORTH_NEGATIVE_Z, connector.getDirection()); + assertEquals(JigsawDirection.UP_POSITIVE_Y, connector.getTop()); assertEquals("fort/pool", connector.getPool()); assertEquals("iris:door", connector.getName()); assertEquals("iris:door", connector.getTargetName()); @@ -57,7 +61,7 @@ public class JigsawStudioMarkerParserTest { @Test public void defaultsMissingOptionalMetadata() { IrisJigsawConnector connector = JigsawStudioMarkerParser.parse( - markerNbt(), Orientation.SOUTH_UP, 0, 0, 0); + markerNbt(), "south_up", 0, 0, 0); assertEquals("", connector.getChannel()); assertEquals(0, connector.getSelectionPriority()); @@ -70,7 +74,7 @@ public class JigsawStudioMarkerParserTest { nbt.remove("pool"); assertThrows(IllegalArgumentException.class, - () -> JigsawStudioMarkerParser.parse(nbt, Orientation.NORTH_UP, 0, 0, 0)); + () -> JigsawStudioMarkerParser.parse(nbt, "north_up", 0, 0, 0)); } @Test @@ -79,7 +83,7 @@ public class JigsawStudioMarkerParserTest { nbt.put("pool", "minecraft:fort/pool"); assertThrows(IllegalArgumentException.class, - () -> JigsawStudioMarkerParser.parse(nbt, Orientation.NORTH_UP, 0, 0, 0)); + () -> JigsawStudioMarkerParser.parse(nbt, "north_up", 0, 0, 0)); } private static Map markerNbt() { @@ -93,9 +97,9 @@ public class JigsawStudioMarkerParserTest { } private static void assertDirections( - Orientation orientation, - IrisDirection expectedFront, - IrisDirection expectedTop + String orientation, + JigsawDirection expectedFront, + JigsawDirection expectedTop ) { JigsawStudioMarkerParser.Directions directions = JigsawStudioMarkerParser.directions(orientation); assertEquals(expectedFront, directions.front()); diff --git a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioMenuControllerTest.java b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioMenuControllerTest.java index 860be98ab..b005b0eb1 100644 --- a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioMenuControllerTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioMenuControllerTest.java @@ -6,17 +6,12 @@ import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioPieceRules; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolAction; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolPayload; -import art.arcane.iris.spi.IrisServices; -import art.arcane.iris.util.common.scheduling.J; -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.bukkit.event.player.PlayerChangedWorldEvent; -import org.bukkit.plugin.java.JavaPlugin; +import com.volmit.ModuleLog; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolText; +import org.junit.After; import org.junit.Test; -import org.mockito.MockedStatic; import java.lang.reflect.Field; import java.lang.reflect.Method; @@ -30,17 +25,15 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; public class JigsawStudioMenuControllerTest { + private final JigsawStudioScheduler scheduler = new JigsawStudioScheduler(mock(ModuleLog.class)); + private final FakeToolWorld studioWorld = new FakeToolWorld("jigsaw"); private static final UUID WORLD_ID = UUID.fromString("22222222-2222-2222-2222-222222222222"); private static final UUID REQUEST_ID = UUID.fromString("77777777-7777-7777-7777-777777777777"); private static final JigsawStudioPieceRules RULES = new JigsawStudioPieceRules(1, 12, 2, 8, false); @@ -81,7 +74,7 @@ public class JigsawStudioMenuControllerTest { false, List.of(active)); - assertEquals(ChatColor.GREEN + "Autosaved", JigsawStudioMenuController.workcellStatus(fresh)); + assertEquals(ToolText.colored(TextColor.GREEN, "Autosaved"), JigsawStudioMenuController.workcellStatus(fresh)); } @Test @@ -92,10 +85,10 @@ public class JigsawStudioMenuControllerTest { List.of(), List.of()); - assertEquals(Material.JIGSAW, JigsawStudioMenuController.variantMaterial(active)); - assertEquals(Material.EMERALD, + assertEquals(JigsawStudioMenuIcon.JIGSAW, JigsawStudioMenuController.variantMaterial(active)); + assertEquals(JigsawStudioMenuIcon.EMERALD, JigsawStudioMenuController.evaluationMaterial(JigsawStudioEvaluationState.VALID)); - assertEquals(Material.TARGET, + assertEquals(JigsawStudioMenuIcon.TARGET, JigsawStudioMenuController.RuleField.MINIMUM_PLACEMENTS.material()); } @@ -245,29 +238,26 @@ public class JigsawStudioMenuControllerTest { @Test public void stagesMultipleCellSizeEditsAndAppliesOneRelayoutWithoutClosing() throws Exception { UUID playerId = UUID.fromString("55555555-5555-5555-5555-555555555555"); - Player player = mock(Player.class); + FakeToolPlayer player = new FakeToolPlayer(playerId, "editor", studioWorld); JigsawStudioMenuController.Actions actions = mock(JigsawStudioMenuController.Actions.class); JigsawStudioMenuState.Variant active = variant("pieces/corner", true, List.of(), List.of()); JigsawStudioMenuState.Workcell workcell = workcell(active); JigsawStudioMenuState state = state(JigsawStudioMenuState.Evaluation.pending(), workcell); - JigsawStudioMenuController controller = new JigsawStudioMenuController( - mock(JavaPlugin.class), - actions); + JigsawStudioMenuController controller = new JigsawStudioMenuController(actions, scheduler); Method resize = JigsawStudioMenuController.class.getDeclaredMethod( "resizeWorkcell", - Player.class, + ToolPlayer.class, UUID.class, String.class, JigsawStudioMenuController.DimensionAxis.class, int.class); Method apply = JigsawStudioMenuController.class.getDeclaredMethod( "applyWorkcellResize", - Player.class, + ToolPlayer.class, UUID.class, String.class); resize.setAccessible(true); apply.setAccessible(true); - when(player.getUniqueId()).thenReturn(playerId); when(actions.menuState(player)).thenReturn(Optional.of(state)); when(actions.updateWorkcellDimensions( player, @@ -293,19 +283,13 @@ public class JigsawStudioMenuControllerTest { player, workcell.stableId(), new JigsawStudioCellDimensions(25, 20, 18)); - try (MockedStatic scheduling = mockStatic(J.class)) { - scheduling.when(() -> J.runEntity( - same(player), - any(Runnable.class), - eq(2))).thenReturn(true); - apply.invoke(controller, player, REQUEST_ID, workcell.stableId()); + apply.invoke(controller, player, REQUEST_ID, workcell.stableId()); - verify(actions).updateWorkcellDimensions( - player, - workcell.stableId(), - new JigsawStudioCellDimensions(25, 20, 18)); - } + verify(actions).updateWorkcellDimensions( + player, + workcell.stableId(), + new JigsawStudioCellDimensions(25, 20, 18)); } @Test @@ -530,59 +514,32 @@ public class JigsawStudioMenuControllerTest { @Test public void openMarshalsToThePlayerRegionBeforeReadingStudioState() { - Player player = mock(Player.class); + FakeToolPlayer player = new FakeToolPlayer(UUID.randomUUID(), "editor", studioWorld); + player.ownedElsewhere = true; JigsawStudioMenuController.Actions actions = mock(JigsawStudioMenuController.Actions.class); - JigsawStudioMenuController controller = new JigsawStudioMenuController( - mock(JavaPlugin.class), - actions); + JigsawStudioMenuController controller = new JigsawStudioMenuController(actions, scheduler); - try (MockedStatic scheduling = mockStatic(J.class)) { - scheduling.when(() -> J.isOwnedByCurrentRegion(player)).thenReturn(false); - scheduling.when(() -> J.runEntity(same(player), any(Runnable.class))).thenReturn(true); + assertTrue(controller.open(player)); + verifyNoInteractions(actions); - assertTrue(controller.open(player)); - verifyNoInteractions(actions); - } + player.runWaiting(); + verify(actions).menuState(player); } @Test - public void changedWorldClosesTheActiveMenuLease() throws ReflectiveOperationException { + public void leavingTheStudioClosesTheMenuAndHidesTheSidebar() throws ReflectiveOperationException { UUID playerId = UUID.fromString("33333333-3333-3333-3333-333333333333"); - UUID worldId = UUID.fromString("44444444-4444-4444-4444-444444444444"); - Player player = mock(Player.class); - World world = mock(World.class); - Location location = mock(Location.class); - PlayerChangedWorldEvent event = mock(PlayerChangedWorldEvent.class); + FakeToolPlayer player = new FakeToolPlayer(playerId, "editor", studioWorld); JigsawStudioMenuController menu = mock(JigsawStudioMenuController.class); - BoardSVC board = mock(BoardSVC.class); - JigsawStudioService service = new JigsawStudioService(); - BoardSVC previousBoard = IrisServices.getOrNull(BoardSVC.class); - - when(event.getPlayer()).thenReturn(player); - when(player.getUniqueId()).thenReturn(playerId); - when(player.getWorld()).thenReturn(world); - when(player.getLocation()).thenReturn(location); - when(world.getUID()).thenReturn(worldId); - when(location.getWorld()).thenReturn(world); - + JigsawStudioService service = new JigsawStudioService(mock(ModuleLog.class)); Field menuField = JigsawStudioService.class.getDeclaredField("menuController"); menuField.setAccessible(true); menuField.set(service, menu); - IrisServices.register(BoardSVC.class, board); - try (MockedStatic scheduling = mockStatic(J.class)) { - scheduling.when(() -> J.isOwnedByCurrentRegion(player)).thenReturn(true); - service.onPlayerChangedWorld(event); + service.playerLeft(player); - verify(menu).close(player); - verify(board).clearJigsawContext(player); - } finally { - if (previousBoard == null) { - IrisServices.remove(BoardSVC.class); - } else { - IrisServices.register(BoardSVC.class, previousBoard); - } - } + verify(menu).close(player); + assertEquals(1, player.sidebarsHidden); } private JigsawStudioMenuState state( diff --git a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioMenuWindowTest.java b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioMenuWindowTest.java new file mode 100644 index 000000000..1938cb718 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioMenuWindowTest.java @@ -0,0 +1,180 @@ +package art.arcane.iris.core.service; + +import com.volmit.resource.ResourceId; +import com.volmit.tooling.world.MenuButton; +import com.volmit.tooling.world.MenuClick; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolMenu; +import com.volmit.tooling.world.ToolText; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class JigsawStudioMenuWindowTest { + private final FakeToolPlayer viewer = new FakeToolPlayer(UUID.randomUUID(), "editor", new FakeToolWorld("jigsaw")); + + @Test + public void elementsSitAtColumnsCountedFromTheMiddleOfTheirRow() { + JigsawStudioMenuWindow window = new JigsawStudioMenuWindow(viewer).setTitle("Jigsaw: village"); + window.setElement(0, 0, element("middle")); + window.setElement(-4, 0, element("left-edge")); + window.setElement(4, 1, element("right-edge-below")); + window.setElement(-9, 2, element("clamped-left")); + window.setElement(9, 3, element("clamped-right")); + + window.open(); + + ToolMenu menu = viewer.menus.getLast(); + assertEquals(ToolText.plain("Jigsaw: village"), menu.title()); + assertEquals(List.of(0, 4, 17, 18, 35), slotsOf(menu)); + } + + @Test + public void buttonCarriesTheIconNameLoreAndGlow() { + JigsawStudioMenuWindow window = new JigsawStudioMenuWindow(viewer); + window.setElement(0, 0, new JigsawStudioMenuElement("details") + .setIcon(JigsawStudioMenuIcon.EMERALD) + .setName(ToolText.colored(TextColor.GREEN, "Ready to Assemble")) + .addLore(ToolText.colored(TextColor.GRAY, "Seed 1337 assembled 19 pieces")) + .setEnchanted(true)); + + window.open(); + + MenuButton button = viewer.menus.getLast().buttons().getFirst(); + assertEquals(ResourceId.parse("minecraft:emerald"), button.icon().item()); + assertEquals(ToolText.colored(TextColor.GREEN, "Ready to Assemble"), button.icon().name()); + assertEquals(List.of(ToolText.colored(TextColor.GRAY, "Seed 1337 assembled 19 pieces")), button.icon().lore()); + assertTrue(button.icon().glowing()); + } + + @Test + public void viewportHidesElementsBelowItsLastRow() { + JigsawStudioMenuWindow window = new JigsawStudioMenuWindow(viewer).setViewportHeight(2); + window.setElement(0, 0, element("visible")); + window.setElement(0, 1, element("last-row")); + window.setElement(0, 2, element("hidden")); + + window.open(); + + ToolMenu menu = viewer.menus.getLast(); + assertEquals(2, menu.rows()); + assertEquals(List.of(4, 13), slotsOf(menu)); + } + + @Test + public void eachKindOfClickRunsItsOwnAction() { + List clicks = new ArrayList<>(); + JigsawStudioMenuElement element = new JigsawStudioMenuElement("variant") + .onLeftClick(clicked -> clicks.add("left")) + .onRightClick(clicked -> clicks.add("right")) + .onShiftLeftClick(clicked -> clicks.add("shift-left")) + .onShiftRightClick(clicked -> clicks.add("shift-right")) + .onMiddleClick(clicked -> clicks.add("middle")); + JigsawStudioMenuWindow window = new JigsawStudioMenuWindow(viewer); + window.setElement(0, 0, element); + window.open(); + MenuButton button = viewer.menus.getLast().buttons().getFirst(); + + button.action().accept(new MenuClick(viewer, false, false, false)); + button.action().accept(new MenuClick(viewer, true, false, false)); + button.action().accept(new MenuClick(viewer, false, true, false)); + button.action().accept(new MenuClick(viewer, true, true, false)); + button.action().accept(new MenuClick(viewer, false, false, true)); + + assertEquals(List.of("left", "right", "shift-left", "shift-right", "middle"), clicks); + } + + @Test + public void aClickWithoutAnActionDoesNothing() { + JigsawStudioMenuWindow window = new JigsawStudioMenuWindow(viewer); + window.setElement(0, 0, new JigsawStudioMenuElement("plain").onLeftClick(clicked -> { })); + window.open(); + + viewer.menus.getLast().buttons().getFirst().action().accept(new MenuClick(viewer, true, false, false)); + + assertEquals(1, viewer.menus.size()); + } + + @Test + public void everyChangeIsShownOnceAndABatchIsShownOnce() { + JigsawStudioMenuWindow window = new JigsawStudioMenuWindow(viewer); + window.open(); + assertEquals(1, viewer.menus.size()); + + window.setElement(0, 0, element("one")); + window.setElement(1, 0, element("two")); + assertEquals(3, viewer.menus.size()); + + window.batch(() -> { + window.clearElements(); + window.setElement(0, 0, element("three")); + window.setElement(1, 0, element("four")); + }); + assertEquals(4, viewer.menus.size()); + assertEquals(2, viewer.menus.getLast().buttons().size()); + } + + @Test + public void aWindowThatIsNotOpenShowsNothing() { + JigsawStudioMenuWindow window = new JigsawStudioMenuWindow(viewer); + + window.setElement(0, 0, element("quiet")); + window.batch(() -> window.setElement(1, 0, element("quieter"))); + + assertTrue(viewer.menus.isEmpty()); + } + + @Test + public void closingFromTheWindowClosesTheViewerMenuOnceAndRunsTheCloseHandler() { + AtomicInteger closed = new AtomicInteger(); + JigsawStudioMenuWindow window = new JigsawStudioMenuWindow(viewer).onClosed(closed::incrementAndGet); + window.open(); + + window.close(); + window.close(); + + assertEquals(1, viewer.menusClosed); + assertEquals(1, closed.get()); + } + + @Test + public void theHostClosingTheMenuRunsTheCloseHandler() { + AtomicInteger closed = new AtomicInteger(); + JigsawStudioMenuWindow window = new JigsawStudioMenuWindow(viewer).onClosed(closed::incrementAndGet); + window.open(); + + viewer.menus.getLast().onClose().run(); + + assertEquals(1, closed.get()); + assertEquals(0, viewer.menusClosed); + } + + @Test + public void aMenuTheWindowReplacedDoesNotCloseTheWindowWhenTheHostClosesIt() { + AtomicInteger closed = new AtomicInteger(); + JigsawStudioMenuWindow window = new JigsawStudioMenuWindow(viewer).onClosed(closed::incrementAndGet); + window.open(); + ToolMenu replaced = viewer.menus.getLast(); + + window.setElement(0, 0, element("newer")); + replaced.onClose().run(); + + assertEquals(0, closed.get()); + assertFalse(viewer.menus.getLast() == replaced); + } + + private static JigsawStudioMenuElement element(String id) { + return new JigsawStudioMenuElement(id).setName(ToolText.plain(id)); + } + + private static List slotsOf(ToolMenu menu) { + return menu.buttons().stream().map(MenuButton::slot).toList(); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioPreviewRendererTest.java b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioPreviewRendererTest.java index 6b9d49f23..09e8746f7 100644 --- a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioPreviewRendererTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioPreviewRendererTest.java @@ -5,13 +5,20 @@ import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; import art.arcane.iris.engine.framework.PlacedStructurePiece; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.ObjectTurn; +import art.arcane.iris.engine.framework.structure.ObjectFrame; +import art.arcane.iris.engine.framework.structure.assembly.PieceTurn; import art.arcane.iris.spi.PlatformBlockState; -import org.bukkit.World; +import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.object.PackObjects; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.world.ToolWorld; import org.junit.Test; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.UUID; @@ -25,15 +32,17 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; public class JigsawStudioPreviewRendererTest { + private final BlockRegistry registry = mock(BlockRegistry.class); + @Test public void planUsesPlacedPieceCenterAndExactBlockState() throws Exception { PlatformBlockState stone = mock(PlatformBlockState.class); when(stone.key()).thenReturn("minecraft:stone"); IrisObject object = new IrisObject(3, 3, 3); object.setUnsigned(2, 1, 0, stone); - PlacedStructurePiece piece = piece(object, 100, 70, -40, ObjectTurn.of(0, 0, 0)); + PlacedStructurePiece piece = piece(object, 100, 70, -40, PieceTurn.NONE); - JigsawStudioPreviewRenderer.PreviewPlan plan = JigsawStudioPreviewRenderer.plan(List.of(piece)); + JigsawStudioPreviewRenderer.PreviewPlan plan = JigsawStudioPreviewRenderer.plan(List.of(piece), packOf(object)); assertEquals(1, plan.blocks().size()); assertEquals( @@ -56,7 +65,7 @@ public class JigsawStudioPreviewRendererTest { object.setUnsigned(0, 0, 0, structureVoid); JigsawStudioPreviewRenderer.PreviewPlan plan = JigsawStudioPreviewRenderer.plan(List.of( - piece(object, 0, 65, 0, ObjectTurn.of(0, 0, 0)))); + piece(object, 0, 65, 0, PieceTurn.NONE)), packOf(object)); assertTrue(plan.blocks().isEmpty()); assertFalse(plan.bounds().isEmpty()); @@ -64,7 +73,7 @@ public class JigsawStudioPreviewRendererTest { @Test public void emptyAssemblyProducesAnEmptyPlan() throws Exception { - JigsawStudioPreviewRenderer.PreviewPlan plan = JigsawStudioPreviewRenderer.plan(List.of()); + JigsawStudioPreviewRenderer.PreviewPlan plan = JigsawStudioPreviewRenderer.plan(List.of(), packOf(new IrisObject(1, 1, 1))); assertTrue(plan.blocks().isEmpty()); assertTrue(plan.bounds().isEmpty()); @@ -77,7 +86,7 @@ public class JigsawStudioPreviewRendererTest { 10, 10, 10, - ObjectTurn.of(0, 0, 0)); + PieceTurn.NONE); PlacedStructurePiece planar = JigsawStudioService.alignPreviewPieces( List.of(source), @@ -111,11 +120,9 @@ public class JigsawStudioPreviewRendererTest { @Test public void forgettingARequestDropsTrackingWithoutWorldCleanup() { - World world = mock(World.class); - UUID worldId = UUID.fromString("11111111-1111-1111-1111-111111111111"); + ToolWorld world = mock(ToolWorld.class); UUID requestId = UUID.fromString("22222222-2222-2222-2222-222222222222"); - when(world.getUID()).thenReturn(worldId); - JigsawStudioPreviewRenderer renderer = new JigsawStudioPreviewRenderer(); + JigsawStudioPreviewRenderer renderer = new JigsawStudioPreviewRenderer(mock(ModuleLog.class)); renderer.render( world, requestId, @@ -132,19 +139,31 @@ public class JigsawStudioPreviewRendererTest { verifyNoInteractions(world); } + /** A pack whose only object, {@code preview}, is {@code object}, and whose blocks are {@link #registry}. */ + private PackResources packOf(IrisObject object) { + PackResources pack = mock(PackResources.class); + PackObjects objects = mock(PackObjects.class); + when(pack.idOf("preview")).thenReturn(ResourceId.parse("test:preview")); + when(pack.objects()).thenReturn(objects); + when(objects.object(ResourceId.parse("test:preview"))).thenReturn(Optional.of(object)); + when(pack.blocks()).thenReturn(registry); + return pack; + } + private static PlacedStructurePiece piece( IrisObject object, int x, int y, int z, - ObjectTurn rotation + PieceTurn rotation ) { int minimumX = x - object.getW() / 2; int minimumY = y - object.getH() / 2; int minimumZ = z - object.getD() / 2; return new PlacedStructurePiece( new IrisJigsawPiece().setObject("preview"), - object, + "preview", + new ObjectFrame(object.getW(), object.getH(), object.getD()), x, y, z, diff --git a/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioActivationTest.java b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioRegistryTest.java similarity index 55% rename from core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioActivationTest.java rename to core/src/test/java/art/arcane/iris/core/service/JigsawStudioRegistryTest.java index b8e2076ac..5bd207520 100644 --- a/core/src/test/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioActivationTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioRegistryTest.java @@ -1,6 +1,14 @@ -package art.arcane.iris.core.runtime.jigsaw; +package art.arcane.iris.core.service; -import art.arcane.iris.core.loader.IrisData; +import com.volmit.tooling.ToolPack; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioPieceRules; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioSession; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariant; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariantCatalog; import org.junit.After; import org.junit.Test; @@ -16,21 +24,23 @@ import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; -public class JigsawStudioActivationTest { +public class JigsawStudioRegistryTest { private static final UUID OWNER = UUID.fromString("11111111-1111-1111-1111-111111111111"); + private final JigsawStudioRegistry registry = new JigsawStudioRegistry(); + @After public void clearActivation() { - JigsawStudioActivation.finishOpen(OWNER); - JigsawStudioActivation.deactivate("overworld"); - JigsawStudioActivation.deactivate("nether"); + registry.finishOpen(OWNER); + registry.deactivate("overworld"); + registry.deactivate("nether"); } @Test public void storesRequestAndSessionByNormalizedPackKey() { - IrisData source = mock(IrisData.class); + ToolPack source = StudioToolPacks.toolPack(); JigsawStudioCellDimensions dimensions = new JigsawStudioCellDimensions(11, 7, 11); - JigsawStudioActivation.Request request = JigsawStudioActivation.activate( + JigsawStudioRequest request = registry.activate( "OverWorld", "village/plains", JigsawStudioMode.PLANAR_JIGSAW, @@ -39,20 +49,20 @@ public class JigsawStudioActivationTest { source ); - assertTrue(JigsawStudioActivation.isActive("overworld")); - assertSame(request, JigsawStudioActivation.getRequest("OVERWORLD")); + assertTrue(registry.isActive("overworld")); + assertSame(request, registry.getRequest("OVERWORLD")); assertSame(source, request.source()); assertEquals(JigsawStudioMode.PLANAR_JIGSAW, request.mode()); assertEquals(JigsawStudioCompatibilityTarget.VANILLA_PORTABLE, request.compatibilityTarget()); assertEquals(dimensions, request.cellDimensions()); - assertNotNull(JigsawStudioActivation.getSession("overworld")); - assertEquals(6, JigsawStudioActivation.getLayout("overworld").bays().size()); + assertNotNull(registry.getSession("overworld")); + assertEquals(6, registry.getLayout("overworld").bays().size()); } @Test public void replacementGetsANewRequestScopedSession() { - IrisData source = mock(IrisData.class); - JigsawStudioActivation.Request first = JigsawStudioActivation.activate( + ToolPack source = StudioToolPacks.toolPack(); + JigsawStudioRequest first = registry.activate( "overworld", "village", JigsawStudioMode.PLANAR_JIGSAW, @@ -60,7 +70,7 @@ public class JigsawStudioActivationTest { new JigsawStudioCellDimensions(7, 5, 7), source ); - JigsawStudioActivation.Request second = JigsawStudioActivation.activate( + JigsawStudioRequest second = registry.activate( "overworld", "stronghold", JigsawStudioMode.SPATIAL_JIGSAW, @@ -70,18 +80,18 @@ public class JigsawStudioActivationTest { ); assertNotEquals(first.requestId(), second.requestId()); - assertEquals(second.requestId(), JigsawStudioActivation.getSession("overworld").sessionId()); - assertEquals(JigsawStudioMode.SPATIAL_JIGSAW, JigsawStudioActivation.getLayout("overworld").mode()); - assertEquals(1, JigsawStudioActivation.getLayout("overworld").bays().size()); + assertEquals(second.requestId(), registry.getSession("overworld").sessionId()); + assertEquals(JigsawStudioMode.SPATIAL_JIGSAW, registry.getLayout("overworld").mode()); + assertEquals(1, registry.getLayout("overworld").bays().size()); - JigsawStudioActivation.deactivate("overworld"); - assertFalse(JigsawStudioActivation.isActive("overworld")); + registry.deactivate("overworld"); + assertFalse(registry.isActive("overworld")); } @Test public void staleRequestCannotDeactivateItsReplacement() { - IrisData source = mock(IrisData.class); - JigsawStudioActivation.Request first = JigsawStudioActivation.activate( + ToolPack source = StudioToolPacks.toolPack(); + JigsawStudioRequest first = registry.activate( "overworld", "village", JigsawStudioMode.SPATIAL_JIGSAW, @@ -89,7 +99,7 @@ public class JigsawStudioActivationTest { new JigsawStudioCellDimensions(16, 16, 16), source ); - JigsawStudioActivation.Request second = JigsawStudioActivation.activate( + JigsawStudioRequest second = registry.activate( "overworld", "stronghold", JigsawStudioMode.SPATIAL_JIGSAW, @@ -98,15 +108,15 @@ public class JigsawStudioActivationTest { source ); - assertFalse(JigsawStudioActivation.deactivate("overworld", first.requestId())); - assertSame(second, JigsawStudioActivation.getRequest("overworld")); - assertTrue(JigsawStudioActivation.deactivate("overworld", second.requestId())); - assertFalse(JigsawStudioActivation.isActive("overworld")); + assertFalse(registry.deactivate("overworld", first.requestId())); + assertSame(second, registry.getRequest("overworld")); + assertTrue(registry.deactivate("overworld", second.requestId())); + assertFalse(registry.isActive("overworld")); } @Test public void acceptsExistingGraphLayoutAsCleanInitialState() { - IrisData source = mock(IrisData.class); + ToolPack source = StudioToolPacks.toolPack(); JigsawStudioCellDimensions dimensions = new JigsawStudioCellDimensions(9, 6, 9); JigsawStudioVariant variant = new JigsawStudioVariant( "stronghold/hall", @@ -126,7 +136,7 @@ public class JigsawStudioActivationTest { new JigsawStudioVariantCatalog(List.of(variant)) ); - JigsawStudioActivation.activate( + registry.activate( "overworld", "stronghold", JigsawStudioMode.SPATIAL_JIGSAW, @@ -136,22 +146,22 @@ public class JigsawStudioActivationTest { initialLayout ); - assertSame(initialLayout, JigsawStudioActivation.getLayout("overworld")); - assertSame(variant, JigsawStudioActivation.getSession("overworld") + assertSame(initialLayout, registry.getLayout("overworld")); + assertSame(variant, registry.getSession("overworld") .activeVariant(JigsawStudioLayout.SPATIAL_WORKCELL_ID).orElseThrow()); - assertFalse(JigsawStudioActivation.getSession("overworld").isDirty()); + assertFalse(registry.getSession("overworld").isDirty()); } @Test public void stagedSamePackReplacementKeepsPriorActivationUntilCommit() { - IrisData source = mock(IrisData.class); + ToolPack source = StudioToolPacks.toolPack(); JigsawStudioCellDimensions dimensions = new JigsawStudioCellDimensions(16, 16, 16); JigsawStudioLayout oldLayout = JigsawStudioLayout.create( JigsawStudioMode.SPATIAL_JIGSAW, dimensions, JigsawStudioVariantCatalog.empty()); - assertTrue(JigsawStudioActivation.tryBeginOpen(OWNER)); - JigsawStudioActivation.Request previous = JigsawStudioActivation.activate( + assertTrue(registry.tryBeginOpen(OWNER)); + JigsawStudioRequest previous = registry.activate( "overworld", "stronghold/old", JigsawStudioMode.SPATIAL_JIGSAW, @@ -160,11 +170,11 @@ public class JigsawStudioActivationTest { source, oldLayout, OWNER); - JigsawStudioSession previousSession = JigsawStudioActivation.getSession("overworld"); - JigsawStudioActivation.finishOpen(OWNER); + JigsawStudioSession previousSession = registry.getSession("overworld"); + registry.finishOpen(OWNER); - assertTrue(JigsawStudioActivation.tryBeginOpen(OWNER)); - JigsawStudioActivation.StagedActivation staged = JigsawStudioActivation.stage( + assertTrue(registry.tryBeginOpen(OWNER)); + JigsawStudioRegistry.StagedActivation staged = registry.stage( "overworld", "stronghold/new", JigsawStudioMode.SPATIAL_JIGSAW, @@ -175,31 +185,28 @@ public class JigsawStudioActivationTest { OWNER, previous.requestId()); - assertSame(previous, JigsawStudioActivation.getRequest("overworld")); - assertSame(previousSession, JigsawStudioActivation.getSession("overworld")); - assertSame(previous, JigsawStudioActivation.getGeneratorRequest("overworld")); - assertTrue(JigsawStudioActivation.beginStagedGeneration(staged)); - assertSame(staged.request(), JigsawStudioActivation.getGeneratorRequest("overworld")); - assertSame(staged.session(), JigsawStudioActivation.getGeneratorSession("overworld")); - assertSame(previous, JigsawStudioActivation.getRequest("overworld")); - assertFalse(JigsawStudioActivation.deactivate("overworld", previous.requestId())); - assertSame(previous, JigsawStudioActivation.getRequest("overworld")); + assertSame(previous, registry.getRequest("overworld")); + assertSame(previousSession, registry.getSession("overworld")); + assertTrue(registry.beginStagedGeneration(staged)); + assertSame(previous, registry.getRequest("overworld")); + assertFalse(registry.deactivate("overworld", previous.requestId())); + assertSame(previous, registry.getRequest("overworld")); - assertTrue(JigsawStudioActivation.commit(staged)); - assertSame(staged.request(), JigsawStudioActivation.getRequest("overworld")); - assertSame(staged.session(), JigsawStudioActivation.getSession("overworld")); + assertTrue(registry.commit(staged)); + assertSame(staged.request(), registry.getRequest("overworld")); + assertSame(staged.session(), registry.getSession("overworld")); } @Test public void failedSamePackReplacementRollsBackWithoutReplacingPriorSession() { - IrisData source = mock(IrisData.class); + ToolPack source = StudioToolPacks.toolPack(); JigsawStudioCellDimensions dimensions = new JigsawStudioCellDimensions(16, 16, 16); JigsawStudioLayout layout = JigsawStudioLayout.create( JigsawStudioMode.SPATIAL_JIGSAW, dimensions, JigsawStudioVariantCatalog.empty()); - assertTrue(JigsawStudioActivation.tryBeginOpen(OWNER)); - JigsawStudioActivation.Request previous = JigsawStudioActivation.activate( + assertTrue(registry.tryBeginOpen(OWNER)); + JigsawStudioRequest previous = registry.activate( "overworld", "stronghold/old", JigsawStudioMode.SPATIAL_JIGSAW, @@ -208,11 +215,11 @@ public class JigsawStudioActivationTest { source, layout, OWNER); - JigsawStudioSession previousSession = JigsawStudioActivation.getSession("overworld"); - JigsawStudioActivation.finishOpen(OWNER); + JigsawStudioSession previousSession = registry.getSession("overworld"); + registry.finishOpen(OWNER); - assertTrue(JigsawStudioActivation.tryBeginOpen(OWNER)); - JigsawStudioActivation.StagedActivation staged = JigsawStudioActivation.stage( + assertTrue(registry.tryBeginOpen(OWNER)); + JigsawStudioRegistry.StagedActivation staged = registry.stage( "overworld", "stronghold/new", JigsawStudioMode.SPATIAL_JIGSAW, @@ -222,12 +229,11 @@ public class JigsawStudioActivationTest { layout, OWNER, previous.requestId()); - assertTrue(JigsawStudioActivation.beginStagedGeneration(staged)); - assertFalse(JigsawStudioActivation.deactivate("overworld", previous.requestId())); + assertTrue(registry.beginStagedGeneration(staged)); + assertFalse(registry.deactivate("overworld", previous.requestId())); - assertTrue(JigsawStudioActivation.rollback(staged)); - assertSame(previous, JigsawStudioActivation.getRequest("overworld")); - assertSame(previousSession, JigsawStudioActivation.getSession("overworld")); - assertSame(previous, JigsawStudioActivation.getGeneratorRequest("overworld")); + assertTrue(registry.rollback(staged)); + assertSame(previous, registry.getRequest("overworld")); + assertSame(previousSession, registry.getSession("overworld")); } } diff --git a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioResourceBundleAssemblerTest.java b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioResourceBundleAssemblerTest.java index f5a870226..d03043a78 100644 --- a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioResourceBundleAssemblerTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioResourceBundleAssemblerTest.java @@ -11,11 +11,11 @@ import art.arcane.iris.core.structure.authoring.StructureTransactionWriter; import art.arcane.iris.core.structure.authoring.StructureWriteMode; import art.arcane.iris.core.structure.authoring.StructureWriteOptions; import art.arcane.iris.core.structure.authoring.StructureWriteResult; -import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.value.IrisPosition; +import com.volmit.geometry.BlockPosition; import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -90,7 +90,7 @@ public class JigsawStudioResourceBundleAssemblerTest { JigsawStudioMode.PLANAR_JIGSAW, JigsawStudioCompatibilityTarget.IRIS_EXTENDED, new JigsawStudioCellDimensions(16, 16, 16)); - assertTrue(JigsawStudioProjectCreator.create(packRoot, options).successful()); + assertTrue(JigsawStudioProjectCreator.create(packRoot, new art.arcane.iris.core.tooling.IrisObjectCodec(), options).successful()); String pieceKey = structureKey + "/end"; IrisJigsawPiece piece = new Gson().fromJson( Files.readString( @@ -238,7 +238,7 @@ public class JigsawStudioResourceBundleAssemblerTest { JigsawStudioMode.SPATIAL_JIGSAW, JigsawStudioCompatibilityTarget.IRIS_EXTENDED, new JigsawStudioCellDimensions(4, 4, 4)); - StructureWriteResult result = JigsawStudioProjectCreator.create(packRoot, options); + StructureWriteResult result = JigsawStudioProjectCreator.create(packRoot, new art.arcane.iris.core.tooling.IrisObjectCodec(), options); assertTrue(result.successful()); return packRoot; } @@ -275,9 +275,9 @@ public class JigsawStudioResourceBundleAssemblerTest { private static IrisJigsawConnector connector() { return new IrisJigsawConnector() - .setPosition(new IrisPosition(0, 0, 0)) - .setDirection(IrisDirection.NORTH_NEGATIVE_Z) - .setTop(IrisDirection.UP_POSITIVE_Y) + .setPosition(new BlockPosition(0, 0, 0)) + .setDirection(JigsawDirection.NORTH_NEGATIVE_Z) + .setTop(JigsawDirection.UP_POSITIVE_Y) .setPool("fort/start") .setName("iris:door") .setTargetName("iris:door") diff --git a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioServiceCaptureTest.java b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioServiceCaptureTest.java index 70561f5c4..c8156f6fc 100644 --- a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioServiceCaptureTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioServiceCaptureTest.java @@ -1,13 +1,10 @@ package art.arcane.iris.core.service; -import art.arcane.iris.engine.framework.structure.StructureResources; -import art.arcane.iris.core.modules.ModuleResourceFixture; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.loader.ResourceLoader; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBounds; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioActivation; +import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarArchetype; +import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarTopology; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBay; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBayKind; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBounds; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout; @@ -17,161 +14,91 @@ import art.arcane.iris.core.runtime.jigsaw.JigsawStudioPoolMembership; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioSession; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariant; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariantCatalog; -import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarTopology; -import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarArchetype; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioWorkcellSpec; import art.arcane.iris.core.structure.authoring.StructureWriteResult; -import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.engine.framework.structure.assembly.PieceTurn; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.ObjectTurn; -import art.arcane.iris.engine.object.prefab.BlockStateRotation; -import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint; -import art.arcane.iris.engine.object.prefab.TileData; -import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; +import com.volmit.geometry.BlockPosition; import art.arcane.iris.engine.platform.studio.generators.JigsawStudioGenerator; -import art.arcane.iris.platform.bukkit.BukkitBlockState; -import art.arcane.iris.platform.bukkit.BukkitPlatform; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.spi.IrisPlatform; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.spi.PlatformRegistries; -import art.arcane.iris.util.common.data.B; -import art.arcane.volmlib.util.math.IrisBlockVector; -import art.arcane.iris.util.common.plugin.VolmitPlugin; -import art.arcane.iris.util.common.scheduling.J; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KMap; -import org.bukkit.Chunk; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.Directional; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.block.BlockCookEvent; -import org.bukkit.event.block.BlockDispenseEvent; -import org.bukkit.event.block.BrewingStartEvent; -import org.bukkit.event.block.BlockPistonExtendEvent; -import org.bukkit.event.block.BlockPistonRetractEvent; -import org.bukkit.event.block.BlockRedstoneEvent; -import org.bukkit.event.block.CrafterCraftEvent; -import org.bukkit.event.inventory.BrewEvent; -import org.bukkit.event.inventory.BrewingStandFuelEvent; -import org.bukkit.event.inventory.FurnaceBurnEvent; -import org.bukkit.event.inventory.FurnaceStartSmeltEvent; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.inventory.InventoryDragEvent; -import org.bukkit.event.inventory.InventoryMoveItemEvent; -import org.bukkit.event.inventory.InventoryPickupItemEvent; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.world.ChunkLoadEvent; -import org.bukkit.event.world.WorldUnloadEvent; +import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import com.volmit.object.GeneratedObject; +import com.volmit.object.ObjectBlock; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.ObjectCodec; +import org.junit.After; import org.junit.Test; -import org.mockito.MockedStatic; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.same; -import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class JigsawStudioServiceCaptureTest { + private static final UUID OWNER = UUID.fromString("11111111-1111-1111-1111-111111111111"); + private static final long WAIT_SECONDS = 10L; + private static final ResourceId TILE_FORMAT = ResourceId.parse("iris:tile"); - @Test - public void shutdownQuiesceIsIdempotentAndResetsOnEnable() throws Exception { - JigsawStudioService service = new JigsawStudioService(); - VolmitPlugin plugin = mock(VolmitPlugin.class); - Field disableStartedField = JigsawStudioService.class.getDeclaredField("disableStarted"); - Field enabledField = JigsawStudioService.class.getDeclaredField("enabled"); - disableStartedField.setAccessible(true); - enabledField.setAccessible(true); - AtomicBoolean disableStarted = (AtomicBoolean) disableStartedField.get(service); + private final ModuleLog log = mock(ModuleLog.class); + private final JigsawStudioService service = new JigsawStudioService(log); + private final BlockRegistry registry = FakeBlockRegistry.create(); + private final ObjectCodec codec = new TextObjectCodec(); - try (MockedStatic platform = mockStatic(BukkitPlatform.class)) { - platform.when(BukkitPlatform::volmitPlugin).thenReturn(plugin); - - service.onEnable(); - assertFalse(disableStarted.get()); - assertTrue(enabledField.getBoolean(service)); - - service.quiesceForServerShutdown(); - service.quiesceForServerShutdown(); - assertTrue(disableStarted.get()); - assertFalse(enabledField.getBoolean(service)); - - service.onEnable(); - assertFalse(disableStarted.get()); - assertTrue(enabledField.getBoolean(service)); - service.onDisable(); - } + @After + public void stopService() { + service.registry().finishOpen(OWNER); + service.registry().deactivate("overworld"); } @Test public void successfulStudioSavePlaysOneOwnerLocalBell() { - Player player = mock(Player.class); - Location location = mock(Location.class); - when(player.getLocation()).thenReturn(location); + FakeToolPlayer player = new FakeToolPlayer(OWNER, "owner", new FakeToolWorld("jigsaw")); - try (MockedStatic scheduling = mockStatic(J.class)) { - scheduling.when(() -> J.runEntity(same(player), any(Runnable.class))).thenAnswer(invocation -> { - invocation.getArgument(1, Runnable.class).run(); - return true; - }); + JigsawStudioService.playSaveSound(player); - JigsawStudioService.playSaveSound(player); - - verify(player).playSound(location, "minecraft:block.note_block.bell", 0.65F, 1.65F); - } + assertEquals( + List.of(new FakeToolPlayer.Sound(ResourceId.parse("minecraft:block.note_block.bell"), 0.65F, 1.65F)), + player.sounds); } @Test public void hiddenConnectorResetRestoresOnlyItsSavedOrdinaryBlock() throws Exception { - World world = mock(World.class); - Block target = mock(Block.class); - BlockData blockData = mock(BlockData.class); - PlatformBlockState state = mock(PlatformBlockState.class); + FakeToolWorld world = new FakeToolWorld("jigsaw"); + BlockState stone = BlockState.parse("minecraft:stone"); JigsawStudioCellDimensions dimensions = new JigsawStudioCellDimensions(15, 15, 15); JigsawStudioBay workcell = new JigsawStudioBay( "spatial", @@ -179,32 +106,49 @@ public class JigsawStudioServiceCaptureTest { Optional.empty(), "", new JigsawStudioBounds(10, 20, 30, dimensions)); - IrisJigsawConnector connector = connectorAt(1, 2, 3) - .setFinalState("minecraft:stone"); JigsawStudioGenerator.RenderedConnector renderedConnector = new JigsawStudioGenerator.RenderedConnector( 1, 2, 3, - connector, + connectorAt(1, 2, 3).setFinalState("minecraft:stone"), "north_up"); JigsawStudioGenerator.RenderedBlock renderedBlock = - new JigsawStudioGenerator.RenderedBlock(1, 2, 3, state, null); - - when(world.getBlockAt(11, 22, 33)).thenReturn(target); - when(state.isCustom()).thenReturn(false); - when(state.nativeHandle()).thenReturn(blockData); + new JigsawStudioGenerator.RenderedBlock(1, 2, 3, stone, null); JigsawStudioService.restoreConnectorChunk( world, + registry, workcell, List.of(renderedConnector), Map.of(new JigsawStudioService.LocalPosition(1, 2, 3), renderedBlock), false); - verify(world).getBlockAt(11, 22, 33); - verify(target).setBlockData(blockData, false); + assertEquals(Map.of(new BlockPosition(11, 22, 33), stone), world.blocks); } + + @Test + public void visibleConnectorResetRestoresItsJigsawMarkerWithTheConnectorNbt() throws Exception { + FakeToolWorld world = new FakeToolWorld("jigsaw"); + JigsawStudioBay workcell = new JigsawStudioBay( + "spatial", + JigsawStudioBayKind.SPATIAL_WORKCELL, + Optional.empty(), + "", + new JigsawStudioBounds(10, 20, 30, new JigsawStudioCellDimensions(15, 15, 15))); + IrisJigsawConnector connector = connectorAt(1, 2, 3).setFinalState("minecraft:stone"); + JigsawStudioGenerator.RenderedConnector rendered = + new JigsawStudioGenerator.RenderedConnector(1, 2, 3, connector, "north_up"); + + JigsawStudioService.restoreConnectorChunk(world, registry, workcell, List.of(rendered), Map.of(), true); + + BlockPosition at = new BlockPosition(11, 22, 33); + assertEquals(BlockState.parse("minecraft:jigsaw[orientation=north_up]"), world.blocks.get(at)); + KMap nbt = JigsawStudioTileCodec.nbt(world.entities.get(at)).orElseThrow(); + assertEquals("minecraft:stone", nbt.get("final_state")); + assertEquals("iris:door", nbt.get("name")); + } + @Test public void liveRelayoutDetectsMovedBoundsAndIncludesCageChunks() { JigsawStudioCellDimensions originalDimensions = new JigsawStudioCellDimensions(16, 8, 16); @@ -291,7 +235,7 @@ public class JigsawStudioServiceCaptureTest { } @Test - public void nonOwnerMutatingCommandsAreBlockedAtHighestPriority() throws NoSuchMethodException { + public void nonOwnerMutatingCommandsAreBlocked() { UUID ownerId = UUID.fromString("11111111-1111-1111-1111-111111111111"); UUID otherId = UUID.fromString("22222222-2222-2222-2222-222222222222"); @@ -315,22 +259,6 @@ public class JigsawStudioServiceCaptureTest { true, "/iris jigsaw variant load test/end")); assertFalse(JigsawStudioService.blocksNonEditableWorkcellMutation( false, "/fill 0 0 0 1 1 1 stone")); - - Method method = JigsawStudioService.class.getMethod( - "onUnauthorizedPlayerCommand", - PlayerCommandPreprocessEvent.class); - EventHandler handler = method.getAnnotation(EventHandler.class); - assertNotNull(handler); - assertEquals(EventPriority.HIGHEST, handler.priority()); - assertTrue(handler.ignoreCancelled()); - } - - @Test - public void indirectMutationEventsRemainMonitorListeners() throws NoSuchMethodException { - assertMutationHandler("onPlayerInteract", PlayerInteractEvent.class); - assertMutationHandler("onBlockRedstone", BlockRedstoneEvent.class); - assertMutationHandler("onPistonExtend", BlockPistonExtendEvent.class); - assertMutationHandler("onPistonRetract", BlockPistonRetractEvent.class); } @Test @@ -356,31 +284,6 @@ public class JigsawStudioServiceCaptureTest { true, true, false, false, ownerId, ownerId)); } - @Test - public void containerAndMachineMutationEventsHaveProtectionAndAutosaveContracts() - throws NoSuchMethodException { - assertHandler("onProtectedInventoryClick", InventoryClickEvent.class, EventPriority.HIGHEST, true); - assertHandler("onProtectedInventoryDrag", InventoryDragEvent.class, EventPriority.HIGHEST, true); - assertHandler("onProtectedInventoryMove", InventoryMoveItemEvent.class, EventPriority.HIGHEST, true); - assertHandler("onProtectedInventoryPickup", InventoryPickupItemEvent.class, EventPriority.HIGHEST, true); - assertHandler("onProtectedBlockCook", BlockCookEvent.class, EventPriority.HIGHEST, true); - assertHandler("onProtectedFurnaceBurn", FurnaceBurnEvent.class, EventPriority.HIGHEST, true); - assertHandler("onProtectedBrew", BrewEvent.class, EventPriority.HIGHEST, true); - assertHandler("onProtectedBrewingStandFuel", BrewingStandFuelEvent.class, EventPriority.HIGHEST, true); - assertHandler("onProtectedBlockDispense", BlockDispenseEvent.class, EventPriority.HIGHEST, true); - assertHandler("onProtectedCrafterCraft", CrafterCraftEvent.class, EventPriority.HIGHEST, true); - - assertMutationHandler("onBlockCook", BlockCookEvent.class); - assertMutationHandler("onFurnaceBurn", FurnaceBurnEvent.class); - assertHandler("onFurnaceStartSmelt", FurnaceStartSmeltEvent.class, EventPriority.MONITOR, false); - assertMutationHandler("onBrew", BrewEvent.class); - assertHandler("onBrewingStart", BrewingStartEvent.class, EventPriority.MONITOR, false); - assertMutationHandler("onBrewingStandFuel", BrewingStandFuelEvent.class); - assertMutationHandler("onBlockDispense", BlockDispenseEvent.class); - assertMutationHandler("onCrafterCraft", CrafterCraftEvent.class); - assertHandler("onWorldUnload", WorldUnloadEvent.class, EventPriority.HIGHEST, true); - } - @Test public void jigsawTileSnapshotDetectsLateVanillaGuiMutation() { KMap baseline = new KMap<>(); @@ -437,48 +340,47 @@ public class JigsawStudioServiceCaptureTest { JigsawStudioService.AutosaveFailureState writerState = new JigsawStudioService.AutosaveFailureState(); - try (MockedStatic logging = mockStatic(IrisLogging.class)) { - JigsawStudioService.AutosaveFailureDecision firstValidation = - JigsawStudioService.recordPersistentAutosaveFailure( - validationState, - requestId, - "qa/profile_final", - "workcell/end", - "qa/profile_final/end", - validationDetail, - validationFailure); - JigsawStudioService.AutosaveFailureDecision secondValidation = - JigsawStudioService.recordPersistentAutosaveFailure( - validationState, - requestId, - "qa/profile_final", - "workcell/end", - "qa/profile_final/end", - validationDetail, - validationFailure); - List writerDelays = new ArrayList<>(); - for (int attempt = 0; attempt < 7; attempt++) { - writerDelays.add(JigsawStudioService.recordPersistentAutosaveFailure( - writerState, + JigsawStudioService.AutosaveFailureDecision firstValidation = + JigsawStudioService.recordPersistentAutosaveFailure( + log, + validationState, requestId, "qa/profile_final", "workcell/end", "qa/profile_final/end", - writerDetail, - null).retryTicks()); - } - - assertEquals(40, firstValidation.retryTicks()); - assertTrue(firstValidation.logFailure()); - assertEquals(80, secondValidation.retryTicks()); - assertFalse(secondValidation.logFailure()); - assertEquals(List.of(40, 80, 160, 320, 600, 600, 600), writerDelays); - logging.verify( - () -> IrisLogging.reportError(validationContext, validationFailure), - times(1)); - logging.verify(() -> IrisLogging.warn("%s", writerContext), times(1)); + validationDetail, + validationFailure); + JigsawStudioService.AutosaveFailureDecision secondValidation = + JigsawStudioService.recordPersistentAutosaveFailure( + log, + validationState, + requestId, + "qa/profile_final", + "workcell/end", + "qa/profile_final/end", + validationDetail, + validationFailure); + List writerDelays = new ArrayList<>(); + for (int attempt = 0; attempt < 7; attempt++) { + writerDelays.add(JigsawStudioService.recordPersistentAutosaveFailure( + log, + writerState, + requestId, + "qa/profile_final", + "workcell/end", + "qa/profile_final/end", + writerDetail, + null).retryTicks()); } + assertEquals(40, firstValidation.retryTicks()); + assertTrue(firstValidation.logFailure()); + assertEquals(80, secondValidation.retryTicks()); + assertFalse(secondValidation.logFailure()); + assertEquals(List.of(40, 80, 160, 320, 600, 600, 600), writerDelays); + verify(log, times(1)).error(validationContext, validationFailure); + verify(log, times(1)).warn(writerContext); + JigsawStudioService.AutosaveFailureDecision newIdentity = new JigsawStudioService.AutosaveFailureState().recordPersistentFailure(); assertEquals(40, newIdentity.retryTicks()); @@ -487,9 +389,7 @@ public class JigsawStudioServiceCaptureTest { @Test public void siblingAutosaveResolvesTheCurrentBayAfterACommittedSaveReloadsLayout() - throws ReflectiveOperationException { - UUID requestId = UUID.fromString("33333333-3333-3333-3333-333333333333"); - UUID worldId = UUID.fromString("44444444-4444-4444-4444-444444444444"); + throws ReflectiveOperationException, InterruptedException { JigsawStudioCellDimensions dimensions = new JigsawStudioCellDimensions(16, 16, 16); JigsawStudioVariant endVariant = planarVariant( "test/end", @@ -507,10 +407,15 @@ public class JigsawStudioServiceCaptureTest { JigsawStudioMode.PLANAR_JIGSAW, dimensions, catalog); - JigsawStudioSession session = new JigsawStudioSession( + JigsawStudioRequest request = service.registry().activate( "overworld", "qa/profile_final", + JigsawStudioMode.PLANAR_JIGSAW, + JigsawStudioCompatibilityTarget.IRIS_EXTENDED, + dimensions, + StudioToolPacks.toolPack(), initialLayout); + JigsawStudioSession session = service.registry().getSession(request.requestId()); JigsawStudioBay initialEnd = initialLayout.get("workcell/end"); JigsawStudioBay initialStraight = initialLayout.get("workcell/straight"); JigsawStudioSession.DirtyIdentity endDirty = session.markWorkcellDirty(initialEnd.stableId()) @@ -519,191 +424,97 @@ public class JigsawStudioServiceCaptureTest { JigsawStudioSession.DirtyIdentity straightDirty = session.markWorkcellDirty(initialStraight.stableId()) .identity() .orElseThrow(); - JigsawStudioActivation.Request request = mock(JigsawStudioActivation.Request.class); - when(request.requestId()).thenReturn(requestId); - when(request.packKey()).thenReturn("overworld"); - when(request.structureKey()).thenReturn("qa/profile_final"); - IrisData source = mock(IrisData.class); - @SuppressWarnings("unchecked") - ResourceLoader objectLoader = mock(ResourceLoader.class); - when(request.source()).thenReturn(source); - ModuleResourceFixture resources = ModuleResourceFixture.serve(source); - when(source.getObjectLoader()).thenReturn(objectLoader); - resources.resource(StructureResources.PIECES, "test/end", new IrisJigsawPiece().setObject("test/end")); - resources.resource(StructureResources.PIECES, "test/straight", new IrisJigsawPiece().setObject("test/straight")); - when(objectLoader.load("test/end", false)).thenReturn(new IrisObject(16, 16, 16)); - when(objectLoader.load("test/straight", false)).thenReturn(new IrisObject(16, 16, 16)); - JigsawStudioGenerator generator = mock(JigsawStudioGenerator.class); - when(generator.getRequest()).thenReturn(request); - when(generator.getSession()).thenReturn(session); - when(generator.getLayout()).thenAnswer(invocation -> session.layout()); - World world = mock(World.class); - when(world.getUID()).thenReturn(worldId); + FakeStudioPack pack = new FakeStudioPack() + .piece("test/end", new IrisJigsawPiece().setObject("test/end")) + .piece("test/straight", new IrisJigsawPiece().setObject("test/straight")) + .emptyObject("test/end", 16, 16, 16) + .emptyObject("test/straight", 16, 16, 16); + FakeToolWorld world = new FakeToolWorld("jigsaw"); + world.holdTasks = true; + JigsawStudioGenerator generator = generatorOf(pack, request, session); ConcurrentHashMap populations = new ConcurrentHashMap<>(); - JigsawStudioService.BayPopulation endPopulation = - new JigsawStudioService.BayPopulation(Set.of(0L), ""); - JigsawStudioService.BayPopulation straightPopulation = - new JigsawStudioService.BayPopulation(Set.of(0L), ""); - endPopulation.markFullyReady(); - straightPopulation.markFullyReady(); - populations.put(initialEnd.stableId(), endPopulation); - populations.put(initialStraight.stableId(), straightPopulation); - Class studioType = Class.forName(JigsawStudioService.class.getName() + "$ActiveStudio"); - Constructor studioConstructor = studioType.getDeclaredConstructor( - UUID.class, - World.class, - Engine.class, - JigsawStudioGenerator.class, - ConcurrentHashMap.class, - Set.class, - AtomicLong.class); - studioConstructor.setAccessible(true); - Object studio = studioConstructor.newInstance( - worldId, - world, - mock(Engine.class), - generator, - populations, - ConcurrentHashMap.newKeySet(), - new AtomicLong()); + populations.put(initialEnd.stableId(), readyPopulation()); + populations.put(initialStraight.stableId(), readyPopulation()); + JigsawStudioService.ActiveStudio studio = register(world, generator, populations); Method scheduleAutosave = JigsawStudioService.class.getDeclaredMethod( "scheduleAutosave", - studioType, + JigsawStudioService.ActiveStudio.class, JigsawStudioBay.class, JigsawStudioSession.DirtyIdentity.class, int.class); scheduleAutosave.setAccessible(true); - JigsawStudioService service = new JigsawStudioService(); - Field studiosField = JigsawStudioService.class.getDeclaredField("studios"); - studiosField.setAccessible(true); - @SuppressWarnings("unchecked") - Map studios = (Map) studiosField.get(service); - studios.put(worldId, studio); - List delayedAutosaves = new ArrayList<>(); - try (MockedStatic scheduling = mockStatic(J.class); - MockedStatic activation = mockStatic(JigsawStudioActivation.class)) { - activation.when(() -> JigsawStudioActivation.getRequest("overworld")).thenReturn(request); - scheduling.when(() -> J.runRegion( - any(World.class), - anyInt(), - anyInt(), - any(Runnable.class), - eq(40))) - .thenAnswer(invocation -> { - delayedAutosaves.add(invocation.getArgument(3, Runnable.class)); - return true; - }); - scheduling.when(() -> J.runRegion( - any(World.class), - anyInt(), - anyInt(), - any(Runnable.class))) - .thenReturn(true); - scheduleAutosave.invoke(service, studio, initialEnd, endDirty, 40); - scheduleAutosave.invoke(service, studio, initialStraight, straightDirty, 40); - assertEquals(2, delayedAutosaves.size()); + scheduleAutosave.invoke(service, studio, initialEnd, endDirty, 1); + scheduleAutosave.invoke(service, studio, initialStraight, straightDirty, 1); + awaitTrue(() -> world.held.size() == 2); - JigsawStudioSession.SaveIdentity committedEnd = session.beginSave(initialEnd.stableId()) - .identity() - .orElseThrow(); - assertTrue(session.markWorkcellSaved(committedEnd)); - JigsawStudioLayout replacementLayout = JigsawStudioLayout.create( - JigsawStudioMode.PLANAR_JIGSAW, - dimensions, - catalog); - assertTrue(session.replaceLayout(replacementLayout)); - JigsawStudioBay currentStraight = JigsawStudioService.resolveCurrentAutosaveBay( - session, - initialStraight.stableId()); - assertNotSame(initialStraight, currentStraight); - assertSame(replacementLayout.get(initialStraight.stableId()), currentStraight); - assertTrue(session.isDirtyCurrent(straightDirty)); + JigsawStudioSession.SaveIdentity committedEnd = session.beginSave(initialEnd.stableId()) + .identity() + .orElseThrow(); + assertTrue(session.markWorkcellSaved(committedEnd)); + JigsawStudioLayout replacementLayout = JigsawStudioLayout.create( + JigsawStudioMode.PLANAR_JIGSAW, + dimensions, + catalog); + assertTrue(session.replaceLayout(replacementLayout)); + JigsawStudioBay currentStraight = JigsawStudioService.resolveCurrentAutosaveBay( + session, + initialStraight.stableId()); + assertNotSame(initialStraight, currentStraight); + assertSame(replacementLayout.get(initialStraight.stableId()), currentStraight); + assertTrue(session.isDirtyCurrent(straightDirty)); - delayedAutosaves.get(1).run(); + world.holdTasks = true; + world.runHeld(); - assertTrue(session.workcellSnapshot(initialStraight.stableId()).saveInProgress()); - } + assertTrue(session.workcellSnapshot(initialStraight.stableId()).saveInProgress()); } @Test public void saveNowRetainsAutosaveAcrossNotReadyInProgressAndSchedulerRejection() throws ReflectiveOperationException { - UUID ownerId = UUID.fromString("11111111-1111-1111-1111-111111111111"); - UUID requestId = UUID.fromString("33333333-3333-3333-3333-333333333333"); - UUID worldId = UUID.fromString("44444444-4444-4444-4444-444444444444"); JigsawStudioCellDimensions dimensions = new JigsawStudioCellDimensions(16, 16, 16); JigsawStudioLayout layout = JigsawStudioLayout.create( JigsawStudioMode.PLANAR_JIGSAW, dimensions, new JigsawStudioVariantCatalog(List.of(planarVariant(true, true)))); JigsawStudioBay bay = layout.get("workcell/end"); - JigsawStudioSession session = new JigsawStudioSession("overworld", "village", layout); + assertTrue(service.registry().tryBeginOpen(OWNER)); + JigsawStudioRequest request = service.registry().activate( + "overworld", + "village", + JigsawStudioMode.PLANAR_JIGSAW, + JigsawStudioCompatibilityTarget.IRIS_EXTENDED, + dimensions, + StudioToolPacks.toolPack(), + layout, + OWNER); + service.registry().finishOpen(OWNER); + JigsawStudioSession session = service.registry().getSession(request.requestId()); JigsawStudioSession.DirtyIdentity identity = session.markWorkcellDirty(bay.stableId()) .identity() .orElseThrow(); - JigsawStudioActivation.Request request = mock(JigsawStudioActivation.Request.class); - when(request.requestId()).thenReturn(requestId); - when(request.ownerId()).thenReturn(ownerId); - IrisData source = mock(IrisData.class); - @SuppressWarnings("unchecked") - ResourceLoader objectLoader = mock(ResourceLoader.class); - IrisJigsawPiece piece = new IrisJigsawPiece().setObject("test/end"); - IrisObject object = new IrisObject(16, 16, 16); - when(request.source()).thenReturn(source); - ModuleResourceFixture resources = ModuleResourceFixture.serve(source); - when(source.getObjectLoader()).thenReturn(objectLoader); - resources.resource(StructureResources.PIECES, "test/end", piece); - when(objectLoader.load("test/end", false)).thenReturn(object); - JigsawStudioGenerator generator = mock(JigsawStudioGenerator.class); - when(generator.getRequest()).thenReturn(request); - when(generator.getSession()).thenReturn(session); - when(generator.getLayout()).thenReturn(layout); - when(generator.renderBay(any(JigsawStudioBay.class))) - .thenReturn(JigsawStudioGenerator.RenderedBay.empty(dimensions)); - World world = mock(World.class); - when(world.getUID()).thenReturn(worldId); - Player player = mock(Player.class); - when(player.getUniqueId()).thenReturn(ownerId); - when(player.getWorld()).thenReturn(world); - - JigsawStudioService service = new JigsawStudioService(); + FakeStudioPack pack = new FakeStudioPack() + .piece("test/end", new IrisJigsawPiece().setObject("test/end")) + .emptyObject("test/end", 16, 16, 16); + FakeToolWorld world = new FakeToolWorld("jigsaw"); + world.schedulingFails = true; + FakeToolPlayer player = new FakeToolPlayer(OWNER, "owner", world); + JigsawStudioGenerator generator = generatorOf(pack, request, session); ConcurrentHashMap populations = new ConcurrentHashMap<>(); populations.put( bay.stableId(), new JigsawStudioService.BayPopulation(Set.of(0L), "workcell hydration failed")); - Class studioType = Class.forName(JigsawStudioService.class.getName() + "$ActiveStudio"); - Constructor studioConstructor = studioType.getDeclaredConstructor( - UUID.class, - World.class, - Engine.class, - JigsawStudioGenerator.class, - ConcurrentHashMap.class, - Set.class, - AtomicLong.class); - studioConstructor.setAccessible(true); - Object studio = studioConstructor.newInstance( - worldId, - world, - mock(Engine.class), - generator, - populations, - ConcurrentHashMap.newKeySet(), - new AtomicLong()); - Field studiosField = JigsawStudioService.class.getDeclaredField("studios"); - studiosField.setAccessible(true); - @SuppressWarnings("unchecked") - Map studios = (Map) studiosField.get(service); - studios.put(worldId, studio); + JigsawStudioService.ActiveStudio studio = register(world, generator, populations); Class keyType = Class.forName(JigsawStudioService.class.getName() + "$AutosaveKey"); Constructor keyConstructor = keyType.getDeclaredConstructor(UUID.class, String.class); keyConstructor.setAccessible(true); - Object key = keyConstructor.newInstance(requestId, bay.stableId()); + Object key = keyConstructor.newInstance(request.requestId(), bay.stableId()); Class ticketType = Class.forName(JigsawStudioService.class.getName() + "$AutosaveTicket"); Constructor ticketConstructor = ticketType.getDeclaredConstructor( keyType, - studioType, + JigsawStudioService.ActiveStudio.class, JigsawStudioSession.DirtyIdentity.class, AtomicBoolean.class, AtomicBoolean.class); @@ -725,38 +536,27 @@ public class JigsawStudioServiceCaptureTest { (JigsawStudioService.AutosaveFailureState) failureStateAccessor.invoke(ticket); assertEquals(40, failureState.recordPersistentFailure().retryTicks()); - try (MockedStatic scheduling = mockStatic(J.class)) { - scheduling.when(() -> J.isOwnedByCurrentRegion(player)).thenReturn(true); - scheduling.when(() -> J.runRegion( - any(World.class), anyInt(), anyInt(), any(Runnable.class), anyInt())) - .thenReturn(false); + assertFalse(service.flushAutosave(player, bay.stableId())); + assertEquals(1, autosaves.size()); + assertTrue(session.isDirtyCurrent(identity)); - assertFalse(service.flushAutosave(player, bay.stableId())); - assertEquals(1, autosaves.size()); - assertTrue(session.isDirtyCurrent(identity)); + populations.put( + bay.stableId(), + new JigsawStudioService.BayPopulation(Set.of(0L), "")); + assertFalse(service.flushAutosave(player, bay.stableId())); + assertEquals(1, autosaves.size()); + assertTrue(session.isDirtyCurrent(identity)); - populations.put( - bay.stableId(), - new JigsawStudioService.BayPopulation(Set.of(0L), "")); - assertFalse(service.flushAutosave(player, bay.stableId())); - assertEquals(1, autosaves.size()); - assertTrue(session.isDirtyCurrent(identity)); - - JigsawStudioService.BayPopulation ready = - new JigsawStudioService.BayPopulation(Set.of(0L), ""); - ready.markFullyReady(); - populations.put(bay.stableId(), ready); - JigsawStudioSession.SaveIdentity inProgress = session.beginSave(bay.stableId()) - .identity() - .orElseThrow(); - assertFalse(service.flushAutosave(player, bay.stableId())); - assertEquals(1, autosaves.size()); - assertTrue(session.abortSave(inProgress)); - scheduling.verify(() -> J.s(any(Runnable.class), eq(5)), times(3)); - Object retainedTicket = autosaves.values().iterator().next(); - assertSame(failureState, failureStateAccessor.invoke(retainedTicket)); - assertEquals(80, failureState.recordPersistentFailure().retryTicks()); - } + populations.put(bay.stableId(), readyPopulation()); + JigsawStudioSession.SaveIdentity inProgress = session.beginSave(bay.stableId()) + .identity() + .orElseThrow(); + assertFalse(service.flushAutosave(player, bay.stableId())); + assertEquals(1, autosaves.size()); + assertTrue(session.abortSave(inProgress)); + Object retainedTicket = autosaves.values().iterator().next(); + assertSame(failureState, failureStateAccessor.invoke(retainedTicket)); + assertEquals(80, failureState.recordPersistentFailure().retryTicks()); } @Test @@ -782,8 +582,8 @@ public class JigsawStudioServiceCaptureTest { JigsawStudioMode.PLANAR_JIGSAW, dimensions, JigsawStudioVariantCatalog.empty()); - IrisJigsawConnector eastSource = connector().setDirection(IrisDirection.EAST_POSITIVE_X); - IrisJigsawConnector southDisplayed = connector().setDirection(IrisDirection.SOUTH_POSITIVE_Z); + IrisJigsawConnector eastSource = connector().setDirection(JigsawDirection.EAST_POSITIVE_X); + IrisJigsawConnector southDisplayed = connector().setDirection(JigsawDirection.SOUTH_POSITIVE_Z); JigsawStudioService.requireWorkcellTopology( layout.get("workcell/end"), @@ -816,17 +616,17 @@ public class JigsawStudioServiceCaptureTest { 0, new JigsawStudioCellDimensions(3, 1, 3)); List areas = JigsawStudioService.chunkIntersections(bounds); - PlatformBlockState sourceState = BukkitBlockState.of(directionalBlockData(BlockFace.NORTH)); + BlockState sourceState = BlockState.parse("minecraft:observer[facing=north]"); for (int quarterTurns = 1; quarterTurns <= 3; quarterTurns++) { - ObjectTurn displayRotation = ObjectTurn.of(0, -90.0D * quarterTurns, 0); - PlatformBlockState displayedState = BlockStateRotation.rotate(displayRotation, sourceState); - IrisDirection displayedDirection = displayRotation.rotate(IrisDirection.NORTH_NEGATIVE_Z); + PieceTurn displayRotation = PieceTurn.aroundY(-90 * quarterTurns); + BlockState displayedState = FakeBlockRegistry.rotated(sourceState, displayRotation.blockTurn()); + JigsawDirection displayedDirection = JigsawDirection.NORTH_NEGATIVE_Z.turnedBy(displayRotation.quarterTurns()); JigsawStudioService.CapturedConnector connector = new JigsawStudioService.CapturedConnector( 1, 0, 1, displayedDirection, - IrisDirection.UP_POSITIVE_Y, + JigsawDirection.UP_POSITIVE_Y, "test/pool", "door", "door", @@ -839,24 +639,23 @@ public class JigsawStudioServiceCaptureTest { areas.getFirst(), List.of(), List.of(connector)); - try (MockedStatic blocks = mockStatic(B.class)) { - blocks.when(() -> B.getStateOrNull( - displayedState.key(), false)).thenReturn(displayedState); - JigsawStudioService.Capture capture = JigsawStudioService.aggregateSnapshots( - bounds, - areas, - List.of(snapshot), - quarterTurns); - assertEquals(sourceState.key(), capture.connectors().getFirst().getFinalState()); - assertEquals(-3, capture.connectors().getFirst().getSelectionPriority()); - assertEquals(7, capture.connectors().getFirst().getPlacementPriority()); - } + JigsawStudioService.Capture capture = JigsawStudioService.aggregateSnapshots( + registry, + codec, + bounds, + areas, + List.of(snapshot), + quarterTurns); + + assertEquals(sourceState.key(), capture.connectors().getFirst().getFinalState()); + assertEquals(-3, capture.connectors().getFirst().getSelectionPriority()); + assertEquals(7, capture.connectors().getFirst().getPlacementPriority()); } } @Test - public void hiddenConnectorCapturesExactBlockStateTilePayloadAndMetadata() throws Throwable { + public void hiddenConnectorCapturesExactBlockStateTilePayloadAndMetadata() throws Exception { JigsawStudioBounds bounds = new JigsawStudioBounds( 0, 64, @@ -868,70 +667,61 @@ public class JigsawStudioServiceCaptureTest { .setPlacementPriority(11); IrisJigsawPiece piece = new IrisJigsawPiece().setConnectors(new KList<>()); piece.getConnectors().add(connector); - BlockData chestData = directionalBlockData(Material.CHEST, BlockFace.EAST); - PlatformBlockState chestState = BukkitBlockState.of(chestData); - IrisObject sourceObject = new IrisObject(1, 1, 1); - sourceObject.setUnsigned(0, 0, 0, chestState); - KMap properties = new KMap<>(); - properties.put("CustomName", "Hidden Connector Chest"); - properties.put("Lock", "iris:hidden"); - TileData tileData = new TileData("minecraft:chest", properties); - Block block = mock(Block.class); - when(block.getBlockData()).thenReturn(chestData); - World world = mock(World.class); - when(world.getBlockAt(0, 64, 0)).thenReturn(block); + BlockState chest = BlockState.parse("minecraft:chest[facing=east]"); + BlockEntityData tile = tile(1); + FakeToolWorld world = new FakeToolWorld("jigsaw"); + world.setBlock(new BlockPosition(0, 64, 0), chest, Optional.of(tile)); JigsawStudioService.ChunkCaptureArea area = JigsawStudioService.chunkIntersections(bounds).getFirst(); - JigsawStudioService.ChunkSnapshot snapshot; - try (MockedStatic tiles = mockStatic(TileData.class)) { - tiles.when(() -> TileData.getTileState(block, false)).thenReturn(tileData); - snapshot = JigsawStudioService.captureChunkIntersection( - world, - bounds, - piece, - sourceObject, - area, - 0, - false); - } + JigsawStudioService.ChunkSnapshot snapshot = JigsawStudioService.captureChunkIntersection( + world, + registry, + bounds, + piece, + new JigsawStudioService.SourceObject(1, 1, 1, Map.of()), + area, + 0, + false); JigsawStudioService.Capture capture = JigsawStudioService.aggregateSnapshots( + registry, + codec, bounds, List.of(area), List.of(snapshot)); - IrisObject restored = readCapturedObject(capture.objectContent(), chestState); + GeneratedObject restored = codec.decode(capture.objectContent()); IrisJigsawConnector captured = capture.connectors().getFirst(); - assertEquals(chestData.getAsString(), captured.getFinalState()); + assertEquals(chest.key(), captured.getFinalState()); assertEquals("gate/owned", captured.getChannel()); assertEquals(-7, captured.getSelectionPriority()); assertEquals(11, captured.getPlacementPriority()); - assertEquals(tileData, restored.getStates().get(restored.getSigned(0, 0, 0))); + assertEquals(Optional.of(tile), restored.blocks().getFirst().blockEntity()); assertTrue(capture.hasBlockEntities()); } @Test public void noOpTeeAndCrossCapturePreservesCreatorOrderForSeededAssembly() throws IOException { JigsawStudioCellDimensions dimensions = new JigsawStudioCellDimensions(16, 16, 16); - List> authoredOrders = List.of( + List> authoredOrders = List.of( List.of( - IrisDirection.NORTH_NEGATIVE_Z, - IrisDirection.EAST_POSITIVE_X, - IrisDirection.WEST_NEGATIVE_X), + JigsawDirection.NORTH_NEGATIVE_Z, + JigsawDirection.EAST_POSITIVE_X, + JigsawDirection.WEST_NEGATIVE_X), List.of( - IrisDirection.NORTH_NEGATIVE_Z, - IrisDirection.EAST_POSITIVE_X, - IrisDirection.SOUTH_POSITIVE_Z, - IrisDirection.WEST_NEGATIVE_X)); - List> captureOrders = List.of( + JigsawDirection.NORTH_NEGATIVE_Z, + JigsawDirection.EAST_POSITIVE_X, + JigsawDirection.SOUTH_POSITIVE_Z, + JigsawDirection.WEST_NEGATIVE_X)); + List> captureOrders = List.of( List.of( - IrisDirection.WEST_NEGATIVE_X, - IrisDirection.NORTH_NEGATIVE_Z, - IrisDirection.EAST_POSITIVE_X), + JigsawDirection.WEST_NEGATIVE_X, + JigsawDirection.NORTH_NEGATIVE_Z, + JigsawDirection.EAST_POSITIVE_X), List.of( - IrisDirection.WEST_NEGATIVE_X, - IrisDirection.NORTH_NEGATIVE_Z, - IrisDirection.SOUTH_POSITIVE_Z, - IrisDirection.EAST_POSITIVE_X)); + JigsawDirection.WEST_NEGATIVE_X, + JigsawDirection.NORTH_NEGATIVE_Z, + JigsawDirection.SOUTH_POSITIVE_Z, + JigsawDirection.EAST_POSITIVE_X)); for (int index = 0; index < authoredOrders.size(); index++) { IrisJigsawPiece source = pieceWithPlanarConnectors(dimensions, authoredOrders.get(index)); @@ -949,11 +739,11 @@ public class JigsawStudioServiceCaptureTest { public void connectorMetadataEditsAtTheSamePositionKeepAuthoredOrder() throws IOException { JigsawStudioCellDimensions dimensions = new JigsawStudioCellDimensions(16, 16, 16); IrisJigsawPiece source = pieceWithPlanarConnectors(dimensions, List.of( - IrisDirection.NORTH_NEGATIVE_Z, - IrisDirection.EAST_POSITIVE_X)); + JigsawDirection.NORTH_NEGATIVE_Z, + JigsawDirection.EAST_POSITIVE_X)); IrisJigsawConnector capturedNorth = planarConnector( dimensions, - IrisDirection.NORTH_NEGATIVE_Z) + JigsawDirection.NORTH_NEGATIVE_Z) .setPool("changed/pool") .setName("changed:name") .setTargetName("changed:target") @@ -964,7 +754,7 @@ public class JigsawStudioServiceCaptureTest { .setPlacementPriority(-4); IrisJigsawConnector capturedEast = planarConnector( dimensions, - IrisDirection.EAST_POSITIVE_X); + JigsawDirection.EAST_POSITIVE_X); List ordered = JigsawStudioService.preserveCapturedConnectorOrder( source, @@ -980,23 +770,23 @@ public class JigsawStudioServiceCaptureTest { public void removedConnectorsDisappearWithoutReorderingSurvivors() throws IOException { JigsawStudioCellDimensions dimensions = new JigsawStudioCellDimensions(16, 16, 16); IrisJigsawPiece source = pieceWithPlanarConnectors(dimensions, List.of( - IrisDirection.NORTH_NEGATIVE_Z, - IrisDirection.EAST_POSITIVE_X, - IrisDirection.WEST_NEGATIVE_X)); + JigsawDirection.NORTH_NEGATIVE_Z, + JigsawDirection.EAST_POSITIVE_X, + JigsawDirection.WEST_NEGATIVE_X)); IrisJigsawConnector capturedWest = planarConnector( dimensions, - IrisDirection.WEST_NEGATIVE_X); + JigsawDirection.WEST_NEGATIVE_X); IrisJigsawConnector capturedNorth = planarConnector( dimensions, - IrisDirection.NORTH_NEGATIVE_Z); + JigsawDirection.NORTH_NEGATIVE_Z); List ordered = JigsawStudioService.preserveCapturedConnectorOrder( source, List.of(capturedWest, capturedNorth)); assertEquals(List.of( - IrisDirection.NORTH_NEGATIVE_Z, - IrisDirection.WEST_NEGATIVE_X), connectorDirections(ordered)); + JigsawDirection.NORTH_NEGATIVE_Z, + JigsawDirection.WEST_NEGATIVE_X), connectorDirections(ordered)); } @Test @@ -1004,10 +794,10 @@ public class JigsawStudioServiceCaptureTest { JigsawStudioCellDimensions dimensions = new JigsawStudioCellDimensions(16, 16, 16); IrisJigsawPiece source = pieceWithPlanarConnectors( dimensions, - List.of(IrisDirection.NORTH_NEGATIVE_Z)); + List.of(JigsawDirection.NORTH_NEGATIVE_Z)); IrisJigsawConnector capturedNorth = planarConnector( dimensions, - IrisDirection.NORTH_NEGATIVE_Z); + JigsawDirection.NORTH_NEGATIVE_Z); IrisJigsawConnector highY = connectorAt(2, 5, 9); IrisJigsawConnector highZ = connectorAt(2, 3, 10); IrisJigsawConnector lowZ = connectorAt(2, 3, 4); @@ -1026,7 +816,7 @@ public class JigsawStudioServiceCaptureTest { public void duplicateSourceOrCapturedConnectorPositionsAreRejected() { IrisJigsawConnector first = connectorAt(1, 2, 3); IrisJigsawConnector second = connectorAt(1, 2, 3) - .setDirection(IrisDirection.SOUTH_POSITIVE_Z); + .setDirection(JigsawDirection.SOUTH_POSITIVE_Z); IrisJigsawPiece duplicateSource = new IrisJigsawPiece().setConnectors(new KList<>()); duplicateSource.getConnectors().add(first); duplicateSource.getConnectors().add(second); @@ -1049,18 +839,17 @@ public class JigsawStudioServiceCaptureTest { new JigsawStudioCellDimensions(5, 1, 3)); List areas = JigsawStudioService.chunkIntersections(bounds); IrisJigsawConnector sourceFirst = connectorAt(0, 0, 1) - .setDirection(IrisDirection.NORTH_NEGATIVE_Z); + .setDirection(JigsawDirection.NORTH_NEGATIVE_Z); IrisJigsawConnector sourceSecond = connectorAt(2, 0, 2) - .setDirection(IrisDirection.EAST_POSITIVE_X); + .setDirection(JigsawDirection.EAST_POSITIVE_X); IrisJigsawPiece source = new IrisJigsawPiece().setConnectors(new KList<>()); source.getConnectors().add(sourceFirst); source.getConnectors().add(sourceSecond); - PlatformBlockState sourceState = BukkitBlockState.of( - directionalBlockData(Material.OBSERVER, BlockFace.NORTH)); + BlockState sourceState = BlockState.parse("minecraft:observer[facing=north]"); for (int quarterTurns = 1; quarterTurns <= 3; quarterTurns++) { - ObjectTurn displayRotation = ObjectTurn.of(0, -90.0D * quarterTurns, 0); - PlatformBlockState displayedState = BlockStateRotation.rotate(displayRotation, sourceState); + PieceTurn displayRotation = PieceTurn.aroundY(-90 * quarterTurns); + BlockState displayedState = FakeBlockRegistry.rotated(sourceState, displayRotation.blockTurn()); JigsawStudioService.CapturedConnector displayedFirst = displayedConnector( sourceFirst, bounds.dimensions(), @@ -1078,35 +867,34 @@ public class JigsawStudioServiceCaptureTest { List.of(), List.of(displayedSecond, displayedFirst)); - try (MockedStatic blocks = mockStatic(B.class)) { - blocks.when(() -> B.getStateOrNull(displayedState.key(), false)).thenReturn(displayedState); - JigsawStudioService.Capture capture = JigsawStudioService.aggregateSnapshots( - bounds, - areas, - List.of(snapshot), - quarterTurns); - List ordered = JigsawStudioService.preserveCapturedConnectorOrder( - source, - capture.connectors()); + JigsawStudioService.Capture capture = JigsawStudioService.aggregateSnapshots( + registry, + codec, + bounds, + areas, + List.of(snapshot), + quarterTurns); + List ordered = JigsawStudioService.preserveCapturedConnectorOrder( + source, + capture.connectors()); - assertEquals(sourceFirst.getPosition(), ordered.getFirst().getPosition()); - assertEquals(sourceSecond.getPosition(), ordered.getLast().getPosition()); - } + assertEquals(sourceFirst.getPosition(), ordered.getFirst().getPosition()); + assertEquals(sourceSecond.getPosition(), ordered.getLast().getPosition()); } } @Test - public void rotatedBlockEntityPayloadReturnsToItsStoredCoordinateUnchanged() throws Throwable { + public void rotatedBlockEntityPayloadReturnsToItsStoredCoordinateUnchanged() throws IOException { + int width = 5; + int height = 2; + int depth = 3; JigsawStudioBounds bounds = new JigsawStudioBounds( 0, 64, 0, - new JigsawStudioCellDimensions(5, 2, 3)); + new JigsawStudioCellDimensions(width, height, depth)); List areas = JigsawStudioService.chunkIntersections(bounds); - KMap properties = new KMap<>(); - properties.put("CustomName", "QA Chest"); - properties.put("Lock", "iris:test"); - TileData tileData = new TileData("minecraft:chest", properties); + BlockEntityData tile = tile(2); int[][] expectedPositions = { {0, 0, 0}, {1, 1, 3}, @@ -1114,109 +902,106 @@ public class JigsawStudioServiceCaptureTest { {1, 1, 1} }; for (int quarterTurns = 1; quarterTurns <= 3; quarterTurns++) { - BlockData displayedData = directionalBlockData(Material.CHEST, BlockFace.EAST); - PlatformBlockState displayedState = BukkitBlockState.of(displayedData); + BlockState displayedState = BlockState.parse("minecraft:chest[facing=east]"); JigsawStudioService.CapturedBlock capturedBlock = new JigsawStudioService.CapturedBlock( 1, 1, 1, displayedState, - tileData); + tile); JigsawStudioService.ChunkSnapshot snapshot = new JigsawStudioService.ChunkSnapshot( areas.getFirst(), List.of(capturedBlock), List.of()); JigsawStudioService.Capture capture = JigsawStudioService.aggregateSnapshots( + registry, + codec, bounds, areas, List.of(snapshot), quarterTurns); - IrisObject restored = readCapturedObject(capture.objectContent(), displayedState); + GeneratedObject restored = codec.decode(capture.objectContent()); + int sourceWidth = (quarterTurns & 1) == 0 ? width : depth; + int sourceDepth = (quarterTurns & 1) == 0 ? depth : width; int[] expected = expectedPositions[quarterTurns]; - TileData restoredTile = restored.getStates().get(restored.getSigned( - expected[0], expected[1], expected[2])); + BlockPosition storedAt = new BlockPosition( + expected[0] - sourceWidth / 2, + expected[1] - height / 2, + expected[2] - sourceDepth / 2); + ObjectBlock restoredBlock = restored.blocks().stream() + .filter(block -> block.position().equals(storedAt)) + .findFirst() + .orElse(null); assertTrue(capture.hasBlockEntities()); - assertNotNull(restoredTile); - assertEquals(tileData, restoredTile); + assertNotNull(restoredBlock); + assertEquals(Optional.of(tile), restoredBlock.blockEntity()); } } @Test public void rotatedTilePayloadDoesNotBlockMaterialization() { - KMap properties = new KMap<>(); - properties.put("CustomName", "QA Chest"); - TileData tileData = new TileData("minecraft:chest", properties); - PlatformBlockState state = BukkitBlockState.of( - directionalBlockData(Material.CHEST, BlockFace.NORTH)); + BlockState state = BlockState.parse("minecraft:chest[facing=north]"); JigsawStudioGenerator.RenderedBay rendered = JigsawStudioGenerator.RenderedBay.valid( new JigsawStudioCellDimensions(3, 2, 5), - List.of(new JigsawStudioGenerator.RenderedBlock(0, 0, 0, state, tileData)), + List.of(new JigsawStudioGenerator.RenderedBlock(0, 0, 0, state, tile(3))), List.of()); - assertEquals("", JigsawStudioService.validateMaterialization(rendered)); + assertEquals("", JigsawStudioService.validateMaterialization(rendered, registry)); } @Test - public void explicitAirFinalStateRemainsInTheCapturedObject() throws Throwable { - IrisObject object = new IrisObject(2, 2, 2); - BlockData air = blockData(Material.AIR, "minecraft:air"); - BlockData structureVoid = blockData(Material.STRUCTURE_VOID, "minecraft:structure_void"); + public void explicitAirFinalStateRemainsInTheCapturedObject() throws Exception { + JigsawStudioBounds bounds = new JigsawStudioBounds( + 0, + 64, + 0, + new JigsawStudioCellDimensions(2, 1, 1)); + JigsawStudioService.ChunkCaptureArea area = JigsawStudioService.chunkIntersections(bounds).getFirst(); + FakeToolWorld world = new FakeToolWorld("jigsaw"); + IrisJigsawConnector airMarker = connectorAt(0, 0, 0).setName("iris:air").setFinalState("minecraft:air"); + IrisJigsawConnector voidMarker = connectorAt(1, 0, 0).setName("iris:void").setFinalState("minecraft:structure_void"); + IrisJigsawPiece piece = new IrisJigsawPiece().setConnectors(new KList<>()); + piece.getConnectors().add(airMarker); + piece.getConnectors().add(voidMarker); + world.setBlock(new BlockPosition(0, 64, 0), BlockState.parse("minecraft:jigsaw[orientation=north_up]"), + Optional.of(JigsawStudioTileCodec.encode("minecraft:jigsaw", JigsawStudioService.markerNbt(airMarker)))); + world.setBlock(new BlockPosition(1, 64, 0), BlockState.parse("minecraft:jigsaw[orientation=north_up]"), + Optional.of(JigsawStudioTileCodec.encode("minecraft:jigsaw", JigsawStudioService.markerNbt(voidMarker)))); - JigsawStudioService.storeConnectorFinalState(object, 0, 0, 0, air); - JigsawStudioService.storeConnectorFinalState(object, 1, 0, 0, structureVoid); + JigsawStudioService.ChunkSnapshot snapshot = JigsawStudioService.captureChunkIntersection( + world, + registry, + bounds, + piece, + new JigsawStudioService.SourceObject(2, 1, 1, Map.of()), + area, + 0, + true); + JigsawStudioService.Capture capture = JigsawStudioService.aggregateSnapshots( + registry, + codec, + bounds, + List.of(area), + List.of(snapshot)); + GeneratedObject restored = codec.decode(capture.objectContent()); - IrisBlockVector airPosition = object.getSigned(0, 0, 0); - IrisBlockVector structureVoidPosition = object.getSigned(1, 0, 0); - assertTrue(object.getBlocks().containsKey(airPosition)); - assertEquals("minecraft:air", object.getBlocks().get(airPosition).key()); - assertFalse(object.getBlocks().containsKey(structureVoidPosition)); - - assertAirRoundTrip(object); + assertEquals(2, snapshot.connectors().size()); + assertEquals(1, restored.blocks().size()); + assertEquals("minecraft:air", restored.blocks().getFirst().state().key()); } @Test - public void originalExplicitAirOutsideAConnectorSurvivesWhileNewAirRemainsAbsent() throws Throwable { - IrisObject source = new IrisObject(2, 2, 2); - BlockData air = blockData(Material.AIR, "minecraft:air"); - BlockData structureVoid = blockData(Material.STRUCTURE_VOID, "minecraft:structure_void"); - PlatformBlockState sourceAir = mock(PlatformBlockState.class); - when(sourceAir.isAir()).thenReturn(true); - when(sourceAir.key()).thenReturn("minecraft:air"); - source.setUnsigned(0, 0, 0, sourceAir); + public void originalExplicitAirOutsideAConnectorSurvivesWhileNewAirRemainsAbsent() { + BlockState air = BlockState.parse("minecraft:air"); + BlockState structureVoid = BlockState.parse("minecraft:structure_void"); + JigsawStudioService.SourceObject source = new JigsawStudioService.SourceObject( + 2, 2, 2, Map.of(new JigsawStudioService.LocalPosition(0, 0, 0), air)); - PlatformBlockState retained = JigsawStudioService.retainedSourceAir(source, 0, 0, 0, air); - assertNotNull(retained); + assertEquals(air, JigsawStudioService.retainedSourceAir(source, 0, 0, 0, air)); assertNull(JigsawStudioService.retainedSourceAir(source, 1, 0, 0, air)); assertNull(JigsawStudioService.retainedSourceAir(source, 0, 0, 0, structureVoid)); - - IrisObject captured = new IrisObject(2, 2, 2); - captured.setUnsigned(0, 0, 0, retained); - assertAirRoundTrip(captured); - } - - private static void assertAirRoundTrip(IrisObject object) throws Throwable { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - object.write(output); - PlatformBlockState restoredAir = mock(PlatformBlockState.class); - when(restoredAir.key()).thenReturn("minecraft:air"); - PlatformRegistries registries = mock(PlatformRegistries.class); - when(registries.block(anyString())).thenReturn(restoredAir); - IrisPlatform platform = mock(IrisPlatform.class); - when(platform.registries()).thenReturn(registries); - IrisPlatforms.unbind(); - IrisPlatforms.bind(platform); - try { - IrisObject restored = new IrisObject(); - restored.read(new ByteArrayInputStream(output.toByteArray())); - - assertTrue(restored.getBlocks().containsKey(restored.getSigned(0, 0, 0))); - assertEquals("minecraft:air", restored.getBlocks().get(restored.getSigned(0, 0, 0)).key()); - assertFalse(restored.getBlocks().containsKey(restored.getSigned(1, 0, 0))); - } finally { - IrisPlatforms.unbind(); - } } @Test @@ -1275,9 +1060,7 @@ public class JigsawStudioServiceCaptureTest { } @Test - public void chunkLoadRecoversAGenerationSignalMissedDuringStudioRegistration() - throws ReflectiveOperationException { - UUID worldId = UUID.fromString("55555555-5555-5555-5555-555555555555"); + public void chunkLoadRecoversAGenerationSignalMissedDuringStudioRegistration() { JigsawStudioCellDimensions dimensions = new JigsawStudioCellDimensions(16, 16, 16); JigsawStudioLayout layout = JigsawStudioLayout.create( JigsawStudioMode.PLANAR_JIGSAW, @@ -1289,49 +1072,17 @@ public class JigsawStudioServiceCaptureTest { new JigsawStudioService.BayPopulation(Set.of(chunkKey), ""); ConcurrentHashMap populations = new ConcurrentHashMap<>(); populations.put(blank.stableId(), population); - - World world = mock(World.class); - when(world.getUID()).thenReturn(worldId); + JigsawStudioRequest request = requestOf(UUID.randomUUID(), JigsawStudioMode.PLANAR_JIGSAW, dimensions); + FakeToolWorld world = new FakeToolWorld("jigsaw"); + world.holdTasks = true; JigsawStudioGenerator generator = mock(JigsawStudioGenerator.class); when(generator.getLayout()).thenReturn(layout); - JigsawStudioActivation.Request request = mock(JigsawStudioActivation.Request.class); - when(request.requestId()).thenReturn(UUID.randomUUID()); when(generator.getRequest()).thenReturn(request); when(generator.renderBay(any(JigsawStudioBay.class))) .thenReturn(JigsawStudioGenerator.RenderedBay.empty(dimensions)); - Class studioType = Class.forName(JigsawStudioService.class.getName() + "$ActiveStudio"); - Constructor studioConstructor = studioType.getDeclaredConstructor( - UUID.class, - World.class, - Engine.class, - JigsawStudioGenerator.class, - ConcurrentHashMap.class, - Set.class, - AtomicLong.class); - studioConstructor.setAccessible(true); - Object studio = studioConstructor.newInstance( - worldId, - world, - mock(Engine.class), - generator, - populations, - ConcurrentHashMap.newKeySet(), - new AtomicLong()); - JigsawStudioService service = new JigsawStudioService(); - Field studiosField = JigsawStudioService.class.getDeclaredField("studios"); - studiosField.setAccessible(true); - @SuppressWarnings("unchecked") - Map studios = (Map) studiosField.get(service); - studios.put(worldId, studio); + register(world, generator, populations); - Chunk chunk = mock(Chunk.class); - when(chunk.getX()).thenReturn(1); - when(chunk.getZ()).thenReturn(1); - ChunkLoadEvent event = mock(ChunkLoadEvent.class); - when(event.getWorld()).thenReturn(world); - when(event.getChunk()).thenReturn(chunk); - - service.onChunkLoad(event); + service.chunkLoaded(request.requestId(), 1, 1); assertTrue(population.needsApplication(chunkKey)); assertEquals(1, population.readiness().generatedChunks()); @@ -1392,8 +1143,7 @@ public class JigsawStudioServiceCaptureTest { 0, new JigsawStudioCellDimensions(20, 2, 1)); List areas = JigsawStudioService.chunkIntersections(bounds); - PlatformBlockState stone = mock(PlatformBlockState.class); - when(stone.key()).thenReturn("minecraft:stone"); + BlockState stone = BlockState.parse("minecraft:stone"); JigsawStudioService.ChunkSnapshot first = new JigsawStudioService.ChunkSnapshot( areas.getFirst(), List.of(new JigsawStudioService.CapturedBlock(0, 0, 0, stone, null)), @@ -1404,20 +1154,19 @@ public class JigsawStudioServiceCaptureTest { List.of()); JigsawStudioService.Capture forward = JigsawStudioService.aggregateSnapshots( - bounds, areas, List.of(first, second)); + registry, codec, bounds, areas, List.of(first, second)); JigsawStudioService.Capture reverse = JigsawStudioService.aggregateSnapshots( - bounds, areas, List.of(second, first)); + registry, codec, bounds, areas, List.of(second, first)); assertArrayEquals(forward.objectContent(), reverse.objectContent()); assertFalse(forward.hasBlockEntities()); assertTrue(forward.connectors().isEmpty()); assertThrows(IOException.class, - () -> JigsawStudioService.aggregateSnapshots(bounds, areas, List.of(first))); + () -> JigsawStudioService.aggregateSnapshots(registry, codec, bounds, areas, List.of(first))); } @Test public void saveRegistrationIsRequestScoped() { - JigsawStudioService service = new JigsawStudioService(); UUID firstRequest = UUID.fromString("44444444-4444-4444-4444-444444444444"); UUID secondRequest = UUID.fromString("55555555-5555-5555-5555-555555555555"); @@ -1431,11 +1180,85 @@ public class JigsawStudioServiceCaptureTest { service.finishSave(secondRequest); } + private JigsawStudioService.ActiveStudio register( + FakeToolWorld world, + JigsawStudioGenerator generator, + ConcurrentHashMap populations + ) { + UUID studioId = generator.getRequest().requestId(); + JigsawStudioService.ActiveStudio studio = new JigsawStudioService.ActiveStudio( + studioId, + world, + generator, + populations, + ConcurrentHashMap.newKeySet(), + new AtomicLong()); + try { + Field studiosField = JigsawStudioService.class.getDeclaredField("studios"); + studiosField.setAccessible(true); + @SuppressWarnings("unchecked") + Map studios = + (Map) studiosField.get(service); + studios.put(studioId, studio); + } catch (ReflectiveOperationException failure) { + throw new IllegalStateException(failure); + } + return studio; + } + + private static JigsawStudioGenerator generatorOf( + FakeStudioPack pack, + JigsawStudioRequest request, + JigsawStudioSession session + ) { + JigsawStudioGenerator generator = mock(JigsawStudioGenerator.class); + when(generator.getRequest()).thenReturn(request); + when(generator.getSession()).thenReturn(session); + when(generator.getLayout()).thenAnswer(invocation -> session.layout()); + when(generator.getPack()).thenReturn(pack.pack); + when(generator.renderBay(any(JigsawStudioBay.class))).thenAnswer(invocation -> + JigsawStudioGenerator.RenderedBay.empty(request.cellDimensions())); + return generator; + } + + private static JigsawStudioRequest requestOf(UUID id, JigsawStudioMode mode, JigsawStudioCellDimensions dimensions) { + return new JigsawStudioRequest( + id, + "overworld", + "qa/profile_final", + mode, + JigsawStudioCompatibilityTarget.IRIS_EXTENDED, + dimensions, + mock(com.volmit.tooling.ToolPack.class), + java.nio.file.Path.of("pack"), + null); + } + + private static JigsawStudioService.BayPopulation readyPopulation() { + JigsawStudioService.BayPopulation ready = new JigsawStudioService.BayPopulation(Set.of(0L), ""); + ready.markFullyReady(); + return ready; + } + + private static BlockEntityData tile(int seed) { + return new BlockEntityData(TILE_FORMAT, 1, new byte[]{(byte) seed, 2, 3}); + } + + private static void awaitTrue(BooleanSupplier condition) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(WAIT_SECONDS); + while (!condition.getAsBoolean()) { + if (System.nanoTime() > deadline) { + throw new AssertionError("Timed out waiting for the studio scheduler"); + } + Thread.sleep(10L); + } + } + private static IrisJigsawConnector connector() { return new IrisJigsawConnector() - .setPosition(new IrisPosition(0, 0, 0)) - .setDirection(IrisDirection.NORTH_NEGATIVE_Z) - .setTop(IrisDirection.UP_POSITIVE_Y) + .setPosition(new BlockPosition(0, 0, 0)) + .setDirection(JigsawDirection.NORTH_NEGATIVE_Z) + .setTop(JigsawDirection.UP_POSITIVE_Y) .setPool("fort/start") .setName("iris:door") .setTargetName("iris:door") @@ -1444,14 +1267,14 @@ public class JigsawStudioServiceCaptureTest { } private static IrisJigsawConnector connectorAt(int x, int y, int z) { - return connector().setPosition(new IrisPosition(x, y, z)); + return connector().setPosition(new BlockPosition(x, y, z)); } private static IrisJigsawConnector planarConnector( JigsawStudioCellDimensions dimensions, - IrisDirection direction + JigsawDirection direction ) { - IrisPosition size = new IrisPosition( + BlockPosition size = new BlockPosition( dimensions.width(), dimensions.height(), dimensions.depth()); @@ -1462,10 +1285,10 @@ public class JigsawStudioServiceCaptureTest { private static List planarConnectors( JigsawStudioCellDimensions dimensions, - List directions + List directions ) { List connectors = new ArrayList<>(directions.size()); - for (IrisDirection direction : directions) { + for (JigsawDirection direction : directions) { connectors.add(planarConnector(dimensions, direction)); } return connectors; @@ -1473,15 +1296,15 @@ public class JigsawStudioServiceCaptureTest { private static IrisJigsawPiece pieceWithPlanarConnectors( JigsawStudioCellDimensions dimensions, - List directions + List directions ) { IrisJigsawPiece piece = new IrisJigsawPiece().setConnectors(new KList<>()); piece.getConnectors().addAll(planarConnectors(dimensions, directions)); return piece; } - private static List connectorDirections(List connectors) { - List directions = new ArrayList<>(connectors.size()); + private static List connectorDirections(List connectors) { + List directions = new ArrayList<>(connectors.size()); for (IrisJigsawConnector connector : connectors) { directions.add(connector.getDirection()); } @@ -1492,19 +1315,19 @@ public class JigsawStudioServiceCaptureTest { IrisJigsawConnector source, JigsawStudioCellDimensions displayDimensions, int displayRotationQuarterTurns, - ObjectTurn displayRotation, + PieceTurn displayRotation, String finalState ) { - IrisPosition displayedPosition = displayedPosition( + BlockPosition displayedPosition = displayedPosition( source.getPosition(), displayDimensions, displayRotationQuarterTurns); return new JigsawStudioService.CapturedConnector( - displayedPosition.getX(), - displayedPosition.getY(), - displayedPosition.getZ(), - displayRotation.rotate(source.getDirection()), - displayRotation.rotate(source.getTop()), + displayedPosition.x(), + displayedPosition.y(), + displayedPosition.z(), + source.getDirection().turnedBy(displayRotation.quarterTurns()), + source.getTop().turnedBy(displayRotation.quarterTurns()), source.getPool(), source.getName(), source.getTargetName(), @@ -1515,8 +1338,8 @@ public class JigsawStudioServiceCaptureTest { source.getPlacementPriority()); } - private static IrisPosition displayedPosition( - IrisPosition source, + private static BlockPosition displayedPosition( + BlockPosition source, JigsawStudioCellDimensions displayDimensions, int displayRotationQuarterTurns ) { @@ -1529,12 +1352,12 @@ public class JigsawStudioServiceCaptureTest { : displayDimensions.width(); return switch (quarterTurns) { case 0 -> source; - case 1 -> new IrisPosition(sourceDepth - 1 - source.getZ(), source.getY(), source.getX()); - case 2 -> new IrisPosition( - sourceWidth - 1 - source.getX(), - source.getY(), - sourceDepth - 1 - source.getZ()); - case 3 -> new IrisPosition(source.getZ(), source.getY(), sourceWidth - 1 - source.getX()); + case 1 -> new BlockPosition(sourceDepth - 1 - source.z(), source.y(), source.x()); + case 2 -> new BlockPosition( + sourceWidth - 1 - source.x(), + source.y(), + sourceDepth - 1 - source.z()); + case 3 -> new BlockPosition(source.z(), source.y(), sourceWidth - 1 - source.x()); default -> throw new IllegalStateException("Unreachable Jigsaw Studio test rotation"); }; } @@ -1566,72 +1389,4 @@ public class JigsawStudioServiceCaptureTest { new JigsawStudioPieceRules(0, 30, 0, 0, false), List.of()); } - - private static Directional directionalBlockData(BlockFace initialFacing) { - return directionalBlockData(Material.OBSERVER, initialFacing); - } - - private static Directional directionalBlockData(Material material, BlockFace initialFacing) { - AtomicReference facing = new AtomicReference<>(initialFacing); - Directional data = mock(Directional.class); - when(data.getFacing()).thenAnswer(invocation -> facing.get()); - when(data.getFaces()).thenReturn(Set.of( - BlockFace.NORTH, - BlockFace.EAST, - BlockFace.SOUTH, - BlockFace.WEST)); - doAnswer(invocation -> { - facing.set(invocation.getArgument(0, BlockFace.class)); - return null; - }).when(data).setFacing(any(BlockFace.class)); - when(data.getMaterial()).thenReturn(material); - when(data.getAsString()).thenAnswer(invocation -> - "minecraft:" + material.name().toLowerCase(Locale.ROOT) + "[facing=" - + facing.get().name().toLowerCase(Locale.ROOT) + "]"); - when(data.clone()).thenAnswer(invocation -> directionalBlockData(material, facing.get())); - return data; - } - - private static IrisObject readCapturedObject( - byte[] content, - PlatformBlockState restoredState - ) throws Throwable { - PlatformRegistries registries = mock(PlatformRegistries.class); - when(registries.block(anyString())).thenReturn(restoredState); - IrisPlatform platform = mock(IrisPlatform.class); - when(platform.registries()).thenReturn(registries); - IrisPlatforms.unbind(); - IrisPlatforms.bind(platform); - try { - IrisObject restored = new IrisObject(); - restored.read(new ByteArrayInputStream(content)); - return restored; - } finally { - IrisPlatforms.unbind(); - } - } - - private static void assertMutationHandler(String methodName, Class eventType) throws NoSuchMethodException { - assertHandler(methodName, eventType, EventPriority.MONITOR, true); - } - - private static void assertHandler( - String methodName, - Class eventType, - EventPriority priority, - boolean ignoreCancelled - ) throws NoSuchMethodException { - Method method = JigsawStudioService.class.getMethod(methodName, eventType); - EventHandler annotation = method.getAnnotation(EventHandler.class); - assertNotNull(annotation); - assertEquals(priority, annotation.priority()); - assertEquals(ignoreCancelled, annotation.ignoreCancelled()); - } - - private static BlockData blockData(Material material, String state) { - BlockData blockData = mock(BlockData.class); - when(blockData.getMaterial()).thenReturn(material); - when(blockData.getAsString()).thenReturn(state); - return blockData; - } } diff --git a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioToolCodecTest.java b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioToolCodecTest.java index 329dce332..1e5a3771a 100644 --- a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioToolCodecTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioToolCodecTest.java @@ -2,15 +2,13 @@ package art.arcane.iris.core.service; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolAction; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolPayload; - -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.persistence.PersistentDataContainer; -import org.bukkit.persistence.PersistentDataType; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolItem; +import com.volmit.tooling.world.ToolText; import org.junit.Test; +import java.util.List; import java.util.Optional; import java.util.UUID; @@ -18,20 +16,14 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; public class JigsawStudioToolCodecTest { private static final UUID REQUEST = UUID.fromString("77777777-7777-7777-7777-777777777777"); + private static final ResourceId STICK = ResourceId.parse("minecraft:stick"); @Test - public void bindsACompleteNamedStickPayload() { + public void createsACompleteNamedStickWithLore() { JigsawStudioToolCodec codec = new JigsawStudioToolCodec(); - ItemStack tool = mock(ItemStack.class); - ItemMeta meta = mock(ItemMeta.class); - PersistentDataContainer data = mock(PersistentDataContainer.class); JigsawStudioToolPayload payload = JigsawStudioToolPayload.membership( JigsawStudioToolAction.ADJUST_VARIANT_WEIGHT, REQUEST, @@ -40,57 +32,56 @@ public class JigsawStudioToolCodecTest { "village/start", 3, -1); - when(tool.getType()).thenReturn(Material.STICK); - when(tool.getItemMeta()).thenReturn(meta); - when(tool.setItemMeta(meta)).thenReturn(true); - when(meta.getPersistentDataContainer()).thenReturn(data); - codec.bind(tool, payload); + ToolItem tool = codec.create(payload); - verify(data).set( - JigsawStudioToolCodec.SCHEMA_KEY, - PersistentDataType.INTEGER, - JigsawStudioToolPayload.CURRENT_SCHEMA_VERSION); - verify(data).set( - JigsawStudioToolCodec.ACTION_KEY, - PersistentDataType.STRING, - JigsawStudioToolAction.ADJUST_VARIANT_WEIGHT.name()); - verify(data).set( - JigsawStudioToolCodec.REQUEST_KEY, - PersistentDataType.STRING, - REQUEST.toString()); - verify(data).set( - JigsawStudioToolCodec.WORKCELL_KEY, - PersistentDataType.STRING, - "workcell/corner"); - verify(data).set( - JigsawStudioToolCodec.PIECE_KEY, - PersistentDataType.STRING, - "village/corner_mossy"); - verify(data).set( - JigsawStudioToolCodec.POOL_KEY, - PersistentDataType.STRING, - "village/start"); - verify(data).set(JigsawStudioToolCodec.ENTRY_INDEX_KEY, PersistentDataType.INTEGER, 3); - verify(data).set(JigsawStudioToolCodec.AMOUNT_KEY, PersistentDataType.INTEGER, -1); - verify(meta).setDisplayName(ChatColor.AQUA + "Jigsaw Studio: Adjust Variant Weight"); - verify(meta).setLore(argThat(lore -> lore.contains(ChatColor.GRAY + "Amount: -1") - && lore.contains(ChatColor.YELLOW + "Right-click to use"))); - verify(tool).setItemMeta(meta); + assertEquals(STICK, tool.item()); + assertEquals(ToolText.colored(TextColor.AQUA, "Jigsaw Studio: Adjust Variant Weight"), tool.name()); + assertEquals(List.of( + ToolText.colored(TextColor.GRAY, "Workcell: workcell/corner"), + ToolText.colored(TextColor.GRAY, "Variant: village/corner_mossy"), + ToolText.colored(TextColor.GRAY, "Pool: village/start [3]"), + ToolText.colored(TextColor.GRAY, "Amount: -1"), + ToolText.colored(TextColor.YELLOW, "Right-click to use")), tool.lore()); + assertFalse(tool.glowing()); + } + + @Test + public void aDestructiveToolAsksForConfirmationInRed() { + JigsawStudioToolCodec codec = new JigsawStudioToolCodec(); + + ToolItem tool = codec.create(JigsawStudioToolPayload.request(JigsawStudioToolAction.DELETE_PROJECT, REQUEST)); + + assertEquals(ToolText.colored(TextColor.RED, "Right-click twice to confirm"), tool.lore().getLast()); + } + + @Test + public void everyPayloadRoundTripsThroughTheItem() { + JigsawStudioToolCodec codec = new JigsawStudioToolCodec(); + List payloads = List.of( + JigsawStudioToolPayload.request(JigsawStudioToolAction.PREVIEW_GRAPH, REQUEST), + JigsawStudioToolPayload.workcell(JigsawStudioToolAction.SELECT_WORKCELL, REQUEST, "workcell/end"), + JigsawStudioToolPayload.membership( + JigsawStudioToolAction.ADJUST_VARIANT_WEIGHT, + REQUEST, + "workcell/corner", + "village/corner_mossy", + "village/start", + 3, + -1)); + + for (JigsawStudioToolPayload payload : payloads) { + assertEquals(payload, codec.decode(codec.create(payload)).orElseThrow()); + } } @Test public void decodesCurrentSchemaAndDefaultsOptionalFields() { JigsawStudioToolCodec codec = new JigsawStudioToolCodec(); - PersistentDataContainer data = mock(PersistentDataContainer.class); - when(data.get(JigsawStudioToolCodec.SCHEMA_KEY, PersistentDataType.INTEGER)) - .thenReturn(JigsawStudioToolPayload.CURRENT_SCHEMA_VERSION); - when(data.get(JigsawStudioToolCodec.ACTION_KEY, PersistentDataType.STRING)) - .thenReturn(JigsawStudioToolAction.PREVIEW_GRAPH.name()); - when(data.get(JigsawStudioToolCodec.REQUEST_KEY, PersistentDataType.STRING)) - .thenReturn(REQUEST.toString()); + String payload = "{\"schema\":" + JigsawStudioToolPayload.CURRENT_SCHEMA_VERSION + + ",\"action\":\"PREVIEW_GRAPH\",\"request\":\"" + REQUEST + "\"}"; - Optional decoded = codec.decode(data); + Optional decoded = codec.decode(payload); assertTrue(decoded.isPresent()); assertEquals( @@ -102,49 +93,52 @@ public class JigsawStudioToolCodecTest { public void schemaTwoInvalidatesLegacyBoundTools() { assertEquals(2, JigsawStudioToolPayload.CURRENT_SCHEMA_VERSION); JigsawStudioToolCodec codec = new JigsawStudioToolCodec(); - PersistentDataContainer legacy = mock(PersistentDataContainer.class); - when(legacy.get(JigsawStudioToolCodec.SCHEMA_KEY, PersistentDataType.INTEGER)).thenReturn(1); - when(legacy.get(JigsawStudioToolCodec.ACTION_KEY, PersistentDataType.STRING)) - .thenReturn(JigsawStudioToolAction.DUPLICATE_VARIANT.name()); - when(legacy.get(JigsawStudioToolCodec.REQUEST_KEY, PersistentDataType.STRING)) - .thenReturn(REQUEST.toString()); + String legacy = "{\"schema\":1,\"action\":\"DUPLICATE_VARIANT\",\"request\":\"" + REQUEST + "\"}"; assertTrue(codec.decode(legacy).isEmpty()); } @Test - public void rejectsMalformedOrUnsupportedPersistentBindings() { + public void rejectsMalformedOrUnsupportedPayloads() { JigsawStudioToolCodec codec = new JigsawStudioToolCodec(); - PersistentDataContainer unsupported = mock(PersistentDataContainer.class); - when(unsupported.get(JigsawStudioToolCodec.SCHEMA_KEY, PersistentDataType.INTEGER)).thenReturn(99); - when(unsupported.get(JigsawStudioToolCodec.ACTION_KEY, PersistentDataType.STRING)) - .thenReturn(JigsawStudioToolAction.SELECT_WORKCELL.name()); - when(unsupported.get(JigsawStudioToolCodec.REQUEST_KEY, PersistentDataType.STRING)) - .thenReturn(REQUEST.toString()); - assertTrue(codec.decode(unsupported).isEmpty()); + String unsupported = "{\"schema\":99,\"action\":\"SELECT_WORKCELL\",\"request\":\"" + REQUEST + "\"}"; + String malformed = "{\"schema\":" + JigsawStudioToolPayload.CURRENT_SCHEMA_VERSION + + ",\"action\":\"NOT_AN_ACTION\",\"request\":\"not-a-uuid\"}"; - PersistentDataContainer malformed = mock(PersistentDataContainer.class); - when(malformed.get(JigsawStudioToolCodec.SCHEMA_KEY, PersistentDataType.INTEGER)) - .thenReturn(JigsawStudioToolPayload.CURRENT_SCHEMA_VERSION); - when(malformed.get(JigsawStudioToolCodec.ACTION_KEY, PersistentDataType.STRING)) - .thenReturn("NOT_AN_ACTION"); - when(malformed.get(JigsawStudioToolCodec.REQUEST_KEY, PersistentDataType.STRING)) - .thenReturn("not-a-uuid"); + assertTrue(codec.decode(unsupported).isEmpty()); assertTrue(codec.decode(malformed).isEmpty()); + assertTrue(codec.decode("not json").isEmpty()); + assertTrue(codec.decode("").isEmpty()); } @Test public void recognizesOnlyValidStickBindings() { JigsawStudioToolCodec codec = new JigsawStudioToolCodec(); - ItemStack stone = mock(ItemStack.class); - when(stone.getType()).thenReturn(Material.STONE); + JigsawStudioToolPayload payload = JigsawStudioToolPayload.request(JigsawStudioToolAction.PREVIEW_GRAPH, REQUEST); + ToolItem tool = codec.create(payload); + ToolItem stone = new ToolItem(ResourceId.parse("minecraft:stone"), tool.name(), tool.lore(), false, tool.payload()); + ToolItem plainStick = new ToolItem(STICK, ToolText.plain("Stick"), List.of(), false, ""); + assertTrue(codec.isTool(tool)); assertFalse(codec.isTool(stone)); - assertThrows( - IllegalArgumentException.class, - () -> codec.bind( - stone, - JigsawStudioToolPayload.request(JigsawStudioToolAction.PREVIEW_GRAPH, REQUEST))); + assertFalse(codec.isTool(plainStick)); + assertFalse(codec.isTool(null)); + } + + @Test + public void refusesToCreateAToolOfAnOldSchema() { + JigsawStudioToolCodec codec = new JigsawStudioToolCodec(); + JigsawStudioToolPayload old = new JigsawStudioToolPayload( + 1, + JigsawStudioToolAction.PREVIEW_GRAPH, + REQUEST, + "", + "", + "", + JigsawStudioToolPayload.NO_ENTRY_INDEX, + 0); + + assertThrows(IllegalArgumentException.class, () -> codec.create(old)); } @Test diff --git a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioWorldListenerTest.java b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioWorldListenerTest.java new file mode 100644 index 000000000..8eb310c15 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioWorldListenerTest.java @@ -0,0 +1,368 @@ +package art.arcane.iris.core.service; + +import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarTopology; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBay; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioControlPosition; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioPieceRules; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioSession; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariant; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariantCatalog; +import art.arcane.iris.engine.platform.studio.generators.JigsawStudioGenerator; +import com.volmit.ModuleLog; +import com.volmit.block.BlockState; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolAction; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolPayload; +import com.volmit.geometry.BlockPosition; +import com.volmit.geometry.ChunkPos; +import com.volmit.tooling.world.ToolText; +import com.volmit.tooling.world.BlockChange; +import com.volmit.tooling.world.BlockChange.Cause; +import com.volmit.tooling.world.ToolWorldListener; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.lang.reflect.Field; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicLong; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** What a studio world's listener decides for each cause of a block change, in a bay that is editable and in ones that are not. */ +public class JigsawStudioWorldListenerTest { + private static final UUID OWNER = UUID.fromString("11111111-1111-1111-1111-111111111111"); + private static final UUID OTHER = UUID.fromString("22222222-2222-2222-2222-222222222222"); + private static final Set PLAYER_EDIT_CAUSES = EnumSet.of(Cause.PLACE, Cause.BREAK, Cause.BUCKET); + private static final Set WORLD_CAUSES = EnumSet.complementOf( + EnumSet.of(Cause.PLACE, Cause.BREAK, Cause.BUCKET, Cause.CONTAINER, Cause.MACHINE)); + private static final String EDITABLE_BAY = "workcell/end"; + private static final String SECOND_EDITABLE_BAY = "workcell/straight"; + private static final String EMPTY_BAY = "workcell/blank"; + + private final JigsawStudioService service = new JigsawStudioService(mock(ModuleLog.class)); + private final FakeToolWorld world = new FakeToolWorld("jigsaw"); + private final FakeToolPlayer owner = new FakeToolPlayer(OWNER, "owner", world); + private final FakeToolPlayer other = new FakeToolPlayer(OTHER, "other", world); + private JigsawStudioLayout layout; + private JigsawStudioSession session; + private JigsawStudioService.ActiveStudio studio; + private UUID requestId; + private ToolWorldListener listener; + + @Before + public void openStudio() throws ReflectiveOperationException { + JigsawStudioCellDimensions dimensions = new JigsawStudioCellDimensions(16, 16, 16); + layout = JigsawStudioLayout.create( + JigsawStudioMode.PLANAR_JIGSAW, + dimensions, + new JigsawStudioVariantCatalog(List.of( + ownedVariant("test/end", JigsawPlanarTopology.NORTH_END), + ownedVariant("test/straight", JigsawPlanarTopology.NORTH_SOUTH_STRAIGHT)))); + assertTrue(service.registry().tryBeginOpen(OWNER)); + JigsawStudioRequest request = service.registry().activate( + "overworld", + "village", + JigsawStudioMode.PLANAR_JIGSAW, + JigsawStudioCompatibilityTarget.IRIS_EXTENDED, + dimensions, + StudioToolPacks.toolPack(), + layout, + OWNER); + service.registry().finishOpen(OWNER); + session = service.registry().getSession(request.requestId()); + assertTrue(session.activeVariant(EDITABLE_BAY).isPresent()); + assertTrue(session.activeVariant(EMPTY_BAY).isEmpty()); + JigsawStudioGenerator generator = mock(JigsawStudioGenerator.class); + when(generator.getRequest()).thenReturn(request); + when(generator.getSession()).thenReturn(session); + when(generator.getLayout()).thenReturn(layout); + when(generator.renderBay(any(JigsawStudioBay.class))).thenReturn( + JigsawStudioGenerator.RenderedBay.empty(dimensions)); + JigsawStudioService.ActiveStudio studio = new JigsawStudioService.ActiveStudio( + request.requestId(), + world, + generator, + new ConcurrentHashMap<>(), + ConcurrentHashMap.newKeySet(), + new AtomicLong()); + Field studiosField = JigsawStudioService.class.getDeclaredField("studios"); + studiosField.setAccessible(true); + @SuppressWarnings("unchecked") + Map studios = + (Map) studiosField.get(service); + studios.put(request.requestId(), studio); + this.studio = studio; + this.requestId = request.requestId(); + listener = new JigsawStudioWorldListener(service, request.requestId()); + } + + @After + public void closeStudio() { + service.registry().deactivate("overworld"); + } + + @Test + public void everyCauseIsAllowedAndMarksTheBayDirtyInAnEditableBay() { + for (Cause cause : Cause.values()) { + assertTrue(cause.name(), listener.blockChanging(change(cause, owner, inside(EDITABLE_BAY)))); + assertTrue(cause.name(), dirty(EDITABLE_BAY)); + clean(EDITABLE_BAY); + } + } + + @Test + public void causesWithoutAPlayerAreAllowedInAnEditableBay() { + for (Cause cause : WORLD_CAUSES) { + assertTrue(cause.name(), listener.blockChanging(change(cause, null, inside(EDITABLE_BAY)))); + } + assertTrue(listener.blockChanging(change(Cause.MACHINE, null, inside(EDITABLE_BAY)))); + } + + @Test + public void everyCauseIsRefusedAndLeavesTheBayCleanInABayWithoutAnEditableVariant() { + for (Cause cause : Cause.values()) { + assertFalse(cause.name(), listener.blockChanging(change(cause, owner, inside(EMPTY_BAY)))); + assertFalse(cause.name(), dirty(EMPTY_BAY)); + } + } + + @Test + public void aPlayerEditInAnUneditableBayTellsThePlayerWhy() { + assertFalse(listener.blockChanging(change(Cause.PLACE, owner, inside(EMPTY_BAY)))); + + assertEquals( + List.of("[Iris Jigsaw Studio] This empty Jigsaw Studio workcell has no loaded editable variant. Load one before editing it."), + owner.messages); + } + + @Test + public void anotherPlayerCannotEditOrOpenContainersInAnEditableBay() { + for (Cause cause : PLAYER_EDIT_CAUSES) { + assertFalse(cause.name(), listener.blockChanging(change(cause, other, inside(EDITABLE_BAY)))); + } + assertFalse(listener.blockChanging(change(Cause.CONTAINER, other, inside(EDITABLE_BAY)))); + assertFalse(dirty(EDITABLE_BAY)); + assertTrue(other.messages.contains("[Iris Jigsaw Studio] This Jigsaw Studio is owned by another player session.")); + assertTrue(other.messages.contains( + "[Iris Jigsaw Studio] This Jigsaw Studio container is read-only during the current operation or owner session.")); + } + + @Test + public void anotherPlayersWorldCausesStillRunInAnEditableBay() { + for (Cause cause : WORLD_CAUSES) { + assertTrue(cause.name(), listener.blockChanging(change(cause, other, inside(EDITABLE_BAY)))); + } + } + + @Test + public void outsideEveryBayThePlayersEditsAndTheWorldAreLeftAlone() { + BlockPosition outside = new BlockPosition(100_000, 64, 100_000); + for (Cause cause : Cause.values()) { + assertTrue(cause.name(), listener.blockChanging(change(cause, owner, outside))); + } + assertFalse(dirty(EDITABLE_BAY)); + assertFalse(dirty(SECOND_EDITABLE_BAY)); + } + + @Test + public void theControlChestCannotBeRemovedOrChangedByTheWorld() { + JigsawStudioControlPosition control = layout.controlPosition(); + BlockPosition chest = new BlockPosition(control.worldX(), control.worldY(), control.worldZ()); + world.setBlock(chest, BlockState.parse("minecraft:chest[facing=south]"), Optional.empty()); + + assertFalse(listener.blockChanging(change(Cause.BREAK, owner, chest))); + assertEquals( + List.of("[Iris Jigsaw Studio] The Jigsaw Studio control chest cannot be removed."), + owner.messages); + for (Cause cause : WORLD_CAUSES) { + assertFalse(cause.name(), listener.blockChanging(change(cause, null, chest))); + } + assertFalse(listener.blockChanging(change(Cause.MACHINE, null, chest))); + assertFalse(listener.blockChanging(change(Cause.CONTAINER, owner, chest))); + } + + @Test + public void aPistonIsCheckedAgainstItsPositionsAndMarksTheBlocksItChanged() { + BlockPosition end = inside(EDITABLE_BAY); + BlockPosition straight = inside(SECOND_EDITABLE_BAY); + BlockChange change = new BlockChange( + Cause.PISTON, List.of(end), List.of(straight), Optional.empty(), Optional.empty()); + + assertTrue(listener.blockChanging(change)); + + assertFalse(dirty(EDITABLE_BAY)); + assertTrue(dirty(SECOND_EDITABLE_BAY)); + } + + @Test + public void aPistonThatMovesNothingIsAllowedAndMarksItsOwnBlocks() { + BlockChange change = new BlockChange( + Cause.PISTON, List.of(), List.of(inside(EDITABLE_BAY)), Optional.empty(), Optional.empty()); + + assertTrue(listener.blockChanging(change)); + + assertTrue(dirty(EDITABLE_BAY)); + } + + @Test + public void aPistonCheckedAgainstAnUneditableBayIsRefusedWhateverItChanged() { + BlockChange change = new BlockChange( + Cause.PISTON, List.of(inside(EMPTY_BAY)), List.of(inside(EDITABLE_BAY)), Optional.empty(), Optional.empty()); + + assertFalse(listener.blockChanging(change)); + + assertFalse(dirty(EDITABLE_BAY)); + } + + @Test + public void aContainerThatChangedMarksItsBayDirtyAndOneOutsideAnyBayDoesNot() { + listener.containerChanged(Optional.of(owner), inside(EDITABLE_BAY)); + listener.containerChanged(Optional.empty(), new BlockPosition(100_000, 64, 100_000)); + listener.containerChanged(Optional.empty(), inside(EMPTY_BAY)); + + assertTrue(dirty(EDITABLE_BAY)); + assertFalse(dirty(SECOND_EDITABLE_BAY)); + assertFalse(dirty(EMPTY_BAY)); + } + + @Test + public void aTeleportMakesTheStudioReconcileTheArrivalAtOnceAndEnteringAloneDoesNot() { + listener.entered(owner); + assertTrue(owner.sidebars.isEmpty()); + + listener.teleported(owner, inside(EDITABLE_BAY)); + + assertFalse(owner.sidebars.isEmpty()); + assertTrue(owner.sidebars.getLast().stream() + .map(ToolText::plainText).anyMatch(line -> line.startsWith("Workcell: "))); + } + + @Test + public void aChunkIsLoadedWhenThePlatformSaysSo() { + world.unloadedChunks.add(new ChunkPos(3, 4)); + + assertTrue(studio.isChunkLoaded(0, 0)); + assertFalse(studio.isChunkLoaded(3, 4)); + } + + @Test + public void aToolIsNotGivenWhenTheInventoryIsFullAndThePlayerIsToldSo() { + JigsawStudioToolPayload payload = JigsawStudioToolPayload.request(JigsawStudioToolAction.PREVIEW_GRAPH, requestId); + owner.inventoryFull = true; + + assertFalse(service.giveTool(owner, payload)); + + assertTrue(owner.given.isEmpty()); + assertEquals( + List.of("[Iris Jigsaw Studio] Your inventory is full; no Jigsaw Studio tool was added."), + owner.messages); + } + + @Test + public void aToolThatFitsIsGivenAndAnnounced() { + JigsawStudioToolPayload payload = JigsawStudioToolPayload.request(JigsawStudioToolAction.PREVIEW_GRAPH, requestId); + + assertTrue(service.giveTool(owner, payload)); + + assertEquals(1, owner.given.size()); + assertEquals( + List.of("[Iris Jigsaw Studio] Added " + JigsawStudioToolAction.PREVIEW_GRAPH.displayName() + " tool."), + owner.messages); + } + + @Test + public void studioMessagesAreWhiteTextWithTheStudioPrefix() { + assertFalse(listener.blockChanging(change(Cause.PLACE, owner, inside(EMPTY_BAY)))); + + assertEquals( + List.of(ToolText.plain("[Iris Jigsaw Studio] This empty Jigsaw Studio workcell has no loaded editable variant. Load one before editing it.")), + owner.texts); + } + + @Test + public void aMultiBlockChangeMarksTheBaysItTouchesByItsCause() { + BlockPosition end = inside(EDITABLE_BAY); + BlockPosition straight = inside(SECOND_EDITABLE_BAY); + + assertTrue(listener.blockChanging(change(Cause.PHYSICS, null, end, straight))); + assertTrue(dirty(EDITABLE_BAY)); + assertFalse(dirty(SECOND_EDITABLE_BAY)); + clean(EDITABLE_BAY); + + assertTrue(listener.blockChanging(change(Cause.FLUID, null, end, straight))); + assertFalse(dirty(EDITABLE_BAY)); + assertTrue(dirty(SECOND_EDITABLE_BAY)); + clean(SECOND_EDITABLE_BAY); + + assertTrue(listener.blockChanging(change(Cause.PISTON, null, end, straight))); + assertTrue(dirty(EDITABLE_BAY)); + assertTrue(dirty(SECOND_EDITABLE_BAY)); + } + + @Test + public void aChangeThatTouchesAnUneditableBayIsRefusedAsAWhole() { + assertFalse(listener.blockChanging(change( + Cause.EXPLOSION, null, inside(EDITABLE_BAY), inside(EMPTY_BAY)))); + assertFalse(dirty(EDITABLE_BAY)); + } + + @Test + public void aStudioThatIsNotOpenFreezesItsWorld() { + ToolWorldListener stranger = new JigsawStudioWorldListener(service, UUID.randomUUID()); + + for (Cause cause : Cause.values()) { + assertFalse(cause.name(), stranger.blockChanging(change(cause, owner, inside(EDITABLE_BAY)))); + } + } + + private BlockChange change(Cause cause, FakeToolPlayer player, BlockPosition... positions) { + return new BlockChange(cause, List.of(positions), Optional.ofNullable(player), Optional.empty()); + } + + private BlockPosition inside(String bayId) { + JigsawStudioBay bay = layout.get(bayId); + return new BlockPosition( + bay.bounds().originX() + 1, + bay.bounds().originY() + 1, + bay.bounds().originZ() + 1); + } + + private boolean dirty(String bayId) { + return session.workcellSnapshot(bayId).dirty(); + } + + private void clean(String bayId) { + JigsawStudioSession.SaveIdentity save = session.beginSave(bayId).identity().orElseThrow(); + assertTrue(session.markWorkcellSaved(save)); + } + + private static JigsawStudioVariant ownedVariant(String key, JigsawPlanarTopology topology) { + return new JigsawStudioVariant( + key, + key, + "", + Optional.of(new JigsawStudioCellDimensions(16, 16, 16)), + JigsawStudioMode.PLANAR_JIGSAW, + Optional.of(topology), + true, + true, + List.of(), + new JigsawStudioPieceRules(0, 30, 0, 0, false), + List.of()); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/service/StudioSVCJigsawProtectionTest.java b/core/src/test/java/art/arcane/iris/core/service/StudioSVCJigsawProtectionTest.java index 6396de9ae..4505dc83b 100644 --- a/core/src/test/java/art/arcane/iris/core/service/StudioSVCJigsawProtectionTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/StudioSVCJigsawProtectionTest.java @@ -1,34 +1,36 @@ package art.arcane.iris.core.service; -import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.project.IrisProject; import art.arcane.iris.core.runtime.StudioOpenCoordinator; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioActivation; +import art.arcane.iris.core.runtime.StudioSlotOccupant; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariantCatalog; -import art.arcane.iris.platform.bukkit.BukkitPlatform; -import art.arcane.iris.util.common.plugin.VolmitPlugin; +import art.arcane.iris.engine.platform.PlatformChunkGenerator; import art.arcane.iris.util.common.plugin.VolmitSender; +import com.volmit.ModuleLog; +import org.bukkit.entity.Player; import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.mockito.MockedStatic; -import org.bukkit.entity.Player; +import java.io.File; import java.lang.reflect.Field; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; +import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -37,47 +39,37 @@ public class StudioSVCJigsawProtectionTest { private static final UUID OWNER = UUID.fromString("33333333-3333-3333-3333-333333333333"); private JigsawStudioService jigsawService; - private MockedStatic bukkitPlatform; @Before - public void enableJigsawService() { - VolmitPlugin plugin = mock(VolmitPlugin.class); - bukkitPlatform = mockStatic(BukkitPlatform.class); - bukkitPlatform.when(BukkitPlatform::volmitPlugin).thenReturn(plugin); - jigsawService = new JigsawStudioService(); - jigsawService.onEnable(); + public void startJigsawService() { + jigsawService = new JigsawStudioService(mock(ModuleLog.class)); } @After public void clearLifecycle() { - jigsawService.onDisable(); - JigsawStudioActivation.finishOpen(OWNER); - JigsawStudioActivation.deactivate("overworld"); - bukkitPlatform.close(); + jigsawService.registry().finishOpen(OWNER); + jigsawService.registry().deactivate("overworld"); } @Test - public void directStudioCloseRequiresJigsawCloseAuthorization() throws ReflectiveOperationException { - JigsawStudioActivation.Request request = activateOwnedStudio(); - IrisProject project = mock(IrisProject.class); - when(project.getName()).thenReturn("overworld"); + public void directStudioCloseRequiresJigsawCloseAuthorization() { + JigsawStudioRequest request = activateOwnedStudio(); + AtomicBoolean closed = new AtomicBoolean(); + StudioSlotOccupant occupant = occupantOf(request, closed); StudioSVC studio = new StudioSVC(); - setActiveProject(studio, project); + studio.occupyStudioSlot(occupant, () -> CompletableFuture.completedFuture(null)).join(); CompletionException blocked = assertThrows(CompletionException.class, () -> studio.close().join()); assertTrue(blocked.getCause().getMessage().contains("owner-controlled")); - verify(project, never()).close(); + assertFalse(closed.get()); assertEquals( JigsawStudioService.CloseStart.STARTED, jigsawService.tryBeginClose(request.requestId(), OWNER, false)); - StudioOpenCoordinator.StudioCloseResult closeResult = successfulClose(); - when(project.close()).thenReturn(CompletableFuture.completedFuture(closeResult)); - assertEquals(closeResult, studio.close().join()); - assertNull(studio.getActiveProject()); - verify(project).close(); + assertTrue(studio.close().join().successful()); + assertTrue(closed.get()); } @Test @@ -95,41 +87,101 @@ public class StudioSVCJigsawProtectionTest { } @Test - public void ownerCanReplaceJigsawStudioThroughOrdinaryStudioOpen() throws ReflectiveOperationException { - activateOwnedStudio(); - IrisProject project = mock(IrisProject.class); - when(project.getName()).thenReturn("overworld"); - StudioOpenCoordinator.StudioCloseResult closeResult = successfulClose(); - when(project.close()).thenReturn(CompletableFuture.completedFuture(closeResult)); + public void anOpenJigsawStudioIsTheOpenStudioProjectToEveryoneWhoAsks() { + JigsawStudioRequest request = activateOwnedStudio(); + AtomicBoolean closed = new AtomicBoolean(); + StudioSVC studio = new StudioSVC(); + StudioSlotOccupant occupant = occupantOf(request, closed); + studio.occupyStudioSlot(occupant, () -> CompletableFuture.completedFuture(null)).join(); + + assertFalse(studio.isProjectOpen()); + occupant.project().setActiveProvider(mock(PlatformChunkGenerator.class)); + assertTrue(studio.isProjectOpen()); + assertSame(occupant.project(), studio.getActiveProject()); + + jigsawService.tryBeginClose(request.requestId(), OWNER, false); + studio.close().join(); + occupant.project().setActiveProvider(null); + assertFalse(studio.isProjectOpen()); + assertNull(studio.getActiveProject()); + } + + @Test + public void ownerCanReplaceJigsawStudioThroughOrdinaryStudioOpen() { + JigsawStudioRequest request = activateOwnedStudio(); + AtomicBoolean closed = new AtomicBoolean(); + StudioSVC studio = new StudioSVC(); + studio.occupyStudioSlot(occupantOf(request, closed), () -> CompletableFuture.completedFuture(null)).join(); Player player = mock(Player.class); when(player.getUniqueId()).thenReturn(OWNER); VolmitSender sender = mock(VolmitSender.class); when(sender.isPlayer()).thenReturn(true); when(sender.player()).thenReturn(player); - StudioSVC studio = new StudioSVC(); - setActiveProject(studio, project); - assertEquals(closeResult, studio.closeActiveProjectForReplacement(sender).join()); - assertNull(studio.getActiveProject()); - verify(project).close(); + assertTrue(studio.closeActiveProjectForReplacement(sender).join().successful()); + assertTrue(closed.get()); } - private static JigsawStudioActivation.Request activateOwnedStudio() { - assertTrue(JigsawStudioActivation.tryBeginOpen(OWNER)); + @Test + public void aStudioThatRefusesToCloseKeepsTheSlotAndNeverClosesTheProject() throws ReflectiveOperationException { + JigsawStudioRequest request = activateOwnedStudio(); + AtomicBoolean closed = new AtomicBoolean(); + StudioSVC studio = new StudioSVC(); + studio.occupyStudioSlot(occupantOf(request, closed), () -> CompletableFuture.completedFuture(null)).join(); + IrisProject project = mock(IrisProject.class); + setActiveProject(studio, project); + + assertThrows(CompletionException.class, () -> studio.close().join()); + + verify(project, never()).close(); + assertFalse(closed.get()); + } + + /** The occupant the Bukkit host makes of a tool world: it asks the studio and closes the world. */ + private StudioSlotOccupant occupantOf(JigsawStudioRequest request, AtomicBoolean closed) { + IrisProject project = new IrisProject(new File("overworld")); + return new StudioSlotOccupant() { + @Override + public IrisProject project() { + return project; + } + + @Override + public Optional closeRefusal() { + return jigsawService.closeRefusal(request.requestId()); + } + + @Override + public CompletableFuture prepareReplacement(Optional requestedBy) { + return jigsawService.closing(request.requestId(), requestedBy.map(id -> + new FakeToolPlayer(id, "owner", new FakeToolWorld("jigsaw")))); + } + + @Override + public CompletableFuture close() { + closed.set(true); + return CompletableFuture.completedFuture(null); + } + }; + } + + private JigsawStudioRequest activateOwnedStudio() { + JigsawStudioRegistry registry = jigsawService.registry(); + assertTrue(registry.tryBeginOpen(OWNER)); JigsawStudioCellDimensions dimensions = new JigsawStudioCellDimensions(16, 16, 16); - JigsawStudioActivation.Request request = JigsawStudioActivation.activate( + JigsawStudioRequest request = registry.activate( "overworld", "stronghold", JigsawStudioMode.SPATIAL_JIGSAW, JigsawStudioCompatibilityTarget.IRIS_EXTENDED, dimensions, - mock(IrisData.class), - JigsawStudioLayout.create( - JigsawStudioMode.SPATIAL_JIGSAW, - dimensions, - JigsawStudioVariantCatalog.empty()), + StudioToolPacks.toolPack(), + JigsawStudioLayout.create( + JigsawStudioMode.SPATIAL_JIGSAW, + dimensions, + JigsawStudioVariantCatalog.empty()), OWNER); - JigsawStudioActivation.finishOpen(OWNER); + registry.finishOpen(OWNER); return request; } diff --git a/core/src/test/java/art/arcane/iris/core/service/StudioToolPacks.java b/core/src/test/java/art/arcane/iris/core/service/StudioToolPacks.java new file mode 100644 index 000000000..aaff3ab56 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/service/StudioToolPacks.java @@ -0,0 +1,36 @@ +package art.arcane.iris.core.service; + +import com.volmit.resource.PackResources; +import com.volmit.tooling.PackEdit; +import com.volmit.tooling.ToolPack; + +import java.nio.file.Path; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** A pack of tool tests that runs every edit on the folder {@code pack}. */ +public final class StudioToolPacks { + private static final Path PACK_FOLDER = Path.of("pack"); + + private StudioToolPacks() { + } + + public static ToolPack toolPack(PackResources resources) { + ToolPack pack = toolPack(); + when(pack.resources()).thenReturn(resources); + return pack; + } + + @SuppressWarnings("unchecked") + public static ToolPack toolPack() { + ToolPack pack = mock(ToolPack.class); + try { + when(pack.edit(any(PackEdit.class))).thenAnswer(invocation -> ((PackEdit) invocation.getArgument(0)).apply(PACK_FOLDER)); + } catch (java.io.IOException impossible) { + throw new IllegalStateException(impossible); + } + return pack; + } +} diff --git a/core/src/test/java/art/arcane/iris/core/service/TextObjectCodec.java b/core/src/test/java/art/arcane/iris/core/service/TextObjectCodec.java new file mode 100644 index 000000000..0f7449584 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/service/TextObjectCodec.java @@ -0,0 +1,74 @@ +package art.arcane.iris.core.service; + +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockBox; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import com.volmit.object.GeneratedObject; +import com.volmit.object.ObjectBlock; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.ObjectCodec; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Optional; + +/** An object codec that writes an object as readable lines, in the order the object keeps its blocks. */ +final class TextObjectCodec implements ObjectCodec { + private static final String NO_BLOCK_ENTITY = "-"; + + @Override + public String extension() { + return ".txt"; + } + + @Override + public byte[] encode(GeneratedObject object) { + BlockBox bounds = object.bounds(); + StringBuilder text = new StringBuilder(); + text.append(bounds.minX()).append(' ').append(bounds.minY()).append(' ').append(bounds.minZ()).append(' ') + .append(bounds.maxX()).append(' ').append(bounds.maxY()).append(' ').append(bounds.maxZ()).append('\n'); + for (ObjectBlock block : object.blocks()) { + text.append(block.position().x()).append(' ') + .append(block.position().y()).append(' ') + .append(block.position().z()).append(' ') + .append(block.state().key()).append(' ') + .append(block.blockEntity().map(TextObjectCodec::describe).orElse(NO_BLOCK_ENTITY)) + .append('\n'); + } + return text.toString().getBytes(StandardCharsets.UTF_8); + } + + @Override + public GeneratedObject decode(byte[] bytes) throws IOException { + String[] lines = new String(bytes, StandardCharsets.UTF_8).split("\n"); + String[] bound = lines[0].split(" "); + BlockBox bounds = new BlockBox( + Integer.parseInt(bound[0]), Integer.parseInt(bound[1]), Integer.parseInt(bound[2]), + Integer.parseInt(bound[3]), Integer.parseInt(bound[4]), Integer.parseInt(bound[5])); + List blocks = new ArrayList<>(); + for (int index = 1; index < lines.length; index++) { + String[] parts = lines[index].split(" "); + Optional entity = parts[4].equals(NO_BLOCK_ENTITY) + ? Optional.empty() + : Optional.of(parseEntity(parts[4])); + blocks.add(new ObjectBlock( + new BlockPosition(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]), Integer.parseInt(parts[2])), + BlockState.parse(parts[3]), + entity)); + } + return new GeneratedObject(bounds, new BlockPosition(0, 0, 0), blocks, List.of()); + } + + private static String describe(BlockEntityData entity) { + return entity.format() + "@" + entity.version() + "@" + HexFormat.of().formatHex(entity.payload()); + } + + private static BlockEntityData parseEntity(String description) { + String[] parts = description.split("@"); + return new BlockEntityData(ResourceId.parse(parts[0]), Integer.parseInt(parts[1]), HexFormat.of().parseHex(parts[2])); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/structure/FakePlatformStructures.java b/core/src/test/java/art/arcane/iris/core/structure/FakePlatformStructures.java new file mode 100644 index 000000000..556be69ca --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/structure/FakePlatformStructures.java @@ -0,0 +1,82 @@ +package art.arcane.iris.core.structure; + +import com.volmit.resource.ResourceId; +import com.volmit.tooling.JigsawStructureInfo; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.Sender; +import com.volmit.tooling.StructureTemplate; +import com.volmit.tooling.TemplatePool; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** A platform with exactly the structures, templates and pools a test gives it, and no way to capture. */ +public final class FakePlatformStructures implements PlatformStructures { + private final List structures = new ArrayList<>(); + private final List structureSets = new ArrayList<>(); + private final Map templates = new LinkedHashMap<>(); + private final Map jigsaws = new LinkedHashMap<>(); + private final Map pools = new LinkedHashMap<>(); + + public FakePlatformStructures withStructures(String... keys) { + for (String key : keys) { + structures.add(ResourceId.parse(key)); + } + return this; + } + + public FakePlatformStructures withStructureSets(String... keys) { + for (String key : keys) { + structureSets.add(ResourceId.parse(key)); + } + return this; + } + + public FakePlatformStructures withTemplate(String key, StructureTemplate template) { + templates.put(ResourceId.parse(key), template); + return this; + } + + @Override + public List templates() { + return new ArrayList<>(templates.keySet()); + } + + @Override + public Optional template(ResourceId id) { + return Optional.ofNullable(templates.get(id)); + } + + @Override + public List structures() { + return List.copyOf(structures); + } + + @Override + public List structureSets() { + return List.copyOf(structureSets); + } + + @Override + public Optional jigsaw(ResourceId structure) { + return Optional.ofNullable(jigsaws.get(structure)); + } + + @Override + public Optional pool(ResourceId pool) { + return Optional.ofNullable(pools.get(pool)); + } + + @Override + public boolean supportsCapture() { + return false; + } + + @Override + public Optional openCaptureArea(Sender sender) { + return Optional.empty(); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/structure/StructureImporterCaptureTest.java b/core/src/test/java/art/arcane/iris/core/structure/StructureImporterCaptureTest.java index 4299e4a02..6433727e6 100644 --- a/core/src/test/java/art/arcane/iris/core/structure/StructureImporterCaptureTest.java +++ b/core/src/test/java/art/arcane/iris/core/structure/StructureImporterCaptureTest.java @@ -19,39 +19,40 @@ package art.arcane.iris.core.structure; import art.arcane.iris.core.structure.authoring.StructureCapability; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.BlockState; -import org.bukkit.block.data.BlockData; -import org.bukkit.structure.Palette; -import org.bukkit.structure.Structure; -import org.bukkit.util.BlockVector; +import art.arcane.iris.engine.UsableBlockPlatform; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.tooling.StructureTemplate; +import com.volmit.tooling.TemplateBlock; +import org.junit.After; +import org.junit.Before; import org.junit.Test; import java.util.List; +import java.util.Optional; 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.when; public class StructureImporterCaptureTest { + @Before + public void bindBlocks() { + UsableBlockPlatform.bind(); + } + + @After + public void unbindBlocks() { + UsableBlockPlatform.unbind(); + } + @Test public void captureReturnsAnInMemorySnapshotWithDistinctBlockMarkerLoss() { - Structure structure = mock(Structure.class); - Palette palette = mock(Palette.class); - BlockState marker = mock(BlockState.class); - BlockData markerData = mock(BlockData.class); - Location location = mock(Location.class); - when(structure.getSize()).thenReturn(new BlockVector(2, 3, 4)); - when(structure.getPalettes()).thenReturn(List.of(palette)); - when(structure.getPaletteCount()).thenReturn(2); - when(structure.getEntityCount()).thenReturn(1); - when(palette.getBlocks()).thenReturn(List.of(marker)); - when(marker.getLocation()).thenReturn(location); - when(marker.getBlockData()).thenReturn(markerData); - when(markerData.getMaterial()).thenReturn(Material.STRUCTURE_BLOCK); + StructureTemplate structure = new StructureTemplate( + new BlockPosition(2, 3, 4), + 2, + 1, + List.of(block("minecraft:structure_block", 0))); StructureImporter.CapturedStructure captured = StructureImporter.captureStructure(structure); @@ -71,13 +72,11 @@ public class StructureImporterCaptureTest { @Test public void captureCountsStoredAirSeparatelyFromPhysicalBlocks() { - Structure structure = mock(Structure.class); - Palette palette = mock(Palette.class); - BlockState air = blockState(Material.AIR, "minecraft:air", 0); - BlockState stone = blockState(Material.STONE, "minecraft:stone", 1); - when(structure.getSize()).thenReturn(new BlockVector(2, 1, 1)); - when(structure.getPalettes()).thenReturn(List.of(palette)); - when(palette.getBlocks()).thenReturn(List.of(air, stone)); + StructureTemplate structure = new StructureTemplate( + new BlockPosition(2, 1, 1), + 1, + 0, + List.of(block("minecraft:air", 0), block("minecraft:stone", 1))); StructureImporter.CapturedStructure captured = StructureImporter.captureStructure(structure); @@ -85,15 +84,7 @@ public class StructureImporterCaptureTest { assertEquals(1, captured.nonAirBlocks()); } - private static BlockState blockState(Material material, String state, int x) { - BlockState block = mock(BlockState.class); - BlockData data = mock(BlockData.class); - Location location = mock(Location.class); - when(block.getLocation()).thenReturn(location); - when(block.getBlockData()).thenReturn(data); - when(location.getBlockX()).thenReturn(x); - when(data.getMaterial()).thenReturn(material); - when(data.getAsString()).thenReturn(state); - return block; + private static TemplateBlock block(String state, int x) { + return TemplateBlock.of(new BlockPosition(x, 0, 0), BlockState.parse(state), Optional.empty()); } } diff --git a/core/src/test/java/art/arcane/iris/core/structure/StructureImporterModeTest.java b/core/src/test/java/art/arcane/iris/core/structure/StructureImporterModeTest.java index 198b8ce25..9719bec8e 100644 --- a/core/src/test/java/art/arcane/iris/core/structure/StructureImporterModeTest.java +++ b/core/src/test/java/art/arcane/iris/core/structure/StructureImporterModeTest.java @@ -18,7 +18,7 @@ package art.arcane.iris.core.structure; -import org.bukkit.NamespacedKey; +import com.volmit.resource.ResourceId; import org.junit.Test; import static org.junit.Assert.assertEquals; @@ -62,12 +62,12 @@ public class StructureImporterModeTest { @Test public void deriveNameFromNamespacedKeyJoinsNamespaceAndPath() { - assertEquals("minecraft_village", StructureImporter.deriveName(NamespacedKey.minecraft("village"))); + assertEquals("minecraft_village", StructureImporter.deriveName(ResourceId.parse("minecraft:village"))); } @Test public void deriveNameFromNamespacedKeyNormalizesSlashesInPath() { - NamespacedKey key = NamespacedKey.fromString("nova_structures:temple/large"); + ResourceId key = ResourceId.parse("nova_structures:temple/large"); assertEquals("nova_structures_temple_large", StructureImporter.deriveName(key)); } diff --git a/core/src/test/java/art/arcane/iris/core/structure/VillageImporterConnectorRoundTripTest.java b/core/src/test/java/art/arcane/iris/core/structure/VillageImporterConnectorRoundTripTest.java index 925db0852..ebf643a2d 100644 --- a/core/src/test/java/art/arcane/iris/core/structure/VillageImporterConnectorRoundTripTest.java +++ b/core/src/test/java/art/arcane/iris/core/structure/VillageImporterConnectorRoundTripTest.java @@ -12,13 +12,18 @@ 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 art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.core.structure.export.ObjectContents; +import art.arcane.iris.engine.framework.structure.ObjectFrame; import art.arcane.iris.engine.object.structure.IrisStructure; -import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.block.BlockState; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.nbt.io.NBTUtil; import art.arcane.volmlib.util.nbt.tag.CompoundTag; import com.google.gson.Gson; +import com.volmit.geometry.BlockFace; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.TemplatePool; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -31,8 +36,6 @@ 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.when; public class VillageImporterConnectorRoundTripTest { private static final String FINAL_STATE = @@ -43,22 +46,19 @@ public class VillageImporterConnectorRoundTripTest { @Test public void vanillaNbtMetadataSurvivesIrisPieceAndVanillaExport() throws Exception { - FakeJigsawBlockInfo jigsaw = new FakeJigsawBlockInfo(-29, -17); - FakeStructureBlockInfo info = new FakeStructureBlockInfo(new FakeCompoundTag(FINAL_STATE)); - VillageImporter.ConnectorMetadata metadata = VillageImporter.readConnectorMetadata(jigsaw, info); - Map importedConnector = VillageImporter.connectorJson( - 1, - 1, - 0, - "north", - "up", - "minecraft:terminal", - "roundtrip", + TemplatePool.JigsawConnector jigsaw = new TemplatePool.JigsawConnector( + new BlockPosition(1, 1, 0), + BlockFace.NORTH, + BlockFace.UP, + Optional.of(ResourceId.parse("minecraft:terminal")), "minecraft:source", "minecraft:door", - "ALIGNED", - metadata + true, + Optional.of(FINAL_STATE), + -17, + -29 ); + Map importedConnector = VillageImporter.connectorJson(jigsaw, "roundtrip"); Map importedPiece = new LinkedHashMap<>(); importedPiece.put("object", "objects/start"); @@ -76,7 +76,8 @@ public class VillageImporterConnectorRoundTripTest { VanillaJigsawExportSource source = VanillaJigsawExportSource.forStructure( "metadata", graph.structure, - graph + graph, + graph.objects::get ); VanillaJigsawExportResult result = new VanillaJigsawDatapackExporter().export( VanillaJigsawExportRequest.builder(source, output) @@ -97,11 +98,8 @@ public class VillageImporterConnectorRoundTripTest { private static TestGraph graph(IrisJigsawPiece piece, IrisJigsawConnector connector) { TestGraph graph = new TestGraph(); - IrisObject object = new IrisObject(3, 3, 3); - PlatformBlockState finalState = mock(PlatformBlockState.class); - when(finalState.key()).thenReturn(connector.getFinalState()); - object.setUnsigned(1, 1, 0, finalState); - graph.objects.put("objects/start", object); + graph.objects.put("objects/start", ObjectContents.plain(3, 3, 3, + Map.of(new BlockPosition(1, 1, 0), BlockState.parse(connector.getFinalState())), Map.of())); graph.pieces.put("pieces/start", piece); graph.pools.put("pools/start", new IrisJigsawPool().setPieces(new KList<>( new IrisJigsawPieceEntry("pieces/start", 1) @@ -116,26 +114,13 @@ public class VillageImporterConnectorRoundTripTest { .setBranchFailurePolicy(IrisJigsawBranchFailurePolicy.TERMINATE_BRANCH) .setCompatibility(IrisJigsawCompatibility.VANILLA_PORTABLE) .setPlaceMode(ObjectPlaceMode.STRUCTURE_PIECE); - graph.structure.setLoadKey("metadata"); return graph; } - private record FakeJigsawBlockInfo(int placementPriority, int selectionPriority) { - } - - private record FakeStructureBlockInfo(FakeCompoundTag nbt) { - } - - private record FakeCompoundTag(String finalState) { - public Optional getString(String key) { - return "final_state".equals(key) ? Optional.of(finalState) : Optional.empty(); - } - } - private static final class TestGraph implements StructureGraphResolver { private final Map pools = new LinkedHashMap<>(); private final Map pieces = new LinkedHashMap<>(); - private final Map objects = new LinkedHashMap<>(); + private final Map objects = new LinkedHashMap<>(); private IrisStructure structure; @Override @@ -149,8 +134,9 @@ public class VillageImporterConnectorRoundTripTest { } @Override - public IrisObject loadObject(String key) { - return objects.get(key); + public ObjectFrame loadObject(String key) { + ObjectContents contents = objects.get(key); + return contents == null ? null : new ObjectFrame(contents.width(), contents.height(), contents.depth()); } } } diff --git a/core/src/test/java/art/arcane/iris/core/structure/VillageImporterListPoolElementTest.java b/core/src/test/java/art/arcane/iris/core/structure/VillageImporterListPoolElementTest.java index 61879d7a2..4534c5bb8 100644 --- a/core/src/test/java/art/arcane/iris/core/structure/VillageImporterListPoolElementTest.java +++ b/core/src/test/java/art/arcane/iris/core/structure/VillageImporterListPoolElementTest.java @@ -20,7 +20,6 @@ package art.arcane.iris.core.structure; import art.arcane.iris.core.structure.authoring.StructureCapability; import art.arcane.iris.core.structure.authoring.StructureLoss; -import art.arcane.iris.engine.object.prefab.IrisObject; import org.junit.Test; import java.util.List; @@ -28,93 +27,17 @@ import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; public class VillageImporterListPoolElementTest { - @Test - public void plainTemplateElementRemainsUnchanged() throws Exception { - FakeSinglePoolElement single = new FakeSinglePoolElement("minecraft:village/plains/houses/plains_small_house_1"); - - VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(single); - - assertSame(single, resolution.physicalElement()); - assertEquals("minecraft:village/plains/houses/plains_small_house_1", resolution.templateLocation()); - assertEquals(0, resolution.listLevels()); - assertEquals(0, resolution.omittedElements()); - } - - @Test - public void nestedListsRetainOnlyTheRecursivePrimaryTemplate() throws Exception { - FakeSinglePoolElement primary = new FakeSinglePoolElement("minecraft:pillager_outpost/watchtower"); - FakeSinglePoolElement innerOverlay = new FakeSinglePoolElement("test:inner_overlay"); - FakeSinglePoolElement outerOverlay = new FakeSinglePoolElement("test:outer_overlay"); - FakeListPoolElement inner = new FakeListPoolElement(List.of(primary, innerOverlay)); - FakeListPoolElement outer = new FakeListPoolElement(List.of(inner, outerOverlay)); - - VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(outer); - - assertSame(primary, resolution.physicalElement()); - assertEquals("minecraft:pillager_outpost/watchtower", resolution.templateLocation()); - assertEquals(2, resolution.listLevels()); - assertEquals(2, resolution.omittedElements()); - } - - @Test - public void unsupportedPrimaryDoesNotFallThroughToLaterChildren() throws Exception { - FakeFeaturePoolElement feature = new FakeFeaturePoolElement(); - FakeSinglePoolElement fallback = new FakeSinglePoolElement("test:must_not_be_selected"); - FakeListPoolElement list = new FakeListPoolElement(List.of(feature, fallback)); - - VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(list); - - assertSame(feature, resolution.physicalElement()); - assertNull(resolution.templateLocation()); - assertEquals(1, resolution.omittedElements()); - } - - @Test - public void emptyListResolvesWithoutIndexingAChild() throws Exception { - VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement( - new FakeListPoolElement(List.of()) - ); - - assertNull(resolution.physicalElement()); - assertNull(resolution.templateLocation()); - assertEquals(1, resolution.listLevels()); - assertEquals(0, resolution.omittedElements()); - } - - @Test - public void outerChoiceProducesOneEntryWithItsOriginalWeight() throws Exception { - FakeListPoolElement towers = new FakeListPoolElement(List.of( - new FakeSinglePoolElement("minecraft:pillager_outpost/watchtower"), - new FakeSinglePoolElement("minecraft:pillager_outpost/watchtower_overgrown") - )); - VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(towers); - - List> entries = List.of(VillageImporter.piecePoolEntry( - "qa/pillager_outpost/piece/minecraft/pillager_outpost/watchtower", - 7 - )); - - assertEquals(1, entries.size()); - assertEquals("minecraft:pillager_outpost/watchtower", resolution.templateLocation()); - assertEquals(7, entries.getFirst().get("weight")); - assertEquals(1, resolution.omittedElements()); - } - @Test public void omittedCompositeChildrenProduceExplicitFidelityLoss() throws Exception { - FakeListPoolElement towers = new FakeListPoolElement(List.of( - new FakeSinglePoolElement("minecraft:pillager_outpost/watchtower"), - new FakeSinglePoolElement("minecraft:pillager_outpost/watchtower_overgrown") - )); - VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(towers); + int listLevels = 1; + int omittedElements = 1; StructureLoss loss = VillageImporter.listElementFallbackLoss( - resolution, + listLevels, + omittedElements, "minecraft:pillager_outpost/towers" ); @@ -351,7 +274,7 @@ public class VillageImporterListPoolElementTest { @Test public void omittedTemplateContributesNoBlocksOrCapturedCapabilities() { VillageImporter.ImportedTemplate imported = new VillageImporter.ImportedTemplate( - new IrisObject(3, 3, 3), + DeclaredObjects.empty(3, 3, 3), 27, 4, List.of(), @@ -373,49 +296,4 @@ public class VillageImporterListPoolElementTest { assertTrue(imported.emittedCapabilities(omitted).isEmpty()); } - private static final class FakeListPoolElement { - private final List elements; - - private FakeListPoolElement(List elements) { - this.elements = List.copyOf(elements); - } - - public List getElements() { - return elements; - } - } - - private static final class FakeSinglePoolElement { - private final FakeResourceLocation location; - - private FakeSinglePoolElement(String location) { - String[] parts = location.split(":", 2); - this.location = new FakeResourceLocation(parts[0], parts[1]); - } - - public FakeResourceLocation getTemplateLocation() { - return location; - } - } - - private static final class FakeFeaturePoolElement { - } - - private static final class FakeResourceLocation { - private final String namespace; - private final String path; - - private FakeResourceLocation(String namespace, String path) { - this.namespace = namespace; - this.path = path; - } - - public String getNamespace() { - return namespace; - } - - public String getPath() { - return path; - } - } } diff --git a/core/src/test/java/art/arcane/iris/core/structure/StructureIndexServiceTest.java b/core/src/test/java/art/arcane/iris/core/structure/authoring/StructureIndexServiceTest.java similarity index 55% rename from core/src/test/java/art/arcane/iris/core/structure/StructureIndexServiceTest.java rename to core/src/test/java/art/arcane/iris/core/structure/authoring/StructureIndexServiceTest.java index 65fc15e93..733154e02 100644 --- a/core/src/test/java/art/arcane/iris/core/structure/StructureIndexServiceTest.java +++ b/core/src/test/java/art/arcane/iris/core/structure/authoring/StructureIndexServiceTest.java @@ -1,16 +1,14 @@ -package art.arcane.iris.core.structure; +package art.arcane.iris.core.structure.authoring; -import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.IrisModuleHost; import art.arcane.iris.core.modules.ModuleResourceFixture; -import art.arcane.iris.core.modules.StructureModelModule; +import art.arcane.iris.core.structure.FakePlatformStructures; +import art.arcane.iris.core.tooling.IrisToolPack; +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 org.junit.After; -import org.junit.Before; +import art.arcane.iris.modules.jigsaw.JigsawModule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -18,38 +16,19 @@ import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.InputStream; import java.nio.charset.StandardCharsets; -import java.util.List; +import java.nio.file.Files; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; 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 StructureIndexServiceTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); - private IrisPlatform previousPlatform; - - @Before - public void detachPlatform() { - previousPlatform = IrisPlatforms.isBound() ? IrisPlatforms.get() : null; - IrisPlatforms.unbind(); - } - - @After - public void restorePlatform() { - IrisPlatforms.unbind(); - if (previousPlatform != null) { - IrisPlatforms.bind(previousPlatform); - } - } - @Test public void generatedIndexLivesOutsideStructureRegistrantDirectory() throws Exception { File pack = temporaryFolder.newFolder("pack"); @@ -60,30 +39,24 @@ public class StructureIndexServiceTest { } @Test - public void writeOnceWaitsForBoundHooksThenWritesOnce() throws Exception { + public void writeListsPlatformStructuresAndTheStructuresOfThePack() throws Exception { File pack = temporaryFolder.newFolder("pack"); IrisData data = mock(IrisData.class); - IrisPlatform platform = mock(IrisPlatform.class); - PlatformStructureHooks structureHooks = mock(PlatformStructureHooks.class); - ModuleResourceFixture.serveModules(data, new StructureModelModule(), new StructureModule()); + ModuleResourceFixture.serveModules(data, new StructureModule(), new JigsawModule()); when(data.getDataFolder()).thenReturn(pack); ModuleResourceFixture.serve(data).resource(StructureResources.STRUCTURES, "castle", new IrisStructure()); - when(structureHooks.structureKeys()).thenReturn(List.of("minecraft:village", "example:castle")); - when(structureHooks.structureSetKeys()).thenReturn(List.of("minecraft:villages")); + FakePlatformStructures platform = new FakePlatformStructures() + .withStructures("minecraft:village", "example:castle") + .withStructureSets("minecraft:villages"); - assertNull(StructureIndexService.writeOnce(data)); - - IrisPlatforms.bind(platform); - assertNull(StructureIndexService.writeOnce(data)); - - when(platform.structureHooks()).thenReturn(structureHooks); - File index = StructureIndexService.writeOnce(data); + File index = StructureIndexService.write(new IrisToolPack(data, IrisModuleHost.hostLog()), platform); assertEquals(StructureIndexService.indexFile(pack), index); - assertTrue(index.isFile()); - assertNull(StructureIndexService.writeOnce(data)); - verify(structureHooks, times(1)).structureKeys(); - verify(structureHooks, times(1)).structureSetKeys(); + String written = Files.readString(index.toPath()); + assertTrue(written.contains("minecraft:village")); + assertTrue(written.contains("example:castle")); + assertTrue(written.contains("minecraft:villages")); + assertTrue(written.contains("\"castle\"")); } @Test diff --git a/core/src/test/java/art/arcane/iris/core/structure/export/VanillaJigsawDatapackExporterTest.java b/core/src/test/java/art/arcane/iris/core/structure/export/VanillaJigsawDatapackExporterTest.java index 8706112bf..309e69501 100644 --- a/core/src/test/java/art/arcane/iris/core/structure/export/VanillaJigsawDatapackExporterTest.java +++ b/core/src/test/java/art/arcane/iris/core/structure/export/VanillaJigsawDatapackExporterTest.java @@ -3,7 +3,12 @@ package art.arcane.iris.core.structure.export; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.blocks.ObjectReplace; import art.arcane.iris.engine.framework.structure.StructureGraphResolver; -import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; +import art.arcane.iris.engine.framework.structure.ObjectFrame; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import com.volmit.resource.ResourceId; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawCompatibility; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; @@ -12,22 +17,13 @@ import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceEntry; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceRules; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.structure.IrisStructure; -import art.arcane.iris.engine.object.prefab.TileData; -import art.arcane.iris.spi.IrisPlatform; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.spi.PlatformRegistries; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.nbt.io.NBTUtil; import art.arcane.volmlib.util.nbt.tag.CompoundTag; import art.arcane.volmlib.util.nbt.tag.ListTag; import com.google.gson.JsonObject; import com.google.gson.JsonParser; -import org.junit.AfterClass; -import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -48,32 +44,14 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; public class VanillaJigsawDatapackExporterTest { - private static PlatformBlockState stone; + private static final BlockState STONE = new BlockState("minecraft:stone"); + private static final BlockState AIR = new BlockState("minecraft:air"); @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); - @BeforeClass - public static void bindPlatform() { - IrisPlatforms.unbind(); - stone = blockState("minecraft:stone"); - PlatformRegistries registries = mock(PlatformRegistries.class); - when(registries.block(anyString())).thenReturn(stone); - IrisPlatform platform = mock(IrisPlatform.class); - when(platform.registries()).thenReturn(registries); - IrisPlatforms.bind(platform); - } - - @AfterClass - public static void unbindPlatform() { - IrisPlatforms.unbind(); - } - @Test public void exportsComplete26_2DirectoryAndConnectorTemplate() throws Exception { TestGraph graph = connectorGraph(); @@ -166,22 +144,21 @@ public class VanillaJigsawDatapackExporterTest { @Test public void preservesExplicitAirAndStructureVoidConnectorFinalStates() throws Exception { TestGraph graph = terminalGraph(); - PlatformBlockState air = blockState("minecraft:air"); - IrisObject object = graph.objects.get("objects/start"); - object.setUnsigned(0, 1, 1, air); + graph.objects.put("objects/start", ObjectContents.plain(3, 3, 3, + Map.of(new BlockPosition(1, 1, 1), STONE, new BlockPosition(0, 1, 1), AIR), Map.of())); IrisJigsawPiece piece = graph.pieces.get("pieces/start"); piece.getConnectors().add(new IrisJigsawConnector() - .setPosition(new IrisPosition(0, 1, 1)) - .setDirection(IrisDirection.WEST_NEGATIVE_X) - .setTop(IrisDirection.UP_POSITIVE_Y) + .setPosition(new BlockPosition(0, 1, 1)) + .setDirection(JigsawDirection.WEST_NEGATIVE_X) + .setTop(JigsawDirection.UP_POSITIVE_Y) .setPool("pools/terminal") .setName("studio:air") .setTargetName("studio:door") .setFinalState("minecraft:air")); piece.getConnectors().add(new IrisJigsawConnector() - .setPosition(new IrisPosition(2, 1, 1)) - .setDirection(IrisDirection.EAST_POSITIVE_X) - .setTop(IrisDirection.UP_POSITIVE_Y) + .setPosition(new BlockPosition(2, 1, 1)) + .setDirection(JigsawDirection.EAST_POSITIVE_X) + .setTop(JigsawDirection.UP_POSITIVE_Y) .setPool("pools/terminal") .setName("studio:void") .setTargetName("studio:door") @@ -211,7 +188,8 @@ public class VanillaJigsawDatapackExporterTest { @Test public void rejectsTilePayloadWithoutPublishingPartialOutput() { TestGraph graph = terminalGraph(); - graph.objects.get("objects/start").setUnsignedTile(0, 0, 0, mock(TileData.class)); + graph.objects.put("objects/start", ObjectContents.plain(3, 3, 3, Map.of(new BlockPosition(1, 1, 1), STONE), + Map.of(new BlockPosition(0, 0, 0), new BlockEntityData(ResourceId.parse("test:tile"), 0, new byte[0])))); Path output = temporaryFolder.getRoot().toPath().resolve("rejected-pack"); VanillaJigsawExportResult result = new VanillaJigsawDatapackExporter().export( @@ -310,18 +288,18 @@ public class VanillaJigsawDatapackExporterTest { VanillaJigsawExportSource source = VanillaJigsawExportSource.forStructure( "test_structure", graph.structure, - graph); + graph, + graph.objects::get); return VanillaJigsawExportRequest.builder(source, output); } private static TestGraph connectorGraph() { TestGraph graph = new TestGraph(); - IrisObject object = new IrisObject(3, 3, 3); - object.setUnsigned(1, 1, 0, stone); + ObjectContents object = ObjectContents.plain(3, 3, 3, Map.of(new BlockPosition(1, 1, 0), STONE), Map.of()); IrisJigsawConnector connector = new IrisJigsawConnector() - .setPosition(new IrisPosition(1, 1, 0)) - .setDirection(IrisDirection.NORTH_NEGATIVE_Z) - .setTop(IrisDirection.UP_POSITIVE_Y) + .setPosition(new BlockPosition(1, 1, 0)) + .setDirection(JigsawDirection.NORTH_NEGATIVE_Z) + .setTop(JigsawDirection.UP_POSITIVE_Y) .setPool("pools/terminal") .setName("studio:source") .setTargetName("studio:door") @@ -338,9 +316,7 @@ public class VanillaJigsawDatapackExporterTest { private static TestGraph terminalGraph() { TestGraph graph = new TestGraph(); - IrisObject object = new IrisObject(3, 3, 3); - object.setUnsigned(1, 1, 1, stone); - graph.objects.put("objects/start", object); + graph.objects.put("objects/start", ObjectContents.plain(3, 3, 3, Map.of(new BlockPosition(1, 1, 1), STONE), Map.of())); graph.pieces.put("pieces/start", piece("objects/start")); graph.pools.put("pools/start", pool(entry("pieces/start", 1))); graph.structure = structure("pools/start"); @@ -349,7 +325,6 @@ public class VanillaJigsawDatapackExporterTest { private static IrisStructure structure(String startPool) { IrisStructure structure = new IrisStructure(); - structure.setLoadKey("test_structure"); structure.setStartPool(startPool); structure.setMaxDepth(4); structure.setMaxSizeChunks(4); @@ -377,13 +352,6 @@ public class VanillaJigsawDatapackExporterTest { return new IrisJigsawPieceEntry().setEmpty(true).setWeight(weight); } - private static PlatformBlockState blockState(String key) { - PlatformBlockState state = mock(PlatformBlockState.class); - when(state.key()).thenReturn(key); - when(state.namespace()).thenReturn(key.substring(0, key.indexOf(':'))); - return state; - } - private static JsonObject json(Path path) throws IOException { return JsonParser.parseString(Files.readString(path, StandardCharsets.UTF_8)).getAsJsonObject(); } @@ -398,7 +366,7 @@ public class VanillaJigsawDatapackExporterTest { private static final class TestGraph implements StructureGraphResolver { private final Map pools = new LinkedHashMap<>(); private final Map pieces = new LinkedHashMap<>(); - private final Map objects = new LinkedHashMap<>(); + private final Map objects = new LinkedHashMap<>(); private IrisStructure structure; @Override @@ -412,8 +380,9 @@ public class VanillaJigsawDatapackExporterTest { } @Override - public IrisObject loadObject(String key) { - return objects.get(key); + public ObjectFrame loadObject(String key) { + ObjectContents contents = objects.get(key); + return contents == null ? null : new ObjectFrame(contents.width(), contents.height(), contents.depth()); } } } diff --git a/core/src/test/java/art/arcane/iris/core/structure/tooling/JigsawCommandsContractTest.java b/core/src/test/java/art/arcane/iris/core/structure/tooling/JigsawCommandsContractTest.java new file mode 100644 index 000000000..09e8bf90f --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/structure/tooling/JigsawCommandsContractTest.java @@ -0,0 +1,569 @@ +package art.arcane.iris.core.structure.tooling; + +import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarArchetype; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariantCatalog; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioWorkcellSpec; +import art.arcane.iris.core.service.JigsawStudioService; +import art.arcane.iris.core.structure.authoring.StructureBackend; +import art.arcane.iris.core.structure.authoring.StructureCapability; +import art.arcane.iris.core.structure.authoring.StructureHash; +import art.arcane.iris.core.structure.authoring.StructureKey; +import art.arcane.iris.core.structure.authoring.StructureOwnershipManifest; +import art.arcane.iris.core.structure.authoring.StructureSource; +import art.arcane.iris.core.structure.authoring.StructureTransactionWriter; +import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionInputKind; +import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionStrategy; +import art.arcane.iris.core.structure.export.VanillaJigsawExportFormat; +import art.arcane.iris.engine.framework.structure.ObjectFrame; +import com.volmit.geometry.BlockPosition; +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.JigsawDirection; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.Argument; +import com.volmit.tooling.Command; +import com.volmit.tooling.CommandContext; +import com.volmit.tooling.Sender; +import com.volmit.tooling.world.ToolPlayer; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.lang.reflect.Method; +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.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +public class JigsawCommandsContractTest { + private static final long DEFAULT_SEED = 1337L; + + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + private final Command root = JigsawCommands.root(new JigsawStudios()); + + @Test + public void theJigsawRootAnswersToItsShortNamesAndHoldsTheWholeTree() { + assertEquals("jigsaw", root.name()); + assertEquals(List.of("jig", "jgs"), root.aliases()); + for (String name : List.of("adopt", "connector", "pool", "piece", "variant", "workcell", "rules", "preview")) { + assertTrue(name, child(root, name).action().isEmpty()); + } + } + + @Test + public void exposesStudioLifecycleAndAuthoringCommands() { + assertArguments("create", "key", "mode", "compatibility", "width", "height", "depth", "seed"); + assertArguments("convert", "source", "target", "seed"); + assertArguments("open", "key", "seed"); + assertArguments("close", "discard"); + assertArguments("delete", "confirm"); + assertArguments("status"); + assertArguments("menu"); + assertArguments("select"); + assertArguments("bounds", "width", "height", "depth"); + assertArguments("save", "bay"); + assertArguments("goto", "bay"); + assertArguments("particles", "visible"); + assertArguments("export", "namespace", "output", "format", "replace"); + } + + @Test + public void importAndCaptureAreJigsawCommandsAndNeedNoPlayer() { + Command importAll = child(root, "import"); + Command capture = child(root, "capture"); + + assertEquals(List.of("import-all", "reimport", "imp", "all"), importAll.aliases()); + assertEquals(List.of("cap"), capture.aliases()); + assertTrue(importAll.arguments().isEmpty()); + assertTrue(capture.arguments().isEmpty()); + assertTrue(importAll.action().isPresent()); + assertTrue(capture.action().isPresent()); + } + + @Test + public void committedActivationStartsInitialEvaluationBeforePlayerBinding() throws Exception { + String source = source("StudioLifecycleCommands.java"); + int commit = source.indexOf("registry.commit(staged)"); + int evaluation = source.indexOf( + "use.studio().activationCommitted(request.requestId())", + commit); + int binding = source.indexOf("StudioSessions.bind(", evaluation); + + assertTrue(commit >= 0); + assertTrue(evaluation > commit); + assertTrue(binding > evaluation); + } + + @Test + public void convertIsAddOnlyWorkflowWithAliasesAndDefaults() { + Command convert = child(root, "convert"); + + assertEquals(List.of("import-vanilla"), convert.aliases()); + assertEquals("auto", convert.arguments().get(1).fallback()); + assertEquals(DEFAULT_SEED, convert.arguments().get(2).fallback()); + ResourceId source = StudioLifecycleCommands.parseRegisteredStructureKey("minecraft:village_plains"); + assertEquals("minecraft_village_plains", StudioLifecycleCommands.resolveConversionTarget(source, "auto")); + assertEquals("villages/plains", StudioLifecycleCommands.resolveConversionTarget(source, "iris:villages/plains")); + ResourceId ancientCity = StudioLifecycleCommands.parseRegisteredStructureKey("minecraft:ancient_city"); + assertEquals("minecraft_ancient_city", StudioLifecycleCommands.resolveConversionTarget(ancientCity, "auto")); + assertThrows(IllegalArgumentException.class, + () -> StudioLifecycleCommands.resolveConversionTarget(source, "custom:village")); + } + + @Test + public void adoptionCommandsExposeTwoStepPlanContract() { + Command adopt = child(root, "adopt"); + Command inspect = child(adopt, "inspect"); + Command apply = child(adopt, "apply"); + + assertEquals(List.of("source", "target", "strategy"), argumentNames(inspect)); + assertEquals("auto", inspect.arguments().get(1).fallback()); + assertEquals("auto", inspect.arguments().get(2).fallback()); + assertEquals(List.of("plan"), argumentNames(apply)); + assertEquals(List.of("auto", "clone", "in-place"), inspect.arguments().get(2).complete("", null)); + assertEquals(IrisStructureAdoptionStrategy.IN_PLACE, AdoptionCommands.parseAdoptionStrategy("claim")); + assertEquals(IrisStructureAdoptionStrategy.CLONE, AdoptionCommands.parseAdoptionStrategy("copy")); + assertThrows(IllegalArgumentException.class, () -> AdoptionCommands.parseAdoptionStrategy("overwrite")); + } + + @Test + public void adoptionInputKindUsesOnlyOwnershipProvenance() throws Exception { + Path packRoot = temporaryFolder.newFolder("adoption-provenance").toPath(); + + assertEquals(IrisStructureAdoptionInputKind.UNOWNED_IRIS, + AdoptionCommands.adoptionInputKind(packRoot, "unowned")); + writeManifest(packRoot, "datapack-created", StructureSource.Kind.DATAPACK, + StructureOwnershipManifest.Provenance.created()); + assertEquals(IrisStructureAdoptionInputKind.UNOWNED_IRIS, + AdoptionCommands.adoptionInputKind(packRoot, "datapack-created")); + writeManifest(packRoot, "managed-provenance", StructureSource.Kind.IRIS, managedProvenance()); + assertEquals(IrisStructureAdoptionInputKind.MANAGED_DATAPACK, + AdoptionCommands.adoptionInputKind(packRoot, "managed-provenance")); + } + + @Test + public void legacyGraphWritersShareTheServiceMutationContract() throws Exception { + Method mutation = GraphMutations.class.getDeclaredMethod( + "runGraphMutation", + StudioUse.class, + StudioSessions.ActiveContext.class, + JigsawStudioService.CommandGraphMutation.class); + + assertEquals(void.class, mutation.getReturnType()); + assertNotNull(JigsawStudioService.CommandGraphMutation.class.getDeclaredMethod("run")); + assertNotNull(JigsawStudioService.CommandGraphMutationResult.class.getDeclaredConstructor( + JigsawStudioLayout.class, + String.class, + String.class, + String.class)); + } + + @Test + public void exposesAutosaveDynamicEvaluationAndSelectedWorkcellResize() { + assertEquals("Flush the automatic save for a workcell now", child(root, "save").description()); + assertEquals("Show active Jigsaw Studio and dynamic evaluation state", child(root, "status").description()); + assertEquals("Set the selected Studio workcell capacity", child(root, "bounds").description()); + assertThrows(IllegalStateException.class, () -> child(root, "validate")); + } + + @Test + public void createDefaultsToPlanarIrisWithCompleteCellAndSeedDefaults() { + List> arguments = child(root, "create").arguments(); + + assertEquals("planar", arguments.get(1).fallback()); + assertEquals("iris", arguments.get(2).fallback()); + assertEquals(15L, arguments.get(3).fallback()); + assertEquals(15L, arguments.get(4).fallback()); + assertEquals(15L, arguments.get(5).fallback()); + assertEquals(DEFAULT_SEED, arguments.get(6).fallback()); + } + + @Test + public void structureKeysExplainTheirResourceAndOpenSupportsEditingAliases() { + Command create = child(root, "create"); + Command open = child(root, "open"); + + assertEquals("key", create.arguments().getFirst().name()); + assertEquals("New key written as structures/.json", create.arguments().getFirst().description()); + assertEquals("key", open.arguments().getFirst().name()); + assertEquals("Existing key loaded from structures/.json", open.arguments().getFirst().description()); + assertEquals(List.of("edit", "reopen"), open.aliases()); + } + + @Test + public void createChoicesExposeCanonicalCompletionsAndRetainAliases() { + Command create = child(root, "create"); + + assertEquals(List.of("planar", "spatial"), create.arguments().get(1).complete("", null)); + assertEquals(JigsawStudioMode.PLANAR_JIGSAW, StudioLifecycleCommands.parseMode("2d")); + assertEquals(JigsawStudioMode.SPATIAL_JIGSAW, StudioLifecycleCommands.parseMode("3d")); + assertEquals(List.of("iris", "vanilla"), create.arguments().get(2).complete("", null)); + assertEquals(art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget.IRIS_EXTENDED, + StudioLifecycleCommands.parseCompatibility("extended")); + assertEquals(art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget.VANILLA_PORTABLE, + StudioLifecycleCommands.parseCompatibility("portable")); + assertThrows(IllegalArgumentException.class, () -> StudioLifecycleCommands.parseMode("volume")); + assertThrows(IllegalArgumentException.class, () -> StudioLifecycleCommands.parseCompatibility("mixed")); + } + + @Test + public void exposesNestedPieceVariantAndPreviewCommands() { + assertArguments(child(root, "pool"), "create", "poolKey", "fallbackPoolKey"); + assertArguments(child(root, "connector"), "channel", "channel"); + Command piece = child(root, "piece"); + assertArguments(piece, "create", "poolKey", "pieceKey", "weight"); + assertArguments(piece, "add", "poolKey", "pieceKey", "weight"); + assertArguments(piece, "remove", "poolKey"); + assertArguments(piece, "rotatable", "rotatable"); + assertArguments(piece, "expand"); + assertEquals("Resize the selected piece object exactly to workcell capacity", + child(piece, "expand").description()); + Command variant = child(root, "variant"); + assertArguments(variant, "weight", "poolKey", "weight"); + assertArguments(variant, "resize", "width", "height", "depth"); + assertArguments(variant, "label", "displayName"); + assertArguments(variant, "label-reset"); + assertArguments(variant, "duplicate"); + assertArguments(variant, "duplicate-family", "themeKey"); + assertEquals("next", child(variant, "duplicate-family").arguments().getFirst().fallback()); + Command workcell = child(root, "workcell"); + assertArguments(workcell, "capacity", "width", "height", "depth"); + assertArguments(workcell, "label", "displayName"); + assertArguments(workcell, "label-reset"); + Command rules = child(root, "rules"); + assertArguments(rules, "limits", "maxDepth", "maxSizeChunks"); + assertArguments(rules, "fallback", "poolKey", "fallbackPoolKey"); + Command preview = child(root, "preview"); + assertArguments(preview, "assemble", "seed"); + assertArguments(preview, "goto"); + } + + @Test + public void pieceCreateUsesResolvedWorkcellCapacityInsteadOfLayoutDefault() throws Exception { + String source = source("GraphEditCommands.java"); + int create = source.indexOf("private void pieceCreate("); + int add = source.indexOf("private void pieceAdd(", create); + String createSource = source.substring(create, add); + + assertTrue(createSource.contains("targetWorkcell = contextual;")); + assertTrue(createSource.contains("JigsawStudioCellDimensions dimensions = targetWorkcell.capacity();")); + assertFalse(createSource.contains("layout().cellDimensions()")); + } + + @Test + public void pieceAddUsesCanonicalAxesForRotatedRectangularPlanarWorkcells() { + JigsawStudioLayout layout = nonuniformPlanarLayout(); + IrisJigsawPiece eastEnd = new IrisJigsawPiece(); + eastEnd.getConnectors().add(new IrisJigsawConnector().setDirection(JigsawDirection.EAST_POSITIVE_X)); + ObjectFrame exactObject = new ObjectFrame(7, 5, 13); + + GraphMutations.PieceWorkcellResolution exact = GraphMutations.resolvePieceWorkcell( + layout, + eastEnd, + exactObject); + GraphMutations.PieceWorkcellResolution oversized = GraphMutations.resolvePieceWorkcell( + layout, + eastEnd, + new ObjectFrame(8, 5, 13)); + + assertEquals(JigsawPlanarArchetype.END.stableId(), exact.workcell().stableId()); + assertEquals(new BlockPosition(13, 5, 7), exact.requiredDimensions()); + assertEquals(new JigsawStudioCellDimensions(13, 5, 7), exact.workcell().capacity()); + assertTrue(exact.fits()); + assertTrue(exactObject.depth() > exact.workcell().capacity().depth()); + assertFalse(oversized.fits()); + } + + @Test + public void pieceAddKeepsRawObjectAxesForSpatialWorkcells() { + JigsawStudioCellDimensions capacity = new JigsawStudioCellDimensions(7, 5, 13); + JigsawStudioLayout layout = JigsawStudioLayout.create( + JigsawStudioMode.SPATIAL_JIGSAW, + capacity, + JigsawStudioVariantCatalog.empty()); + IrisJigsawPiece spatialPiece = new IrisJigsawPiece(); + spatialPiece.getConnectors().add( + new IrisJigsawConnector().setDirection(JigsawDirection.EAST_POSITIVE_X)); + + GraphMutations.PieceWorkcellResolution resolution = GraphMutations.resolvePieceWorkcell( + layout, + spatialPiece, + new ObjectFrame(7, 5, 13)); + + assertEquals(JigsawStudioLayout.SPATIAL_WORKCELL_ID, resolution.workcell().stableId()); + assertEquals(new BlockPosition(7, 5, 13), resolution.requiredDimensions()); + assertEquals(capacity, resolution.workcell().capacity()); + assertTrue(resolution.fits()); + } + + @Test + public void everyStudioCommandRejectsSendersThatAreNotPlayers() throws Exception { + List answered = new ArrayList<>(); + RecordingSender sender = new RecordingSender(); + + for (Command command : playerCommands(root)) { + sender.errors.clear(); + command.action().orElseThrow().run(contextOf(sender)); + assertEquals(command.name(), List.of(StudioUse.PLAYERS_ONLY), sender.errors); + answered.add(command.name()); + } + + assertTrue(answered.size() > 30); + } + + @Test + public void exportOutputIsOneSafeChildArtifact() { + Path exportRoot = Path.of("build", "jigsaw-exports").toAbsolutePath().normalize(); + + assertEquals(exportRoot.resolve("village.zip"), JigsawExportCommand.resolveExportDestination( + exportRoot, "village", VanillaJigsawExportFormat.ZIP)); + assertEquals(exportRoot.resolve("village"), JigsawExportCommand.resolveExportDestination( + exportRoot, "village", VanillaJigsawExportFormat.DIRECTORY)); + assertThrows(IllegalArgumentException.class, () -> JigsawExportCommand.resolveExportDestination( + exportRoot, "", VanillaJigsawExportFormat.DIRECTORY)); + assertThrows(IllegalArgumentException.class, () -> JigsawExportCommand.resolveExportDestination( + exportRoot, ".", VanillaJigsawExportFormat.DIRECTORY)); + assertThrows(IllegalArgumentException.class, () -> JigsawExportCommand.resolveExportDestination( + exportRoot, "../all-exports", VanillaJigsawExportFormat.DIRECTORY)); + assertThrows(IllegalArgumentException.class, () -> JigsawExportCommand.resolveExportDestination( + exportRoot, "nested/export", VanillaJigsawExportFormat.DIRECTORY)); + } + + @Test + public void exportLeaseRejectsDuplicatePlayerAndDestination() { + UUID firstPlayer = UUID.randomUUID(); + UUID secondPlayer = UUID.randomUUID(); + Path firstDestination = Path.of("build", "jigsaw-exports", "first.zip"); + Path secondDestination = Path.of("build", "jigsaw-exports", "second.zip"); + + assertTrue(JigsawExportCommand.beginExport(firstPlayer, firstDestination)); + try { + assertFalse(JigsawExportCommand.beginExport(firstPlayer, secondDestination)); + assertFalse(JigsawExportCommand.beginExport(secondPlayer, firstDestination)); + } finally { + JigsawExportCommand.finishExport(firstPlayer, firstDestination); + } + + assertTrue(JigsawExportCommand.beginExport(secondPlayer, firstDestination)); + JigsawExportCommand.finishExport(secondPlayer, firstDestination); + } + + @Test + public void exportStartFailuresHavePreciseOperatorMessages() { + assertEquals("The active Jigsaw Studio is no longer available.", + JigsawExportCommand.exportStartError(JigsawStudioService.ExportStart.NOT_ACTIVE)); + assertEquals("Only the Jigsaw Studio owner can export this project.", + JigsawExportCommand.exportStartError(JigsawStudioService.ExportStart.NOT_OWNER)); + assertEquals("Wait for the pending autosave or discard the edits before exporting the on-disk graph.", + JigsawExportCommand.exportStartError(JigsawStudioService.ExportStart.DIRTY)); + assertEquals("The active Jigsaw Studio is closing and cannot be exported.", + JigsawExportCommand.exportStartError(JigsawStudioService.ExportStart.CLOSING)); + assertEquals("Wait for the current Jigsaw Studio save to finish before exporting.", + JigsawExportCommand.exportStartError(JigsawStudioService.ExportStart.SAVE_IN_PROGRESS)); + assertEquals("Wait for the current Jigsaw Studio operation to finish before exporting.", + JigsawExportCommand.exportStartError(JigsawStudioService.ExportStart.OPERATION_IN_PROGRESS)); + assertEquals("A Jigsaw Studio export is already in progress.", + JigsawExportCommand.exportStartError(JigsawStudioService.ExportStart.IN_PROGRESS)); + assertThrows(IllegalArgumentException.class, + () -> JigsawExportCommand.exportStartError(JigsawStudioService.ExportStart.STARTED)); + } + + @Test + public void exportLeaseReleaseActionRunsExactlyOnce() { + AtomicInteger releases = new AtomicInteger(); + JigsawExportCommand.ExportLease lease = new JigsawExportCommand.ExportLease(releases::incrementAndGet); + + lease.release(); + lease.release(); + + assertEquals(1, releases.get()); + } + + @Test + public void exportSourceAcquiresStudioLeaseBeforeStaticLeaseAndReleasesBothPaths() throws Exception { + String source = source("JigsawExportCommand.java"); + int serviceLease = source.indexOf("studioService.tryBeginExport(requestId, playerId)"); + int staticLease = source.indexOf("beginExport(playerId, destination)", serviceLease); + int dispatch = source.indexOf("runExport(operation);", staticLease); + int schedulingRelease = source.indexOf("operation.lease().release()", dispatch); + int exporter = source.indexOf("new VanillaJigsawDatapackExporter().export(operation.request())", dispatch); + int completionRelease = source.indexOf("operation.lease().release()", exporter); + + assertTrue(serviceLease >= 0); + assertTrue(staticLease > serviceLease); + assertTrue(dispatch > staticLease); + assertTrue(schedulingRelease > dispatch); + assertTrue(exporter > schedulingRelease); + assertTrue(completionRelease > exporter); + } + + @Test + public void exportGoesBelowTheOutputFolderOfThePack() throws Exception { + String source = source("JigsawExportCommand.java"); + + assertTrue(source.contains("use.pack().outputFolder()")); + } + + private static Command child(Command parent, String name) { + return parent.children().stream() + .filter(command -> command.answersTo(name)) + .findFirst() + .orElseThrow(() -> new IllegalStateException(parent.name() + " has no sub-command " + name)); + } + + private void assertArguments(String name, String... argumentNames) { + assertArguments(root, name, argumentNames); + } + + private static void assertArguments(Command parent, String name, String... argumentNames) { + Command command = child(parent, name); + assertTrue(name, command.action().isPresent()); + assertEquals(name, List.of(argumentNames), argumentNames(command)); + } + + private static List argumentNames(Command command) { + return command.arguments().stream().map(Argument::name).toList(); + } + + private static List playerCommands(Command parent) { + List commands = new ArrayList<>(); + for (Command child : parent.children()) { + if (parent.name().equals("jigsaw") && (child.name().equals("import") || child.name().equals("capture"))) { + continue; + } + if (child.action().isPresent()) { + commands.add(child); + } + commands.addAll(playerCommands(child)); + } + return commands; + } + + private static String source(String fileName) throws Exception { + return Files.readString(Path.of("../module/src/main/java/art/arcane/iris/core/structure/tooling", fileName)) + .replace("\r\n", "\n"); + } + + private static CommandContext contextOf(Sender sender) { + return (CommandContext) java.lang.reflect.Proxy.newProxyInstance( + JigsawCommandsContractTest.class.getClassLoader(), + new Class[]{CommandContext.class}, + (proxy, method, arguments) -> { + if (method.getName().equals("sender")) { + return sender; + } + throw new IllegalStateException("A command that needs a player asks for " + method.getName() + " too early"); + }); + } + + private static final class RecordingSender implements Sender { + private final List errors = new ArrayList<>(); + + @Override + public String name() { + return "console"; + } + + @Override + public void info(String message) { + } + + @Override + public void success(String message) { + } + + @Override + public void error(String message) { + errors.add(message); + } + + @Override + public Optional extension(Class type) { + return Optional.empty(); + } + + @Override + public Optional player() { + return Optional.empty(); + } + } + + private static JigsawStudioLayout nonuniformPlanarLayout() { + List workcells = List.of( + workcell(JigsawPlanarArchetype.BLANK, 3, 1, 3), + workcell(JigsawPlanarArchetype.END, 13, 5, 7), + workcell(JigsawPlanarArchetype.STRAIGHT, 5, 2, 11), + workcell(JigsawPlanarArchetype.CORNER, 9, 3, 6), + workcell(JigsawPlanarArchetype.TEE, 12, 4, 8), + workcell(JigsawPlanarArchetype.CROSS, 10, 6, 10)); + return JigsawStudioLayout.createPlanar( + new JigsawStudioCellDimensions(3, 1, 3), + workcells, + JigsawStudioVariantCatalog.empty()); + } + + private static JigsawStudioWorkcellSpec workcell( + JigsawPlanarArchetype archetype, + int width, + int height, + int depth + ) { + return new JigsawStudioWorkcellSpec( + archetype, + "", + new JigsawStudioCellDimensions(width, height, depth), + true); + } + + private static void writeManifest( + Path packRoot, + String structure, + StructureSource.Kind sourceKind, + StructureOwnershipManifest.Provenance provenance + ) throws Exception { + StructureKey structureKey = new StructureKey("iris", structure); + StructureOwnershipManifest manifest = new StructureOwnershipManifest( + StructureOwnershipManifest.CURRENT_SCHEMA_VERSION, + structureKey, + StructureSource.of(sourceKind, new StructureKey("iris", "source/" + structure)), + StructureBackend.IRIS_ASSEMBLY, + List.of(StructureCapability.BLOCKS, StructureCapability.CONNECTORS), + List.of(), + Map.of("structures/" + structure + ".json", StructureHash.sha256( + structure.getBytes(StandardCharsets.UTF_8))), + provenance); + Path manifestPath = new StructureTransactionWriter(packRoot).ownershipManifestPath(structureKey); + Files.createDirectories(manifestPath.getParent()); + Files.write(manifestPath, manifest.toJson()); + } + + private static StructureOwnershipManifest.Provenance managedProvenance() { + String path = "structures/source.json"; + String hash = StructureHash.sha256("source".getBytes(StandardCharsets.UTF_8)); + return new StructureOwnershipManifest.Provenance( + StructureOwnershipManifest.Origin.MANAGED_DATAPACK, + UUID.randomUUID().toString(), + StructureHash.sha256("plan".getBytes(StandardCharsets.UTF_8)), + StructureHash.sha256("closure".getBytes(StandardCharsets.UTF_8)), + 1L, + Map.of(path, hash), + Map.of(path, path), + StructureOwnershipManifest.RollbackDisposition.NONE); + } +} 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 index d27c6b563..5c57f8cc9 100644 --- a/core/src/test/java/art/arcane/iris/core/tooling/CommandRootCollisionTest.java +++ b/core/src/test/java/art/arcane/iris/core/tooling/CommandRootCollisionTest.java @@ -2,7 +2,7 @@ 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.mantle.components.StructureModule; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleSetup; @@ -37,21 +37,21 @@ public class CommandRootCollisionTest { @Test public void aModuleCannotTakeTheRootNameOfTheStructureModule() { var collision = assertThrows(IllegalArgumentException.class, () -> ModuleResourceFixture.catalogOf( - new StructureModelModule(), registering("test:rival", Command.named("structure")))); + new StructureModule(), 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("iris:structure")); 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())); + registering("test:rival", Command.named("shapes").alias("str")), new StructureModule())); 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")); + assertTrue(collision.getMessage(), collision.getMessage().contains("iris:structure")); } @Test diff --git a/core/src/test/java/art/arcane/iris/core/tooling/IrisObjectCodecTest.java b/core/src/test/java/art/arcane/iris/core/tooling/IrisObjectCodecTest.java new file mode 100644 index 000000000..79ffe8eb9 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/tooling/IrisObjectCodecTest.java @@ -0,0 +1,165 @@ +package art.arcane.iris.core.tooling; + +import art.arcane.iris.spi.IrisPlatform; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.spi.PlatformRegistries; +import art.arcane.iris.core.modules.BlockEntities; +import art.arcane.iris.engine.object.prefab.TileData; +import art.arcane.volmlib.util.collection.KMap; +import com.google.gson.Gson; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockBox; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import com.volmit.object.GeneratedObject; +import com.volmit.object.ObjectBlock; +import com.volmit.object.ObjectMarker; +import com.volmit.resource.ResourceId; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class IrisObjectCodecTest { + private final IrisObjectCodec codec = new IrisObjectCodec(); + + @Before + public void bindPlatform() { + IrisPlatforms.unbind(); + PlatformRegistries registries = mock(PlatformRegistries.class); + when(registries.block(anyString())).thenAnswer(invocation -> state(invocation.getArgument(0))); + IrisPlatform platform = mock(IrisPlatform.class); + when(platform.registries()).thenReturn(registries); + IrisPlatforms.bind(platform); + } + + @After + public void unbindPlatform() { + IrisPlatforms.unbind(); + } + + @Test + public void aFileWrittenAgainKeepsItsDeclaredSize() throws IOException { + for (int[] size : new int[][]{{1, 1, 1}, {2, 3, 4}, {16, 8, 16}, {15, 15, 15}, {9, 6, 7}}) { + byte[] written = codec.encode(codec.decode(file(size[0], size[1], size[2], 6))); + + assertArrayEquals(size[0] + "x" + size[1] + "x" + size[2], List.of(size[0], size[1], size[2]).toArray(), + declaredSizeOf(written)); + } + } + + @Test + public void anObjectWithoutBlocksKeepsItsDeclaredSize() throws IOException { + GeneratedObject decoded = codec.decode(file(5, 3, 5, 0)); + + assertEquals(new BlockBox(-2, -1, -2, 3, 2, 3), decoded.bounds()); + assertEquals(new BlockBox(-2, -1, -2, 3, 2, 3), codec.decode(codec.encode(decoded)).bounds()); + } + + @Test + public void aFileWrittenAgainHoldsTheSameBlocksAtTheSamePlaces() throws IOException { + for (int blocks : new int[]{1, 7, 25, 60}) { + GeneratedObject decoded = codec.decode(file(11, 9, 13, blocks)); + + GeneratedObject again = codec.decode(codec.encode(decoded)); + + assertEquals(blocks + " blocks", blocksOf(decoded), blocksOf(again)); + assertEquals(decoded.bounds(), again.bounds()); + } + } + + @Test + public void aTileSurvivesTheRoundTripWithItsContent() throws IOException { + TileData.TileReader previousReader = TileData.bindPlatformReader( + in -> new TileData(in.readUTF(), new Gson().fromJson(in.readUTF(), KMap.class))); + try { + KMap properties = new KMap<>(); + properties.put("CustomName", "vault"); + properties.put("Lock", "key"); + BlockEntityData chest = BlockEntities.of(new TileData("minecraft:chest", properties)); + GeneratedObject original = new GeneratedObject(new BlockBox(-2, -1, -2, 3, 2, 3), new BlockPosition(0, 0, 0), + List.of(new ObjectBlock(new BlockPosition(1, 0, -1), new BlockState("minecraft:chest"), Optional.of(chest)), + new ObjectBlock(new BlockPosition(0, 1, 0), new BlockState("minecraft:stone")), + new ObjectBlock(new BlockPosition(-2, -1, 2), new BlockState("minecraft:oak_planks"))), + List.of()); + + GeneratedObject again = codec.decode(codec.encode(original)); + + assertEquals(original.bounds(), again.bounds()); + assertEquals(original.anchor(), again.anchor()); + assertEquals(original.blocks(), again.blocks()); + assertEquals(original.markers(), again.markers()); + } finally { + TileData.restorePlatformReader(previousReader); + } + } + + @Test + public void anObjectWithMarkersIsRefusedInsteadOfLosingThem() { + GeneratedObject marked = new GeneratedObject(new BlockBox(0, 0, 0, 1, 1, 1), new BlockPosition(0, 0, 0), List.of(), + List.of(new ObjectMarker(new BlockPosition(0, 0, 0), ResourceId.parse("test:spawn"), Map.of()))); + + assertThrows(IOException.class, () -> codec.encode(marked)); + } + + private static Map blocksOf(GeneratedObject object) { + Map blocks = new HashMap<>(); + object.blocks().forEach(block -> blocks.put(block.position(), block.state())); + return blocks; + } + + private static Object[] declaredSizeOf(byte[] file) throws IOException { + DataInputStream in = new DataInputStream(new ByteArrayInputStream(file)); + return new Object[]{in.readInt(), in.readInt(), in.readInt()}; + } + + private static final String[] PALETTE = {"minecraft:stone", "minecraft:oak_planks", + "minecraft:oak_stairs[facing=east,half=top,shape=straight,waterlogged=false]"}; + + /** A file as Iris writes them: the declared size, the palette, the blocks at their offsets from the center, and no tiles. */ + private static byte[] file(int width, int height, int depth, int blockCount) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + DataOutputStream out = new DataOutputStream(bytes); + out.writeInt(width); + out.writeInt(height); + out.writeInt(depth); + out.writeUTF("Iris V2 IOB;"); + out.writeShort(PALETTE.length); + for (String key : PALETTE) { + out.writeUTF(key); + } + out.writeInt(blockCount); + for (int index = 0; index < blockCount; index++) { + out.writeShort(index % width - width / 2); + out.writeShort((index / 2) % height - height / 2); + out.writeShort((index * 3) % depth - depth / 2); + out.writeShort(index % PALETTE.length); + } + out.writeInt(0); + return bytes.toByteArray(); + } + + private static PlatformBlockState state(String key) { + PlatformBlockState state = mock(PlatformBlockState.class); + when(state.key()).thenReturn(key); + when(state.namespace()).thenReturn(key.substring(0, key.indexOf(':'))); + return state; + } +} diff --git a/core/src/test/java/art/arcane/iris/core/tooling/IrisToolPackTest.java b/core/src/test/java/art/arcane/iris/core/tooling/IrisToolPackTest.java index 58fab7978..2ab65db6c 100644 --- a/core/src/test/java/art/arcane/iris/core/tooling/IrisToolPackTest.java +++ b/core/src/test/java/art/arcane/iris/core/tooling/IrisToolPackTest.java @@ -1,9 +1,16 @@ package art.arcane.iris.core.tooling; import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.PackModuleSet; import art.arcane.iris.spi.IrisPlatform; import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.IrisServices; import com.volmit.ModuleLog; +import com.volmit.host.FeatureCatalog; +import com.volmit.host.LoadedPack; +import com.volmit.service.Providers; +import com.volmit.service.Service; +import com.volmit.tooling.world.ToolWorlds; import org.junit.After; import org.junit.Before; import org.junit.Rule; @@ -14,6 +21,7 @@ import java.io.File; import java.io.IOException; import java.io.InterruptedIOException; import java.nio.file.Path; +import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -138,6 +146,45 @@ public class IrisToolPackTest { assertFalse(output.startsWith(packFolder.toPath())); } + @Test + public void aPlatformWithoutToolWorldsAnswersThatTheyAreNotSupported() { + IrisServices.remove(ToolWorldsHost.class); + + ToolWorlds worlds = pack.worlds(); + + assertSame(UnsupportedToolWorlds.INSTANCE, worlds); + assertTrue(worlds.find("any").isEmpty()); + } + + @Test + public void aPlatformWithToolWorldsAnswersWithThoseOfThePacksFolder() { + ToolWorlds overworldWorlds = mock(ToolWorlds.class); + IrisServices.register(ToolWorldsHost.class, (ToolWorldsHost) packName -> "overworld".equals(packName) ? overworldWorlds : null); + try { + assertSame(overworldWorlds, pack.worlds()); + } finally { + IrisServices.remove(ToolWorldsHost.class); + } + } + + @Test + public void servicesAreTheProvidersOfThePacksModules() { + Probe probe = new Probe() { }; + FeatureCatalog catalog = mock(FeatureCatalog.class); + LoadedPack loaded = mock(LoadedPack.class); + PackModuleSet modules = mock(PackModuleSet.class); + when(catalog.services(Probe.class)).thenReturn(List.of(probe)); + when(loaded.catalog()).thenReturn(catalog); + when(modules.pack()).thenReturn(loaded); + when(data.getModules()).thenReturn(modules); + + assertEquals(List.of(probe), pack.services(Probe.class)); + } + + @Service(Providers.ALL) + interface Probe { + } + @Test public void theObjectCodecReadsAndWritesIobFiles() { assertEquals(".iob", pack.objects().extension()); diff --git a/core/src/test/java/art/arcane/iris/core/tooling/RecordingSender.java b/core/src/test/java/art/arcane/iris/core/tooling/RecordingSender.java index 98dc3f25d..26d6dafae 100644 --- a/core/src/test/java/art/arcane/iris/core/tooling/RecordingSender.java +++ b/core/src/test/java/art/arcane/iris/core/tooling/RecordingSender.java @@ -1,5 +1,7 @@ package art.arcane.iris.core.tooling; +import com.volmit.tooling.world.ToolPlayer; + import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -39,6 +41,11 @@ final class RecordingSender implements ToolingSender { return Optional.empty(); } + @Override + public Optional player() { + return Optional.empty(); + } + @Override public boolean isOperator() { return operator; 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 index 83fb1658d..77701f55e 100644 --- a/core/src/test/java/art/arcane/iris/core/tooling/StructureCommandsTest.java +++ b/core/src/test/java/art/arcane/iris/core/tooling/StructureCommandsTest.java @@ -2,7 +2,8 @@ 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.modules.jigsaw.JigsawModule; +import art.arcane.iris.core.structure.FakePlatformStructures; import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.engine.mantle.components.StructureModule; import art.arcane.iris.engine.object.structure.IrisStructure; @@ -51,7 +52,7 @@ public class StructureCommandsTest { packFolder = temporaryFolder.newFolder("overworld"); data = mock(IrisData.class); - ModuleResourceFixture.serveModules(data, new StructureModelModule(), new StructureModule()); + ModuleResourceFixture.serveModules(data, new JigsawModule(), new StructureModule()); when(data.getDataFolder()).thenReturn(packFolder); IrisStructure emptyCastle = new IrisStructure(); emptyCastle.setStartPool("ghost-pool"); @@ -70,7 +71,9 @@ public class StructureCommandsTest { public List names() { return List.of("overworld"); } - }, Runnable::run, Optional::empty); + }, Runnable::run, Optional::empty, () -> Optional.of(new FakePlatformStructures() + .withStructures("minecraft:village", "example:castle") + .withStructureSets("minecraft:villages"))); } @After diff --git a/core/src/test/java/art/arcane/iris/core/tooling/StructureIndexOnStartTest.java b/core/src/test/java/art/arcane/iris/core/tooling/StructureIndexOnStartTest.java new file mode 100644 index 000000000..fbeebe05c --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/tooling/StructureIndexOnStartTest.java @@ -0,0 +1,61 @@ +package art.arcane.iris.core.tooling; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.ModuleResourceFixture; +import art.arcane.iris.modules.jigsaw.JigsawModule; +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.IrisServices; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.PlatformStructures; +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.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +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 StructureIndexOnStartTest { + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Before + @After + public void withoutPlatformStructures() { + IrisServices.remove(PlatformStructures.class); + } + + @Test + public void writeOnceWaitsForPlatformStructuresThenWritesOnce() throws Exception { + File pack = temporaryFolder.newFolder("pack"); + IrisData data = mock(IrisData.class); + PlatformStructures platform = mock(PlatformStructures.class); + ModuleResourceFixture.serveModules(data, new JigsawModule(), new StructureModule()); + when(data.getDataFolder()).thenReturn(pack); + ModuleResourceFixture.serve(data).resource(StructureResources.STRUCTURES, "castle", new IrisStructure()); + when(platform.structures()).thenReturn(List.of(ResourceId.parse("minecraft:village"), ResourceId.parse("example:castle"))); + when(platform.structureSets()).thenReturn(List.of(ResourceId.parse("minecraft:villages"))); + + assertNull(StructureIndexOnStart.writeOnce(data)); + + IrisServices.register(PlatformStructures.class, platform); + File index = StructureIndexOnStart.writeOnce(data); + + assertEquals(new File(pack, ".iris/structure-index.json"), index); + assertTrue(index.isFile()); + assertNull(StructureIndexOnStart.writeOnce(data)); + verify(platform, times(1)).structures(); + verify(platform, times(1)).structureSets(); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/tooling/UnsupportedToolWorldsTest.java b/core/src/test/java/art/arcane/iris/core/tooling/UnsupportedToolWorldsTest.java new file mode 100644 index 000000000..028eddb9a --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/tooling/UnsupportedToolWorldsTest.java @@ -0,0 +1,31 @@ +package art.arcane.iris.core.tooling; + +import com.volmit.tooling.world.ToolWorld; +import com.volmit.tooling.world.ToolWorldListener; +import com.volmit.tooling.world.ToolWorldSpec; +import org.junit.Test; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +public class UnsupportedToolWorldsTest { + @Test + public void openingFailsAndSaysThatToolWorldsAreNotSupportedYet() { + ToolWorldSpec spec = new ToolWorldSpec("scratch", (chunkX, chunkZ, canvas) -> { }, new ToolWorldListener() { }); + + CompletableFuture opened = UnsupportedToolWorlds.INSTANCE.open(spec); + + ExecutionException failure = assertThrows(ExecutionException.class, opened::get); + assertTrue(failure.getCause() instanceof UnsupportedOperationException); + assertEquals("Tool worlds are not supported on this platform yet", failure.getCause().getMessage()); + } + + @Test + public void nothingIsFound() { + assertTrue(UnsupportedToolWorlds.INSTANCE.find("scratch").isEmpty()); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/framework/IrisStructureLocatorContractTest.java b/core/src/test/java/art/arcane/iris/engine/framework/IrisStructureLocatorContractTest.java index b32b754e7..84f75b89a 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/IrisStructureLocatorContractTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/IrisStructureLocatorContractTest.java @@ -24,18 +24,18 @@ import com.google.gson.Gson; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.core.modules.ModuleResourceFixture; +import art.arcane.iris.modules.jigsaw.JigsawModule; +import art.arcane.iris.engine.mantle.components.StructureModule; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.structure.StructureGraphCatalog; -import art.arcane.iris.engine.object.value.IrisDirection; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; +import com.volmit.geometry.BlockPosition; +import art.arcane.iris.engine.framework.structure.JigsawStructureAssembly; 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 art.arcane.iris.builtin.structure.NativeStructureSource; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.iris.builtin.structure.StructureAnchorMode; import art.arcane.iris.builtin.structure.StructurePlacement; @@ -46,7 +46,15 @@ import art.arcane.volmlib.util.math.RNG; import com.volmit.host.ModuleLogs; import org.junit.Test; +import com.volmit.world.PackWorld; + +import java.util.ArrayList; +import java.util.List; import java.util.Set; +import art.arcane.iris.engine.framework.structure.assembly.AssembledPiece; +import art.arcane.iris.engine.framework.structure.assembly.PieceTurn; +import art.arcane.iris.engine.framework.structure.assembly.StructureStamp; +import com.volmit.resource.ResourceId; import art.arcane.iris.engine.object.TestSettings; import static art.arcane.iris.engine.framework.StructurePlacementFixtures.placement; @@ -82,16 +90,15 @@ public class IrisStructureLocatorContractTest { @Test public void isPlacedIsFalseForNullOrEmptyKey() { - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - assertFalse(IrisStructureLocator.isPlaced(engine, null)); - assertFalse(IrisStructureLocator.isPlaced(engine, "")); + StructureTestWorld world = new StructureTestWorld(); + assertFalse(IrisStructureLocator.isPlaced(world, null)); + assertFalse(IrisStructureLocator.isPlaced(world, "")); } @Test public void locatablePlacementsExcludeDisabledDensityConfigurations() { - Engine disabled = densityEngine(0.0, false, -64, 384, -2032, 2032); - Engine active = densityEngine(0.01, false, -64, 384, -2032, 2032); + StructureTestWorld disabled = densityWorld(0.0, false, -64, 384, -2032, 2032); + StructureTestWorld active = densityWorld(0.01, false, -64, 384, -2032, 2032); assertTrue(IrisStructureLocator.isPlaced(disabled, "test:density")); assertFalse(IrisStructureLocator.hasLocatablePlacement(disabled, "test:density")); @@ -104,12 +111,10 @@ public class IrisStructureLocatorContractTest { @Test public void locatablePlacementsExcludeEveryDistributionOutsideWorldHeight() { - Engine randomSpread = densityEngine(1.0, false, -64, 384, 400, 500); - TestSettings.with(StructurePlacementScope.placementsOf(randomSpread.getDimension()).get(0), - "distribution", StructureDistribution.RANDOM_SPREAD); - Engine concentricRings = densityEngine(1.0, false, -64, 384, 400, 500); - TestSettings.with(StructurePlacementScope.placementsOf(concentricRings.getDimension()).get(0), - "distribution", StructureDistribution.CONCENTRIC_RINGS); + StructureTestWorld randomSpread = densityWorld(1.0, false, -64, 384, 400, 500); + TestSettings.with(densityPlacement(randomSpread), "distribution", StructureDistribution.RANDOM_SPREAD); + StructureTestWorld concentricRings = densityWorld(1.0, false, -64, 384, 400, 500); + TestSettings.with(densityPlacement(concentricRings), "distribution", StructureDistribution.CONCENTRIC_RINGS); assertFalse(IrisStructureLocator.hasLocatablePlacement(randomSpread, "test:density")); assertFalse(IrisStructureLocator.hasLocatablePlacement(concentricRings, "test:density")); @@ -118,8 +123,8 @@ public class IrisStructureLocatorContractTest { @Test public void locatableIndexIncludesAliasesAndSeparatesEditableFromNativePlacements() { IrisData data = mock(IrisData.class); + ModuleResourceFixture.serveModules(data, new JigsawModule(), new StructureModule()); IrisStructure structure = new IrisStructure(); - structure.setLoadKey("test:city"); structure.setVanillaSource("source:city"); ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "test:city_definition", structure); @@ -127,23 +132,11 @@ public class IrisStructureLocatorContractTest { withAdded(editable, "structures", "test:city_definition"); StructurePlacement nativePlacement = new StructurePlacement(); withAdded(nativePlacement, "nativeStructures", nativeSource("source:native_city")); - IrisDimension dimension = mock(IrisDimension.class); - KList placements = new KList<>(); - placements.add(editable); - placements.add(nativePlacement); - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(engine.getData()).thenReturn(data); - when(engine.getDimension()).thenReturn(dimension); - when(engine.getMinHeight()).thenReturn(-64); - when(engine.getHeight()).thenReturn(384); - when(dimension.getModuleSettings()).thenReturn(declaring(placements)); - when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); - when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); + StructureTestWorld engine = jigsawWorld(data).dimension(editable, nativePlacement); - assertEquals(Set.of("test:city_definition", "test:city", "source:city", "source:native_city"), + assertEquals(Set.of("test:city_definition", "source:city", "source:native_city"), IrisStructureLocator.locatableKeys(engine)); - assertEquals(Set.of("test:city_definition", "test:city", "source:city"), + assertEquals(Set.of("test:city_definition", "source:city"), IrisStructureLocator.locatableEditableKeys(engine)); assertEquals(Set.of("source:native_city"), IrisStructureLocator.locatableNativeKeys(engine)); assertTrue(IrisStructureLocator.hasLocatableEditablePlacement(engine, "SOURCE:CITY")); @@ -160,18 +153,10 @@ public class IrisStructureLocatorContractTest { @Test public void nativeStructureReplacementSuppressesOnlyItsRegisteredSource() { IrisData data = mock(IrisData.class); - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - IrisDimension dimension = mock(IrisDimension.class); + ModuleResourceFixture.serveModules(data, new JigsawModule(), new StructureModule()); StructurePlacement placement = placement("nativeSuppression", NativeStructureSuppression.REPLACE_SOURCE); withAdded(placement, "nativeStructures", nativeSource("minecraft:ancient_city")); - KList placements = new KList<>(); - placements.add(placement); - when(engine.getData()).thenReturn(data); - when(engine.getDimension()).thenReturn(dimension); - when(dimension.getModuleSettings()).thenReturn(declaring(placements)); - when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); - when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); + StructureTestWorld engine = jigsawWorld(data).dimension(placement); assertTrue(IrisStructureLocator.isPlaced(engine, "minecraft:ancient_city")); assertTrue(IrisStructureLocator.suppressesVanilla(engine, "minecraft:ancient_city")); @@ -180,48 +165,36 @@ public class IrisStructureLocatorContractTest { @Test public void suppressesVanillaIsFalseForNullOrEmptyKey() { - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - assertFalse(IrisStructureLocator.suppressesVanilla(engine, null)); - assertFalse(IrisStructureLocator.suppressesVanilla(engine, "")); + StructureTestWorld world = new StructureTestWorld(); + assertFalse(IrisStructureLocator.suppressesVanilla(world, null)); + assertFalse(IrisStructureLocator.suppressesVanilla(world, "")); } @Test public void vanillaSourceRequiresExplicitDimensionSuppression() { IrisData data = mock(IrisData.class); + ModuleResourceFixture.serveModules(data, new JigsawModule(), new StructureModule()); IrisStructure structure = new IrisStructure(); - structure.setLoadKey("test:city"); structure.setVanillaSource("minecraft:ancient_city"); ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "test:city", structure); registerSinglePieceGraph(data, structure, "test:city"); StructurePlacement placement = new StructurePlacement(); withAdded(placement, "structures", "test:city"); - IrisDimension dimension = mock(IrisDimension.class); - KList placements = new KList<>(); - placements.add(placement); - when(dimension.getModuleSettings()).thenReturn(declaring(placements)); - when(dimension.getAllRegions(any())).thenReturn(new KList<>()); - when(dimension.getReachableBiomes(any())).thenReturn(new KList<>()); - - Engine engine = mock(Engine.class); - - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(engine.getData()).thenReturn(data); - when(engine.getDimension()).thenReturn(dimension); + StructureTestWorld engine = jigsawWorld(data).dimension(placement); assertTrue(IrisStructureLocator.isPlaced(engine, "minecraft:ancient_city")); assertFalse(IrisStructureLocator.suppressesVanilla(engine, "minecraft:ancient_city")); TestSettings.with(placement, "nativeSuppression", NativeStructureSuppression.REPLACE_SOURCE); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); + engine = jigsawWorld(data).dimension(placement); assertTrue(IrisStructureLocator.suppressesVanilla(engine, "minecraft:ancient_city")); } @Test public void regionReplacementFailsInsteadOfFallingBackToNative() { IrisData data = mock(IrisData.class); + ModuleResourceFixture.serveModules(data, new JigsawModule(), new StructureModule()); IrisStructure structure = new IrisStructure(); - structure.setLoadKey("test:city"); structure.setVanillaSource("minecraft:ancient_city"); ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "test:city", structure); registerSinglePieceGraph(data, structure, "test:city"); @@ -229,18 +202,7 @@ public class IrisStructureLocatorContractTest { StructurePlacement placement = new StructurePlacement(); withAdded(placement, "structures", "test:city"); TestSettings.with(placement, "nativeSuppression", NativeStructureSuppression.REPLACE_SOURCE); - IrisRegion region = mock(IrisRegion.class); - when(region.getModuleSettings()).thenReturn(declaring(new KList().qadd(placement))); - IrisDimension dimension = mock(IrisDimension.class); - when(dimension.getModuleSettings()).thenReturn(declaring(new KList<>())); - when(dimension.getAllRegions(any())).thenReturn(new KList().qadd(region)); - when(dimension.getReachableBiomes(any())).thenReturn(new KList<>()); - - Engine engine = mock(Engine.class); - - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(engine.getData()).thenReturn(data); - when(engine.getDimension()).thenReturn(dimension); + StructureTestWorld engine = jigsawWorld(data).region(StructureTestWorld.REGION, placement); assertReplacementFailure( () -> IrisStructureLocator.suppressesVanilla(engine, "minecraft:ancient_city"), @@ -250,21 +212,21 @@ public class IrisStructureLocatorContractTest { @Test public void geometryFailureFailsInsteadOfFallingBackToNative() { IrisData data = mock(IrisData.class); + ModuleResourceFixture.serveModules(data, new JigsawModule(), new StructureModule()); IrisStructure structure = new IrisStructure() .setStartPool("test:start") .setMaxDepth(1) .setMaxSizeChunks(1) .setVanillaSource("minecraft:ancient_city"); - structure.setLoadKey("test:city"); IrisJigsawConnector source = new IrisJigsawConnector() - .setPosition(new IrisPosition(0, 0, 0)) - .setDirection(IrisDirection.EAST_POSITIVE_X) + .setPosition(new BlockPosition(0, 0, 0)) + .setDirection(JigsawDirection.EAST_POSITIVE_X) .setPool("test:target") .setName("source") .setTargetName("door"); IrisJigsawConnector target = new IrisJigsawConnector() - .setPosition(new IrisPosition(50, 0, 0)) - .setDirection(IrisDirection.WEST_NEGATIVE_X) + .setPosition(new BlockPosition(50, 0, 0)) + .setDirection(JigsawDirection.WEST_NEGATIVE_X) .setPool("test:target") .setName("door") .setTargetName("unused"); @@ -276,33 +238,17 @@ public class IrisStructureLocatorContractTest { startPool.getPieces().add(new IrisJigsawPieceEntry("test:start-piece", 1)); IrisJigsawPool targetPool = new IrisJigsawPool(); targetPool.getPieces().add(new IrisJigsawPieceEntry("test:target-piece", 1)); - IrisObject startObject = mock(IrisObject.class); - IrisObject targetObject = mock(IrisObject.class); - when(startObject.getW()).thenReturn(1); - when(startObject.getH()).thenReturn(1); - when(startObject.getD()).thenReturn(1); - when(targetObject.getW()).thenReturn(100); - when(targetObject.getH()).thenReturn(1); - when(targetObject.getD()).thenReturn(1); + ModuleResourceFixture.of(data).object("test:start-object", 1, 1, 1).object("test:target-object", 100, 1, 1); ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "test:city", structure); ModuleResourceFixture.of(data).resource(StructureResources.POOLS, "test:start", startPool); ModuleResourceFixture.of(data).resource(StructureResources.POOLS, "test:target", targetPool); ModuleResourceFixture.of(data).resource(StructureResources.PIECES, "test:start-piece", startPiece); ModuleResourceFixture.of(data).resource(StructureResources.PIECES, "test:target-piece", targetPiece); - when(data.load(IrisObject.class, "test:start-object", false)).thenReturn(startObject); - when(data.load(IrisObject.class, "test:target-object", false)).thenReturn(targetObject); - assertFalse(StructureGraphCatalog.compile(data, structure, ModuleLogs.discarding()).isAssemblyViable()); + assertFalse(StructureGraphCatalog.compile(data.getPackResources(), "test:city", structure, ModuleLogs.discarding()).isAssemblyViable()); StructurePlacement placement = placement("nativeSuppression", NativeStructureSuppression.REPLACE_SOURCE); withAdded(placement, "structures", "test:city"); - IrisDimension dimension = mock(IrisDimension.class); - when(dimension.getModuleSettings()).thenReturn(declaring(new KList().qadd(placement))); - when(dimension.getAllRegions(any())).thenReturn(new KList<>()); - when(dimension.getReachableBiomes(any())).thenReturn(new KList<>()); - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(engine.getData()).thenReturn(data); - when(engine.getDimension()).thenReturn(dimension); + StructureTestWorld engine = jigsawWorld(data).dimension(placement); assertReplacementFailure( () -> IrisStructureLocator.suppressesVanilla(engine, "minecraft:ancient_city"), @@ -312,20 +258,13 @@ public class IrisStructureLocatorContractTest { @Test public void missingVanillaSourceFailsInsteadOfFallingBackToNative() { IrisData data = mock(IrisData.class); + ModuleResourceFixture.serveModules(data, new JigsawModule(), new StructureModule()); IrisStructure structure = new IrisStructure(); - structure.setLoadKey("test:city"); ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "test:city", structure); registerSinglePieceGraph(data, structure, "test:city"); StructurePlacement placement = placement("nativeSuppression", NativeStructureSuppression.REPLACE_SOURCE); withAdded(placement, "structures", "test:city"); - IrisDimension dimension = mock(IrisDimension.class); - when(dimension.getModuleSettings()).thenReturn(declaring(new KList().qadd(placement))); - when(dimension.getAllRegions(any())).thenReturn(new KList<>()); - when(dimension.getReachableBiomes(any())).thenReturn(new KList<>()); - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(engine.getData()).thenReturn(data); - when(engine.getDimension()).thenReturn(dimension); + StructureTestWorld engine = jigsawWorld(data).dimension(placement); assertReplacementFailure( () -> IrisStructureLocator.suppressesVanilla(engine, "minecraft:ancient_city"), @@ -335,17 +274,11 @@ public class IrisStructureLocatorContractTest { @Test public void missingNonReplacementStructureFailsInsteadOfBeingSkipped() { IrisData data = mock(IrisData.class); + ModuleResourceFixture.serveModules(data, new JigsawModule(), new StructureModule()); ModuleResourceFixture.serve(data); StructurePlacement placement = new StructurePlacement(); withAdded(placement, "structures", "test:missing"); - IrisDimension dimension = mock(IrisDimension.class); - when(dimension.getModuleSettings()).thenReturn(declaring(new KList().qadd(placement))); - when(dimension.getAllRegions(any())).thenReturn(new KList<>()); - when(dimension.getReachableBiomes(any())).thenReturn(new KList<>()); - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(engine.getData()).thenReturn(data); - when(engine.getDimension()).thenReturn(dimension); + StructureTestWorld engine = jigsawWorld(data).dimension(placement); assertReplacementFailure( () -> IrisStructureLocator.isPlaced(engine, "test:missing"), @@ -353,10 +286,10 @@ public class IrisStructureLocatorContractTest { } @Test - public void placementResolutionRejectsAnUnboundEngine() { + public void placementResolutionRejectsAMissingWorld() { assertReplacementFailure( () -> IrisStructureLocator.resolvePlacement(null, new StructurePlacement(), 0, 0), - "fully bound engine"); + "requires a world"); } @Test @@ -394,54 +327,53 @@ public class IrisStructureLocatorContractTest { @Test public void locateReturnsNotFoundForNullOrEmptyKey() { - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); + StructureTestWorld world = new StructureTestWorld(); assertEquals(IrisStructureLocator.LocateStatus.NOT_FOUND, - IrisStructureLocator.locate(engine, null, 0, 0, 100).status()); + IrisStructureLocator.locate(world, null, 0, 0, 100).status()); assertEquals(IrisStructureLocator.LocateStatus.NOT_FOUND, - IrisStructureLocator.locate(engine, "", 0, 0, 100).status()); + IrisStructureLocator.locate(world, "", 0, 0, 100).status()); } @Test public void zeroDensityLocateReturnsWithoutScanningPlacementGraphs() { - Engine engine = densityEngine(0.0, false, -64, 384, -2032, 2032); + StructureTestWorld world = densityWorld(0.0, false, -64, 384, -2032, 2032); IrisStructureLocator.LocateResult result = - IrisStructureLocator.locate(engine, "test:density", 0, 0, 100); + IrisStructureLocator.locate(world, "test:density", 0, 0, 100); assertEquals(IrisStructureLocator.LocateStatus.NOT_FOUND, result.status()); - verify(engine, never()).getComplex(); + assertEquals(0, world.placementScans()); } @Test public void impossibleDensityHeightBandReturnsWithoutScanningPlacementGraphs() { - Engine engine = densityEngine(1.0, true, -64, 384, 500, 600); + StructureTestWorld world = densityWorld(1.0, true, -64, 384, 500, 600); IrisStructureLocator.LocateResult result = - IrisStructureLocator.locate(engine, "test:density", 0, 0, 100); + IrisStructureLocator.locate(world, "test:density", 0, 0, 100); assertEquals(IrisStructureLocator.LocateStatus.NOT_FOUND, result.status()); - verify(engine, never()).getComplex(); + assertEquals(0, world.placementScans()); } @Test public void densityLocateReportsSafetyLimitAfterFixedCandidateBudget() { - Engine engine = densityEngine(1.0, false, -64, 384, -2032, 2032); + StructureTestWorld world = densityWorld(1.0, false, -64, 384, -2032, 2032); IrisStructureLocator.LocateResult result = - IrisStructureLocator.locate(engine, "test:density", 0, 0, 2048); + IrisStructureLocator.locate(world, "test:density", 0, 0, 2048); assertEquals(IrisStructureLocator.LocateStatus.SEARCH_LIMIT_REACHED, result.status()); assertFalse(result.found()); - verify(engine, times(4_096)).getComplex(); + assertEquals(4_096, world.placementScans()); } @Test public void densityLocateDoesNotReturnPartialRingWinnerAtSafetyLimit() { - Engine engine = densityEngine(1.0, false, -64, 384, -2032, 2032); + StructureTestWorld world = densityWorld(1.0, false, -64, 384, -2032, 2032); IrisStructureLocator.LocateResult result = IrisStructureLocator.locate( - engine, "test:density", 0, 0, 2048, + world, "test:density", 0, 0, 2048, (chunkX, chunkZ) -> chunkX == 31 && chunkZ == 31 || chunkX == 0 && chunkZ == 32); @@ -451,7 +383,7 @@ public class IrisStructureLocatorContractTest { @Test public void zeroRadiusDoesNotSearchAdjacentDensityChunks() { - Engine engine = densityEngine(1.0, false, -64, 384, -2032, 2032); + StructureTestWorld engine = densityWorld(1.0, false, -64, 384, -2032, 2032); IrisStructureLocator.LocateResult result = IrisStructureLocator.locate( engine, "test:density", 0, 0, 0, @@ -462,10 +394,8 @@ public class IrisStructureLocatorContractTest { @Test public void locateRanksEditableStartsByResolvedBlockOrigin() { - Engine engine = densityEngine(1.0, false, -64, 384, -2032, 2032); - when(engine.getHeight(anyInt(), anyInt(), eq(true))).thenReturn(128); - when(engine.getDimension().getFluidHeight()).thenReturn(63); - StructurePlacement placement = StructurePlacementScope.placementsOf(engine.getDimension()).get(0); + StructureTestWorld engine = densityWorld(1.0, false, -64, 384, -2032, 2032).highest((x, z) -> 128).fluidHeight(63); + StructurePlacement placement = densityPlacement(engine); NearestScenario scenario = nearestEqualChunkDistanceScenario(engine, placement); assertNotNull(scenario); @@ -489,10 +419,7 @@ public class IrisStructureLocatorContractTest { @Test public void searchableDensityRequiresPositiveProbabilityAndWorldHeightOverlap() { - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(engine.getMinHeight()).thenReturn(-64); - when(engine.getHeight()).thenReturn(384); + StructureTestWorld engine = new StructureTestWorld(); StructurePlacement placement = new StructurePlacement(); TestSettings.with(placement, "distribution", StructureDistribution.DENSITY); TestSettings.with(placement, "minHeight", -32); @@ -512,27 +439,28 @@ public class IrisStructureLocatorContractTest { @Test public void placementIndexIsKeptPerWorld() { IrisData sharedData = mock(IrisData.class); - Engine firstEngine = emptyEngine(sharedData); - Engine secondEngine = emptyEngine(sharedData); - Set firstIndex = IrisStructureLocator.placedKeys(firstEngine); - assertSame(firstIndex, IrisStructureLocator.placedKeys(firstEngine)); - assertNotSame(firstIndex, IrisStructureLocator.placedKeys(secondEngine)); + ModuleResourceFixture.serveModules(sharedData, new JigsawModule(), new StructureModule()); + StructureTestWorld firstWorld = emptyWorld(sharedData); + StructureTestWorld secondWorld = emptyWorld(sharedData); + Set firstIndex = IrisStructureLocator.placedKeys(firstWorld); + assertSame(firstIndex, IrisStructureLocator.placedKeys(firstWorld)); + assertNotSame(firstIndex, IrisStructureLocator.placedKeys(secondWorld)); - when(firstEngine.getGeneration()).thenReturn(new EngineGeneration(firstEngine)); - assertNotSame("a new world builds its own index", firstIndex, IrisStructureLocator.placedKeys(firstEngine)); + StructureTestWorld restartedWorld = emptyWorld(sharedData); + assertNotSame("a new world builds its own index", firstIndex, IrisStructureLocator.placedKeys(restartedWorld)); } @Test public void assembledBoundsMustFitVerticallyAndHorizontally() { - KList fitting = new KList<>(); + KList fitting = new KList<>(); fitting.add(piece(-4, 1, -4, 4, 20, 4)); assertTrue(IrisStructureLocator.fitsWorldBounds(fitting, 0, 20, 0, 0, 4)); - KList belowWorld = new KList<>(); + KList belowWorld = new KList<>(); belowWorld.add(piece(-4, -1, -4, 4, 20, 4)); assertFalse(IrisStructureLocator.fitsWorldBounds(belowWorld, 0, 20, 0, 0, 4)); - KList outsideRadius = new KList<>(); + KList outsideRadius = new KList<>(); outsideRadius.add(piece(-4, 1, -4, 5, 20, 4)); assertFalse(IrisStructureLocator.fitsWorldBounds(outsideRadius, 0, 20, 0, 0, 4)); } @@ -556,9 +484,7 @@ public class IrisStructureLocatorContractTest { String selectedKey = IrisStructureLocator.selectStructureKey(placement, selectsLast); assertEquals("test:second", selectedKey); - IrisStructure selected = new IrisStructure(); - selected.setLoadKey("test:second"); - selected.setVanillaSource("minecraft:second"); + StructureStamp selected = new StructureStamp(ObjectPlaceMode.STRUCTURE_PIECE, List.of(), List.of(), "minecraft:second"); IrisStructureLocator.ResolvedPlacement resolved = new IrisStructureLocator.ResolvedPlacement( placement, selectedKey, selected, new KList<>(), selectsLast, 0, 64, 0, false); assertFalse(IrisStructureLocator.matchesResolved(resolved, "test:first")); @@ -573,71 +499,64 @@ public class IrisStructureLocatorContractTest { TestSettings.with(placement, "minHeight", -10); TestSettings.with(placement, "maxHeight", 10); - KList movable = new KList<>(); + KList movable = new KList<>(); movable.add(piece(-4, -10, -4, 4, 5, 4)); assertEquals(Integer.valueOf(10), IrisStructureLocator.resolveVerticalShift(movable, placement, -10, 0, 319)); - KList tooTall = new KList<>(); + KList tooTall = new KList<>(); tooTall.add(piece(-4, -100, -4, 4, 400, 4)); assertNull(IrisStructureLocator.resolveVerticalShift(tooTall, placement, 0, 0, 319)); TestSettings.with(placement, "underground", false); - KList clippedSurface = new KList<>(); + KList clippedSurface = new KList<>(); clippedSurface.add(piece(-4, 300, -4, 4, 330, 4)); assertNull(IrisStructureLocator.resolveVerticalShift(clippedSurface, placement, 300, -64, 319)); } @Test public void caveAssemblyBoundsAlignToTheRequestedAnchorFace() { - KList pieces = new KList<>(); + KList pieces = new KList<>(); pieces.add(piece(-2, 10, -2, 2, 14, 2)); StructurePlacement placement = new StructurePlacement(); TestSettings.with(placement, "anchor", StructureAnchorMode.CAVE_FLOOR); - KList floor = IrisStructureLocator.alignCavePieces(pieces, placement, 40); - assertEquals(40, floor.getFirst().getMinY()); - assertEquals(44, floor.getFirst().getMaxY()); + KList floor = IrisStructureLocator.alignCavePieces(pieces, placement, 40); + assertEquals(40, floor.getFirst().minY()); + assertEquals(44, floor.getFirst().maxY()); TestSettings.with(placement, "anchor", StructureAnchorMode.CAVE_CEILING); - KList ceiling = IrisStructureLocator.alignCavePieces(pieces, placement, 40); - assertEquals(36, ceiling.getFirst().getMinY()); - assertEquals(40, ceiling.getFirst().getMaxY()); + KList ceiling = IrisStructureLocator.alignCavePieces(pieces, placement, 40); + assertEquals(36, ceiling.getFirst().minY()); + assertEquals(40, ceiling.getFirst().maxY()); TestSettings.with(placement, "anchor", StructureAnchorMode.CAVE_CENTER); - KList center = IrisStructureLocator.alignCavePieces(pieces, placement, 40); - assertEquals(38, center.getFirst().getMinY()); - assertEquals(42, center.getFirst().getMaxY()); + KList center = IrisStructureLocator.alignCavePieces(pieces, placement, 40); + assertEquals(38, center.getFirst().minY()); + assertEquals(42, center.getFirst().maxY()); } @Test public void caveSearchabilityReservesVerticalBoundaryCells() { - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(engine.getMinHeight()).thenReturn(-64); - when(engine.getHeight()).thenReturn(384); + StructureTestWorld engine = new StructureTestWorld(); StructurePlacement placement = placement("distribution", StructureDistribution.DENSITY, "density", 1D, "anchor", StructureAnchorMode.CAVE_FLOOR, "minHeight", 319, "maxHeight", 319); assertFalse(IrisStructureLocator.isSearchableDensityPlacement(engine, placement)); TestSettings.with(placement, "minHeight", 318, "maxHeight", 318); assertTrue(IrisStructureLocator.isSearchableDensityPlacement(engine, placement)); - when(engine.getHeight()).thenReturn(2); + engine.height(2); TestSettings.with(placement, "minHeight", -2032, "maxHeight", 2032); assertFalse(IrisStructureLocator.isSearchableDensityPlacement(engine, placement)); } @Test public void undergroundAssemblyIsShiftedBelowEveryTerrainColumn() { - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(engine.getMinHeight()).thenReturn(-64); - when(engine.getHeight(anyInt(), anyInt(), eq(true))) - .thenAnswer(invocation -> invocation.getArgument(0) == 1 ? 140 : 164); + StructureTestWorld engine = new StructureTestWorld().highest((x, z) -> x == 1 ? 140 : 164); StructurePlacement placement = new StructurePlacement(); TestSettings.with(placement, "underground", true); TestSettings.with(placement, "minHeight", -64); TestSettings.with(placement, "maxHeight", 100); - KList pieces = new KList<>(); + KList pieces = new KList<>(); pieces.add(piece(0, 60, 0, 1, 80, 0)); assertEquals(Integer.valueOf(-5), IrisStructureLocator.resolveUndergroundBurialShift( @@ -651,16 +570,13 @@ public class IrisStructureLocatorContractTest { @Test public void undergroundBurialIncludesForceCarveCeiling() { - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(engine.getMinHeight()).thenReturn(-64); - when(engine.getHeight(anyInt(), anyInt(), eq(true))).thenReturn(164); + StructureTestWorld engine = new StructureTestWorld().highest((x, z) -> 164); StructurePlacement placement = new StructurePlacement(); TestSettings.with(placement, "underground", true); TestSettings.with(placement, "minHeight", -64); TestSettings.with(placement, "maxHeight", 100); TestSettings.with(placement, "terrain", forceCarve("\"horizontalPadding\":2,\"ceilingPadding\":20,\"shape\":\"ERODED\"")); - KList pieces = new KList<>(); + KList pieces = new KList<>(); pieces.add(piece(0, 60, 0, 1, 80, 1)); assertEquals(Integer.valueOf(-14), IrisStructureLocator.resolveUndergroundBurialShift( @@ -681,39 +597,36 @@ public class IrisStructureLocatorContractTest { @Test public void zeroForceCarvePaddingDoesNotExpandTheBurialEnvelope() { - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(engine.getMinHeight()).thenReturn(-64); - when(engine.getHeight(anyInt(), anyInt(), eq(true))).thenReturn(164); + List heightReads = new ArrayList<>(); + StructureTestWorld engine = new StructureTestWorld().highest((x, z) -> { + heightReads.add(x + "," + z); + return 164; + }); StructurePlacement placement = placement("underground", true, "minHeight", -64, "maxHeight", 100, "terrain", forceCarve("\"shape\":\"ROUNDED\",\"horizontalPadding\":0,\"ceilingPadding\":0")); - KList pieces = new KList<>(); + KList pieces = new KList<>(); pieces.add(piece(4, 60, 7, 4, 80, 7)); assertEquals(Integer.valueOf(0), IrisStructureLocator.resolveUndergroundBurialShift( engine, pieces, placement, 60, -63, 319)); - verify(engine, times(1)).getHeight(4, 7, true); + assertEquals(List.of("4,7"), heightReads); } @Test public void exactYOnlyCoversPlacementPathsWithResolvedAbsoluteAnchors() { StructurePlacement placement = new StructurePlacement(); - IrisStructure structure = new IrisStructure(); - structure.setPlaceMode(ObjectPlaceMode.CENTER_HEIGHT); - KList onePiece = new KList<>(); + KList onePiece = new KList<>(); onePiece.add(piece(-4, 1, -4, 4, 20, 4)); - assertFalse(IrisStructureLocator.hasExactY(placement, structure, onePiece)); + assertFalse(IrisStructureLocator.hasExactY(placement, stamp(ObjectPlaceMode.CENTER_HEIGHT), onePiece)); - structure.setPlaceMode(ObjectPlaceMode.STRUCTURE_PIECE); - assertTrue(IrisStructureLocator.hasExactY(placement, structure, onePiece)); + assertTrue(IrisStructureLocator.hasExactY(placement, stamp(ObjectPlaceMode.STRUCTURE_PIECE), onePiece)); - structure.setPlaceMode(ObjectPlaceMode.CENTER_HEIGHT); TestSettings.with(placement, "underground", true); - assertTrue(IrisStructureLocator.hasExactY(placement, structure, onePiece)); + assertTrue(IrisStructureLocator.hasExactY(placement, stamp(ObjectPlaceMode.CENTER_HEIGHT), onePiece)); TestSettings.with(placement, "underground", false); - KList multiplePieces = new KList<>(onePiece); + KList multiplePieces = new KList<>(onePiece); multiplePieces.add(piece(5, 1, -4, 12, 20, 4)); - assertTrue(IrisStructureLocator.hasExactY(placement, structure, multiplePieces)); + assertTrue(IrisStructureLocator.hasExactY(placement, stamp(ObjectPlaceMode.CENTER_HEIGHT), multiplePieces)); } @Test @@ -733,7 +646,7 @@ public class IrisStructureLocatorContractTest { } private NearestScenario nearestEqualChunkDistanceScenario( - Engine engine, StructurePlacement placement) { + PackWorld engine, StructurePlacement placement) { int[][] chunks = { {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1} @@ -778,27 +691,34 @@ public class IrisStructureLocatorContractTest { return dx * dx + dz * dz; } - private PlacedStructurePiece piece(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { - return new PlacedStructurePiece(null, null, 0, 0, 0, null, minX, minY, minZ, maxX, maxY, maxZ); + private AssembledPiece piece(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { + return new AssembledPiece(new ResourceId("test", "piece"), 0, 0, 0, PieceTurn.NONE, minX, minY, minZ, maxX, maxY, maxZ); } - private Engine emptyEngine(IrisData data) { - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - IrisDimension dimension = mock(IrisDimension.class); - when(engine.getData()).thenReturn(data); - when(engine.getDimension()).thenReturn(dimension); - when(dimension.getModuleSettings()).thenReturn(declaring(new KList<>())); - when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); - when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); - return engine; + private StructureStamp stamp(ObjectPlaceMode placeMode) { + return new StructureStamp(placeMode, List.of(), List.of(), ""); } - private Engine densityEngine(double density, boolean underground, int worldMin, int worldHeight, - int placementMin, int placementMax) { + private StructureTestWorld emptyWorld(IrisData data) { + return jigsawWorld(data).dimension(); + } + + /** A world whose pack is {@code data} and whose structures the jigsaw provider assembles. */ + private StructureTestWorld jigsawWorld(IrisData data) { + return new StructureTestWorld() + .resources(data.getPackResources()) + .assembling(new JigsawStructureAssembly(ModuleLogs.discarding())); + } + + private StructurePlacement densityPlacement(StructureTestWorld world) { + return world.dimensionPlacements().get(0); + } + + private StructureTestWorld densityWorld(double density, boolean underground, int worldMin, int worldHeight, + int placementMin, int placementMax) { IrisData data = mock(IrisData.class); + ModuleResourceFixture.serveModules(data, new JigsawModule(), new StructureModule()); IrisStructure structure = new IrisStructure(); - structure.setLoadKey("test:density"); ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "test:density", structure); registerSinglePieceGraph(data, structure, "test:density"); @@ -810,21 +730,13 @@ public class IrisStructureLocatorContractTest { TestSettings.with(placement, "minHeight", placementMin); TestSettings.with(placement, "maxHeight", placementMax); - Engine engine = mock(Engine.class); - - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - IrisDimension dimension = mock(IrisDimension.class); - KList placements = new KList<>(); - placements.add(placement); - when(engine.getData()).thenReturn(data); - when(engine.getDimension()).thenReturn(dimension); - when(engine.getSeedManager()).thenReturn(new SeedManager(77L)); - when(engine.getMinHeight()).thenReturn(worldMin); - when(engine.getHeight()).thenReturn(worldHeight); - when(dimension.getModuleSettings()).thenReturn(declaring(placements)); - when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); - when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); - return engine; + return jigsawWorld(data) + .highest((x, z) -> 0) + .fluidHeight(0) + .placementSeed(new SeedManager(77L).getMantle()) + .minY(worldMin) + .height(worldHeight) + .dimension(placement); } private void registerSinglePieceGraph(IrisData data, IrisStructure structure, String prefix) { @@ -836,13 +748,9 @@ public class IrisStructureLocatorContractTest { pool.getPieces().add(new IrisJigsawPieceEntry().setPiece(pieceKey).setWeight(1)); IrisJigsawPiece piece = new IrisJigsawPiece(); piece.setObject(objectKey); - IrisObject object = mock(IrisObject.class); - when(object.getW()).thenReturn(1); - when(object.getH()).thenReturn(1); - when(object.getD()).thenReturn(1); + ModuleResourceFixture.of(data).object(objectKey, 1, 1, 1); ModuleResourceFixture.of(data).resource(StructureResources.POOLS, poolKey, pool); ModuleResourceFixture.of(data).resource(StructureResources.PIECES, pieceKey, piece); - when(data.load(IrisObject.class, objectKey, false)).thenReturn(object); } private void assertReplacementFailure(Runnable operation, String expectedMessage) { diff --git a/core/src/test/java/art/arcane/iris/engine/framework/IrisStructurePlacementRingLocatorTest.java b/core/src/test/java/art/arcane/iris/engine/framework/IrisStructurePlacementRingLocatorTest.java index f5c28bbf9..28f019c8a 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/IrisStructurePlacementRingLocatorTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/IrisStructurePlacementRingLocatorTest.java @@ -1,26 +1,17 @@ package art.arcane.iris.engine.framework; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.builtin.structure.NativeStructureSource; import art.arcane.iris.builtin.structure.StructurePlacement; import art.arcane.iris.builtin.structure.StructureDistribution; -import art.arcane.volmlib.util.collection.KList; import org.junit.Test; import java.util.concurrent.atomic.AtomicBoolean; import static art.arcane.iris.engine.framework.StructurePlacementFixtures.placement; import static art.arcane.iris.engine.framework.StructurePlacementFixtures.nativeSource; -import static art.arcane.iris.engine.framework.StructurePlacementFixtures.declaring; import static art.arcane.iris.engine.framework.StructurePlacementFixtures.withAdded; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; public class IrisStructurePlacementRingLocatorTest { private static final String STRUCTURE_KEY = "test:manual_native"; @@ -28,18 +19,18 @@ public class IrisStructurePlacementRingLocatorTest { @Test public void zeroVanillaRingSearchesTheOriginPlacementCell() { StructurePlacement placement = randomPlacement("origin-cell", 24, 6); - Engine engine = engine(placement); - long seed = engine.getSeedManager().getMantle(); + StructureTestWorld world = world(placement); + long seed = world.seed(); int[] expected = StructurePlacementGrid.randomSpreadCellChunk( 0, 0, placement.spacing(), placement.separation(), StructurePlacementGrid.placementSalt(placement), seed); assertTrue(expected[0] != 0 || expected[1] != 0); IrisStructureLocator.LocateResult chunkRadius = IrisStructureLocator.locate( - engine, STRUCTURE_KEY, 0, 0, 0); + world, STRUCTURE_KEY, 0, 0, 0); IrisStructureLocator.LocateResult placementRadius = IrisStructureLocator.locateInPlacementRings( - engine, STRUCTURE_KEY, 0, 0, 0, (chunkX, chunkZ) -> true); + world, STRUCTURE_KEY, 0, 0, 0, (chunkX, chunkZ) -> true); assertEquals(IrisStructureLocator.LocateStatus.NOT_FOUND, chunkRadius.status()); assertEquals(IrisStructureLocator.LocateStatus.FOUND, placementRadius.status()); @@ -51,8 +42,8 @@ public class IrisStructurePlacementRingLocatorTest { public void mixedSpacingPlacementsShareTheSameVanillaRingIndex() { StructurePlacement small = randomPlacement("small-grid", 8, 2); StructurePlacement large = randomPlacement("large-grid", 40, 10); - Engine engine = engine(small, large); - long seed = engine.getSeedManager().getMantle(); + StructureTestWorld world = world(small, large); + long seed = world.seed(); int[] smallRingZero = candidate(small, seed, 0, 0); int[] largeRingZero = candidate(large, seed, 0, 0); int[] smallRingOne = candidate(small, seed, -1, -1); @@ -60,7 +51,7 @@ public class IrisStructurePlacementRingLocatorTest { IrisStructureLocator.LocateResult result = IrisStructureLocator.locateInPlacementRings( - engine, STRUCTURE_KEY, 0, 0, 1, + world, STRUCTURE_KEY, 0, 0, 1, (chunkX, chunkZ) -> { if (chunkX == smallRingOne[0] && chunkZ == smallRingOne[1]) { visitedLaterSmallRing.set(true); @@ -81,11 +72,11 @@ public class IrisStructurePlacementRingLocatorTest { StructurePlacement placement = placement("placementId", "concentric", "distribution", StructureDistribution.CONCENTRIC_RINGS, "ringCount", 1, "ringDistance", 32, "ringSpread", 1); withAdded(placement, "nativeStructures", nativeSource(STRUCTURE_KEY)); - Engine engine = engine(placement); + StructureTestWorld world = world(placement); IrisStructureLocator.LocateResult result = IrisStructureLocator.locateInPlacementRings( - engine, STRUCTURE_KEY, 0, 0, 0, (chunkX, chunkZ) -> true); + world, STRUCTURE_KEY, 0, 0, 0, (chunkX, chunkZ) -> true); assertEquals(IrisStructureLocator.LocateStatus.FOUND, result.status()); long chunkX = result.originX() >> 4; @@ -98,11 +89,11 @@ public class IrisStructurePlacementRingLocatorTest { StructurePlacement placement = placement("placementId", "density", "distribution", StructureDistribution.DENSITY, "density", 1.0); withAdded(placement, "nativeStructures", nativeSource(STRUCTURE_KEY)); - Engine engine = engine(placement); + StructureTestWorld world = world(placement); IrisStructureLocator.LocateResult result = IrisStructureLocator.locateInPlacementRings( - engine, STRUCTURE_KEY, 0, 0, 2048, + world, STRUCTURE_KEY, 0, 0, 2048, (chunkX, chunkZ) -> false); assertEquals(IrisStructureLocator.LocateStatus.SEARCH_LIMIT_REACHED, result.status()); @@ -113,10 +104,10 @@ public class IrisStructurePlacementRingLocatorTest { StructurePlacement placement = placement("placementId", "unbounded-concentric-rings", "distribution", StructureDistribution.CONCENTRIC_RINGS, "ringCount", Integer.MAX_VALUE, "ringDistance", 32, "ringSpread", 1); withAdded(placement, "nativeStructures", nativeSource(STRUCTURE_KEY)); - Engine engine = engine(placement); + StructureTestWorld world = world(placement); IrisStructureLocator.LocateResult result = IrisStructureLocator.locateInPlacementRings( - engine, STRUCTURE_KEY, 0, 0, 2048, (chunkX, chunkZ) -> false); + world, STRUCTURE_KEY, 0, 0, 2048, (chunkX, chunkZ) -> false); assertEquals(IrisStructureLocator.LocateStatus.SEARCH_LIMIT_REACHED, result.status()); } @@ -126,10 +117,10 @@ public class IrisStructurePlacementRingLocatorTest { StructurePlacement placement = placement("placementId", "unbounded-concentric-chunks", "distribution", StructureDistribution.CONCENTRIC_RINGS, "ringCount", Integer.MAX_VALUE, "ringDistance", 32, "ringSpread", 1); withAdded(placement, "nativeStructures", nativeSource(STRUCTURE_KEY)); - Engine engine = engine(placement); + StructureTestWorld world = world(placement); IrisStructureLocator.LocateResult result = IrisStructureLocator.locate( - engine, STRUCTURE_KEY, 0, 0, 2048, (chunkX, chunkZ) -> false); + world, STRUCTURE_KEY, 0, 0, 2048, (chunkX, chunkZ) -> false); assertEquals(IrisStructureLocator.LocateStatus.SEARCH_LIMIT_REACHED, result.status()); } @@ -149,26 +140,10 @@ public class IrisStructurePlacementRingLocatorTest { return placement; } - private static Engine engine(StructurePlacement... placements) { - IrisData data = mock(IrisData.class); - IrisDimension dimension = mock(IrisDimension.class); - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - KList configured = new KList<>(); - for (StructurePlacement placement : placements) { - configured.add(placement); - } - when(engine.getData()).thenReturn(data); - when(engine.getDimension()).thenReturn(dimension); - when(engine.getSeedManager()).thenReturn(new SeedManager(1337L)); - when(engine.getComplex()).thenReturn(null); - when(engine.getMinHeight()).thenReturn(-64); - when(engine.getHeight()).thenReturn(384); - when(engine.getHeight(anyInt(), anyInt(), anyBoolean())).thenReturn(128); - when(dimension.getFluidHeight()).thenReturn(63); - when(dimension.getModuleSettings()).thenReturn(declaring(configured)); - when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); - when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); - return engine; + private static StructureTestWorld world(StructurePlacement... placements) { + return new StructureTestWorld() + .placementSeed(new SeedManager(1337L).getMantle()) + .highest((x, z) -> 128) + .dimension(placements); } } diff --git a/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureStartsTest.java b/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureStartsTest.java index 638381812..e775270c1 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureStartsTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureStartsTest.java @@ -127,7 +127,7 @@ public class NativeStructureStartsTest { for (int chunkX = -GRID_RADIUS_CHUNKS; chunkX <= GRID_RADIUS_CHUNKS; chunkX++) { for (int chunkZ = -GRID_RADIUS_CHUNKS; chunkZ <= GRID_RADIUS_CHUNKS; chunkZ++) { List plans = NativeStructureStarts.plansAt(engine, chunkX, chunkZ); - List modulePlans = NativeStartPlanner.plansAt(engine, chunkX, chunkZ); + List modulePlans = NativeStartPlanner.plansAt(engine.getGeneration().world(), chunkX, chunkZ); assertEquals(modulePlans.size(), plans.size()); for (int index = 0; index < plans.size(); index++) { NativeStructureStartPlan plan = plans.get(index); diff --git a/core/src/test/java/art/arcane/iris/engine/framework/StructureAssemblerTest.java b/core/src/test/java/art/arcane/iris/engine/framework/StructureAssemblerTest.java index bc181b9cb..eee4674f4 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/StructureAssemblerTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/StructureAssemblerTest.java @@ -18,12 +18,11 @@ package art.arcane.iris.engine.framework; -import art.arcane.iris.engine.framework.structure.StructureResources; -import art.arcane.iris.core.modules.ModuleResourceFixture; -import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.engine.framework.structure.MapStructureResolver; +import art.arcane.iris.engine.framework.structure.ObjectFrame; import art.arcane.iris.engine.framework.structure.StructureAssemblyResult; import art.arcane.iris.engine.framework.structure.StructureAssemblyStatus; -import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawMode; @@ -32,8 +31,6 @@ import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceEntry; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceRules; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint; import art.arcane.iris.spi.IrisPlatform; @@ -41,7 +38,7 @@ import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.spi.PlatformRegistries; import art.arcane.volmlib.util.math.RNG; -import com.volmit.host.ModuleLogs; +import com.volmit.geometry.BlockPosition; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -77,16 +74,16 @@ public class StructureAssemblerTest { @Test public void attachedNonRotatablePieceKeepsItsAuthoredFacing() { Fixture fixture = new Fixture(); - IrisJigsawConnector startConnector = connector(IrisDirection.EAST_POSITIVE_X, "target", "start", "door"); + IrisJigsawConnector startConnector = connector(JigsawDirection.EAST_POSITIVE_X, "target", "start", "door"); IrisJigsawPiece startPiece = piece("start-object", false, startConnector); - IrisJigsawConnector candidateConnector = connector(IrisDirection.NORTH_NEGATIVE_Z, "", "door", ""); + IrisJigsawConnector candidateConnector = connector(JigsawDirection.NORTH_NEGATIVE_Z, "", "door", ""); IrisJigsawPiece candidatePiece = piece("candidate-object", false, candidateConnector); fixture.pool("start", pool("", "start-piece")); fixture.pool("target", pool("", "candidate-piece")); fixture.piece("start-piece", startPiece); fixture.piece("candidate-piece", candidatePiece); - fixture.object("start-object", new IrisObject(1, 1, 1)); - fixture.object("candidate-object", new IrisObject(1, 1, 1)); + fixture.object("start-object", new ObjectFrame(1, 1, 1)); + fixture.object("candidate-object", new ObjectFrame(1, 1, 1)); StructureAssemblyResult fixed = fixture.assembler( structure("start", 1), 0, 0, 0).assemble(new RNG(11L)); @@ -105,20 +102,20 @@ public class StructureAssemblerTest { public void fallbackCandidatesAreTriedAfterPrimaryCandidatesFail() { Fixture fixture = new Fixture(); IrisJigsawPiece startPiece = piece("start-object", false, - connector(IrisDirection.EAST_POSITIVE_X, "branch", "start", "door")); + connector(JigsawDirection.EAST_POSITIVE_X, "branch", "start", "door")); IrisJigsawPiece incompatiblePiece = piece("incompatible-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "", "wrong", "")); + connector(JigsawDirection.WEST_NEGATIVE_X, "", "wrong", "")); IrisJigsawPiece fallbackPiece = piece("fallback-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "", "door", "")); + connector(JigsawDirection.WEST_NEGATIVE_X, "", "door", "")); fixture.pool("start", pool("", "start-piece")); fixture.pool("branch", pool("fallback", "incompatible-piece")); fixture.pool("fallback", pool("", "fallback-piece")); fixture.piece("start-piece", startPiece); fixture.piece("incompatible-piece", incompatiblePiece); fixture.piece("fallback-piece", fallbackPiece); - fixture.object("start-object", new IrisObject(1, 1, 1)); - fixture.object("incompatible-object", new IrisObject(1, 1, 1)); - fixture.object("fallback-object", new IrisObject(1, 1, 1)); + fixture.object("start-object", new ObjectFrame(1, 1, 1)); + fixture.object("incompatible-object", new ObjectFrame(1, 1, 1)); + fixture.object("fallback-object", new ObjectFrame(1, 1, 1)); List placed = completedPieces( fixture.assembler(structure("start", 2), 0, 0, 0), new RNG(29L)); @@ -139,21 +136,21 @@ public class StructureAssemblerTest { public void branchTerminationPolicyEndsOnlyAnUnmatchedOptionalBranch() { Fixture fixture = new Fixture(); IrisJigsawPiece startPiece = piece("start-object", false, - connector(IrisDirection.EAST_POSITIVE_X, "target", "start", "door"), - connector(IrisDirection.SOUTH_POSITIVE_Z, "sibling", "start", "hall")); + connector(JigsawDirection.EAST_POSITIVE_X, "target", "start", "door"), + connector(JigsawDirection.SOUTH_POSITIVE_Z, "sibling", "start", "hall")); IrisJigsawPiece incompatiblePiece = piece("incompatible-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "", "wrong", "")); + connector(JigsawDirection.WEST_NEGATIVE_X, "", "wrong", "")); IrisJigsawPiece siblingPiece = piece("sibling-object", false, - connector(IrisDirection.NORTH_NEGATIVE_Z, "", "hall", "")); + connector(JigsawDirection.NORTH_NEGATIVE_Z, "", "hall", "")); fixture.pool("start", pool("", "start-piece")); fixture.pool("target", pool("", "incompatible-piece")); fixture.pool("sibling", pool("", "sibling-piece")); fixture.piece("start-piece", startPiece); fixture.piece("incompatible-piece", incompatiblePiece); fixture.piece("sibling-piece", siblingPiece); - fixture.object("start-object", new IrisObject(1, 1, 1)); - fixture.object("incompatible-object", new IrisObject(1, 1, 1)); - fixture.object("sibling-object", new IrisObject(1, 1, 1)); + fixture.object("start-object", new ObjectFrame(1, 1, 1)); + fixture.object("incompatible-object", new ObjectFrame(1, 1, 1)); + fixture.object("sibling-object", new ObjectFrame(1, 1, 1)); StructureAssemblyResult strict = fixture.assembler( structure("start", 2), 0, 0, 0).assemble(new RNG(17L)); @@ -173,17 +170,17 @@ public class StructureAssemblerTest { public void requiredFallbackOverridesBranchTerminationPolicy() { Fixture fixture = new Fixture(); IrisJigsawPiece startPiece = piece("start-object", false, - connector(IrisDirection.EAST_POSITIVE_X, "target", "start", "door")); + connector(JigsawDirection.EAST_POSITIVE_X, "target", "start", "door")); IrisJigsawPiece capPiece = piece("cap-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "", "door", "unused")); + connector(JigsawDirection.WEST_NEGATIVE_X, "", "door", "unused")); capPiece.setRules(new IrisJigsawPieceRules().setTerminal(true)); fixture.pool("start", pool("", "start-piece")); fixture.pool("target", pool("caps")); fixture.pool("caps", pool("", "cap-piece")); fixture.piece("start-piece", startPiece); fixture.piece("cap-piece", capPiece); - fixture.object("start-object", new IrisObject(1, 1, 1)); - fixture.object("cap-object", new IrisObject(64, 1, 1)); + fixture.object("start-object", new ObjectFrame(1, 1, 1)); + fixture.object("cap-object", new ObjectFrame(64, 1, 1)); IrisStructure structure = structure("start", 2) .setMaxSizeChunks(1) .setBranchFailurePolicy(IrisJigsawBranchFailurePolicy.TERMINATE_BRANCH); @@ -203,9 +200,9 @@ public class StructureAssemblerTest { public void explicitEmptyAndEmptyPrimaryPoolsCutOffDirectFallback() { Fixture fixture = new Fixture(); IrisJigsawPiece startPiece = piece("start-object", false, - connector(IrisDirection.EAST_POSITIVE_X, "target", "start", "door")); + connector(JigsawDirection.EAST_POSITIVE_X, "target", "start", "door")); IrisJigsawPiece fallbackPiece = piece("fallback-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "", "door", "")); + connector(JigsawDirection.WEST_NEGATIVE_X, "", "door", "")); IrisJigsawPool explicitEmpty = pool("fallback"); explicitEmpty.getPieces().add(new IrisJigsawPieceEntry().setEmpty(true).setWeight(1)); fixture.pool("start", pool("", "start-piece")); @@ -213,8 +210,8 @@ public class StructureAssemblerTest { fixture.pool("fallback", pool("", "fallback-piece")); fixture.piece("start-piece", startPiece); fixture.piece("fallback-piece", fallbackPiece); - fixture.object("start-object", new IrisObject(1, 1, 1)); - fixture.object("fallback-object", new IrisObject(1, 1, 1)); + fixture.object("start-object", new ObjectFrame(1, 1, 1)); + fixture.object("fallback-object", new ObjectFrame(1, 1, 1)); IrisStructure structure = structure("start", 2) .setBranchFailurePolicy(IrisJigsawBranchFailurePolicy.TERMINATE_BRANCH); @@ -233,25 +230,25 @@ public class StructureAssemblerTest { @Test public void alignedRuntimeConnectorsPreserveTopOrientation() { Fixture fixture = new Fixture(); - IrisJigsawConnector source = connector(IrisDirection.EAST_POSITIVE_X, "target", "start", "door") + IrisJigsawConnector source = connector(JigsawDirection.EAST_POSITIVE_X, "target", "start", "door") .setJoint(JigsawJoint.ALIGNED) - .setTop(IrisDirection.UP_POSITIVE_Y); - IrisJigsawConnector target = connector(IrisDirection.WEST_NEGATIVE_X, "target", "door", "unused") - .setTop(IrisDirection.DOWN_NEGATIVE_Y); + .setTop(JigsawDirection.UP_POSITIVE_Y); + IrisJigsawConnector target = connector(JigsawDirection.WEST_NEGATIVE_X, "target", "door", "unused") + .setTop(JigsawDirection.DOWN_NEGATIVE_Y); IrisJigsawPiece startPiece = piece("start-object", false, source); IrisJigsawPiece targetPiece = piece("target-object", false, target); fixture.pool("start", pool("", "start-piece")); fixture.pool("target", pool("", "target-piece")); fixture.piece("start-piece", startPiece); fixture.piece("target-piece", targetPiece); - fixture.object("start-object", new IrisObject(1, 1, 1)); - fixture.object("target-object", new IrisObject(1, 1, 1)); + fixture.object("start-object", new ObjectFrame(1, 1, 1)); + fixture.object("target-object", new ObjectFrame(1, 1, 1)); assertEquals(StructureAssemblyStatus.FAILED_UNCAPPED, fixture.assembler(structure("start", 1), 0, 0, 0) .assemble(new RNG(13L)).status()); - target.setTop(IrisDirection.UP_POSITIVE_Y); + target.setTop(JigsawDirection.UP_POSITIVE_Y); List placed = completedPieces( fixture.assembler(structure("start", 1), 0, 0, 0), new RNG(13L)); assertEquals(2, placed.size()); @@ -261,31 +258,31 @@ public class StructureAssemblerTest { public void planarCanonicalSocketsPlaceEveryNeighborOnTheExactCellGrid() { Fixture fixture = new Fixture(); IrisJigsawConnector northSource = connector( - IrisDirection.NORTH_NEGATIVE_Z, "north", "start", "door") - .setPosition(new IrisPosition(8, 4, 0)); + JigsawDirection.NORTH_NEGATIVE_Z, "north", "start", "door") + .setPosition(new BlockPosition(8, 4, 0)); IrisJigsawConnector eastSource = connector( - IrisDirection.EAST_POSITIVE_X, "east", "start", "door") - .setPosition(new IrisPosition(15, 4, 8)); + JigsawDirection.EAST_POSITIVE_X, "east", "start", "door") + .setPosition(new BlockPosition(15, 4, 8)); IrisJigsawConnector southSource = connector( - IrisDirection.SOUTH_POSITIVE_Z, "south", "start", "door") - .setPosition(new IrisPosition(8, 4, 15)); + JigsawDirection.SOUTH_POSITIVE_Z, "south", "start", "door") + .setPosition(new BlockPosition(8, 4, 15)); IrisJigsawConnector westSource = connector( - IrisDirection.WEST_NEGATIVE_X, "west", "start", "door") - .setPosition(new IrisPosition(0, 4, 8)); + JigsawDirection.WEST_NEGATIVE_X, "west", "start", "door") + .setPosition(new BlockPosition(0, 4, 8)); IrisJigsawPiece startPiece = piece( "start-object", false, northSource, eastSource, southSource, westSource); IrisJigsawPiece northPiece = piece("north-object", false, - connector(IrisDirection.SOUTH_POSITIVE_Z, "", "door", "") - .setPosition(new IrisPosition(8, 4, 15))); + connector(JigsawDirection.SOUTH_POSITIVE_Z, "", "door", "") + .setPosition(new BlockPosition(8, 4, 15))); IrisJigsawPiece eastPiece = piece("east-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "", "door", "") - .setPosition(new IrisPosition(0, 4, 8))); + connector(JigsawDirection.WEST_NEGATIVE_X, "", "door", "") + .setPosition(new BlockPosition(0, 4, 8))); IrisJigsawPiece southPiece = piece("south-object", false, - connector(IrisDirection.NORTH_NEGATIVE_Z, "", "door", "") - .setPosition(new IrisPosition(8, 4, 0))); + connector(JigsawDirection.NORTH_NEGATIVE_Z, "", "door", "") + .setPosition(new BlockPosition(8, 4, 0))); IrisJigsawPiece westPiece = piece("west-object", false, - connector(IrisDirection.EAST_POSITIVE_X, "", "door", "") - .setPosition(new IrisPosition(15, 4, 8))); + connector(JigsawDirection.EAST_POSITIVE_X, "", "door", "") + .setPosition(new BlockPosition(15, 4, 8))); fixture.pool("start", pool("", "start-piece")); fixture.pool("north", pool("", "north-piece")); fixture.pool("east", pool("", "east-piece")); @@ -296,14 +293,14 @@ public class StructureAssemblerTest { fixture.piece("east-piece", eastPiece); fixture.piece("south-piece", southPiece); fixture.piece("west-piece", westPiece); - fixture.object("start-object", new IrisObject(16, 8, 16)); - fixture.object("north-object", new IrisObject(16, 8, 16)); - fixture.object("east-object", new IrisObject(16, 8, 16)); - fixture.object("south-object", new IrisObject(16, 8, 16)); - fixture.object("west-object", new IrisObject(16, 8, 16)); + fixture.object("start-object", new ObjectFrame(16, 8, 16)); + fixture.object("north-object", new ObjectFrame(16, 8, 16)); + fixture.object("east-object", new ObjectFrame(16, 8, 16)); + fixture.object("south-object", new ObjectFrame(16, 8, 16)); + fixture.object("west-object", new ObjectFrame(16, 8, 16)); IrisStructure structure = structure("start", 1) .setMode(IrisJigsawMode.PLANAR_JIGSAW) - .setCellSize(new IrisPosition(16, 8, 16)); + .setCellSize(new BlockPosition(16, 8, 16)); List placed = completedPieces( fixture.assembler(structure, 32, 64, -48), new RNG(127L)); @@ -336,23 +333,23 @@ public class StructureAssemblerTest { public void selectionPriorityProcessesHigherConnectorsFirstAndPreservesStableTies() { Fixture fixture = new Fixture(); IrisJigsawConnector eastSource = connector( - IrisDirection.EAST_POSITIVE_X, "east", "start", "door").setSelectionPriority(-20); + JigsawDirection.EAST_POSITIVE_X, "east", "start", "door").setSelectionPriority(-20); IrisJigsawConnector westSource = connector( - IrisDirection.WEST_NEGATIVE_X, "west", "start", "door").setSelectionPriority(-10); + JigsawDirection.WEST_NEGATIVE_X, "west", "start", "door").setSelectionPriority(-10); IrisJigsawPiece startPiece = piece("start-object", false, eastSource, westSource); IrisJigsawPiece eastPiece = piece("east-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "", "door", "")); + connector(JigsawDirection.WEST_NEGATIVE_X, "", "door", "")); IrisJigsawPiece westPiece = piece("west-object", false, - connector(IrisDirection.EAST_POSITIVE_X, "", "door", "")); + connector(JigsawDirection.EAST_POSITIVE_X, "", "door", "")); fixture.pool("start", pool("", "start-piece")); fixture.pool("east", pool("", "east-piece")); fixture.pool("west", pool("", "west-piece")); fixture.piece("start-piece", startPiece); fixture.piece("east-piece", eastPiece); fixture.piece("west-piece", westPiece); - fixture.object("start-object", new IrisObject(1, 1, 1)); - fixture.object("east-object", new IrisObject(1, 1, 1)); - fixture.object("west-object", new IrisObject(1, 1, 1)); + fixture.object("start-object", new ObjectFrame(1, 1, 1)); + fixture.object("east-object", new ObjectFrame(1, 1, 1)); + fixture.object("west-object", new ObjectFrame(1, 1, 1)); IrisStructure structure = structure("start", 1); List prioritized = completedPieces( @@ -374,20 +371,20 @@ public class StructureAssemblerTest { public void selectionPriorityChoosesHigherCandidateConnectorAndPreservesStableTies() { Fixture fixture = new Fixture(); IrisJigsawPiece startPiece = piece("start-object", false, - connector(IrisDirection.EAST_POSITIVE_X, "target", "start", "door")); - IrisJigsawConnector low = connector(IrisDirection.WEST_NEGATIVE_X, "", "door", "") - .setPosition(new IrisPosition(0, 0, 0)) + connector(JigsawDirection.EAST_POSITIVE_X, "target", "start", "door")); + IrisJigsawConnector low = connector(JigsawDirection.WEST_NEGATIVE_X, "", "door", "") + .setPosition(new BlockPosition(0, 0, 0)) .setSelectionPriority(-20); - IrisJigsawConnector high = connector(IrisDirection.WEST_NEGATIVE_X, "", "door", "") - .setPosition(new IrisPosition(0, 0, 2)) + IrisJigsawConnector high = connector(JigsawDirection.WEST_NEGATIVE_X, "", "door", "") + .setPosition(new BlockPosition(0, 0, 2)) .setSelectionPriority(-10); IrisJigsawPiece targetPiece = piece("target-object", false, low, high); fixture.pool("start", pool("", "start-piece")); fixture.pool("target", pool("", "target-piece")); fixture.piece("start-piece", startPiece); fixture.piece("target-piece", targetPiece); - fixture.object("start-object", new IrisObject(1, 1, 1)); - fixture.object("target-object", new IrisObject(1, 1, 3)); + fixture.object("start-object", new ObjectFrame(1, 1, 1)); + fixture.object("target-object", new ObjectFrame(1, 1, 3)); IrisStructure structure = structure("start", 1); List prioritized = completedPieces( @@ -406,20 +403,20 @@ public class StructureAssemblerTest { public void placementPrioritySchedulesChildExpansionAfterTheCurrentPieceAndPreservesStableTies() { Fixture fixture = new Fixture(); IrisJigsawConnector eastSource = connector( - IrisDirection.EAST_POSITIVE_X, "east", "start", "door").setPlacementPriority(-20); + JigsawDirection.EAST_POSITIVE_X, "east", "start", "door").setPlacementPriority(-20); IrisJigsawConnector westSource = connector( - IrisDirection.WEST_NEGATIVE_X, "west", "start", "door").setPlacementPriority(-10); + JigsawDirection.WEST_NEGATIVE_X, "west", "start", "door").setPlacementPriority(-10); IrisJigsawPiece startPiece = piece("start-object", false, eastSource, westSource); IrisJigsawPiece eastPiece = piece("east-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "", "door", ""), - connector(IrisDirection.EAST_POSITIVE_X, "east-leaf", "east", "leaf")); + connector(JigsawDirection.WEST_NEGATIVE_X, "", "door", ""), + connector(JigsawDirection.EAST_POSITIVE_X, "east-leaf", "east", "leaf")); IrisJigsawPiece westPiece = piece("west-object", false, - connector(IrisDirection.EAST_POSITIVE_X, "", "door", ""), - connector(IrisDirection.WEST_NEGATIVE_X, "west-leaf", "west", "leaf")); + connector(JigsawDirection.EAST_POSITIVE_X, "", "door", ""), + connector(JigsawDirection.WEST_NEGATIVE_X, "west-leaf", "west", "leaf")); IrisJigsawPiece eastLeaf = piece("east-leaf-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "", "leaf", "")); + connector(JigsawDirection.WEST_NEGATIVE_X, "", "leaf", "")); IrisJigsawPiece westLeaf = piece("west-leaf-object", false, - connector(IrisDirection.EAST_POSITIVE_X, "", "leaf", "")); + connector(JigsawDirection.EAST_POSITIVE_X, "", "leaf", "")); fixture.pool("start", pool("", "start-piece")); fixture.pool("east", pool("", "east-piece")); fixture.pool("west", pool("", "west-piece")); @@ -430,11 +427,11 @@ public class StructureAssemblerTest { fixture.piece("west-piece", westPiece); fixture.piece("east-leaf-piece", eastLeaf); fixture.piece("west-leaf-piece", westLeaf); - fixture.object("start-object", new IrisObject(1, 1, 1)); - fixture.object("east-object", new IrisObject(1, 1, 1)); - fixture.object("west-object", new IrisObject(1, 1, 1)); - fixture.object("east-leaf-object", new IrisObject(1, 1, 1)); - fixture.object("west-leaf-object", new IrisObject(1, 1, 1)); + fixture.object("start-object", new ObjectFrame(1, 1, 1)); + fixture.object("east-object", new ObjectFrame(1, 1, 1)); + fixture.object("west-object", new ObjectFrame(1, 1, 1)); + fixture.object("east-leaf-object", new ObjectFrame(1, 1, 1)); + fixture.object("west-leaf-object", new ObjectFrame(1, 1, 1)); IrisStructure structure = structure("start", 2); List prioritized = completedPieces( @@ -458,17 +455,17 @@ public class StructureAssemblerTest { public void connectorChannelsMustMatchExactly() { Fixture fixture = new Fixture(); IrisJigsawConnector source = connector( - IrisDirection.EAST_POSITIVE_X, "target", "start", "door").setChannel("road"); + JigsawDirection.EAST_POSITIVE_X, "target", "start", "door").setChannel("road"); IrisJigsawConnector target = connector( - IrisDirection.WEST_NEGATIVE_X, "", "door", "").setChannel("room"); + JigsawDirection.WEST_NEGATIVE_X, "", "door", "").setChannel("room"); IrisJigsawPiece startPiece = piece("start-object", false, source); IrisJigsawPiece targetPiece = piece("target-object", false, target); fixture.pool("start", pool("", "start-piece")); fixture.pool("target", pool("", "target-piece")); fixture.piece("start-piece", startPiece); fixture.piece("target-piece", targetPiece); - fixture.object("start-object", new IrisObject(1, 1, 1)); - fixture.object("target-object", new IrisObject(1, 1, 1)); + fixture.object("start-object", new ObjectFrame(1, 1, 1)); + fixture.object("target-object", new ObjectFrame(1, 1, 1)); IrisStructure structure = structure("start", 1); assertEquals(StructureAssemblyStatus.FAILED_UNCAPPED, @@ -493,15 +490,15 @@ public class StructureAssemblerTest { public void fallbackAtMaximumDepthDoesNotExpandAgain() { Fixture fixture = new Fixture(); IrisJigsawPiece startPiece = piece("start-object", false, - connector(IrisDirection.EAST_POSITIVE_X, "branch", "start", "door")); + connector(JigsawDirection.EAST_POSITIVE_X, "branch", "start", "door")); IrisJigsawPiece branchPiece = piece("branch-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "", "door", ""), - connector(IrisDirection.EAST_POSITIVE_X, "terminal", "branch", "door")); + connector(JigsawDirection.WEST_NEGATIVE_X, "", "door", ""), + connector(JigsawDirection.EAST_POSITIVE_X, "terminal", "branch", "door")); IrisJigsawPiece primaryTerminal = piece("primary-terminal-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "", "door", "")); + connector(JigsawDirection.WEST_NEGATIVE_X, "", "door", "")); IrisJigsawPiece fallbackTerminal = piece("fallback-terminal-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "", "door", ""), - connector(IrisDirection.EAST_POSITIVE_X, "terminal", "terminal", "door")); + connector(JigsawDirection.WEST_NEGATIVE_X, "", "door", ""), + connector(JigsawDirection.EAST_POSITIVE_X, "terminal", "terminal", "door")); fixture.pool("start", pool("", "start-piece")); fixture.pool("branch", pool("", "branch-piece")); fixture.pool("terminal", pool("terminal-fallback", "primary-terminal-piece")); @@ -510,10 +507,10 @@ public class StructureAssemblerTest { fixture.piece("branch-piece", branchPiece); fixture.piece("primary-terminal-piece", primaryTerminal); fixture.piece("fallback-terminal-piece", fallbackTerminal); - fixture.object("start-object", new IrisObject(1, 1, 1)); - fixture.object("branch-object", new IrisObject(1, 1, 1)); - fixture.object("primary-terminal-object", new IrisObject(1, 1, 1)); - fixture.object("fallback-terminal-object", new IrisObject(1, 1, 1)); + fixture.object("start-object", new ObjectFrame(1, 1, 1)); + fixture.object("branch-object", new ObjectFrame(1, 1, 1)); + fixture.object("primary-terminal-object", new ObjectFrame(1, 1, 1)); + fixture.object("fallback-terminal-object", new ObjectFrame(1, 1, 1)); IrisStructure structure = structure("start", 1); structure.setMaxSizeChunks(1); @@ -529,17 +526,17 @@ public class StructureAssemblerTest { public void fallbackOfFallbackIsNotSelected() { Fixture fixture = new Fixture(); IrisJigsawPiece startPiece = piece("start-object", false, - connector(IrisDirection.EAST_POSITIVE_X, "branch", "start", "door")); + connector(JigsawDirection.EAST_POSITIVE_X, "branch", "start", "door")); IrisJigsawPiece incompatiblePiece = piece("incompatible-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "", "wrong", "")); + connector(JigsawDirection.WEST_NEGATIVE_X, "", "wrong", "")); fixture.pool("start", pool("", "start-piece")); fixture.pool("branch", pool("terminators", "incompatible-piece")); fixture.pool("terminators", pool("empty", "incompatible-piece")); fixture.pool("empty", pool("")); fixture.piece("start-piece", startPiece); fixture.piece("incompatible-piece", incompatiblePiece); - fixture.object("start-object", new IrisObject(1, 1, 1)); - fixture.object("incompatible-object", new IrisObject(1, 1, 1)); + fixture.object("start-object", new ObjectFrame(1, 1, 1)); + fixture.object("incompatible-object", new ObjectFrame(1, 1, 1)); assertEquals(StructureAssemblyStatus.FAILED_UNCAPPED, fixture.assembler(structure("start", 2), 0, 0, 0) @@ -552,7 +549,7 @@ public class StructureAssemblerTest { IrisJigsawPiece startPiece = piece("start-object", false); fixture.pool("start", pool("", "start-piece")); fixture.piece("start-piece", startPiece); - fixture.object("start-object", new IrisObject(4, 2, 6)); + fixture.object("start-object", new ObjectFrame(4, 2, 6)); PlacedStructurePiece placed = completedPieces( fixture.assembler(structure("start", 1), 10, 20, 30), new RNG(53L)).getFirst(); @@ -566,7 +563,7 @@ public class StructureAssemblerTest { IrisJigsawPiece startPiece = piece("start-object", true); fixture.pool("start", pool("", "start-piece")); fixture.piece("start-piece", startPiece); - fixture.object("start-object", new IrisObject(4, 2, 6)); + fixture.object("start-object", new ObjectFrame(4, 2, 6)); StructureAssembler assembler = fixture.assembler(structure("start", 1), 10, 20, 30); assertBounds(completedPieces(assembler, rotationIndex(1)).getFirst(), 7, 19, 29, 12, 20, 32); @@ -579,12 +576,12 @@ public class StructureAssemblerTest { for (int quarterTurn = 0; quarterTurn < 4; quarterTurn++) { Fixture fixture = new Fixture(); IrisJigsawConnector source = connector( - IrisDirection.NORTH_NEGATIVE_Z, "target", "start", "door") - .setPosition(new IrisPosition(2, 1, 0)) + JigsawDirection.NORTH_NEGATIVE_Z, "target", "start", "door") + .setPosition(new BlockPosition(2, 1, 0)) .setJoint(JigsawJoint.ALIGNED); IrisJigsawConnector target = connector( - IrisDirection.SOUTH_POSITIVE_Z, "", "door", "unused") - .setPosition(new IrisPosition(2, 1, 5)) + JigsawDirection.SOUTH_POSITIVE_Z, "", "door", "unused") + .setPosition(new BlockPosition(2, 1, 5)) .setJoint(JigsawJoint.ALIGNED); IrisJigsawPiece startPiece = piece("start-object", true, source); IrisJigsawPiece targetPiece = piece("target-object", true, target); @@ -592,11 +589,11 @@ public class StructureAssemblerTest { fixture.pool("target", pool("", "target-piece")); fixture.piece("start-piece", startPiece); fixture.piece("target-piece", targetPiece); - fixture.object("start-object", new IrisObject(4, 2, 6)); - fixture.object("target-object", new IrisObject(4, 2, 6)); + fixture.object("start-object", new ObjectFrame(4, 2, 6)); + fixture.object("target-object", new ObjectFrame(4, 2, 6)); IrisStructure structure = structure("start", 1) .setMode(IrisJigsawMode.PLANAR_JIGSAW) - .setCellSize(new IrisPosition(4, 2, 6)); + .setCellSize(new BlockPosition(4, 2, 6)); List pieces = completedPieces( fixture.assembler(structure, 10, 20, 30), rotationIndex(quarterTurn)); @@ -662,18 +659,18 @@ public class StructureAssemblerTest { public void pillagerOutpostAirScaffoldAllowsTheWatchtowerToOverlapItsNativeBounds() { Fixture fixture = new Fixture(); IrisJigsawConnector baseEntrance = connector( - IrisDirection.NORTH_NEGATIVE_Z, + JigsawDirection.NORTH_NEGATIVE_Z, "towers", "minecraft:entrance", "minecraft:entrance") - .setPosition(new IrisPosition(8, 1, 14)) + .setPosition(new BlockPosition(8, 1, 14)) .setJoint(JigsawJoint.ALIGNED); IrisJigsawConnector towerEntrance = connector( - IrisDirection.SOUTH_POSITIVE_Z, + JigsawDirection.SOUTH_POSITIVE_Z, "terminal", "minecraft:entrance", "minecraft:entrance") - .setPosition(new IrisPosition(7, 1, 13)) + .setPosition(new BlockPosition(7, 1, 13)) .setJoint(JigsawJoint.ALIGNED); IrisJigsawPiece basePlate = piece("base-plate-object", true, baseEntrance); IrisJigsawPiece watchtower = piece("watchtower-object", true, towerEntrance); @@ -681,8 +678,8 @@ public class StructureAssemblerTest { fixture.pool("towers", pool("terminal", "watchtower")); fixture.piece("base-plate", basePlate); fixture.piece("watchtower", watchtower); - fixture.object("base-plate-object", new IrisObject(16, 30, 16)); - fixture.object("watchtower-object", new IrisObject(15, 21, 15)); + fixture.object("base-plate-object", new ObjectFrame(16, 30, 16)); + fixture.object("watchtower-object", new ObjectFrame(15, 21, 15)); IrisStructure structure = structure("start", 1); StructureAssemblyResult collidable = fixture.assembler(structure, 0, 0, 0) @@ -714,8 +711,8 @@ public class StructureAssemblerTest { fixture.pool("start", start); fixture.piece("first-piece", first); fixture.piece("second-piece", second); - fixture.object("first-object", new IrisObject(1, 1, 1)); - fixture.object("second-object", new IrisObject(1, 1, 1)); + fixture.object("first-object", new ObjectFrame(1, 1, 1)); + fixture.object("second-object", new ObjectFrame(1, 1, 1)); for (long seed = 0; seed < 32; seed++) { List placed = completedPieces( @@ -731,7 +728,7 @@ public class StructureAssemblerTest { startPiece.setConnectors(null); fixture.pool("start", pool("", "start-piece")); fixture.piece("start-piece", startPiece); - fixture.object("start-object", new IrisObject(1, 1, 1)); + fixture.object("start-object", new ObjectFrame(1, 1, 1)); assertThrows(IllegalStateException.class, () -> fixture.assembler(structure("start", 1), 0, 0, 0).assemble(new RNG(3L))); @@ -741,20 +738,20 @@ public class StructureAssemblerTest { public void corruptWeightedPeerFailsBeforeCandidateSelection() { Fixture fixture = new Fixture(); IrisJigsawPiece startPiece = piece("start-object", false, - connector(IrisDirection.EAST_POSITIVE_X, "branch", "start", "door")); + connector(JigsawDirection.EAST_POSITIVE_X, "branch", "start", "door")); IrisJigsawPiece validPiece = piece("valid-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "", "door", "")); + connector(JigsawDirection.WEST_NEGATIVE_X, "", "door", "")); IrisJigsawPiece fallbackPiece = piece("fallback-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "", "door", "")); + connector(JigsawDirection.WEST_NEGATIVE_X, "", "door", "")); fixture.pool("start", pool("", "start-piece")); fixture.pool("branch", pool("fallback", "valid-piece", "missing-piece")); fixture.pool("fallback", pool("", "fallback-piece")); fixture.piece("start-piece", startPiece); fixture.piece("valid-piece", validPiece); fixture.piece("fallback-piece", fallbackPiece); - fixture.object("start-object", new IrisObject(1, 1, 1)); - fixture.object("valid-object", new IrisObject(1, 1, 1)); - fixture.object("fallback-object", new IrisObject(1, 1, 1)); + fixture.object("start-object", new ObjectFrame(1, 1, 1)); + fixture.object("valid-object", new ObjectFrame(1, 1, 1)); + fixture.object("fallback-object", new ObjectFrame(1, 1, 1)); IllegalStateException failure = assertThrows(IllegalStateException.class, () -> fixture.assembler(structure("start", 2), 0, 0, 0).assemble(new RNG(17L))); @@ -769,7 +766,7 @@ public class StructureAssemblerTest { IrisJigsawPiece validPiece = piece("valid-object", false); fixture.pool("start", pool("", "valid-piece", "missing-piece")); fixture.piece("valid-piece", validPiece); - fixture.object("valid-object", new IrisObject(1, 1, 1)); + fixture.object("valid-object", new ObjectFrame(1, 1, 1)); IllegalStateException failure = assertThrows(IllegalStateException.class, () -> fixture.assembler(structure("start", 1), 0, 0, 0).assemble(new RNG(18L))); @@ -782,20 +779,20 @@ public class StructureAssemblerTest { public void malformedNestedConnectorDoesNotFallThroughToAuthoredFallback() { Fixture fixture = new Fixture(); IrisJigsawPiece startPiece = piece("start-object", false, - connector(IrisDirection.EAST_POSITIVE_X, "branch", "start", "door")); + connector(JigsawDirection.EAST_POSITIVE_X, "branch", "start", "door")); IrisJigsawPiece malformedPiece = piece("malformed-object", false); malformedPiece.getConnectors().add((IrisJigsawConnector) null); IrisJigsawPiece fallbackPiece = piece("fallback-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "", "door", "")); + connector(JigsawDirection.WEST_NEGATIVE_X, "", "door", "")); fixture.pool("start", pool("", "start-piece")); fixture.pool("branch", pool("fallback", "malformed-piece")); fixture.pool("fallback", pool("", "fallback-piece")); fixture.piece("start-piece", startPiece); fixture.piece("malformed-piece", malformedPiece); fixture.piece("fallback-piece", fallbackPiece); - fixture.object("start-object", new IrisObject(1, 1, 1)); - fixture.object("malformed-object", new IrisObject(1, 1, 1)); - fixture.object("fallback-object", new IrisObject(1, 1, 1)); + fixture.object("start-object", new ObjectFrame(1, 1, 1)); + fixture.object("malformed-object", new ObjectFrame(1, 1, 1)); + fixture.object("fallback-object", new ObjectFrame(1, 1, 1)); assertThrows(IllegalStateException.class, () -> fixture.assembler(structure("start", 2), 0, 0, 0).assemble(new RNG(19L))); @@ -805,13 +802,13 @@ public class StructureAssemblerTest { public void emptyPoolChoiceTerminatesTheBranchWithoutPlacingAir() { Fixture fixture = new Fixture(); IrisJigsawPiece startPiece = piece("start-object", false, - connector(IrisDirection.EAST_POSITIVE_X, "terminal", "start", "door")); + connector(JigsawDirection.EAST_POSITIVE_X, "terminal", "start", "door")); fixture.pool("start", pool("", "start-piece")); IrisJigsawPool terminal = new IrisJigsawPool(); terminal.getPieces().add(new IrisJigsawPieceEntry().setEmpty(true).setWeight(1)); fixture.pool("terminal", terminal); fixture.piece("start-piece", startPiece); - fixture.object("start-object", new IrisObject(1, 1, 1)); + fixture.object("start-object", new ObjectFrame(1, 1, 1)); List placed = completedPieces( fixture.assembler(structure("start", 2), 0, 0, 0), new RNG(7L)); @@ -859,8 +856,8 @@ public class StructureAssemblerTest { fixture.pool("start", pool("", "first-piece", "second-piece")); fixture.piece("first-piece", first); fixture.piece("second-piece", second); - fixture.object("first-object", new IrisObject(1, 1, 1)); - fixture.object("second-object", new IrisObject(1, 1, 1)); + fixture.object("first-object", new ObjectFrame(1, 1, 1)); + fixture.object("second-object", new ObjectFrame(1, 1, 1)); IrisStructure structure = structure("start", 1); structure.getThemeSets().add(new IrisJigsawThemeSet("variant-1", 1)); structure.getThemeSets().add(new IrisJigsawThemeSet("variant-2", 1)); @@ -877,12 +874,12 @@ public class StructureAssemblerTest { public void unmetMinimumPlacementsTakePriorityWithinTheirPool() { Fixture fixture = new Fixture(); IrisJigsawPiece start = piece("start-object", false, - connector(IrisDirection.EAST_POSITIVE_X, "branch", "start", "door")); + connector(JigsawDirection.EAST_POSITIVE_X, "branch", "start", "door")); IrisJigsawPiece required = piece("required-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "", "door", "")); + connector(JigsawDirection.WEST_NEGATIVE_X, "", "door", "")); required.setRules(new IrisJigsawPieceRules().setMinimumPlacements(1)); IrisJigsawPiece common = piece("common-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "", "door", "")); + connector(JigsawDirection.WEST_NEGATIVE_X, "", "door", "")); fixture.pool("start", pool("", "start-piece")); IrisJigsawPool branch = new IrisJigsawPool(); branch.getPieces().add(new IrisJigsawPieceEntry("common-piece", 100)); @@ -891,9 +888,9 @@ public class StructureAssemblerTest { fixture.piece("start-piece", start); fixture.piece("required-piece", required); fixture.piece("common-piece", common); - fixture.object("start-object", new IrisObject(1, 1, 1)); - fixture.object("required-object", new IrisObject(1, 1, 1)); - fixture.object("common-object", new IrisObject(1, 1, 1)); + fixture.object("start-object", new ObjectFrame(1, 1, 1)); + fixture.object("required-object", new ObjectFrame(1, 1, 1)); + fixture.object("common-object", new ObjectFrame(1, 1, 1)); StructureAssemblyResult result = fixture.assembler(structure("start", 2), 0, 0, 0) .assemble(new RNG(61L)); @@ -906,16 +903,16 @@ public class StructureAssemblerTest { public void terminalPiecesNeverEnqueueTheirRemainingConnectors() { Fixture fixture = new Fixture(); IrisJigsawPiece terminal = piece("terminal-object", false, - connector(IrisDirection.EAST_POSITIVE_X, "child", "start", "door")); + connector(JigsawDirection.EAST_POSITIVE_X, "child", "start", "door")); terminal.setRules(new IrisJigsawPieceRules().setTerminal(true)); IrisJigsawPiece child = piece("child-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "", "door", "")); + connector(JigsawDirection.WEST_NEGATIVE_X, "", "door", "")); fixture.pool("start", pool("", "terminal-piece")); fixture.pool("child", pool("", "child-piece")); fixture.piece("terminal-piece", terminal); fixture.piece("child-piece", child); - fixture.object("terminal-object", new IrisObject(1, 1, 1)); - fixture.object("child-object", new IrisObject(1, 1, 1)); + fixture.object("terminal-object", new ObjectFrame(1, 1, 1)); + fixture.object("child-object", new ObjectFrame(1, 1, 1)); StructureAssemblyResult result = fixture.assembler(structure("start", 2), 0, 0, 0) .assemble(new RNG(67L)); @@ -928,11 +925,11 @@ public class StructureAssemblerTest { public void requiredCapsResolveThroughACompatibleTerminalFallback() { Fixture fixture = new Fixture(); IrisJigsawPiece start = piece("start-object", false, - connector(IrisDirection.EAST_POSITIVE_X, "branch", "start", "door")); + connector(JigsawDirection.EAST_POSITIVE_X, "branch", "start", "door")); IrisJigsawPiece incompatible = piece("incompatible-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "", "wrong", "")); + connector(JigsawDirection.WEST_NEGATIVE_X, "", "wrong", "")); IrisJigsawPiece cap = piece("cap-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "", "door", "")); + connector(JigsawDirection.WEST_NEGATIVE_X, "", "door", "")); cap.setRules(new IrisJigsawPieceRules().setTerminal(true)); fixture.pool("start", pool("", "start-piece")); fixture.pool("branch", pool("caps", "incompatible-piece")); @@ -940,9 +937,9 @@ public class StructureAssemblerTest { fixture.piece("start-piece", start); fixture.piece("incompatible-piece", incompatible); fixture.piece("cap-piece", cap); - fixture.object("start-object", new IrisObject(1, 1, 1)); - fixture.object("incompatible-object", new IrisObject(1, 1, 1)); - fixture.object("cap-object", new IrisObject(1, 1, 1)); + fixture.object("start-object", new ObjectFrame(1, 1, 1)); + fixture.object("incompatible-object", new ObjectFrame(1, 1, 1)); + fixture.object("cap-object", new ObjectFrame(1, 1, 1)); IrisStructure structure = structure("start", 2).setRequireCaps(true); StructureAssemblyResult result = fixture.assembler(structure, 0, 0, 0) @@ -957,20 +954,20 @@ public class StructureAssemblerTest { public void compatibleOpenConnectorsCloseAgainstAnAlreadyPlacedNeighbor() { Fixture fixture = new Fixture(); IrisJigsawPiece start = piece("start-object", false, - connector(IrisDirection.EAST_POSITIVE_X, "east", "start-east", "door"), - connector(IrisDirection.SOUTH_POSITIVE_Z, "south", "start-south", "door")); + connector(JigsawDirection.EAST_POSITIVE_X, "east", "start-east", "door"), + connector(JigsawDirection.SOUTH_POSITIVE_Z, "south", "start-south", "door")); IrisJigsawPiece east = piece("east-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "terminal", "door", "unused"), - connector(IrisDirection.SOUTH_POSITIVE_Z, "diagonal", "east-south", "door")); + connector(JigsawDirection.WEST_NEGATIVE_X, "terminal", "door", "unused"), + connector(JigsawDirection.SOUTH_POSITIVE_Z, "diagonal", "east-south", "door")); IrisJigsawPiece south = piece("south-object", false, - connector(IrisDirection.NORTH_NEGATIVE_Z, "terminal", "door", "unused"), - connector(IrisDirection.EAST_POSITIVE_X, "diagonal", "south-east", "door")); + connector(JigsawDirection.NORTH_NEGATIVE_Z, "terminal", "door", "unused"), + connector(JigsawDirection.EAST_POSITIVE_X, "diagonal", "south-east", "door")); IrisJigsawPiece diagonal = piece("diagonal-object", false, - connector(IrisDirection.NORTH_NEGATIVE_Z, "loop", "door", "unused"), - connector(IrisDirection.WEST_NEGATIVE_X, "loop", "door", "unused")); + connector(JigsawDirection.NORTH_NEGATIVE_Z, "loop", "door", "unused"), + connector(JigsawDirection.WEST_NEGATIVE_X, "loop", "door", "unused")); IrisJigsawPiece cap = piece("cap-object", true, - connector(IrisDirection.WEST_NEGATIVE_X, "terminal", "door", "unused"), - connector(IrisDirection.WEST_NEGATIVE_X, "terminal", "unused", "unused")); + connector(JigsawDirection.WEST_NEGATIVE_X, "terminal", "door", "unused"), + connector(JigsawDirection.WEST_NEGATIVE_X, "terminal", "unused", "unused")); cap.setRules(new IrisJigsawPieceRules().setTerminal(true)); fixture.pool("start", pool("", "start-piece")); fixture.pool("east", pool("caps", "east-piece")); @@ -983,11 +980,11 @@ public class StructureAssemblerTest { fixture.piece("south-piece", south); fixture.piece("diagonal-piece", diagonal); fixture.piece("cap-piece", cap); - fixture.object("start-object", new IrisObject(1, 1, 1)); - fixture.object("east-object", new IrisObject(1, 1, 1)); - fixture.object("south-object", new IrisObject(1, 1, 1)); - fixture.object("diagonal-object", new IrisObject(1, 1, 1)); - fixture.object("cap-object", new IrisObject(1, 1, 1)); + fixture.object("start-object", new ObjectFrame(1, 1, 1)); + fixture.object("east-object", new ObjectFrame(1, 1, 1)); + fixture.object("south-object", new ObjectFrame(1, 1, 1)); + fixture.object("diagonal-object", new ObjectFrame(1, 1, 1)); + fixture.object("cap-object", new ObjectFrame(1, 1, 1)); IrisStructure structure = structure("start", 2).setRequireCaps(true); List placed = completedPieces( @@ -1001,26 +998,26 @@ public class StructureAssemblerTest { public void planarRequiredCapsRejectASecondOpenReservationForTheSameEmptyCell() { Fixture fixture = new Fixture(); IrisJigsawPiece start = piece("start-object", false, - connector(IrisDirection.EAST_POSITIVE_X, "east", "start-east", "door") - .setPosition(new IrisPosition(2, 0, 1)), - connector(IrisDirection.SOUTH_POSITIVE_Z, "south", "start-south", "door") - .setPosition(new IrisPosition(1, 0, 2))); + connector(JigsawDirection.EAST_POSITIVE_X, "east", "start-east", "door") + .setPosition(new BlockPosition(2, 0, 1)), + connector(JigsawDirection.SOUTH_POSITIVE_Z, "south", "start-south", "door") + .setPosition(new BlockPosition(1, 0, 2))); IrisJigsawPiece east = piece("east-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "terminal", "door", "unused") - .setPosition(new IrisPosition(0, 0, 1)), - connector(IrisDirection.SOUTH_POSITIVE_Z, "grow", "east-south", "door") - .setPosition(new IrisPosition(1, 0, 2))); + connector(JigsawDirection.WEST_NEGATIVE_X, "terminal", "door", "unused") + .setPosition(new BlockPosition(0, 0, 1)), + connector(JigsawDirection.SOUTH_POSITIVE_Z, "grow", "east-south", "door") + .setPosition(new BlockPosition(1, 0, 2))); IrisJigsawPiece conflicting = piece("conflicting-object", false, - connector(IrisDirection.NORTH_NEGATIVE_Z, "terminal", "door", "unused") - .setPosition(new IrisPosition(1, 0, 0)), - connector(IrisDirection.EAST_POSITIVE_X, "grow", "south-east", "door") - .setPosition(new IrisPosition(2, 0, 1))); + connector(JigsawDirection.NORTH_NEGATIVE_Z, "terminal", "door", "unused") + .setPosition(new BlockPosition(1, 0, 0)), + connector(JigsawDirection.EAST_POSITIVE_X, "grow", "south-east", "door") + .setPosition(new BlockPosition(2, 0, 1))); IrisJigsawPiece compatible = piece("compatible-object", false, - connector(IrisDirection.NORTH_NEGATIVE_Z, "terminal", "door", "unused") - .setPosition(new IrisPosition(1, 0, 0))); + connector(JigsawDirection.NORTH_NEGATIVE_Z, "terminal", "door", "unused") + .setPosition(new BlockPosition(1, 0, 0))); IrisJigsawPiece cap = piece("cap-object", true, - connector(IrisDirection.NORTH_NEGATIVE_Z, "terminal", "door", "unused") - .setPosition(new IrisPosition(1, 0, 0))); + connector(JigsawDirection.NORTH_NEGATIVE_Z, "terminal", "door", "unused") + .setPosition(new BlockPosition(1, 0, 0))); cap.setRules(new IrisJigsawPieceRules().setTerminal(true)); fixture.pool("start", pool("", "start-piece")); fixture.pool("east", pool("caps", "east-piece")); @@ -1032,14 +1029,14 @@ public class StructureAssemblerTest { fixture.piece("conflicting-piece", conflicting); fixture.piece("compatible-piece", compatible); fixture.piece("cap-piece", cap); - fixture.object("start-object", new IrisObject(3, 1, 3)); - fixture.object("east-object", new IrisObject(3, 1, 3)); - fixture.object("conflicting-object", new IrisObject(3, 1, 3)); - fixture.object("compatible-object", new IrisObject(3, 1, 3)); - fixture.object("cap-object", new IrisObject(3, 1, 3)); + fixture.object("start-object", new ObjectFrame(3, 1, 3)); + fixture.object("east-object", new ObjectFrame(3, 1, 3)); + fixture.object("conflicting-object", new ObjectFrame(3, 1, 3)); + fixture.object("compatible-object", new ObjectFrame(3, 1, 3)); + fixture.object("cap-object", new ObjectFrame(3, 1, 3)); IrisStructure structure = structure("start", 2) .setMode(IrisJigsawMode.PLANAR_JIGSAW) - .setCellSize(new IrisPosition(3, 1, 3)) + .setCellSize(new BlockPosition(3, 1, 3)) .setRequireCaps(true); List placed = completedPieces( @@ -1059,7 +1056,7 @@ public class StructureAssemblerTest { startPool.getPieces().getFirst().setChance(0D); fixture.pool("start", startPool); fixture.piece("start-piece", start); - fixture.object("start-object", new IrisObject(1, 1, 1)); + fixture.object("start-object", new ObjectFrame(1, 1, 1)); StructureAssemblyResult result = fixture.assembler(structure("start", 1), 0, 0, 0) .assemble(new RNG(73L)); @@ -1072,18 +1069,18 @@ public class StructureAssemblerTest { public void branchingGeometryReturnsATypedHardCapFailure() { Fixture fixture = new Fixture(); IrisJigsawConnector[] connectors = { - connector(IrisDirection.NORTH_NEGATIVE_Z, "branch", "door", "door"), - connector(IrisDirection.EAST_POSITIVE_X, "branch", "door", "door"), - connector(IrisDirection.SOUTH_POSITIVE_Z, "branch", "door", "door"), - connector(IrisDirection.WEST_NEGATIVE_X, "branch", "door", "door"), - connector(IrisDirection.UP_POSITIVE_Y, "branch", "door", "door"), - connector(IrisDirection.DOWN_NEGATIVE_Y, "branch", "door", "door") + connector(JigsawDirection.NORTH_NEGATIVE_Z, "branch", "door", "door"), + connector(JigsawDirection.EAST_POSITIVE_X, "branch", "door", "door"), + connector(JigsawDirection.SOUTH_POSITIVE_Z, "branch", "door", "door"), + connector(JigsawDirection.WEST_NEGATIVE_X, "branch", "door", "door"), + connector(JigsawDirection.UP_POSITIVE_Y, "branch", "door", "door"), + connector(JigsawDirection.DOWN_NEGATIVE_Y, "branch", "door", "door") }; IrisJigsawPiece node = piece("node-object", false, connectors); fixture.pool("start", pool("", "node-piece")); fixture.pool("branch", pool("terminal", "node-piece")); fixture.piece("node-piece", node); - fixture.object("node-object", new IrisObject(1, 1, 1)); + fixture.object("node-object", new ObjectFrame(1, 1, 1)); StructureAssemblyResult result = fixture.assembler(structure("start", 10), 0, 0, 0) .assemble(new RNG(83L)); @@ -1093,9 +1090,9 @@ public class StructureAssemblerTest { assertFalse(result.hasOutput()); } - private static IrisJigsawConnector connector(IrisDirection direction, String pool, String name, String targetName) { + private static IrisJigsawConnector connector(JigsawDirection direction, String pool, String name, String targetName) { return new IrisJigsawConnector() - .setPosition(new IrisPosition()) + .setPosition(new BlockPosition(0, 0, 0)) .setDirection(direction) .setPool(pool == null || pool.isBlank() ? "terminal" : pool) .setName(name) @@ -1105,7 +1102,7 @@ public class StructureAssemblerTest { private static IrisJigsawPiece piece(String object, boolean rotatable, IrisJigsawConnector... connectors) { IrisJigsawPiece piece = new IrisJigsawPiece().setObject(object).setRotatable(rotatable); - piece.getConnectors().add(connectors); + piece.getConnectors().addAll(List.of(connectors)); return piece; } @@ -1123,17 +1120,17 @@ public class StructureAssemblerTest { ) { Fixture fixture = new Fixture(); IrisJigsawPiece start = piece("start-object", false, - connector(IrisDirection.EAST_POSITIVE_X, "target", "start", "door")) + connector(JigsawDirection.EAST_POSITIVE_X, "target", "start", "door")) .setCollidable(placedCollidable); IrisJigsawPiece candidate = piece("candidate-object", false, - connector(IrisDirection.WEST_NEGATIVE_X, "terminal", "door", "unused")) + connector(JigsawDirection.WEST_NEGATIVE_X, "terminal", "door", "unused")) .setCollidable(candidateCollidable); fixture.pool("start", pool("", "start-piece")); fixture.pool("target", pool("", "candidate-piece")); fixture.piece("start-piece", start); fixture.piece("candidate-piece", candidate); - fixture.object("start-object", new IrisObject(3, 3, 3)); - fixture.object("candidate-object", new IrisObject(3, 3, 3)); + fixture.object("start-object", new ObjectFrame(3, 3, 3)); + fixture.object("candidate-object", new ObjectFrame(3, 3, 3)); return fixture.assembler(structure("start", 1), 0, 0, 0).assemble(new RNG(137L)); } @@ -1165,7 +1162,7 @@ public class StructureAssemblerTest { } private static PlacedStructurePiece bounds(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { - return new PlacedStructurePiece(null, null, 0, 0, 0, null, minX, minY, minZ, maxX, maxY, maxZ); + return new PlacedStructurePiece(null, null, null, 0, 0, 0, null, minX, minY, minZ, maxX, maxY, maxZ); } private static List completedPieces(StructureAssembler assembler, RNG rng) { @@ -1195,26 +1192,26 @@ public class StructureAssemblerTest { } private static final class Fixture { - private final IrisData data = mock(IrisData.class); + private final MapStructureResolver resolver = new MapStructureResolver(); private Fixture() { - ModuleResourceFixture.of(data).resource(StructureResources.POOLS, "terminal", new IrisJigsawPool()); + resolver.pool("terminal", new IrisJigsawPool()); } private void pool(String key, IrisJigsawPool pool) { - ModuleResourceFixture.of(data).resource(StructureResources.POOLS, key, pool); + resolver.pool(key, pool); } private void piece(String key, IrisJigsawPiece piece) { - ModuleResourceFixture.of(data).resource(StructureResources.PIECES, key, piece); + resolver.piece(key, piece); } - private void object(String key, IrisObject object) { - when(data.load(IrisObject.class, key, false)).thenReturn(object); + private void object(String key, ObjectFrame object) { + resolver.object(key, object); } private StructureAssembler assembler(IrisStructure structure, int x, int y, int z) { - return StructureAssembler.forData(data, structure, new IrisPosition(x, y, z), ModuleLogs.discarding()); + return StructureAssembler.forResolver("test", resolver, structure, new BlockPosition(x, y, z)); } } } diff --git a/core/src/test/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolverTest.java b/core/src/test/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolverTest.java index 45f121783..52a8bd00a 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolverTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolverTest.java @@ -1,23 +1,16 @@ package art.arcane.iris.engine.framework; -import art.arcane.iris.builtin.carve.CaveLavaHeightSettings; -import art.arcane.iris.core.modules.BuiltInPack; import art.arcane.iris.builtin.structure.StructureAnchorMode; import art.arcane.iris.builtin.structure.StructurePlacement; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.spi.IrisPlatform; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.spi.PlatformRegistries; import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.matter.MatterCavern; -import org.junit.After; -import org.junit.Before; +import com.volmit.mantle.CarvedVoid; import org.junit.Test; import java.util.Arrays; import java.util.HashSet; +import java.util.Optional; import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.IntPredicate; import static art.arcane.iris.engine.framework.StructurePlacementFixtures.placement; @@ -27,31 +20,9 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.RETURNS_DEEP_STUBS; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; public class StructureCaveAnchorResolverTest { - @Before - public void bindPlatform() { - IrisPlatforms.unbind(); - PlatformBlockState block = mock(PlatformBlockState.class); - PlatformRegistries registries = mock(PlatformRegistries.class); - when(registries.block(anyString())).thenReturn(block); - IrisPlatform platform = mock(IrisPlatform.class); - when(platform.registries()).thenReturn(registries); - IrisPlatforms.bind(platform); - } - - @After - public void unbindPlatform() { - IrisPlatforms.unbind(); - } + private final AtomicInteger surfaceReads = new AtomicInteger(); @Test public void floorRequiresSolidBoundaryAndUpwardClearance() { @@ -143,33 +114,33 @@ public class StructureCaveAnchorResolverTest { @Test public void dryCaveUnderSubmergedSurfaceUsesAnchorCavernState() { - Engine engine = engineWithFloorAnchor(new MatterCavern(true, "", (byte) 0), 0); + StructureTestWorld world = worldWithFloorAnchor(CarvedVoid.OPEN, 0); StructureCaveAnchorResolver.Anchor anchor = StructureCaveAnchorResolver.resolve( - engine, floorPlacement(false), 0, 0, new RNG(87234L)); + world, floorPlacement(false), 0, 0, new RNG(87234L)); assertNotNull(anchor); assertEquals(-54, anchor.y()); - verify(engine, never()).getHeight(anyInt(), anyInt(), eq(true)); + assertEquals(0, surfaceReads.get()); } @Test public void wetCaveUnderDrySurfaceIsRejectedAtTheAnchor() { - Engine engine = engineWithFloorAnchor(new MatterCavern(true, "", (byte) 1), 200); + StructureTestWorld world = worldWithFloorAnchor(CarvedVoid.FLUID, 200); StructureCaveAnchorResolver.Anchor anchor = StructureCaveAnchorResolver.resolve( - engine, floorPlacement(false), 0, 0, new RNG(87234L)); + world, floorPlacement(false), 0, 0, new RNG(87234L)); assertNull(anchor); - verify(engine, never()).getHeight(anyInt(), anyInt(), eq(true)); + assertEquals(0, surfaceReads.get()); } @Test public void dryPolicyHonorsExplicitLiquidsAndDefaultLavaHeight() { - MatterCavern air = new MatterCavern(true, "", (byte) 0); - MatterCavern water = new MatterCavern(true, "", (byte) 1); - MatterCavern lava = new MatterCavern(true, "", (byte) 2); - MatterCavern forcedAir = new MatterCavern(true, "", (byte) 3); + CarvedVoid air = CarvedVoid.OPEN; + CarvedVoid water = CarvedVoid.FLUID; + CarvedVoid lava = CarvedVoid.LAVA; + CarvedVoid forcedAir = CarvedVoid.AIR; assertFalse(StructureCaveAnchorResolver.acceptsAnchorFluid(false, air, 8, 8)); assertTrue(StructureCaveAnchorResolver.acceptsAnchorFluid(false, air, 9, 8)); @@ -177,30 +148,22 @@ public class StructureCaveAnchorResolverTest { assertFalse(StructureCaveAnchorResolver.acceptsAnchorFluid(false, lava, 20, 8)); assertTrue(StructureCaveAnchorResolver.acceptsAnchorFluid(false, forcedAir, 0, 8)); assertTrue(StructureCaveAnchorResolver.acceptsAnchorFluid(true, water, 20, 8)); - assertFalse(StructureCaveAnchorResolver.acceptsAnchorFluid( - true, new MatterCavern(false, "", (byte) 0), 20, 8)); + assertFalse(StructureCaveAnchorResolver.acceptsAnchorFluid(true, null, 20, 8)); } - private static Engine engineWithFloorAnchor(MatterCavern anchorCavern, int surfaceHeight) { - Engine engine = mock(Engine.class, RETURNS_DEEP_STUBS); - IrisDimension dimension = mock(IrisDimension.class); - MatterCavern carvedAir = new MatterCavern(true, "", (byte) 0); - when(engine.getMinHeight()).thenReturn(-64); - when(engine.getHeight()).thenReturn(384); - when(engine.getHeight(anyInt(), anyInt(), eq(true))).thenReturn(surfaceHeight); - when(engine.getDimension()).thenReturn(dimension); - when(dimension.getFluidHeight()).thenReturn(127); - when(dimension.getModuleSettings()).thenReturn(BuiltInPack.settings(new CaveLavaHeightSettings(8))); - when(engine.getMantle().getMantle().get( - anyInt(), anyInt(), anyInt(), eq(MatterCavern.class))) - .thenAnswer(invocation -> { - int mantleY = invocation.getArgument(1); + private StructureTestWorld worldWithFloorAnchor(CarvedVoid anchorVoid, int surfaceHeight) { + return new StructureTestWorld() + .fluidHeight(127) + .highest((x, z) -> { + surfaceReads.incrementAndGet(); + return surfaceHeight; + }) + .carved((x, mantleY, z) -> { if (mantleY == 10) { - return anchorCavern; + return Optional.of(anchorVoid); } - return mantleY == 11 || mantleY == 12 ? carvedAir : null; + return mantleY == 11 || mantleY == 12 ? Optional.of(CarvedVoid.OPEN) : Optional.empty(); }); - return engine; } private static StructurePlacement floorPlacement(boolean underwater) { diff --git a/core/src/test/java/art/arcane/iris/engine/framework/StructurePlacementScopeTest.java b/core/src/test/java/art/arcane/iris/engine/framework/StructurePlacementScopeTest.java index 5e4b2a603..c33151786 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/StructurePlacementScopeTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/StructurePlacementScopeTest.java @@ -1,27 +1,22 @@ package art.arcane.iris.engine.framework; -import art.arcane.iris.engine.IrisComplex; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.builtin.structure.StructureAnchorMode; import art.arcane.iris.builtin.structure.StructurePlacement; -import art.arcane.volmlib.util.collection.KList; +import com.volmit.resource.ResourceId; +import com.volmit.world.BiomeSample; import org.junit.Test; +import java.util.List; +import java.util.Optional; + import static art.arcane.iris.engine.framework.StructurePlacementFixtures.placement; -import static art.arcane.iris.engine.framework.StructurePlacementFixtures.declare; -import static art.arcane.iris.engine.framework.StructurePlacementFixtures.declaring; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.RETURNS_DEEP_STUBS; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; public class StructurePlacementScopeTest { + private static final ResourceId CAVE_BIOME = ResourceId.parse("test:biome/caves"); + @Test public void caveBiomeContributesOnlyCaveAnchoredPlacements() { StructurePlacement surfacePlacement = new StructurePlacement(); @@ -29,31 +24,15 @@ public class StructurePlacementScopeTest { StructurePlacement invalidCaveScopePlacement = placement("anchor", StructureAnchorMode.SURFACE); StructurePlacement regionPlacement = new StructurePlacement(); StructurePlacement dimensionPlacement = new StructurePlacement(); + StructureTestWorld world = new StructureTestWorld() + .biome(StructureTestWorld.SURFACE_BIOME, surfacePlacement) + .biome(CAVE_BIOME, cavePlacement, invalidCaveScopePlacement) + .region(StructureTestWorld.REGION, regionPlacement) + .dimension(dimensionPlacement, cavePlacement) + .biomes((x, y, z) -> new BiomeSample( + StructureTestWorld.REGION, StructureTestWorld.SURFACE_BIOME, Optional.of(CAVE_BIOME))); - IrisBiome surfaceBiome = declare(new IrisBiome(), surfacePlacement); - IrisBiome caveBiome = declare(new IrisBiome(), cavePlacement, invalidCaveScopePlacement); - IrisRegion region = declare(new IrisRegion(), regionPlacement); - Engine engine = mock(Engine.class, RETURNS_DEEP_STUBS); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - IrisComplex complex = engine.getComplex(); - IrisDimension dimension = mock(IrisDimension.class); - KList dimensionStructures = new KList<>(); - dimensionStructures.add(dimensionPlacement); - dimensionStructures.add(cavePlacement); - KList allRegions = new KList<>(); - allRegions.add(region); - KList allBiomes = new KList<>(); - allBiomes.add(surfaceBiome); - allBiomes.add(caveBiome); - when(engine.getDimension()).thenReturn(dimension); - when(engine.getAllBiomes()).thenReturn(allBiomes); - when(dimension.getModuleSettings()).thenReturn(declaring(dimensionStructures)); - when(dimension.getAllRegions(engine)).thenReturn(allRegions); - when(complex.getTrueBiomeStream().get(8, 8)).thenReturn(surfaceBiome); - when(complex.getCaveBiomeStream().get(8, 8)).thenReturn(caveBiome); - when(complex.getRegionStream().get(8, 8)).thenReturn(region); - - KList placements = StructurePlacementScope.placementsAt(engine, 0, 0); + List placements = StructurePlacementScope.placementsAt(world, 0, 0); assertEquals(4, placements.size()); assertTrue(placements.contains(surfacePlacement)); @@ -66,23 +45,12 @@ public class StructurePlacementScopeTest { @Test public void dimensionOnlyPlacementsDoNotResolveBiomeScopes() { StructurePlacement dimensionPlacement = new StructurePlacement(); - Engine engine = mock(Engine.class, RETURNS_DEEP_STUBS); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - IrisComplex complex = engine.getComplex(); - IrisDimension dimension = mock(IrisDimension.class); - KList dimensionStructures = new KList<>(); - dimensionStructures.add(dimensionPlacement); - when(engine.getDimension()).thenReturn(dimension); - when(engine.getAllBiomes()).thenReturn(new KList<>()); - when(dimension.getModuleSettings()).thenReturn(declaring(dimensionStructures)); - when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); + StructureTestWorld world = new StructureTestWorld().dimension(dimensionPlacement); - KList placements = StructurePlacementScope.placementsAt(engine, 0, 0); + List placements = StructurePlacementScope.placementsAt(world, 0, 0); assertEquals(1, placements.size()); assertTrue(placements.contains(dimensionPlacement)); - verify(complex.getTrueBiomeStream(), never()).get(8, 8); - verify(complex.getCaveBiomeStream(), never()).get(8, 8); - verify(complex.getRegionStream(), never()).get(8, 8); + assertEquals(0, world.columnReads()); } } diff --git a/core/src/test/java/art/arcane/iris/engine/framework/StructureTestWorld.java b/core/src/test/java/art/arcane/iris/engine/framework/StructureTestWorld.java new file mode 100644 index 000000000..966c7d867 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/framework/StructureTestWorld.java @@ -0,0 +1,443 @@ +package art.arcane.iris.engine.framework; + +import art.arcane.iris.builtin.structure.StructurePlacement; +import art.arcane.iris.builtin.structure.StructurePlacementSettings; +import art.arcane.iris.engine.framework.structure.assembly.StructureAssembly; +import com.volmit.IrisFeature; +import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.config.FeatureSettings; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.Level; +import com.volmit.config.PackSettings; +import com.volmit.config.SettingsStack; +import com.volmit.data.SavedKey; +import com.volmit.geometry.BlockBox; +import com.volmit.geometry.BlockPosition; +import com.volmit.host.ModuleLogs; +import com.volmit.item.ItemRegistry; +import com.volmit.mantle.CarvedVoid; +import com.volmit.noise.NoiseFactory; +import com.volmit.object.PackObjects; +import com.volmit.placement.PlacementRecord; +import com.volmit.placement.Placements; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.resource.ResourceKind; +import com.volmit.world.BiomeKind; +import com.volmit.world.BiomeSample; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; +import com.volmit.world.TerrainSample; +import com.volmit.world.TerrainSampler; +import com.volmit.world.UpperDimension; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.OptionalInt; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; +import java.util.function.IntBinaryOperator; + +/** + * A world as structure placement sees it, for tests: the declarations of the dimension, regions and biomes, the biome of + * each column, its height and the voids carved into it. Everything is set before the first read. + */ +public final class StructureTestWorld implements PackWorld { + public static final ResourceId DIMENSION = ResourceId.parse("test:dimension/overworld"); + public static final ResourceId REGION = ResourceId.parse("test:region/plains"); + public static final ResourceId SURFACE_BIOME = ResourceId.parse("test:biome/plains"); + private static final int WORLD_LIMIT_BLOCKS = 30_000_000; + + private PackResources resources = new FakePack(); + private final List> declarations = new ArrayList<>(); + private final List assemblies = new ArrayList<>(); + private final Map, Object> states = new HashMap<>(); + private final AtomicInteger columnReads = new AtomicInteger(); + private final AtomicInteger placementScans = new AtomicInteger(); + private int minY = -64; + private int height = 384; + private int fluidHeight = 63; + private long placementSeed = 0L; + private Long worldSeed; + private PackWorld host; + private IntBinaryOperator highest = (x, z) -> 64; + private BiomeColumns biomeColumns = (x, y, z) -> new BiomeSample(REGION, SURFACE_BIOME, Optional.empty()); + private CarvedColumns carved = (x, y, z) -> Optional.empty(); + + /** The world that gives this one its pack, its services and the placement stages it runs. */ + public StructureTestWorld hostedBy(PackWorld value) { + host = value; + return this; + } + + /** The world's own seed, when it differs from the one placement starts from. */ + public StructureTestWorld worldSeed(long value) { + worldSeed = value; + return this; + } + + /** The pack the world generates, in place of the empty one. */ + public StructureTestWorld resources(PackResources value) { + resources = value; + return this; + } + + public StructureTestWorld minY(int value) { + minY = value; + return this; + } + + public StructureTestWorld height(int value) { + height = value; + return this; + } + + public StructureTestWorld fluidHeight(int value) { + fluidHeight = value; + return this; + } + + public StructureTestWorld placementSeed(long value) { + placementSeed = value; + return this; + } + + public StructureTestWorld highest(IntBinaryOperator value) { + highest = value; + return this; + } + + public StructureTestWorld biomes(BiomeColumns value) { + biomeColumns = value; + return this; + } + + public StructureTestWorld carved(CarvedColumns value) { + carved = value; + return this; + } + + public StructureTestWorld assembling(StructureAssembly assembly) { + assemblies.add(assembly); + return this; + } + + public StructureTestWorld dimension(StructurePlacement... placements) { + return declare(Level.DIMENSION, DIMENSION, placements); + } + + public StructureTestWorld region(ResourceId region, StructurePlacement... placements) { + return declare(Level.REGION, region, placements); + } + + public StructureTestWorld biome(ResourceId biome, StructurePlacement... placements) { + return declare(Level.BIOME, biome, placements); + } + + private StructureTestWorld declare(Level level, ResourceId source, StructurePlacement[] placements) { + declarations.add(new Entry<>(level, source, StructurePlacementFixtures.placementSettings(List.of(placements)))); + return this; + } + + /** The placements the dimension declares. */ + public List dimensionPlacements() { + return declarations.stream().filter(entry -> entry.level() == Level.DIMENSION) + .flatMap(entry -> entry.value().placements().stream()).toList(); + } + + /** How many times the placements of a chunk were worked out. */ + public int placementScans() { + return placementScans.get(); + } + + /** How many columns placement asked the world's layout about. */ + public int columnReads() { + return columnReads.get(); + } + + @Override + public long seed() { + return worldSeed == null ? placementSeed : worldSeed; + } + + @Override + public long seed(ResourceId purpose) { + return placementSeed; + } + + @Override + public PackResources resources() { + return host == null ? resources : host.resources(); + } + + @Override + public PackSettings settings() { + return new PackSettings() { + @Override + @SuppressWarnings("unchecked") + public SettingsStack declared(Class featureType) { + return featureType == StructurePlacementSettings.class + ? (SettingsStack) SettingsStack.of(declarations) : SettingsStack.empty(); + } + + @Override + public PackResources resources() { + return StructureTestWorld.this.resources(); + } + }; + } + + @Override + public int minWorldY() { + return minY; + } + + @Override + public Optional running() { + return Optional.of(new Running()); + } + + @Override + public T state(Class type, Function create) { + if (type == StructurePlacementScope.ScopeIndex.class) { + placementScans.incrementAndGet(); + } + Object known = states.get(type); + if (known == null) { + known = create.apply(this); + states.put(type, known); + } + return type.cast(known); + } + + @Override + public Placements placements() { + if (host == null) { + throw new UnsupportedOperationException("No placements here"); + } + return host.placements(); + } + + @Override + public ModuleLog log() { + return ModuleLogs.discarding(); + } + + @Override + @SuppressWarnings("unchecked") + public List services(Class service) { + if (host != null) { + return host.services(service); + } + return service == StructureAssembly.class ? (List) List.copyOf(assemblies) : List.of(); + } + + /** The biome of a column at a height. */ + @FunctionalInterface + public interface BiomeColumns { + BiomeSample at(int worldX, int y, int worldZ); + } + + /** The void carved into a block, if any. */ + @FunctionalInterface + public interface CarvedColumns { + Optional at(int worldX, int y, int worldZ); + } + + private final class Running implements RunningWorld { + private final TerrainSampler layout = new Layout(); + + @Override + public TerrainSampler layout() { + return layout; + } + + @Override + public FeatureSettings settings() { + return new FeatureSettings() { + @Override + @SuppressWarnings("unchecked") + public SettingsStack at(Class featureType, int worldX, int worldZ) { + if (featureType != StructurePlacementSettings.class) { + return SettingsStack.empty(); + } + columnReads.incrementAndGet(); + BiomeSample column = biomeColumns.at(worldX, minY, worldZ); + List> here = new ArrayList<>(); + for (Entry declaration : declarations) { + if (declaration.level() == Level.DIMENSION + || declaration.source().equals(column.region()) + || declaration.source().equals(column.surfaceBiome())) { + here.add(declaration); + } + } + return (SettingsStack) SettingsStack.of(here); + } + + @Override + @SuppressWarnings("unchecked") + public Optional declaredBy(ResourceId biome, Class featureType) { + if (featureType != StructurePlacementSettings.class) { + return Optional.empty(); + } + return declarations.stream().filter(entry -> entry.level() == Level.BIOME && entry.source().equals(biome)) + .map(entry -> (F) entry.value()).findFirst(); + } + }; + } + + @Override + public int highest(int worldX, int worldZ, boolean ignoreFluid) { + return highest.applyAsInt(worldX, worldZ); + } + + @Override + public List caveFloors(int chunkX, int chunkZ) { + return List.of(); + } + + @Override + public Optional placementAt(int worldX, int y, int worldZ) { + return Optional.empty(); + } + + @Override + public Optional carvedAt(int worldX, int y, int worldZ) { + return carved.at(worldX, y, worldZ); + } + + @Override + public T saved(SavedKey key) { + throw new UnsupportedOperationException("No saved state here"); + } + + @Override + public Optional sky() { + return Optional.empty(); + } + + @Override + public Set platformLootTables() { + return Set.of(); + } + + @Override + public boolean debug() { + return false; + } + } + + private final class Layout implements TerrainSampler { + @Override + public BlockBox bounds() { + return new BlockBox(-WORLD_LIMIT_BLOCKS, 0, -WORLD_LIMIT_BLOCKS, WORLD_LIMIT_BLOCKS, height, WORLD_LIMIT_BLOCKS); + } + + @Override + public TerrainSample column(int worldX, int worldZ) { + throw new UnsupportedOperationException("No terrain columns here"); + } + + @Override + public double surfaceY(int worldX, int worldZ) { + return highest.applyAsInt(worldX, worldZ); + } + + @Override + public BiomeSample biome(int worldX, int y, int worldZ) { + return biomeColumns.at(worldX, y, worldZ); + } + + @Override + public int fluidHeight() { + return fluidHeight; + } + + @Override + public OptionalInt upperDimensionY(int worldX, int worldZ) { + return OptionalInt.empty(); + } + + @Override + public BiomeKind surfaceKind(int worldX, int worldZ) { + throw new UnsupportedOperationException("No biome kinds here"); + } + + @Override + public Optional surfaceBlock(int worldX, int worldZ) { + return Optional.empty(); + } + + @Override + public double biomeHeight(ResourceId biome, int worldX, int worldZ, long seed) { + throw new UnsupportedOperationException("No biome heights here"); + } + + @Override + public Optional skyBiome(ResourceId biome, int worldX, int worldZ) { + return Optional.empty(); + } + + @Override + public int minWorldY() { + return minY; + } + + @Override + public Optional upperDimension() { + return Optional.empty(); + } + } + + /** A pack with no resources at all: placement only reads its id. */ + private static final class FakePack implements PackResources { + private final UUID snapshot = UUID.randomUUID(); + + @Override + public ResourceId packId() { + return ResourceId.parse("test:pack"); + } + + @Override + public UUID snapshotId() { + return snapshot; + } + + @Override + public BlockRegistry blocks() { + throw new UnsupportedOperationException("No blocks here"); + } + + @Override + public ItemRegistry items() { + throw new UnsupportedOperationException("No items here"); + } + + @Override + public NoiseFactory noise() { + throw new UnsupportedOperationException("No noise here"); + } + + @Override + public PackObjects objects() { + throw new UnsupportedOperationException("No objects here"); + } + + @Override + public Optional find(ResourceKind kind, ResourceId id) { + return Optional.empty(); + } + + @Override + public List ids(ResourceKind kind) { + return List.of(); + } + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/IrisObjectFrameReaderTest.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/IrisObjectFrameReaderTest.java index 3c51ae1a8..e3b235c19 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/structure/IrisObjectFrameReaderTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/IrisObjectFrameReaderTest.java @@ -1,6 +1,5 @@ package art.arcane.iris.engine.framework.structure; -import art.arcane.iris.engine.object.prefab.IrisObject; import org.junit.Test; import java.io.ByteArrayInputStream; @@ -15,14 +14,14 @@ import static org.junit.Assert.assertTrue; public class IrisObjectFrameReaderTest { @Test public void acceptsModernTileFrame() throws Exception { - IrisObject object = readObject(tile -> { + ObjectFrame object = readObject(tile -> { tile.writeUTF("minecraft:chest"); tile.writeUTF("{}"); }); - assertEquals(1, object.getW()); - assertEquals(1, object.getH()); - assertEquals(1, object.getD()); + assertEquals(1, object.width()); + assertEquals(1, object.height()); + assertEquals(1, object.depth()); } @Test @@ -146,7 +145,7 @@ public class IrisObjectFrameReaderTest { new ByteArrayInputStream(content), "objects/trailing.iob")); } - private IrisObject readObject(TileWriter tileWriter) throws Exception { + private ObjectFrame readObject(TileWriter tileWriter) throws Exception { return IrisObjectFrameReader.readBounds( new ByteArrayInputStream(objectBytes(tileWriter)), "objects/test.iob"); } diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/MapStructureResolver.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/MapStructureResolver.java new file mode 100644 index 000000000..a4b363517 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/MapStructureResolver.java @@ -0,0 +1,44 @@ +package art.arcane.iris.engine.framework.structure; + +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; + +import java.util.HashMap; +import java.util.Map; + +/** A structure graph resolver for tests: the pools, pieces and object sizes a test sets by key, and nothing else. */ +public final class MapStructureResolver implements StructureGraphResolver { + private final Map pools = new HashMap<>(); + private final Map pieces = new HashMap<>(); + private final Map objects = new HashMap<>(); + + public MapStructureResolver pool(String key, IrisJigsawPool pool) { + pools.put(key, pool); + return this; + } + + public MapStructureResolver piece(String key, IrisJigsawPiece piece) { + pieces.put(key, piece); + return this; + } + + public MapStructureResolver object(String key, ObjectFrame object) { + objects.put(key, object); + return this; + } + + @Override + public IrisJigsawPool loadPool(String key) { + return pools.get(key); + } + + @Override + public IrisJigsawPiece loadPiece(String key) { + return pieces.get(key); + } + + @Override + public ObjectFrame loadObject(String key) { + return objects.get(key); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/NativeStartPlannerTest.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/NativeStartPlannerTest.java index 0afe13c15..8de0a6585 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/structure/NativeStartPlannerTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/NativeStartPlannerTest.java @@ -1,10 +1,8 @@ package art.arcane.iris.engine.framework.structure; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.EngineGeneration; import art.arcane.iris.engine.framework.SeedManager; import art.arcane.iris.engine.framework.StructurePlacementGrid; +import art.arcane.iris.engine.framework.StructureTestWorld; import art.arcane.iris.builtin.structure.StructureStilts; import art.arcane.iris.builtin.structure.StructureTerrain; import art.arcane.iris.builtin.structure.StructureTerrainMode; @@ -44,7 +42,7 @@ import static org.mockito.Mockito.when; public class NativeStartPlannerTest { @Test public void undergroundPlanIsDeterministicAndUsesConfiguredBand() { - Engine engine = engine(982374L, -64, 384, 90); + StructureTestWorld engine = engine(982374L, -64, 384, 90); StructurePlacement placement = TestSettings.with(nativePlacement(), "underground", true, "minHeight", -45, "maxHeight", -20); NativeStartPlanner.Plan first = NativeStartPlanner.planAt(engine, placement, 12, -7); @@ -60,7 +58,7 @@ public class NativeStartPlannerTest { @Test public void undergroundBandOutsideWorldBoundsSkipsTheCandidate() { - Engine engine = engine(982374L, -64, 384, 90); + StructureTestWorld engine = engine(982374L, -64, 384, 90); StructurePlacement placement = TestSettings.with(nativePlacement(), "underground", true, "minHeight", 500, "maxHeight", 600); assertNull(NativeStartPlanner.planAt(engine, placement, 12, -7)); @@ -68,7 +66,7 @@ public class NativeStartPlannerTest { @Test public void surfacePlanUsesIrisTerrainAndHonorsHeightGate() { - Engine engine = engine(77L, -64, 384, 150); + StructureTestWorld engine = engine(77L, -64, 384, 150); StructurePlacement placement = TestSettings.with(nativePlacement(), "minHeight", 80, "maxHeight", 90); NativeStartPlanner.Plan plan = NativeStartPlanner.planAt(engine, placement, 0, 0); @@ -107,7 +105,7 @@ public class NativeStartPlannerTest { @Test public void underwaterFlagRejectsSubmergedColumnsForSurfaceAndUndergroundPlans() { - Engine engine = engine(77L, -64, 384, 63); + StructureTestWorld engine = engine(77L, -64, 384, 63); StructurePlacement placement = nativePlacement(); assertNull(NativeStartPlanner.planAt(engine, placement, 0, 0)); @@ -121,7 +119,7 @@ public class NativeStartPlannerTest { @Test public void fluidHeightBoundaryIsShoreForPlannerAndLocator() { - Engine engine = engine(77L, -64, 384, 64); + StructureTestWorld engine = engine(77L, -64, 384, 64); StructurePlacement placement = nativePlacement(); assertTrue(!NativeStartPlanner.isSubmerged(engine, 8, 8)); @@ -133,7 +131,7 @@ public class NativeStartPlannerTest { @Test public void duplicateSelectedStructureUsesOneDeterministicPlan() { - Engine engine = engine(77L, -64, 384, 150); + StructureTestWorld engine = engine(77L, -64, 384, 150); StructurePlacement first = TestSettings.with(nativePlacement(), "placementId", "first"); StructurePlacement second = TestSettings.with(nativePlacement(), "placementId", "second"); bindPlacements(engine, first, second); @@ -189,27 +187,17 @@ public class NativeStartPlannerTest { return placement; } - private Engine engine(long seed, int minHeight, int height, int terrainHeight) { - Engine engine = mock(Engine.class); - when(engine.getSeedManager()).thenReturn(new SeedManager(seed)); - when(engine.getMinHeight()).thenReturn(minHeight); - when(engine.getHeight()).thenReturn(height); - when(engine.getHeight(org.mockito.ArgumentMatchers.anyInt(), - org.mockito.ArgumentMatchers.anyInt(), org.mockito.ArgumentMatchers.eq(true))) - .thenReturn(terrainHeight); - IrisDimension dimension = mock(IrisDimension.class); - when(dimension.getFluidHeight()).thenReturn(64); - when(engine.getDimension()).thenReturn(dimension); - return engine; + private StructureTestWorld engine(long seed, int minHeight, int height, int terrainHeight) { + return new StructureTestWorld() + .placementSeed(new SeedManager(seed).getMantle()) + .minY(minHeight) + .height(height) + .highest((x, z) -> terrainHeight) + .fluidHeight(64); } - private void bindPlacements(Engine engine, StructurePlacement... placements) { - IrisDimension dimension = engine.getDimension(); - when(engine.getData()).thenReturn(mock(IrisData.class)); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(dimension.getModuleSettings()).thenReturn(declaring(placements)); - when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); - when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); + private void bindPlacements(StructureTestWorld engine, StructurePlacement... placements) { + engine.dimension(placements); } private void assertInvalid(StructurePlacement placement) { diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/PlanarJigsawWorkcellResolverTest.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/PlanarJigsawWorkcellResolverTest.java index 6c4b50acb..d66f51005 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/structure/PlanarJigsawWorkcellResolverTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/PlanarJigsawWorkcellResolverTest.java @@ -1,13 +1,12 @@ package art.arcane.iris.engine.framework.structure; -import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; 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.IrisJigsawWorkcell; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.structure.IrisStructure; +import com.volmit.geometry.BlockPosition; import org.junit.Test; import java.util.Map; @@ -19,14 +18,14 @@ import static org.junit.Assert.assertThrows; public class PlanarJigsawWorkcellResolverTest { @Test public void legacyCellSizeProducesSixEnabledRectangularWorkcells() { - IrisStructure structure = new IrisStructure().setCellSize(new IrisPosition(12, 7, 18)); + IrisStructure structure = new IrisStructure().setCellSize(new BlockPosition(12, 7, 18)); Map workcells = PlanarJigsawWorkcellResolver.resolve(structure); assertEquals(6, workcells.size()); for (PlanarJigsawWorkcellResolver.ResolvedWorkcell workcell : workcells.values()) { - assertEquals(new IrisPosition(12, 7, 18), workcell.dimensions()); + assertEquals(new BlockPosition(12, 7, 18), workcell.dimensions()); assertEquals(true, workcell.enabled()); } } @@ -60,13 +59,13 @@ public class PlanarJigsawWorkcellResolverTest { @Test public void canonicalDimensionsSwapRectangularRotatedVariants() { IrisJigsawPiece eastEnd = new IrisJigsawPiece(); - eastEnd.getConnectors().add(new IrisJigsawConnector().setDirection(IrisDirection.EAST_POSITIVE_X)); + eastEnd.getConnectors().add(new IrisJigsawConnector().setDirection(JigsawDirection.EAST_POSITIVE_X)); - IrisPosition dimensions = PlanarJigsawWorkcellResolver.canonicalDimensions( + BlockPosition dimensions = PlanarJigsawWorkcellResolver.canonicalDimensions( eastEnd, - new IrisObject(7, 5, 13)); + new ObjectFrame(7, 5, 13)); - assertEquals(new IrisPosition(13, 5, 7), dimensions); + assertEquals(new BlockPosition(13, 5, 7), dimensions); assertEquals(IrisJigsawWorkcellArchetype.END, IrisJigsawWorkcellArchetype.fromPiece(eastEnd)); assertFalse(IrisJigsawWorkcellArchetype.fromPiece(eastEnd) diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureGraphCompilerTest.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureGraphCompilerTest.java index da14b127b..70a919f42 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureGraphCompilerTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureGraphCompilerTest.java @@ -1,6 +1,6 @@ package art.arcane.iris.engine.framework.structure; -import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawCompatibility; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; @@ -10,8 +10,6 @@ import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceEntry; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceRules; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint; import art.arcane.iris.spi.IrisPlatform; @@ -19,6 +17,7 @@ import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.spi.PlatformRegistries; import art.arcane.volmlib.util.collection.KList; +import com.volmit.geometry.BlockPosition; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; @@ -60,8 +59,8 @@ public class StructureGraphCompilerTest { resolver.pools.put("pools/start", pool(entry("pieces/start", 1))); IrisStructure structure = structure("pools/start"); - StructureGraphCompilation first = StructureGraphCompiler.compile(structure, resolver); - StructureGraphCompilation second = StructureGraphCompiler.compile(structure, resolver); + StructureGraphCompilation first = compile(structure, resolver); + StructureGraphCompilation second = compile(structure, resolver); assertTrue(first.getDiagnostics().isEmpty()); assertTrue(first.isAssemblyViable()); @@ -84,7 +83,7 @@ public class StructureGraphCompilerTest { start.setFallback("pools/missing-fallback"); resolver.pools.put("pools/start", start); - StructureGraphCompilation result = StructureGraphCompiler.compile(structure("pools/start"), resolver); + StructureGraphCompilation result = compile(structure("pools/start"), resolver); assertCodes(result, StructureGraphDiagnostic.Code.INVALID_WEIGHT, @@ -98,15 +97,15 @@ public class StructureGraphCompilerTest { @Test public void reportsEmptyPoolsAndConnectorFieldFailures() { InMemoryResolver resolver = new InMemoryResolver(); - IrisJigsawConnector connector = connector(new IrisPosition(4, 1, 1), null, "", "path", "path"); + IrisJigsawConnector connector = connector(new BlockPosition(4, 1, 1), null, "", "path", "path"); resolver.objects.put("objects/start", object()); resolver.pieces.put("pieces/start", piece("objects/start", connector)); resolver.pools.put("pools/start", pool(entry("pieces/start", 1))); resolver.pools.put("pools/empty", pool()); - StructureGraphCompilation invalidConnector = StructureGraphCompiler.compile( + StructureGraphCompilation invalidConnector = compile( structure("pools/start"), resolver); - StructureGraphCompilation emptyStart = StructureGraphCompiler.compile( + StructureGraphCompilation emptyStart = compile( structure("pools/empty"), resolver); assertCodes(invalidConnector, @@ -120,9 +119,9 @@ public class StructureGraphCompilerTest { @Test public void reportsIncompatibleDirectionsAndUnreachablePieces() { - InMemoryResolver resolver = connectorGraph(false, IrisDirection.NORTH_NEGATIVE_Z); + InMemoryResolver resolver = connectorGraph(false, JigsawDirection.NORTH_NEGATIVE_Z); - StructureGraphCompilation result = StructureGraphCompiler.compile( + StructureGraphCompilation result = compile( structure("pools/start"), resolver); assertCodes(result, @@ -139,9 +138,9 @@ public class StructureGraphCompilerTest { @Test public void acceptsHorizontalRotationWithVanillaOneWayTargetMatching() { - InMemoryResolver resolver = connectorGraph(true, IrisDirection.NORTH_NEGATIVE_Z); + InMemoryResolver resolver = connectorGraph(true, JigsawDirection.NORTH_NEGATIVE_Z); - StructureGraphCompilation result = StructureGraphCompiler.compile( + StructureGraphCompilation result = compile( structure("pools/start"), resolver); assertTrue(result.getDiagnostics().isEmpty()); @@ -154,10 +153,10 @@ public class StructureGraphCompilerTest { @Test public void connectorNamesUseTheRuntimeExactMatchingContract() { - InMemoryResolver resolver = connectorGraph(false, IrisDirection.SOUTH_POSITIVE_Z); + InMemoryResolver resolver = connectorGraph(false, JigsawDirection.SOUTH_POSITIVE_Z); resolver.pieces.get("pieces/target").getConnectors().getFirst().setName(" door"); - StructureGraphCompilation result = StructureGraphCompiler.compile( + StructureGraphCompilation result = compile( structure("pools/start"), resolver); assertCodes(result, @@ -168,9 +167,9 @@ public class StructureGraphCompilerTest { @Test public void rejectsVerticalConnectorsThatYRotationCannotAlign() { - InMemoryResolver resolver = connectorGraph(true, IrisDirection.UP_POSITIVE_Y); + InMemoryResolver resolver = connectorGraph(true, JigsawDirection.UP_POSITIVE_Y); - StructureGraphCompilation result = StructureGraphCompiler.compile( + StructureGraphCompilation result = compile( structure("pools/start"), resolver); assertCodes(result, @@ -180,34 +179,34 @@ public class StructureGraphCompilerTest { @Test public void alignedConnectorsRequireMatchingTopOrientation() { - InMemoryResolver resolver = connectorGraph(false, IrisDirection.SOUTH_POSITIVE_Z); + InMemoryResolver resolver = connectorGraph(false, JigsawDirection.SOUTH_POSITIVE_Z); IrisJigsawConnector source = resolver.pieces.get("pieces/start").getConnectors().getFirst(); IrisJigsawConnector target = resolver.pieces.get("pieces/target").getConnectors().getFirst(); source.setJoint(JigsawJoint.ALIGNED); - source.setTop(IrisDirection.UP_POSITIVE_Y); - target.setTop(IrisDirection.DOWN_NEGATIVE_Y); + source.setTop(JigsawDirection.UP_POSITIVE_Y); + target.setTop(JigsawDirection.DOWN_NEGATIVE_Y); - StructureGraphCompilation aligned = StructureGraphCompiler.compile( + StructureGraphCompilation aligned = compile( structure("pools/start"), resolver); assertCodes(aligned, StructureGraphDiagnostic.Code.NO_COMPATIBLE_CONNECTOR, StructureGraphDiagnostic.Code.UNREACHABLE_PIECE); source.setJoint(JigsawJoint.ROLLABLE); - StructureGraphCompilation rollable = StructureGraphCompiler.compile( + StructureGraphCompilation rollable = compile( structure("pools/start"), resolver); assertTrue(rollable.isAssemblyViable()); } @Test public void channelsParticipateInMatchingAndPortableGraphsRejectThem() { - InMemoryResolver resolver = connectorGraph(false, IrisDirection.SOUTH_POSITIVE_Z); + InMemoryResolver resolver = connectorGraph(false, JigsawDirection.SOUTH_POSITIVE_Z); IrisJigsawConnector source = resolver.pieces.get("pieces/start").getConnectors().getFirst(); IrisJigsawConnector target = resolver.pieces.get("pieces/target").getConnectors().getFirst(); source.setChannel("roads"); target.setChannel("rooms"); - StructureGraphCompilation mismatched = StructureGraphCompiler.compile( + StructureGraphCompilation mismatched = compile( structure("pools/start"), resolver); assertCodes(mismatched, @@ -215,7 +214,7 @@ public class StructureGraphCompilerTest { StructureGraphDiagnostic.Code.UNREACHABLE_PIECE); target.setChannel("Roads"); - StructureGraphCompilation mismatchedCase = StructureGraphCompiler.compile( + StructureGraphCompilation mismatchedCase = compile( structure("pools/start"), resolver); assertCodes(mismatchedCase, @@ -223,7 +222,7 @@ public class StructureGraphCompilerTest { StructureGraphDiagnostic.Code.UNREACHABLE_PIECE); target.setChannel(" roads"); - StructureGraphCompilation mismatchedWhitespace = StructureGraphCompiler.compile( + StructureGraphCompilation mismatchedWhitespace = compile( structure("pools/start"), resolver); assertCodes(mismatchedWhitespace, @@ -231,7 +230,7 @@ public class StructureGraphCompilerTest { StructureGraphDiagnostic.Code.UNREACHABLE_PIECE); target.setChannel("roads"); - StructureGraphCompilation matched = StructureGraphCompiler.compile( + StructureGraphCompilation matched = compile( structure("pools/start"), resolver); assertTrue(matched.isAssemblyViable()); @@ -239,7 +238,7 @@ public class StructureGraphCompilerTest { IrisStructure portable = structure("pools/start") .setCompatibility(IrisJigsawCompatibility.VANILLA_PORTABLE) .setBranchFailurePolicy(IrisJigsawBranchFailurePolicy.TERMINATE_BRANCH); - StructureGraphCompilation rejectedPortable = StructureGraphCompiler.compile(portable, resolver); + StructureGraphCompilation rejectedPortable = compile(portable, resolver); assertCodes(rejectedPortable, StructureGraphDiagnostic.Code.NON_PORTABLE_CONNECTOR); assertTrue(rejectedPortable.hasErrors()); @@ -249,7 +248,7 @@ public class StructureGraphCompilerTest { public void validatesPlanarCellSizeAndConnectorMetadata() { InMemoryResolver resolver = new InMemoryResolver(); IrisJigsawConnector connector = connector( - new IrisPosition(1, 1, 0), IrisDirection.NORTH_NEGATIVE_Z, + new BlockPosition(1, 1, 0), JigsawDirection.NORTH_NEGATIVE_Z, "pools/terminal", "source", "door") .setFinalState("") .setSelectionPriority(-1); @@ -259,9 +258,9 @@ public class StructureGraphCompilerTest { resolver.pools.put("pools/terminal", pool()); IrisStructure structure = structure("pools/start") .setMode(IrisJigsawMode.PLANAR_JIGSAW) - .setCellSize(new IrisPosition(16, 0, 16)); + .setCellSize(new BlockPosition(16, 0, 16)); - StructureGraphCompilation result = StructureGraphCompiler.compile(structure, resolver); + StructureGraphCompilation result = compile(structure, resolver); assertCodes(result, StructureGraphDiagnostic.Code.INVALID_PLANAR_CELL_SIZE, @@ -272,14 +271,14 @@ public class StructureGraphCompilerTest { @Test public void acceptsRectangularPlanarCellSize() { InMemoryResolver resolver = new InMemoryResolver(); - resolver.objects.put("objects/start", new IrisObject(16, 8, 8)); + resolver.objects.put("objects/start", new ObjectFrame(16, 8, 8)); resolver.pieces.put("pieces/start", piece("objects/start")); resolver.pools.put("pools/start", pool(entry("pieces/start", 1))); IrisStructure structure = structure("pools/start") .setMode(IrisJigsawMode.PLANAR_JIGSAW) - .setCellSize(new IrisPosition(16, 8, 8)); + .setCellSize(new BlockPosition(16, 8, 8)); - StructureGraphCompilation result = StructureGraphCompiler.compile(structure, resolver); + StructureGraphCompilation result = compile(structure, resolver); assertFalse(hasCode(result, StructureGraphDiagnostic.Code.INVALID_PLANAR_CELL_SIZE)); assertTrue(result.isAssemblyViable()); @@ -288,24 +287,24 @@ public class StructureGraphCompilerTest { @Test public void allowsSmallerPlanarObjectsAndRejectsObjectsOutsideTheirWorkcell() { InMemoryResolver resolver = new InMemoryResolver(); - resolver.objects.put("objects/start", new IrisObject(4, 3, 4)); + resolver.objects.put("objects/start", new ObjectFrame(4, 3, 4)); resolver.pieces.put("pieces/start", piece("objects/start")); resolver.pools.put("pools/start", pool(entry("pieces/start", 1))); IrisStructure structure = structure("pools/start") .setMode(IrisJigsawMode.PLANAR_JIGSAW) - .setCellSize(new IrisPosition(4, 3, 4)); + .setCellSize(new BlockPosition(4, 3, 4)); - StructureGraphCompilation valid = StructureGraphCompiler.compile(structure, resolver); + StructureGraphCompilation valid = compile(structure, resolver); assertFalse(hasCode(valid, StructureGraphDiagnostic.Code.INVALID_PLANAR_OBJECT_SIZE)); - resolver.objects.put("objects/start", new IrisObject(4, 2, 4)); - StructureGraphCompilation smaller = StructureGraphCompiler.compile(structure, resolver); + resolver.objects.put("objects/start", new ObjectFrame(4, 2, 4)); + StructureGraphCompilation smaller = compile(structure, resolver); assertFalse(hasCode(smaller, StructureGraphDiagnostic.Code.INVALID_PLANAR_OBJECT_SIZE)); - resolver.objects.put("objects/start", new IrisObject(5, 3, 4)); - StructureGraphCompilation oversized = StructureGraphCompiler.compile(structure, resolver); + resolver.objects.put("objects/start", new ObjectFrame(5, 3, 4)); + StructureGraphCompilation oversized = compile(structure, resolver); assertCodes(oversized, StructureGraphDiagnostic.Code.INVALID_PLANAR_OBJECT_SIZE); assertTrue(oversized.getDiagnostics().stream().anyMatch( @@ -316,22 +315,22 @@ public class StructureGraphCompilerTest { public void ignoresPlanarObjectSizeForPiecesThatCannotBeReached() { InMemoryResolver resolver = new InMemoryResolver(); IrisJigsawConnector source = connector( - new IrisPosition(2, 1, 0), IrisDirection.NORTH_NEGATIVE_Z, + new BlockPosition(2, 1, 0), JigsawDirection.NORTH_NEGATIVE_Z, "pools/target", "source", "door"); IrisJigsawConnector target = connector( - new IrisPosition(2, 1, 0), IrisDirection.NORTH_NEGATIVE_Z, + new BlockPosition(2, 1, 0), JigsawDirection.NORTH_NEGATIVE_Z, "pools/target", "door", "unused"); - resolver.objects.put("objects/start", new IrisObject(4, 3, 4)); - resolver.objects.put("objects/target", new IrisObject(4, 2, 4)); + resolver.objects.put("objects/start", new ObjectFrame(4, 3, 4)); + resolver.objects.put("objects/target", new ObjectFrame(4, 2, 4)); resolver.pieces.put("pieces/start", piece("objects/start", source).setRotatable(false)); resolver.pieces.put("pieces/target", piece("objects/target", target).setRotatable(false)); resolver.pools.put("pools/start", pool(entry("pieces/start", 1))); resolver.pools.put("pools/target", pool(entry("pieces/target", 1))); IrisStructure structure = structure("pools/start") .setMode(IrisJigsawMode.PLANAR_JIGSAW) - .setCellSize(new IrisPosition(4, 3, 4)); + .setCellSize(new BlockPosition(4, 3, 4)); - StructureGraphCompilation result = StructureGraphCompiler.compile(structure, resolver); + StructureGraphCompilation result = compile(structure, resolver); assertFalse(result.getGraph().getReachablePieces().contains("pieces/target")); assertFalse(hasCode(result, StructureGraphDiagnostic.Code.INVALID_PLANAR_OBJECT_SIZE)); @@ -341,26 +340,26 @@ public class StructureGraphCompilerTest { public void acceptsAllCanonicalPlanarFaceCenterSockets() { InMemoryResolver resolver = new InMemoryResolver(); IrisJigsawConnector north = connector( - new IrisPosition(2, 1, 0), IrisDirection.NORTH_NEGATIVE_Z, + new BlockPosition(2, 1, 0), JigsawDirection.NORTH_NEGATIVE_Z, "pools/terminal", "north", "door"); IrisJigsawConnector east = connector( - new IrisPosition(3, 1, 2), IrisDirection.EAST_POSITIVE_X, + new BlockPosition(3, 1, 2), JigsawDirection.EAST_POSITIVE_X, "pools/terminal", "east", "door"); IrisJigsawConnector south = connector( - new IrisPosition(2, 1, 3), IrisDirection.SOUTH_POSITIVE_Z, + new BlockPosition(2, 1, 3), JigsawDirection.SOUTH_POSITIVE_Z, "pools/terminal", "south", "door"); IrisJigsawConnector west = connector( - new IrisPosition(0, 1, 2), IrisDirection.WEST_NEGATIVE_X, + new BlockPosition(0, 1, 2), JigsawDirection.WEST_NEGATIVE_X, "pools/terminal", "west", "door"); - resolver.objects.put("objects/start", new IrisObject(4, 3, 4)); + resolver.objects.put("objects/start", new ObjectFrame(4, 3, 4)); resolver.pieces.put("pieces/start", piece("objects/start", north, east, south, west)); resolver.pools.put("pools/start", pool(entry("pieces/start", 1))); resolver.pools.put("pools/terminal", pool()); IrisStructure structure = structure("pools/start") .setMode(IrisJigsawMode.PLANAR_JIGSAW) - .setCellSize(new IrisPosition(4, 3, 4)); + .setCellSize(new BlockPosition(4, 3, 4)); - StructureGraphCompilation result = StructureGraphCompiler.compile(structure, resolver); + StructureGraphCompilation result = compile(structure, resolver); assertTrue(result.getDiagnostics().isEmpty()); assertTrue(result.isAssemblyViable()); @@ -370,24 +369,24 @@ public class StructureGraphCompilerTest { public void rejectsOffsetVerticalAndTiltedPlanarConnectors() { InMemoryResolver resolver = new InMemoryResolver(); IrisJigsawConnector offset = connector( - new IrisPosition(1, 1, 0), IrisDirection.NORTH_NEGATIVE_Z, + new BlockPosition(1, 1, 0), JigsawDirection.NORTH_NEGATIVE_Z, "pools/terminal", "offset", "door"); IrisJigsawConnector vertical = connector( - new IrisPosition(2, 1, 2), IrisDirection.UP_POSITIVE_Y, + new BlockPosition(2, 1, 2), JigsawDirection.UP_POSITIVE_Y, "pools/terminal", "vertical", "door"); IrisJigsawConnector tilted = connector( - new IrisPosition(2, 1, 3), IrisDirection.SOUTH_POSITIVE_Z, + new BlockPosition(2, 1, 3), JigsawDirection.SOUTH_POSITIVE_Z, "pools/terminal", "tilted", "door") - .setTop(IrisDirection.DOWN_NEGATIVE_Y); - resolver.objects.put("objects/start", new IrisObject(4, 3, 4)); + .setTop(JigsawDirection.DOWN_NEGATIVE_Y); + resolver.objects.put("objects/start", new ObjectFrame(4, 3, 4)); resolver.pieces.put("pieces/start", piece("objects/start", offset, vertical, tilted)); resolver.pools.put("pools/start", pool(entry("pieces/start", 1))); resolver.pools.put("pools/terminal", pool()); IrisStructure structure = structure("pools/start") .setMode(IrisJigsawMode.PLANAR_JIGSAW) - .setCellSize(new IrisPosition(4, 3, 4)); + .setCellSize(new BlockPosition(4, 3, 4)); - StructureGraphCompilation result = StructureGraphCompiler.compile(structure, resolver); + StructureGraphCompilation result = compile(structure, resolver); List messages = new ArrayList<>(); for (StructureGraphDiagnostic diagnostic : result.getDiagnostics()) { if (diagnostic.code() == StructureGraphDiagnostic.Code.INVALID_PLANAR_CONNECTOR) { @@ -406,18 +405,18 @@ public class StructureGraphCompilerTest { public void spatialGraphsIgnoreThePlanarGeometryContract() { InMemoryResolver resolver = new InMemoryResolver(); IrisJigsawConnector vertical = connector( - new IrisPosition(1, 4, 1), IrisDirection.UP_POSITIVE_Y, + new BlockPosition(1, 4, 1), JigsawDirection.UP_POSITIVE_Y, "pools/terminal", "vertical", "door") - .setTop(IrisDirection.DOWN_NEGATIVE_Y); - resolver.objects.put("objects/start", new IrisObject(2, 5, 3)); + .setTop(JigsawDirection.DOWN_NEGATIVE_Y); + resolver.objects.put("objects/start", new ObjectFrame(2, 5, 3)); resolver.pieces.put("pieces/start", piece("objects/start", vertical)); resolver.pools.put("pools/start", pool(entry("pieces/start", 1))); resolver.pools.put("pools/terminal", pool()); IrisStructure structure = structure("pools/start") .setMode(IrisJigsawMode.SPATIAL_JIGSAW) - .setCellSize(new IrisPosition(16, 0, 8)); + .setCellSize(new BlockPosition(16, 0, 8)); - StructureGraphCompilation result = StructureGraphCompiler.compile(structure, resolver); + StructureGraphCompilation result = compile(structure, resolver); assertFalse(hasCode(result, StructureGraphDiagnostic.Code.INVALID_PLANAR_CELL_SIZE)); assertFalse(hasCode(result, StructureGraphDiagnostic.Code.INVALID_PLANAR_OBJECT_SIZE)); @@ -429,20 +428,20 @@ public class StructureGraphCompilerTest { public void deterministicSamplesHonorSelectionPriorityAndStableTies() { InMemoryResolver resolver = new InMemoryResolver(); IrisJigsawConnector east = connector( - new IrisPosition(2, 1, 1), IrisDirection.EAST_POSITIVE_X, + new BlockPosition(2, 1, 1), JigsawDirection.EAST_POSITIVE_X, "pools/east", "source", "door").setSelectionPriority(-20); IrisJigsawConnector west = connector( - new IrisPosition(0, 1, 1), IrisDirection.WEST_NEGATIVE_X, + new BlockPosition(0, 1, 1), JigsawDirection.WEST_NEGATIVE_X, "pools/west", "source", "door").setSelectionPriority(-10); resolver.objects.put("objects/start", object()); resolver.objects.put("objects/east", object()); resolver.objects.put("objects/west", object()); resolver.pieces.put("pieces/start", piece("objects/start", east, west)); resolver.pieces.put("pieces/east", piece("objects/east", connector( - new IrisPosition(0, 1, 1), IrisDirection.WEST_NEGATIVE_X, + new BlockPosition(0, 1, 1), JigsawDirection.WEST_NEGATIVE_X, "pools/terminal", "door", "unused"))); resolver.pieces.put("pieces/west", piece("objects/west", connector( - new IrisPosition(2, 1, 1), IrisDirection.EAST_POSITIVE_X, + new BlockPosition(2, 1, 1), JigsawDirection.EAST_POSITIVE_X, "pools/terminal", "door", "unused"))); resolver.pools.put("pools/start", pool(entry("pieces/start", 1))); resolver.pools.put("pools/east", pool(entry("pieces/east", 1))); @@ -450,7 +449,7 @@ public class StructureGraphCompilerTest { resolver.pools.put("pools/terminal", pool()); IrisStructure structure = structure("pools/start"); - StructureGraphCompilation prioritized = StructureGraphCompiler.compile(structure, resolver); + StructureGraphCompilation prioritized = compile(structure, resolver); for (StructureGraphAssemblySample sample : prioritized.getAssemblySamples()) { assertEquals(List.of("pieces/start", "pieces/west", "pieces/east"), @@ -458,7 +457,7 @@ public class StructureGraphCompilerTest { } east.setSelectionPriority(-10); - StructureGraphCompilation tied = StructureGraphCompiler.compile(structure, resolver); + StructureGraphCompilation tied = compile(structure, resolver); for (StructureGraphAssemblySample sample : tied.getAssemblySamples()) { assertEquals(List.of("pieces/start", "pieces/east", "pieces/west"), @@ -470,22 +469,22 @@ public class StructureGraphCompilerTest { public void deterministicSamplesScheduleChildExpansionBySourcePlacementPriority() { InMemoryResolver resolver = new InMemoryResolver(); IrisJigsawConnector eastSource = connector( - new IrisPosition(2, 1, 1), IrisDirection.EAST_POSITIVE_X, + new BlockPosition(2, 1, 1), JigsawDirection.EAST_POSITIVE_X, "pools/east", "source", "door").setPlacementPriority(-20); IrisJigsawConnector westSource = connector( - new IrisPosition(0, 1, 1), IrisDirection.WEST_NEGATIVE_X, + new BlockPosition(0, 1, 1), JigsawDirection.WEST_NEGATIVE_X, "pools/west", "source", "door").setPlacementPriority(-10); IrisJigsawConnector eastTarget = connector( - new IrisPosition(0, 1, 1), IrisDirection.WEST_NEGATIVE_X, + new BlockPosition(0, 1, 1), JigsawDirection.WEST_NEGATIVE_X, "pools/terminal", "door", "unused"); IrisJigsawConnector eastBranch = connector( - new IrisPosition(2, 1, 1), IrisDirection.EAST_POSITIVE_X, + new BlockPosition(2, 1, 1), JigsawDirection.EAST_POSITIVE_X, "pools/east-leaf", "east", "leaf"); IrisJigsawConnector westTarget = connector( - new IrisPosition(2, 1, 1), IrisDirection.EAST_POSITIVE_X, + new BlockPosition(2, 1, 1), JigsawDirection.EAST_POSITIVE_X, "pools/terminal", "door", "unused"); IrisJigsawConnector westBranch = connector( - new IrisPosition(0, 1, 1), IrisDirection.WEST_NEGATIVE_X, + new BlockPosition(0, 1, 1), JigsawDirection.WEST_NEGATIVE_X, "pools/west-leaf", "west", "leaf"); resolver.objects.put("objects/start", object()); resolver.objects.put("objects/east", object()); @@ -496,10 +495,10 @@ public class StructureGraphCompilerTest { resolver.pieces.put("pieces/east", piece("objects/east", eastTarget, eastBranch)); resolver.pieces.put("pieces/west", piece("objects/west", westTarget, westBranch)); resolver.pieces.put("pieces/east-leaf", piece("objects/east-leaf", connector( - new IrisPosition(0, 1, 1), IrisDirection.WEST_NEGATIVE_X, + new BlockPosition(0, 1, 1), JigsawDirection.WEST_NEGATIVE_X, "pools/terminal", "leaf", "unused"))); resolver.pieces.put("pieces/west-leaf", piece("objects/west-leaf", connector( - new IrisPosition(2, 1, 1), IrisDirection.EAST_POSITIVE_X, + new BlockPosition(2, 1, 1), JigsawDirection.EAST_POSITIVE_X, "pools/terminal", "leaf", "unused"))); resolver.pools.put("pools/start", pool(entry("pieces/start", 1))); resolver.pools.put("pools/east", pool(entry("pieces/east", 1))); @@ -509,7 +508,7 @@ public class StructureGraphCompilerTest { resolver.pools.put("pools/terminal", pool()); IrisStructure structure = structure("pools/start"); - StructureGraphCompilation prioritized = StructureGraphCompiler.compile(structure, resolver); + StructureGraphCompilation prioritized = compile(structure, resolver); for (StructureGraphAssemblySample sample : prioritized.getAssemblySamples()) { assertEquals(List.of( @@ -519,7 +518,7 @@ public class StructureGraphCompilerTest { } westSource.setPlacementPriority(-20); - StructureGraphCompilation tied = StructureGraphCompiler.compile(structure, resolver); + StructureGraphCompilation tied = compile(structure, resolver); for (StructureGraphAssemblySample sample : tied.getAssemblySamples()) { assertEquals(List.of( @@ -533,25 +532,25 @@ public class StructureGraphCompilerTest { public void deterministicSamplesUseSelectionPriorityForCandidateConnectors() { InMemoryResolver resolver = new InMemoryResolver(); IrisJigsawConnector source = connector( - new IrisPosition(0, 1, 0), IrisDirection.EAST_POSITIVE_X, + new BlockPosition(0, 1, 0), JigsawDirection.EAST_POSITIVE_X, "pools/target", "source", "door"); IrisJigsawConnector low = connector( - new IrisPosition(0, 1, 0), IrisDirection.WEST_NEGATIVE_X, + new BlockPosition(0, 1, 0), JigsawDirection.WEST_NEGATIVE_X, "pools/low", "door", "leaf").setSelectionPriority(-20); IrisJigsawConnector high = connector( - new IrisPosition(0, 1, 2), IrisDirection.WEST_NEGATIVE_X, + new BlockPosition(0, 1, 2), JigsawDirection.WEST_NEGATIVE_X, "pools/high", "door", "leaf").setSelectionPriority(-10); - resolver.objects.put("objects/start", new IrisObject(1, 3, 1)); - resolver.objects.put("objects/target", new IrisObject(1, 3, 3)); - resolver.objects.put("objects/low-leaf", new IrisObject(1, 3, 1)); - resolver.objects.put("objects/high-leaf", new IrisObject(1, 3, 1)); + resolver.objects.put("objects/start", new ObjectFrame(1, 3, 1)); + resolver.objects.put("objects/target", new ObjectFrame(1, 3, 3)); + resolver.objects.put("objects/low-leaf", new ObjectFrame(1, 3, 1)); + resolver.objects.put("objects/high-leaf", new ObjectFrame(1, 3, 1)); resolver.pieces.put("pieces/start", piece("objects/start", source).setRotatable(false)); resolver.pieces.put("pieces/target", piece("objects/target", low, high).setRotatable(false)); resolver.pieces.put("pieces/low-leaf", piece("objects/low-leaf", connector( - new IrisPosition(0, 1, 0), IrisDirection.EAST_POSITIVE_X, + new BlockPosition(0, 1, 0), JigsawDirection.EAST_POSITIVE_X, "pools/terminal", "leaf", "unused")).setRotatable(false)); resolver.pieces.put("pieces/high-leaf", piece("objects/high-leaf", connector( - new IrisPosition(0, 1, 0), IrisDirection.EAST_POSITIVE_X, + new BlockPosition(0, 1, 0), JigsawDirection.EAST_POSITIVE_X, "pools/terminal", "leaf", "unused")).setRotatable(false)); resolver.pools.put("pools/start", pool(entry("pieces/start", 1))); resolver.pools.put("pools/target", pool(entry("pieces/target", 1))); @@ -560,7 +559,7 @@ public class StructureGraphCompilerTest { resolver.pools.put("pools/terminal", pool()); IrisStructure structure = structure("pools/start"); - StructureGraphCompilation prioritized = StructureGraphCompiler.compile(structure, resolver); + StructureGraphCompilation prioritized = compile(structure, resolver); for (StructureGraphAssemblySample sample : prioritized.getAssemblySamples()) { assertEquals(List.of("pieces/start", "pieces/target", "pieces/low-leaf"), @@ -568,7 +567,7 @@ public class StructureGraphCompilerTest { } low.setSelectionPriority(-10); - StructureGraphCompilation tied = StructureGraphCompiler.compile(structure, resolver); + StructureGraphCompilation tied = compile(structure, resolver); for (StructureGraphAssemblySample sample : tied.getAssemblySamples()) { assertEquals(List.of("pieces/start", "pieces/target", "pieces/high-leaf"), @@ -580,16 +579,16 @@ public class StructureGraphCompilerTest { public void deterministicSamplingUsesFallbackAtTheMaximumDepth() { InMemoryResolver resolver = new InMemoryResolver(); IrisJigsawConnector source = connector( - new IrisPosition(1, 1, 0), IrisDirection.NORTH_NEGATIVE_Z, + new BlockPosition(1, 1, 0), JigsawDirection.NORTH_NEGATIVE_Z, "pools/primary", "source", "door"); IrisJigsawConnector primaryTarget = connector( - new IrisPosition(1, 1, 2), IrisDirection.SOUTH_POSITIVE_Z, + new BlockPosition(1, 1, 2), JigsawDirection.SOUTH_POSITIVE_Z, "pools/primary", "door", "unused"); IrisJigsawConnector primarySource = connector( - new IrisPosition(1, 1, 0), IrisDirection.NORTH_NEGATIVE_Z, + new BlockPosition(1, 1, 0), JigsawDirection.NORTH_NEGATIVE_Z, "pools/primary", "source", "door"); IrisJigsawConnector fallbackTarget = connector( - new IrisPosition(1, 1, 2), IrisDirection.SOUTH_POSITIVE_Z, + new BlockPosition(1, 1, 2), JigsawDirection.SOUTH_POSITIVE_Z, "pools/primary", "door", "unused"); resolver.objects.put("objects/start", object()); resolver.objects.put("objects/primary", object()); @@ -605,7 +604,7 @@ public class StructureGraphCompilerTest { IrisStructure structure = structure("pools/start"); structure.setMaxDepth(1); - StructureGraphCompilation result = StructureGraphCompiler.compile(structure, resolver); + StructureGraphCompilation result = compile(structure, resolver); assertTrue(result.getDiagnostics().isEmpty()); assertTrue(result.isAssemblyViable()); @@ -620,13 +619,13 @@ public class StructureGraphCompilerTest { public void deterministicSamplingDoesNotSelectFallbackOfFallback() { InMemoryResolver resolver = new InMemoryResolver(); IrisJigsawConnector source = connector( - new IrisPosition(1, 1, 0), IrisDirection.NORTH_NEGATIVE_Z, + new BlockPosition(1, 1, 0), JigsawDirection.NORTH_NEGATIVE_Z, "pools/primary", "source", "door"); IrisJigsawConnector incompatible = connector( - new IrisPosition(1, 1, 2), IrisDirection.SOUTH_POSITIVE_Z, + new BlockPosition(1, 1, 2), JigsawDirection.SOUTH_POSITIVE_Z, "pools/primary", "wrong", "unused"); IrisJigsawConnector nestedTarget = connector( - new IrisPosition(1, 1, 2), IrisDirection.SOUTH_POSITIVE_Z, + new BlockPosition(1, 1, 2), JigsawDirection.SOUTH_POSITIVE_Z, "pools/primary", "door", "unused"); resolver.objects.put("objects/start", object()); resolver.objects.put("objects/incompatible", object()); @@ -643,7 +642,7 @@ public class StructureGraphCompilerTest { resolver.pools.put("pools/direct", direct); resolver.pools.put("pools/nested", pool(entry("pieces/nested", 1))); - StructureGraphCompilation result = StructureGraphCompiler.compile( + StructureGraphCompilation result = compile( structure("pools/start"), resolver); assertFalse(result.getGraph().getReachablePools().contains("pools/nested")); @@ -671,7 +670,7 @@ public class StructureGraphCompilerTest { resolver.pools.put("pools/first", first); resolver.pools.put("pools/second", second); - StructureGraphCompilation result = StructureGraphCompiler.compile( + StructureGraphCompilation result = compile( structure("pools/start"), resolver); assertCodes(result, @@ -694,7 +693,7 @@ public class StructureGraphCompilerTest { resolver.pools.put("pools/chain-" + index, pool); } - StructureGraphCompilation result = StructureGraphCompiler.compile( + StructureGraphCompilation result = compile( structure("pools/chain-0"), resolver); assertTrue(result.getDiagnostics().stream().noneMatch( @@ -705,14 +704,14 @@ public class StructureGraphCompilerTest { @Test public void reportsMissingObjectsAndInvalidObjectBounds() { InMemoryResolver resolver = new InMemoryResolver(); - resolver.objects.put("objects/empty", new IrisObject()); + resolver.objects.put("objects/empty", new ObjectFrame(0, 0, 0)); resolver.pieces.put("pieces/missing-object", piece("objects/missing")); resolver.pieces.put("pieces/empty-object", piece("objects/empty")); resolver.pools.put("pools/start", pool( entry("pieces/missing-object", 1), entry("pieces/empty-object", 1))); - StructureGraphCompilation result = StructureGraphCompiler.compile( + StructureGraphCompilation result = compile( structure("pools/start"), resolver); assertCodes(result, @@ -730,15 +729,15 @@ public class StructureGraphCompilerTest { nullListResolver.pieces.put("pieces/start", nullListPiece); nullListResolver.pools.put("pools/start", pool(entry("pieces/start", 1))); - StructureGraphCompilation nullList = StructureGraphCompiler.compile( + StructureGraphCompilation nullList = compile( structure("pools/start"), nullListResolver); assertCodes(nullList, StructureGraphDiagnostic.Code.INVALID_CONNECTOR); assertTrue(nullList.hasErrors()); - InMemoryResolver nullNamesResolver = connectorGraph(true, IrisDirection.SOUTH_POSITIVE_Z); + InMemoryResolver nullNamesResolver = connectorGraph(true, JigsawDirection.SOUTH_POSITIVE_Z); nullNamesResolver.pieces.get("pieces/start").getConnectors().getFirst().setTargetName(null); - StructureGraphCompilation nullNames = StructureGraphCompiler.compile( + StructureGraphCompilation nullNames = compile( structure("pools/start"), nullNamesResolver); assertCodes(nullNames, StructureGraphDiagnostic.Code.INVALID_CONNECTOR); @@ -759,11 +758,11 @@ public class StructureGraphCompilerTest { IrisStructure overflowing = structure("pools/start"); overflowing.setMaxSizeChunks(Integer.MAX_VALUE); - assertCodes(StructureGraphCompiler.compile(deep, resolver), + assertCodes(compile(deep, resolver), StructureGraphDiagnostic.Code.INVALID_MAX_DEPTH); - assertCodes(StructureGraphCompiler.compile(wide, resolver), + assertCodes(compile(wide, resolver), StructureGraphDiagnostic.Code.INVALID_MAX_SIZE); - assertCodes(StructureGraphCompiler.compile(overflowing, resolver), + assertCodes(compile(overflowing, resolver), StructureGraphDiagnostic.Code.INVALID_MAX_SIZE); } @@ -771,14 +770,14 @@ public class StructureGraphCompilerTest { public void emptyPoolChoiceTerminatesABranchWithoutAPlaceholderPiece() { InMemoryResolver resolver = new InMemoryResolver(); IrisJigsawConnector source = connector( - new IrisPosition(1, 1, 0), IrisDirection.NORTH_NEGATIVE_Z, + new BlockPosition(1, 1, 0), JigsawDirection.NORTH_NEGATIVE_Z, "pools/terminal", "source", "door"); resolver.objects.put("objects/start", object()); resolver.pieces.put("pieces/start", piece("objects/start", source)); resolver.pools.put("pools/start", pool(entry("pieces/start", 1))); resolver.pools.put("pools/terminal", pool(emptyEntry(4))); - StructureGraphCompilation result = StructureGraphCompiler.compile( + StructureGraphCompilation result = compile( structure("pools/start"), resolver); assertTrue(result.getDiagnostics().isEmpty()); @@ -794,7 +793,7 @@ public class StructureGraphCompilerTest { InMemoryResolver resolver = new InMemoryResolver(); resolver.pools.put("pools/start", pool(emptyEntry(1))); - StructureGraphCompilation result = StructureGraphCompiler.compile( + StructureGraphCompilation result = compile( structure("pools/start"), resolver); assertTrue(result.isAssemblyViable()); @@ -815,7 +814,7 @@ public class StructureGraphCompilerTest { resolver.pools.put("pools/start", pool( entry("pieces/start", Integer.MAX_VALUE), emptyEntry(1))); - StructureGraphCompilation result = StructureGraphCompiler.compile( + StructureGraphCompilation result = compile( structure("pools/start"), resolver); assertTrue(result.isAssemblyViable()); @@ -827,11 +826,11 @@ public class StructureGraphCompilerTest { @Test public void oversizedStartPreventsGuaranteedReplacementOutput() { InMemoryResolver resolver = new InMemoryResolver(); - resolver.objects.put("objects/start", new IrisObject(130, 3, 3)); + resolver.objects.put("objects/start", new ObjectFrame(130, 3, 3)); resolver.pieces.put("pieces/start", piece("objects/start")); resolver.pools.put("pools/start", pool(entry("pieces/start", 1))); - StructureGraphCompilation result = StructureGraphCompiler.compile( + StructureGraphCompilation result = compile( structure("pools/start"), resolver); assertTrue(result.isAssemblyViable()); @@ -840,9 +839,9 @@ public class StructureGraphCompilerTest { @Test public void reachableBranchRequiresAuthoredEmptyTerminationForReplacementOutput() { - InMemoryResolver resolver = connectorGraph(true, IrisDirection.NORTH_NEGATIVE_Z); + InMemoryResolver resolver = connectorGraph(true, JigsawDirection.NORTH_NEGATIVE_Z); - StructureGraphCompilation unbounded = StructureGraphCompiler.compile( + StructureGraphCompilation unbounded = compile( structure("pools/start"), resolver); assertTrue(unbounded.isAssemblyViable()); @@ -850,7 +849,7 @@ public class StructureGraphCompilerTest { resolver.pools.get("pools/target").setFallback("pools/empty"); resolver.pools.put("pools/empty", pool()); - StructureGraphCompilation terminated = StructureGraphCompiler.compile( + StructureGraphCompilation terminated = compile( structure("pools/start"), resolver); assertTrue(terminated.isAssemblyViable()); @@ -859,13 +858,13 @@ public class StructureGraphCompilerTest { @Test public void branchTerminationPolicyMakesUnmatchedOptionalBranchesViable() { - InMemoryResolver resolver = connectorGraph(false, IrisDirection.NORTH_NEGATIVE_Z); + InMemoryResolver resolver = connectorGraph(false, JigsawDirection.NORTH_NEGATIVE_Z); IrisStructure strictStructure = structure("pools/start"); IrisStructure terminatingStructure = structure("pools/start") .setBranchFailurePolicy(IrisJigsawBranchFailurePolicy.TERMINATE_BRANCH); - StructureGraphCompilation strict = StructureGraphCompiler.compile(strictStructure, resolver); - StructureGraphCompilation terminating = StructureGraphCompiler.compile(terminatingStructure, resolver); + StructureGraphCompilation strict = compile(strictStructure, resolver); + StructureGraphCompilation terminating = compile(terminatingStructure, resolver); assertCodes(strict, StructureGraphDiagnostic.Code.NO_COMPATIBLE_CONNECTOR, @@ -892,9 +891,9 @@ public class StructureGraphCompilerTest { IrisStructure structure = structure("pools/start") .setCompatibility(IrisJigsawCompatibility.VANILLA_PORTABLE); - StructureGraphCompilation strict = StructureGraphCompiler.compile(structure, resolver); + StructureGraphCompilation strict = compile(structure, resolver); structure.setBranchFailurePolicy(IrisJigsawBranchFailurePolicy.TERMINATE_BRANCH); - StructureGraphCompilation terminating = StructureGraphCompiler.compile(structure, resolver); + StructureGraphCompilation terminating = compile(structure, resolver); assertCodes(strict, StructureGraphDiagnostic.Code.NON_PORTABLE_METADATA); assertTrue(strict.hasErrors()); @@ -906,16 +905,16 @@ public class StructureGraphCompilerTest { public void authoritativeGeometrySamplingDoesNotReportTopologyOnlyPieceCaps() { InMemoryResolver resolver = new InMemoryResolver(); IrisJigsawConnector startSource = connector( - new IrisPosition(1, 1, 0), IrisDirection.NORTH_NEGATIVE_Z, + new BlockPosition(1, 1, 0), JigsawDirection.NORTH_NEGATIVE_Z, "pools/recursive", "source", "door"); IrisJigsawConnector recursiveTarget = connector( - new IrisPosition(1, 1, 2), IrisDirection.SOUTH_POSITIVE_Z, + new BlockPosition(1, 1, 2), JigsawDirection.SOUTH_POSITIVE_Z, "pools/recursive", "door", "unused"); IrisJigsawConnector firstBranch = connector( - new IrisPosition(1, 1, 0), IrisDirection.NORTH_NEGATIVE_Z, + new BlockPosition(1, 1, 0), JigsawDirection.NORTH_NEGATIVE_Z, "pools/recursive", "source", "door"); IrisJigsawConnector secondBranch = connector( - new IrisPosition(1, 1, 0), IrisDirection.NORTH_NEGATIVE_Z, + new BlockPosition(1, 1, 0), JigsawDirection.NORTH_NEGATIVE_Z, "pools/recursive", "source", "door"); resolver.objects.put("objects/start", object()); resolver.objects.put("objects/recursive", object()); @@ -931,7 +930,7 @@ public class StructureGraphCompilerTest { structure.setMaxDepth(30); structure.setMaxSizeChunks(8); - StructureGraphCompilation result = StructureGraphCompiler.compile(structure, resolver); + StructureGraphCompilation result = compile(structure, resolver); assertFalse(hasCode(result, StructureGraphDiagnostic.Code.ASSEMBLY_PIECE_CAP_REACHED)); assertTrue(result.isAssemblyViable()); @@ -955,7 +954,7 @@ public class StructureGraphCompilerTest { IrisStructure structure = structure("pools/start"); structure.getThemeSets().add(new IrisJigsawThemeSet("variant-1", 1)); - StructureGraphCompilation result = StructureGraphCompiler.compile(structure, resolver); + StructureGraphCompilation result = compile(structure, resolver); assertCodes(result, StructureGraphDiagnostic.Code.INVALID_CHANCE, @@ -976,18 +975,18 @@ public class StructureGraphCompilerTest { structure.getThemeSets().add(new IrisJigsawThemeSet("variant-1", 1)); structure.getThemeSets().add(new IrisJigsawThemeSet("variant-2", 1)); - StructureGraphCompilation result = StructureGraphCompiler.compile(structure, resolver); + StructureGraphCompilation result = compile(structure, resolver); assertCodes(result, StructureGraphDiagnostic.Code.UNSATISFIABLE_PIECE_RULE); } @Test public void terminalPiecesDoNotMakeTheirOutgoingPoolsReachable() { - InMemoryResolver resolver = connectorGraph(true, IrisDirection.SOUTH_POSITIVE_Z); + InMemoryResolver resolver = connectorGraph(true, JigsawDirection.SOUTH_POSITIVE_Z); resolver.pieces.get("pieces/start").setRules( new IrisJigsawPieceRules().setTerminal(true)); - StructureGraphCompilation result = StructureGraphCompiler.compile( + StructureGraphCompilation result = compile( structure("pools/start"), resolver); assertTrue(result.getGraph().getReachablePieces().contains("pieces/start")); @@ -997,20 +996,20 @@ public class StructureGraphCompilerTest { @Test public void requiredCapsNeedACompatibleTerminalInTheDirectFallback() { - InMemoryResolver resolver = connectorGraph(true, IrisDirection.SOUTH_POSITIVE_Z); + InMemoryResolver resolver = connectorGraph(true, JigsawDirection.SOUTH_POSITIVE_Z); resolver.pools.get("pools/target").setFallback("pools/fallback"); resolver.pools.put("pools/fallback", pool(entry("pieces/target", 1))); IrisStructure structure = structure("pools/start").setRequireCaps(true); - StructureGraphCompilation result = StructureGraphCompiler.compile(structure, resolver); + StructureGraphCompilation result = compile(structure, resolver); assertCodes(result, StructureGraphDiagnostic.Code.NO_REQUIRED_TERMINAL); } - private static InMemoryResolver connectorGraph(boolean rotatable, IrisDirection targetDirection) { + private static InMemoryResolver connectorGraph(boolean rotatable, JigsawDirection targetDirection) { InMemoryResolver resolver = new InMemoryResolver(); IrisJigsawConnector source = connector( - new IrisPosition(1, 1, 0), IrisDirection.NORTH_NEGATIVE_Z, + new BlockPosition(1, 1, 0), JigsawDirection.NORTH_NEGATIVE_Z, "pools/target", "source", "door"); IrisJigsawConnector target = connector( canonicalPosition(targetDirection), targetDirection, @@ -1030,25 +1029,24 @@ public class StructureGraphCompilerTest { private static IrisStructure structure(String startPool) { IrisStructure structure = new IrisStructure(); - structure.setLoadKey("structures/test"); structure.setStartPool(startPool); structure.setMaxDepth(3); structure.setMaxSizeChunks(4); return structure; } - private static IrisObject object() { - return new IrisObject(3, 3, 3); + private static ObjectFrame object() { + return new ObjectFrame(3, 3, 3); } - private static IrisPosition canonicalPosition(IrisDirection direction) { + private static BlockPosition canonicalPosition(JigsawDirection direction) { return switch (direction) { - case NORTH_NEGATIVE_Z -> new IrisPosition(1, 1, 0); - case EAST_POSITIVE_X -> new IrisPosition(2, 1, 1); - case SOUTH_POSITIVE_Z -> new IrisPosition(1, 1, 2); - case WEST_NEGATIVE_X -> new IrisPosition(0, 1, 1); - case UP_POSITIVE_Y -> new IrisPosition(1, 2, 1); - case DOWN_NEGATIVE_Y -> new IrisPosition(1, 0, 1); + case NORTH_NEGATIVE_Z -> new BlockPosition(1, 1, 0); + case EAST_POSITIVE_X -> new BlockPosition(2, 1, 1); + case SOUTH_POSITIVE_Z -> new BlockPosition(1, 1, 2); + case WEST_NEGATIVE_X -> new BlockPosition(0, 1, 1); + case UP_POSITIVE_Y -> new BlockPosition(1, 2, 1); + case DOWN_NEGATIVE_Y -> new BlockPosition(1, 0, 1); }; } @@ -1073,7 +1071,7 @@ public class StructureGraphCompilerTest { return new IrisJigsawPieceEntry().setEmpty(true).setWeight(weight); } - private static IrisJigsawConnector connector(IrisPosition position, IrisDirection direction, String pool, + private static IrisJigsawConnector connector(BlockPosition position, JigsawDirection direction, String pool, String name, String targetName) { return new IrisJigsawConnector() .setPosition(position) @@ -1104,10 +1102,14 @@ public class StructureGraphCompilerTest { return false; } + private static StructureGraphCompilation compile(IrisStructure structure, StructureGraphResolver resolver) { + return StructureGraphCompiler.compile("test", structure, resolver); + } + private static final class InMemoryResolver implements StructureGraphResolver { private final Map pools = new LinkedHashMap<>(); private final Map pieces = new LinkedHashMap<>(); - private final Map objects = new LinkedHashMap<>(); + private final Map objects = new LinkedHashMap<>(); @Override public IrisJigsawPool loadPool(String key) { @@ -1120,7 +1122,7 @@ public class StructureGraphCompilerTest { } @Override - public IrisObject loadObject(String key) { + public ObjectFrame loadObject(String key) { return objects.get(key); } } diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureGraphValidationTest.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureGraphValidationTest.java index 94eb4cfbb..7e766bee5 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureGraphValidationTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureGraphValidationTest.java @@ -19,6 +19,7 @@ package art.arcane.iris.engine.framework.structure; import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.ClasspathPack; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -45,7 +46,7 @@ public class StructureGraphValidationTest { Path pack = temporaryFolder.newFolder("pack").toPath(); write(pack, "structures/castle.json", "{\"startPool\":\"castle/start\"}"); write(pack, "jigsaw-pools/castle/start.json", - "{\"pieces\":[{\"piece\":\"castle/start\",\"weight\":0}]}"); + "{\"pieces\":[{\"piece\":\"castle/start\",\"weight\":1}]}"); write(pack, "jigsaw-pieces/castle/start.json", "{\"object\":\"castle/start\",\"connectors\":[{\"position\":{\"x\":2,\"y\":0,\"z\":0}," + "\"direction\":\"NORTH_NEGATIVE_Z\",\"pool\":\"castle/start\",\"name\":\"path\",\"targetName\":\"path\"}]}"); @@ -53,8 +54,22 @@ public class StructureGraphValidationTest { StructureGraphValidation.Validation validation = validate(pack, null); - assertTrue(validation.errors().stream().anyMatch(message -> message.contains("non-positive weight 0"))); - assertTrue(validation.errors().stream().anyMatch(message -> message.contains("outside object bounds"))); + assertTrue(validation.errors().toString(), validation.errors().stream().anyMatch(message -> message.contains("outside object bounds"))); + } + + @Test + public void aNonPositiveWeightFailsTheLoadOfItsPool() throws Exception { + Path pack = temporaryFolder.newFolder("pack").toPath(); + write(pack, "structures/castle.json", "{\"startPool\":\"castle/start\"}"); + write(pack, "jigsaw-pools/castle/start.json", + "{\"pieces\":[{\"piece\":\"castle/start\",\"weight\":0}]}"); + IrisData data = ClasspathPack.open(pack.toFile(), temporaryFolder); + try { + assertThrows(IllegalStateException.class, () -> data.getPackResources().find( + StructureResources.POOLS, data.getPackResources().idOf("castle/start"))); + } finally { + data.close(); + } } @Test @@ -319,10 +334,10 @@ public class StructureGraphValidationTest { && message.contains("seed 0"))); } - private static StructureGraphValidation.Validation validate(Path pack, Set activeStructureKeys) { - IrisData data = IrisData.openValidation(pack.toFile()); + private StructureGraphValidation.Validation validate(Path pack, Set activeStructureKeys) throws Exception { + IrisData data = ClasspathPack.open(pack.toFile(), temporaryFolder); try { - return StructureGraphValidation.validate(data, activeStructureKeys); + return StructureGraphValidation.validate(data.getPackResources(), pack.toFile(), activeStructureKeys); } finally { data.close(); } diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureReferenceValidationTest.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureReferenceValidationTest.java new file mode 100644 index 000000000..3ebcc479b --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureReferenceValidationTest.java @@ -0,0 +1,70 @@ +package art.arcane.iris.engine.framework.structure; + +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.validation.Problem; +import org.junit.Test; + +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.when; + +public class StructureReferenceValidationTest { + private static final String KNOWN_BLOCK = "minecraft:structure_void"; + private static final String UNKNOWN_BLOCK = "example:not_a_block"; + private static final ResourceId PIECE = new ResourceId("test", "castle/keep"); + private static final ResourceId OBJECT = new ResourceId("test", "castle/keep"); + + @Test + public void aConnectorWhoseFinalStateIsNoBlockOfThePlatformIsAnError() { + List problems = StructureReferenceValidation.validate( + packWithAPieceWhoseConnectorBecomes(UNKNOWN_BLOCK), Optional.of(blocksKnowing(KNOWN_BLOCK))); + + assertEquals(problems.toString(), 1, problems.size()); + assertTrue(problems.get(0).message(), problems.get(0).message().contains( + "Jigsaw piece 'castle/keep' connectors[0] finalState '" + UNKNOWN_BLOCK + "' is not a block.")); + } + + @Test + public void aConnectorWhoseFinalStateIsABlockOfThePlatformIsAccepted() { + List problems = StructureReferenceValidation.validate( + packWithAPieceWhoseConnectorBecomes(KNOWN_BLOCK), Optional.of(blocksKnowing(KNOWN_BLOCK))); + + assertTrue(problems.toString(), problems.isEmpty()); + } + + @Test + public void withoutAPlatformNoFinalStateIsChecked() { + List problems = StructureReferenceValidation.validate( + packWithAPieceWhoseConnectorBecomes(UNKNOWN_BLOCK), Optional.empty()); + + assertTrue(problems.toString(), problems.isEmpty()); + } + + private static BlockRegistry blocksKnowing(String known) { + BlockRegistry blocks = mock(BlockRegistry.class); + when(blocks.find(known)).thenReturn(Optional.of(BlockState.parse(known))); + when(blocks.find(UNKNOWN_BLOCK)).thenReturn(Optional.empty()); + return blocks; + } + + private static PackResources packWithAPieceWhoseConnectorBecomes(String finalState) { + PackResources pack = mock(PackResources.class); + IrisJigsawPiece piece = new IrisJigsawPiece().setObject("castle/keep") + .setConnectors(List.of(new IrisJigsawConnector().setFinalState(finalState))); + when(pack.ids(StructureResources.STRUCTURES)).thenReturn(List.of()); + when(pack.ids(StructureResources.POOLS)).thenReturn(List.of()); + when(pack.ids(StructureResources.PIECES)).thenReturn(List.of(PIECE)); + when(pack.ids(PackResources.OBJECTS)).thenReturn(List.of(OBJECT)); + when(pack.find(StructureResources.PIECES, PIECE)).thenReturn(Optional.of(piece)); + return pack; + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureResourcesTest.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureResourcesTest.java index ee5abbe4e..24b9ba26f 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureResourcesTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/StructureResourcesTest.java @@ -1,6 +1,7 @@ package art.arcane.iris.engine.framework.structure; import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.ClasspathPack; import art.arcane.iris.core.modules.ModuleServices; import art.arcane.iris.core.modules.IrisModuleHost; import art.arcane.iris.core.project.ModuleResourceSchemas; @@ -39,17 +40,17 @@ public class StructureResourcesTest { public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Test - public void theStructureModuleOwnsTheKindsAndTheirValidator() throws Exception { - IrisData data = IrisData.openValidation(castlePack("owned").toFile()); + public void theJigsawModuleOwnsTheKindsAndTheirValidator() throws Exception { + IrisData data = ClasspathPack.open(castlePack("owned").toFile(), temporaryFolder); try { var catalog = data.getModules().pack().catalog(); var kinds = catalog.resourceKinds().stream().map(ResourceKindRegistration::kind) - .filter(kind -> kind.id().toString().startsWith("iris:structure/")).toList(); - assertEquals(List.of("iris:structure/piece", "iris:structure/pool", "iris:structure/structure"), + .filter(kind -> kind.id().toString().startsWith("iris:jigsaw/")).toList(); + assertEquals(List.of("iris:jigsaw/piece", "iris:jigsaw/pool", "iris:jigsaw/structure"), kinds.stream().map(kind -> kind.id().toString()).toList()); assertEquals(List.of("jigsaw-pieces", "jigsaw-pools", "structures"), kinds.stream().map(kind -> kind.folder()).toList()); - assertTrue(catalog.validators().stream().map(ValidatorRegistration::validator).anyMatch(StructureValidator.class::isInstance)); + assertTrue(catalog.validators().stream().map(ValidatorRegistration::validator).anyMatch(JigsawValidator.class::isInstance)); assertFalse(data.getLoaders().containsKey(IrisStructure.class)); assertFalse(data.getLoaders().containsKey(IrisJigsawPool.class)); assertFalse(data.getLoaders().containsKey(IrisJigsawPiece.class)); @@ -60,7 +61,7 @@ public class StructureResourcesTest { @Test public void theStructureModuleListsThePacksStructuresForIrissIndexThroughItsLocator() throws Exception { - IrisData data = IrisData.openValidation(castlePack("listed").toFile()); + IrisData data = ClasspathPack.open(castlePack("listed").toFile(), temporaryFolder); try { assertEquals(Set.of(new ResourceId("listed", "castle")), new StructureLocating().structures(data.getPackResources())); assertEquals(Set.of("castle"), ModuleServices.structureKeys(data)); @@ -72,13 +73,12 @@ public class StructureResourcesTest { @Test public void structuresPoolsAndPiecesAreReadThroughPackResources() throws Exception { Path pack = castlePack("castles"); - IrisData data = IrisData.openValidation(pack.toFile()); + IrisData data = ClasspathPack.open(pack.toFile(), temporaryFolder); try { IrisStructure castle = StructureResources.structure(data.getPackResources(),"castle"); assertEquals("castle/start", castle.getStartPool()); assertEquals(5, castle.getMaxDepth()); - assertEquals("castle", castle.getLoadKey()); assertSame(castle, data.getPackResources().find(StructureResources.STRUCTURES, new ResourceId("castles", "castle")).orElseThrow()); assertEquals("castle/start", StructureResources.pool(data.getPackResources(), "castle/start").getPieces().getFirst().getPiece()); assertEquals("castle/start", StructureResources.piece(data.getPackResources(), "castle/start").getObject()); @@ -95,7 +95,7 @@ public class StructureResourcesTest { public void aBrokenStructureIsAbsentToLookupsButAnErrorToPackResources() throws Exception { Path pack = castlePack("broken"); write(pack, "structures/ruin.json", "{\"maxDepth\":"); - IrisData data = IrisData.openValidation(pack.toFile()); + IrisData data = ClasspathPack.open(pack.toFile(), temporaryFolder); try { assertNull(StructureResources.structure(data.getPackResources(),"ruin")); assertThrows(IllegalStateException.class, @@ -108,7 +108,7 @@ public class StructureResourcesTest { @Test public void rewrittenFilesAreReadAgainAfterInvalidationDumpAndHotload() throws Exception { Path pack = castlePack("reloaded"); - IrisData data = IrisData.openValidation(pack.toFile()); + IrisData data = ClasspathPack.open(pack.toFile(), temporaryFolder); try { assertEquals(5, StructureResources.structure(data.getPackResources(),"castle").getMaxDepth()); write(pack, "structures/castle.json", "{\"startPool\":\"castle/start\",\"maxDepth\":9}"); @@ -126,7 +126,7 @@ public class StructureResourcesTest { data.close(); } - IrisData runtime = IrisData.openRuntime(pack.toFile()); + IrisData runtime = ClasspathPack.openRuntime(pack.toFile(), temporaryFolder); try { assertEquals(3, StructureResources.structure(runtime.getPackResources(),"castle").getMaxDepth()); write(pack, "structures/castle.json", "{\"startPool\":\"castle/start\",\"maxDepth\":2}"); @@ -140,7 +140,7 @@ public class StructureResourcesTest { @Test public void studioDescribesStructuresAsIrisDoesAndCompletesTheirPools() throws Exception { Path pack = castlePack("studio"); - IrisData data = IrisData.openValidation(pack.toFile()); + IrisData data = ClasspathPack.open(pack.toFile(), temporaryFolder); try (SchemaTestPlatform ignored = SchemaTestPlatform.bind(temporaryFolder.getRoot())) { List entries = ModuleResourceSchemas.entries(data, true); @@ -149,7 +149,7 @@ public class StructureResourcesTest { entries.stream().map(entry -> entry.getString("url")).filter(url -> url.contains("jigsaw") || url.contains("structures-")).toList()); JSONObject structures = new JSONObject(Files.readString(pack.resolve(".iris/schema/structures-schema.json"))); JSONObject startPool = structures.getJSONObject("properties").getJSONObject("startPool"); - assertEquals("#/definitions/erzjigsaw-pools", startPool.getString("$ref")); + assertEquals("#/definitions/erzjigsaw-pools", startPool.optString("$ref", startPool.toString())); assertEquals("[\"castle/start\"]", structures.getJSONObject("definitions").getJSONObject("erzjigsaw-pools").getJSONArray("enum").toString()); } finally { diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegrationTest.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegrationTest.java index 1b5c16ded..54155e608 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegrationTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegrationTest.java @@ -1,12 +1,14 @@ package art.arcane.iris.engine.framework.structure.fit; import art.arcane.iris.builtin.structure.StructureCarveShape; +import art.arcane.iris.core.modules.IrisTestNoise; import art.arcane.iris.builtin.structure.StructureTerrain; import art.arcane.iris.builtin.structure.StructureTerrainMode; import art.arcane.iris.engine.framework.structure.NativeStructureFit; import art.arcane.iris.engine.mantle.components.StructureCarvingFootprint; import com.google.gson.Gson; import com.volmit.block.BlockState; +import com.volmit.noise.NoiseFactory; import com.volmit.vanilla.DecorationStep; import com.volmit.vanilla.PieceKind; import com.volmit.vanilla.StartMemo; @@ -40,6 +42,7 @@ import static org.junit.Assert.assertTrue; public class TerrainIntegrationTest { private static final long SEED = 1234L; private static final long CARVE_SEED = 8675309L; + private static final NoiseFactory NOISE = IrisTestNoise.factory(); private static final int SLAB_DEPTH = 128; private static final int SLAB_MIN_Y = 64; private static final int SLAB_PADDING = 14; @@ -92,7 +95,7 @@ public class TerrainIntegrationTest { FitStart start = start("{\"mode\":\"ENCASE\",\"encasePalette\":{\"palette\":[{\"block\":\"tuff\"}]}}", TerrainAdaptation.BURY, FitFixture.Piece.fixed(PYRAMID)); - TerrainIntegration.integrateTerrain(world.fitBlocks(), PYRAMID, start, SEED, NATURAL, tuff, null); + TerrainIntegration.integrateTerrain(world.fitBlocks(), PYRAMID, start, SEED, NOISE, NATURAL, tuff, null); assertEquals(state("tuff"), world.at(0, 64, 0)); assertEquals(SEED ^ "test:structure".hashCode(), (long) seeds.getFirst()); @@ -415,7 +418,7 @@ public class TerrainIntegrationTest { } private static void integrate(FitFixture.World world, Box area, FitStart start) { - TerrainIntegration.prepareTerrain(world.fitBlocks(), area, List.of(start), SEED, NATURAL, NO_PALETTES); + TerrainIntegration.prepareTerrain(world.fitBlocks(), area, List.of(start), SEED, NOISE, NATURAL, NO_PALETTES); } private static FitStart start(String terrainJson, TerrainAdaptation adaptation, FitFixture.Piece... pieces) { @@ -444,7 +447,7 @@ public class TerrainIntegrationTest { StructureTerrain terrain = erodedTerrain(horizontalPadding, lobeStrength); FitStart start = start(JSON.toJson(terrain), TerrainAdaptation.NONE, FitFixture.Piece.fixed(PYRAMID)); return TerrainIntegration.organicCarve(CarveFootprints.of(start, horizontalPadding), terrain, - StructureCarveShape.ERODED, CARVE_SEED); + StructureCarveShape.ERODED, CARVE_SEED, NOISE); } private static StructureTerrain erodedTerrain(int horizontalPadding, double lobeStrength) { @@ -471,7 +474,7 @@ public class TerrainIntegrationTest { FitFixture.World world = filled(area); TerrainIntegration.carveOrganicColumns(world.fitBlocks(), area, TerrainIntegration.organicCarve( - footprint, erodedTerrain(SLAB_PADDING, lobeStrength), StructureCarveShape.ERODED, CARVE_SEED)); + footprint, erodedTerrain(SLAB_PADDING, lobeStrength), StructureCarveShape.ERODED, CARVE_SEED, NOISE)); int[] depths = new int[SLAB_DEPTH]; for (int z = 0; z < SLAB_DEPTH; z++) { 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 d6b2e4dba..1615a07d8 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 @@ -226,6 +226,11 @@ public class LootValidatorTest { return Optional.empty(); } + @Override + public List services(Class service) { + return List.of(); + } + @Override public void report(Problem problem) { problems.add(problem); diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisStructureFoundationWriteTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisStructureFoundationWriteTest.java index 79001c814..46e60bf0e 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisStructureFoundationWriteTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisStructureFoundationWriteTest.java @@ -1,14 +1,11 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.engine.UsableBlockPlatform; -import art.arcane.iris.engine.mantle.MantleWriter; -import art.arcane.iris.spi.IrisPlatform; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.spi.PlatformRegistries; -import art.arcane.volmlib.util.matter.MatterCavern; import com.volmit.block.BlockState; import com.volmit.block.PaletteSampler; -import org.junit.After; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.Mantle; +import com.volmit.mantle.MantleLayer; +import com.volmit.placement.PlacementTerrain; import org.junit.Test; import org.mockito.InOrder; @@ -17,51 +14,45 @@ import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; public class IrisStructureFoundationWriteTest { - @After - public void unbindPlatform() { - UsableBlockPlatform.unbind(); - } + private static final BlockState SUPPORT = new BlockState("minecraft:deepslate_bricks"); @Test + @SuppressWarnings("unchecked") public void resolvesWorldCoordinatesThenClearsCavernBeforeWritingSupport() { - UsableBlockPlatform.bind(); - MantleWriter writer = mock(MantleWriter.class); + Mantle mantle = mock(Mantle.class); + MantleLayer carved = mock(MantleLayer.class); + when(mantle.carved()).thenReturn(carved); + PlacementTerrain terrain = mock(PlacementTerrain.class); List asked = new ArrayList<>(); PaletteSampler picker = (x, y, z) -> { asked.add((int) x + "," + (int) y + "," + (int) z); - return new BlockState("minecraft:deepslate_bricks"); + return SUPPORT; }; - StructurePlacing.writeFoundationSupport(writer, picker, 12, 9, -18, -256); + StructurePlacing.writeFoundationSupport(terrain, mantle, picker, 12, 9, -18, -256); assertEquals(List.of("12,-247,-18"), asked); - InOrder order = inOrder(writer); - order.verify(writer).clearData(12, 9, -18, MatterCavern.class); - order.verify(writer).set(eq(12), eq(9), eq(-18), any(art.arcane.iris.spi.PlatformBlockState.class)); + InOrder order = inOrder(carved, terrain); + order.verify(carved).remove(12, 9, -18); + order.verify(terrain).set(12, 9, -18, SUPPORT); } @Test public void unresolvedPaletteFailsBeforeChangingCavernOrBlocks() { - UsableBlockPlatform.unbind(); - IrisPlatform platform = mock(IrisPlatform.class); - when(platform.registries()).thenReturn(mock(PlatformRegistries.class)); - IrisPlatforms.bind(platform); - MantleWriter writer = mock(MantleWriter.class); + Mantle mantle = mock(Mantle.class); + PlacementTerrain terrain = mock(PlacementTerrain.class); try { - StructurePlacing.writeFoundationSupport(writer, (x, y, z) -> new BlockState("test:unknown"), 12, 9, -18, -256); + StructurePlacing.writeFoundationSupport(terrain, mantle, (x, y, z) -> null, 12, 9, -18, -256); } catch (IllegalStateException error) { assertTrue(error.getMessage().contains("12,-247,-18")); - verifyNoInteractions(writer); + verifyNoInteractions(mantle, terrain); return; } throw new AssertionError("Expected an unresolved structure stilt palette to fail"); diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelopeTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelopeTest.java index 1b0e9391e..2f3377f2a 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelopeTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelopeTest.java @@ -1,8 +1,9 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.structure.StructureCarveShape; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.volmlib.util.math.RNG; +import art.arcane.iris.core.modules.IrisTestNoise; +import com.volmit.noise.NoiseSampler; +import com.volmit.noise.NoiseStyle; import org.junit.Test; import static org.junit.Assert.assertEquals; @@ -10,6 +11,16 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class StructureCarveEnvelopeTest { + private static final com.volmit.noise.NoiseFactory NOISE = IrisTestNoise.factory(); + + private static NoiseSampler signature(long seed) { + return NOISE.sampler(NoiseStyle.of("IRIS"), seed); + } + + private static NoiseSampler singleOctave(long seed) { + return NOISE.sampler(NoiseStyle.of("SIMPLEX"), seed); + } + @Test public void exactStructureFootprintAlwaysCarves() { assertTrue(StructureCarveEnvelope.shouldCarveOverboreCell( @@ -65,7 +76,7 @@ public class StructureCarveEnvelopeTest { @Test public void erodedCeilingStaysInsideTheAdvertisedCarveShapeExtension() { - CNG roll = CNG.signature(new RNG(4242L)); + NoiseSampler roll = signature(4242L); for (double strength : new double[]{0.25D, 0.5D, 1D}) { int limit = StructureCarveShape.ERODED.maximumCeilingExtension(10, strength); @@ -81,7 +92,7 @@ public class StructureCarveEnvelopeTest { @Test public void floorModulationNeverCutsPastTheConfiguredPadding() { - CNG roll = CNG.signature(new RNG(9001L)); + NoiseSampler roll = signature(9001L); assertEquals(0D, StructureCarveEnvelope.erodedDownReach(null, 0.05D, 1D, 0, 0, 0), 0D); assertEquals(6D, StructureCarveEnvelope.erodedDownReach(null, 0.05D, 0D, 0, 0, 6), 0D); @@ -99,7 +110,7 @@ public class StructureCarveEnvelopeTest { @Test public void lobedSideReachWandersInsideTheConfiguredPaddingBand() { - CNG lobe = new CNG(new RNG(1337L), 1D, 1); + NoiseSampler lobe = singleOctave(1337L); double lowest = 14D; double highest = 0D; @@ -118,7 +129,7 @@ public class StructureCarveEnvelopeTest { @Test public void zeroLobeStrengthKeepsTheUniformPadding() { - CNG lobe = new CNG(new RNG(1337L), 1D, 1); + NoiseSampler lobe = singleOctave(1337L); for (int x = -64; x <= 64; x++) { for (int z = -64; z <= 64; z++) { @@ -133,7 +144,7 @@ public class StructureCarveEnvelopeTest { @Test public void lobeWavelengthSpansTensOfBlocksAtTheDerivedFrequency() { - CNG lobe = new CNG(new RNG(20250729L), 1D, 1); + NoiseSampler lobe = singleOctave(20250729L); int span = 2048; int crossings = 0; double previous = 0D; @@ -153,7 +164,7 @@ public class StructureCarveEnvelopeTest { @Test public void ceilingLobeIsHalfTheWallLobe() { - CNG lobe = new CNG(new RNG(4242L), 1D, 1); + NoiseSampler lobe = singleOctave(4242L); for (int x = -96; x <= 96; x += 3) { for (int z = -96; z <= 96; z += 3) { @@ -170,7 +181,7 @@ public class StructureCarveEnvelopeTest { @Test public void lobeSamplingIsAPureFunctionOfTheColumn() { - CNG lobe = new CNG(new RNG(77L), 1D, 1); + NoiseSampler lobe = singleOctave(77L); for (int x = -32; x <= 32; x += 7) { for (int z = -32; z <= 32; z += 7) { diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureCarvingFootprintTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureCarvingFootprintTest.java index 1bb22d779..1c767a5e0 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureCarvingFootprintTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureCarvingFootprintTest.java @@ -1,30 +1,31 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.engine.framework.PlacedStructurePiece; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.ObjectTurn; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.volmlib.util.math.IrisBlockVector; -import art.arcane.volmlib.util.collection.KList; +import art.arcane.iris.engine.framework.structure.assembly.AssembledPiece; +import art.arcane.iris.engine.framework.structure.assembly.PieceTurn; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; import org.junit.Test; +import java.util.ArrayList; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; public class StructureCarvingFootprintTest { @Test public void preservesIrregularFootprintInsteadOfFillingItsBoundingBox() { - PlacedStructurePiece piece = piece(10, 40, 20, ObjectTurn.of(0, 0, 0), + Piece piece = piece(10, 40, 20, PieceTurn.NONE, block(0, 0, 0), block(1, 0, 0), block(2, 0, 0), block(0, 0, 1), block(0, 0, 2)); - StructureCarvingFootprint footprint = StructureCarvingFootprint.from(pieces(piece), 0); + StructureCarvingFootprint footprint = footprintOf(pieces(piece), 0); assertNotNull(footprint); assertEquals(10, footprint.minX()); @@ -39,11 +40,11 @@ public class StructureCarvingFootprintTest { @Test public void reportsExactDistanceAndNearestColumnHeights() { - PlacedStructurePiece piece = piece(0, 0, 0, ObjectTurn.of(0, 0, 0), + Piece piece = piece(0, 0, 0, PieceTurn.NONE, block(0, 10, 0), block(0, 12, 0), block(4, 30, 0), block(4, 35, 0)); - StructureCarvingFootprint footprint = StructureCarvingFootprint.from(pieces(piece), 2); + StructureCarvingFootprint footprint = footprintOf(pieces(piece), 2); StructureCarvingFootprint.Column nearestRight = footprint.sample(3, 2); StructureCarvingFootprint.Column tied = footprint.sample(2, 0); @@ -59,12 +60,12 @@ public class StructureCarvingFootprintTest { @Test public void rotatesAndMergesOverlappingColumns() { - PlacedStructurePiece rotated = piece(10, 20, 30, ObjectTurn.of(0, 90, 0), + Piece rotated = piece(10, 20, 30, PieceTurn.aroundY(90), block(2, 1, 0)); - PlacedStructurePiece overlapping = piece(10, 5, 28, ObjectTurn.of(0, 0, 0), + Piece overlapping = piece(10, 5, 28, PieceTurn.NONE, block(0, 3, 0), block(0, 9, 0)); - StructureCarvingFootprint footprint = StructureCarvingFootprint.from( + StructureCarvingFootprint footprint = footprintOf( pieces(rotated, overlapping), 0); assertNotNull(footprint); @@ -82,18 +83,18 @@ public class StructureCarvingFootprintTest { int[][] sourceBlocks = new int[][]{ block(0, 2, 0), block(3, 4, 1), block(1, 6, 4), block(5, 8, 5) }; - PlacedStructurePiece piece = piece( - -8, 30, 11, ObjectTurn.of(0, 0, 0), sourceBlocks); + Piece piece = piece( + -8, 30, 11, PieceTurn.NONE, sourceBlocks); - StructureCarvingFootprint footprint = StructureCarvingFootprint.from(pieces(piece), 3); + StructureCarvingFootprint footprint = footprintOf(pieces(piece), 3); assertNotNull(footprint); for (int z = footprint.minZ(); z <= footprint.maxZ(); z++) { for (int x = footprint.minX(); x <= footprint.maxX(); x++) { long expected = Long.MAX_VALUE; for (int[] source : sourceBlocks) { - long deltaX = (long) x - (piece.getX() + source[0]); - long deltaZ = (long) z - (piece.getZ() + source[2]); + long deltaX = (long) x - (piece.assembled.x() + source[0]); + long deltaZ = (long) z - (piece.assembled.z() + source[2]); expected = Math.min(expected, deltaX * deltaX + deltaZ * deltaZ); } assertEquals(expected, footprint.distanceSquaredAt(x, z)); @@ -103,23 +104,22 @@ public class StructureCarvingFootprintTest { @Test public void returnsNullForEmptyInvalidOrOversizedInputs() { - assertNull(StructureCarvingFootprint.from(null, 0)); - assertNull(StructureCarvingFootprint.from(new KList<>(), 0)); + assertNull(footprintOf(null, 0)); + assertNull(footprintOf(new ArrayList<>(), 0)); - KList invalidPieces = new KList<>(); - invalidPieces.add((PlacedStructurePiece) null); - invalidPieces.add(new PlacedStructurePiece( - null, null, 0, 0, 0, null, 0, 0, 0, 0, 0, 0)); - assertNull(StructureCarvingFootprint.from(invalidPieces, 0)); + List invalidPieces = new ArrayList<>(); + invalidPieces.add(null); + invalidPieces.add(new Piece(piece(0, 0, 0, PieceTurn.NONE).assembled, null)); + assertNull(footprintOf(invalidPieces, 0)); - PlacedStructurePiece piece = piece(0, 0, 0, ObjectTurn.of(0, 0, 0), block(0, 0, 0)); - assertNull(StructureCarvingFootprint.from(pieces(piece), 2, 24)); - PlacedStructurePiece overflowing = piece( - Integer.MAX_VALUE, 0, 0, ObjectTurn.of(0, 0, 0), block(1, 0, 0)); - assertNull(StructureCarvingFootprint.from(pieces(overflowing), 0)); + Piece piece = piece(0, 0, 0, PieceTurn.NONE, block(0, 0, 0)); + assertNull(footprintOf(pieces(piece), 2, 24)); + Piece overflowing = piece( + Integer.MAX_VALUE, 0, 0, PieceTurn.NONE, block(1, 0, 0)); + assertNull(footprintOf(pieces(overflowing), 0)); try { - StructureCarvingFootprint.from(pieces(piece), -1); + footprintOf(pieces(piece), -1); fail("Expected negative padding to fail"); } catch (IllegalArgumentException e) { assertEquals("padding must be non-negative", e.getMessage()); @@ -128,9 +128,9 @@ public class StructureCarvingFootprintTest { @Test public void includesTheEntirePaddingBoundary() { - PlacedStructurePiece piece = piece(7, 14, -4, ObjectTurn.of(0, 0, 0), block(0, 0, 0)); + Piece piece = piece(7, 14, -4, PieceTurn.NONE, block(0, 0, 0)); - StructureCarvingFootprint footprint = StructureCarvingFootprint.from(pieces(piece), 2, 25); + StructureCarvingFootprint footprint = footprintOf(pieces(piece), 2, 25); assertNotNull(footprint); assertEquals(5, footprint.minX()); @@ -148,17 +148,12 @@ public class StructureCarvingFootprintTest { @Test public void explicitAirDoesNotExpandTheExteriorFootprint() { - IrisObject object = new IrisObject(1, 1, 1); - PlatformBlockState solid = mock(PlatformBlockState.class); - PlatformBlockState air = mock(PlatformBlockState.class); - when(air.isAir()).thenReturn(true); - object.getBlocks().put(new IrisBlockVector(0, 0, 0), solid); - object.getBlocks().put(new IrisBlockVector(8, 4, 8), air); - PlacedStructurePiece piece = new PlacedStructurePiece( - null, object, 10, 20, 30, ObjectTurn.of(0, 0, 0), - 10, 20, 30, 18, 24, 38); + Piece piece = new Piece(new AssembledPiece(new ResourceId("test", "piece"), 10, 20, 30, PieceTurn.NONE, + 10, 20, 30, 18, 24, 38), List.of( + new StructurePieceColumns.PieceBlock(new BlockPosition(0, 0, 0), false), + new StructurePieceColumns.PieceBlock(new BlockPosition(8, 4, 8), true))); - StructureCarvingFootprint footprint = StructureCarvingFootprint.from(pieces(piece), 0); + StructureCarvingFootprint footprint = footprintOf(pieces(piece), 0); assertNotNull(footprint); assertEquals(10, footprint.minX()); @@ -167,23 +162,40 @@ public class StructureCarvingFootprintTest { assertEquals(30, footprint.maxZ()); } - private static PlacedStructurePiece piece(int x, int y, int z, ObjectTurn rotation, - int[]... blocks) { - IrisObject object = new IrisObject(1, 1, 1); - PlatformBlockState state = mock(PlatformBlockState.class); - for (int[] block : blocks) { - object.getBlocks().put(new IrisBlockVector(block[0], block[1], block[2]), state); - } - return new PlacedStructurePiece( - null, object, x, y, z, rotation, x, y, z, x, y, z); + private record Piece(AssembledPiece assembled, List blocks) { } - private static KList pieces(PlacedStructurePiece... pieces) { - KList result = new KList<>(); - for (PlacedStructurePiece piece : pieces) { - result.add(piece); + private static StructureCarvingFootprint footprintOf(List pieces, int padding) { + return footprintOf(pieces, padding, StructureCarvingFootprint.DEFAULT_MAX_CELLS); + } + + private static StructureCarvingFootprint footprintOf(List pieces, int padding, int maxCells) { + Map> blocksOf = new IdentityHashMap<>(); + List assembled = pieces == null ? null : new ArrayList<>(); + if (pieces != null) { + for (Piece piece : pieces) { + if (piece == null) { + assembled.add(null); + continue; + } + assembled.add(piece.assembled); + blocksOf.put(piece.assembled, piece.blocks); + } } - return result; + return StructureCarvingFootprint.fromColumns( + sink -> StructurePieceColumns.emit(assembled, blocksOf::get, sink), padding, maxCells); + } + + private static Piece piece(int x, int y, int z, PieceTurn turn, int[]... blocks) { + List pieceBlocks = new ArrayList<>(); + for (int[] block : blocks) { + pieceBlocks.add(new StructurePieceColumns.PieceBlock(new BlockPosition(block[0], block[1], block[2]), false)); + } + return new Piece(new AssembledPiece(new ResourceId("test", "piece"), x, y, z, turn, x, y, z, x, y, z), pieceBlocks); + } + + private static List pieces(Piece... pieces) { + return new ArrayList<>(List.of(pieces)); } private static int[] block(int x, int y, int z) { diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlannerTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlannerTest.java index 363bb8b88..69573b4e2 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlannerTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlannerTest.java @@ -1,7 +1,9 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.spi.PlatformBlockState; -import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; +import art.arcane.iris.engine.framework.structure.ColumnHeights; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; import org.junit.Test; import java.util.ArrayList; @@ -10,29 +12,40 @@ import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class StructureFoundationPlannerTest { + private static final BlockState SOLID = new BlockState("minecraft:stone"); + private static final BlockState NON_OCCLUDING_SOLID = new BlockState("minecraft:glass"); + private static final BlockState DECORATION = new BlockState("minecraft:poppy"); + private static final BlockState FLUID = new BlockState("minecraft:water"); + private static final BlockRegistry BLOCKS = blocks(); + + private static BlockRegistry blocks() { + BlockRegistry registry = mock(BlockRegistry.class); + when(registry.hasTrait(any(), any())).thenAnswer(call -> { + BlockState state = call.getArgument(0); + BlockTrait trait = call.getArgument(1); + if (trait == BlockTrait.SOLID) { + return state.equals(SOLID) || state.equals(NON_OCCLUDING_SOLID); + } + return trait == BlockTrait.OCCLUDING && state.equals(SOLID); + }); + return registry; + } + @Test public void recordsLowestPlacedOccludingCellByDefault() { - PlatformBlockState solid = mock(PlatformBlockState.class); - when(solid.isOccluding()).thenReturn(true); - when(solid.isSolid()).thenReturn(true); - PlatformBlockState nonOccludingSolid = mock(PlatformBlockState.class); - when(nonOccludingSolid.isSolid()).thenReturn(true); - when(nonOccludingSolid.isOccluding()).thenReturn(false); - PlatformBlockState decoration = mock(PlatformBlockState.class); - when(decoration.isOccluding()).thenReturn(false); - - Long2IntOpenHashMap columns = new Long2IntOpenHashMap(); - StructureFoundationPlanner.recordBaseCell(columns, 100, 48, 200, decoration, false); - StructureFoundationPlanner.recordBaseCell(columns, 100, 49, 200, solid, false); - StructureFoundationPlanner.recordBaseCell(columns, 100, 50, 200, solid, false); - StructureFoundationPlanner.recordBaseCell(columns, 100, 45, 200, solid, false); - StructureFoundationPlanner.recordBaseCell(columns, -17, 60, -33, solid, false); - StructureFoundationPlanner.recordBaseCell(columns, 12, 41, 44, solid, false); - StructureFoundationPlanner.recordBaseCell(columns, 12, 36, 44, nonOccludingSolid, false); + ColumnHeights columns = new ColumnHeights(0); + StructureFoundationPlanner.recordBaseCell(columns, 100, 48, 200, DECORATION, BLOCKS, false); + StructureFoundationPlanner.recordBaseCell(columns, 100, 49, 200, SOLID, BLOCKS, false); + StructureFoundationPlanner.recordBaseCell(columns, 100, 50, 200, SOLID, BLOCKS, false); + StructureFoundationPlanner.recordBaseCell(columns, 100, 45, 200, SOLID, BLOCKS, false); + StructureFoundationPlanner.recordBaseCell(columns, -17, 60, -33, SOLID, BLOCKS, false); + StructureFoundationPlanner.recordBaseCell(columns, 12, 41, 44, SOLID, BLOCKS, false); + StructureFoundationPlanner.recordBaseCell(columns, 12, 36, 44, NON_OCCLUDING_SOLID, BLOCKS, false); assertEquals(3, columns.size()); assertEquals(45, columns.get(StructureFoundationPlanner.pack(100, 200))); @@ -44,18 +57,9 @@ public class StructureFoundationPlannerTest { @Test public void recordsSolidNonOccludingBaseWhenEnabled() { - PlatformBlockState partialStructureBlock = mock(PlatformBlockState.class); - when(partialStructureBlock.isSolid()).thenReturn(true); - when(partialStructureBlock.isOccluding()).thenReturn(false); - PlatformBlockState fullStructureBlock = mock(PlatformBlockState.class); - when(fullStructureBlock.isSolid()).thenReturn(true); - when(fullStructureBlock.isOccluding()).thenReturn(true); - - Long2IntOpenHashMap columns = new Long2IntOpenHashMap(); - StructureFoundationPlanner.recordBaseCell( - columns, 12, 41, 44, fullStructureBlock, true); - StructureFoundationPlanner.recordBaseCell( - columns, 12, 36, 44, partialStructureBlock, true); + ColumnHeights columns = new ColumnHeights(0); + StructureFoundationPlanner.recordBaseCell(columns, 12, 41, 44, SOLID, BLOCKS, true); + StructureFoundationPlanner.recordBaseCell(columns, 12, 36, 44, NON_OCCLUDING_SOLID, BLOCKS, true); assertEquals(1, columns.size()); assertEquals(36, columns.get(StructureFoundationPlanner.pack(12, 44))); @@ -72,30 +76,20 @@ public class StructureFoundationPlannerTest { @Test public void compositeGroundUsesOverlayThenCarvingThenTerrain() { - PlatformBlockState solid = mock(PlatformBlockState.class); - when(solid.isSolid()).thenReturn(true); - PlatformBlockState fluid = mock(PlatformBlockState.class); - when(fluid.isSolid()).thenReturn(false); - - assertTrue(StructureFoundationPlanner.isGroundSolid(solid, true, 12, 20)); - assertFalse(StructureFoundationPlanner.isGroundSolid(fluid, false, 12, 20)); - assertFalse(StructureFoundationPlanner.isGroundSolid(null, true, 12, 20)); - assertTrue(StructureFoundationPlanner.isGroundSolid(null, false, 12, 20)); - assertFalse(StructureFoundationPlanner.isGroundSolid(null, false, 21, 20)); - assertTrue(StructureFoundationPlanner.isGroundSolid(null, true, 0, -20)); + assertTrue(StructureFoundationPlanner.isGroundSolid(SOLID, BLOCKS, true, 12, 20)); + assertFalse(StructureFoundationPlanner.isGroundSolid(FLUID, BLOCKS, false, 12, 20)); + assertFalse(StructureFoundationPlanner.isGroundSolid(null, BLOCKS, true, 12, 20)); + assertTrue(StructureFoundationPlanner.isGroundSolid(null, BLOCKS, false, 12, 20)); + assertFalse(StructureFoundationPlanner.isGroundSolid(null, BLOCKS, false, 21, 20)); + assertTrue(StructureFoundationPlanner.isGroundSolid(null, BLOCKS, true, 0, -20)); } @Test public void surfaceSupportStopsAtCarvedCaveBoundary() { - PlatformBlockState solid = mock(PlatformBlockState.class); - when(solid.isSolid()).thenReturn(true); - PlatformBlockState air = mock(PlatformBlockState.class); - when(air.isSolid()).thenReturn(false); - - assertTrue(StructureFoundationPlanner.isSurfaceSupportBoundary(null, true, 18, 24)); - assertTrue(StructureFoundationPlanner.isSurfaceSupportBoundary(solid, false, 30, 24)); - assertFalse(StructureFoundationPlanner.isSurfaceSupportBoundary(air, false, 30, 24)); - assertTrue(StructureFoundationPlanner.isSurfaceSupportBoundary(null, false, 24, 24)); + assertTrue(StructureFoundationPlanner.isSurfaceSupportBoundary(null, BLOCKS, true, 18, 24)); + assertTrue(StructureFoundationPlanner.isSurfaceSupportBoundary(SOLID, BLOCKS, false, 30, 24)); + assertFalse(StructureFoundationPlanner.isSurfaceSupportBoundary(FLUID, BLOCKS, false, 30, 24)); + assertTrue(StructureFoundationPlanner.isSurfaceSupportBoundary(null, BLOCKS, false, 24, 24)); } @Test diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureOutputPinTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureOutputPinTest.java new file mode 100644 index 000000000..a33567ff6 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureOutputPinTest.java @@ -0,0 +1,852 @@ +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.builtin.structure.StructureAnchorMode; +import art.arcane.iris.builtin.structure.StructureCarveShape; +import art.arcane.iris.builtin.structure.StructureDistribution; +import art.arcane.iris.builtin.structure.StructurePlacement; +import art.arcane.iris.builtin.structure.StructureStilts; +import art.arcane.iris.builtin.structure.StructureTerrain; +import art.arcane.iris.builtin.structure.StructureTerrainMode; +import art.arcane.iris.core.IrisSettings; +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.BuiltInPack; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.EngineGeneration; +import art.arcane.iris.engine.framework.IrisStructureLocator; +import art.arcane.iris.engine.framework.structure.assembly.AssembledPiece; +import art.arcane.iris.engine.framework.SeedManager; +import art.arcane.iris.engine.framework.StructurePlacementScope; +import art.arcane.iris.engine.framework.StructureTestWorld; +import art.arcane.iris.engine.object.TestSettings; +import art.arcane.iris.engine.object.prefab.IrisObject; +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.IrisJigsawMode; +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.IrisJigsawPieceRules; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; +import com.volmit.geometry.BlockPosition; +import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.spi.IrisPlatform; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.spi.PlatformRegistries; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.iris.core.modules.IrisPackResources; +import art.arcane.iris.core.modules.PlacementMarkers; +import com.volmit.IrisFeature; +import com.volmit.block.BlockState; +import com.volmit.config.FeatureSettings; +import com.volmit.config.Level; +import com.volmit.config.PackSettings; +import com.volmit.config.SettingsStack; +import com.volmit.data.SavedKey; +import com.volmit.geometry.BlockBox; +import com.volmit.geometry.BlockPosition; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.Mantle; +import com.volmit.mantle.MantleEdit; +import com.volmit.mantle.MantleLayer; +import com.volmit.mantle.MantleVisitor; +import com.volmit.object.BlockEntityData; +import com.volmit.placement.PlacedMarker; +import com.volmit.placement.PlacementRecord; +import com.volmit.placement.PlacementTerrain; +import com.volmit.placement.Placements; +import com.volmit.placement.StructureVolumes; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.stage.MantleStageContext; +import com.volmit.world.BiomeKind; +import com.volmit.world.BiomeSample; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; +import com.volmit.world.TerrainSample; +import com.volmit.world.TerrainSampler; +import com.volmit.world.UpperDimension; +import com.volmit.ModuleLog; +import com.volmit.config.FeatureSettings.Entry; +import com.google.gson.Gson; +import com.volmit.host.LoadedPack; +import com.volmit.host.ModuleLogs; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues; +import org.mockito.invocation.InvocationOnMock; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.withSettings; +import static org.mockito.Mockito.when; + +/** + * Pins what the structure placements of a pack generate, so the code that places them can move without changing a world. + * One pack of jigsaw structures (a spatial one, a planar one, a themed one and one with caps) is placed by placements of + * every distribution and anchor the engine knows, with stilts, borings and carves, over a grid of chunks on a fixed uneven + * terrain with a cave. Per scenario two hashes are pinned: the pieces every resolved placement assembled (object key, origin, + * turn and bounds, in order), and every block, marker and carve the placing wrote to the mantle, in order. A mismatch prints + * every scenario's hashes. These hashes are never re-recorded. + */ +public class StructureOutputPinTest { + private static final long WORLD_SEED = 20261110L; + private static final int MIN_HEIGHT = -64; + private static final int WORLD_HEIGHT = 320; + private static final int FLUID_HEIGHT = 63; + private static final int GRID_RADIUS_CHUNKS = 40; + private static final int GRID_BLOCKS = 1_000_000; + private static final int CAVE_FLOOR_MANTLE_Y = 50; + private static final int CAVE_CEILING_MANTLE_Y = 78; + + /** What a scenario must write besides blocks and markers: a boring or carving, or foundation columns below stilts. */ + private static final Map> EXPECTED_WRITE_KINDS = Map.of( + "themed-bore", List.of("S ", "C "), + "caps-box-carve", List.of("S ", "C "), + "eroded-carve", List.of("S ", "C "), + "underground", List.of("S ", "C ")); + + private static final Map PINNED = pinned(); + + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + private final Map registryStates = new HashMap<>(); + private final Map objects = new HashMap<>(); + private IrisData data; + private LoadedPack pack; + + private IrisSettings previousSettings; + + @Before + public void bindPlatform() throws IOException { + previousSettings = IrisSettings.settings; + IrisSettings.settings = new IrisSettings(); + IrisPlatforms.unbind(); + PlatformRegistries registries = mock(PlatformRegistries.class); + when(registries.block(anyString())).thenAnswer(invocation -> registryState(invocation.getArgument(0))); + IrisPlatform platform = mock(IrisPlatform.class); + when(platform.registries()).thenReturn(registries); + IrisPlatforms.bind(platform); + + data = mock(IrisData.class); + pack = BuiltInPack.serve(data, folder, List.of()); + writePack(); + when(data.getBlockLoader()).thenReturn(mock(art.arcane.iris.core.loader.ResourceLoader.class)); + art.arcane.iris.core.loader.ResourceLoader objectLoader = mock(art.arcane.iris.core.loader.ResourceLoader.class); + when(objectLoader.getPossibleKeys()).thenAnswer(invocation -> objects.keySet().toArray(String[]::new)); + when(objectLoader.findFile(anyString())).thenAnswer(invocation -> objectFile(invocation.getArgument(0))); + when(objectLoader.load(anyString())).thenAnswer(invocation -> objects.get((String) invocation.getArgument(0))); + when(data.getObjectLoader()).thenReturn(objectLoader); + when(data.load(eq(IrisObject.class), anyString(), anyBoolean())) + .thenAnswer(invocation -> objects.get((String) invocation.getArgument(1))); + } + + /** The .iob file of the object {@code key}, written on first ask, which is where the graph reads an object's size from. */ + private File objectFile(String key) throws IOException { + IrisObject object = objects.get(key); + if (object == null) { + return null; + } + File file = new File(folder.getRoot(), "objects/" + key + ".iob"); + if (!file.exists()) { + Files.createDirectories(file.getParentFile().toPath()); + object.write(file); + } + return file; + } + + @After + public void unbindPlatform() { + pack.close(); + IrisPlatforms.unbind(); + IrisSettings.settings = previousSettings; + } + + @Test + public void everyScenarioPlacesThePinnedStructures() { + Map actual = new LinkedHashMap<>(); + for (Map.Entry scenario : scenarios().entrySet()) { + Outcome outcome = run(scenario.getValue()); + assertTrue(scenario.getKey() + " assembled no structure", outcome.starts > 0); + assertTrue(scenario.getKey() + " wrote nothing", !outcome.writes.isEmpty()); + for (String kind : EXPECTED_WRITE_KINDS.getOrDefault(scenario.getKey(), List.of("S ", "D "))) { + assertTrue(scenario.getKey() + " wrote no '" + kind + "' line", outcome.writes.stream().anyMatch(line -> line.startsWith(kind))); + } + actual.put(scenario.getKey(), outcome.starts + "/" + hash(outcome.pieces) + "/" + hash(outcome.writes)); + } + StringBuilder report = new StringBuilder(); + actual.forEach((name, hashes) -> report.append(" Map.entry(\"").append(name).append("\", \"") + .append(hashes).append("\"),\n")); + assertEquals("Pinned structure output changed:\n" + report, PINNED, actual); + } + + private Map scenarios() { + Map scenarios = new LinkedHashMap<>(); + scenarios.put("spatial", spread("pin-spatial", "pin/spatial", 10, 3)); + scenarios.put("planar", spread("pin-planar", "pin/planar", 12, 4)); + scenarios.put("themed-bore", withTerrain(spread("pin-themed", "pin/themed", 9, 2), + terrain(StructureTerrainMode.BORE, StructureCarveShape.BOX, 2, 3, 1))); + scenarios.put("caps-box-carve", withTerrain(spread("pin-caps", "pin/caps", 11, 3), + terrain(StructureTerrainMode.FORCE_CARVE, StructureCarveShape.BOX, 3, 4, 2))); + scenarios.put("rings", rings("pin-rings", "pin/spatial")); + scenarios.put("stilts", withStilt(spread("pin-stilts", "pin/spatial", 10, 3))); + scenarios.put("eroded-carve", withTerrain(spread("pin-eroded", "pin/spatial", 10, 3), + terrain(StructureTerrainMode.FORCE_CARVE, StructureCarveShape.ERODED, 4, 5, 3))); + scenarios.put("cave", cave("pin-cave", "pin/caps")); + scenarios.put("underground", underground("pin-underground", "pin/spatial")); + return scenarios; + } + + private static StructurePlacement spread(String id, String structure, int spacing, int separation) { + return placement("placementId", id, "structures", List.of(structure), "distribution", StructureDistribution.RANDOM_SPREAD, + "spacing", spacing, "separation", separation); + } + + private static StructurePlacement rings(String id, String structure) { + return placement("placementId", id, "structures", List.of(structure), "distribution", StructureDistribution.CONCENTRIC_RINGS, + "ringCount", 6, "ringDistance", 7, "ringSpread", 3); + } + + private static StructurePlacement cave(String id, String structure) { + return placement("placementId", id, "structures", List.of(structure), "distribution", StructureDistribution.RANDOM_SPREAD, + "spacing", 6, "separation", 1, "underground", true, "anchor", StructureAnchorMode.CAVE_FLOOR, + "minHeight", -20, "maxHeight", 0, "caveMinimumClearance", 5); + } + + private static StructurePlacement underground(String id, String structure) { + return withTerrain(placement("placementId", id, "structures", List.of(structure), "distribution", StructureDistribution.RANDOM_SPREAD, + "spacing", 10, "separation", 3, "underground", true, "anchor", StructureAnchorMode.HEIGHT_BAND, + "minHeight", -40, "maxHeight", 20), + terrain(StructureTerrainMode.FORCE_CARVE, StructureCarveShape.ROUNDED, 2, 2, 1)); + } + + private static StructurePlacement withTerrain(StructurePlacement placement, StructureTerrain terrain) { + return TestSettings.with(placement, "terrain", terrain); + } + + private static StructurePlacement withStilt(StructurePlacement placement) { + return TestSettings.with(placement, "stilt", TestSettings.with(new StructureStilts(), "maxDepth", 10)); + } + + private static StructureTerrain terrain(StructureTerrainMode mode, StructureCarveShape shape, int horizontal, int ceiling, int floor) { + return TestSettings.with(new StructureTerrain(), "mode", mode, "shape", shape, "horizontalPadding", horizontal, + "ceilingPadding", ceiling, "floorPadding", floor); + } + + private static StructurePlacement placement(Object... namesAndValues) { + return TestSettings.with(new StructurePlacement(), namesAndValues); + } + + private Outcome run(StructurePlacement placement) { + Engine engine = engineWith(placement); + StructureTestWorld world = new StructureTestWorld() + .hostedBy(engine.getGeneration().world()) + .worldSeed(WORLD_SEED) + .placementSeed(new SeedManager(WORLD_SEED).getMantle()) + .minY(MIN_HEIGHT) + .height(WORLD_HEIGHT) + .fluidHeight(FLUID_HEIGHT) + .highest(StructureOutputPinTest::terrainHeight) + .carved((x, mantleY, z) -> caveAt(mantleY)) + .dimension(placement); + WriterLog log = new WriterLog(world); + Outcome outcome = new Outcome(); + StructurePlacing placing = new StructurePlacing(world, ModuleLogs.discarding()); + for (int chunkX = -GRID_RADIUS_CHUNKS; chunkX < GRID_RADIUS_CHUNKS; chunkX++) { + for (int chunkZ = -GRID_RADIUS_CHUNKS; chunkZ < GRID_RADIUS_CHUNKS; chunkZ++) { + for (StructurePlacement scoped : StructurePlacementScope.placementsAt(world, chunkX, chunkZ)) { + IrisStructureLocator.ResolvedPlacement resolved = IrisStructureLocator.resolvePlacement(world, scoped, chunkX, chunkZ); + if (resolved == null) { + continue; + } + outcome.starts++; + outcome.pieces.add("start " + chunkX + "," + chunkZ + " " + resolved.structureKey() + " " + resolved.originX() + "," + + resolved.baseY() + "," + resolved.originZ() + " exactY=" + resolved.exactY()); + for (AssembledPiece piece : resolved.pieces()) { + outcome.pieces.add(describe(piece)); + } + } + placing.place(log.contextOf(chunkX, chunkZ)); + } + } + outcome.writes.addAll(log.lines); + return outcome; + } + + private String describe(AssembledPiece piece) { + return data.getPackResources().keyOf(piece.object()) + " " + piece.x() + "," + piece.y() + "," + piece.z() + + " turn=0.0," + (double) piece.turn().yDegrees() + ",0.0" + + " box=" + piece.minX() + "," + piece.minY() + "," + piece.minZ() + ".." + + piece.maxX() + "," + piece.maxY() + "," + piece.maxZ(); + } + + private Engine engineWith(StructurePlacement placement) { + Engine engine = mock(Engine.class, withSettings().stubOnly()); + IrisDimension dimension = mock(IrisDimension.class, withSettings().stubOnly()); + art.arcane.iris.engine.mantle.EngineMantle engineMantle = mock(art.arcane.iris.engine.mantle.EngineMantle.class, withSettings().stubOnly()); + @SuppressWarnings("unchecked") + art.arcane.volmlib.util.mantle.runtime.Mantle mantle = + mock(art.arcane.volmlib.util.mantle.runtime.Mantle.class, withSettings().stubOnly()); + when(mantle.get(anyInt(), anyInt(), anyInt(), eq(art.arcane.volmlib.util.matter.MatterCavern.class))) + .thenAnswer(invocation -> caveAt(invocation.getArgument(1)).map(ignored -> new art.arcane.volmlib.util.matter.MatterCavern(true, "", (byte) 3)).orElse(null)); + when(engineMantle.getMantle()).thenReturn(mantle); + when(engineMantle.trueHeight(anyInt(), anyInt())).thenAnswer(invocation -> terrainHeight(invocation.getArgument(0), invocation.getArgument(1))); + when(engine.getMantle()).thenReturn(engineMantle); + when(engine.getData()).thenReturn(data); + when(data.getEngine()).thenReturn(engine); + when(engine.getSeedManager()).thenReturn(new SeedManager(WORLD_SEED)); + when(engine.getMinHeight()).thenReturn(MIN_HEIGHT); + when(engine.getHeight()).thenReturn(WORLD_HEIGHT); + when(engine.getHeight(anyInt(), anyInt(), anyBoolean())) + .thenAnswer(invocation -> terrainHeight(invocation.getArgument(0), invocation.getArgument(1))); + when(engine.getHeight(anyInt(), anyInt())) + .thenAnswer(invocation -> terrainHeight(invocation.getArgument(0), invocation.getArgument(1))); + when(dimension.getFluidHeight()).thenReturn(FLUID_HEIGHT); + when(dimension.getModuleSettings()).thenReturn(BuiltInPack.settings( + TestSettings.with(new art.arcane.iris.builtin.structure.StructurePlacementSettings(), "placements", new ArrayList<>(List.of(placement))))); + when(dimension.getAllRegions(any())).thenReturn(new KList<>()); + when(dimension.getReachableBiomes(any())).thenReturn(new KList<>()); + when(engine.getDimension()).thenReturn(dimension); + when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); + return engine; + } + + /** Uneven terrain, as a height above the dimension's bottom: it climbs and falls by up to nine blocks over a few columns. */ + private static int terrainHeight(int x, int z) { + return 128 + Math.floorMod(x * 3 + z * 5, 9) + Math.floorMod(x / 7 - z / 5, 4); + } + + private static Optional caveAt(int mantleY) { + return mantleY >= CAVE_FLOOR_MANTLE_Y && mantleY <= CAVE_CEILING_MANTLE_Y ? Optional.of(CarvedVoid.AIR) : Optional.empty(); + } + + /** + * The mantle placement writes into, as the api shows it: it records every write as one line, in the order the writes + * come, and reads back what was written. + */ + private final class WriterLog { + private final Map written = new HashMap<>(); + private final List lines = new ArrayList<>(); + private final StructureTestWorld world; + private final PlacementTerrain terrain = new RecordingTerrain(); + private final Mantle mantle = new RecordingMantle(); + private final MutableContext context = new MutableContext(); + + WriterLog(StructureTestWorld world) { + this.world = world; + } + + MantleStageContext contextOf(int chunkX, int chunkZ) { + context.chunkX = chunkX; + context.chunkZ = chunkZ; + return context; + } + + private BlockState stateAt(int x, int y, int z) { + BlockState state = written.get(position(x, y, z)); + if (state != null) { + return state; + } + boolean ground = y <= terrainHeight(x, z) && caveAt(y).isEmpty(); + return new BlockState(ground ? "minecraft:stone" : "minecraft:air"); + } + + private static String position(int x, int y, int z) { + return x + "," + y + "," + z; + } + + private final class MutableContext implements MantleStageContext { + private int chunkX; + private int chunkZ; + + @Override + public int chunkX() { + return chunkX; + } + + @Override + public int chunkZ() { + return chunkZ; + } + + @Override + public int originX() { + return chunkX << 4; + } + + @Override + public int originZ() { + return chunkZ << 4; + } + + @Override + public PackWorld world() { + return world; + } + + @Override + public TerrainSampler terrain() { + return world.running().orElseThrow().layout(); + } + + @Override + public FeatureSettings settings() { + return world.running().orElseThrow().settings(); + } + + @Override + public Mantle mantle() { + return mantle; + } + + @Override + public PlacementTerrain placementTerrain() { + return terrain; + } + + @Override + public com.volmit.random.WorldRandom random() { + throw new UnsupportedOperationException("No random here"); + } + + @Override + public O output(com.volmit.stage.Stage stage) { + throw new UnsupportedOperationException("No stage outputs here"); + } + + @Override + public SettingsStack configured(Class settingsType) { + throw new UnsupportedOperationException("No stage settings here"); + } + } + + private final class RecordingTerrain implements PlacementTerrain { + @Override + public int highest(int x, int z, boolean ignoreFluid) { + return terrainHeight(x, z); + } + + @Override + public BlockState get(int x, int y, int z) { + return stateAt(x, y, z); + } + + @Override + public void set(int x, int y, int z, BlockState state) { + lines.add("S " + position(x, y, z) + "=" + state.key()); + written.put(position(x, y, z), state); + } + + @Override + public void set(int x, int y, int z, BlockState state, BlockEntityData blockEntity) { + set(x, y, z, state); + lines.add("T " + position(x, y, z)); + } + + @Override + public void clearBlock(int x, int y, int z) { + written.remove(position(x, y, z)); + } + + @Override + public void clearAttached(int x, int y, int z) { + } + + @Override + public boolean isCarved(int x, int y, int z) { + return false; + } + + @Override + public boolean isSurfaceSolid(int x, int y, int z) { + return true; + } + + @Override + public boolean isUnderwater(int x, int z) { + return false; + } + + @Override + public int fluidHeight() { + return FLUID_HEIGHT - MIN_HEIGHT; + } + + @Override + public boolean preventsDecay() { + return false; + } + + @Override + public void recordPlacement(int x, int y, int z, PlacementRecord placement) { + IrisPackResources resources = (IrisPackResources) world.resources(); + lines.add("D " + position(x, y, z) + "=String:" + PlacementMarkers.encode(placement, resources)); + } + + @Override + public Optional placementAt(int x, int y, int z) { + return Optional.empty(); + } + + @Override + public StructureVolumes structureVolumes(int minX, int minZ, int maxX, int maxZ) { + return new StructureVolumes() { + @Override + public boolean isEmpty() { + return true; + } + + @Override + public boolean intersects(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { + return false; + } + + @Override + public boolean containsWithin(int x, int y, int z, int margin) { + return false; + } + }; + } + + @Override + public void mark(PlacedMarker marker) { + BlockPosition at = marker.position(); + String kind = switch (marker) { + case PlacedMarker.TreeMaterial ignored -> "TreeBlockMaterial"; + case PlacedMarker.BuriedTreasure ignored -> "MatterStructurePOI"; + case PlacedMarker.PackMarker ignored -> "MatterMarker"; + }; + lines.add("D " + position(at.x(), at.y(), at.z()) + "=" + kind); + } + } + + private final class RecordingMantle implements Mantle { + private final MantleLayer blocks = new MantleLayer<>() { + @Override + public BlockState get(int x, int y, int z) { + return written.get(position(x, y, z)); + } + + @Override + public void set(int x, int y, int z, BlockState value) { + throw new UnsupportedOperationException("Blocks are written through placements"); + } + + @Override + public void remove(int x, int y, int z) { + throw new UnsupportedOperationException("Blocks are written through placements"); + } + + @Override + public void visit(BlockBox area, MantleVisitor visitor) { + throw new UnsupportedOperationException("No visits here"); + } + + @Override + public void clear(BlockBox area) { + throw new UnsupportedOperationException("No clears here"); + } + }; + private final MantleLayer carved = new MantleLayer<>() { + @Override + public CarvedVoid get(int x, int y, int z) { + return null; + } + + @Override + public void set(int x, int y, int z, CarvedVoid value) { + lines.add("C " + position(x, y, z)); + } + + @Override + public void remove(int x, int y, int z) { + lines.add("R " + position(x, y, z) + "=MatterCavern"); + } + + @Override + public void visit(BlockBox area, MantleVisitor visitor) { + throw new UnsupportedOperationException("No visits here"); + } + + @Override + public void clear(BlockBox area) { + throw new UnsupportedOperationException("No clears here"); + } + }; + + @Override + public BlockBox bounds() { + return new BlockBox(-GRID_BLOCKS, 0, -GRID_BLOCKS, GRID_BLOCKS, WORLD_HEIGHT, GRID_BLOCKS); + } + + @Override + public MantleLayer layer(com.volmit.mantle.MantleKey key) { + throw new UnsupportedOperationException("No module layers here"); + } + + @Override + public MantleLayer blocks() { + return blocks; + } + + @Override + public MantleLayer carved() { + return carved; + } + + @Override + public void setPlatformBiome(int x, int y, int z, ResourceId biome) { + throw new UnsupportedOperationException("No biomes here"); + } + + @Override + public MantleEdit edit() { + throw new UnsupportedOperationException("No edits here"); + } + } + } + + private PlatformBlockState registryState(String key) { + String normalized = key.toLowerCase(); + String namespaced = normalized.contains(":") ? normalized : "minecraft:" + normalized; + return registryStates.computeIfAbsent(namespaced, value -> state(value)); + } + + private static PlatformBlockState state(String key) { + boolean air = key.contains("air"); + boolean solid = !air && !key.contains("water") && !key.contains("snow") && !key.contains("glass"); + PlatformBlockState state = mock(PlatformBlockState.class, withSettings().stubOnly()); + when(state.key()).thenReturn(key); + when(state.materialKey()).thenReturn(key); + when(state.isSolid()).thenReturn(solid); + when(state.isOccluding()).thenReturn(solid); + when(state.isAir()).thenReturn(air); + when(state.isStorageChest()).thenReturn(key.endsWith(":chest")); + return state; + } + + private void writePack() throws IOException { + Gson gson = new Gson(); + Map structures = new LinkedHashMap<>(); + Map pools = new LinkedHashMap<>(); + Map pieces = new LinkedHashMap<>(); + pools.put("terminal", new IrisJigsawPool()); + + defineSpatial(structures, pools, pieces); + definePlanar(structures, pools, pieces); + defineThemed(structures, pools, pieces); + defineCaps(structures, pools, pieces); + + write(gson, "structures", structures); + write(gson, "jigsaw-pools", pools); + write(gson, "jigsaw-pieces", pieces); + } + + private void defineSpatial(Map structures, Map pools, Map pieces) { + pools.put("pin/spatial/start", pool("", "pin/spatial/hall")); + pools.put("pin/spatial/arms", pool("", "pin/spatial/wing")); + pools.put("pin/spatial/tails", pool("", "pin/spatial/tower")); + pools.put("pin/spatial/ends", pool("", "pin/spatial/cap")); + pieces.put("pin/spatial/hall", piece("pin/spatial/hall", true, + connector(JigsawDirection.EAST_POSITIVE_X, "pin/spatial/arms", "hall-east", "door", 8, 1, 4), + connector(JigsawDirection.WEST_NEGATIVE_X, "pin/spatial/tails", "hall-west", "tail", 0, 1, 4))); + pieces.put("pin/spatial/wing", piece("pin/spatial/wing", true, + connector(JigsawDirection.WEST_NEGATIVE_X, "terminal", "door", "unused", 0, 1, 2), + connector(JigsawDirection.EAST_POSITIVE_X, "pin/spatial/ends", "wing-east", "door", 6, 1, 2))); + pieces.put("pin/spatial/tower", piece("pin/spatial/tower", true, + connector(JigsawDirection.EAST_POSITIVE_X, "terminal", "tail", "unused", 2, 1, 1))); + pieces.put("pin/spatial/cap", piece("pin/spatial/cap", true, + connector(JigsawDirection.WEST_NEGATIVE_X, "terminal", "door", "unused", 0, 1, 1))); + objects.put("pin/spatial/hall", building("pin/spatial/hall", 9, 5, 9, "oak_planks", true)); + objects.put("pin/spatial/wing", building("pin/spatial/wing", 7, 4, 5, "spruce_planks", false)); + objects.put("pin/spatial/tower", building("pin/spatial/tower", 3, 8, 3, "stone_bricks", true)); + objects.put("pin/spatial/cap", building("pin/spatial/cap", 3, 3, 3, "cobblestone", false)); + structures.put("pin/spatial", structure("pin/spatial/start", 3, 6)); + } + + private void definePlanar(Map structures, Map pools, Map pieces) { + pools.put("pin/planar/start", pool("", "pin/planar/start")); + pools.put("pin/planar/north", pool("", "pin/planar/north")); + pools.put("pin/planar/east", pool("", "pin/planar/east")); + pools.put("pin/planar/south", pool("", "pin/planar/south")); + pools.put("pin/planar/west", pool("", "pin/planar/west")); + pieces.put("pin/planar/start", piece("pin/planar/start", false, + connector(JigsawDirection.NORTH_NEGATIVE_Z, "pin/planar/north", "start", "door", 8, 4, 0), + connector(JigsawDirection.EAST_POSITIVE_X, "pin/planar/east", "start", "door", 15, 4, 8), + connector(JigsawDirection.SOUTH_POSITIVE_Z, "pin/planar/south", "start", "door", 8, 4, 15), + connector(JigsawDirection.WEST_NEGATIVE_X, "pin/planar/west", "start", "door", 0, 4, 8))); + pieces.put("pin/planar/north", piece("pin/planar/north", false, + connector(JigsawDirection.SOUTH_POSITIVE_Z, "terminal", "door", "", 8, 4, 15))); + pieces.put("pin/planar/east", piece("pin/planar/east", false, + connector(JigsawDirection.WEST_NEGATIVE_X, "terminal", "door", "", 0, 4, 8))); + pieces.put("pin/planar/south", piece("pin/planar/south", false, + connector(JigsawDirection.NORTH_NEGATIVE_Z, "terminal", "door", "", 8, 4, 0))); + pieces.put("pin/planar/west", piece("pin/planar/west", false, + connector(JigsawDirection.EAST_POSITIVE_X, "terminal", "door", "", 15, 4, 8))); + objects.put("pin/planar/start", building("pin/planar/start", 16, 8, 16, "oak_planks", true)); + objects.put("pin/planar/north", building("pin/planar/north", 16, 8, 16, "spruce_planks", false)); + objects.put("pin/planar/east", building("pin/planar/east", 16, 8, 16, "birch_planks", false)); + objects.put("pin/planar/south", building("pin/planar/south", 16, 8, 16, "dark_oak_planks", true)); + objects.put("pin/planar/west", building("pin/planar/west", 16, 8, 16, "acacia_planks", false)); + structures.put("pin/planar", structure("pin/planar/start", 1, 8) + .setMode(IrisJigsawMode.PLANAR_JIGSAW).setCellSize(new BlockPosition(16, 8, 16))); + } + + private void defineThemed(Map structures, Map pools, Map pieces) { + pools.put("pin/themed/start", pool("", "pin/themed/first", "pin/themed/second")); + IrisJigsawPiece first = piece("pin/themed/first", false); + first.getThemes().add("variant-1"); + IrisJigsawPiece second = piece("pin/themed/second", true); + second.getThemes().add("variant-2"); + pieces.put("pin/themed/first", first); + pieces.put("pin/themed/second", second); + objects.put("pin/themed/first", building("pin/themed/first", 7, 6, 7, "oak_planks", true)); + objects.put("pin/themed/second", building("pin/themed/second", 5, 9, 5, "stone_bricks", false)); + IrisStructure structure = structure("pin/themed/start", 1, 4); + structure.getThemeSets().add(new IrisJigsawThemeSet("variant-1", 1)); + structure.getThemeSets().add(new IrisJigsawThemeSet("variant-2", 1)); + structures.put("pin/themed", structure); + } + + private void defineCaps(Map structures, Map pools, Map pieces) { + pools.put("pin/caps/start", pool("", "pin/caps/start")); + pools.put("pin/caps/branch", pool("pin/caps/caps", "pin/caps/incompatible")); + pools.put("pin/caps/caps", pool("", "pin/caps/cap")); + pieces.put("pin/caps/start", piece("pin/caps/start", false, + connector(JigsawDirection.EAST_POSITIVE_X, "pin/caps/branch", "start", "door", 6, 1, 2), + connector(JigsawDirection.WEST_NEGATIVE_X, "pin/caps/branch", "start", "door", 0, 1, 2))); + pieces.put("pin/caps/incompatible", piece("pin/caps/incompatible", false, + connector(JigsawDirection.WEST_NEGATIVE_X, "terminal", "wrong", "", 0, 1, 1))); + IrisJigsawPiece cap = piece("pin/caps/cap", false, + connector(JigsawDirection.WEST_NEGATIVE_X, "terminal", "door", "", 0, 1, 1), + connector(JigsawDirection.EAST_POSITIVE_X, "terminal", "door", "", 2, 1, 1)); + cap.setRules(new IrisJigsawPieceRules().setTerminal(true)); + pieces.put("pin/caps/cap", cap); + objects.put("pin/caps/start", building("pin/caps/start", 7, 5, 5, "oak_planks", true)); + objects.put("pin/caps/incompatible", building("pin/caps/incompatible", 3, 3, 3, "stone", false)); + objects.put("pin/caps/cap", building("pin/caps/cap", 3, 4, 3, "cobblestone", true)); + structures.put("pin/caps", structure("pin/caps/start", 2, 6).setRequireCaps(true)); + } + + private static IrisStructure structure(String startPool, int maxDepth, int maxSizeChunks) { + return new IrisStructure().setStartPool(startPool).setMaxDepth(maxDepth).setMaxSizeChunks(maxSizeChunks); + } + + private static IrisJigsawPool pool(String fallback, String... pieceKeys) { + IrisJigsawPool pool = new IrisJigsawPool().setFallback(fallback); + for (String pieceKey : pieceKeys) { + pool.getPieces().add(new IrisJigsawPieceEntry().setPiece(pieceKey).setWeight(1)); + } + return pool; + } + + private static IrisJigsawPiece piece(String object, boolean rotatable, IrisJigsawConnector... connectors) { + IrisJigsawPiece piece = new IrisJigsawPiece().setObject(object).setRotatable(rotatable); + piece.getConnectors().addAll(List.of(connectors)); + return piece; + } + + private static IrisJigsawConnector connector(JigsawDirection direction, String pool, String name, String targetName, int x, int y, int z) { + return new IrisJigsawConnector() + .setPosition(new BlockPosition(x, y, z)) + .setDirection(direction) + .setPool(pool) + .setName(name) + .setTargetName(targetName) + .setJoint(JigsawJoint.ROLLABLE); + } + + /** A hollow building with a doorway in the middle of two opposite walls, a window row and, optionally, a chest by the door. */ + private IrisObject building(String key, int width, int height, int depth, String wall, boolean chest) { + IrisObject object = new IrisObject(width, height, depth); + object.setLoadKey(key); + PlatformBlockState floor = registryState("minecraft:stone"); + PlatformBlockState walls = registryState("minecraft:" + wall); + PlatformBlockState glass = registryState("minecraft:glass"); + for (int x = 0; x < width; x++) { + for (int z = 0; z < depth; z++) { + if ((x + z) % 5 != 4) { + object.setUnsigned(x, 0, z, floor); + } + for (int y = 1; y < height; y++) { + boolean shell = x == 0 || x == width - 1 || z == 0 || z == depth - 1 || y == height - 1; + boolean doorway = (x == 0 || x == width - 1) && z == depth / 2 && y < 3; + if (shell && !doorway) { + object.setUnsigned(x, y, z, y == 2 && (x + z) % 2 == 0 && y < height - 1 ? glass : walls); + } + } + } + } + if (chest && width > 3 && depth > 3) { + object.setUnsigned(1, 1, 1, registryState("minecraft:chest")); + } + return object; + } + + private void write(Gson gson, String folderName, Map resources) throws IOException { + for (Map.Entry resource : resources.entrySet()) { + Path file = folder.getRoot().toPath().resolve(folderName).resolve(resource.getKey() + ".json"); + Files.createDirectories(file.getParent()); + Files.writeString(file, gson.toJson(resource.getValue()), StandardCharsets.UTF_8); + } + } + + private static String hash(List lines) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + for (String line : lines) { + digest.update(line.getBytes(StandardCharsets.UTF_8)); + digest.update((byte) '\n'); + } + return lines.size() + ":" + HexFormat.of().formatHex(digest.digest()).substring(0, 24); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } + + private static final class Outcome { + private int starts; + private final List pieces = new ArrayList<>(); + private final List writes = new ArrayList<>(); + } + + private static Map pinned() { + return Map.ofEntries( + Map.entry("spatial", "64/320:2332f4bcffe3b09749ed5af3/26944:38d50ba318e070eba6a3db62"), + Map.entry("planar", "42/252:e15ff2ebb66f87363d66c207/171738:de11453c28c528afb56c68d1"), + Map.entry("themed-bore", "78/156:282a92cb631ae1c15e65af1f/102483:1fb6c4122cf54a848ae89e8a"), + Map.entry("caps-box-carve", "54/216:862f59ec9d164ed5feb37322/133812:b1023f34a227e6c5b8fcff9d"), + Map.entry("rings", "6/30:e31d276ce85624af3ba14642/2526:bc0ff7eae5831894052e6343"), + Map.entry("stilts", "64/320:1a39c3f3255c55b16e8188a1/40214:840373ed96bd4916b98fe6c5"), + Map.entry("eroded-carve", "64/320:ad8a6ff5c913c07ac5bf245a/167070:f9106559688ccd4c4f39aa26"), + Map.entry("cave", "175/700:09e748228682b3073b879ec8/31325:5cd287cc7c0a3e42319e7493"), + Map.entry("underground", "64/320:131ff0564f8624534b2f660d/127534:1025f82c04539d4881a0e92b")); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructurePlacingMarkerTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructurePlacingMarkerTest.java index 74131c292..376059ca0 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructurePlacingMarkerTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructurePlacingMarkerTest.java @@ -1,13 +1,19 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.engine.framework.IrisStructureLocator; -import art.arcane.iris.engine.framework.PlacedStructurePiece; -import art.arcane.iris.engine.object.structure.IrisStructure; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.engine.framework.structure.assembly.AssembledPiece; +import art.arcane.iris.engine.framework.structure.assembly.PieceTurn; +import art.arcane.iris.engine.framework.structure.assembly.StructureStamp; +import com.volmit.resource.ResourceId; +import java.util.List; import art.arcane.iris.builtin.structure.StructurePlacement; import art.arcane.iris.builtin.structure.NativeStructureSuppression; -import art.arcane.iris.spi.PlatformBlockState; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; import org.junit.Test; import static art.arcane.iris.engine.framework.StructurePlacementFixtures.placement; @@ -23,14 +29,13 @@ import static org.mockito.Mockito.when; public class StructurePlacingMarkerTest { @Test public void markerFilterAcceptsOnlyStorageContainers() { - PlatformBlockState storage = mock(PlatformBlockState.class); - PlatformBlockState solid = mock(PlatformBlockState.class); - when(storage.isStorageChest()).thenReturn(true); - when(solid.isStorageChest()).thenReturn(false); + BlockState storage = new BlockState("minecraft:chest"); + BlockState solid = new BlockState("minecraft:stone"); + BlockRegistry blocks = blocksWith(BlockTrait.STORAGE, storage); - assertTrue(StructurePlacing.shouldWriteStructureMarker(storage)); - assertFalse(StructurePlacing.shouldWriteStructureMarker(solid)); - assertFalse(StructurePlacing.shouldWriteStructureMarker(null)); + assertTrue(StructurePlacing.shouldWriteStructureMarker(storage, blocks)); + assertFalse(StructurePlacing.shouldWriteStructureMarker(solid, blocks)); + assertFalse(StructurePlacing.shouldWriteStructureMarker(null, blocks)); } @Test @@ -45,14 +50,21 @@ public class StructurePlacingMarkerTest { @Test public void treeCollisionUsesOnlyNonAirStructureBlocks() { - PlatformBlockState solid = mock(PlatformBlockState.class); - PlatformBlockState air = mock(PlatformBlockState.class); - when(solid.isAir()).thenReturn(false); - when(air.isAir()).thenReturn(true); + BlockState solid = new BlockState("minecraft:stone"); + BlockState air = new BlockState("minecraft:air"); + BlockRegistry blocks = blocksWith(BlockTrait.AIR, air); - assertTrue(StructurePlacing.isOccupiedStructureState(solid)); - assertFalse(StructurePlacing.isOccupiedStructureState(air)); - assertFalse(StructurePlacing.isOccupiedStructureState(null)); + assertTrue(StructurePlacing.isOccupiedStructureState(solid, blocks)); + assertFalse(StructurePlacing.isOccupiedStructureState(air, blocks)); + assertFalse(StructurePlacing.isOccupiedStructureState(null, blocks)); + } + + private static BlockRegistry blocksWith(BlockTrait trait, BlockState... having) { + BlockRegistry blocks = mock(BlockRegistry.class); + for (BlockState state : having) { + when(blocks.hasTrait(state, trait)).thenReturn(true); + } + return blocks; } @Test @@ -88,21 +100,20 @@ public class StructurePlacingMarkerTest { private IrisStructureLocator.ResolvedPlacement resolvedWithOnePiece( NativeStructureSuppression suppression ) { - KList pieces = new KList<>(); - pieces.add(mock(PlacedStructurePiece.class)); + KList pieces = new KList<>(); + pieces.add(new AssembledPiece(new ResourceId("test", "piece"), 0, 0, 0, PieceTurn.NONE, 0, 0, 0, 0, 0, 0)); return resolvedPlacement(suppression, pieces); } private IrisStructureLocator.ResolvedPlacement resolvedPlacement( NativeStructureSuppression suppression, - KList pieces + KList pieces ) { StructurePlacement placement = placement("nativeSuppression", suppression); withAdded(placement, "structures", "test:city"); - IrisStructure structure = new IrisStructure(); - structure.setLoadKey("test:city"); + StructureStamp stamp = new StructureStamp(ObjectPlaceMode.STRUCTURE_PIECE, List.of(), List.of(), ""); return new IrisStructureLocator.ResolvedPlacement( - placement, "test:city", structure, pieces, new RNG(1L), 0, 64, 0, false); + placement, "test:city", stamp, pieces, new RNG(1L), 0, 64, 0, false); } private void assertReplacementFailure(Runnable operation, String expectedMessage) { diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructurePlacingOverboreTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructurePlacingOverboreTest.java index b84ff804d..36e415a91 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructurePlacingOverboreTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructurePlacingOverboreTest.java @@ -1,7 +1,11 @@ package art.arcane.iris.engine.mantle.components; +import com.volmit.placement.PlacementRecord; +import com.volmit.resource.ResourceId; import org.junit.Test; +import java.util.Optional; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -9,10 +13,11 @@ import static org.junit.Assert.assertTrue; public class StructurePlacingOverboreTest { @Test public void ordinaryMarkersAreSeparatedFromStructureMarkers() { - assertTrue(StructurePlacing.isOrdinaryObjectMarker("trees/oak@42")); - assertFalse(StructurePlacing.isOrdinaryObjectMarker( - "@iris-structure:v1:dHJlZXMvb2Fr:42:bWluZWNyYWZ0Om1hbnNpb24")); - assertFalse(StructurePlacing.isOrdinaryObjectMarker("not-a-marker")); + ResourceId oak = new ResourceId("test", "trees/oak"); + assertTrue(StructurePlacing.isOrdinaryObjectRecord(Optional.of(PlacementRecord.of(oak, 42)))); + assertFalse(StructurePlacing.isOrdinaryObjectRecord( + Optional.of(PlacementRecord.ofPiece(oak, 42, new ResourceId("minecraft", "mansion"))))); + assertFalse(StructurePlacing.isOrdinaryObjectRecord(Optional.empty())); } @Test diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/ApiChunk.java b/core/src/test/java/art/arcane/iris/engine/modifier/ApiChunk.java index 6150c235e..57c4f0003 100644 --- a/core/src/test/java/art/arcane/iris/engine/modifier/ApiChunk.java +++ b/core/src/test/java/art/arcane/iris/engine/modifier/ApiChunk.java @@ -690,6 +690,11 @@ public final class ApiChunk implements GenerationContext { return type.cast(known); } + @Override + public List services(Class service) { + return List.of(); + } + @Override public ModuleLog log() { return ModuleLogs.discarding(); diff --git a/core/src/test/java/art/arcane/iris/engine/object/structure/IrisStructureLootPlacementTest.java b/core/src/test/java/art/arcane/iris/engine/object/structure/IrisStructureLootPlacementTest.java index 5ee6bb2c5..e2a80948a 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/structure/IrisStructureLootPlacementTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/structure/IrisStructureLootPlacementTest.java @@ -2,9 +2,12 @@ package art.arcane.iris.engine.object.structure; import art.arcane.iris.engine.mantle.components.StructurePlacing; import art.arcane.iris.builtin.objects.ObjectPlacement; -import art.arcane.iris.engine.object.structure.IrisStructure; +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.engine.framework.structure.assembly.StructureStamp; import org.junit.Test; +import java.util.List; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -12,11 +15,10 @@ import static org.junit.Assert.assertTrue; public class IrisStructureLootPlacementTest { @Test public void createsPiecePlacementWithAuthoredLootOrderAndDefaultWeights() { - IrisStructure structure = new IrisStructure(); - structure.getLoot().add("village_common"); - structure.getLoot().add("village_rare"); + StructureStamp stamp = new StructureStamp(ObjectPlaceMode.STRUCTURE_PIECE, List.of(), + List.of("village_common", "village_rare"), ""); - ObjectPlacement placement = StructurePlacing.lootPlacement(structure, "pieces/village_house"); + ObjectPlacement placement = StructurePlacing.lootPlacement(stamp, "pieces/village_house"); assertEquals(1, placement.place().size()); assertEquals("pieces/village_house", placement.place().get(0)); @@ -32,7 +34,8 @@ public class IrisStructureLootPlacementTest { @Test public void createsEmptyLootPlacementWhenStructureHasNoLoot() { - ObjectPlacement placement = StructurePlacing.lootPlacement(new IrisStructure(), "pieces/empty_house"); + ObjectPlacement placement = StructurePlacing.lootPlacement( + new StructureStamp(ObjectPlaceMode.STRUCTURE_PIECE, List.of(), List.of(), ""), "pieces/empty_house"); assertEquals("pieces/empty_house", placement.place().get(0)); assertTrue(placement.loot().isEmpty()); diff --git a/core/src/test/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawModelMetadataTest.java b/core/src/test/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawModelMetadataTest.java index a44a46fde..e0e318b0d 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawModelMetadataTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawModelMetadataTest.java @@ -6,8 +6,8 @@ import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawCompatibility; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawMode; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; -import art.arcane.iris.engine.object.value.IrisPosition; import com.google.gson.Gson; +import com.volmit.geometry.BlockPosition; import org.junit.Test; import static org.junit.Assert.assertEquals; @@ -25,7 +25,7 @@ public class IrisJigsawModelMetadataTest { assertEquals(IrisJigsawCompatibility.IRIS_EXTENDED, structure.resolvedCompatibility()); assertEquals(IrisJigsawBranchFailurePolicy.FAIL_ASSEMBLY, structure.resolvedBranchFailurePolicy()); - assertEquals(new IrisPosition(15, 15, 15), structure.getCellSize()); + assertEquals(new BlockPosition(15, 15, 15), structure.getCellSize()); assertEquals("", connector.getChannel()); assertEquals("minecraft:air", connector.getFinalState()); assertEquals(0, connector.getSelectionPriority()); @@ -57,7 +57,7 @@ public class IrisJigsawModelMetadataTest { assertEquals(IrisJigsawCompatibility.IRIS_EXTENDED, structure.resolvedCompatibility()); assertEquals(IrisJigsawBranchFailurePolicy.FAIL_ASSEMBLY, structure.resolvedBranchFailurePolicy()); - assertEquals(new IrisPosition(15, 15, 15), structure.getCellSize()); + assertEquals(new BlockPosition(15, 15, 15), structure.getCellSize()); assertEquals("", connector.getChannel()); assertEquals("minecraft:air", connector.getFinalState()); assertEquals(0, connector.getSelectionPriority()); diff --git a/core/src/test/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawRulesModelTest.java b/core/src/test/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawRulesModelTest.java index 71b2b1e4d..ec8ff2ca5 100644 --- a/core/src/test/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawRulesModelTest.java +++ b/core/src/test/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawRulesModelTest.java @@ -6,13 +6,14 @@ import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceEntry; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceRules; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; import com.google.gson.Gson; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; import org.junit.Test; import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -117,18 +118,18 @@ public class IrisJigsawRulesModelTest { Field minimumPlacements = IrisJigsawPieceRules.class.getDeclaredField("minimumPlacements"); Field maximumPlacements = IrisJigsawPieceRules.class.getDeclaredField("maximumPlacements"); - ArrayType themeSetArray = themeSets.getAnnotation(ArrayType.class); - ArrayType themeArray = themes.getAnnotation(ArrayType.class); - assertNotNull(themeSetArray); - assertEquals(IrisJigsawThemeSet.class, themeSetArray.type()); - assertNotNull(themeArray); - assertEquals(String.class, themeArray.type()); + assertEquals(IrisJigsawThemeSet.class, elementTypeOf(themeSets)); + assertEquals(String.class, elementTypeOf(themes)); assertEquals(0D, chance.getAnnotation(MinNumber.class).value(), 0D); assertEquals(1D, chance.getAnnotation(MaxNumber.class).value(), 0D); assertEquals(0D, minimumPlacements.getAnnotation(MinNumber.class).value(), 0D); assertEquals(512D, maximumPlacements.getAnnotation(MaxNumber.class).value(), 0D); } + private static Type elementTypeOf(Field list) { + return ((ParameterizedType) list.getGenericType()).getActualTypeArguments()[0]; + } + @Test public void mandatoryPoolFallbackCombinesWithStructurePolicy() { IrisJigsawPool optional = new IrisJigsawPool(); diff --git a/core/src/test/java/art/arcane/iris/engine/platform/studio/TerrainChunkCanvasTest.java b/core/src/test/java/art/arcane/iris/engine/platform/studio/TerrainChunkCanvasTest.java new file mode 100644 index 000000000..d3fc4530d --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/platform/studio/TerrainChunkCanvasTest.java @@ -0,0 +1,125 @@ +package art.arcane.iris.engine.platform.studio; + +import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedBlockEntity; +import art.arcane.iris.engine.data.chunk.TerrainChunk; +import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.block.BlockState; +import com.volmit.object.BlockEntityData; +import com.volmit.resource.ResourceId; +import org.junit.Before; +import org.junit.Test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class TerrainChunkCanvasTest { + private static final int MIN_Y = -64; + private static final int MAX_Y = 320; + private static final BlockEntityData CHEST_DATA = + new BlockEntityData(ResourceId.parse("iris:tile"), 1, new byte[] {1, 2, 3}); + private static final BlockEntityData SIGN_DATA = + new BlockEntityData(ResourceId.parse("iris:tile"), 1, new byte[] {9}); + + private TerrainChunk chunk; + private final Map platformStates = new HashMap<>(); + private TerrainChunkCanvas canvas; + + @Before + public void anEmptyChunk() { + chunk = mock(TerrainChunk.class); + when(chunk.getMinHeight()).thenReturn(MIN_Y); + when(chunk.getMaxHeight()).thenReturn(MAX_Y); + canvas = new TerrainChunkCanvas(chunk, key -> platformStates.computeIfAbsent(key, ignored -> mock(PlatformBlockState.class))); + } + + @Test + public void theCanvasReportsTheHeightRangeOfTheChunk() { + assertEquals(MIN_Y, canvas.minY()); + assertEquals(MAX_Y, canvas.maxY()); + } + + @Test + public void aBlockGoesIntoTheChunkAsThePlatformsStateOfItsKey() { + canvas.set(3, 70, 12, BlockState.parse("minecraft:oak_log[axis=y]")); + + PlatformBlockState written = platformStates.get("minecraft:oak_log[axis=y]"); + verify(chunk).setBlock(3, 70, 12, written); + } + + @Test + public void thePlatformIsAskedOnceForAKeyAndItsAnswerIsReused() { + canvas.set(0, 0, 0, BlockState.parse("minecraft:stone")); + canvas.set(1, 0, 0, BlockState.parse("minecraft:stone")); + + PlatformBlockState stone = platformStates.get("minecraft:stone"); + verify(chunk).setBlock(0, 0, 0, stone); + verify(chunk).setBlock(1, 0, 0, stone); + assertEquals(1, platformStates.size()); + } + + @Test + public void positionsOutsideTheChunkOrTheWorldAreRefusedAndNothingIsWritten() { + BlockState stone = BlockState.parse("minecraft:stone"); + + assertThrows(IllegalArgumentException.class, () -> canvas.set(16, 0, 0, stone)); + assertThrows(IllegalArgumentException.class, () -> canvas.set(-1, 0, 0, stone)); + assertThrows(IllegalArgumentException.class, () -> canvas.set(0, 0, 16, stone)); + assertThrows(IllegalArgumentException.class, () -> canvas.set(0, MIN_Y - 1, 0, stone)); + assertThrows(IllegalArgumentException.class, () -> canvas.set(0, MAX_Y, 0, stone)); + verify(chunk, never()).setBlock(anyInt(), anyInt(), anyInt(), any()); + } + + @Test + public void theLowestAndHighestBlocksOfTheWorldAreInside() { + canvas.set(0, MIN_Y, 0, BlockState.parse("minecraft:bedrock")); + canvas.set(15, MAX_Y - 1, 15, BlockState.parse("minecraft:glass")); + + verify(chunk).setBlock(0, MIN_Y, 0, platformStates.get("minecraft:bedrock")); + verify(chunk).setBlock(15, MAX_Y - 1, 15, platformStates.get("minecraft:glass")); + } + + @Test + public void blockEntitiesAreKeptInPaintOrderWithTheirPositions() { + canvas.set(1, 64, 2, BlockState.parse("minecraft:chest"), CHEST_DATA); + canvas.set(4, 65, 5, BlockState.parse("minecraft:oak_sign"), SIGN_DATA); + + assertEquals(List.of(new PaintedBlockEntity(1, 64, 2, CHEST_DATA), new PaintedBlockEntity(4, 65, 5, SIGN_DATA)), + canvas.blockEntities()); + } + + @Test + public void paintingAnotherBlockOverABlockEntityDropsTheEntity() { + canvas.set(1, 64, 2, BlockState.parse("minecraft:chest"), CHEST_DATA); + canvas.set(1, 64, 2, BlockState.parse("minecraft:stone")); + + assertTrue(canvas.blockEntities().isEmpty()); + } + + @Test + public void paintingTwoEntitiesAtOnePositionKeepsTheLaterOne() { + canvas.set(1, 64, 2, BlockState.parse("minecraft:chest"), CHEST_DATA); + canvas.set(1, 64, 2, BlockState.parse("minecraft:chest"), SIGN_DATA); + + assertEquals(List.of(new PaintedBlockEntity(1, 64, 2, SIGN_DATA)), canvas.blockEntities()); + } + + @Test + public void aStateThePlatformLacksFailsThePaint() { + TerrainChunkCanvas strict = new TerrainChunkCanvas(chunk, key -> { + throw new IllegalArgumentException("no " + key); + }); + + assertThrows(IllegalArgumentException.class, () -> strict.set(0, 0, 0, BlockState.parse("example:nothing"))); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/platform/studio/generators/JigsawStudioGeneratorTest.java b/core/src/test/java/art/arcane/iris/engine/platform/studio/generators/JigsawStudioGeneratorTest.java index 36fa86025..02d2946d1 100644 --- a/core/src/test/java/art/arcane/iris/engine/platform/studio/generators/JigsawStudioGeneratorTest.java +++ b/core/src/test/java/art/arcane/iris/engine/platform/studio/generators/JigsawStudioGeneratorTest.java @@ -1,13 +1,9 @@ package art.arcane.iris.engine.platform.studio.generators; import art.arcane.iris.engine.framework.structure.StructureResources; -import art.arcane.iris.core.modules.ModuleResourceFixture; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.loader.ResourceLoader; import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarArchetype; import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarDirection; import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarTopology; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioActivation; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBay; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget; @@ -18,59 +14,56 @@ import art.arcane.iris.core.runtime.jigsaw.JigsawStudioPieceRules; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioSession; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariant; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariantCatalog; -import art.arcane.iris.engine.data.chunk.TerrainChunk; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.core.service.JigsawStudioRequest; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.ObjectTurn; -import art.arcane.iris.engine.object.value.IrisPosition; +import art.arcane.iris.engine.framework.structure.assembly.PieceTurn; import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint; -import art.arcane.iris.engine.object.prefab.TileData; -import art.arcane.iris.spi.PlatformBiome; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.collection.KMap; -import org.bukkit.block.data.BlockData; -import org.bukkit.generator.ChunkGenerator.ChunkData; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockBox; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import com.volmit.object.GeneratedObject; +import com.volmit.object.ObjectBlock; +import com.volmit.object.PackObjects; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.ToolPack; +import com.volmit.tooling.world.ChunkCanvas; import org.junit.Test; -import org.mockito.MockedStatic; +import java.nio.file.Path; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; public class JigsawStudioGeneratorTest { + private static final String PACK_NAMESPACE = "test"; + @Test - @SuppressWarnings("unchecked") public void connectorBlocksAreHiddenByDefaultAndCanBeShownPerWorkcell() { - IrisData source = mock(IrisData.class); - ResourceLoader objectLoader = mock(ResourceLoader.class); - ModuleResourceFixture resources = ModuleResourceFixture.serve(source); - when(source.getObjectLoader()).thenReturn(objectLoader); + PackFixture pack = new PackFixture(); IrisJigsawConnector connector = new IrisJigsawConnector() - .setPosition(new IrisPosition(1, 1, 1)) - .setDirection(IrisDirection.NORTH_NEGATIVE_Z) - .setTop(IrisDirection.UP_POSITIVE_Y) + .setPosition(new BlockPosition(1, 1, 1)) + .setDirection(JigsawDirection.NORTH_NEGATIVE_Z) + .setTop(JigsawDirection.UP_POSITIVE_Y) .setPool("test/start") .setName("door") .setTargetName("door") @@ -80,11 +73,9 @@ public class JigsawStudioGeneratorTest { .setObject("test/room") .setConnectors(new KList<>()); piece.getConnectors().add(connector); - PlatformBlockState stone = mock(PlatformBlockState.class); - IrisObject object = new IrisObject(3, 3, 3); - object.setUnsigned(1, 1, 1, stone); - resources.resource(StructureResources.PIECES, "test/room", piece); - when(objectLoader.load("test/room", false)).thenReturn(object); + BlockState stone = BlockState.parse("minecraft:stone"); + pack.piece("test/room", piece); + pack.object("test/room", object(3, 3, 3, new PlacedBlock(1, 1, 1, stone, null))); JigsawStudioVariant variant = new JigsawStudioVariant( "test/room", "test/room", @@ -98,7 +89,7 @@ public class JigsawStudioGeneratorTest { new JigsawStudioPieceRules(0, 30, 0, 0, false), List.of()); GeneratorFixture fixture = fixture( - source, + pack, JigsawStudioMode.SPATIAL_JIGSAW, new JigsawStudioCellDimensions(3, 3, 3), new JigsawStudioVariantCatalog(List.of(variant))); @@ -111,52 +102,10 @@ public class JigsawStudioGeneratorTest { workcell.stableId()).connectorsVisible()); assertSame(stone, stateAt(fixture.generator(), worldX, worldY, worldZ)); - PlatformBlockState marker = mock(PlatformBlockState.class); + BlockState marker = BlockState.parse("minecraft:jigsaw[orientation=north_up]"); + when(pack.blocks.find("minecraft:jigsaw[orientation=north_up]")).thenReturn(Optional.of(marker)); fixture.generator().getSession().setConnectorsVisible(workcell.stableId(), true); - try (MockedStatic blocks = mockStatic(B.class)) { - blocks.when(() -> B.getState("minecraft:jigsaw[orientation=north_up]")).thenReturn(marker); - assertSame(marker, stateAt(fixture.generator(), worldX, worldY, worldZ)); - } - } - - @Test - public void serviceRegistrationIsPublishedAfterTheRegistrationFinishes() throws Exception { - GeneratorFixture fixture = fixture( - JigsawStudioMode.PLANAR_JIGSAW, - new JigsawStudioCellDimensions(3, 3, 3), - JigsawStudioVariantCatalog.empty()); - CountDownLatch registrationStarted = new CountDownLatch(1); - CountDownLatch releaseRegistration = new CountDownLatch(1); - CountDownLatch secondStarted = new CountDownLatch(1); - CountDownLatch secondFinished = new CountDownLatch(1); - AtomicInteger registrations = new AtomicInteger(); - ExecutorService executor = Executors.newFixedThreadPool(2); - try { - Future first = executor.submit(() -> fixture.generator().publishServiceRegistration(() -> { - registrations.incrementAndGet(); - registrationStarted.countDown(); - await(releaseRegistration); - })); - assertTrue(registrationStarted.await(5, TimeUnit.SECONDS)); - Future second = executor.submit(() -> { - secondStarted.countDown(); - fixture.generator().publishServiceRegistration(registrations::incrementAndGet); - secondFinished.countDown(); - }); - assertTrue(secondStarted.await(5, TimeUnit.SECONDS)); - assertFalse(secondFinished.await(250, TimeUnit.MILLISECONDS)); - - releaseRegistration.countDown(); - first.get(5, TimeUnit.SECONDS); - second.get(5, TimeUnit.SECONDS); - - assertEquals(1, registrations.get()); - assertEquals(0L, secondFinished.getCount()); - } finally { - releaseRegistration.countDown(); - executor.shutdownNow(); - assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS)); - } + assertSame(marker, stateAt(fixture.generator(), worldX, worldY, worldZ)); } @Test @@ -319,7 +268,7 @@ public class JigsawStudioGeneratorTest { JigsawStudioBay cross = fixture.layout().get("workcell/cross"); int chunkX = (cross.bounds().originX() + 32) >> 4; int chunkZ = (cross.bounds().originZ() + 32) >> 4; - RecordingTerrainChunk chunk = new RecordingTerrainChunk(-64, 320); + RecordingCanvas chunk = new RecordingCanvas(-64, 320); fixture.generator().paintChunk(chunk, chunkX, chunkZ); @@ -330,16 +279,12 @@ public class JigsawStudioGeneratorTest { } @Test - @SuppressWarnings("unchecked") public void rendersSourceVariantInCanonicalOrientationAndRotatesFinalState() { - IrisData source = mock(IrisData.class); - ResourceLoader objectLoader = mock(ResourceLoader.class); - ModuleResourceFixture resources = ModuleResourceFixture.serve(source); - when(source.getObjectLoader()).thenReturn(objectLoader); + PackFixture pack = new PackFixture(); IrisJigsawConnector connector = new IrisJigsawConnector() - .setPosition(new IrisPosition(2, 1, 1)) - .setDirection(IrisDirection.EAST_POSITIVE_X) - .setTop(IrisDirection.UP_POSITIVE_Y) + .setPosition(new BlockPosition(2, 1, 1)) + .setDirection(JigsawDirection.EAST_POSITIVE_X) + .setTop(JigsawDirection.UP_POSITIVE_Y) .setPool("village/start") .setName("door") .setTargetName("door") @@ -349,19 +294,13 @@ public class JigsawStudioGeneratorTest { .setObject("village/east") .setConnectors(new KList<>()); piece.getConnectors().add(connector); - IrisObject object = new IrisObject(3, 3, 3); - PlatformBlockState sourceBlock = mock(PlatformBlockState.class); - when(sourceBlock.nativeHandle()).thenReturn(mock(BlockData.class)); - KMap tileProperties = new KMap<>(); - tileProperties.put("CustomName", "QA Chest"); - TileData sourceTile = new TileData("minecraft:chest", tileProperties); - object.setUnsigned(0, 0, 0, sourceBlock); - object.setUnsignedTile(0, 0, 0, sourceTile); - resources.resource(StructureResources.PIECES, "village/east", piece); - when(objectLoader.load("village/east", false)).thenReturn(object); + BlockState sourceBlock = BlockState.parse("minecraft:chest"); + BlockEntityData sourceTile = new BlockEntityData(new ResourceId("iris", "tile"), 1, new byte[]{1, 2, 3}); + pack.piece("village/east", piece); + pack.object("village/east", object(3, 3, 3, new PlacedBlock(0, 0, 0, sourceBlock, sourceTile))); JigsawStudioVariant variant = planarVariant("village/east", JigsawPlanarTopology.EAST_END); GeneratorFixture fixture = fixture( - source, + pack, JigsawStudioMode.PLANAR_JIGSAW, new JigsawStudioCellDimensions(3, 3, 3), new JigsawStudioVariantCatalog(List.of(variant))); @@ -373,25 +312,20 @@ public class JigsawStudioGeneratorTest { JigsawStudioGenerator.RenderedConnector rotated = rendered.connectors().getFirst(); assertEquals(1, rotated.x()); assertEquals(0, rotated.z()); - assertEquals(IrisDirection.NORTH_NEGATIVE_Z, rotated.connector().getDirection()); + assertEquals(JigsawDirection.NORTH_NEGATIVE_Z, rotated.connector().getDirection()); assertEquals("north_up", rotated.orientation()); assertTrue(rotated.connector().getFinalState().contains("facing=north")); JigsawStudioGenerator.RenderedBlock rotatedBlock = rendered.blocks().getFirst(); - assertEquals(sourceTile, rotatedBlock.tileData()); - assertNotSame(sourceTile, rotatedBlock.tileData()); + assertEquals(sourceTile, rotatedBlock.blockEntity()); } @Test - @SuppressWarnings("unchecked") public void invalidRotatedFinalStateFailsRenderPrecisely() { - IrisData source = mock(IrisData.class); - ResourceLoader objectLoader = mock(ResourceLoader.class); - ModuleResourceFixture resources = ModuleResourceFixture.serve(source); - when(source.getObjectLoader()).thenReturn(objectLoader); + PackFixture pack = new PackFixture(); IrisJigsawConnector connector = new IrisJigsawConnector() - .setPosition(new IrisPosition(2, 1, 1)) - .setDirection(IrisDirection.EAST_POSITIVE_X) - .setTop(IrisDirection.UP_POSITIVE_Y) + .setPosition(new BlockPosition(2, 1, 1)) + .setDirection(JigsawDirection.EAST_POSITIVE_X) + .setTop(JigsawDirection.UP_POSITIVE_Y) .setPool("village/start") .setName("door") .setTargetName("door") @@ -401,11 +335,11 @@ public class JigsawStudioGeneratorTest { .setObject("village/east") .setConnectors(new KList<>()); piece.getConnectors().add(connector); - resources.resource(StructureResources.PIECES, "village/east", piece); - when(objectLoader.load("village/east", false)).thenReturn(new IrisObject(3, 3, 3)); + pack.piece("village/east", piece); + pack.object("village/east", object(3, 3, 3)); JigsawStudioVariant variant = planarVariant("village/east", JigsawPlanarTopology.EAST_END); GeneratorFixture fixture = fixture( - source, + pack, JigsawStudioMode.PLANAR_JIGSAW, new JigsawStudioCellDimensions(3, 3, 3), new JigsawStudioVariantCatalog(List.of(variant))); @@ -418,17 +352,13 @@ public class JigsawStudioGeneratorTest { } @Test - @SuppressWarnings("unchecked") public void renderCacheIncludesLoadGenerationAndSupportsExplicitInvalidation() { - IrisData source = mock(IrisData.class); - ResourceLoader objectLoader = mock(ResourceLoader.class); - ModuleResourceFixture resources = ModuleResourceFixture.serve(source); - when(source.getObjectLoader()).thenReturn(objectLoader); + PackFixture pack = new PackFixture(); IrisJigsawPiece piece = new IrisJigsawPiece() .setObject("stronghold/hall") .setConnectors(new KList<>()); - resources.resource(StructureResources.PIECES, "stronghold/hall", piece); - when(objectLoader.load("stronghold/hall", false)).thenReturn(new IrisObject(3, 3, 3)); + pack.piece("stronghold/hall", piece); + pack.object("stronghold/hall", object(3, 3, 3)); JigsawStudioVariant variant = new JigsawStudioVariant( "stronghold/hall", "stronghold/hall", @@ -442,7 +372,7 @@ public class JigsawStudioGeneratorTest { new JigsawStudioPieceRules(0, 30, 0, 0, false), List.of()); GeneratorFixture fixture = fixture( - source, + pack, JigsawStudioMode.SPATIAL_JIGSAW, new JigsawStudioCellDimensions(3, 3, 3), new JigsawStudioVariantCatalog(List.of(variant))); @@ -459,14 +389,14 @@ public class JigsawStudioGeneratorTest { @Test public void mapsAllVanillaJigsawOrientations() { assertEquals("north_up", JigsawStudioGenerator.orientation( - IrisDirection.NORTH_NEGATIVE_Z, IrisDirection.UP_POSITIVE_Y)); + JigsawDirection.NORTH_NEGATIVE_Z, JigsawDirection.UP_POSITIVE_Y)); assertEquals("up_east", JigsawStudioGenerator.orientation( - IrisDirection.UP_POSITIVE_Y, IrisDirection.EAST_POSITIVE_X)); + JigsawDirection.UP_POSITIVE_Y, JigsawDirection.EAST_POSITIVE_X)); assertEquals("down_west", JigsawStudioGenerator.orientation( - IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.WEST_NEGATIVE_X)); + JigsawDirection.DOWN_NEGATIVE_Y, JigsawDirection.WEST_NEGATIVE_X)); } - private static PlatformBlockState stateAt( + private static BlockState stateAt( JigsawStudioGenerator generator, int worldX, int worldY, @@ -474,20 +404,9 @@ public class JigsawStudioGeneratorTest { ) { int chunkX = worldX >> 4; int chunkZ = worldZ >> 4; - RecordingTerrainChunk chunk = new RecordingTerrainChunk(-64, 320); + RecordingCanvas chunk = new RecordingCanvas(-64, 320); generator.paintChunk(chunk, chunkX, chunkZ); - return chunk.getBlockData(worldX - (chunkX << 4), worldY, worldZ - (chunkZ << 4)); - } - - private static void await(CountDownLatch latch) { - try { - if (!latch.await(5, TimeUnit.SECONDS)) { - throw new IllegalStateException("Timed out waiting for Jigsaw Studio registration"); - } - } catch (InterruptedException exception) { - Thread.currentThread().interrupt(); - throw new IllegalStateException("Interrupted while waiting for Jigsaw Studio registration", exception); - } + return chunk.blockAt(worldX - (chunkX << 4), worldY, worldZ - (chunkZ << 4)); } private static GeneratorFixture fixture( @@ -495,42 +414,42 @@ public class JigsawStudioGeneratorTest { JigsawStudioCellDimensions dimensions, JigsawStudioVariantCatalog catalog ) { - return fixture(mock(IrisData.class), mode, dimensions, catalog); + return fixture(new PackFixture(), mode, dimensions, catalog); } private static GeneratorFixture fixture( - IrisData source, + PackFixture pack, JigsawStudioMode mode, JigsawStudioCellDimensions dimensions, JigsawStudioVariantCatalog catalog ) { - Engine engine = mock(Engine.class); UUID requestId = UUID.randomUUID(); JigsawStudioLayout layout = JigsawStudioLayout.create(mode, dimensions, catalog); - JigsawStudioActivation.Request request = new JigsawStudioActivation.Request( + JigsawStudioRequest request = new JigsawStudioRequest( requestId, "overworld", "test/structure", mode, JigsawStudioCompatibilityTarget.IRIS_EXTENDED, dimensions, - source, + pack.pack, + Path.of("pack"), null); JigsawStudioSession session = new JigsawStudioSession( requestId, "overworld", "test/structure", layout); - PlatformBlockState lightFloor = mock(PlatformBlockState.class); - PlatformBlockState darkFloor = mock(PlatformBlockState.class); - PlatformBlockState frame = mock(PlatformBlockState.class); - PlatformBlockState topologyBase = mock(PlatformBlockState.class); - PlatformBlockState topologyPath = mock(PlatformBlockState.class); - PlatformBlockState connectorCap = mock(PlatformBlockState.class); - PlatformBlockState invalidMarker = mock(PlatformBlockState.class); - PlatformBlockState controlChest = mock(PlatformBlockState.class); + BlockState lightFloor = BlockState.parse("minecraft:smooth_stone"); + BlockState darkFloor = BlockState.parse("minecraft:polished_deepslate"); + BlockState frame = BlockState.parse("minecraft:white_concrete"); + BlockState topologyBase = BlockState.parse("minecraft:light_gray_wool"); + BlockState topologyPath = BlockState.parse("minecraft:red_wool"); + BlockState connectorCap = BlockState.parse("minecraft:sea_lantern"); + BlockState invalidMarker = BlockState.parse("minecraft:red_stained_glass"); + BlockState controlChest = BlockState.parse("minecraft:chest[facing=south,type=single,waterlogged=false]"); JigsawStudioGenerator generator = new JigsawStudioGenerator( - engine, + pack.pack, request, session, lightFloor, @@ -569,7 +488,7 @@ public class JigsawStudioGeneratorTest { private static String renderFinalState( String finalState, - ObjectTurn rotation, + PieceTurn rotation, int quarterTurns ) { if (finalState.equals("minecraft:not_a_real_block")) { @@ -581,83 +500,113 @@ public class JigsawStudioGeneratorTest { return finalState; } + private static TestObject object(int width, int height, int depth, PlacedBlock... placed) { + BlockPosition center = new BlockPosition(width / 2, height / 2, depth / 2); + List blocks = new ArrayList<>(); + for (PlacedBlock block : placed) { + blocks.add(new ObjectBlock( + new BlockPosition(block.x() - center.x(), block.y() - center.y(), block.z() - center.z()), + block.state(), + Optional.ofNullable(block.blockEntity()))); + } + BlockBox bounds = new BlockBox( + -center.x(), -center.y(), -center.z(), + width - center.x(), height - center.y(), depth - center.z()); + GeneratedObject geometry = new GeneratedObject(bounds, new BlockPosition(0, 0, 0), blocks, List.of()); + return new TestObject(width, height, depth, center, geometry); + } + + /** A block at its coordinates inside the object, counted from the object's own corner. */ + private record PlacedBlock(int x, int y, int z, BlockState state, BlockEntityData blockEntity) { + } + + private record TestObject(int width, int height, int depth, BlockPosition center, GeneratedObject geometry) + implements PlaceableObject { + @Override + public String name() { + return "test-object"; + } + } + + /** A pack whose pieces and objects a test sets by key, and whose block registry knows every block. */ + private static final class PackFixture { + final ToolPack pack = mock(ToolPack.class); + final PackResources resources = mock(PackResources.class); + final PackObjects objects = mock(PackObjects.class); + final BlockRegistry blocks = mock(BlockRegistry.class); + + PackFixture() { + when(pack.resources()).thenReturn(resources); + when(resources.objects()).thenReturn(objects); + when(resources.blocks()).thenReturn(blocks); + when(resources.idOf(anyString())).thenAnswer(invocation -> idOf(invocation.getArgument(0))); + when(blocks.find(anyString())).thenAnswer(invocation -> + Optional.of(BlockState.parse(invocation.getArgument(0)))); + when(blocks.rotate(any(), any())).thenAnswer(invocation -> invocation.getArgument(0)); + when(blocks.tryRotate(any(), any())).thenAnswer(invocation -> Optional.of(invocation.getArgument(0))); + } + + void piece(String key, IrisJigsawPiece piece) { + when(resources.find(StructureResources.PIECES, idOf(key))).thenReturn(Optional.of(piece)); + } + + void object(String key, PlaceableObject object) { + when(objects.object(idOf(key))).thenReturn(Optional.of(object)); + } + + private static ResourceId idOf(String key) { + return ResourceId.ofPackKey(PACK_NAMESPACE, key); + } + } + private record GeneratorFixture( JigsawStudioGenerator generator, JigsawStudioLayout layout, - PlatformBlockState frame, - PlatformBlockState topologyBase, - PlatformBlockState topologyPath, - PlatformBlockState connectorCap, - PlatformBlockState controlChest + BlockState frame, + BlockState topologyBase, + BlockState topologyPath, + BlockState connectorCap, + BlockState controlChest ) { } - private static final class RecordingTerrainChunk implements TerrainChunk { - private final int minHeight; - private final int maxHeight; - private final Map blocks = new HashMap<>(); + private static final class RecordingCanvas implements ChunkCanvas { + private final int minY; + private final int maxY; + private final Map blocks = new HashMap<>(); - private RecordingTerrainChunk(int minHeight, int maxHeight) { - this.minHeight = minHeight; - this.maxHeight = maxHeight; + private RecordingCanvas(int minY, int maxY) { + this.minY = minY; + this.maxY = maxY; } @Override - public PlatformBiome getBiome(int x, int y, int z) { - return null; + public int minY() { + return minY; } @Override - public void setBiome(int x, int y, int z, PlatformBiome biome) { + public int maxY() { + return maxY; } @Override - public int getMinHeight() { - return minHeight; + public void set(int x, int y, int z, BlockState state) { + blocks.put(key(x, y, z), state); } @Override - public int getMaxHeight() { - return maxHeight; + public void set(int x, int y, int z, BlockState state, BlockEntityData data) { + set(x, y, z, state); } - @Override - public void setBlock(int x, int y, int z, PlatformBlockState blockData) { - blocks.put(key(x, y, z), blockData); - } - - @Override - public void setRegion( - int xMin, - int yMin, - int zMin, - int xMax, - int yMax, - int zMax, - PlatformBlockState blockData - ) { - for (int x = xMin; x < xMax; x++) { - for (int y = yMin; y < yMax; y++) { - for (int z = zMin; z < zMax; z++) { - setBlock(x, y, z, blockData); - } - } - } - } - - @Override - public PlatformBlockState getBlockData(int x, int y, int z) { + private BlockState blockAt(int x, int y, int z) { return blocks.get(key(x, y, z)); } - @Override - public ChunkData getChunkData() { - return null; - } - - private int countState(PlatformBlockState state) { + private int countState(BlockState state) { int count = 0; - for (PlatformBlockState block : blocks.values()) { + for (BlockState block : blocks.values()) { if (block == state) { count++; } diff --git a/core/src/test/java/art/arcane/iris/engine/platform/studio/generators/PainterStudioGeneratorTest.java b/core/src/test/java/art/arcane/iris/engine/platform/studio/generators/PainterStudioGeneratorTest.java new file mode 100644 index 000000000..120469ee3 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/platform/studio/generators/PainterStudioGeneratorTest.java @@ -0,0 +1,85 @@ +package art.arcane.iris.engine.platform.studio.generators; + +import art.arcane.iris.core.runtime.StudioPainterSlots; +import art.arcane.iris.engine.data.chunk.TerrainChunk; +import art.arcane.iris.engine.platform.studio.TerrainChunkCanvas; +import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.block.BlockState; +import com.volmit.object.BlockEntityData; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.world.ChunkPainter; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class PainterStudioGeneratorTest { + private static final BlockEntityData CHEST_DATA = + new BlockEntityData(ResourceId.parse("iris:tile"), 1, new byte[] {1}); + + private TerrainChunk chunk; + private final List sunk = new ArrayList<>(); + + @Before + public void anEmptyChunk() { + chunk = mock(TerrainChunk.class); + when(chunk.getMinHeight()).thenReturn(0); + when(chunk.getMaxHeight()).thenReturn(256); + } + + private PainterStudioGenerator generatorPainting(ChunkPainter painter) { + StudioPainterSlots.Slot slot = new StudioPainterSlots.Slot(painter, sunk::add); + return new PainterStudioGenerator(slot, terrain -> new TerrainChunkCanvas(terrain, key -> mock(PlatformBlockState.class))); + } + + @Test + public void theChunkIsWhatThePainterPaintsForThatChunkPosition() { + List asked = new ArrayList<>(); + PainterStudioGenerator generator = generatorPainting((chunkX, chunkZ, canvas) -> { + asked.add(new int[] {chunkX, chunkZ}); + canvas.set(0, 5, 0, BlockState.parse("minecraft:stone")); + }); + + generator.paint(chunk, 3, -4); + + assertEquals(1, asked.size()); + assertEquals(3, asked.get(0)[0]); + assertEquals(-4, asked.get(0)[1]); + verify(chunk).setBlock(eq(0), eq(5), eq(0), any()); + assertTrue("no block entities were painted", sunk.isEmpty()); + } + + @Test + public void blockEntitiesGoToTheSlotWithTheChunkTheyBelongTo() { + PainterStudioGenerator generator = generatorPainting((chunkX, chunkZ, canvas) -> + canvas.set(1, 64, 2, BlockState.parse("minecraft:chest"), CHEST_DATA)); + + generator.paint(chunk, 7, 8); + + assertEquals(1, sunk.size()); + assertEquals(7, sunk.get(0).chunkX()); + assertEquals(8, sunk.get(0).chunkZ()); + assertEquals(List.of(new StudioPainterSlots.PaintedBlockEntity(1, 64, 2, CHEST_DATA)), sunk.get(0).blockEntities()); + } + + @Test + public void aPainterThatThrowsLeavesTheChunkAsFarAsItGotAndDoesNotFailTheGeneration() { + PainterStudioGenerator generator = generatorPainting((chunkX, chunkZ, canvas) -> { + canvas.set(0, 5, 0, BlockState.parse("minecraft:stone")); + throw new IllegalStateException("painter bug"); + }); + + generator.paint(chunk, 0, 0); + + verify(chunk).setBlock(eq(0), eq(5), eq(0), any()); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/terrain/TestLayerBlocks.java b/core/src/test/java/art/arcane/iris/engine/terrain/TestLayerBlocks.java index d5a45d98f..0023ccca8 100644 --- a/core/src/test/java/art/arcane/iris/engine/terrain/TestLayerBlocks.java +++ b/core/src/test/java/art/arcane/iris/engine/terrain/TestLayerBlocks.java @@ -30,6 +30,7 @@ import com.volmit.world.PackWorld; import com.volmit.world.RunningWorld; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; @@ -85,6 +86,11 @@ public final class TestLayerBlocks { return type.cast(states.computeIfAbsent(type, ignored -> create.apply(this))); } + @Override + public List services(Class service) { + return List.of(); + } + @Override public ModuleLog log() { return ModuleLogs.discarding(); diff --git a/core/src/test/java/art/arcane/iris/engine/terrain/TestPackWorld.java b/core/src/test/java/art/arcane/iris/engine/terrain/TestPackWorld.java index 44a0bc106..29ac31a9b 100644 --- a/core/src/test/java/art/arcane/iris/engine/terrain/TestPackWorld.java +++ b/core/src/test/java/art/arcane/iris/engine/terrain/TestPackWorld.java @@ -114,6 +114,11 @@ public final class TestPackWorld implements PackWorld { return type.cast(states.computeIfAbsent(type, ignored -> create.apply(this))); } + @Override + public List services(Class service) { + return List.of(); + } + @Override public ModuleLog log() { return ModuleLogs.discarding(); diff --git a/core/src/test/java/art/arcane/iris/util/common/director/specialhandlers/StructureHandlerTest.java b/core/src/test/java/art/arcane/iris/util/common/director/specialhandlers/StructureHandlerTest.java index 34671a9c6..c855fe63e 100644 --- a/core/src/test/java/art/arcane/iris/util/common/director/specialhandlers/StructureHandlerTest.java +++ b/core/src/test/java/art/arcane/iris/util/common/director/specialhandlers/StructureHandlerTest.java @@ -4,7 +4,7 @@ import art.arcane.iris.builtin.structure.StructureSettings; import art.arcane.iris.core.modules.BuiltInPack; import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.core.modules.ModuleResourceFixture; -import art.arcane.iris.core.modules.StructureModelModule; +import art.arcane.iris.modules.jigsaw.JigsawModule; import art.arcane.iris.engine.mantle.components.StructureModule; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.Engine; @@ -104,14 +104,12 @@ public class StructureHandlerTest { placements.add(editablePlacement("iris:collision_definition")); IrisStructure custom = new IrisStructure(); - custom.setLoadKey("iris:custom"); IrisStructure collision = new IrisStructure(); - collision.setLoadKey("pack:collision"); - ModuleResourceFixture.serveModules(data, new StructureModelModule(), new StructureModule()); + ModuleResourceFixture.serveModules(data, new JigsawModule(), new StructureModule()); ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "iris:custom_definition", custom); ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "iris:collision_definition", collision); when(engine.getData()).thenReturn(data); - ModuleResourceFixture.serveModules(data, new StructureModelModule(), new StructureModule()); + ModuleResourceFixture.serveModules(data, new JigsawModule(), new StructureModule()); when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); when(engine.getDimension()).thenReturn(dimension); when(engine.getWorld()).thenReturn(world); @@ -168,20 +166,18 @@ public class StructureHandlerTest { StructureSettings settings = new StructureSettings(List.of("minecraft:replacement"), List.of(), 0, true, List.of(), List.of()); IrisStructure editable = new IrisStructure(); - editable.setLoadKey("iris:editable"); IrisStructure replacement = new IrisStructure(); - replacement.setLoadKey("iris:replacement"); replacement.setVanillaSource("minecraft:replacement"); KList placements = new KList<>(); placements.add(editablePlacement("iris:editable_definition")); placements.add(editablePlacement("iris:replacement_definition")); placements.add(nativePlacement("minecraft:explicit", StructureDistribution.RANDOM_SPREAD, 1.0)); - ModuleResourceFixture.serveModules(data, new StructureModelModule(), new StructureModule()); + ModuleResourceFixture.serveModules(data, new JigsawModule(), new StructureModule()); ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "iris:editable_definition", editable); ModuleResourceFixture.of(data).resource(StructureResources.STRUCTURES, "iris:replacement_definition", replacement); when(engine.getData()).thenReturn(data); - ModuleResourceFixture.serveModules(data, new StructureModelModule(), new StructureModule()); + ModuleResourceFixture.serveModules(data, new JigsawModule(), new StructureModule()); when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); when(engine.getDimension()).thenReturn(dimension); when(engine.getWorld()).thenReturn(world); @@ -205,9 +201,7 @@ public class StructureHandlerTest { assertEquals(Set.of( "minecraft:replacement", "iris:editable_definition", - "iris:editable", - "iris:replacement_definition", - "iris:replacement"), possibilities); + "iris:replacement_definition"), possibilities); assertFalse(possibilities.contains("minecraft:explicit")); assertFalse(possibilities.contains("minecraft:reachable")); } finally { diff --git a/module/README.md b/module/README.md index 111f9cbe8..926f1e29f 100644 --- a/module/README.md +++ b/module/README.md @@ -29,24 +29,24 @@ service or hook, `setup.log()` during setup), which labels each line with the mo use `IrisLogging`. Classes of the host's object model (the host-classes list) and code that only has an engine or pack data still log as Iris itself. -Modules also own pack resources and checks of their own. `iris:structure` (`StructureModule`) reads structures, jigsaw -pools and jigsaw pieces as resource kinds (`StructureResources`, `iris:structure/structure`, `/pool`, `/piece`), from the -folders and files packs have always used, and declares the structure placement settings and the mantle stage. Its -definitions (`IrisStructure`, `IrisJigsawPiece`, `IrisJigsawPool` and their parts in `engine/object/structure`) live -here and build against the API. It is not in the built-ins jar: Iris registers it with its own modules, because Iris's -jigsaw studio, importers and exporters read the structures it registers as the same classes, which a jar's own copy of -a class is not. Iris's own module `iris:structure-model` (core `StructureModelModule`) checks them with its validator -(`StructureValidator`: assembly samples and vanilla structure replacement) wherever Iris validates a pack. The -assembler, locator, fitting and placing are still Iris's, and `iris:structure` places through the `StructureHost` -facade (`art.arcane.iris.builtin.structure`). +Structures are two modules of the built-ins jar. `iris:structure` (`StructureModule`) is where structures go and how they +meet the terrain: it declares the structure placement settings and the mantle stage, validates the placements +(`StructureValidator`), provides `StructureLocator` and `VanillaStructures`, and brings the `/iris module structure` +commands. It gets the pieces of a structure only from the `StructureAssembly` providers of the pack's modules and knows +none of them. `iris:jigsaw` (`JigsawModule`) is what a structure is made of: it reads structures, jigsaw pools and jigsaw +pieces as resource kinds (`StructureResources`, from the folders and files packs have always used), validates them +(`JigsawValidator`), provides `StructureAssembly` (`JigsawStructureAssembly`), and brings the tools that make them: the +importers of the platform's structures and of a datapack's (`DatapackStructureImport`) and the `/iris module jigsaw` +commands with the in-world Jigsaw Studio. The studio runs only on IrisApi's tool world api and `PlatformStructures`, so +it runs on every platform that implements them. Built-in modules answer Iris through IrisApi services instead of Iris reading their features: `iris:objects` -provides `ObjectsAt` (the objects a chunk would get, for the object search and studio tools) and `iris:structure-model` +provides `ObjectsAt` (the objects a chunk would get, for the object search and studio tools) and `iris:structure` provides `StructureLocator` (`StructureLocating`: the pack's structure keys for Iris's structure index, the ones a world places, and their nearest start for the find commands). A world's structure index lives in the world's state (`engine.getGeneration().state(...)`), so every reload of the pack's structure files, which starts a new world, builds it again. -`iris:structure-model` also provides `VanillaStructures` (`StructureVanillaStructures`) for the platform's own structures: +`iris:structure` also provides `VanillaStructures` (`StructureVanillaStructures`) for the platform's own structures: which ones its placements replace or the dimension's `importedStructures` disables, the starts its `nativeStructures` placements make (`startedStructures`, `locatableStarts`, `locateStart`), the shift and band of the platform's starts, and the whole terrain fit of every start (SOURCE, PRESERVE, VACUUM, ENCASE, BORE, FORCE_CARVE, stilts) in `engine/framework/structure/fit`, written against IrisApi's @@ -164,9 +164,8 @@ compiled these sources itself. Iris includes this build (`includeBuild('module')` in its `settings.gradle`) and depends on its classes: Iris core and its adapters still name many of them (the cut-over that ends this comes later). Classes that need Iris itself are Iris's and live in Iris core: the layout model (`IrisBiome`, `IrisRegion`, `IrisDimension`, generators, noise -styles, expressions, images), the pack's objects and blocks, the structure assembler, locator, fitting and placer -(behind `StructureHost`), and the placement service behind `PackWorld.placements()`. A module this build holds -but the jar does not, such as `iris:structure`, is one Iris registers with its own modules (`IrisModuleHost`): its +styles, expressions, images), the pack's objects and blocks, and the placement service behind `PackWorld.placements()`. +A module this build holds but the jar does not is one Iris registers with its own modules (`IrisModuleHost`): its classes are then the ones Iris's own code sees. `./gradlew check` compiles every source and builds the built-ins jar below, which runs the pack class checks. @@ -187,7 +186,7 @@ packages fails the task naming the class and what it uses. Iris checks the jar o VolmLib classes its Bukkit jar strips (`core/volmlib-left-out-of-bukkit-jar.txt`), which only Iris knows. The jar holds `iris:post`, `iris:perfection`, `iris:matter`, `iris:loot`, `iris:spawn`, `iris:vanilla-features` and -`iris:carve`, and the object placement stages `iris:prepare`, `iris:anchor`, `iris:validate`, `iris:bore`, `iris:blocks`, `iris:stilt`, `iris:vacuum` and `iris:snow`. They are +`iris:carve`, `iris:structure`, `iris:jigsaw`, and the object placement stages `iris:prepare`, `iris:anchor`, `iris:validate`, `iris:bore`, `iris:blocks`, `iris:stilt`, `iris:vacuum` and `iris:snow`. They are written against IrisApi and `art.arcane.iris.builtin` alone: the chunk's `BlockState` hunk, the block registry's traits and `canPlaceOn`, the terrain sampler (heights around the chunk, slope, fluid height, where the upper dimension begins) and the mantle's planned blocks; the placement stages read the placement being run through the `ObjectPlacement` facade, and the loot and @@ -201,7 +200,7 @@ none of the jar's modules (`IrisModuleHost.JAR_MODULE_IDS`, which a test keeps e `art.arcane.iris.builtin` also holds what the compiled-in built-ins and the jar must share, because each sees its own copy of every other class. The facades among them are interfaces Iris implements and offers through IrisApi's extension point, never -through the thread or a cast: a module asks `world.extension(X.class)` for what belongs to a world (`StructureHost`), +through the thread or a cast: a module asks `world.extension(X.class)` for what belongs to a world, `context.extension(X.class)` for what belongs to one invocation (`IrisChunk` in a chunk stage, `IrisMantleChunk` in a mantle stage) and `settings.extension(X.class)` for a reach worked out before any world exists, each with `.orElseThrow()`, since a built-in runs only where Iris offers them. Iris's per-feature world seeds are diff --git a/module/build.gradle.kts b/module/build.gradle.kts index a9122a20e..9cfe66e78 100644 --- a/module/build.gradle.kts +++ b/module/build.gradle.kts @@ -1,3 +1,4 @@ +import org.gradle.api.tasks.bundling.ZipEntryCompression import org.gradle.jvm.tasks.Jar import java.io.ByteArrayOutputStream @@ -54,7 +55,8 @@ val builtinModulesJarName = "iris-builtins.jar" val builtinModuleEntryFile = "com.volmit.IrisModule" val builtinModulesFile = layout.projectDirectory.file("builtin-modules.txt").asFile // The packages an Iris host exposes to pack modules besides the API (Iris's IrisModuleHost.EXPOSED_PACKAGES). -val exposedHostPackages = listOf("art.arcane.iris.builtin", "art.arcane.volmlib", "com.google.gson") +val exposedHostPackages = listOf("art.arcane.iris.builtin", "art.arcane.iris.core.structure.authoring", "art.arcane.volmlib", + "com.google.gson") data class BuiltinModulesList(val moduleClasses: List, val classPatterns: List) @@ -101,6 +103,8 @@ val packageBuiltinModules = tasks.register("packageBuiltinModules") { description = "Packages the listed built-in modules and classes before they are checked." archiveFileName.set(builtinModulesJarName) destinationDirectory.set(builtinModulesBuild.map { it.dir("unchecked") }) + // Iris's own jar compresses this one as a whole, which squeezes more out of the classes than compressing them twice. + entryCompression = ZipEntryCompression.STORED inputs.file(builtinModulesFile) from(sourceSets.main.map { it.java.classesDirectory }) { include(builtinPackagedPatterns) diff --git a/module/builtin-modules.txt b/module/builtin-modules.txt index 9b89e2c4c..3789a7d7e 100644 --- a/module/builtin-modules.txt +++ b/module/builtin-modules.txt @@ -98,5 +98,52 @@ include art/arcane/iris/engine/mantle/components/FloatingPlacer*.class include art/arcane/iris/engine/mantle/components/FloatingIslandSampleResolver*.class include art/arcane/iris/engine/mantle/components/IslandFace*.class include art/arcane/iris/engine/mantle/components/UndersideTurn*.class -# iris:structure (art.arcane.iris.engine.mantle.components.StructureModule) is not here: Iris registers it with its own -# modules, because its jigsaw studio reads the structure resources the module registers. +module art.arcane.iris.engine.mantle.components.StructureModule +include art/arcane/iris/engine/mantle/components/StructurePlacing*.class +include art/arcane/iris/engine/mantle/components/StructureCarvingFootprint*.class +include art/arcane/iris/engine/mantle/components/StructureCarveEnvelope*.class +include art/arcane/iris/engine/mantle/components/StructureFoundationPlanner*.class +include art/arcane/iris/engine/mantle/components/StructurePieceColumns*.class +include art/arcane/iris/engine/framework/IrisStructureLocator*.class +include art/arcane/iris/engine/framework/StructureCaveAnchorResolver*.class +include art/arcane/iris/engine/framework/StructurePlacementScope*.class +include art/arcane/iris/engine/framework/StructurePlacementGrid*.class +include art/arcane/iris/engine/framework/structure/fit/** +include art/arcane/iris/engine/framework/structure/assembly/** +include art/arcane/iris/engine/framework/structure/ColumnHeights*.class +include art/arcane/iris/engine/framework/structure/ImportedStructures*.class +include art/arcane/iris/engine/framework/structure/NativeStartPlanner*.class +include art/arcane/iris/engine/framework/structure/NativeStructureFit*.class +include art/arcane/iris/engine/framework/structure/StructureAssemblyStatus*.class +include art/arcane/iris/engine/framework/structure/StructureLocating*.class +include art/arcane/iris/engine/framework/structure/StructurePlacementValidation*.class +include art/arcane/iris/engine/framework/structure/StructureValidator*.class +include art/arcane/iris/engine/framework/structure/StructureVanillaStructures*.class +include art/arcane/iris/engine/framework/structure/StructureWorld*.class +include art/arcane/iris/core/modules/StructureCommands*.class +module art.arcane.iris.modules.jigsaw.JigsawModule +include art/arcane/iris/engine/object/structure/** +include art/arcane/iris/engine/framework/StructureAssembler*.class +include art/arcane/iris/engine/framework/PlacedStructurePiece*.class +include art/arcane/iris/engine/framework/structure/CompiledStructureGraph*.class +include art/arcane/iris/engine/framework/structure/IrisObjectFrameReader*.class +include art/arcane/iris/engine/framework/structure/JigsawPoolSelection*.class +include art/arcane/iris/engine/framework/structure/JigsawStructureAssembly*.class +include art/arcane/iris/engine/framework/structure/JigsawValidator*.class +include art/arcane/iris/engine/framework/structure/NativeReplacementValidation*.class +include art/arcane/iris/engine/framework/structure/ObjectFrame*.class +include art/arcane/iris/engine/framework/structure/PackJsonFiles*.class +include art/arcane/iris/engine/framework/structure/PackStructureGraphResolver*.class +include art/arcane/iris/engine/framework/structure/PlanarJigsawWorkcellResolver*.class +include art/arcane/iris/engine/framework/structure/StructureAssemblyResult*.class +include art/arcane/iris/engine/framework/structure/StructureGraph*.class +include art/arcane/iris/engine/framework/structure/StructureReferenceValidation*.class +include art/arcane/iris/engine/framework/structure/StructureResource*.class +include art/arcane/iris/core/runtime/jigsaw/** +include art/arcane/iris/core/service/JigsawStudio*.class +include art/arcane/iris/engine/platform/studio/generators/JigsawStudioGenerator*.class +include art/arcane/iris/core/structure/*.class +include art/arcane/iris/core/structure/conversion/** +include art/arcane/iris/core/structure/export/** +include art/arcane/iris/core/structure/tooling/** +include art/arcane/iris/core/pack/StructurePackageClosure*.class diff --git a/module/src/main/java/art/arcane/iris/builtin/package-info.java b/module/src/main/java/art/arcane/iris/builtin/package-info.java index 8d084d393..76707f565 100644 --- a/module/src/main/java/art/arcane/iris/builtin/package-info.java +++ b/module/src/main/java/art/arcane/iris/builtin/package-info.java @@ -30,7 +30,7 @@ *

* Besides those, it holds what Iris and the built-ins jar must share, since each sees its own copy * of every other class: narrow facades only Iris's own built-ins use, interfaces Iris's worlds implement - * ({@link art.arcane.iris.builtin.structure.StructureHost}), and the seed purposes of the built-in features + * ({@link art.arcane.iris.builtin.structure.StructureVerifier}), and the seed purposes of the built-in features * ({@link art.arcane.iris.builtin.IrisSeedPurposes}). Keep them few: each is a promise. *

* The placement stages ({@code iris:prepare} to {@code iris:snow}) run in the pack's placement graph, which diff --git a/module/src/main/java/art/arcane/iris/builtin/structure/IrisStructureRef.java b/module/src/main/java/art/arcane/iris/builtin/structure/IrisStructureRef.java index ef2bcfc55..584fc8444 100644 --- a/module/src/main/java/art/arcane/iris/builtin/structure/IrisStructureRef.java +++ b/module/src/main/java/art/arcane/iris/builtin/structure/IrisStructureRef.java @@ -18,17 +18,22 @@ package art.arcane.iris.builtin.structure; +import com.volmit.resource.ResourceId; + import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Iris extension: says that a text option names structures of Iris's structure model by key, which Iris completes in - * studio and carries along when it exports the pack. The structure model is Iris's own resource kind, whose class a - * module cannot see, so {@code @ResourceRef} cannot name it; to another host the option is plain text. + * Iris extension: says that a text option names structures of the pack's jigsaw module by key, which Iris completes in + * studio and carries along when it exports the pack. It stands for {@code @ResourceRef} of the structure kind, whose class + * lives in the module jar and so cannot be named from this exposed package; Iris resolves it by the kind's id, {@link #KIND}. + * To another host the option is plain text. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface IrisStructureRef { + /** The id of the resource kind of the structures, which {@code iris:jigsaw} registers. */ + ResourceId KIND = ResourceId.parse("iris:jigsaw/structure"); } diff --git a/module/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java b/module/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java deleted file mode 100644 index 5703e7117..000000000 --- a/module/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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.builtin.structure; - -import com.volmit.generation.InvocationContext; -import com.volmit.resource.ResourceId; - -import java.util.List; -import java.util.Optional; - -/** - * What {@code iris:structure} asks of Iris: Iris places its jigsaw structures itself. The structure model (structures, - * pools, pieces), the assembler that builds a structure from them and the locator that spreads them over the world are - * Iris's, shared with the jigsaw studio and the structure importers and exporters. Iris offers it as an extension of its - * worlds and of the settings of the pack it loads: {@code world.extension(StructureHost.class)}. - */ -public interface StructureHost { - /** Places the structures that start in the chunk whose mantle the mantle invocation {@code context} generates. */ - void placeChunk(InvocationContext context); - - /** How far, in blocks along X and Z, a structure may write beyond the chunk it starts in. */ - int reach(); - - /** The loot tables the structure gives its pieces' containers; empty when the pack has no such structure. */ - Optional> lootTables(ResourceId structure); -} diff --git a/module/src/main/java/art/arcane/iris/builtin/structure/StructureSeeds.java b/module/src/main/java/art/arcane/iris/builtin/structure/StructureSeeds.java new file mode 100644 index 000000000..78fc4c0cd --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/structure/StructureSeeds.java @@ -0,0 +1,15 @@ +package art.arcane.iris.builtin.structure; + +import com.volmit.resource.ResourceId; + +/** The seed purposes of structure placement, for {@link com.volmit.world.PackWorld#seed(ResourceId)}. */ +public final class StructureSeeds { + /** + * The seed placements start from: where structures start, their anchors and their pieces. Iris keeps the seed it has + * always used for it, so the structures of existing worlds stay where they are. + */ + public static final ResourceId PLACEMENT = ResourceId.parse("iris:structure/placement"); + + private StructureSeeds() { + } +} diff --git a/module/src/main/java/art/arcane/iris/builtin/structure/StructureVerifier.java b/module/src/main/java/art/arcane/iris/builtin/structure/StructureVerifier.java new file mode 100644 index 000000000..ca884e04f --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/structure/StructureVerifier.java @@ -0,0 +1,31 @@ +/* + * 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.builtin.structure; + +import com.volmit.tooling.CommandContext; + +/** + * What Iris's running worlds offer {@code iris:structure}'s {@code verify} command: whether each structure can generate + * in the world, which needs the world's native structure policy and biome reachability that only Iris itself reads. + * Ask for it with {@code world.extension(StructureVerifier.class)}. + */ +public interface StructureVerifier { + /** Reports to the sender of {@code context}, for every structure the platform registers and every structure the pack places, whether it can generate within {@code radiusChunks} of the world origin. */ + void verify(CommandContext context, int radiusChunks); +} diff --git a/module/src/main/java/art/arcane/iris/core/modules/StructureCommands.java b/module/src/main/java/art/arcane/iris/core/modules/StructureCommands.java new file mode 100644 index 000000000..16f56e503 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/modules/StructureCommands.java @@ -0,0 +1,149 @@ +/* + * 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.builtin.structure.StructureVerifier; +import art.arcane.iris.core.structure.authoring.StructureIndexService; +import art.arcane.iris.core.structure.tooling.PlatformStructuresAccess; +import art.arcane.iris.engine.framework.structure.assembly.AssembledPiece; +import art.arcane.iris.engine.framework.structure.assembly.Assembly; +import art.arcane.iris.engine.framework.structure.assembly.StructureAssembly; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.Argument; +import com.volmit.tooling.Command; +import com.volmit.tooling.CommandContext; +import com.volmit.tooling.PlatformStructures; + +import java.io.File; +import java.io.IOException; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +/** The {@code /iris module structure} commands of {@code iris:structure}: the index, one structure's graph, and the verification of a world's structures. */ +public 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 long DEFAULT_RADIUS_CHUNKS = 48L; + private static final long MAX_RADIUS_CHUNKS = 1000L; + private static final char NAMESPACE_SEPARATOR = ':'; + private static final String STRUCTURES_FOLDER = "structures"; + + private static final Argument STRUCTURE = Argument.reading("structure", StructureCommands::readStructure) + .describe("The Iris structure to inspect") + .suggesting(StructureCommands::structureKeys); + private 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 StructureCommands() { + } + + public 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(RADIUS) + .runs(StructureCommands::verify)); + } + + private static void list(CommandContext context) throws IOException { + Optional platform = PlatformStructuresAccess.require(context); + if (platform.isEmpty()) { + return; + } + File index = StructureIndexService.write(context.pack(), platform.get()); + context.sender().success("Wrote the structure index: " + index.getPath()); + } + + private static void info(CommandContext context) { + ResourceId id = context.get(STRUCTURE); + Assembly assembly = sampleAssembly(context, id).orElseThrow(); + if (!assembly.hasOutput()) { + context.sender().error("Structure " + id + " assembled 0 pieces" + (assembly.detail().isBlank() ? "" : " (" + assembly.detail() + ")")); + 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 (AssembledPiece piece : pieces) { + minX = Math.min(minX, piece.minX()); + minZ = Math.min(minZ, piece.minZ()); + maxX = Math.max(maxX, piece.maxX()); + maxZ = Math.max(maxZ, piece.maxZ()); + } + context.sender().success("Structure " + id + ": " + pieces.size() + " pieces, footprint " + (maxX - minX + 1) + "x" + + (maxZ - minZ + 1) + " blocks (sample seed " + INFO_SAMPLE_SEED + ")"); + } + + private static Optional sampleAssembly(CommandContext context, ResourceId id) { + PackResources resources = context.pack().resources(); + BlockPosition origin = new BlockPosition(0, INFO_ORIGIN_Y, 0); + for (StructureAssembly provider : context.pack().services(StructureAssembly.class)) { + Optional assembly = provider.assemble(resources, id, origin, new RNG(INFO_SAMPLE_SEED)); + if (assembly.isPresent()) { + return assembly; + } + } + return Optional.empty(); + } + + private static void verify(CommandContext context) { + Optional verifier = context.world().flatMap(world -> world.extension(StructureVerifier.class)); + if (verifier.isEmpty()) { + context.sender().error("Stand in a world generated with this pack: verify reads the running world"); + return; + } + verifier.get().verify(context, Math.toIntExact(context.get(RADIUS))); + } + + private static ResourceId readStructure(String written, CommandContext context) { + PackResources resources = context.pack().resources(); + ResourceId id = written.indexOf(NAMESPACE_SEPARATOR) < 0 ? resources.idOf(written) : ResourceId.parse(written); + boolean known = context.pack().services(StructureAssembly.class).stream().anyMatch(provider -> provider.knows(resources, id)); + if (!known) { + throw new IllegalArgumentException("No " + STRUCTURES_FOLDER + " resource '" + written + "' in this pack"); + } + return id; + } + + private static List structureKeys(CommandContext context) { + PackResources resources = context.pack().resources(); + Set keys = new LinkedHashSet<>(); + for (StructureAssembly provider : context.pack().services(StructureAssembly.class)) { + provider.structures(resources).forEach(id -> keys.add(resources.idOf(id.path()).equals(id) ? id.path() : id.toString())); + } + return List.copyOf(keys); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/pack/StructurePackageClosure.java b/module/src/main/java/art/arcane/iris/core/pack/StructurePackageClosure.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/pack/StructurePackageClosure.java rename to module/src/main/java/art/arcane/iris/core/pack/StructurePackageClosure.java diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawPlanarArchetype.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawPlanarArchetype.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawPlanarArchetype.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawPlanarArchetype.java diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawPlanarDirection.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawPlanarDirection.java similarity index 65% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawPlanarDirection.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawPlanarDirection.java index 5b853527b..9f8076905 100644 --- a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawPlanarDirection.java +++ b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawPlanarDirection.java @@ -1,6 +1,6 @@ package art.arcane.iris.core.runtime.jigsaw; -import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; public enum JigsawPlanarDirection { NORTH(1), @@ -18,12 +18,12 @@ public enum JigsawPlanarDirection { return bit; } - public IrisDirection irisDirection() { + public JigsawDirection direction() { return switch (this) { - case NORTH -> IrisDirection.NORTH_NEGATIVE_Z; - case EAST -> IrisDirection.EAST_POSITIVE_X; - case SOUTH -> IrisDirection.SOUTH_POSITIVE_Z; - case WEST -> IrisDirection.WEST_NEGATIVE_X; + case NORTH -> JigsawDirection.NORTH_NEGATIVE_Z; + case EAST -> JigsawDirection.EAST_POSITIVE_X; + case SOUTH -> JigsawDirection.SOUTH_POSITIVE_Z; + case WEST -> JigsawDirection.WEST_NEGATIVE_X; }; } diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawPlanarTopology.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawPlanarTopology.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawPlanarTopology.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawPlanarTopology.java diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawPlanarTopologyKind.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawPlanarTopologyKind.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawPlanarTopologyKind.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawPlanarTopologyKind.java diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioAuthoringAccess.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioAuthoringAccess.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioAuthoringAccess.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioAuthoringAccess.java diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioBay.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioBay.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioBay.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioBay.java diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioBayKind.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioBayKind.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioBayKind.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioBayKind.java diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioBounds.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioBounds.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioBounds.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioBounds.java diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioCellDimensions.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioCellDimensions.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioCellDimensions.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioCellDimensions.java diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioCompatibilityTarget.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioCompatibilityTarget.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioCompatibilityTarget.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioCompatibilityTarget.java diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioControlPosition.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioControlPosition.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioControlPosition.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioControlPosition.java diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphEditor.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphEditor.java similarity index 91% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphEditor.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphEditor.java index 63344516f..087a5ed0b 100644 --- a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphEditor.java +++ b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphEditor.java @@ -9,19 +9,19 @@ import art.arcane.iris.core.structure.authoring.StructureWriteOptions; import art.arcane.iris.core.structure.authoring.StructureWriteResult; import art.arcane.iris.engine.framework.structure.PlanarJigsawWorkcellResolver; import art.arcane.iris.engine.framework.structure.StructureResourceBundleGraphCompiler; -import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawMode; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint; -import art.arcane.iris.engine.object.prefab.TileData; -import art.arcane.iris.spi.PlatformBlockState; import art.arcane.volmlib.util.math.IrisBlockVector; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import com.volmit.tooling.ObjectCodec; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; @@ -53,6 +53,7 @@ public final class JigsawStudioGraphEditor { public static StructureWriteResult createPiece( Path packRoot, + ObjectCodec codec, String structureKey, String poolKey, String pieceKey, @@ -90,14 +91,14 @@ public final class JigsawStudioGraphEditor { .setObject(normalizedPiece) .setRotatable(true); if (topology != null) { - IrisPosition cellSize = new IrisPosition( + BlockPosition cellSize = new BlockPosition( dimensions.width(), dimensions.height(), dimensions.depth()); for (JigsawPlanarDirection planarDirection : topology.directions()) { - IrisDirection direction = planarDirection.irisDirection(); + JigsawDirection direction = planarDirection.direction(); piece.getConnectors().add(new IrisJigsawConnector() .setPosition(IrisJigsawConnector.canonicalPlanarPosition(cellSize, direction)) .setDirection(direction) - .setTop(IrisDirection.UP_POSITIVE_Y) + .setTop(JigsawDirection.UP_POSITIVE_Y) .setPool(normalizedPool) .setName("iris:planar") .setTargetName("iris:planar") @@ -105,20 +106,22 @@ public final class JigsawStudioGraphEditor { .setFinalState("minecraft:structure_void")); } } - IrisObject object = new IrisObject(dimensions.width(), dimensions.height(), dimensions.depth()); + JigsawStudioObject object = JigsawStudioObject.empty(dimensions.width(), dimensions.height(), dimensions.depth()); bundle.textResource(pieceResource, GSON.toJson(piece) + "\n"); - bundle.resource(objectResource, JigsawStudioProjectCreator.serialize(object)); + bundle.resource(objectResource, codec.encode(object.toGenerated())); return write(graph, bundle.build()); } public static StructureWriteResult duplicatePiece( Path packRoot, + ObjectCodec codec, String structureKey, String sourcePieceKey, String targetPieceKey ) throws IOException { return createVariantFromPiece( packRoot, + codec, structureKey, sourcePieceKey, targetPieceKey, @@ -127,12 +130,14 @@ public final class JigsawStudioGraphEditor { public static StructureWriteResult createBlankVariant( Path packRoot, + ObjectCodec codec, String structureKey, String sourcePieceKey, String targetPieceKey ) throws IOException { return createVariantFromPiece( packRoot, + codec, structureKey, sourcePieceKey, targetPieceKey, @@ -472,6 +477,7 @@ public final class JigsawStudioGraphEditor { public static VariantResizeResult resizePieceObject( Path packRoot, + ObjectCodec codec, String structureKey, String pieceKey, JigsawStudioCellDimensions dimensions @@ -496,18 +502,17 @@ public final class JigsawStudioGraphEditor { } requireExclusiveObjectReference(graph, normalizedPiece, objectKey); Path objectPath = resolveOwnedResource(graph.root(), objectResource); - IrisObject source = new IrisObject(); - source.read(objectPath.toFile()); + JigsawStudioObject source = JigsawStudioObject.of(codec.decode(Files.readAllBytes(objectPath))); String structureResource = "structures/" + JigsawStudioProjectCreator.Options.requireResourceKey(structureKey) + ".json"; IrisStructure structure = readStructure( resolveOwnedResource(graph.root(), structureResource), structureResource); - IrisObject resizedObject; + JigsawStudioObject resizedObject; JigsawStudioCellDimensions sourceDimensions = new JigsawStudioCellDimensions( - source.getW(), - source.getH(), - source.getD()); + source.width(), + source.height(), + source.depth()); JigsawStudioCellDimensions previousDimensions; int relocatedConnectors = 0; if (structure.resolvedMode() == IrisJigsawMode.PLANAR_JIGSAW) { @@ -545,7 +550,7 @@ public final class JigsawStudioGraphEditor { for (String relativePath : graph.manifest().resourceHashes().keySet()) { byte[] content; if (relativePath.equals(objectResource)) { - content = JigsawStudioProjectCreator.serialize(resizedObject); + content = codec.encode(resizedObject.toGenerated()); } else if (relativePath.equals(pieceResource)) { content = (GSON.toJson(piece) + "\n").getBytes(StandardCharsets.UTF_8); } else { @@ -631,11 +636,11 @@ public final class JigsawStudioGraphEditor { Path packRoot, String structureKey, String pieceKey, - IrisPosition position, + BlockPosition position, String channel ) throws IOException { String normalizedPiece = JigsawStudioProjectCreator.Options.requireResourceKey(pieceKey); - IrisPosition connectorPosition = Objects.requireNonNull(position, "Jigsaw connector position"); + BlockPosition connectorPosition = Objects.requireNonNull(position, "Jigsaw connector position"); String normalizedChannel = normalizeChannel(channel); OwnedGraph graph = loadOwnedGraph(packRoot, structureKey); String pieceResource = "jigsaw-pieces/" + normalizedPiece + ".json"; @@ -668,8 +673,8 @@ public final class JigsawStudioGraphEditor { } if (!found) { throw new IOException("Piece '" + normalizedPiece + "' has no connector at " - + connectorPosition.getX() + "," + connectorPosition.getY() + "," - + connectorPosition.getZ()); + + connectorPosition.x() + "," + connectorPosition.y() + "," + + connectorPosition.z()); } return write(graph, bundle.build()); } @@ -787,6 +792,7 @@ public final class JigsawStudioGraphEditor { private static StructureWriteResult createVariantFromPiece( Path packRoot, + ObjectCodec codec, String structureKey, String sourcePieceKey, String targetPieceKey, @@ -820,11 +826,9 @@ public final class JigsawStudioGraphEditor { if (objectMode == VariantObjectMode.COPY_SOURCE) { targetObjectContent = Files.readAllBytes(sourceObjectPath); } else { - IrisBlockVector sourceSize = IrisObject.sampleSize(sourceObjectPath.toFile()); - targetObjectContent = JigsawStudioProjectCreator.serialize(new IrisObject( - sourceSize.getBlockX(), - sourceSize.getBlockY(), - sourceSize.getBlockZ())); + JigsawStudioObject source = JigsawStudioObject.of(codec.decode(Files.readAllBytes(sourceObjectPath))); + targetObjectContent = codec.encode( + JigsawStudioObject.empty(source.width(), source.height(), source.depth()).toGenerated()); } Map targetPieceKeysBySource = Map.of(normalizedSource, normalizedTarget); @@ -1228,13 +1232,13 @@ public final class JigsawStudioGraphEditor { } static PlanarPieceObjectResize resizePlanarPieceObject( - IrisObject source, + JigsawStudioObject source, IrisJigsawPiece piece, JigsawPlanarArchetype archetype, JigsawStudioCellDimensions dimensions, String pieceKey ) throws IOException { - IrisObject sourceObject = Objects.requireNonNull(source, "Planar Jigsaw Studio source object"); + JigsawStudioObject sourceObject = Objects.requireNonNull(source, "Planar Jigsaw Studio source object"); IrisJigsawPiece targetPiece = Objects.requireNonNull(piece, "Planar Jigsaw Studio piece"); JigsawPlanarArchetype targetArchetype = Objects.requireNonNull( archetype, @@ -1247,7 +1251,7 @@ public final class JigsawStudioGraphEditor { throw new IllegalArgumentException( "Planar Jigsaw Studio workcell width and depth must each be at least 3 blocks"); } - if (sourceObject.getW() < 1 || sourceObject.getH() < 1 || sourceObject.getD() < 1) { + if (sourceObject.width() < 1 || sourceObject.height() < 1 || sourceObject.depth() < 1) { throw new IOException("Planar piece '" + targetPieceKey + "' has invalid object dimensions"); } if (IrisJigsawWorkcellArchetype.fromPiece(targetPiece) != targetArchetype.modelArchetype()) { @@ -1257,16 +1261,19 @@ public final class JigsawStudioGraphEditor { int quarterTurns = targetArchetype.modelArchetype().sourceToCanonicalQuarterTurns(targetPiece); JigsawStudioCellDimensions sourceDimensions = new JigsawStudioCellDimensions( - sourceObject.getW(), - sourceObject.getH(), - sourceObject.getD()); + sourceObject.width(), + sourceObject.height(), + sourceObject.depth()); JigsawStudioCellDimensions canonicalDimensions = canonicalDimensions(sourceDimensions, quarterTurns); - Map canonicalBlocks = canonicalBlocks( + JigsawStudioObject sourceContents = sourceObject; + Map canonicalBlocks = canonicalBlocks( sourceObject, + sourceContents, quarterTurns, targetPieceKey); - Map canonicalTiles = canonicalTiles( + Map canonicalTiles = canonicalTiles( sourceObject, + sourceContents, quarterTurns, targetPieceKey); List connectors = targetPiece.getConnectors(); @@ -1284,7 +1291,8 @@ public final class JigsawStudioGraphEditor { requireContentInsideTarget(canonicalBlocks, canonicalTiles, targetDimensions, targetPieceKey); JigsawStudioCellDimensions resizedSourceDimensions = sourceDimensions(targetDimensions, quarterTurns); - IrisObject resizedObject = rebuildSourceObject( + JigsawStudioObject resizedObject = rebuildSourceObject( + sourceContents, canonicalBlocks, canonicalTiles, resizedSourceDimensions, @@ -1296,7 +1304,7 @@ public final class JigsawStudioGraphEditor { connectorResize.targetCanonical(), resizedSourceDimensions, quarterTurns); - connectorResize.connector().setPosition(sourcePosition.toIrisPosition()); + connectorResize.connector().setPosition(sourcePosition.toBlockPosition()); if (!connectorResize.sourceCanonical().equals(connectorResize.targetCanonical())) { relocatedConnectors++; } @@ -1304,24 +1312,22 @@ public final class JigsawStudioGraphEditor { return new PlanarPieceObjectResize(resizedObject, relocatedConnectors); } - private static Map canonicalBlocks( - IrisObject source, + private static Map canonicalBlocks( + JigsawStudioObject source, + JigsawStudioObject contents, int quarterTurns, String pieceKey ) throws IOException { - Map blocks = new LinkedHashMap<>(); - for (Map.Entry entry : source.getBlocks()) { - LocalPosition sourcePosition = unsignedPosition(entry.getKey(), source); - requireInside(sourcePosition, source.getW(), source.getH(), source.getD(), + Map blocks = new LinkedHashMap<>(); + for (Map.Entry entry : contents.blocks().entrySet()) { + LocalPosition sourcePosition = LocalPosition.from(entry.getKey()); + requireInside(sourcePosition, source.width(), source.height(), source.depth(), "stored block", pieceKey); - PlatformBlockState state = entry.getValue(); - if (state == null) { - throw new IOException("Planar piece '" + pieceKey + "' contains a null stored block state"); - } + BlockState state = entry.getValue(); LocalPosition canonicalPosition = toCanonical( sourcePosition, - source.getW(), - source.getD(), + source.width(), + source.depth(), quarterTurns); if (blocks.putIfAbsent(canonicalPosition, state) != null) { throw new IOException("Planar piece '" + pieceKey @@ -1331,26 +1337,24 @@ public final class JigsawStudioGraphEditor { return blocks; } - private static Map canonicalTiles( - IrisObject source, + private static Map canonicalTiles( + JigsawStudioObject source, + JigsawStudioObject contents, int quarterTurns, String pieceKey ) throws IOException { - Map tiles = new LinkedHashMap<>(); - for (Map.Entry entry : source.getStates()) { - LocalPosition sourcePosition = unsignedPosition(entry.getKey(), source); - requireInside(sourcePosition, source.getW(), source.getH(), source.getD(), + Map tiles = new LinkedHashMap<>(); + for (Map.Entry entry : contents.blockEntities().entrySet()) { + LocalPosition sourcePosition = LocalPosition.from(entry.getKey()); + requireInside(sourcePosition, source.width(), source.height(), source.depth(), "tile data", pieceKey); - TileData tile = entry.getValue(); - if (tile == null) { - throw new IOException("Planar piece '" + pieceKey + "' contains null tile data"); - } + BlockEntityData tile = entry.getValue(); LocalPosition canonicalPosition = toCanonical( sourcePosition, - source.getW(), - source.getD(), + source.width(), + source.depth(), quarterTurns); - if (tiles.putIfAbsent(canonicalPosition, tile.clone()) != null) { + if (tiles.putIfAbsent(canonicalPosition, tile) != null) { throw new IOException("Planar piece '" + pieceKey + "' maps more than one tile payload to " + canonicalPosition.describe()); } @@ -1369,9 +1373,9 @@ public final class JigsawStudioGraphEditor { List planned = new ArrayList<>(connectors.size()); Set sourcePositions = new LinkedHashSet<>(); Set targetPositions = new LinkedHashSet<>(); - IrisPosition sourceSize = dimensionsPosition(sourceDimensions); - IrisPosition canonicalSize = dimensionsPosition(canonicalDimensions); - IrisPosition targetSize = dimensionsPosition(targetDimensions); + BlockPosition sourceSize = dimensionsPosition(sourceDimensions); + BlockPosition canonicalSize = dimensionsPosition(canonicalDimensions); + BlockPosition targetSize = dimensionsPosition(targetDimensions); for (int index = 0; index < connectors.size(); index++) { IrisJigsawConnector connector = connectors.get(index); if (connector == null || connector.getPosition() == null || connector.getDirection() == null @@ -1395,7 +1399,7 @@ public final class JigsawStudioGraphEditor { sourceDimensions.width(), sourceDimensions.depth(), quarterTurns); - IrisDirection canonicalDirection = rotateHorizontalDirection( + JigsawDirection canonicalDirection = rotateHorizontalDirection( connector.getDirection(), quarterTurns); LocalPosition expectedSource = LocalPosition.from(IrisJigsawConnector.canonicalPlanarPosition( @@ -1425,8 +1429,8 @@ public final class JigsawStudioGraphEditor { } private static void relocateConnectorPayloads( - Map blocks, - Map tiles, + Map blocks, + Map tiles, List connectorResizes, String pieceKey ) throws IOException { @@ -1460,7 +1464,7 @@ public final class JigsawStudioGraphEditor { continue; } boolean present = blocks.containsKey(connectorResize.sourceCanonical()); - PlatformBlockState state = blocks.remove(connectorResize.sourceCanonical()); + BlockState state = blocks.remove(connectorResize.sourceCanonical()); payloads.add(new BlockRelocation(connectorResize.targetCanonical(), state, present)); } for (BlockRelocation payload : payloads) { @@ -1475,8 +1479,8 @@ public final class JigsawStudioGraphEditor { } private static void requireContentInsideTarget( - Map blocks, - Map tiles, + Map blocks, + Map tiles, JigsawStudioCellDimensions dimensions, String pieceKey ) throws IOException { @@ -1494,51 +1498,36 @@ public final class JigsawStudioGraphEditor { } } - private static IrisObject rebuildSourceObject( - Map canonicalBlocks, - Map canonicalTiles, + private static JigsawStudioObject rebuildSourceObject( + JigsawStudioObject sourceContents, + Map canonicalBlocks, + Map canonicalTiles, JigsawStudioCellDimensions sourceDimensions, int quarterTurns, String pieceKey ) throws IOException { - IrisObject resized = new IrisObject( - sourceDimensions.width(), - sourceDimensions.height(), - sourceDimensions.depth()); - Set sourcePositions = new LinkedHashSet<>(); - for (Map.Entry entry : canonicalBlocks.entrySet()) { + Map blocks = new LinkedHashMap<>(); + for (Map.Entry entry : canonicalBlocks.entrySet()) { LocalPosition sourcePosition = toSource(entry.getKey(), sourceDimensions, quarterTurns); - if (!sourcePositions.add(sourcePosition)) { + if (blocks.put(sourcePosition.toBlockPosition(), entry.getValue()) != null) { throw new IOException("Planar piece '" + pieceKey + "' maps multiple stored blocks to " + sourcePosition.describe()); } - resized.setUnsigned( - sourcePosition.x(), - sourcePosition.y(), - sourcePosition.z(), - entry.getValue()); } - sourcePositions.clear(); - for (Map.Entry entry : canonicalTiles.entrySet()) { + Map blockEntities = new LinkedHashMap<>(); + for (Map.Entry entry : canonicalTiles.entrySet()) { LocalPosition sourcePosition = toSource(entry.getKey(), sourceDimensions, quarterTurns); - if (!sourcePositions.add(sourcePosition)) { + if (blockEntities.put(sourcePosition.toBlockPosition(), entry.getValue()) != null) { throw new IOException("Planar piece '" + pieceKey + "' maps multiple tile payloads to " + sourcePosition.describe()); } - resized.setUnsignedTile( - sourcePosition.x(), - sourcePosition.y(), - sourcePosition.z(), - entry.getValue().clone()); } - return resized; - } - - private static LocalPosition unsignedPosition(IrisBlockVector signed, IrisObject object) { - return new LocalPosition( - signed.getBlockX() + object.getCenter().getBlockX(), - signed.getBlockY() + object.getCenter().getBlockY(), - signed.getBlockZ() + object.getCenter().getBlockZ()); + return sourceContents.with( + sourceDimensions.width(), + sourceDimensions.height(), + sourceDimensions.depth(), + blocks, + blockEntities); } private static JigsawStudioCellDimensions canonicalDimensions( @@ -1600,7 +1589,7 @@ public final class JigsawStudioGraphEditor { }; } - private static IrisDirection rotateHorizontalDirection(IrisDirection direction, int quarterTurns) { + private static JigsawDirection rotateHorizontalDirection(JigsawDirection direction, int quarterTurns) { JigsawPlanarDirection planarDirection = switch (direction) { case NORTH_NEGATIVE_Z -> JigsawPlanarDirection.NORTH; case EAST_POSITIVE_X -> JigsawPlanarDirection.EAST; @@ -1609,11 +1598,11 @@ public final class JigsawStudioGraphEditor { case UP_POSITIVE_Y, DOWN_NEGATIVE_Y -> throw new IllegalArgumentException( "Planar connector direction must be horizontal"); }; - return planarDirection.rotateClockwise(quarterTurns).irisDirection(); + return planarDirection.rotateClockwise(quarterTurns).direction(); } - private static IrisPosition dimensionsPosition(JigsawStudioCellDimensions dimensions) { - return new IrisPosition(dimensions.width(), dimensions.height(), dimensions.depth()); + private static BlockPosition dimensionsPosition(JigsawStudioCellDimensions dimensions) { + return new BlockPosition(dimensions.width(), dimensions.height(), dimensions.depth()); } private static boolean inside(LocalPosition position, JigsawStudioCellDimensions dimensions) { @@ -1640,45 +1629,33 @@ public final class JigsawStudioGraphEditor { } } - static IrisObject resizeObject( - IrisObject source, + static JigsawStudioObject resizeObject( + JigsawStudioObject source, JigsawStudioCellDimensions dimensions, String pieceKey ) throws IOException { - IrisObject object = Objects.requireNonNull(source, "Jigsaw Studio source object"); + JigsawStudioObject object = Objects.requireNonNull(source, "Jigsaw Studio source object"); JigsawStudioCellDimensions target = Objects.requireNonNull( dimensions, "Jigsaw Studio target object dimensions"); String normalizedPiece = pieceKey == null || pieceKey.isBlank() ? "unknown" : pieceKey; - IrisObject resized = new IrisObject(target.width(), target.height(), target.depth()); - for (Map.Entry entry : object.getBlocks()) { - IrisBlockVector position = entry.getKey(); - LocalPosition unsigned = unsignedPosition(position, object); + JigsawStudioObject contents = object; + for (BlockPosition position : contents.blocks().keySet()) { + LocalPosition unsigned = LocalPosition.from(position); if (!inside(unsigned, target)) { throw new IOException("Spatial piece '" + normalizedPiece + "' has a stored block, including explicit air, at " + unsigned.describe() + " that would be cropped by the requested variant size"); } - resized.setUnsigned( - unsigned.x(), - unsigned.y(), - unsigned.z(), - entry.getValue()); } - for (Map.Entry entry : object.getStates()) { - IrisBlockVector position = entry.getKey(); - LocalPosition unsigned = unsignedPosition(position, object); + for (BlockPosition position : contents.blockEntities().keySet()) { + LocalPosition unsigned = LocalPosition.from(position); if (!inside(unsigned, target)) { throw new IOException("Spatial piece '" + normalizedPiece + "' has tile data at " + unsigned.describe() + " that would be cropped by the requested variant size"); } - resized.setUnsignedTile( - unsigned.x(), - unsigned.y(), - unsigned.z(), - entry.getValue().clone()); } - return resized; + return contents.with(target.width(), target.height(), target.depth(), contents.blocks(), contents.blockEntities()); } private static void requireConnectorsInside( @@ -1827,7 +1804,7 @@ public final class JigsawStudioGraphEditor { EMPTY_SOURCE_SIZE } - record PlanarPieceObjectResize(IrisObject object, int relocatedConnectors) { + record PlanarPieceObjectResize(JigsawStudioObject object, int relocatedConnectors) { PlanarPieceObjectResize { Objects.requireNonNull(object, "Resized planar Jigsaw Studio object"); if (relocatedConnectors < 0) { @@ -1848,7 +1825,7 @@ public final class JigsawStudioGraphEditor { } } - private record BlockRelocation(LocalPosition target, PlatformBlockState state, boolean present) { + private record BlockRelocation(LocalPosition target, BlockState state, boolean present) { private BlockRelocation { Objects.requireNonNull(target, "Planar Jigsaw Studio connector block target"); if (present) { @@ -1858,12 +1835,12 @@ public final class JigsawStudioGraphEditor { } private record LocalPosition(int x, int y, int z) { - private static LocalPosition from(IrisPosition position) { - return new LocalPosition(position.getX(), position.getY(), position.getZ()); + private static LocalPosition from(BlockPosition position) { + return new LocalPosition(position.x(), position.y(), position.z()); } - private IrisPosition toIrisPosition() { - return new IrisPosition(x, y, z); + private BlockPosition toBlockPosition() { + return new BlockPosition(x, y, z); } private String describe() { diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphMapper.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphMapper.java similarity index 82% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphMapper.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphMapper.java index f9c1bb1e2..3e615e187 100644 --- a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphMapper.java +++ b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioGraphMapper.java @@ -1,23 +1,23 @@ package art.arcane.iris.core.runtime.jigsaw; +import art.arcane.iris.engine.framework.structure.ObjectFrame; import art.arcane.iris.engine.framework.structure.StructureResources; -import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.structure.authoring.StructureKey; import art.arcane.iris.core.structure.authoring.StructureOwnershipManifest; import art.arcane.iris.core.structure.authoring.StructureTransactionWriter; import art.arcane.iris.engine.framework.structure.PlanarJigsawWorkcellResolver; -import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawMode; 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 art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.structure.IrisStructure; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.PackResources; +import com.volmit.tooling.ToolPack; -import java.io.File; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; @@ -38,20 +38,24 @@ public final class JigsawStudioGraphMapper { private JigsawStudioGraphMapper() { } - public static JigsawStudioLayout map(IrisData data, IrisStructure structure) { - Objects.requireNonNull(data, "Jigsaw Studio graph mapping requires pack data"); + /** + * The studio layout of {@code structure}, the structure {@code structureKey} of {@code pack}, whose files are below {@code packRoot}. + */ + public static JigsawStudioLayout map(ToolPack pack, Path packRoot, String structureKey, IrisStructure structure) { + Source data = new Source(Objects.requireNonNull(pack, "Jigsaw Studio graph mapping requires a pack").resources(), + Objects.requireNonNull(packRoot, "Jigsaw Studio graph mapping requires the pack folder"), structureKey); Objects.requireNonNull(structure, "Jigsaw Studio graph mapping requires a structure"); JigsawStudioMode mode = structure.resolvedMode() == IrisJigsawMode.PLANAR_JIGSAW ? JigsawStudioMode.PLANAR_JIGSAW : JigsawStudioMode.SPATIAL_JIGSAW; JigsawStudioVariantCatalog catalog = catalog(data, structure, mode); - IrisPosition configuredCell = structure.getCellSize(); + BlockPosition configuredCell = structure.getCellSize(); JigsawStudioCellDimensions dimensions = configuredCell == null ? new JigsawStudioCellDimensions(15, 15, 15) : new JigsawStudioCellDimensions( - Math.max(1, configuredCell.getX()), - Math.max(1, configuredCell.getY()), - Math.max(1, configuredCell.getZ())); + Math.max(1, configuredCell.x()), + Math.max(1, configuredCell.y()), + Math.max(1, configuredCell.z())); if (mode == JigsawStudioMode.SPATIAL_JIGSAW) { dimensions = expandSpatialDimensions(data, catalog, dimensions); return JigsawStudioLayout.createSpatial( @@ -77,11 +81,18 @@ public final class JigsawStudioGraphMapper { } public static JigsawStudioVariantCatalog catalog( - IrisData data, + ToolPack pack, + Path packRoot, + String structureKey, IrisStructure structure, JigsawStudioMode mode ) { - IrisData source = Objects.requireNonNull(data, "Jigsaw Studio catalog pack data"); + return catalog(new Source(Objects.requireNonNull(pack, "Jigsaw Studio catalog pack").resources(), + Objects.requireNonNull(packRoot, "Jigsaw Studio catalog pack folder"), structureKey), structure, mode); + } + + private static JigsawStudioVariantCatalog catalog(Source data, IrisStructure structure, JigsawStudioMode mode) { + Source source = data; IrisStructure root = Objects.requireNonNull(structure, "Jigsaw Studio catalog structure"); JigsawStudioMode activeMode = Objects.requireNonNull(mode, "Jigsaw Studio catalog mode"); OwnedResources owned = ownedResources(source, root); @@ -123,37 +134,34 @@ public final class JigsawStudioGraphMapper { } static JigsawStudioCellDimensions expandSpatialDimensions( - IrisData data, + Source data, JigsawStudioVariantCatalog catalog, JigsawStudioCellDimensions configured ) { - if (data.getObjectLoader() == null) { - return configured; - } int width = configured.width(); int height = configured.height(); int depth = configured.depth(); for (JigsawStudioVariant variant : catalog.spatialVariants()) { - IrisObject object = data.getObjectLoader().load(variant.objectKey()); + ObjectFrame object = data.objectFrame(variant.objectKey()); if (object == null) { continue; } - int objectWidth = object.getW(); - int objectDepth = object.getD(); + int objectWidth = object.width(); + int objectDepth = object.depth(); if (variant.rotatable()) { int horizontalSpan = Math.max(objectWidth, objectDepth); objectWidth = horizontalSpan; objectDepth = horizontalSpan; } width = Math.max(width, objectWidth); - height = Math.max(height, object.getH()); + height = Math.max(height, object.height()); depth = Math.max(depth, objectDepth); } return new JigsawStudioCellDimensions(width, height, depth); } private static void traversePools( - IrisData data, + Source data, JigsawStudioMode mode, OwnedResources owned, ArrayDeque pools, @@ -166,7 +174,7 @@ public final class JigsawStudioGraphMapper { if (!visitedPools.add(poolKey)) { continue; } - IrisJigsawPool pool = StructureResources.pool(data.getPackResources(), poolKey); + IrisJigsawPool pool = StructureResources.pool(data.resources(), poolKey); if (pool == null) { continue; } @@ -180,7 +188,7 @@ public final class JigsawStudioGraphMapper { continue; } String pieceKey = entry.getPiece(); - IrisJigsawPiece piece = StructureResources.piece(data.getPackResources(), pieceKey); + IrisJigsawPiece piece = StructureResources.piece(data.resources(), pieceKey); if (piece == null || piece.getObject() == null || piece.getObject().isBlank()) { continue; } @@ -202,7 +210,7 @@ public final class JigsawStudioGraphMapper { } private static void addOwnedVariant( - IrisData data, + Source data, JigsawStudioMode mode, OwnedResources owned, String pieceKey, @@ -211,21 +219,20 @@ public final class JigsawStudioGraphMapper { if (variants.containsKey(pieceKey)) { return; } - IrisJigsawPiece piece = StructureResources.piece(data.getPackResources(), pieceKey); + IrisJigsawPiece piece = StructureResources.piece(data.resources(), pieceKey); if (piece == null || piece.getObject() == null || piece.getObject().isBlank()) { return; } variants.put(pieceKey, new MutableVariant(pieceKey, piece, mode, owned.owns(pieceKey, piece.getObject()))); } - private static OwnedResources ownedResources(IrisData data, IrisStructure structure) { - String structureKey = structure.getLoadKey(); - File dataFolder = data.getDataFolder(); - if (structureKey == null || structureKey.isBlank() || dataFolder == null) { + private static OwnedResources ownedResources(Source data, IrisStructure structure) { + String structureKey = data.structureKey(); + if (structureKey == null || structureKey.isBlank()) { return OwnedResources.empty(); } try { - Path root = dataFolder.toPath().toAbsolutePath().normalize(); + Path root = data.root().toAbsolutePath().normalize(); StructureTransactionWriter writer = new StructureTransactionWriter(root); Path manifestPath = writer.ownershipManifestPath(StructureKey.parse(structureKey, "iris")); if (!Files.isRegularFile(manifestPath, LinkOption.NOFOLLOW_LINKS)) { @@ -255,7 +262,7 @@ public final class JigsawStudioGraphMapper { } } - private static int directionBit(IrisDirection direction) { + private static int directionBit(JigsawDirection direction) { return switch (direction) { case NORTH_NEGATIVE_Z -> JigsawPlanarDirection.NORTH.bit(); case EAST_POSITIVE_X -> JigsawPlanarDirection.EAST.bit(); @@ -310,7 +317,7 @@ public final class JigsawStudioGraphMapper { memberships.add(membership); } - private JigsawStudioVariant build(IrisData data) { + private JigsawStudioVariant build(Source data) { Optional dimensions = objectDimensions(data, piece, mode); return new JigsawStudioVariant( pieceKey, @@ -329,21 +336,18 @@ public final class JigsawStudioGraphMapper { } private static Optional objectDimensions( - IrisData data, + Source data, IrisJigsawPiece piece, JigsawStudioMode mode ) { - if (data.getObjectLoader() == null) { - return Optional.empty(); - } - IrisObject object = data.getObjectLoader().load(piece.getObject()); + ObjectFrame object = data.objectFrame(piece.getObject()); if (object == null) { return Optional.empty(); } JigsawStudioCellDimensions sourceDimensions = new JigsawStudioCellDimensions( - object.getW(), - object.getH(), - object.getD()); + object.width(), + object.height(), + object.depth()); if (mode == JigsawStudioMode.SPATIAL_JIGSAW) { return Optional.of(sourceDimensions); } @@ -359,6 +363,14 @@ public final class JigsawStudioGraphMapper { } } + /** What the mapper reads: the pack's resources, its folder for the ownership manifests, and the key of the mapped structure. */ + record Source(PackResources resources, Path root, String structureKey) { + /** The declared size of the object the pack key {@code key} names; null when the pack has none. */ + private ObjectFrame objectFrame(String key) { + return resources.objects().sizeOf(resources.idOf(key)).map(ObjectFrame::of).orElse(null); + } + } + private record OwnedResources( Set pieceKeys, Set poolKeys, diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioLayout.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioLayout.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioLayout.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioLayout.java diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioMarkerKeyCodec.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioMarkerKeyCodec.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioMarkerKeyCodec.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioMarkerKeyCodec.java diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioMode.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioMode.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioMode.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioMode.java diff --git a/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioObject.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioObject.java new file mode 100644 index 000000000..f96126d95 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioObject.java @@ -0,0 +1,59 @@ +package art.arcane.iris.core.runtime.jigsaw; + +import art.arcane.iris.core.structure.DeclaredObjects; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import com.volmit.object.GeneratedObject; +import com.volmit.object.ObjectBlock; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * An object as the studio edits it: a declared size, and blocks and block entities at positions counted from the + * object's minimum corner. + */ +record JigsawStudioObject( + int width, + int height, + int depth, + Map blocks, + Map blockEntities +) { + JigsawStudioObject { + blocks = Collections.unmodifiableMap(new LinkedHashMap<>(blocks)); + blockEntities = Collections.unmodifiableMap(new LinkedHashMap<>(blockEntities)); + } + + /** An object of the given size without a block. */ + static JigsawStudioObject empty(int width, int height, int depth) { + return new JigsawStudioObject(width, height, depth, Map.of(), Map.of()); + } + + static JigsawStudioObject of(GeneratedObject object) { + BlockPosition size = DeclaredObjects.sizeOf(object); + Map blocks = new LinkedHashMap<>(); + Map blockEntities = new LinkedHashMap<>(); + for (ObjectBlock block : object.blocks()) { + BlockPosition corner = DeclaredObjects.fromCorner(object, block.position()); + blocks.put(corner, block.state()); + block.blockEntity().ifPresent(entity -> blockEntities.put(corner, entity)); + } + return new JigsawStudioObject(size.x(), size.y(), size.z(), blocks, blockEntities); + } + + /** This object's contents in an object of another size, with blocks and block entities the caller edited. */ + JigsawStudioObject with(int width, int height, int depth, + Map blocks, Map blockEntities) { + return new JigsawStudioObject(width, height, depth, blocks, blockEntities); + } + + GeneratedObject toGenerated() { + DeclaredObjects.Builder builder = DeclaredObjects.builder(width, height, depth); + blocks.forEach((position, state) -> builder.state(position.x(), position.y(), position.z(), state)); + blockEntities.forEach((position, entity) -> builder.blockEntity(position.x(), position.y(), position.z(), entity)); + return builder.build(); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioPieceRules.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioPieceRules.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioPieceRules.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioPieceRules.java diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioPoolEditor.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioPoolEditor.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioPoolEditor.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioPoolEditor.java diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioPoolMembership.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioPoolMembership.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioPoolMembership.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioPoolMembership.java diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioProjectCreator.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioProjectCreator.java similarity index 84% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioProjectCreator.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioProjectCreator.java index 225eef066..1183e249b 100644 --- a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioProjectCreator.java +++ b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioProjectCreator.java @@ -11,7 +11,7 @@ import art.arcane.iris.core.structure.authoring.StructureWriteResult; import art.arcane.iris.engine.framework.structure.StructureResourceBundleGraphCompiler; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawCompatibility; -import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawMode; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; @@ -20,9 +20,10 @@ import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceRules; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcell; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.value.IrisPosition; +import art.arcane.iris.core.structure.DeclaredObjects; import art.arcane.iris.engine.object.structure.IrisStructure; +import com.volmit.geometry.BlockPosition; +import com.volmit.tooling.ObjectCodec; import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -36,25 +37,25 @@ import java.util.Objects; public final class JigsawStudioProjectCreator { private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); - private static final List SPATIAL_CONNECTOR_ORDER = List.of( - IrisDirection.NORTH_NEGATIVE_Z, - IrisDirection.SOUTH_POSITIVE_Z, - IrisDirection.EAST_POSITIVE_X, - IrisDirection.WEST_NEGATIVE_X, - IrisDirection.UP_POSITIVE_Y, - IrisDirection.DOWN_NEGATIVE_Y); + private static final List SPATIAL_CONNECTOR_ORDER = List.of( + JigsawDirection.NORTH_NEGATIVE_Z, + JigsawDirection.SOUTH_POSITIVE_Z, + JigsawDirection.EAST_POSITIVE_X, + JigsawDirection.WEST_NEGATIVE_X, + JigsawDirection.UP_POSITIVE_Y, + JigsawDirection.DOWN_NEGATIVE_Y); private JigsawStudioProjectCreator() { } - public static StructureWriteResult create(Path packRoot, Options options) throws IOException { + public static StructureWriteResult create(Path packRoot, ObjectCodec codec, Options options) throws IOException { Options activeOptions = Objects.requireNonNull(options, "Jigsaw Studio project options"); - StructureResourceBundle bundle = bundle(activeOptions); + StructureResourceBundle bundle = bundle(codec, activeOptions); StructureResourceBundleGraphCompiler.requireViable(bundle); return new StructureTransactionWriter(packRoot).write(bundle, StructureWriteMode.ADD_ONLY); } - static StructureResourceBundle bundle(Options options) throws IOException { + static StructureResourceBundle bundle(ObjectCodec codec, Options options) throws IOException { String resourceKey = options.structureKey(); StructureKey ownershipKey = new StructureKey("iris", resourceKey); IrisStructure structure = new IrisStructure() @@ -64,7 +65,7 @@ public final class JigsawStudioProjectCreator { .setMode(toModelMode(options.mode())) .setCompatibility(toModelCompatibility(options.compatibilityTarget())) .setBranchFailurePolicy(toBranchFailurePolicy(options.compatibilityTarget())) - .setCellSize(new IrisPosition( + .setCellSize(new BlockPosition( options.cellDimensions().width(), options.cellDimensions().height(), options.cellDimensions().depth())); @@ -79,21 +80,15 @@ public final class JigsawStudioProjectCreator { .capability(StructureCapability.IRIS_PLACEMENT); IrisJigsawPool pool = new IrisJigsawPool(); if (options.mode() == JigsawStudioMode.PLANAR_JIGSAW) { - addPlanarDefaults(bundle, structure, pool, options); + addPlanarDefaults(bundle, codec, structure, pool, options); } else { - addSpatialDefaults(bundle, pool, options); + addSpatialDefaults(bundle, codec, pool, options); } bundle.textResource("jigsaw-pools/" + resourceKey + "/start.json", GSON.toJson(pool) + "\n"); bundle.textResource("structures/" + resourceKey + ".json", GSON.toJson(structure) + "\n"); return bundle.build(); } - static byte[] serialize(IrisObject object) throws IOException { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - object.write(output); - return output.toByteArray(); - } - private static IrisJigsawMode toModelMode(JigsawStudioMode mode) { return mode == JigsawStudioMode.PLANAR_JIGSAW ? IrisJigsawMode.PLANAR_JIGSAW @@ -118,12 +113,13 @@ public final class JigsawStudioProjectCreator { private static void addPlanarDefaults( StructureResourceBundle.Builder bundle, + ObjectCodec codec, IrisStructure structure, IrisJigsawPool pool, Options options ) throws IOException { JigsawStudioCellDimensions dimensions = options.cellDimensions(); - IrisPosition size = new IrisPosition(dimensions.width(), dimensions.height(), dimensions.depth()); + BlockPosition size = new BlockPosition(dimensions.width(), dimensions.height(), dimensions.depth()); String piecePoolKey = options.structureKey() + "/pieces"; String capPoolKey = options.structureKey() + "/caps"; IrisJigsawPool piecePool = new IrisJigsawPool().setFallback(capPoolKey); @@ -153,7 +149,7 @@ public final class JigsawStudioProjectCreator { dimensions.height(), dimensions.depth(), true)); - bundle.resource("objects/" + key + ".iob", serialize(new IrisObject( + bundle.resource("objects/" + key + codec.extension(), codec.encode(DeclaredObjects.empty( dimensions.width(), dimensions.height(), dimensions.depth()))); @@ -166,6 +162,7 @@ public final class JigsawStudioProjectCreator { private static void addSpatialDefaults( StructureResourceBundle.Builder bundle, + ObjectCodec codec, IrisJigsawPool pool, Options options ) throws IOException { @@ -187,7 +184,7 @@ public final class JigsawStudioProjectCreator { if (connectorCount > 0) { piecePool.getPieces().add(new IrisJigsawPieceEntry(key, 1)); } - bundle.resource("objects/" + key + ".iob", serialize(new IrisObject( + bundle.resource("objects/" + key + codec.extension(), codec.encode(DeclaredObjects.empty( dimensions.width(), dimensions.height(), dimensions.depth()))); @@ -209,13 +206,13 @@ public final class JigsawStudioProjectCreator { .setRotatable(true) .setRules(new IrisJigsawPieceRules().setMaximumPlacements(16)); for (int index = 0; index < connectorCount; index++) { - IrisDirection direction = SPATIAL_CONNECTOR_ORDER.get(index); + JigsawDirection direction = SPATIAL_CONNECTOR_ORDER.get(index); piece.getConnectors().add(new IrisJigsawConnector() .setPosition(spatialConnectorPosition(dimensions, direction)) .setDirection(direction) .setTop(direction.isVertical() - ? IrisDirection.NORTH_NEGATIVE_Z - : IrisDirection.UP_POSITIVE_Y) + ? JigsawDirection.NORTH_NEGATIVE_Z + : JigsawDirection.UP_POSITIVE_Y) .setPool(poolKey) .setName("iris:spatial") .setTargetName("iris:spatial") @@ -225,36 +222,36 @@ public final class JigsawStudioProjectCreator { return piece; } - private static IrisPosition spatialConnectorPosition( + private static BlockPosition spatialConnectorPosition( JigsawStudioCellDimensions dimensions, - IrisDirection direction + JigsawDirection direction ) { int centerX = dimensions.width() / 2; int centerY = dimensions.height() / 2; int centerZ = dimensions.depth() / 2; return switch (direction) { - case NORTH_NEGATIVE_Z -> new IrisPosition(centerX, centerY, 0); - case SOUTH_POSITIVE_Z -> new IrisPosition(centerX, centerY, dimensions.depth() - 1); - case EAST_POSITIVE_X -> new IrisPosition(dimensions.width() - 1, centerY, centerZ); - case WEST_NEGATIVE_X -> new IrisPosition(0, centerY, centerZ); - case UP_POSITIVE_Y -> new IrisPosition(centerX, dimensions.height() - 1, centerZ); - case DOWN_NEGATIVE_Y -> new IrisPosition(centerX, 0, centerZ); + case NORTH_NEGATIVE_Z -> new BlockPosition(centerX, centerY, 0); + case SOUTH_POSITIVE_Z -> new BlockPosition(centerX, centerY, dimensions.depth() - 1); + case EAST_POSITIVE_X -> new BlockPosition(dimensions.width() - 1, centerY, centerZ); + case WEST_NEGATIVE_X -> new BlockPosition(0, centerY, centerZ); + case UP_POSITIVE_Y -> new BlockPosition(centerX, dimensions.height() - 1, centerZ); + case DOWN_NEGATIVE_Y -> new BlockPosition(centerX, 0, centerZ); }; } private static IrisJigsawPiece planarPiece( String objectKey, String poolKey, - IrisPosition dimensions, + BlockPosition dimensions, JigsawPlanarArchetype archetype ) { IrisJigsawPiece piece = new IrisJigsawPiece().setObject(objectKey).setRotatable(true); for (JigsawPlanarDirection planarDirection : archetype.canonicalTopology().directions()) { - IrisDirection direction = planarDirection.irisDirection(); + JigsawDirection direction = planarDirection.direction(); piece.getConnectors().add(new IrisJigsawConnector() .setPosition(IrisJigsawConnector.canonicalPlanarPosition(dimensions, direction)) .setDirection(direction) - .setTop(IrisDirection.UP_POSITIVE_Y) + .setTop(JigsawDirection.UP_POSITIVE_Y) .setPool(poolKey) .setName("iris:planar") .setTargetName("iris:planar") diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioProjectDeletionService.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioProjectDeletionService.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioProjectDeletionService.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioProjectDeletionService.java diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioSession.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioSession.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioSession.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioSession.java diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioStructureEditor.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioStructureEditor.java similarity index 96% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioStructureEditor.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioStructureEditor.java index e68b6aedd..eb086a536 100644 --- a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioStructureEditor.java +++ b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioStructureEditor.java @@ -12,9 +12,7 @@ import art.arcane.iris.engine.framework.structure.StructureResourceBundleGraphCo import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawMode; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype; -import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.structure.IrisStructure; -import art.arcane.volmlib.util.math.IrisBlockVector; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; @@ -22,6 +20,7 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import java.io.DataInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -270,17 +269,24 @@ public final class JigsawStudioStructureEditor { continue; } Path objectPath = resolveOwnedResource(root, relativePath); - IrisBlockVector size = IrisObject.sampleSize(objectPath.toFile()); - if (size.getBlockX() > dimensions.width() - || size.getBlockY() > dimensions.height() - || size.getBlockZ() > dimensions.depth()) { + int[] size = sampleSize(objectPath); + if (size[0] > dimensions.width() + || size[1] > dimensions.height() + || size[2] > dimensions.depth()) { throw new IOException("Owned object '" + relativePath + "' is " - + size.getBlockX() + "x" + size.getBlockY() + "x" + size.getBlockZ() + + size[0] + "x" + size[1] + "x" + size[2] + " and does not fit the requested cell bounds"); } } } + /** The declared width, height and depth in the header of an {@code .iob} file. */ + private static int[] sampleSize(Path objectPath) throws IOException { + try (DataInputStream header = new DataInputStream(Files.newInputStream(objectPath))) { + return new int[]{header.readInt(), header.readInt(), header.readInt()}; + } + } + private static byte[] updateCellSize( byte[] content, JigsawStudioCellDimensions dimensions, diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioToolAction.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioToolAction.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioToolAction.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioToolAction.java diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioToolPayload.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioToolPayload.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioToolPayload.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioToolPayload.java diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioTripleSneakTracker.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioTripleSneakTracker.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioTripleSneakTracker.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioTripleSneakTracker.java diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioVariant.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioVariant.java similarity index 79% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioVariant.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioVariant.java index 4fd510bee..c24e86b5a 100644 --- a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioVariant.java +++ b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioVariant.java @@ -1,6 +1,6 @@ package art.arcane.iris.core.runtime.jigsaw; -import art.arcane.iris.engine.object.value.IrisPosition; +import com.volmit.geometry.BlockPosition; import java.util.List; import java.util.Objects; @@ -61,8 +61,8 @@ public record JigsawStudioVariant( .canonicalToSourceQuarterTurns(topology); } - public IrisPosition sourceToCanonicalPosition( - IrisPosition sourcePosition, + public BlockPosition sourceToCanonicalPosition( + BlockPosition sourcePosition, JigsawStudioCellDimensions sourceDimensions ) { return rotatePosition( @@ -71,8 +71,8 @@ public record JigsawStudioVariant( sourceToCanonicalQuarterTurns()); } - public IrisPosition canonicalToSourcePosition( - IrisPosition canonicalPosition, + public BlockPosition canonicalToSourcePosition( + BlockPosition canonicalPosition, JigsawStudioCellDimensions sourceDimensions ) { JigsawStudioCellDimensions canonicalDimensions = canonicalDimensions(sourceDimensions); @@ -98,34 +98,34 @@ public record JigsawStudioVariant( return !memberships.isEmpty(); } - private static IrisPosition rotatePosition( - IrisPosition position, + private static BlockPosition rotatePosition( + BlockPosition position, JigsawStudioCellDimensions dimensions, int quarterTurns ) { - IrisPosition source = Objects.requireNonNull(position, "Jigsaw Studio variant position"); + BlockPosition source = Objects.requireNonNull(position, "Jigsaw Studio variant position"); JigsawStudioCellDimensions bounds = Objects.requireNonNull( dimensions, "Jigsaw Studio variant position bounds"); - if (source.getX() < 0 || source.getX() >= bounds.width() - || source.getY() < 0 || source.getY() >= bounds.height() - || source.getZ() < 0 || source.getZ() >= bounds.depth()) { + if (source.x() < 0 || source.x() >= bounds.width() + || source.y() < 0 || source.y() >= bounds.height() + || source.z() < 0 || source.z() >= bounds.depth()) { throw new IllegalArgumentException("Jigsaw Studio variant position is outside its object bounds"); } return switch (Math.floorMod(quarterTurns, 4)) { - case 0 -> new IrisPosition(source.getX(), source.getY(), source.getZ()); - case 1 -> new IrisPosition( - bounds.depth() - 1 - source.getZ(), - source.getY(), - source.getX()); - case 2 -> new IrisPosition( - bounds.width() - 1 - source.getX(), - source.getY(), - bounds.depth() - 1 - source.getZ()); - case 3 -> new IrisPosition( - source.getZ(), - source.getY(), - bounds.width() - 1 - source.getX()); + case 0 -> new BlockPosition(source.x(), source.y(), source.z()); + case 1 -> new BlockPosition( + bounds.depth() - 1 - source.z(), + source.y(), + source.x()); + case 2 -> new BlockPosition( + bounds.width() - 1 - source.x(), + source.y(), + bounds.depth() - 1 - source.z()); + case 3 -> new BlockPosition( + source.z(), + source.y(), + bounds.width() - 1 - source.x()); default -> throw new IllegalStateException("Unreachable Jigsaw Studio rotation"); }; } diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioVariantCatalog.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioVariantCatalog.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioVariantCatalog.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioVariantCatalog.java diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioWorkcellSpec.java b/module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioWorkcellSpec.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioWorkcellSpec.java rename to module/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioWorkcellSpec.java diff --git a/module/src/main/java/art/arcane/iris/core/service/JigsawStudioBlocks.java b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioBlocks.java new file mode 100644 index 000000000..025f661de --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioBlocks.java @@ -0,0 +1,48 @@ +package art.arcane.iris.core.service; + +import art.arcane.iris.engine.framework.structure.assembly.PieceTurn; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; + +import java.util.Set; + +/** The few block facts the studio needs, asked of api block states. */ +public final class JigsawStudioBlocks { + public static final BlockState AIR = BlockState.parse("minecraft:air"); + public static final String JIGSAW_BLOCK = "minecraft:jigsaw"; + public static final String ORIENTATION_PROPERTY = "orientation"; + private static final String CHEST_BLOCK = "minecraft:chest"; + private static final String STRUCTURE_VOID_BLOCK = "minecraft:structure_void"; + private static final Set AIR_BLOCKS = Set.of("minecraft:air", "minecraft:cave_air", "minecraft:void_air"); + + private JigsawStudioBlocks() { + } + + public static boolean isAir(BlockState state) { + return AIR_BLOCKS.contains(state.material().toString()); + } + + public static boolean isJigsaw(BlockState state) { + return JIGSAW_BLOCK.equals(state.material().toString()); + } + + public static boolean isChest(BlockState state) { + return CHEST_BLOCK.equals(state.material().toString()); + } + + public static boolean isStructureVoid(BlockState state) { + return STRUCTURE_VOID_BLOCK.equals(state.material().toString()); + } + + public static BlockState jigsawMarker(String orientation) { + return BlockState.parse(JIGSAW_BLOCK + "[" + ORIENTATION_PROPERTY + "=" + orientation + "]"); + } + + /** {@code state} turned like {@code rotation}; null when the registry cannot turn the block. */ + public static BlockState rotated(BlockRegistry registry, BlockState state, PieceTurn rotation) { + if (rotation.quarterTurns() == 0) { + return state; + } + return registry.tryRotate(state, rotation.blockTurn()).orElse(null); + } +} diff --git a/module/src/main/java/art/arcane/iris/core/service/JigsawStudioBoardContext.java b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioBoardContext.java new file mode 100644 index 000000000..f1c998233 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioBoardContext.java @@ -0,0 +1,108 @@ +package art.arcane.iris.core.service; + +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolText; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.UUID; + +public record JigsawStudioBoardContext( + UUID worldId, + UUID requestId, + String structureKey, + JigsawStudioMode mode, + String workcellRole, + String workcellName, + String variantName, + JigsawStudioBoardState state, + String controlHint +) { + private static final String SEPARATOR = "-------------------"; + private static final int SIDEBAR_LINE_CAPACITY = 11; + + public JigsawStudioBoardContext { + worldId = Objects.requireNonNull(worldId, "Jigsaw Studio board world ID"); + requestId = Objects.requireNonNull(requestId, "Jigsaw Studio board request ID"); + structureKey = requireText(structureKey, "structure key"); + mode = Objects.requireNonNull(mode, "Jigsaw Studio board mode"); + workcellRole = optionalText(workcellRole); + workcellName = optionalText(workcellName); + variantName = optionalText(variantName); + state = Objects.requireNonNull(state, "Jigsaw Studio board state"); + controlHint = optionalText(controlHint); + if (workcellName.isEmpty() && (!workcellRole.isEmpty() || !variantName.isEmpty())) { + throw new IllegalArgumentException("Jigsaw Studio board variants require a workcell"); + } + } + + public boolean insideWorkcell() { + return !workcellName.isEmpty(); + } + + /** Empty: the sidebar keeps the platform's own title. */ + public ToolText sidebarTitle() { + return ToolText.EMPTY; + } + + /** The sidebar lines for this context, top to bottom. */ + public List sidebarLines() { + List lines = new ArrayList<>(SIDEBAR_LINE_CAPACITY); + lines.add(separator()); + lines.add(ToolText.colored(TextColor.LIGHT_PURPLE, "Jigsaw Studio")); + lines.add(labelled("Structure", structureKey)); + if (!insideWorkcell()) { + lines.add(labelled("Mode", modeDisplayName())); + lines.add(separator()); + lines.add(ToolText.colored(TextColor.YELLOW, "Walk into a workcell")); + if (!controlHint.isEmpty()) { + lines.add(ToolText.colored(TextColor.GRAY, controlHint)); + } + lines.add(separator()); + return List.copyOf(lines); + } + lines.add(labelled("Workcell", workcellName)); + if (!workcellRole.isEmpty() && !workcellRole.equals(workcellName)) { + lines.add(labelled("Role", workcellRole)); + } + lines.add(labelled("Variant", variantName.isEmpty() ? "None" : variantName)); + lines.add(labelled("State", state.displayName())); + lines.add(separator()); + if (!controlHint.isEmpty()) { + lines.add(ToolText.colored(TextColor.YELLOW, controlHint)); + } + lines.add(separator()); + return List.copyOf(lines); + } + + private static ToolText separator() { + return ToolText.builder() + .append(new ToolText.Span(SEPARATOR, TextColor.GRAY, false, false, true)) + .build(); + } + + private static ToolText labelled(String label, String value) { + return ToolText.builder().aqua(label).gray(": " + value).build(); + } + + public String modeDisplayName() { + return switch (mode) { + case PLANAR_JIGSAW -> "Planar"; + case SPATIAL_JIGSAW -> "Spatial"; + }; + } + + private static String requireText(String value, String name) { + String normalized = optionalText(value); + if (normalized.isEmpty()) { + throw new IllegalArgumentException("Jigsaw Studio board " + name + " cannot be blank"); + } + return normalized; + } + + private static String optionalText(String value) { + return value == null ? "" : value.trim(); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioBoardState.java b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioBoardState.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/service/JigsawStudioBoardState.java rename to module/src/main/java/art/arcane/iris/core/service/JigsawStudioBoardState.java diff --git a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioEvaluationState.java b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioEvaluationState.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/service/JigsawStudioEvaluationState.java rename to module/src/main/java/art/arcane/iris/core/service/JigsawStudioEvaluationState.java diff --git a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioGraphEvaluation.java b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioGraphEvaluation.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/service/JigsawStudioGraphEvaluation.java rename to module/src/main/java/art/arcane/iris/core/service/JigsawStudioGraphEvaluation.java diff --git a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioHistoryStore.java b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioHistoryStore.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/service/JigsawStudioHistoryStore.java rename to module/src/main/java/art/arcane/iris/core/service/JigsawStudioHistoryStore.java diff --git a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioMarkerParser.java b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioMarkerParser.java similarity index 62% rename from core/src/main/java/art/arcane/iris/core/service/JigsawStudioMarkerParser.java rename to module/src/main/java/art/arcane/iris/core/service/JigsawStudioMarkerParser.java index 6db1db301..050d58973 100644 --- a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioMarkerParser.java +++ b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioMarkerParser.java @@ -1,11 +1,10 @@ package art.arcane.iris.core.service; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMarkerKeyCodec; -import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; -import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint; -import org.bukkit.block.Orientation; +import com.volmit.geometry.BlockPosition; import java.util.Locale; import java.util.Map; @@ -17,7 +16,7 @@ final class JigsawStudioMarkerParser { static IrisJigsawConnector parse( Map nbt, - Orientation orientation, + String orientation, int x, int y, int z @@ -32,7 +31,7 @@ final class JigsawStudioMarkerParser { throw new IllegalArgumentException("Unsupported jigsaw joint '" + jointName + "'", exception); } return new IrisJigsawConnector() - .setPosition(new IrisPosition(x, y, z)) + .setPosition(new BlockPosition(x, y, z)) .setDirection(directions.front()) .setTop(directions.top()) .setPool(JigsawStudioMarkerKeyCodec.decodePool(requiredString(properties, "pool"))) @@ -45,20 +44,23 @@ final class JigsawStudioMarkerParser { .setPlacementPriority(optionalInt(properties, "placement_priority")); } - static Directions directions(Orientation orientation) { - return switch (Objects.requireNonNull(orientation, "Jigsaw orientation")) { - case DOWN_EAST -> new Directions(IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.EAST_POSITIVE_X); - case DOWN_NORTH -> new Directions(IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.NORTH_NEGATIVE_Z); - case DOWN_SOUTH -> new Directions(IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.SOUTH_POSITIVE_Z); - case DOWN_WEST -> new Directions(IrisDirection.DOWN_NEGATIVE_Y, IrisDirection.WEST_NEGATIVE_X); - case UP_EAST -> new Directions(IrisDirection.UP_POSITIVE_Y, IrisDirection.EAST_POSITIVE_X); - case UP_NORTH -> new Directions(IrisDirection.UP_POSITIVE_Y, IrisDirection.NORTH_NEGATIVE_Z); - case UP_SOUTH -> new Directions(IrisDirection.UP_POSITIVE_Y, IrisDirection.SOUTH_POSITIVE_Z); - case UP_WEST -> new Directions(IrisDirection.UP_POSITIVE_Y, IrisDirection.WEST_NEGATIVE_X); - case WEST_UP -> new Directions(IrisDirection.WEST_NEGATIVE_X, IrisDirection.UP_POSITIVE_Y); - case EAST_UP -> new Directions(IrisDirection.EAST_POSITIVE_X, IrisDirection.UP_POSITIVE_Y); - case NORTH_UP -> new Directions(IrisDirection.NORTH_NEGATIVE_Z, IrisDirection.UP_POSITIVE_Y); - case SOUTH_UP -> new Directions(IrisDirection.SOUTH_POSITIVE_Z, IrisDirection.UP_POSITIVE_Y); + /** The front and top a jigsaw block's {@code orientation} property names, such as {@code down_east}. */ + static Directions directions(String orientation) { + String name = Objects.requireNonNull(orientation, "Jigsaw orientation").toLowerCase(Locale.ROOT); + return switch (name) { + case "down_east" -> new Directions(JigsawDirection.DOWN_NEGATIVE_Y, JigsawDirection.EAST_POSITIVE_X); + case "down_north" -> new Directions(JigsawDirection.DOWN_NEGATIVE_Y, JigsawDirection.NORTH_NEGATIVE_Z); + case "down_south" -> new Directions(JigsawDirection.DOWN_NEGATIVE_Y, JigsawDirection.SOUTH_POSITIVE_Z); + case "down_west" -> new Directions(JigsawDirection.DOWN_NEGATIVE_Y, JigsawDirection.WEST_NEGATIVE_X); + case "up_east" -> new Directions(JigsawDirection.UP_POSITIVE_Y, JigsawDirection.EAST_POSITIVE_X); + case "up_north" -> new Directions(JigsawDirection.UP_POSITIVE_Y, JigsawDirection.NORTH_NEGATIVE_Z); + case "up_south" -> new Directions(JigsawDirection.UP_POSITIVE_Y, JigsawDirection.SOUTH_POSITIVE_Z); + case "up_west" -> new Directions(JigsawDirection.UP_POSITIVE_Y, JigsawDirection.WEST_NEGATIVE_X); + case "west_up" -> new Directions(JigsawDirection.WEST_NEGATIVE_X, JigsawDirection.UP_POSITIVE_Y); + case "east_up" -> new Directions(JigsawDirection.EAST_POSITIVE_X, JigsawDirection.UP_POSITIVE_Y); + case "north_up" -> new Directions(JigsawDirection.NORTH_NEGATIVE_Z, JigsawDirection.UP_POSITIVE_Y); + case "south_up" -> new Directions(JigsawDirection.SOUTH_POSITIVE_Z, JigsawDirection.UP_POSITIVE_Y); + default -> throw new IllegalArgumentException("Unsupported jigsaw orientation '" + orientation + "'"); }; } @@ -96,7 +98,7 @@ final class JigsawStudioMarkerParser { return (int) longValue; } - record Directions(IrisDirection front, IrisDirection top) { + record Directions(JigsawDirection front, JigsawDirection top) { Directions { Objects.requireNonNull(front, "Jigsaw front direction"); Objects.requireNonNull(top, "Jigsaw top direction"); diff --git a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuController.java b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuController.java similarity index 69% rename from core/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuController.java rename to module/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuController.java index f1028b0ef..9faa40447 100644 --- a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuController.java +++ b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuController.java @@ -6,17 +6,9 @@ import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioPieceRules; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolAction; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolPayload; -import art.arcane.iris.util.common.scheduling.J; -import art.arcane.volmlib.util.data.MaterialBlock; -import art.arcane.volmlib.util.inventorygui.UIElement; -import art.arcane.volmlib.util.inventorygui.UIPaneDecorator; -import art.arcane.volmlib.util.inventorygui.UIWindow; -import art.arcane.volmlib.util.inventorygui.WindowResolution; -import art.arcane.volmlib.util.plugin.ComponentMessenger; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.plugin.java.JavaPlugin; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolText; import java.util.ArrayList; import java.util.List; @@ -26,6 +18,7 @@ import java.util.Objects; import java.util.Optional; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; public final class JigsawStudioMenuController { static final int VARIANTS_PER_PAGE = 28; @@ -40,38 +33,42 @@ public final class JigsawStudioMenuController { private static final int WORKCELL_RESIZE_REFRESH_TICKS = 2; private static final int WORKCELL_RESIZE_REFRESH_ATTEMPTS = 200; private static final int[] GRID_POSITIONS = {-3, -2, -1, 0, 1, 2, 3}; + private static final Pattern LEGACY_COLOR = Pattern.compile("(?i)\\u00a7[0-9A-FK-ORX]"); + private static final int CLOSE_AFTER_ACTION_TICKS = 1; + private static final int RIGHT_CLICK_OPEN_DELAY_TICKS = 1; + private static final int DETAILS_REFRESH_DELAY_TICKS = 1; - private final JavaPlugin plugin; private final Actions actions; - private final Map windows = new ConcurrentHashMap<>(); + private final JigsawStudioScheduler scheduler; + private final Map windows = new ConcurrentHashMap<>(); private final Map pendingUnlinks = new ConcurrentHashMap<>(); private final Map pendingDeletes = new ConcurrentHashMap<>(); private final Map pendingProjectDeletes = new ConcurrentHashMap<>(); private final Map pendingWorkcellResizes = new ConcurrentHashMap<>(); - public JigsawStudioMenuController(JavaPlugin plugin, Actions actions) { - this.plugin = Objects.requireNonNull(plugin, "Jigsaw Studio menu plugin"); + public JigsawStudioMenuController(Actions actions, JigsawStudioScheduler scheduler) { this.actions = Objects.requireNonNull(actions, "Jigsaw Studio menu actions"); + this.scheduler = Objects.requireNonNull(scheduler, "Jigsaw Studio menu scheduler"); } - public boolean open(Player player) { + public boolean open(ToolPlayer player) { if (player == null) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> open(player)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> open(player)); } Optional available = actions.menuState(player); if (available.isEmpty()) { close(player); - send(player, ChatColor.RED + "Iris Jigsaw Studio is not active in this world."); + sendError(player, "Iris Jigsaw Studio is not active in this world."); return false; } JigsawStudioMenuState state = available.get(); if (state.workcells().isEmpty()) { close(player); - send(player, ChatColor.RED + "This Jigsaw Studio has no workcells."); + sendError(player, "This Jigsaw Studio has no workcells."); return false; } @@ -93,13 +90,11 @@ public final class JigsawStudioMenuController { } close(player); - UUID playerId = player.getUniqueId(); - UIWindow window = new UIWindow(plugin, player); - window.setResolution(WindowResolution.W9_H6); + UUID playerId = player.id(); + JigsawStudioMenuWindow window = new JigsawStudioMenuWindow(player); window.setViewportHeight(6); - window.setDecorator(new UIPaneDecorator(Material.BLACK_STAINED_GLASS_PANE)); window.setTitle(title(state.structureKey())); - window.onClosed(closed -> { + window.onClosed(() -> { windows.remove(playerId, window); pendingUnlinks.remove(playerId); pendingDeletes.remove(playerId); @@ -116,12 +111,12 @@ public final class JigsawStudioMenuController { return true; } - public boolean openWorkcellSettings(Player player, String workcellId) { + public boolean openWorkcellSettings(ToolPlayer player, String workcellId) { if (player == null || workcellId == null || workcellId.isBlank()) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> openWorkcellSettings(player, workcellId)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> openWorkcellSettings(player, workcellId)); } if (!open(player)) { return false; @@ -135,7 +130,7 @@ public final class JigsawStudioMenuController { return true; } - public boolean openVariantSettings(Player player, String workcellId, String pieceKey) { + public boolean openVariantSettings(ToolPlayer player, String workcellId, String pieceKey) { if (player == null || workcellId == null || workcellId.isBlank() @@ -143,8 +138,8 @@ public final class JigsawStudioMenuController { || pieceKey.isBlank()) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> openVariantSettings(player, workcellId, pieceKey)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> openVariantSettings(player, workcellId, pieceKey)); } if (!open(player)) { return false; @@ -161,8 +156,7 @@ public final class JigsawStudioMenuController { return false; } if (!current.get().irisExtended()) { - send(player, ChatColor.YELLOW - + "Vanilla-portable pieces cannot encode Iris theme or piece-rule metadata."); + send(player, "Vanilla-portable pieces cannot encode Iris theme or piece-rule metadata."); close(player); return false; } @@ -170,13 +164,13 @@ public final class JigsawStudioMenuController { return true; } - public boolean openVariantSizeSettings(Player player, String workcellId, String pieceKey) { + public boolean openVariantSizeSettings(ToolPlayer player, String workcellId, String pieceKey) { if (player == null || workcellId == null || workcellId.isBlank() || pieceKey == null || pieceKey.isBlank()) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> openVariantSizeSettings(player, workcellId, pieceKey)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> openVariantSizeSettings(player, workcellId, pieceKey)); } if (!open(player)) { return false; @@ -192,7 +186,7 @@ public final class JigsawStudioMenuController { stale(player); return false; } - UIWindow window = windows.get(player.getUniqueId()); + JigsawStudioMenuWindow window = windows.get(player.id()); if (window == null) { return false; } @@ -200,12 +194,12 @@ public final class JigsawStudioMenuController { return true; } - public boolean openStructureSettings(Player player) { + public boolean openStructureSettings(ToolPlayer player) { if (player == null) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> openStructureSettings(player)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> openStructureSettings(player)); } if (!open(player)) { return false; @@ -223,44 +217,35 @@ public final class JigsawStudioMenuController { return true; } - public void close(Player player) { + public void close(ToolPlayer player) { if (player == null) { return; } - UUID playerId = player.getUniqueId(); - UIWindow window = windows.remove(playerId); + UUID playerId = player.id(); + JigsawStudioMenuWindow window = windows.remove(playerId); pendingUnlinks.remove(playerId); pendingDeletes.remove(playerId); pendingProjectDeletes.remove(playerId); if (window == null) { return; } - if (J.isOwnedByCurrentRegion(player)) { - window.close(); - return; - } - J.runEntity(player, window::close); + JigsawStudioThreads.run(player, window::close); } public void closeAll() { - List activeWindows = new ArrayList<>(windows.values()); + List activeWindows = new ArrayList<>(windows.values()); windows.clear(); pendingUnlinks.clear(); pendingDeletes.clear(); pendingProjectDeletes.clear(); pendingWorkcellResizes.clear(); - for (UIWindow window : activeWindows) { - Player player = window.getViewer(); - if (J.isOwnedByCurrentRegion(player)) { - window.close(); - } else { - J.runEntity(player, window::close); - } + for (JigsawStudioMenuWindow window : activeWindows) { + JigsawStudioThreads.run(window.getViewer(), window::close); } } private void renderMain( - UIWindow window, + JigsawStudioMenuWindow window, JigsawStudioMenuState state, JigsawStudioMenuState.Workcell selected, int requestedPage @@ -276,49 +261,49 @@ public final class JigsawStudioMenuController { }); } - private void addFamilyControl(UIWindow window, JigsawStudioMenuState state) { + private void addFamilyControl(JigsawStudioMenuWindow window, JigsawStudioMenuState state) { String nextThemeKey = nextThemeSetKey(state.themeSets()); boolean available = state.irisExtended() && state.workcells().stream() .filter(JigsawStudioMenuState.Workcell::enabled) .allMatch(workcell -> workcell.activeVariant() != null && workcell.activeVariant().owned()); - UIElement family = element( + JigsawStudioMenuElement family = element( "duplicate-family", - available ? Material.PURPLE_DYE : Material.GRAY_DYE, + available ? JigsawStudioMenuIcon.PURPLE_DYE : JigsawStudioMenuIcon.GRAY_DYE, available - ? ChatColor.LIGHT_PURPLE + "Duplicate All Enabled Cells as Family" - : ChatColor.GRAY + "Duplicate All Enabled Cells as Family"); - family.addLore(ChatColor.GRAY + "Copies each enabled cell's loaded variant into one coherent family."); - family.addLore(ChatColor.GRAY + "New family: " + safe(nextThemeKey)); + ? lightPurple("Duplicate All Enabled Cells as Family") + : gray("Duplicate All Enabled Cells as Family")); + family.addLore(gray("Copies each enabled cell's loaded variant into one coherent family.")); + family.addLore(gray("New family: " + safe(nextThemeKey))); if (available) { - family.addLore(ChatColor.YELLOW + "Left-click to duplicate the complete family atomically"); + family.addLore(yellow("Left-click to duplicate the complete family atomically")); family.onLeftClick(clicked -> duplicateActiveFamily( window.getViewer(), state.requestId(), nextThemeKey)); } else if (!state.irisExtended()) { - family.addLore(ChatColor.GRAY + "Coherent families require Iris compatibility."); + family.addLore(gray("Coherent families require Iris compatibility.")); } else { - family.addLore(ChatColor.GRAY + "Load an owned variant in every enabled workcell first."); + family.addLore(gray("Load an owned variant in every enabled workcell first.")); } window.setElement(3, 0, family); } private void addStructureControl( - UIWindow window, + JigsawStudioMenuWindow window, JigsawStudioMenuState state, String selectedWorkcellId ) { - UIElement structure = element( + JigsawStudioMenuElement structure = element( "structure-rules", state.irisExtended() - ? state.requireCaps() ? Material.IRON_BARS : Material.TRIPWIRE_HOOK - : Material.BARRIER, - ChatColor.LIGHT_PURPLE + "Structure Rules"); - structure.addLore(ChatColor.GRAY + "Mandatory caps: " + yesNo(state.requireCaps())); - structure.addLore(ChatColor.GRAY + "Theme sets: " + state.themeSets().size()); - structure.addLore(ChatColor.GRAY + "Compatibility: " + compatibilityName(state.compatibilityTarget())); - structure.addLore(ChatColor.YELLOW + "Left-click for themes and rules"); + ? state.requireCaps() ? JigsawStudioMenuIcon.IRON_BARS : JigsawStudioMenuIcon.TRIPWIRE_HOOK + : JigsawStudioMenuIcon.BARRIER, + lightPurple("Structure Rules")); + structure.addLore(gray("Mandatory caps: " + yesNo(state.requireCaps()))); + structure.addLore(gray("Theme sets: " + state.themeSets().size())); + structure.addLore(gray("Compatibility: " + compatibilityName(state.compatibilityTarget()))); + structure.addLore(yellow("Left-click for themes and rules")); structure.addLore(state.irisExtended() - ? ChatColor.YELLOW + "Right-click to toggle mandatory caps" - : ChatColor.GRAY + "Mandatory caps and themes require Iris compatibility"); + ? yellow("Right-click to toggle mandatory caps") + : gray("Mandatory caps and themes require Iris compatibility")); structure.onLeftClick(clicked -> openStructureSettings( window.getViewer(), state.requestId(), selectedWorkcellId, 0)); if (state.irisExtended()) { @@ -328,36 +313,37 @@ public final class JigsawStudioMenuController { window.setElement(4, 0, structure); } - private void addWorkcells(UIWindow window, JigsawStudioMenuState state, String selectedWorkcellId) { + private void addWorkcells(JigsawStudioMenuWindow window, JigsawStudioMenuState state, String selectedWorkcellId) { int count = state.workcells().size(); int start = count == 1 ? 0 : -(count / 2); for (int index = 0; index < count; index++) { JigsawStudioMenuState.Workcell workcell = state.workcells().get(index); boolean selected = workcell.stableId().equals(selectedWorkcellId); - UIElement element = element( + JigsawStudioMenuElement element = element( "workcell-" + index, workcellMaterial(workcell, selected), - (selected ? ChatColor.AQUA : workcell.enabled() ? ChatColor.WHITE : ChatColor.GRAY) - + safe(workcell.displayName())) + ToolText.colored( + selected ? TextColor.AQUA : workcell.enabled() ? TextColor.WHITE : TextColor.GRAY, + safe(workcell.displayName()))) .setEnchanted(selected); element.addLore(workcell.enabled() - ? ChatColor.GREEN + "Enabled" - : ChatColor.RED + "Disabled for assembly and export"); + ? green("Enabled") + : red("Disabled for assembly and export")); if (!workcell.canonicalName().equals(workcell.displayName())) { - element.addLore(ChatColor.GRAY + "Solver role: " + safe(workcell.canonicalName())); + element.addLore(gray("Solver role: " + safe(workcell.canonicalName()))); } - element.addLore(ChatColor.GRAY + "Capacity: " + dimensions(workcell.capacity())); - element.addLore(ChatColor.GRAY + "Variants: " + workcell.variants().size()); + element.addLore(gray("Capacity: " + dimensions(workcell.capacity()))); + element.addLore(gray("Variants: " + workcell.variants().size())); JigsawStudioMenuState.Variant active = workcell.activeVariant(); - element.addLore(ChatColor.GRAY + "Loaded: " - + (active == null ? "None" : safe(active.displayName()))); + element.addLore(gray("Loaded: " + + (active == null ? "None" : safe(active.displayName())))); element.addLore(workcellStatus(workcell)); - element.addLore(ChatColor.GRAY + "Connector blocks: " - + (workcell.connectorsVisible() ? "Visible" : "Hidden")); - element.addLore(ChatColor.YELLOW + "Left-click to select and teleport"); - element.addLore(ChatColor.YELLOW + "Right-click for workcell settings"); + element.addLore(gray("Connector blocks: " + + (workcell.connectorsVisible() ? "Visible" : "Hidden"))); + element.addLore(yellow("Left-click to select and teleport")); + element.addLore(yellow("Right-click for workcell settings")); if (workcell.dirty() && !workcell.saving()) { - element.addLore(ChatColor.GOLD + "Shift-left: Flush Autosave Now"); + element.addLore(gold("Shift-left: Flush Autosave Now")); element.onShiftLeftClick(clicked -> flushNow( window.getViewer(), state.requestId(), workcell.stableId())); } @@ -365,19 +351,20 @@ public final class JigsawStudioMenuController { window.getViewer(), state.requestId(), workcell.stableId())); - element.onRightClick(clicked -> J.runEntity( + element.onRightClick(clicked -> scheduler.onPlayerLater( window.getViewer(), () -> openWorkcellSettings( window.getViewer(), state.requestId(), workcell.stableId()), - 1)); + RIGHT_CLICK_OPEN_DELAY_TICKS, + () -> { })); window.setElement(start + index, 0, element); } } private void addVariants( - UIWindow window, + JigsawStudioMenuWindow window, JigsawStudioMenuState state, JigsawStudioMenuState.Workcell workcell, int page @@ -385,8 +372,8 @@ public final class JigsawStudioMenuController { List variants = page( workcell.variants(), page, VARIANTS_PER_PAGE); if (variants.isEmpty()) { - UIElement empty = element("no-variants", Material.BARRIER, ChatColor.RED + "No variants"); - empty.addLore(ChatColor.GRAY + "Create a variant to begin authoring this workcell."); + JigsawStudioMenuElement empty = element("no-variants", JigsawStudioMenuIcon.BARRIER, red("No variants")); + empty.addLore(gray("Create a variant to begin authoring this workcell.")); window.setElement(0, 2, empty); return; } @@ -395,35 +382,36 @@ public final class JigsawStudioMenuController { JigsawStudioMenuState.Variant variant = variants.get(index); int position = GRID_POSITIONS[index % GRID_POSITIONS.length]; int row = 1 + index / GRID_POSITIONS.length; - UIElement element = element( + JigsawStudioMenuElement element = element( "variant-" + index, variantMaterial(variant), - (variant.active() ? ChatColor.GREEN : ChatColor.WHITE) - + safe(variant.displayName()) - + (variant.active() ? ChatColor.AQUA + " [Loaded]" : "")) + ToolText.builder() + .append(variant.active() ? TextColor.GREEN : TextColor.WHITE, safe(variant.displayName())) + .aqua(variant.active() ? " [Loaded]" : "") + .build()) .setEnchanted(variant.active()); - element.addLore(ChatColor.DARK_GRAY + safe(variant.pieceKey())); + element.addLore(darkGray(safe(variant.pieceKey()))); element.addLore(variant.owned() - ? ChatColor.GREEN + "Owned" - : ChatColor.GRAY + "Read-only"); - element.addLore(ChatColor.GRAY + "Rotation: " + (variant.rotatable() ? "Enabled" : "Disabled")); - element.addLore(ChatColor.GRAY + "Size: " + variant.dimensions() + ? green("Owned") + : gray("Read-only")); + element.addLore(gray("Rotation: " + (variant.rotatable() ? "Enabled" : "Disabled"))); + element.addLore(gray("Size: " + variant.dimensions() .map(JigsawStudioMenuController::dimensions) - .orElse("Object missing")); - element.addLore(ChatColor.GRAY + "Themes: " + themes(variant.themes())); - element.addLore(ChatColor.GRAY + "Pool entries: " + variant.memberships().size()); - element.addLore(variant.active() - ? ChatColor.YELLOW + "Loaded; right-click for details" - : ChatColor.YELLOW + "Left-click to load"); + .orElse("Object missing"))); + element.addLore(gray("Themes: " + themes(variant.themes()))); + element.addLore(gray("Pool entries: " + variant.memberships().size())); + element.addLore(yellow(variant.active() + ? "Loaded; right-click for details" + : "Left-click to load")); if (!variant.active()) { - element.addLore(ChatColor.YELLOW + "Right-click for details or deletion"); + element.addLore(yellow("Right-click for details or deletion")); } element.onLeftClick(clicked -> switchVariant( window.getViewer(), state.requestId(), workcell.stableId(), variant.pieceKey())); - element.onRightClick(clicked -> J.runEntity( + element.onRightClick(clicked -> scheduler.onPlayerLater( window.getViewer(), () -> openDetails( window.getViewer(), @@ -431,66 +419,65 @@ public final class JigsawStudioMenuController { workcell.stableId(), variant.pieceKey(), 0), - 1)); + RIGHT_CLICK_OPEN_DELAY_TICKS, + () -> { })); window.setElement(position, row, element); } } private void addMainActions( - UIWindow window, + JigsawStudioMenuWindow window, JigsawStudioMenuState state, JigsawStudioMenuState.Workcell workcell, int page ) { - UIElement create = element("create", Material.NETHER_STAR, ChatColor.GREEN + "New Blank Variant"); - create.addLore(ChatColor.GRAY + "Create an empty owned variant with this cell's current size."); + JigsawStudioMenuElement create = element("create", JigsawStudioMenuIcon.NETHER_STAR, green("New Blank Variant")); + create.addLore(gray("Create an empty owned variant with this cell's current size.")); create.onLeftClick(clicked -> createVariant( window.getViewer(), state.requestId(), workcell.stableId(), false)); window.setElement(-4, 5, create); JigsawStudioMenuState.Variant active = workcell.activeVariant(); boolean duplicateAvailable = active != null && active.owned(); - UIElement duplicate = element( + JigsawStudioMenuElement duplicate = element( "duplicate", - duplicateAvailable ? Material.PAPER : Material.GRAY_DYE, + duplicateAvailable ? JigsawStudioMenuIcon.PAPER : JigsawStudioMenuIcon.GRAY_DYE, duplicateAvailable - ? ChatColor.AQUA + "Duplicate This Cell's Variant" - : active == null - ? ChatColor.GRAY + "Duplicate This Cell's Variant" - : ChatColor.GRAY + "Duplicate This Cell's Variant"); - duplicate.addLore(duplicateAvailable - ? ChatColor.GRAY + "Clone the loaded variant into an owned variant." + ? aqua("Duplicate This Cell's Variant") + : gray("Duplicate This Cell's Variant")); + duplicate.addLore(gray(duplicateAvailable + ? "Clone the loaded variant into an owned variant." : active == null - ? ChatColor.GRAY + "Load a variant before duplicating it." - : ChatColor.GRAY + "Adopt the read-only graph before duplicating it."); + ? "Load a variant before duplicating it." + : "Adopt the read-only graph before duplicating it.")); if (duplicateAvailable) { duplicate.onLeftClick(clicked -> createVariant( window.getViewer(), state.requestId(), workcell.stableId(), true)); } window.setElement(-3, 5, duplicate); - UIElement settings = element("settings", Material.CRAFTING_TABLE, ChatColor.GOLD + "Workcell Settings"); - settings.addLore(ChatColor.GRAY + "Enabled: " + yesNo(workcell.enabled())); - settings.addLore(ChatColor.GRAY + "Capacity: " + dimensions(workcell.capacity())); + JigsawStudioMenuElement settings = element("settings", JigsawStudioMenuIcon.CRAFTING_TABLE, gold("Workcell Settings")); + settings.addLore(gray("Enabled: " + yesNo(workcell.enabled()))); + settings.addLore(gray("Capacity: " + dimensions(workcell.capacity()))); settings.onLeftClick(clicked -> openWorkcellSettings( window.getViewer(), state.requestId(), workcell.stableId())); window.setElement(-2, 5, settings); int pageCount = pageCount(workcell.variants().size(), VARIANTS_PER_PAGE); if (page > 0) { - UIElement previous = element("previous", Material.ARROW, ChatColor.YELLOW + "Previous Page"); + JigsawStudioMenuElement previous = element("previous", JigsawStudioMenuIcon.ARROW, yellow("Previous Page")); previous.onLeftClick(clicked -> refreshMain( window.getViewer(), state.requestId(), workcell.stableId(), page - 1)); window.setElement(-1, 5, previous); } - UIElement pageIndicator = element("page", Material.BOOK, ChatColor.WHITE + "Page " - + (page + 1) + "/" + pageCount); - pageIndicator.addLore(ChatColor.GRAY + "" + workcell.variants().size() + " variants"); + JigsawStudioMenuElement pageIndicator = element("page", JigsawStudioMenuIcon.BOOK, white("Page " + + (page + 1) + "/" + pageCount)); + pageIndicator.addLore(gray("" + workcell.variants().size() + " variants")); window.setElement(0, 5, pageIndicator); if (page + 1 < pageCount) { - UIElement next = element("next", Material.ARROW, ChatColor.YELLOW + "Next Page"); + JigsawStudioMenuElement next = element("next", JigsawStudioMenuIcon.ARROW, yellow("Next Page")); next.onLeftClick(clicked -> refreshMain( window.getViewer(), state.requestId(), workcell.stableId(), page + 1)); window.setElement(1, 5, next); @@ -498,25 +485,25 @@ public final class JigsawStudioMenuController { window.setElement(2, 5, evaluationElement(state.evaluation())); - UIElement preview = element("preview", Material.ENDER_EYE, ChatColor.LIGHT_PURPLE + "Go to Preview"); - preview.addLore(ChatColor.GRAY + "Open the deterministic assembly preview."); + JigsawStudioMenuElement preview = element("preview", JigsawStudioMenuIcon.ENDER_EYE, lightPurple("Go to Preview")); + preview.addLore(gray("Open the deterministic assembly preview.")); preview.onLeftClick(clicked -> goToPreview(window.getViewer(), state.requestId())); window.setElement(3, 5, preview); - UIElement toolbox = element("toolbox", Material.STICK, ChatColor.AQUA + "Toolbox"); - toolbox.addLore(ChatColor.GRAY + "Take named sticks bound to this Studio session."); + JigsawStudioMenuElement toolbox = element("toolbox", JigsawStudioMenuIcon.STICK, aqua("Toolbox")); + toolbox.addLore(gray("Take named sticks bound to this Studio session.")); toolbox.onLeftClick(clicked -> openToolbox( window.getViewer(), state.requestId(), workcell.stableId(), 0)); window.setElement(4, 5, toolbox); } private void renderWorkcellSettings( - UIWindow window, + JigsawStudioMenuWindow window, JigsawStudioMenuState state, JigsawStudioMenuState.Workcell workcell ) { PendingWorkcellResize pendingResize = pendingWorkcellResize( - window.getViewer().getUniqueId(), + window.getViewer().id(), state.requestId(), workcell.stableId()); JigsawStudioMenuState.Workcell renderedWorkcell = pendingResize == null @@ -525,31 +512,31 @@ public final class JigsawStudioMenuController { window.batch(() -> { window.clearElements(); - UIElement back = element("settings-back", Material.ARROW, ChatColor.YELLOW + "Back to Variants"); + JigsawStudioMenuElement back = element("settings-back", JigsawStudioMenuIcon.ARROW, yellow("Back to Variants")); back.onLeftClick(clicked -> leaveWorkcellSettings( window.getViewer(), state.requestId(), renderedWorkcell.stableId())); window.setElement(-4, 0, back); - UIElement identity = element( + JigsawStudioMenuElement identity = element( "settings-identity", - renderedWorkcell.enabled() ? Material.LIME_WOOL : Material.GRAY_WOOL, - ChatColor.AQUA + safe(renderedWorkcell.displayName())); - identity.addLore(ChatColor.DARK_GRAY + safe(renderedWorkcell.stableId())); + renderedWorkcell.enabled() ? JigsawStudioMenuIcon.LIME_WOOL : JigsawStudioMenuIcon.GRAY_WOOL, + aqua(safe(renderedWorkcell.displayName()))); + identity.addLore(darkGray(safe(renderedWorkcell.stableId()))); identity.addLore(renderedWorkcell.enabled() - ? ChatColor.GREEN + "Enabled" - : ChatColor.RED + "Disabled for assembly and export"); + ? green("Enabled") + : red("Disabled for assembly and export")); if (!renderedWorkcell.canonicalName().equals(renderedWorkcell.displayName())) { - identity.addLore(ChatColor.GRAY + "Solver role: " + safe(renderedWorkcell.canonicalName())); + identity.addLore(gray("Solver role: " + safe(renderedWorkcell.canonicalName()))); } - identity.addLore(ChatColor.GRAY + "Capacity: " + dimensions(renderedWorkcell.capacity())); + identity.addLore(gray("Capacity: " + dimensions(renderedWorkcell.capacity()))); if (pendingResize != null) { identity.addLore(pendingResize.applying() - ? ChatColor.YELLOW + "Applying one live relayout" - : ChatColor.GOLD + "Pending; apply when all dimensions are ready"); + ? yellow("Applying one live relayout") + : gold("Pending; apply when all dimensions are ready")); } - identity.addLore(ChatColor.YELLOW + "Left-click for a rename stick"); - identity.addLore(ChatColor.GRAY + "Rename that stick in an anvil, then right-click it."); - identity.addLore(ChatColor.GRAY + "Sneak-right-click the stick to reset this label."); + identity.addLore(yellow("Left-click for a rename stick")); + identity.addLore(gray("Rename that stick in an anvil, then right-click it.")); + identity.addLore(gray("Sneak-right-click the stick to reset this label.")); identity.onLeftClick(clicked -> actions.giveTool( window.getViewer(), JigsawStudioToolPayload.workcell( @@ -560,15 +547,15 @@ public final class JigsawStudioMenuController { window.setElement(4, 0, evaluationElement(state.evaluation())); if (state.mode() == JigsawStudioMode.PLANAR_JIGSAW) { - UIElement enabled = element( + JigsawStudioMenuElement enabled = element( "settings-enabled", - renderedWorkcell.enabled() ? Material.LEVER : Material.REDSTONE_TORCH, + renderedWorkcell.enabled() ? JigsawStudioMenuIcon.LEVER : JigsawStudioMenuIcon.REDSTONE_TORCH, renderedWorkcell.enabled() - ? ChatColor.GREEN + "Workcell Enabled" - : ChatColor.RED + "Workcell Disabled"); - enabled.addLore(ChatColor.GRAY + "Disabled workcells remain editable and keep their size."); - enabled.addLore(ChatColor.YELLOW + "Left-click to " - + (renderedWorkcell.enabled() ? "disable" : "enable")); + ? green("Workcell Enabled") + : red("Workcell Disabled")); + enabled.addLore(gray("Disabled workcells remain editable and keep their size.")); + enabled.addLore(yellow("Left-click to " + + (renderedWorkcell.enabled() ? "disable" : "enable"))); enabled.onLeftClick(clicked -> setWorkcellEnabled( window.getViewer(), state.requestId(), @@ -576,24 +563,24 @@ public final class JigsawStudioMenuController { !renderedWorkcell.enabled())); window.setElement(0, 1, enabled); } else { - UIElement spatial = element( + JigsawStudioMenuElement spatial = element( "spatial-bounds", - Material.SCAFFOLDING, - ChatColor.AQUA + "Spatial Workcell Bounds"); - spatial.addLore(ChatColor.GRAY + "Spatial project bounds are shared by the project."); - spatial.addLore(ChatColor.GRAY + "Changing them regenerates the Studio layout."); + JigsawStudioMenuIcon.SCAFFOLDING, + aqua("Spatial Workcell Bounds")); + spatial.addLore(gray("Spatial project bounds are shared by the project.")); + spatial.addLore(gray("Changing them regenerates the Studio layout.")); window.setElement(0, 1, spatial); } - UIElement connectors = element( + JigsawStudioMenuElement connectors = element( "settings-connectors", - renderedWorkcell.connectorsVisible() ? Material.JIGSAW : Material.STRUCTURE_VOID, + renderedWorkcell.connectorsVisible() ? JigsawStudioMenuIcon.JIGSAW : JigsawStudioMenuIcon.STRUCTURE_VOID, renderedWorkcell.connectorsVisible() - ? ChatColor.GREEN + "Connector Blocks Visible" - : ChatColor.YELLOW + "Connector Blocks Hidden"); - connectors.addLore(ChatColor.GRAY + "Hidden connectors retain their metadata and final block state."); - connectors.addLore(ChatColor.YELLOW + "Left-click to " - + (renderedWorkcell.connectorsVisible() ? "hide" : "show") + " connector blocks"); + ? green("Connector Blocks Visible") + : yellow("Connector Blocks Hidden")); + connectors.addLore(gray("Hidden connectors retain their metadata and final block state.")); + connectors.addLore(yellow("Left-click to " + + (renderedWorkcell.connectorsVisible() ? "hide" : "show") + " connector blocks")); connectors.onLeftClick(clicked -> toggleConnectorBlocks( window.getViewer(), state.requestId(), @@ -601,12 +588,12 @@ public final class JigsawStudioMenuController { !renderedWorkcell.connectorsVisible())); window.setElement(2, 1, connectors); - UIElement resetConnectors = element( + JigsawStudioMenuElement resetConnectors = element( "settings-reset-connectors", - Material.RECOVERY_COMPASS, - ChatColor.AQUA + "Reset Connector Blocks"); - resetConnectors.addLore(ChatColor.GRAY + "Restore every connector in this workcell from disk."); - resetConnectors.addLore(ChatColor.GRAY + "Other edited blocks are left unchanged."); + JigsawStudioMenuIcon.RECOVERY_COMPASS, + aqua("Reset Connector Blocks")); + resetConnectors.addLore(gray("Restore every connector in this workcell from disk.")); + resetConnectors.addLore(gray("Other edited blocks are left unchanged.")); resetConnectors.onLeftClick(clicked -> resetConnectorBlocks( window.getViewer(), state.requestId(), @@ -618,29 +605,29 @@ public final class JigsawStudioMenuController { state, renderedWorkcell, DimensionAxis.WIDTH, - Material.IRON_INGOT)); + JigsawStudioMenuIcon.IRON_INGOT)); window.setElement(0, 2, axisElement( window, state, renderedWorkcell, DimensionAxis.HEIGHT, - Material.GOLD_INGOT)); + JigsawStudioMenuIcon.GOLD_INGOT)); window.setElement(2, 2, axisElement( window, state, renderedWorkcell, DimensionAxis.DEPTH, - Material.COPPER_INGOT)); + JigsawStudioMenuIcon.COPPER_INGOT)); if (pendingResize != null) { - UIElement apply = element( + JigsawStudioMenuElement apply = element( "settings-apply-capacity", - pendingResize.applying() ? Material.CLOCK : Material.EMERALD_BLOCK, + pendingResize.applying() ? JigsawStudioMenuIcon.CLOCK : JigsawStudioMenuIcon.EMERALD_BLOCK, pendingResize.applying() - ? ChatColor.YELLOW + "Applying Cell Size" - : ChatColor.GREEN + "Apply Cell Size"); - apply.addLore(ChatColor.WHITE + dimensions(pendingResize.dimensions())); - apply.addLore(ChatColor.GRAY + "Regenerates the layout once after all size edits."); + ? yellow("Applying Cell Size") + : green("Apply Cell Size")); + apply.addLore(white(dimensions(pendingResize.dimensions()))); + apply.addLore(gray("Regenerates the layout once after all size edits.")); if (!pendingResize.applying()) { apply.onLeftClick(clicked -> applyWorkcellResize( window.getViewer(), state.requestId(), renderedWorkcell.stableId())); @@ -648,52 +635,52 @@ public final class JigsawStudioMenuController { window.setElement(0, 3, apply); if (!pendingResize.applying()) { - UIElement discard = element( + JigsawStudioMenuElement discard = element( "settings-discard-capacity", - Material.BARRIER, - ChatColor.RED + "Discard Size Changes"); + JigsawStudioMenuIcon.BARRIER, + red("Discard Size Changes")); discard.onLeftClick(clicked -> discardWorkcellResize( window.getViewer(), state.requestId(), renderedWorkcell.stableId())); window.setElement(2, 3, discard); } } - UIElement footerBack = element("settings-footer-back", Material.ARROW, ChatColor.YELLOW + "Back"); + JigsawStudioMenuElement footerBack = element("settings-footer-back", JigsawStudioMenuIcon.ARROW, yellow("Back")); footerBack.onLeftClick(clicked -> leaveWorkcellSettings( window.getViewer(), state.requestId(), renderedWorkcell.stableId())); window.setElement(-4, 5, footerBack); - UIElement undo = element( + JigsawStudioMenuElement undo = element( "settings-undo", - Material.CLOCK, - ChatColor.LIGHT_PURPLE + "Undo Last Autosave"); - undo.addLore(ChatColor.GRAY + "Restore the previous owned graph iteration."); - undo.addLore(ChatColor.GRAY + "Up to five autosave iterations are retained on disk."); + JigsawStudioMenuIcon.CLOCK, + lightPurple("Undo Last Autosave")); + undo.addLore(gray("Restore the previous owned graph iteration.")); + undo.addLore(gray("Up to five autosave iterations are retained on disk.")); undo.onLeftClick(clicked -> undoAutosave( window.getViewer(), state.requestId())); window.setElement(0, 5, undo); if (renderedWorkcell.dirty() && !renderedWorkcell.saving()) { - UIElement saveNow = element( + JigsawStudioMenuElement saveNow = element( "save-now", - Material.EMERALD, - ChatColor.GOLD + "Flush Autosave Now"); - saveNow.addLore(ChatColor.GRAY + "Autosave is automatic."); - saveNow.addLore(ChatColor.GRAY + "Use this only to flush pending work or recover immediately."); + JigsawStudioMenuIcon.EMERALD, + gold("Flush Autosave Now")); + saveNow.addLore(gray("Autosave is automatic.")); + saveNow.addLore(gray("Use this only to flush pending work or recover immediately.")); saveNow.onLeftClick(clicked -> flushNow( window.getViewer(), state.requestId(), renderedWorkcell.stableId())); window.setElement(2, 5, saveNow); } - UIElement preview = element( + JigsawStudioMenuElement preview = element( "settings-preview", - Material.ENDER_EYE, - ChatColor.LIGHT_PURPLE + "Go to Preview"); + JigsawStudioMenuIcon.ENDER_EYE, + lightPurple("Go to Preview")); preview.onLeftClick(clicked -> goToPreview(window.getViewer(), state.requestId())); window.setElement(3, 5, preview); - UIElement toolbox = element("settings-toolbox", Material.STICK, ChatColor.AQUA + "Toolbox"); + JigsawStudioMenuElement toolbox = element("settings-toolbox", JigsawStudioMenuIcon.STICK, aqua("Toolbox")); toolbox.onLeftClick(clicked -> openToolbox( window.getViewer(), state.requestId(), renderedWorkcell.stableId(), 0)); window.setElement(4, 5, toolbox); @@ -701,7 +688,7 @@ public final class JigsawStudioMenuController { } private void renderVariantSizeSettings( - UIWindow window, + JigsawStudioMenuWindow window, JigsawStudioMenuState state, JigsawStudioMenuState.Workcell workcell, JigsawStudioMenuState.Variant variant @@ -710,38 +697,38 @@ public final class JigsawStudioMenuController { window.batch(() -> { window.clearElements(); - UIElement back = element("variant-size-back", Material.ARROW, ChatColor.YELLOW + "Back to Details"); + JigsawStudioMenuElement back = element("variant-size-back", JigsawStudioMenuIcon.ARROW, yellow("Back to Details")); back.onLeftClick(clicked -> openDetails( window.getViewer(), state.requestId(), workcell.stableId(), variant.pieceKey(), 0)); window.setElement(-4, 0, back); - UIElement identity = element( + JigsawStudioMenuElement identity = element( "variant-size-identity", - Material.SCAFFOLDING, - ChatColor.AQUA + safe(variant.displayName()) + " Size"); - identity.addLore(ChatColor.DARK_GRAY + safe(variant.pieceKey())); - identity.addLore(ChatColor.WHITE + "Current: " + dimensions(current)); - identity.addLore(ChatColor.GRAY + "Workcell capacity: " + dimensions(workcell.capacity())); - identity.addLore(ChatColor.GRAY + "Only this variant object and its edge connectors change."); + JigsawStudioMenuIcon.SCAFFOLDING, + aqua(safe(variant.displayName()) + " Size")); + identity.addLore(darkGray(safe(variant.pieceKey()))); + identity.addLore(white("Current: " + dimensions(current))); + identity.addLore(gray("Workcell capacity: " + dimensions(workcell.capacity()))); + identity.addLore(gray("Only this variant object and its edge connectors change.")); window.setElement(0, 0, identity); window.setElement(4, 0, evaluationElement(state.evaluation())); window.setElement(-2, 2, variantAxisElement( - window, state, workcell, variant, DimensionAxis.WIDTH, Material.IRON_INGOT)); + window, state, workcell, variant, DimensionAxis.WIDTH, JigsawStudioMenuIcon.IRON_INGOT)); window.setElement(0, 2, variantAxisElement( - window, state, workcell, variant, DimensionAxis.HEIGHT, Material.GOLD_INGOT)); + window, state, workcell, variant, DimensionAxis.HEIGHT, JigsawStudioMenuIcon.GOLD_INGOT)); window.setElement(2, 2, variantAxisElement( - window, state, workcell, variant, DimensionAxis.DEPTH, Material.COPPER_INGOT)); + window, state, workcell, variant, DimensionAxis.DEPTH, JigsawStudioMenuIcon.COPPER_INGOT)); - UIElement capacity = element( + JigsawStudioMenuElement capacity = element( "variant-size-capacity", - variant.resizableToCapacity() ? Material.NETHER_STAR : Material.GRAY_DYE, + variant.resizableToCapacity() ? JigsawStudioMenuIcon.NETHER_STAR : JigsawStudioMenuIcon.GRAY_DYE, variant.resizableToCapacity() - ? ChatColor.GREEN + "Resize This Variant to Capacity" - : ChatColor.GRAY + "Variant Already Matches Capacity"); - capacity.addLore(ChatColor.GRAY + dimensions(workcell.capacity())); + ? green("Resize This Variant to Capacity") + : gray("Variant Already Matches Capacity")); + capacity.addLore(gray(dimensions(workcell.capacity()))); if (variant.resizableToCapacity()) { - capacity.addLore(ChatColor.YELLOW + "Left-click to resize only this variant"); + capacity.addLore(yellow("Left-click to resize only this variant")); capacity.onLeftClick(clicked -> resizeVariant( window.getViewer(), state.requestId(), @@ -751,31 +738,31 @@ public final class JigsawStudioMenuController { } window.setElement(0, 3, capacity); - UIElement footerBack = element("variant-size-footer-back", Material.ARROW, ChatColor.YELLOW + "Back"); + JigsawStudioMenuElement footerBack = element("variant-size-footer-back", JigsawStudioMenuIcon.ARROW, yellow("Back")); footerBack.onLeftClick(clicked -> openDetails( window.getViewer(), state.requestId(), workcell.stableId(), variant.pieceKey(), 0)); window.setElement(-4, 5, footerBack); }); } - private UIElement variantAxisElement( - UIWindow window, + private JigsawStudioMenuElement variantAxisElement( + JigsawStudioMenuWindow window, JigsawStudioMenuState state, JigsawStudioMenuState.Workcell workcell, JigsawStudioMenuState.Variant variant, DimensionAxis axis, - Material material + JigsawStudioMenuIcon material ) { JigsawStudioCellDimensions current = variant.dimensions().orElseThrow(); - UIElement element = element( + JigsawStudioMenuElement element = element( "variant-axis-" + axis.name().toLowerCase(Locale.ROOT), material, - ChatColor.AQUA + axis.displayName() + ": " + axis.value(current)); - element.addLore(ChatColor.GREEN + "Left-click: +1"); - element.addLore(ChatColor.YELLOW + "Right-click: -1"); - element.addLore(ChatColor.GREEN + "Shift-left: +8"); - element.addLore(ChatColor.YELLOW + "Shift-right: -8"); - element.addLore(ChatColor.GRAY + "Maximum: " + axis.value(workcell.capacity())); + aqua(axis.displayName() + ": " + axis.value(current))); + element.addLore(green("Left-click: +1")); + element.addLore(yellow("Right-click: -1")); + element.addLore(green("Shift-left: +8")); + element.addLore(yellow("Shift-right: -8")); + element.addLore(gray("Maximum: " + axis.value(workcell.capacity()))); element.onLeftClick(clicked -> resizeVariantAxis( window.getViewer(), state.requestId(), workcell.stableId(), variant.pieceKey(), axis, 1)); element.onRightClick(clicked -> resizeVariantAxis( @@ -788,49 +775,49 @@ public final class JigsawStudioMenuController { } private void renderStructureSettings( - UIWindow window, + JigsawStudioMenuWindow window, JigsawStudioMenuState state, String selectedWorkcellId, int requestedPage ) { int page = clampPage(requestedPage, state.themeSets().size(), THEME_SETS_PER_PAGE); - purgeExpiredConfirmations(window.getViewer().getUniqueId()); + purgeExpiredConfirmations(window.getViewer().id()); window.batch(() -> { window.clearElements(); - UIElement back = element("structure-back", Material.ARROW, ChatColor.YELLOW + "Back to Variants"); + JigsawStudioMenuElement back = element("structure-back", JigsawStudioMenuIcon.ARROW, yellow("Back to Variants")); back.onLeftClick(clicked -> refreshMain( window.getViewer(), state.requestId(), selectedWorkcellId, 0)); window.setElement(-4, 0, back); - UIElement identity = element( + JigsawStudioMenuElement identity = element( "structure-identity", - Material.JIGSAW, - ChatColor.LIGHT_PURPLE + "Structure Themes & Caps"); - identity.addLore(ChatColor.DARK_GRAY + safe(state.structureKey())); - identity.addLore(ChatColor.GRAY + "Compatibility: " + compatibilityName(state.compatibilityTarget())); - identity.addLore(ChatColor.GRAY + "Theme sets select one coherent variant family per assembly."); - identity.addLore(ChatColor.GRAY + "Empty piece themes remain available to every family."); + JigsawStudioMenuIcon.JIGSAW, + lightPurple("Structure Themes & Caps")); + identity.addLore(darkGray(safe(state.structureKey()))); + identity.addLore(gray("Compatibility: " + compatibilityName(state.compatibilityTarget()))); + identity.addLore(gray("Theme sets select one coherent variant family per assembly.")); + identity.addLore(gray("Empty piece themes remain available to every family.")); window.setElement(0, 0, identity); window.setElement(4, 0, evaluationElement(state.evaluation())); - UIElement requireCaps = element( + JigsawStudioMenuElement requireCaps = element( "require-caps", state.irisExtended() - ? state.requireCaps() ? Material.IRON_BARS : Material.TRIPWIRE_HOOK - : Material.BARRIER, + ? state.requireCaps() ? JigsawStudioMenuIcon.IRON_BARS : JigsawStudioMenuIcon.TRIPWIRE_HOOK + : JigsawStudioMenuIcon.BARRIER, !state.irisExtended() - ? ChatColor.GRAY + "Mandatory Caps Require Iris Compatibility" + ? gray("Mandatory Caps Require Iris Compatibility") : state.requireCaps() - ? ChatColor.GREEN + "Mandatory Caps Enabled" - : ChatColor.YELLOW + "Mandatory Caps Disabled"); - requireCaps.addLore(!state.irisExtended() - ? ChatColor.GRAY + "Vanilla-portable export rejects Iris mandatory-cap metadata." + ? green("Mandatory Caps Enabled") + : yellow("Mandatory Caps Disabled")); + requireCaps.addLore(gray(!state.irisExtended() + ? "Vanilla-portable export rejects Iris mandatory-cap metadata." : state.requireCaps() - ? ChatColor.GRAY + "Every open connector must close with a terminal piece." - : ChatColor.GRAY + "Assembly may leave an open connector when no cap can fit."); + ? "Every open connector must close with a terminal piece." + : "Assembly may leave an open connector when no cap can fit.")); if (state.irisExtended()) { - requireCaps.addLore(ChatColor.YELLOW + "Left-click to toggle"); + requireCaps.addLore(yellow("Left-click to toggle")); requireCaps.onLeftClick(clicked -> setRequireCaps( window.getViewer(), state.requestId(), !state.requireCaps())); } @@ -838,65 +825,65 @@ public final class JigsawStudioMenuController { String nextThemeKey = nextThemeSetKey(state.themeSets()); boolean themeEditingAvailable = state.irisExtended(); - UIElement createTheme = element( + JigsawStudioMenuElement createTheme = element( "new-theme-set", - themeEditingAvailable ? Material.NETHER_STAR : Material.BARRIER, + themeEditingAvailable ? JigsawStudioMenuIcon.NETHER_STAR : JigsawStudioMenuIcon.BARRIER, themeEditingAvailable - ? ChatColor.GREEN + "Duplicate All Enabled Cells as Family: " + safe(nextThemeKey) - : ChatColor.GRAY + "Theme Sets Require Iris Compatibility"); + ? green("Duplicate All Enabled Cells as Family: " + safe(nextThemeKey)) + : gray("Theme Sets Require Iris Compatibility")); if (themeEditingAvailable) { - createTheme.addLore(ChatColor.GRAY + "Creates one new owned variant for every enabled workcell."); - createTheme.addLore(ChatColor.GRAY + "All created variants join " + safe(nextThemeKey) + "."); - createTheme.addLore(ChatColor.GRAY + "One family is selected for the complete assembly."); - createTheme.addLore(ChatColor.YELLOW + "Left-click to create the complete set"); + createTheme.addLore(gray("Creates one new owned variant for every enabled workcell.")); + createTheme.addLore(gray("All created variants join " + safe(nextThemeKey) + ".")); + createTheme.addLore(gray("One family is selected for the complete assembly.")); + createTheme.addLore(yellow("Left-click to create the complete set")); createTheme.onLeftClick(clicked -> duplicateActiveFamily( window.getViewer(), state.requestId(), nextThemeKey)); } else { - createTheme.addLore(ChatColor.GRAY + "Vanilla jigsaw resources cannot encode Iris theme metadata."); + createTheme.addLore(gray("Vanilla jigsaw resources cannot encode Iris theme metadata.")); } window.setElement(0, 1, createTheme); boolean deleteConfirmed = isProjectDeleteConfirmed( - window.getViewer().getUniqueId(), state.requestId()); - UIElement deleteProject = element( + window.getViewer().id(), state.requestId()); + JigsawStudioMenuElement deleteProject = element( "delete-project", - deleteConfirmed ? Material.REDSTONE : Material.LAVA_BUCKET, + deleteConfirmed ? JigsawStudioMenuIcon.REDSTONE : JigsawStudioMenuIcon.LAVA_BUCKET, deleteConfirmed - ? ChatColor.RED + "Confirm Delete Jigsaw" - : ChatColor.RED + "Delete Jigsaw") + ? red("Confirm Delete Jigsaw") + : red("Delete Jigsaw")) .setEnchanted(deleteConfirmed); - deleteProject.addLore(deleteConfirmed - ? ChatColor.RED + "Click again to delete this entire managed project." - : ChatColor.RED + "Click twice within 10 seconds to confirm."); + deleteProject.addLore(red(deleteConfirmed + ? "Click again to delete this entire managed project." + : "Click twice within 10 seconds to confirm.")); deleteProject.onLeftClick(clicked -> confirmOrDeleteProject( window.getViewer(), state.requestId(), selectedWorkcellId, page)); window.setElement(3, 1, deleteProject); addThemeSets(window, state, page); - UIElement footerBack = element("structure-footer-back", Material.ARROW, ChatColor.YELLOW + "Back"); + JigsawStudioMenuElement footerBack = element("structure-footer-back", JigsawStudioMenuIcon.ARROW, yellow("Back")); footerBack.onLeftClick(clicked -> refreshMain( window.getViewer(), state.requestId(), selectedWorkcellId, 0)); window.setElement(-4, 5, footerBack); int pageCount = pageCount(state.themeSets().size(), THEME_SETS_PER_PAGE); if (page > 0) { - UIElement previous = element( + JigsawStudioMenuElement previous = element( "theme-previous", - Material.ARROW, - ChatColor.YELLOW + "Previous Page"); + JigsawStudioMenuIcon.ARROW, + yellow("Previous Page")); previous.onLeftClick(clicked -> refreshStructureSettings( window.getViewer(), state.requestId(), selectedWorkcellId, page - 1)); window.setElement(-1, 5, previous); } - UIElement indicator = element( + JigsawStudioMenuElement indicator = element( "theme-page", - Material.BOOK, - ChatColor.WHITE + "Page " + (page + 1) + "/" + pageCount); - indicator.addLore(ChatColor.GRAY + "" + state.themeSets().size() + " theme sets"); + JigsawStudioMenuIcon.BOOK, + white("Page " + (page + 1) + "/" + pageCount)); + indicator.addLore(gray("" + state.themeSets().size() + " theme sets")); window.setElement(0, 5, indicator); if (page + 1 < pageCount) { - UIElement next = element("theme-next", Material.ARROW, ChatColor.YELLOW + "Next Page"); + JigsawStudioMenuElement next = element("theme-next", JigsawStudioMenuIcon.ARROW, yellow("Next Page")); next.onLeftClick(clicked -> refreshStructureSettings( window.getViewer(), state.requestId(), selectedWorkcellId, page + 1)); window.setElement(1, 5, next); @@ -906,18 +893,18 @@ public final class JigsawStudioMenuController { } private void addThemeSets( - UIWindow window, + JigsawStudioMenuWindow window, JigsawStudioMenuState state, int page ) { List themeSets = page( state.themeSets(), page, THEME_SETS_PER_PAGE); if (themeSets.isEmpty()) { - UIElement empty = element( + JigsawStudioMenuElement empty = element( "no-theme-sets", - Material.GRAY_DYE, - ChatColor.GRAY + "Implicit Unthemed Assembly"); - empty.addLore(ChatColor.GRAY + "Create variant-1 to begin coherent theme selection."); + JigsawStudioMenuIcon.GRAY_DYE, + gray("Implicit Unthemed Assembly")); + empty.addLore(gray("Create variant-1 to begin coherent theme selection.")); window.setElement(0, 3, empty); return; } @@ -925,18 +912,20 @@ public final class JigsawStudioMenuController { JigsawStudioMenuState.ThemeSet themeSet = themeSets.get(index); int position = GRID_POSITIONS[index % GRID_POSITIONS.length]; int row = 2 + index / GRID_POSITIONS.length; - UIElement element = element( + JigsawStudioMenuElement element = element( "theme-set-" + index, - state.irisExtended() ? Material.PURPLE_DYE : Material.GRAY_DYE, - (state.irisExtended() ? ChatColor.LIGHT_PURPLE : ChatColor.GRAY) + safe(themeSet.key())); - element.addLore(ChatColor.WHITE + "Selection weight: " + themeSet.weight()); - element.addLore(ChatColor.WHITE + "Whole-assembly chance: " - + themeSelectionPercent(state.themeSets(), themeSet)); + state.irisExtended() ? JigsawStudioMenuIcon.PURPLE_DYE : JigsawStudioMenuIcon.GRAY_DYE, + ToolText.colored( + state.irisExtended() ? TextColor.LIGHT_PURPLE : TextColor.GRAY, + safe(themeSet.key()))); + element.addLore(white("Selection weight: " + themeSet.weight())); + element.addLore(white("Whole-assembly chance: " + + themeSelectionPercent(state.themeSets(), themeSet))); if (state.irisExtended()) { - element.addLore(ChatColor.GREEN + "Left-click: weight +1"); - element.addLore(ChatColor.YELLOW + "Right-click: weight -1"); - element.addLore(ChatColor.GREEN + "Shift-left: weight +8"); - element.addLore(ChatColor.YELLOW + "Shift-right: weight -8"); + element.addLore(green("Left-click: weight +1")); + element.addLore(yellow("Right-click: weight -1")); + element.addLore(green("Shift-left: weight +8")); + element.addLore(yellow("Shift-right: weight -8")); element.onLeftClick(clicked -> adjustThemeSetWeight( window.getViewer(), state.requestId(), themeSet, 1)); element.onRightClick(clicked -> adjustThemeSetWeight( @@ -946,28 +935,28 @@ public final class JigsawStudioMenuController { element.onShiftRightClick(clicked -> adjustThemeSetWeight( window.getViewer(), state.requestId(), themeSet, -8)); } else { - element.addLore(ChatColor.GRAY + "Theme metadata is unavailable for vanilla-portable graphs."); + element.addLore(gray("Theme metadata is unavailable for vanilla-portable graphs.")); } window.setElement(position, row, element); } } - private UIElement axisElement( - UIWindow window, + private JigsawStudioMenuElement axisElement( + JigsawStudioMenuWindow window, JigsawStudioMenuState state, JigsawStudioMenuState.Workcell workcell, DimensionAxis axis, - Material material + JigsawStudioMenuIcon material ) { - UIElement element = element( + JigsawStudioMenuElement element = element( "axis-" + axis.name().toLowerCase(Locale.ROOT), material, - ChatColor.AQUA + axis.displayName() + " Capacity: " + axis.value(workcell.capacity())); - element.addLore(ChatColor.GREEN + "Left-click: +1"); - element.addLore(ChatColor.YELLOW + "Right-click: -1"); - element.addLore(ChatColor.GREEN + "Shift-left: +8"); - element.addLore(ChatColor.YELLOW + "Shift-right: -8"); - element.addLore(ChatColor.GRAY + "Changes stay in this menu until Apply Cell Size."); + aqua(axis.displayName() + " Capacity: " + axis.value(workcell.capacity()))); + element.addLore(green("Left-click: +1")); + element.addLore(yellow("Right-click: -1")); + element.addLore(green("Shift-left: +8")); + element.addLore(yellow("Shift-right: -8")); + element.addLore(gray("Changes stay in this menu until Apply Cell Size.")); element.onLeftClick(clicked -> resizeWorkcell( window.getViewer(), state.requestId(), workcell.stableId(), axis, 1)); element.onRightClick(clicked -> resizeWorkcell( @@ -980,14 +969,14 @@ public final class JigsawStudioMenuController { } private void renderDetails( - UIWindow window, + JigsawStudioMenuWindow window, JigsawStudioMenuState state, JigsawStudioMenuState.Workcell workcell, JigsawStudioMenuState.Variant variant, int requestedPage ) { int page = clampPage(requestedPage, variant.memberships().size(), MEMBERSHIPS_PER_PAGE); - purgeExpiredConfirmations(window.getViewer().getUniqueId()); + purgeExpiredConfirmations(window.getViewer().id()); window.batch(() -> { window.clearElements(); addDetailsHeader(window, state, workcell, variant, page); @@ -997,39 +986,39 @@ public final class JigsawStudioMenuController { } private void addDetailsHeader( - UIWindow window, + JigsawStudioMenuWindow window, JigsawStudioMenuState state, JigsawStudioMenuState.Workcell workcell, JigsawStudioMenuState.Variant variant, int page ) { - UIElement back = element("back", Material.ARROW, ChatColor.YELLOW + "Back to Variants"); + JigsawStudioMenuElement back = element("back", JigsawStudioMenuIcon.ARROW, yellow("Back to Variants")); back.onLeftClick(clicked -> refreshMain( window.getViewer(), state.requestId(), workcell.stableId(), 0)); window.setElement(-4, 0, back); - UIElement identity = element("identity", Material.NAME_TAG, ChatColor.AQUA + safe(variant.displayName())); - identity.addLore(ChatColor.DARK_GRAY + safe(variant.pieceKey())); + JigsawStudioMenuElement identity = element("identity", JigsawStudioMenuIcon.NAME_TAG, aqua(safe(variant.displayName()))); + identity.addLore(darkGray(safe(variant.pieceKey()))); identity.addLore(variant.owned() - ? ChatColor.GREEN + "Owned variant" - : ChatColor.GRAY + "Read-only variant"); + ? green("Owned variant") + : gray("Read-only variant")); identity.addLore(variant.active() - ? ChatColor.GREEN + "Loaded in this workcell" - : ChatColor.GRAY + "Not currently loaded"); - identity.addLore(ChatColor.GRAY + "Size: " + variant.dimensions() + ? green("Loaded in this workcell") + : gray("Not currently loaded")); + identity.addLore(gray("Size: " + variant.dimensions() .map(JigsawStudioMenuController::dimensions) - .orElse("Object missing")); - identity.addLore(ChatColor.GRAY + "Themes: " + themes(variant.themes())); - identity.addLore(ChatColor.GRAY + "Depth: " + variant.rules().minimumDepth() - + "-" + variant.rules().maximumDepth()); - identity.addLore(ChatColor.GRAY + "Placements: " + variant.rules().minimumPlacements() - + "-" + maximumPlacements(variant.rules().maximumPlacements())); - identity.addLore(ChatColor.GRAY + "Terminal: " + yesNo(variant.rules().terminal())); - identity.addLore(ChatColor.GRAY + "Pool entries: " + variant.memberships().size()); + .orElse("Object missing"))); + identity.addLore(gray("Themes: " + themes(variant.themes()))); + identity.addLore(gray("Depth: " + variant.rules().minimumDepth() + + "-" + variant.rules().maximumDepth())); + identity.addLore(gray("Placements: " + variant.rules().minimumPlacements() + + "-" + maximumPlacements(variant.rules().maximumPlacements()))); + identity.addLore(gray("Terminal: " + yesNo(variant.rules().terminal()))); + identity.addLore(gray("Pool entries: " + variant.memberships().size())); if (variant.owned()) { - identity.addLore(ChatColor.YELLOW + "Left-click for a rename stick"); - identity.addLore(ChatColor.GRAY + "Rename that stick in an anvil, then right-click it."); - identity.addLore(ChatColor.GRAY + "Sneak-right-click the stick to reset this label."); + identity.addLore(yellow("Left-click for a rename stick")); + identity.addLore(gray("Rename that stick in an anvil, then right-click it.")); + identity.addLore(gray("Sneak-right-click the stick to reset this label.")); identity.onLeftClick(clicked -> actions.giveTool( window.getViewer(), JigsawStudioToolPayload.variant( @@ -1042,60 +1031,60 @@ public final class JigsawStudioMenuController { boolean activeOwned = variant.active() && variant.owned(); boolean irisRuleEditing = activeOwned && state.irisExtended(); - UIElement settings = element( + JigsawStudioMenuElement settings = element( "variant-settings", - irisRuleEditing ? Material.COMPARATOR : Material.GRAY_DYE, + irisRuleEditing ? JigsawStudioMenuIcon.COMPARATOR : JigsawStudioMenuIcon.GRAY_DYE, irisRuleEditing - ? ChatColor.GOLD + "Themes & Piece Rules" - : ChatColor.GRAY + "Themes & Rules Unavailable"); - settings.addLore(irisRuleEditing - ? ChatColor.GRAY + "Edit this loaded variant's theme membership and placement rules." + ? gold("Themes & Piece Rules") + : gray("Themes & Rules Unavailable")); + settings.addLore(gray(irisRuleEditing + ? "Edit this loaded variant's theme membership and placement rules." : state.irisExtended() - ? ChatColor.GRAY + "Load an owned variant before editing its rules." - : ChatColor.GRAY + "Vanilla-portable pieces cannot encode Iris theme or rule metadata."); + ? "Load an owned variant before editing its rules." + : "Vanilla-portable pieces cannot encode Iris theme or rule metadata.")); if (irisRuleEditing) { - settings.addLore(ChatColor.YELLOW + "Left-click to edit"); + settings.addLore(yellow("Left-click to edit")); settings.onLeftClick(clicked -> openVariantSettings( window.getViewer(), state.requestId(), workcell.stableId(), variant.pieceKey(), 0)); } window.setElement(-2, 0, settings); boolean rotationEditable = variant.active() && variant.rotationEditable(); - UIElement rotation = element( + JigsawStudioMenuElement rotation = element( "rotation", - rotationEditable ? Material.REPEATER : Material.BARRIER, + rotationEditable ? JigsawStudioMenuIcon.REPEATER : JigsawStudioMenuIcon.BARRIER, rotationEditable - ? ChatColor.LIGHT_PURPLE + "Toggle Rotation" - : ChatColor.GRAY + "Rotation is Read-only"); - rotation.addLore(ChatColor.GRAY + "Currently: " + (variant.rotatable() ? "Enabled" : "Disabled")); + ? lightPurple("Toggle Rotation") + : gray("Rotation is Read-only")); + rotation.addLore(gray("Currently: " + (variant.rotatable() ? "Enabled" : "Disabled"))); if (rotationEditable) { - rotation.addLore(ChatColor.YELLOW + "Left-click to toggle"); + rotation.addLore(yellow("Left-click to toggle")); rotation.onLeftClick(clicked -> toggleRotation( window.getViewer(), state.requestId(), workcell.stableId())); } else if (!variant.active()) { - rotation.addLore(ChatColor.GRAY + "Load this variant before editing rotation."); + rotation.addLore(gray("Load this variant before editing rotation.")); } else if (variant.owned() && variant.rotatable()) { - rotation.addLore(ChatColor.GRAY + "Vanilla-portable variants must remain rotatable."); + rotation.addLore(gray("Vanilla-portable variants must remain rotatable.")); } window.setElement(3, 0, rotation); boolean sizeEditable = variant.owned() && variant.dimensions().isPresent(); - UIElement size = element( + JigsawStudioMenuElement size = element( "variant-size", - sizeEditable ? Material.SCAFFOLDING : Material.BARRIER, + sizeEditable ? JigsawStudioMenuIcon.SCAFFOLDING : JigsawStudioMenuIcon.BARRIER, sizeEditable - ? ChatColor.GREEN + "Edit This Variant's Size" - : ChatColor.GRAY + "Variant Size is Read-only"); - size.addLore(ChatColor.GRAY + "Current: " + variant.dimensions() + ? green("Edit This Variant's Size") + : gray("Variant Size is Read-only")); + size.addLore(gray("Current: " + variant.dimensions() .map(JigsawStudioMenuController::dimensions) - .orElse("Object missing")); - size.addLore(ChatColor.GRAY + "Workcell capacity: " + dimensions(workcell.capacity())); + .orElse("Object missing"))); + size.addLore(gray("Workcell capacity: " + dimensions(workcell.capacity()))); if (sizeEditable) { - size.addLore(ChatColor.YELLOW + "Left-click for width, height, and depth controls"); + size.addLore(yellow("Left-click for width, height, and depth controls")); size.onLeftClick(clicked -> openVariantSizeSettings( window.getViewer(), state.requestId(), workcell.stableId(), variant.pieceKey())); if (variant.resizableToCapacity()) { - size.addLore(ChatColor.YELLOW + "Shift-left: resize this variant to capacity"); + size.addLore(yellow("Shift-left: resize this variant to capacity")); size.onShiftLeftClick(clicked -> resizeVariant( window.getViewer(), state.requestId(), @@ -1109,25 +1098,25 @@ public final class JigsawStudioMenuController { boolean lastVariant = workcell.variants().size() <= 1; boolean deletionAvailable = variant.owned() && !variant.active() && !lastVariant; boolean confirmed = deletionAvailable && isDeleteConfirmed( - window.getViewer().getUniqueId(), + window.getViewer().id(), state.requestId(), workcell.stableId(), variant.pieceKey()); - UIElement delete = element( + JigsawStudioMenuElement delete = element( "delete-variant", - deletionAvailable ? confirmed ? Material.REDSTONE : Material.LAVA_BUCKET : Material.BARRIER, + deletionAvailable ? confirmed ? JigsawStudioMenuIcon.REDSTONE : JigsawStudioMenuIcon.LAVA_BUCKET : JigsawStudioMenuIcon.BARRIER, deletionAvailable - ? confirmed ? ChatColor.RED + "Confirm Delete Variant" : ChatColor.RED + "Delete Variant" + ? confirmed ? red("Confirm Delete Variant") : red("Delete Variant") : variant.active() - ? ChatColor.GRAY + "Loaded Variant Cannot Be Deleted" + ? gray("Loaded Variant Cannot Be Deleted") : lastVariant - ? ChatColor.GRAY + "Last Variant Cannot Be Deleted" - : ChatColor.GRAY + "Deletion is Read-only") + ? gray("Last Variant Cannot Be Deleted") + : gray("Deletion is Read-only")) .setEnchanted(confirmed); if (deletionAvailable) { - delete.addLore(confirmed - ? ChatColor.RED + "Click again to permanently delete this owned variant." - : ChatColor.RED + "Click twice within 10 seconds to confirm."); + delete.addLore(red(confirmed + ? "Click again to permanently delete this owned variant." + : "Click twice within 10 seconds to confirm.")); delete.onLeftClick(clicked -> confirmOrDeleteVariant( window.getViewer(), state.requestId(), @@ -1135,15 +1124,15 @@ public final class JigsawStudioMenuController { variant.pieceKey(), page)); } else if (variant.active()) { - delete.addLore(ChatColor.GRAY + "Load another variant in this workcell first."); + delete.addLore(gray("Load another variant in this workcell first.")); } else if (lastVariant) { - delete.addLore(ChatColor.GRAY + "Create another variant before deleting this one."); + delete.addLore(gray("Create another variant before deleting this one.")); } window.setElement(4, 0, delete); } private void addMemberships( - UIWindow window, + JigsawStudioMenuWindow window, JigsawStudioMenuState state, JigsawStudioMenuState.Workcell workcell, JigsawStudioMenuState.Variant variant, @@ -1152,8 +1141,8 @@ public final class JigsawStudioMenuController { List memberships = page( variant.memberships(), page, MEMBERSHIPS_PER_PAGE); if (memberships.isEmpty()) { - UIElement empty = element("no-memberships", Material.BARRIER, ChatColor.RED + "No Pool Entries"); - empty.addLore(ChatColor.GRAY + "This variant is not linked from an owned pool."); + JigsawStudioMenuElement empty = element("no-memberships", JigsawStudioMenuIcon.BARRIER, red("No Pool Entries")); + empty.addLore(gray("This variant is not linked from an owned pool.")); window.setElement(0, 2, empty); return; } @@ -1163,38 +1152,40 @@ public final class JigsawStudioMenuController { int position = GRID_POSITIONS[index % GRID_POSITIONS.length]; int row = 1 + index / GRID_POSITIONS.length; boolean confirmed = variant.active() && variant.owned() && isUnlinkConfirmed( - window.getViewer().getUniqueId(), + window.getViewer().id(), state.requestId(), workcell.stableId(), variant.pieceKey(), membership); - UIElement element = element( + JigsawStudioMenuElement element = element( "membership-" + index, - confirmed ? Material.REDSTONE : Material.GOLD_NUGGET, - (confirmed ? ChatColor.RED : ChatColor.GOLD) - + safe(displayKey(membership.poolKey())) - + " [" + membership.entryIndex() + "]") + confirmed ? JigsawStudioMenuIcon.REDSTONE : JigsawStudioMenuIcon.GOLD_NUGGET, + ToolText.colored( + confirmed ? TextColor.RED : TextColor.GOLD, + safe(displayKey(membership.poolKey())) + + " [" + membership.entryIndex() + "]")) .setEnchanted(confirmed); - element.addLore(ChatColor.DARK_GRAY + safe(membership.poolKey())); - element.addLore(ChatColor.GRAY + "Exact entry: " + membership.entryIndex()); - element.addLore(ChatColor.WHITE + "Weight: " + membership.weight()); - element.addLore((state.irisExtended() ? ChatColor.WHITE : ChatColor.GRAY) - + "Chance: " + chance(membership.chance()) - + (state.irisExtended() ? "" : " (Iris only)")); + element.addLore(darkGray(safe(membership.poolKey()))); + element.addLore(gray("Exact entry: " + membership.entryIndex())); + element.addLore(white("Weight: " + membership.weight())); + element.addLore(ToolText.colored( + state.irisExtended() ? TextColor.WHITE : TextColor.GRAY, + "Chance: " + chance(membership.chance()) + + (state.irisExtended() ? "" : " (Iris only)"))); if (variant.active() && variant.owned()) { - element.addLore(ChatColor.GREEN + "Left-click: weight +1"); - element.addLore(ChatColor.YELLOW + "Right-click: weight -1"); + element.addLore(green("Left-click: weight +1")); + element.addLore(yellow("Right-click: weight -1")); if (state.irisExtended()) { - element.addLore(ChatColor.GREEN + "Shift-left: chance +" - + CHANCE_STEP_PERCENTAGE_POINTS + "%"); - element.addLore(ChatColor.YELLOW + "Shift-right: chance -" - + CHANCE_STEP_PERCENTAGE_POINTS + "%"); + element.addLore(green("Shift-left: chance +" + + CHANCE_STEP_PERCENTAGE_POINTS + "%")); + element.addLore(yellow("Shift-right: chance -" + + CHANCE_STEP_PERCENTAGE_POINTS + "%")); } else { - element.addLore(ChatColor.GRAY + "Vanilla-portable pool entries always have 100% chance."); + element.addLore(gray("Vanilla-portable pool entries always have 100% chance.")); } - element.addLore(confirmed - ? ChatColor.RED + "Middle-click again to unlink" - : ChatColor.RED + "Middle-click twice to unlink"); + element.addLore(red(confirmed + ? "Middle-click again to unlink" + : "Middle-click twice to unlink")); element.onLeftClick(clicked -> adjustMembershipWeight( window.getViewer(), state.requestId(), workcell.stableId(), membership, 1)); element.onRightClick(clicked -> adjustMembershipWeight( @@ -1216,29 +1207,29 @@ public final class JigsawStudioMenuController { element.onMiddleClick(clicked -> confirmOrUnlink( window.getViewer(), state.requestId(), workcell.stableId(), membership, page)); } else { - element.addLore(variant.active() - ? ChatColor.GRAY + "Read-only pool entry" - : ChatColor.GRAY + "Load this variant to edit its pool entry"); + element.addLore(gray(variant.active() + ? "Read-only pool entry" + : "Load this variant to edit its pool entry")); } window.setElement(position, row, element); } } private void addDetailsFooter( - UIWindow window, + JigsawStudioMenuWindow window, JigsawStudioMenuState state, JigsawStudioMenuState.Workcell workcell, JigsawStudioMenuState.Variant variant, int page ) { - UIElement back = element("footer-back", Material.ARROW, ChatColor.YELLOW + "Back"); + JigsawStudioMenuElement back = element("footer-back", JigsawStudioMenuIcon.ARROW, yellow("Back")); back.onLeftClick(clicked -> refreshMain( window.getViewer(), state.requestId(), workcell.stableId(), 0)); window.setElement(-4, 5, back); int pageCount = pageCount(variant.memberships().size(), MEMBERSHIPS_PER_PAGE); if (page > 0) { - UIElement previous = element("membership-previous", Material.ARROW, ChatColor.YELLOW + "Previous Page"); + JigsawStudioMenuElement previous = element("membership-previous", JigsawStudioMenuIcon.ARROW, yellow("Previous Page")); previous.onLeftClick(clicked -> refreshDetails( window.getViewer(), state.requestId(), @@ -1247,12 +1238,12 @@ public final class JigsawStudioMenuController { page - 1)); window.setElement(-1, 5, previous); } - UIElement indicator = element("membership-page", Material.BOOK, ChatColor.WHITE + "Page " - + (page + 1) + "/" + pageCount); - indicator.addLore(ChatColor.GRAY + "" + variant.memberships().size() + " exact pool entries"); + JigsawStudioMenuElement indicator = element("membership-page", JigsawStudioMenuIcon.BOOK, white("Page " + + (page + 1) + "/" + pageCount)); + indicator.addLore(gray("" + variant.memberships().size() + " exact pool entries")); window.setElement(0, 5, indicator); if (page + 1 < pageCount) { - UIElement next = element("membership-next", Material.ARROW, ChatColor.YELLOW + "Next Page"); + JigsawStudioMenuElement next = element("membership-next", JigsawStudioMenuIcon.ARROW, yellow("Next Page")); next.onLeftClick(clicked -> refreshDetails( window.getViewer(), state.requestId(), @@ -1263,14 +1254,14 @@ public final class JigsawStudioMenuController { } window.setElement(2, 5, evaluationElement(state.evaluation())); - UIElement toolbox = element("details-toolbox", Material.STICK, ChatColor.AQUA + "Toolbox"); + JigsawStudioMenuElement toolbox = element("details-toolbox", JigsawStudioMenuIcon.STICK, aqua("Toolbox")); toolbox.onLeftClick(clicked -> openToolbox( window.getViewer(), state.requestId(), workcell.stableId(), 0)); window.setElement(4, 5, toolbox); } private void renderVariantSettings( - UIWindow window, + JigsawStudioMenuWindow window, JigsawStudioMenuState state, JigsawStudioMenuState.Workcell workcell, JigsawStudioMenuState.Variant variant, @@ -1280,31 +1271,31 @@ public final class JigsawStudioMenuController { window.batch(() -> { window.clearElements(); - UIElement back = element("variant-settings-back", Material.ARROW, ChatColor.YELLOW + "Back to Details"); + JigsawStudioMenuElement back = element("variant-settings-back", JigsawStudioMenuIcon.ARROW, yellow("Back to Details")); back.onLeftClick(clicked -> openDetails( window.getViewer(), state.requestId(), workcell.stableId(), variant.pieceKey(), 0)); window.setElement(-4, 0, back); - UIElement identity = element( + JigsawStudioMenuElement identity = element( "variant-settings-identity", - Material.COMPARATOR, - ChatColor.GOLD + safe(variant.displayName()) + " Rules"); - identity.addLore(ChatColor.DARK_GRAY + safe(variant.pieceKey())); - identity.addLore(ChatColor.GRAY + "Theme memberships: " + themes(variant.themes())); - identity.addLore(ChatColor.GRAY + "Use Duplicate All Enabled Cells as Family for coherent sets."); + JigsawStudioMenuIcon.COMPARATOR, + gold(safe(variant.displayName()) + " Rules")); + identity.addLore(darkGray(safe(variant.pieceKey()))); + identity.addLore(gray("Theme memberships: " + themes(variant.themes()))); + identity.addLore(gray("Use Duplicate All Enabled Cells as Family for coherent sets.")); window.setElement(0, 0, identity); window.setElement(4, 0, evaluationElement(state.evaluation())); if (!variant.active() || !variant.owned() || !state.irisExtended()) { - UIElement unavailable = element( + JigsawStudioMenuElement unavailable = element( "variant-settings-unavailable", - Material.BARRIER, + JigsawStudioMenuIcon.BARRIER, state.irisExtended() - ? ChatColor.RED + "Load an Owned Variant First" - : ChatColor.GRAY + "Iris Metadata Unavailable"); - unavailable.addLore(state.irisExtended() - ? ChatColor.GRAY + "Rules and themes can only change for the loaded owned variant." - : ChatColor.GRAY + "Vanilla-portable pieces use vanilla placement behavior."); + ? red("Load an Owned Variant First") + : gray("Iris Metadata Unavailable")); + unavailable.addLore(gray(state.irisExtended() + ? "Rules and themes can only change for the loaded owned variant." + : "Vanilla-portable pieces use vanilla placement behavior.")); window.setElement(0, 2, unavailable); } else { window.setElement(-4, 1, ruleElement( @@ -1316,14 +1307,14 @@ public final class JigsawStudioMenuController { window.setElement(2, 1, ruleElement( window, state, workcell, variant, RuleField.MAXIMUM_PLACEMENTS)); - UIElement terminal = element( + JigsawStudioMenuElement terminal = element( "rule-terminal", - variant.rules().terminal() ? Material.REDSTONE_TORCH : Material.LEVER, + variant.rules().terminal() ? JigsawStudioMenuIcon.REDSTONE_TORCH : JigsawStudioMenuIcon.LEVER, variant.rules().terminal() - ? ChatColor.GREEN + "Terminal Piece: Yes" - : ChatColor.YELLOW + "Terminal Piece: No"); - terminal.addLore(ChatColor.GRAY + "Terminal pieces consume a connector without expanding."); - terminal.addLore(ChatColor.YELLOW + "Left-click to toggle"); + ? green("Terminal Piece: Yes") + : yellow("Terminal Piece: No")); + terminal.addLore(gray("Terminal pieces consume a connector without expanding.")); + terminal.addLore(yellow("Left-click to toggle")); terminal.onLeftClick(clicked -> updateVariantRules( window.getViewer(), state.requestId(), @@ -1335,17 +1326,17 @@ public final class JigsawStudioMenuController { addVariantThemeMemberships(window, state, workcell, variant, page); } - UIElement footerBack = element("variant-rules-footer-back", Material.ARROW, ChatColor.YELLOW + "Back"); + JigsawStudioMenuElement footerBack = element("variant-rules-footer-back", JigsawStudioMenuIcon.ARROW, yellow("Back")); footerBack.onLeftClick(clicked -> openDetails( window.getViewer(), state.requestId(), workcell.stableId(), variant.pieceKey(), 0)); window.setElement(-4, 5, footerBack); int pageCount = pageCount(state.themeSets().size(), THEME_SETS_PER_PAGE); if (page > 0) { - UIElement previous = element( + JigsawStudioMenuElement previous = element( "variant-theme-previous", - Material.ARROW, - ChatColor.YELLOW + "Previous Page"); + JigsawStudioMenuIcon.ARROW, + yellow("Previous Page")); previous.onLeftClick(clicked -> refreshVariantSettings( window.getViewer(), state.requestId(), @@ -1354,17 +1345,17 @@ public final class JigsawStudioMenuController { page - 1)); window.setElement(-1, 5, previous); } - UIElement indicator = element( + JigsawStudioMenuElement indicator = element( "variant-theme-page", - Material.BOOK, - ChatColor.WHITE + "Theme Page " + (page + 1) + "/" + pageCount); - indicator.addLore(ChatColor.GRAY + "" + state.themeSets().size() + " declared themes"); + JigsawStudioMenuIcon.BOOK, + white("Theme Page " + (page + 1) + "/" + pageCount)); + indicator.addLore(gray("" + state.themeSets().size() + " declared themes")); window.setElement(0, 5, indicator); if (page + 1 < pageCount) { - UIElement next = element( + JigsawStudioMenuElement next = element( "variant-theme-next", - Material.ARROW, - ChatColor.YELLOW + "Next Page"); + JigsawStudioMenuIcon.ARROW, + yellow("Next Page")); next.onLeftClick(clicked -> refreshVariantSettings( window.getViewer(), state.requestId(), @@ -1377,35 +1368,35 @@ public final class JigsawStudioMenuController { }); } - private UIElement ruleElement( - UIWindow window, + private JigsawStudioMenuElement ruleElement( + JigsawStudioMenuWindow window, JigsawStudioMenuState state, JigsawStudioMenuState.Workcell workcell, JigsawStudioMenuState.Variant variant, RuleField field ) { int value = field.value(variant.rules()); - UIElement element = element( + JigsawStudioMenuElement element = element( "rule-" + field.name().toLowerCase(Locale.ROOT), field.material(), - ChatColor.AQUA + field.displayName() + ": " + field.displayValue(value)); + aqua(field.displayName() + ": " + field.displayValue(value))); boolean unlimitedMaximum = field == RuleField.MAXIMUM_PLACEMENTS && value == 0; if (unlimitedMaximum) { - element.addLore(ChatColor.GRAY + "Increase is already unlimited."); + element.addLore(gray("Increase is already unlimited.")); } else { - element.addLore(ChatColor.GREEN + "Left-click: +1"); - element.addLore(ChatColor.GREEN + "Shift-left: +" + field.shiftStep()); + element.addLore(green("Left-click: +1")); + element.addLore(green("Shift-left: +" + field.shiftStep())); element.onLeftClick(clicked -> adjustVariantRule( window.getViewer(), state.requestId(), workcell, variant, field, 1)); element.onShiftLeftClick(clicked -> adjustVariantRule( window.getViewer(), state.requestId(), workcell, variant, field, field.shiftStep())); } - element.addLore(unlimitedMaximum - ? ChatColor.YELLOW + "Right-click: set 512" - : ChatColor.YELLOW + "Right-click: -1"); - element.addLore(unlimitedMaximum - ? ChatColor.YELLOW + "Shift-right: set 497" - : ChatColor.YELLOW + "Shift-right: -" + field.shiftStep()); + element.addLore(yellow(unlimitedMaximum + ? "Right-click: set 512" + : "Right-click: -1")); + element.addLore(yellow(unlimitedMaximum + ? "Shift-right: set 497" + : "Shift-right: -" + field.shiftStep())); element.onRightClick(clicked -> adjustVariantRule( window.getViewer(), state.requestId(), workcell, variant, field, -1)); element.onShiftRightClick(clicked -> adjustVariantRule( @@ -1414,7 +1405,7 @@ public final class JigsawStudioMenuController { } private void addVariantThemeMemberships( - UIWindow window, + JigsawStudioMenuWindow window, JigsawStudioMenuState state, JigsawStudioMenuState.Workcell workcell, JigsawStudioMenuState.Variant variant, @@ -1423,11 +1414,11 @@ public final class JigsawStudioMenuController { List themeSets = page( state.themeSets(), page, THEME_SETS_PER_PAGE); if (themeSets.isEmpty()) { - UIElement empty = element( + JigsawStudioMenuElement empty = element( "variant-no-themes", - Material.GRAY_DYE, - ChatColor.GRAY + "Available to Every Theme"); - empty.addLore(ChatColor.GRAY + "Create a coherent theme set from Structure Rules first."); + JigsawStudioMenuIcon.GRAY_DYE, + gray("Available to Every Theme")); + empty.addLore(gray("Create a coherent theme set from Structure Rules first.")); window.setElement(0, 3, empty); return; } @@ -1436,16 +1427,16 @@ public final class JigsawStudioMenuController { boolean member = variant.themes().contains(themeSet.key()); int position = GRID_POSITIONS[index % GRID_POSITIONS.length]; int row = 2 + index / GRID_POSITIONS.length; - UIElement element = element( + JigsawStudioMenuElement element = element( "variant-theme-" + index, - member ? Material.LIME_DYE : Material.GRAY_DYE, - (member ? ChatColor.GREEN : ChatColor.GRAY) + safe(themeSet.key())) + member ? JigsawStudioMenuIcon.LIME_DYE : JigsawStudioMenuIcon.GRAY_DYE, + ToolText.colored(member ? TextColor.GREEN : TextColor.GRAY, safe(themeSet.key()))) .setEnchanted(member); element.addLore(member - ? ChatColor.GREEN + "This variant belongs to the theme." - : ChatColor.GRAY + "This variant does not belong to the theme."); - element.addLore(ChatColor.GRAY + "Only variants in the selected family are eligible."); - element.addLore(ChatColor.YELLOW + "Left-click to toggle membership"); + ? green("This variant belongs to the theme.") + : gray("This variant does not belong to the theme.")); + element.addLore(gray("Only variants in the selected family are eligible.")); + element.addLore(yellow("Left-click to toggle membership")); element.onLeftClick(clicked -> toggleVariantTheme( window.getViewer(), state.requestId(), workcell, variant, themeSet.key())); window.setElement(position, row, element); @@ -1453,7 +1444,7 @@ public final class JigsawStudioMenuController { } private void renderToolbox( - UIWindow window, + JigsawStudioMenuWindow window, JigsawStudioMenuState state, JigsawStudioMenuState.Workcell workcell, int requestedPage @@ -1464,14 +1455,14 @@ public final class JigsawStudioMenuController { window.batch(() -> { window.clearElements(); - UIElement back = element("toolbox-back", Material.ARROW, ChatColor.YELLOW + "Back to Variants"); + JigsawStudioMenuElement back = element("toolbox-back", JigsawStudioMenuIcon.ARROW, yellow("Back to Variants")); back.onLeftClick(clicked -> refreshMain( window.getViewer(), state.requestId(), workcell.stableId(), 0)); window.setElement(-4, 0, back); - UIElement heading = element("toolbox-heading", Material.CHEST, ChatColor.AQUA + "Bound Tool Sticks"); - heading.addLore(ChatColor.GRAY + "Every stick is bound to request " + state.requestId()); - heading.addLore(ChatColor.GRAY + "Stale sticks stop working when this Studio closes."); + JigsawStudioMenuElement heading = element("toolbox-heading", JigsawStudioMenuIcon.CHEST, aqua("Bound Tool Sticks")); + heading.addLore(gray("Every stick is bound to request " + state.requestId())); + heading.addLore(gray("Stale sticks stop working when this Studio closes.")); window.setElement(0, 0, heading); window.setElement(4, 0, evaluationElement(state.evaluation())); @@ -1479,38 +1470,38 @@ public final class JigsawStudioMenuController { ToolboxTool tool = tools.get(index); int position = GRID_POSITIONS[index % GRID_POSITIONS.length]; int row = 1 + index / GRID_POSITIONS.length; - UIElement element = element( + JigsawStudioMenuElement element = element( "tool-" + index, - Material.STICK, - ChatColor.AQUA + safe(tool.displayName())); - element.addLore(ChatColor.GRAY + "Action: " + tool.payload().action().displayName()); + JigsawStudioMenuIcon.STICK, + aqua(safe(tool.displayName()))); + element.addLore(gray("Action: " + tool.payload().action().displayName())); addToolBindingLore(element, tool.payload()); element.addLore(tool.payload().action().destructive() - ? ChatColor.RED + "Bound tools require confirmation when used." - : ChatColor.YELLOW + "Left-click to receive this named stick."); + ? red("Bound tools require confirmation when used.") + : yellow("Left-click to receive this named stick.")); element.onLeftClick(clicked -> giveTool( window.getViewer(), state.requestId(), tool.payload())); window.setElement(position, row, element); } - UIElement footerBack = element("toolbox-footer-back", Material.ARROW, ChatColor.YELLOW + "Back"); + JigsawStudioMenuElement footerBack = element("toolbox-footer-back", JigsawStudioMenuIcon.ARROW, yellow("Back")); footerBack.onLeftClick(clicked -> refreshMain( window.getViewer(), state.requestId(), workcell.stableId(), 0)); window.setElement(-4, 5, footerBack); int pageCount = pageCount(allTools.size(), TOOLS_PER_PAGE); if (page > 0) { - UIElement previous = element("toolbox-previous", Material.ARROW, ChatColor.YELLOW + "Previous Page"); + JigsawStudioMenuElement previous = element("toolbox-previous", JigsawStudioMenuIcon.ARROW, yellow("Previous Page")); previous.onLeftClick(clicked -> refreshToolbox( window.getViewer(), state.requestId(), workcell.stableId(), page - 1)); window.setElement(-1, 5, previous); } - UIElement indicator = element("toolbox-page", Material.BOOK, ChatColor.WHITE + "Page " - + (page + 1) + "/" + pageCount); - indicator.addLore(ChatColor.GRAY + "" + allTools.size() + " bound tools"); + JigsawStudioMenuElement indicator = element("toolbox-page", JigsawStudioMenuIcon.BOOK, white("Page " + + (page + 1) + "/" + pageCount)); + indicator.addLore(gray("" + allTools.size() + " bound tools")); window.setElement(0, 5, indicator); if (page + 1 < pageCount) { - UIElement next = element("toolbox-next", Material.ARROW, ChatColor.YELLOW + "Next Page"); + JigsawStudioMenuElement next = element("toolbox-next", JigsawStudioMenuIcon.ARROW, yellow("Next Page")); next.onLeftClick(clicked -> refreshToolbox( window.getViewer(), state.requestId(), workcell.stableId(), page + 1)); window.setElement(1, 5, next); @@ -1518,18 +1509,18 @@ public final class JigsawStudioMenuController { }); } - private void selectWorkcell(Player player, UUID requestId, String workcellId) { + private void selectWorkcell(ToolPlayer player, UUID requestId, String workcellId) { if (matchingState(player, requestId, true).isEmpty()) { return; } if (actions.teleportToWorkcell(player, workcellId)) { - clearConfirmations(player.getUniqueId()); + clearConfirmations(player.id()); closeAfterAction(player); } } private void toggleConnectorBlocks( - Player player, + ToolPlayer player, UUID requestId, String workcellId, boolean visible @@ -1543,7 +1534,7 @@ public final class JigsawStudioMenuController { } } - private void resetConnectorBlocks(Player player, UUID requestId, String workcellId) { + private void resetConnectorBlocks(ToolPlayer player, UUID requestId, String workcellId) { Optional current = matchingState(player, requestId, true); if (current.isEmpty() || current.get().workcell(workcellId) == null) { return; @@ -1553,7 +1544,7 @@ public final class JigsawStudioMenuController { } } - private void undoAutosave(Player player, UUID requestId) { + private void undoAutosave(ToolPlayer player, UUID requestId) { if (matchingState(player, requestId, true).isEmpty()) { return; } @@ -1562,7 +1553,7 @@ public final class JigsawStudioMenuController { } } - private void switchVariant(Player player, UUID requestId, String workcellId, String pieceKey) { + private void switchVariant(ToolPlayer player, UUID requestId, String workcellId, String pieceKey) { Optional current = matchingState(player, requestId, true); if (current.isEmpty()) { return; @@ -1574,7 +1565,7 @@ public final class JigsawStudioMenuController { return; } if (variant.active()) { - send(player, ChatColor.YELLOW + "That variant is already loaded. Right-click it for details."); + send(player, "That variant is already loaded. Right-click it for details."); return; } if (actions.switchVariant(player, workcellId, pieceKey, false)) { @@ -1583,7 +1574,7 @@ public final class JigsawStudioMenuController { } private void openDetails( - Player player, + ToolPlayer player, UUID requestId, String workcellId, String pieceKey, @@ -1599,19 +1590,19 @@ public final class JigsawStudioMenuController { stale(player); return; } - UIWindow window = windows.get(player.getUniqueId()); + JigsawStudioMenuWindow window = windows.get(player.id()); if (window != null) { renderDetails(window, current.get(), workcell, variant, page); } } - private void openWorkcellSettings(Player player, UUID requestId, String workcellId) { + private void openWorkcellSettings(ToolPlayer player, UUID requestId, String workcellId) { Optional current = matchingState(player, requestId, true); if (current.isEmpty()) { return; } JigsawStudioMenuState.Workcell workcell = current.get().workcell(workcellId); - UIWindow window = windows.get(player.getUniqueId()); + JigsawStudioMenuWindow window = windows.get(player.id()); if (workcell == null || window == null) { stale(player); return; @@ -1620,7 +1611,7 @@ public final class JigsawStudioMenuController { } private void openStructureSettings( - Player player, + ToolPlayer player, UUID requestId, String selectedWorkcellId, int page @@ -1629,7 +1620,7 @@ public final class JigsawStudioMenuController { if (current.isEmpty()) { return; } - UIWindow window = windows.get(player.getUniqueId()); + JigsawStudioMenuWindow window = windows.get(player.id()); if (current.get().workcell(selectedWorkcellId) == null || window == null) { stale(player); return; @@ -1638,7 +1629,7 @@ public final class JigsawStudioMenuController { } private void openVariantSettings( - Player player, + ToolPlayer player, UUID requestId, String workcellId, String pieceKey, @@ -1650,25 +1641,24 @@ public final class JigsawStudioMenuController { } JigsawStudioMenuState.Workcell workcell = current.get().workcell(workcellId); JigsawStudioMenuState.Variant variant = variant(workcell, pieceKey); - UIWindow window = windows.get(player.getUniqueId()); + JigsawStudioMenuWindow window = windows.get(player.id()); if (workcell == null || variant == null || window == null) { stale(player); return; } if (!variant.active() || !variant.owned()) { - send(player, ChatColor.YELLOW + "Load an owned variant before editing its rules."); + send(player, "Load an owned variant before editing its rules."); return; } if (!current.get().irisExtended()) { - send(player, ChatColor.YELLOW - + "Vanilla-portable pieces cannot encode Iris theme or piece-rule metadata."); + send(player, "Vanilla-portable pieces cannot encode Iris theme or piece-rule metadata."); return; } renderVariantSettings(window, current.get(), workcell, variant, page); } private void openVariantSizeSettings( - Player player, + ToolPlayer player, UUID requestId, String workcellId, String pieceKey @@ -1679,7 +1669,7 @@ public final class JigsawStudioMenuController { } JigsawStudioMenuState.Workcell workcell = current.get().workcell(workcellId); JigsawStudioMenuState.Variant variant = variant(workcell, pieceKey); - UIWindow window = windows.get(player.getUniqueId()); + JigsawStudioMenuWindow window = windows.get(player.id()); if (workcell == null || variant == null || !variant.owned() || variant.dimensions().isEmpty() || window == null) { stale(player); @@ -1688,13 +1678,13 @@ public final class JigsawStudioMenuController { renderVariantSizeSettings(window, current.get(), workcell, variant); } - private void openToolbox(Player player, UUID requestId, String workcellId, int page) { + private void openToolbox(ToolPlayer player, UUID requestId, String workcellId, int page) { Optional current = matchingState(player, requestId, true); if (current.isEmpty()) { return; } JigsawStudioMenuState.Workcell workcell = current.get().workcell(workcellId); - UIWindow window = windows.get(player.getUniqueId()); + JigsawStudioMenuWindow window = windows.get(player.id()); if (workcell == null || window == null) { stale(player); return; @@ -1703,7 +1693,7 @@ public final class JigsawStudioMenuController { } private void createVariant( - Player player, + ToolPlayer player, UUID requestId, String workcellId, boolean duplicateActive @@ -1717,7 +1707,7 @@ public final class JigsawStudioMenuController { } private void setWorkcellEnabled( - Player player, + ToolPlayer player, UUID requestId, String workcellId, boolean enabled @@ -1736,7 +1726,7 @@ public final class JigsawStudioMenuController { } private void resizeWorkcell( - Player player, + ToolPlayer player, UUID requestId, String workcellId, DimensionAxis axis, @@ -1751,10 +1741,10 @@ public final class JigsawStudioMenuController { stale(player); return; } - UUID playerId = player.getUniqueId(); + UUID playerId = player.id(); PendingWorkcellResize existing = pendingWorkcellResize(playerId, requestId, workcellId); if (existing != null && existing.applying()) { - send(player, ChatColor.YELLOW + "That cell size is already being applied."); + send(player, "That cell size is already being applied."); return; } JigsawStudioCellDimensions base = existing == null @@ -1763,7 +1753,7 @@ public final class JigsawStudioMenuController { Optional adjusted = adjustedDimensions( base, axis, delta); if (adjusted.isEmpty()) { - send(player, ChatColor.RED + "That workcell size is outside Iris limits."); + sendError(player, "That workcell size is outside Iris limits."); return; } PendingWorkcellResize pending = new PendingWorkcellResize( @@ -1772,18 +1762,18 @@ public final class JigsawStudioMenuController { adjusted.get(), false); pendingWorkcellResizes.put(playerId, pending); - UIWindow window = windows.get(playerId); + JigsawStudioMenuWindow window = windows.get(playerId); if (window != null) { renderWorkcellSettings(window, current.get(), withCapacity(workcell, pending.dimensions())); } } - private void applyWorkcellResize(Player player, UUID requestId, String workcellId) { + private void applyWorkcellResize(ToolPlayer player, UUID requestId, String workcellId) { Optional current = matchingState(player, requestId, true); if (current.isEmpty()) { return; } - UUID playerId = player.getUniqueId(); + UUID playerId = player.id(); PendingWorkcellResize pending = pendingWorkcellResize(playerId, requestId, workcellId); JigsawStudioMenuState.Workcell workcell = current.get().workcell(workcellId); if (pending == null || pending.applying() || workcell == null) { @@ -1800,7 +1790,7 @@ public final class JigsawStudioMenuController { pending.dimensions(), true); pendingWorkcellResizes.put(playerId, applying); - UIWindow window = windows.get(playerId); + JigsawStudioMenuWindow window = windows.get(playerId); if (window != null) { renderWorkcellSettings(window, current.get(), withCapacity(workcell, applying.dimensions())); } @@ -1813,25 +1803,23 @@ public final class JigsawStudioMenuController { } private void scheduleWorkcellResizeRefresh( - Player player, + ToolPlayer player, PendingWorkcellResize pending, int attemptsRemaining ) { - boolean scheduled = J.runEntity( + scheduler.onPlayerLater( player, () -> refreshAppliedWorkcellResize(player, pending, attemptsRemaining), - WORKCELL_RESIZE_REFRESH_TICKS); - if (!scheduled) { - pendingWorkcellResizes.remove(player.getUniqueId(), pending); - } + WORKCELL_RESIZE_REFRESH_TICKS, + () -> pendingWorkcellResizes.remove(player.id(), pending)); } private void refreshAppliedWorkcellResize( - Player player, + ToolPlayer player, PendingWorkcellResize pending, int attemptsRemaining ) { - UUID playerId = player.getUniqueId(); + UUID playerId = player.id(); if (!pending.equals(pendingWorkcellResizes.get(playerId))) { return; } @@ -1845,7 +1833,7 @@ public final class JigsawStudioMenuController { } if (workcell.capacity().equals(pending.dimensions())) { pendingWorkcellResizes.remove(playerId, pending); - UIWindow window = windows.get(playerId); + JigsawStudioMenuWindow window = windows.get(playerId); if (window != null) { renderWorkcellSettings(window, current.orElseThrow(), workcell); } @@ -1861,33 +1849,32 @@ public final class JigsawStudioMenuController { pending.dimensions(), false); pendingWorkcellResizes.replace(playerId, pending, retry); - UIWindow window = windows.get(playerId); + JigsawStudioMenuWindow window = windows.get(playerId); if (window != null) { renderWorkcellSettings(window, current.orElseThrow(), withCapacity(workcell, retry.dimensions())); } - send(player, ChatColor.YELLOW - + "Cell resizing is still pending; use Apply Cell Size to retry after the current operation settles."); + send(player, "Cell resizing is still pending; use Apply Cell Size to retry after the current operation settles."); } - private void discardWorkcellResize(Player player, UUID requestId, String workcellId) { - PendingWorkcellResize pending = pendingWorkcellResize(player.getUniqueId(), requestId, workcellId); + private void discardWorkcellResize(ToolPlayer player, UUID requestId, String workcellId) { + PendingWorkcellResize pending = pendingWorkcellResize(player.id(), requestId, workcellId); if (pending != null && !pending.applying()) { - pendingWorkcellResizes.remove(player.getUniqueId(), pending); + pendingWorkcellResizes.remove(player.id(), pending); } refreshWorkcellSettings(player, requestId, workcellId); } - private void leaveWorkcellSettings(Player player, UUID requestId, String workcellId) { - PendingWorkcellResize pending = pendingWorkcellResize(player.getUniqueId(), requestId, workcellId); + private void leaveWorkcellSettings(ToolPlayer player, UUID requestId, String workcellId) { + PendingWorkcellResize pending = pendingWorkcellResize(player.id(), requestId, workcellId); if (pending != null && !pending.applying()) { - pendingWorkcellResizes.remove(player.getUniqueId(), pending); + pendingWorkcellResizes.remove(player.id(), pending); } refreshMain(player, requestId, workcellId, 0); } - private void refreshWorkcellSettings(Player player, UUID requestId, String workcellId) { + private void refreshWorkcellSettings(ToolPlayer player, UUID requestId, String workcellId) { Optional current = matchingState(player, requestId, true); - UIWindow window = windows.get(player.getUniqueId()); + JigsawStudioMenuWindow window = windows.get(player.id()); JigsawStudioMenuState.Workcell workcell = current .map(state -> state.workcell(workcellId)) .orElse(null); @@ -1908,7 +1895,7 @@ public final class JigsawStudioMenuController { } private void resizeVariantAxis( - Player player, + ToolPlayer player, UUID requestId, String workcellId, String pieceKey, @@ -1928,14 +1915,14 @@ public final class JigsawStudioMenuController { Optional adjusted = adjustedDimensions( variant.dimensions().orElseThrow(), axis, delta); if (adjusted.isEmpty()) { - send(player, ChatColor.RED + "That variant size is outside Iris limits."); + sendError(player, "That variant size is outside Iris limits."); return; } resizeVariant(player, requestId, workcellId, pieceKey, adjusted.get()); } private void resizeVariant( - Player player, + ToolPlayer player, UUID requestId, String workcellId, String pieceKey, @@ -1954,7 +1941,7 @@ public final class JigsawStudioMenuController { if (dimensions.width() > workcell.capacity().width() || dimensions.height() > workcell.capacity().height() || dimensions.depth() > workcell.capacity().depth()) { - send(player, ChatColor.RED + "Increase this workcell's capacity before making the variant larger."); + sendError(player, "Increase this workcell's capacity before making the variant larger."); return; } if (actions.resizeVariant(player, workcellId, pieceKey, dimensions)) { @@ -1962,33 +1949,33 @@ public final class JigsawStudioMenuController { } } - private void setRequireCaps(Player player, UUID requestId, boolean requireCaps) { + private void setRequireCaps(ToolPlayer player, UUID requestId, boolean requireCaps) { Optional current = matchingState(player, requestId, true); if (current.isEmpty()) { return; } if (!current.get().irisExtended()) { - send(player, ChatColor.YELLOW + "Mandatory caps require Iris compatibility."); + send(player, "Mandatory caps require Iris compatibility."); return; } if (current.get().requireCaps() == requireCaps) { - send(player, ChatColor.YELLOW + "Mandatory caps are already " + send(player, "Mandatory caps are already " + (requireCaps ? "enabled." : "disabled.")); return; } if (actions.setRequireCaps(player, requireCaps)) { - clearConfirmations(player.getUniqueId()); + clearConfirmations(player.id()); closeAfterAction(player); } } - private void duplicateActiveFamily(Player player, UUID requestId, String themeKey) { + private void duplicateActiveFamily(ToolPlayer player, UUID requestId, String themeKey) { Optional current = matchingState(player, requestId, true); if (current.isEmpty()) { return; } if (!current.get().irisExtended()) { - send(player, ChatColor.YELLOW + "Theme sets require Iris compatibility."); + send(player, "Theme sets require Iris compatibility."); return; } if (!nextThemeSetKey(current.get().themeSets()).equals(themeKey)) { @@ -1996,13 +1983,13 @@ public final class JigsawStudioMenuController { return; } if (actions.duplicateActiveFamily(player, themeKey)) { - clearConfirmations(player.getUniqueId()); + clearConfirmations(player.id()); closeAfterAction(player); } } private void adjustThemeSetWeight( - Player player, + ToolPlayer player, UUID requestId, JigsawStudioMenuState.ThemeSet expected, int delta @@ -2012,7 +1999,7 @@ public final class JigsawStudioMenuController { return; } if (!current.get().irisExtended()) { - send(player, ChatColor.YELLOW + "Theme weights require Iris compatibility."); + send(player, "Theme weights require Iris compatibility."); return; } JigsawStudioMenuState.ThemeSet themeSet = current.get().themeSet(expected.key()); @@ -2022,16 +2009,16 @@ public final class JigsawStudioMenuController { } Optional weight = adjustedPositiveValue(themeSet.weight(), delta); if (weight.isEmpty()) { - send(player, ChatColor.RED + "Theme weights must remain positive."); + sendError(player, "Theme weights must remain positive."); return; } if (actions.updateThemeSetWeight(player, themeSet.key(), weight.get())) { - clearConfirmations(player.getUniqueId()); + clearConfirmations(player.id()); closeAfterAction(player); } } - private void flushNow(Player player, UUID requestId, String workcellId) { + private void flushNow(ToolPlayer player, UUID requestId, String workcellId) { Optional current = matchingState(player, requestId, true); if (current.isEmpty()) { return; @@ -2042,7 +2029,7 @@ public final class JigsawStudioMenuController { return; } if (!workcell.dirty()) { - send(player, ChatColor.YELLOW + "This workcell has no pending changes to flush."); + send(player, "This workcell has no pending changes to flush."); return; } if (actions.flushAutosave(player, workcellId)) { @@ -2050,14 +2037,14 @@ public final class JigsawStudioMenuController { } } - private void goToPreview(Player player, UUID requestId) { + private void goToPreview(ToolPlayer player, UUID requestId) { if (matchingState(player, requestId, true).isPresent() && actions.goToPreview(player)) { closeAfterAction(player); } } - private void toggleRotation(Player player, UUID requestId, String workcellId) { + private void toggleRotation(ToolPlayer player, UUID requestId, String workcellId) { Optional current = matchingState(player, requestId, true); if (current.isEmpty() || activeVariant(current.get(), workcellId) == null) { return; @@ -2068,7 +2055,7 @@ public final class JigsawStudioMenuController { } private void adjustVariantRule( - Player player, + ToolPlayer player, UUID requestId, JigsawStudioMenuState.Workcell workcell, JigsawStudioMenuState.Variant expected, @@ -2086,7 +2073,7 @@ public final class JigsawStudioMenuController { } Optional rules = adjustedRules(variant.rules(), field, delta); if (rules.isEmpty()) { - send(player, ChatColor.RED + "That piece rule value is outside Iris limits."); + sendError(player, "That piece rule value is outside Iris limits."); return; } updateVariantRules( @@ -2098,7 +2085,7 @@ public final class JigsawStudioMenuController { } private void updateVariantRules( - Player player, + ToolPlayer player, UUID requestId, String workcellId, String pieceKey, @@ -2109,7 +2096,7 @@ public final class JigsawStudioMenuController { return; } if (!current.get().irisExtended()) { - send(player, ChatColor.YELLOW + "Piece rules require Iris compatibility."); + send(player, "Piece rules require Iris compatibility."); return; } JigsawStudioMenuState.Variant variant = activeVariant(current.get(), workcellId); @@ -2118,13 +2105,13 @@ public final class JigsawStudioMenuController { return; } if (actions.updateVariantRules(player, workcellId, pieceKey, rules)) { - clearConfirmations(player.getUniqueId()); + clearConfirmations(player.id()); closeAfterAction(player); } } private void toggleVariantTheme( - Player player, + ToolPlayer player, UUID requestId, JigsawStudioMenuState.Workcell workcell, JigsawStudioMenuState.Variant expected, @@ -2135,7 +2122,7 @@ public final class JigsawStudioMenuController { return; } if (!current.get().irisExtended()) { - send(player, ChatColor.YELLOW + "Theme membership requires Iris compatibility."); + send(player, "Theme membership requires Iris compatibility."); return; } JigsawStudioMenuState.Variant variant = activeVariant(current.get(), workcell.stableId()); @@ -2155,13 +2142,13 @@ public final class JigsawStudioMenuController { workcell.stableId(), variant.pieceKey(), List.copyOf(themes))) { - clearConfirmations(player.getUniqueId()); + clearConfirmations(player.id()); closeAfterAction(player); } } private void adjustMembershipWeight( - Player player, + ToolPlayer player, UUID requestId, String workcellId, JigsawStudioMenuState.Membership membership, @@ -2184,13 +2171,13 @@ public final class JigsawStudioMenuController { membership.poolKey(), membership.entryIndex(), delta)) { - clearConfirmations(player.getUniqueId()); + clearConfirmations(player.id()); closeAfterAction(player); } } private void adjustMembershipChance( - Player player, + ToolPlayer player, UUID requestId, String workcellId, JigsawStudioMenuState.Membership membership, @@ -2202,7 +2189,7 @@ public final class JigsawStudioMenuController { return; } if (!current.get().irisExtended()) { - send(player, ChatColor.YELLOW + "Per-entry chance requires Iris compatibility."); + send(player, "Per-entry chance requires Iris compatibility."); return; } JigsawStudioMenuState.Variant active = activeVariant(current.get(), workcellId); @@ -2217,13 +2204,13 @@ public final class JigsawStudioMenuController { membership.poolKey(), membership.entryIndex(), deltaPercentagePoints)) { - clearConfirmations(player.getUniqueId()); + clearConfirmations(player.id()); closeAfterAction(player); } } private void confirmOrUnlink( - Player player, + ToolPlayer player, UUID requestId, String workcellId, JigsawStudioMenuState.Membership membership, @@ -2235,7 +2222,7 @@ public final class JigsawStudioMenuController { return; } - UUID playerId = player.getUniqueId(); + UUID playerId = player.id(); JigsawStudioMenuState.Variant active = activeVariant(current.get(), workcellId); if (active == null || !active.owned()) { stale(player); @@ -2249,7 +2236,11 @@ public final class JigsawStudioMenuController { membership.poolKey(), membership.entryIndex(), System.nanoTime() + DESTRUCTIVE_CONFIRM_NANOS)); - J.runEntity(player, () -> refreshDetails(player, requestId, workcellId, page), 1); + scheduler.onPlayerLater( + player, + () -> refreshDetails(player, requestId, workcellId, page), + DETAILS_REFRESH_DELAY_TICKS, + () -> { }); return; } @@ -2265,7 +2256,7 @@ public final class JigsawStudioMenuController { } private void confirmOrDeleteVariant( - Player player, + ToolPlayer player, UUID requestId, String workcellId, String pieceKey, @@ -2282,15 +2273,18 @@ public final class JigsawStudioMenuController { return; } - UUID playerId = player.getUniqueId(); + UUID playerId = player.id(); if (!isDeleteConfirmed(playerId, requestId, workcellId, pieceKey)) { pendingDeletes.put(playerId, new PendingDelete( requestId, workcellId, pieceKey, System.nanoTime() + DESTRUCTIVE_CONFIRM_NANOS)); - J.runEntity(player, () -> refreshDetails( - player, requestId, workcellId, pieceKey, page), 1); + scheduler.onPlayerLater( + player, + () -> refreshDetails(player, requestId, workcellId, pieceKey, page), + DETAILS_REFRESH_DELAY_TICKS, + () -> { }); return; } @@ -2301,7 +2295,7 @@ public final class JigsawStudioMenuController { } private void confirmOrDeleteProject( - Player player, + ToolPlayer player, UUID requestId, String selectedWorkcellId, int page @@ -2310,13 +2304,16 @@ public final class JigsawStudioMenuController { if (current.isEmpty()) { return; } - UUID playerId = player.getUniqueId(); + UUID playerId = player.id(); if (!isProjectDeleteConfirmed(playerId, requestId)) { pendingProjectDeletes.put(playerId, new PendingProjectDelete( requestId, System.nanoTime() + DESTRUCTIVE_CONFIRM_NANOS)); - J.runEntity(player, () -> refreshStructureSettings( - player, requestId, selectedWorkcellId, page), 1); + scheduler.onPlayerLater( + player, + () -> refreshStructureSettings(player, requestId, selectedWorkcellId, page), + DETAILS_REFRESH_DELAY_TICKS, + () -> { }); return; } if (actions.deleteProject(player)) { @@ -2325,7 +2322,7 @@ public final class JigsawStudioMenuController { } } - private void giveTool(Player player, UUID requestId, JigsawStudioToolPayload payload) { + private void giveTool(ToolPlayer player, UUID requestId, JigsawStudioToolPayload payload) { if (matchingState(player, requestId, true).isEmpty()) { return; } @@ -2336,13 +2333,13 @@ public final class JigsawStudioMenuController { actions.giveTool(player, payload); } - private void refreshMain(Player player, UUID requestId, String workcellId, int page) { + private void refreshMain(ToolPlayer player, UUID requestId, String workcellId, int page) { Optional current = matchingState(player, requestId, true); if (current.isEmpty()) { return; } JigsawStudioMenuState.Workcell workcell = current.get().workcell(workcellId); - UIWindow window = windows.get(player.getUniqueId()); + JigsawStudioMenuWindow window = windows.get(player.id()); if (workcell == null || window == null) { stale(player); return; @@ -2350,7 +2347,7 @@ public final class JigsawStudioMenuController { renderMain(window, current.get(), workcell, page); } - private void refreshDetails(Player player, UUID requestId, String workcellId, int page) { + private void refreshDetails(ToolPlayer player, UUID requestId, String workcellId, int page) { Optional current = matchingState(player, requestId, true); if (current.isEmpty()) { return; @@ -2364,7 +2361,7 @@ public final class JigsawStudioMenuController { } private void refreshDetails( - Player player, + ToolPlayer player, UUID requestId, String workcellId, String pieceKey, @@ -2376,7 +2373,7 @@ public final class JigsawStudioMenuController { } JigsawStudioMenuState.Workcell workcell = current.get().workcell(workcellId); JigsawStudioMenuState.Variant variant = variant(workcell, pieceKey); - UIWindow window = windows.get(player.getUniqueId()); + JigsawStudioMenuWindow window = windows.get(player.id()); if (workcell == null || variant == null || window == null) { stale(player); return; @@ -2385,7 +2382,7 @@ public final class JigsawStudioMenuController { } private void refreshStructureSettings( - Player player, + ToolPlayer player, UUID requestId, String selectedWorkcellId, int page @@ -2394,7 +2391,7 @@ public final class JigsawStudioMenuController { if (current.isEmpty()) { return; } - UIWindow window = windows.get(player.getUniqueId()); + JigsawStudioMenuWindow window = windows.get(player.id()); if (current.get().workcell(selectedWorkcellId) == null || window == null) { stale(player); return; @@ -2403,7 +2400,7 @@ public final class JigsawStudioMenuController { } private void refreshVariantSettings( - Player player, + ToolPlayer player, UUID requestId, String workcellId, String pieceKey, @@ -2415,7 +2412,7 @@ public final class JigsawStudioMenuController { } JigsawStudioMenuState.Workcell workcell = current.get().workcell(workcellId); JigsawStudioMenuState.Variant variant = variant(workcell, pieceKey); - UIWindow window = windows.get(player.getUniqueId()); + JigsawStudioMenuWindow window = windows.get(player.id()); if (workcell == null || variant == null || window == null) { stale(player); return; @@ -2423,13 +2420,13 @@ public final class JigsawStudioMenuController { renderVariantSettings(window, current.get(), workcell, variant, page); } - private void refreshToolbox(Player player, UUID requestId, String workcellId, int page) { + private void refreshToolbox(ToolPlayer player, UUID requestId, String workcellId, int page) { Optional current = matchingState(player, requestId, true); if (current.isEmpty()) { return; } JigsawStudioMenuState.Workcell workcell = current.get().workcell(workcellId); - UIWindow window = windows.get(player.getUniqueId()); + JigsawStudioMenuWindow window = windows.get(player.id()); if (workcell == null || window == null) { stale(player); return; @@ -2437,7 +2434,7 @@ public final class JigsawStudioMenuController { renderToolbox(window, current.get(), workcell, page); } - private Optional matchingState(Player player, UUID requestId, boolean closeStale) { + private Optional matchingState(ToolPlayer player, UUID requestId, boolean closeStale) { Optional current = actions.menuState(player); if (current.isPresent() && current.get().requestId().equals(requestId)) { return current; @@ -2448,17 +2445,21 @@ public final class JigsawStudioMenuController { return Optional.empty(); } - private void stale(Player player) { + private void stale(ToolPlayer player) { closeAfterAction(player); - send(player, ChatColor.RED + "This Jigsaw Studio menu is stale. Open the control chest again."); + sendError(player, "This Jigsaw Studio menu is stale. Open the control chest again."); } - private static void send(Player player, String message) { - ComponentMessenger.sendSection(player, message); + private static void send(ToolPlayer player, String message) { + player.message(yellow(message)); } - private void closeAfterAction(Player player) { - J.runEntity(player, () -> close(player), 1); + private static void sendError(ToolPlayer player, String message) { + player.message(red(message)); + } + + private void closeAfterAction(ToolPlayer player) { + scheduler.onPlayerLater(player, () -> close(player), CLOSE_AFTER_ACTION_TICKS, () -> { }); } private boolean isUnlinkConfirmed( @@ -2991,19 +2992,19 @@ public final class JigsawStudioMenuController { 0))); } - private static void addToolBindingLore(UIElement element, JigsawStudioToolPayload payload) { + private static void addToolBindingLore(JigsawStudioMenuElement element, JigsawStudioToolPayload payload) { if (!payload.workcellId().isEmpty()) { - element.addLore(ChatColor.GRAY + "Workcell: " + safe(payload.workcellId())); + element.addLore(gray("Workcell: " + safe(payload.workcellId()))); } if (!payload.pieceKey().isEmpty()) { - element.addLore(ChatColor.GRAY + "Variant: " + safe(payload.pieceKey())); + element.addLore(gray("Variant: " + safe(payload.pieceKey()))); } if (!payload.poolKey().isEmpty()) { - element.addLore(ChatColor.GRAY + "Pool: " + safe(payload.poolKey()) - + (payload.entryIndex() < 0 ? "" : " [" + payload.entryIndex() + "]")); + element.addLore(gray("Pool: " + safe(payload.poolKey()) + + (payload.entryIndex() < 0 ? "" : " [" + payload.entryIndex() + "]"))); } if (payload.amount() != 0) { - element.addLore(ChatColor.GRAY + "Amount: " + payload.amount()); + element.addLore(gray("Amount: " + payload.amount())); } } @@ -3027,43 +3028,43 @@ public final class JigsawStudioMenuController { return values.subList(start, end); } - private static UIElement evaluationElement(JigsawStudioMenuState.Evaluation evaluation) { - UIElement element = element( + private static JigsawStudioMenuElement evaluationElement(JigsawStudioMenuState.Evaluation evaluation) { + JigsawStudioMenuElement element = element( "evaluation", evaluationMaterial(evaluation.state()), - evaluationColor(evaluation.state()) + evaluationName(evaluation.state())); - element.addLore(ChatColor.GRAY + "Evaluation updates automatically."); - element.addLore(ChatColor.GRAY + "Seed: " + evaluation.seed()); + ToolText.colored(evaluationColor(evaluation.state()), evaluationName(evaluation.state()))); + element.addLore(gray("Evaluation updates automatically.")); + element.addLore(gray("Seed: " + evaluation.seed())); if (evaluation.generation() > 0L) { - element.addLore(ChatColor.GRAY + "Generation: " + evaluation.generation()); + element.addLore(gray("Generation: " + evaluation.generation())); } if (!evaluation.selectedTheme().isEmpty()) { - element.addLore(ChatColor.GRAY + "Theme: " + safe(evaluation.selectedTheme())); + element.addLore(gray("Theme: " + safe(evaluation.selectedTheme()))); } - element.addLore(ChatColor.GRAY + "Pieces: " + evaluation.pieceCount()); + element.addLore(gray("Pieces: " + evaluation.pieceCount())); if (!evaluation.detail().isEmpty()) { - element.addLore(ChatColor.GRAY + safe(evaluation.detail())); + element.addLore(gray(safe(evaluation.detail()))); } return element; } - static Material evaluationMaterial(JigsawStudioEvaluationState state) { + private static TextColor evaluationColor(JigsawStudioEvaluationState state) { return switch (state) { - case PENDING -> Material.CLOCK; - case VALID -> Material.EMERALD; - case WARNING -> Material.YELLOW_DYE; - case INVALID -> Material.RED_DYE; - case STALE -> Material.GRAY_DYE; + case PENDING -> TextColor.AQUA; + case VALID -> TextColor.GREEN; + case WARNING -> TextColor.YELLOW; + case INVALID -> TextColor.RED; + case STALE -> TextColor.GRAY; }; } - private static ChatColor evaluationColor(JigsawStudioEvaluationState state) { + static JigsawStudioMenuIcon evaluationMaterial(JigsawStudioEvaluationState state) { return switch (state) { - case PENDING -> ChatColor.AQUA; - case VALID -> ChatColor.GREEN; - case WARNING -> ChatColor.YELLOW; - case INVALID -> ChatColor.RED; - case STALE -> ChatColor.GRAY; + case PENDING -> JigsawStudioMenuIcon.CLOCK; + case VALID -> JigsawStudioMenuIcon.EMERALD; + case WARNING -> JigsawStudioMenuIcon.YELLOW_DYE; + case INVALID -> JigsawStudioMenuIcon.RED_DYE; + case STALE -> JigsawStudioMenuIcon.GRAY_DYE; }; } @@ -3077,37 +3078,37 @@ public final class JigsawStudioMenuController { }; } - private static Material workcellMaterial(JigsawStudioMenuState.Workcell workcell, boolean selected) { + private static JigsawStudioMenuIcon workcellMaterial(JigsawStudioMenuState.Workcell workcell, boolean selected) { if (!workcell.enabled()) { - return Material.GRAY_WOOL; + return JigsawStudioMenuIcon.GRAY_WOOL; } if (workcell.loading() || workcell.saving()) { - return Material.YELLOW_WOOL; + return JigsawStudioMenuIcon.YELLOW_WOOL; } if (workcell.dirty()) { - return Material.ORANGE_WOOL; + return JigsawStudioMenuIcon.ORANGE_WOOL; } - return selected ? Material.LIME_WOOL : Material.LIGHT_GRAY_WOOL; + return selected ? JigsawStudioMenuIcon.LIME_WOOL : JigsawStudioMenuIcon.LIGHT_GRAY_WOOL; } - static Material variantMaterial(JigsawStudioMenuState.Variant variant) { + static JigsawStudioMenuIcon variantMaterial(JigsawStudioMenuState.Variant variant) { if (variant.active()) { - return Material.JIGSAW; + return JigsawStudioMenuIcon.JIGSAW; } - return variant.owned() ? Material.PAPER : Material.GRAY_DYE; + return variant.owned() ? JigsawStudioMenuIcon.PAPER : JigsawStudioMenuIcon.GRAY_DYE; } - static String workcellStatus(JigsawStudioMenuState.Workcell workcell) { + static ToolText workcellStatus(JigsawStudioMenuState.Workcell workcell) { if (workcell.loading()) { - return ChatColor.YELLOW + "Loading variant"; + return yellow("Loading variant"); } if (workcell.saving()) { - return ChatColor.YELLOW + "Autosave in progress"; + return yellow("Autosave in progress"); } if (workcell.dirty()) { - return ChatColor.GOLD + "Autosave pending"; + return gold("Autosave pending"); } - return ChatColor.GREEN + "Autosaved"; + return green("Autosaved"); } private static String dimensions(JigsawStudioCellDimensions dimensions) { @@ -3137,12 +3138,48 @@ public final class JigsawStudioMenuController { }; } - private static UIElement element(String id, Material material, String name) { - return new UIElement(id) - .setMaterial(new MaterialBlock(material)) + private static JigsawStudioMenuElement element(String id, JigsawStudioMenuIcon material, ToolText name) { + return new JigsawStudioMenuElement(id) + .setIcon(material) .setName(name); } + private static ToolText gray(String text) { + return ToolText.colored(TextColor.GRAY, text); + } + + private static ToolText yellow(String text) { + return ToolText.colored(TextColor.YELLOW, text); + } + + private static ToolText green(String text) { + return ToolText.colored(TextColor.GREEN, text); + } + + private static ToolText red(String text) { + return ToolText.colored(TextColor.RED, text); + } + + private static ToolText aqua(String text) { + return ToolText.colored(TextColor.AQUA, text); + } + + private static ToolText white(String text) { + return ToolText.colored(TextColor.WHITE, text); + } + + private static ToolText gold(String text) { + return ToolText.colored(TextColor.GOLD, text); + } + + private static ToolText lightPurple(String text) { + return ToolText.colored(TextColor.LIGHT_PURPLE, text); + } + + private static ToolText darkGray(String text) { + return ToolText.colored(TextColor.DARK_GRAY, text); + } + private static String title(String structureKey) { String value = "Iris Jigsaw: " + safe(displayKey(structureKey)); return value.length() > 32 ? value.substring(0, 32) : value; @@ -3154,80 +3191,84 @@ public final class JigsawStudioMenuController { } private static String safe(String value) { - return BoardSVC.untrustedBoardValue(value); + String normalized = value == null ? "" : value.replace('\n', ' ').replace('\r', ' '); + return LEGACY_COLOR.matcher(normalized).replaceAll("") + .replace("&", "&") + .replace("<", "‹") + .replace(">", "›"); } public interface Actions { - Optional menuState(Player player); + Optional menuState(ToolPlayer player); - boolean selectWorkcell(Player player, String workcellId); + boolean selectWorkcell(ToolPlayer player, String workcellId); - boolean teleportToWorkcell(Player player, String workcellId); + boolean teleportToWorkcell(ToolPlayer player, String workcellId); - boolean setConnectorBlocksVisible(Player player, String workcellId, boolean visible); + boolean setConnectorBlocksVisible(ToolPlayer player, String workcellId, boolean visible); - boolean resetConnectorBlocks(Player player, String workcellId); + boolean resetConnectorBlocks(ToolPlayer player, String workcellId); - boolean undoAutosave(Player player); + boolean undoAutosave(ToolPlayer player); - boolean switchVariant(Player player, String workcellId, String pieceKey, boolean discardDirty); + boolean switchVariant(ToolPlayer player, String workcellId, String pieceKey, boolean discardDirty); - boolean createVariant(Player player, String workcellId, boolean duplicateActive); + boolean createVariant(ToolPlayer player, String workcellId, boolean duplicateActive); - boolean setWorkcellEnabled(Player player, String workcellId, boolean enabled); + boolean setWorkcellEnabled(ToolPlayer player, String workcellId, boolean enabled); boolean updateWorkcellDimensions( - Player player, + ToolPlayer player, String workcellId, JigsawStudioCellDimensions dimensions ); - boolean updateWorkcellDisplayName(Player player, String workcellId, String displayName); + boolean updateWorkcellDisplayName(ToolPlayer player, String workcellId, String displayName); - boolean setRequireCaps(Player player, boolean requireCaps); + boolean setRequireCaps(ToolPlayer player, boolean requireCaps); - boolean duplicateActiveFamily(Player player, String themeKey); + boolean duplicateActiveFamily(ToolPlayer player, String themeKey); - boolean updateThemeSetWeight(Player player, String themeKey, int weight); + boolean updateThemeSetWeight(ToolPlayer player, String themeKey, int weight); - boolean flushAutosave(Player player, String workcellId); + boolean flushAutosave(ToolPlayer player, String workcellId); - boolean goToPreview(Player player); + boolean goToPreview(ToolPlayer player); - boolean toggleVariantRotatable(Player player, String workcellId); + boolean toggleVariantRotatable(ToolPlayer player, String workcellId); - boolean expandVariantToCell(Player player, String workcellId); + boolean expandVariantToCell(ToolPlayer player, String workcellId); boolean resizeVariant( - Player player, + ToolPlayer player, String workcellId, String pieceKey, JigsawStudioCellDimensions dimensions ); boolean updateVariantDisplayName( - Player player, + ToolPlayer player, String workcellId, String pieceKey, String displayName ); boolean updateVariantThemes( - Player player, + ToolPlayer player, String workcellId, String pieceKey, List themes ); boolean updateVariantRules( - Player player, + ToolPlayer player, String workcellId, String pieceKey, JigsawStudioPieceRules rules ); boolean adjustVariantWeight( - Player player, + ToolPlayer player, String workcellId, String pieceKey, String poolKey, @@ -3236,7 +3277,7 @@ public final class JigsawStudioMenuController { ); boolean adjustVariantChance( - Player player, + ToolPlayer player, String workcellId, String pieceKey, String poolKey, @@ -3245,40 +3286,40 @@ public final class JigsawStudioMenuController { ); boolean unlinkVariantMembership( - Player player, + ToolPlayer player, String workcellId, String pieceKey, String poolKey, int entryIndex ); - boolean deleteVariant(Player player, String workcellId, String pieceKey); + boolean deleteVariant(ToolPlayer player, String workcellId, String pieceKey); - boolean deleteProject(Player player); + boolean deleteProject(ToolPlayer player); - boolean giveTool(Player player, JigsawStudioToolPayload payload); + boolean giveTool(ToolPlayer player, JigsawStudioToolPayload payload); } enum RuleField { - MINIMUM_DEPTH("Minimum Depth", Material.LIGHT_BLUE_DYE, RULE_SHIFT_STEP) { + MINIMUM_DEPTH("Minimum Depth", JigsawStudioMenuIcon.LIGHT_BLUE_DYE, RULE_SHIFT_STEP) { @Override int value(JigsawStudioPieceRules rules) { return rules.minimumDepth(); } }, - MAXIMUM_DEPTH("Maximum Depth", Material.BLUE_DYE, RULE_SHIFT_STEP) { + MAXIMUM_DEPTH("Maximum Depth", JigsawStudioMenuIcon.BLUE_DYE, RULE_SHIFT_STEP) { @Override int value(JigsawStudioPieceRules rules) { return rules.maximumDepth(); } }, - MINIMUM_PLACEMENTS("Minimum Placements", Material.TARGET, PLACEMENT_RULE_SHIFT_STEP) { + MINIMUM_PLACEMENTS("Minimum Placements", JigsawStudioMenuIcon.TARGET, PLACEMENT_RULE_SHIFT_STEP) { @Override int value(JigsawStudioPieceRules rules) { return rules.minimumPlacements(); } }, - MAXIMUM_PLACEMENTS("Maximum Placements", Material.GREEN_DYE, PLACEMENT_RULE_SHIFT_STEP) { + MAXIMUM_PLACEMENTS("Maximum Placements", JigsawStudioMenuIcon.GREEN_DYE, PLACEMENT_RULE_SHIFT_STEP) { @Override int value(JigsawStudioPieceRules rules) { return rules.maximumPlacements(); @@ -3291,10 +3332,10 @@ public final class JigsawStudioMenuController { }; private final String displayName; - private final Material material; + private final JigsawStudioMenuIcon material; private final int shiftStep; - RuleField(String displayName, Material material, int shiftStep) { + RuleField(String displayName, JigsawStudioMenuIcon material, int shiftStep) { this.displayName = displayName; this.material = material; this.shiftStep = shiftStep; @@ -3304,7 +3345,7 @@ public final class JigsawStudioMenuController { return displayName; } - Material material() { + JigsawStudioMenuIcon material() { return material; } diff --git a/module/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuElement.java b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuElement.java new file mode 100644 index 000000000..2cf0182cb --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuElement.java @@ -0,0 +1,95 @@ +package art.arcane.iris.core.service; + +import com.volmit.tooling.world.MenuButton; +import com.volmit.tooling.world.MenuClick; +import com.volmit.tooling.world.ToolItem; +import com.volmit.tooling.world.ToolText; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.function.Consumer; + +/** One slot of a studio menu: an icon with a name and lore, and what each kind of click on it does. */ +final class JigsawStudioMenuElement { + private final String id; + private final List lore = new ArrayList<>(); + private JigsawStudioMenuIcon icon = JigsawStudioMenuIcon.BARRIER; + private ToolText name = ToolText.EMPTY; + private boolean enchanted; + private Consumer onLeftClick; + private Consumer onRightClick; + private Consumer onShiftLeftClick; + private Consumer onShiftRightClick; + private Consumer onMiddleClick; + + JigsawStudioMenuElement(String id) { + this.id = Objects.requireNonNull(id, "Jigsaw Studio menu element ID"); + } + + String id() { + return id; + } + + JigsawStudioMenuElement setIcon(JigsawStudioMenuIcon icon) { + this.icon = Objects.requireNonNull(icon, "Jigsaw Studio menu icon"); + return this; + } + + JigsawStudioMenuElement setName(ToolText name) { + this.name = Objects.requireNonNull(name, "Jigsaw Studio menu name"); + return this; + } + + JigsawStudioMenuElement setEnchanted(boolean enchanted) { + this.enchanted = enchanted; + return this; + } + + JigsawStudioMenuElement addLore(ToolText line) { + lore.add(Objects.requireNonNull(line, "Jigsaw Studio menu lore")); + return this; + } + + JigsawStudioMenuElement onLeftClick(Consumer action) { + onLeftClick = action; + return this; + } + + JigsawStudioMenuElement onRightClick(Consumer action) { + onRightClick = action; + return this; + } + + JigsawStudioMenuElement onShiftLeftClick(Consumer action) { + onShiftLeftClick = action; + return this; + } + + JigsawStudioMenuElement onShiftRightClick(Consumer action) { + onShiftRightClick = action; + return this; + } + + JigsawStudioMenuElement onMiddleClick(Consumer action) { + onMiddleClick = action; + return this; + } + + /** The api button for this element on {@code slot}. */ + MenuButton toButton(int slot) { + ToolItem item = new ToolItem(icon.id(), name, List.copyOf(lore), enchanted, ""); + return new MenuButton(slot, item, this::click); + } + + private void click(MenuClick click) { + Consumer action = click.middle() + ? onMiddleClick + : click.shift() + ? click.right() ? onShiftRightClick : onShiftLeftClick + : click.right() ? onRightClick : onLeftClick; + if (action != null) { + action.accept(this); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuIcon.java b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuIcon.java new file mode 100644 index 000000000..1628a1f25 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuIcon.java @@ -0,0 +1,58 @@ +package art.arcane.iris.core.service; + +import com.volmit.resource.ResourceId; + +import java.util.Locale; + +/** The items the studio menus draw, named as the platform names them. */ +enum JigsawStudioMenuIcon { + ARROW, + BARRIER, + BLUE_DYE, + BOOK, + CHEST, + CLOCK, + COMPARATOR, + COPPER_INGOT, + CRAFTING_TABLE, + EMERALD, + EMERALD_BLOCK, + ENDER_EYE, + GOLD_INGOT, + GOLD_NUGGET, + GRAY_DYE, + GRAY_WOOL, + GREEN_DYE, + IRON_BARS, + IRON_INGOT, + JIGSAW, + LAVA_BUCKET, + LEVER, + LIGHT_BLUE_DYE, + LIGHT_GRAY_WOOL, + LIME_DYE, + LIME_WOOL, + NAME_TAG, + NETHER_STAR, + ORANGE_WOOL, + PAPER, + PURPLE_DYE, + RECOVERY_COMPASS, + RED_DYE, + REDSTONE, + REDSTONE_TORCH, + REPEATER, + SCAFFOLDING, + STICK, + STRUCTURE_VOID, + TARGET, + TRIPWIRE_HOOK, + YELLOW_DYE, + YELLOW_WOOL; + + private final ResourceId id = ResourceId.parse("minecraft:" + name().toLowerCase(Locale.ROOT)); + + ResourceId id() { + return id; + } +} diff --git a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuState.java b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuState.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuState.java rename to module/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuState.java diff --git a/module/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuWindow.java b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuWindow.java new file mode 100644 index 000000000..49c0fc192 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuWindow.java @@ -0,0 +1,130 @@ +package art.arcane.iris.core.service; + +import com.volmit.tooling.world.MenuButton; +import com.volmit.tooling.world.ToolMenu; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolText; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.TreeMap; + +/** + * A studio menu the controller builds up element by element, the way it lays out a window: each element sits at a + * column counted from the middle of the row (left of it negative) and a row from the top. While the window is open every + * change is shown to the player, and a batch of changes is shown once. + * + *

Used on the viewer's thread only. + */ +final class JigsawStudioMenuWindow { + private static final int ROW_WIDTH = ToolMenu.SLOTS_PER_ROW; + private static final int MIDDLE_COLUMN = ROW_WIDTH / 2; + + private final ToolPlayer viewer; + private final Map elements = new TreeMap<>(); + private ToolText title = ToolText.EMPTY; + private int viewportRows = ToolMenu.MAX_ROWS; + private Runnable onClosed = () -> { }; + private int batchDepth; + private boolean open; + private long shownGeneration; + + JigsawStudioMenuWindow(ToolPlayer viewer) { + this.viewer = Objects.requireNonNull(viewer, "Jigsaw Studio menu viewer"); + } + + ToolPlayer getViewer() { + return viewer; + } + + JigsawStudioMenuWindow setViewportHeight(int rows) { + viewportRows = Math.max(1, Math.min(ToolMenu.MAX_ROWS, rows)); + return this; + } + + JigsawStudioMenuWindow setTitle(ToolText title) { + this.title = Objects.requireNonNull(title, "Jigsaw Studio menu title"); + return this; + } + + JigsawStudioMenuWindow setTitle(String title) { + return setTitle(ToolText.plain(Objects.requireNonNull(title, "Jigsaw Studio menu title"))); + } + + JigsawStudioMenuWindow onClosed(Runnable onClosed) { + this.onClosed = Objects.requireNonNull(onClosed, "Jigsaw Studio menu close handler"); + return this; + } + + JigsawStudioMenuWindow setElement(int position, int row, JigsawStudioMenuElement element) { + elements.put(slotOf(position, row), element); + showUnlessBatching(); + return this; + } + + JigsawStudioMenuWindow clearElements() { + elements.clear(); + showUnlessBatching(); + return this; + } + + JigsawStudioMenuWindow batch(Runnable changes) { + batchDepth++; + try { + changes.run(); + } finally { + batchDepth--; + } + showUnlessBatching(); + return this; + } + + JigsawStudioMenuWindow open() { + open = true; + show(); + return this; + } + + JigsawStudioMenuWindow close() { + if (!open) { + return this; + } + open = false; + shownGeneration++; + viewer.closeMenu(); + onClosed.run(); + return this; + } + + private static int slotOf(int position, int row) { + int column = Math.max(-MIDDLE_COLUMN, Math.min(MIDDLE_COLUMN, position)) + MIDDLE_COLUMN; + return row * ROW_WIDTH + column; + } + + private void showUnlessBatching() { + if (open && batchDepth == 0) { + show(); + } + } + + private void show() { + long generation = ++shownGeneration; + List buttons = new ArrayList<>(elements.size()); + for (Map.Entry entry : elements.entrySet()) { + if (entry.getKey() >= 0 && entry.getKey() < viewportRows * ROW_WIDTH) { + buttons.add(entry.getValue().toButton(entry.getKey())); + } + } + viewer.openMenu(new ToolMenu(title, viewportRows, buttons, () -> closedByHost(generation))); + } + + private void closedByHost(long generation) { + if (generation != shownGeneration || !open) { + return; + } + open = false; + onClosed.run(); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioPreviewRenderer.java b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioPreviewRenderer.java similarity index 73% rename from core/src/main/java/art/arcane/iris/core/service/JigsawStudioPreviewRenderer.java rename to module/src/main/java/art/arcane/iris/core/service/JigsawStudioPreviewRenderer.java index a9c75d472..852a8f42f 100644 --- a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioPreviewRenderer.java +++ b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioPreviewRenderer.java @@ -1,20 +1,15 @@ package art.arcane.iris.core.service; import art.arcane.iris.engine.framework.PlacedStructurePiece; +import art.arcane.iris.engine.framework.structure.assembly.PieceTurn; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.ObjectTurn; -import art.arcane.iris.engine.object.prefab.BlockStateRotation; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.volmlib.util.math.IrisBlockVector; -import art.arcane.iris.util.common.scheduling.J; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.data.BlockData; +import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.object.ObjectBlock; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.PackResources; +import com.volmit.tooling.world.ToolWorld; import java.io.IOException; import java.util.ArrayList; @@ -24,6 +19,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; @@ -34,10 +30,18 @@ public final class JigsawStudioPreviewRenderer { private static final int MAX_BLOCKS = 250_000; private static final String AIR = "minecraft:air"; private static final String STRUCTURE_VOID = "minecraft:structure_void"; + private static final BlockState AIR_STATE = BlockState.parse(AIR); + private static final int CHUNK_SHIFT = 4; private final Map requests = new HashMap<>(); + private final ModuleLog log; - public static PreviewPlan plan(List pieces) throws IOException { + public JigsawStudioPreviewRenderer(ModuleLog log) { + this.log = Objects.requireNonNull(log, "Jigsaw Studio preview log"); + } + + public static PreviewPlan plan(List pieces, PackResources pack) throws IOException { + BlockRegistry registry = pack.blocks(); List source = List.copyOf(Objects.requireNonNull( pieces, "Jigsaw Studio preview pieces")); @@ -62,8 +66,8 @@ public final class JigsawStudioPreviewRenderer { maximumX = Math.max(maximumX, piece.getMaxX()); maximumY = Math.max(maximumY, piece.getMaxY()); maximumZ = Math.max(maximumZ, piece.getMaxZ()); - appendObject(blocks, piece); - appendFinalStates(blocks, piece); + appendObject(blocks, piece, pack); + appendFinalStates(blocks, piece, registry); if (blocks.size() > MAX_BLOCKS) { throw new IOException("The seed-1337 preview exceeds the Studio render limit of " + MAX_BLOCKS + " explicit blocks"); @@ -75,13 +79,13 @@ public final class JigsawStudioPreviewRenderer { } public void render( - World world, + ToolWorld world, UUID requestId, long generation, PreviewPlan plan, Consumer completion ) { - World activeWorld = Objects.requireNonNull(world, "Jigsaw Studio preview world"); + ToolWorld activeWorld = Objects.requireNonNull(world, "Jigsaw Studio preview world"); UUID activeRequestId = Objects.requireNonNull(requestId, "Jigsaw Studio preview request ID"); PreviewPlan activePlan = Objects.requireNonNull(plan, "Jigsaw Studio preview plan"); Consumer callback = Objects.requireNonNull(completion, "Jigsaw Studio preview callback"); @@ -90,10 +94,10 @@ public final class JigsawStudioPreviewRenderer { Map> updates; synchronized (this) { RenderState old = requests.get(activeRequestId); - previous = old == null || !old.worldId().equals(activeWorld.getUID()) + previous = old == null || old.world() != activeWorld ? Map.of() : old.blocks(); - uncertain = old == null || !old.worldId().equals(activeWorld.getUID()) + uncertain = old == null || old.world() != activeWorld ? Set.of() : Set.copyOf(old.pending()); updates = updates(previous, activePlan.blocks(), uncertain); @@ -104,7 +108,7 @@ public final class JigsawStudioPreviewRenderer { } } requests.put(activeRequestId, new RenderState( - activeWorld.getUID(), generation, activePlan.blocks(), activePlan.bounds(), pending)); + activeWorld, generation, activePlan.blocks(), activePlan.bounds(), pending)); } if (updates.isEmpty()) { callback.accept(new RenderResult(true, 0, "")); @@ -115,7 +119,8 @@ public final class JigsawStudioPreviewRenderer { for (Map.Entry> chunk : updates.entrySet()) { int chunkX = chunkX(chunk.getKey()); int chunkZ = chunkZ(chunk.getKey()); - boolean scheduled = J.runRegion( + JigsawStudioThreads.onRegion( + log, activeWorld, chunkX, chunkZ, @@ -126,16 +131,16 @@ public final class JigsawStudioPreviewRenderer { chunk.getValue(), remaining, failed, - callback)); - if (!scheduled) { - failed.set(true); - if (remaining.decrementAndGet() == 0) { - callback.accept(new RenderResult( - false, - activePlan.blocks().size(), - "One or more preview chunks could not be scheduled")); - } - } + callback), + () -> { + failed.set(true); + if (remaining.decrementAndGet() == 0) { + callback.accept(new RenderResult( + false, + activePlan.blocks().size(), + "One or more preview chunks could not be scheduled")); + } + }); } } @@ -158,10 +163,7 @@ public final class JigsawStudioPreviewRenderer { removed = requests.remove(requestId); } if (removed != null) { - World world = Bukkit.getWorld(removed.worldId()); - if (world != null) { - clear(world, removalPositions(removed)); - } + clear(removed.world(), removalPositions(removed)); } } @@ -181,39 +183,34 @@ public final class JigsawStudioPreviewRenderer { requests.clear(); } for (RenderState state : removed.values()) { - World world = Bukkit.getWorld(state.worldId()); - if (world != null) { - clear(world, removalPositions(state)); - } + clear(state.world(), removalPositions(state)); } } private static void appendObject( Map blocks, - PlacedStructurePiece piece + PlacedStructurePiece piece, + PackResources pack ) throws IOException { - IrisObject object = piece.getObject(); - ObjectTurn rotation = piece.getRotation(); - for (Map.Entry entry : object.getBlocks()) { - IrisBlockVector rotated = rotation.rotate(entry.getKey()); - PlatformBlockState state = BlockStateRotation.rotate(rotation, entry.getValue()); + PieceTurn rotation = piece.getRotation(); + PlaceableObject object = pack.objects().object(pack.idOf(piece.getObjectKey())) + .orElseThrow(() -> new IOException("Jigsaw Studio preview cannot find object '" + piece.getObjectKey() + "'")); + for (ObjectBlock block : object.geometry().blocks()) { + com.volmit.geometry.BlockPosition rotated = rotation.rotate(block.position()); putState( blocks, - new BlockPosition( - piece.getX() + rotated.getBlockX(), - piece.getY() + rotated.getBlockY(), - piece.getZ() + rotated.getBlockZ()), - state, + new BlockPosition(piece.getX() + rotated.x(), piece.getY() + rotated.y(), piece.getZ() + rotated.z()), + JigsawStudioBlocks.rotated(pack.blocks(), block.state(), rotation), "object block"); } } private static void appendFinalStates( Map blocks, - PlacedStructurePiece piece + PlacedStructurePiece piece, + BlockRegistry registry ) throws IOException { - IrisObject object = piece.getObject(); - ObjectTurn rotation = piece.getRotation(); + PieceTurn rotation = piece.getRotation(); if (piece.getPiece().getConnectors() == null) { return; } @@ -221,20 +218,15 @@ public final class JigsawStudioPreviewRenderer { if (connector == null || connector.getPosition() == null) { throw new IOException("Jigsaw Studio preview contains an incomplete connector"); } - IrisBlockVector signed = new IrisBlockVector( - connector.getPosition().getX() - object.getCenter().getBlockX(), - connector.getPosition().getY() - object.getCenter().getBlockY(), - connector.getPosition().getZ() - object.getCenter().getBlockZ()); - IrisBlockVector rotated = rotation.rotate(signed); - PlatformBlockState source = B.getStateOrNull(connector.getFinalState(), false); - PlatformBlockState state = source == null ? null : BlockStateRotation.rotate(rotation, source); + com.volmit.geometry.BlockPosition rotated = rotation.rotate(new com.volmit.geometry.BlockPosition( + connector.getPosition().x() - piece.getObject().center().x(), + connector.getPosition().y() - piece.getObject().center().y(), + connector.getPosition().z() - piece.getObject().center().z())); + BlockState source = registry.find(connector.getFinalState()).orElse(null); putState( blocks, - new BlockPosition( - piece.getX() + rotated.getBlockX(), - piece.getY() + rotated.getBlockY(), - piece.getZ() + rotated.getBlockZ()), - state, + new BlockPosition(piece.getX() + rotated.x(), piece.getY() + rotated.y(), piece.getZ() + rotated.z()), + source == null ? null : JigsawStudioBlocks.rotated(registry, source, rotation), "connector final state"); } } @@ -242,7 +234,7 @@ public final class JigsawStudioPreviewRenderer { private static void putState( Map blocks, BlockPosition position, - PlatformBlockState state, + BlockState state, String source ) throws IOException { if (state == null || state.key() == null || state.key().isBlank()) { @@ -257,7 +249,7 @@ public final class JigsawStudioPreviewRenderer { } private void applyChunk( - World world, + ToolWorld world, UUID requestId, long generation, List updates, @@ -268,24 +260,25 @@ public final class JigsawStudioPreviewRenderer { int changed = 0; List applied = new ArrayList<>(updates.size()); try { - if (!isCurrent(world.getUID(), requestId, generation)) { + if (!isCurrent(world, requestId, generation)) { return; } for (BlockUpdate update : updates) { - Block block = world.getBlockAt(update.position().x(), update.position().y(), update.position().z()); - BlockData data = Bukkit.createBlockData(update.stateKey()); - block.setBlockData(data, false); + world.setBlock( + new com.volmit.geometry.BlockPosition(update.position().x(), update.position().y(), update.position().z()), + BlockState.parse(update.stateKey()), + Optional.empty()); applied.add(update.position()); changed++; } } catch (RuntimeException exception) { failed.set(true); - IrisLogging.reportError(exception); + log.error("The Jigsaw Studio preview could not be rendered.", exception); } finally { synchronized (this) { RenderState active = requests.get(requestId); if (active != null - && active.worldId().equals(world.getUID()) + && active.world() == world && active.generation() == generation) { active.pending().removeAll(applied); } @@ -298,7 +291,7 @@ public final class JigsawStudioPreviewRenderer { pendingEmpty = state != null && state.pending().isEmpty(); } boolean current = state != null - && state.worldId().equals(world.getUID()) + && state.world() == world && state.generation() == generation; completion.accept(new RenderResult( current && pendingEmpty && !failed.get(), @@ -310,9 +303,9 @@ public final class JigsawStudioPreviewRenderer { } } - private synchronized boolean isCurrent(UUID worldId, UUID requestId, long generation) { + private synchronized boolean isCurrent(ToolWorld world, UUID requestId, long generation) { RenderState state = requests.get(requestId); - return state != null && state.worldId().equals(worldId) && state.generation() == generation; + return state != null && state.world() == world && state.generation() == generation; } private static Map> updates( @@ -346,23 +339,23 @@ public final class JigsawStudioPreviewRenderer { || !next.getOrDefault(position, AIR).equals(previous.get(position)); } - private static void clear(World world, Set positions) { + private void clear(ToolWorld world, Set positions) { Map> updates = new HashMap<>(); for (BlockPosition position : positions) { updates.computeIfAbsent( - chunkKey(position.x() >> 4, position.z() >> 4), + chunkKey(position.x() >> CHUNK_SHIFT, position.z() >> CHUNK_SHIFT), ignored -> new ArrayList<>()).add(new BlockUpdate(position, AIR)); } for (Map.Entry> chunk : updates.entrySet()) { - J.runRegion(world, chunkX(chunk.getKey()), chunkZ(chunk.getKey()), () -> { + JigsawStudioThreads.onRegion(log, world, chunkX(chunk.getKey()), chunkZ(chunk.getKey()), () -> { for (BlockUpdate update : chunk.getValue()) { - world.getBlockAt( - update.position().x(), - update.position().y(), - update.position().z()) - .setType(Material.AIR, false); + world.setBlock( + new com.volmit.geometry.BlockPosition( + update.position().x(), update.position().y(), update.position().z()), + AIR_STATE, + Optional.empty()); } - }); + }, () -> { }); } } @@ -437,14 +430,14 @@ public final class JigsawStudioPreviewRenderer { } private record RenderState( - UUID worldId, + ToolWorld world, long generation, Map blocks, PreviewBounds bounds, Set pending ) { private RenderState { - Objects.requireNonNull(worldId, "Jigsaw Studio preview world ID"); + Objects.requireNonNull(world, "Jigsaw Studio preview world"); blocks = Map.copyOf(Objects.requireNonNull(blocks, "Jigsaw Studio preview state blocks")); bounds = Objects.requireNonNull(bounds, "Jigsaw Studio preview state bounds"); pending = Objects.requireNonNull(pending, "Jigsaw Studio preview pending blocks"); diff --git a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioActivation.java b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioRegistry.java similarity index 62% rename from core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioActivation.java rename to module/src/main/java/art/arcane/iris/core/service/JigsawStudioRegistry.java index 34132e38e..f94cd1021 100644 --- a/core/src/main/java/art/arcane/iris/core/runtime/jigsaw/JigsawStudioActivation.java +++ b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioRegistry.java @@ -1,6 +1,12 @@ -package art.arcane.iris.core.runtime.jigsaw; +package art.arcane.iris.core.service; -import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioSession; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariantCatalog; +import com.volmit.tooling.ToolPack; import java.util.Locale; import java.util.Map; @@ -10,21 +16,22 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; -public final class JigsawStudioActivation { - private static final Map ACTIVE = new ConcurrentHashMap<>(); - private static final AtomicReference OPENING_OWNER = new AtomicReference<>(); - private static final AtomicReference STAGED = new AtomicReference<>(); +/** + * Which Jigsaw Studio requests are active for each pack, which one is being opened, and the staged replacement of an + * active one. One registry belongs to one studio service; it holds no platform state. + */ +public final class JigsawStudioRegistry { + private final Map active = new ConcurrentHashMap<>(); + private final AtomicReference openingOwner = new AtomicReference<>(); + private final AtomicReference staged = new AtomicReference<>(); - private JigsawStudioActivation() { - } - - public static Request activate( + public JigsawStudioRequest activate( String packKey, String structureKey, JigsawStudioMode mode, JigsawStudioCompatibilityTarget compatibilityTarget, JigsawStudioCellDimensions cellDimensions, - IrisData source + ToolPack source ) { JigsawStudioLayout layout = JigsawStudioLayout.create( mode, @@ -42,13 +49,13 @@ public final class JigsawStudioActivation { ); } - public static Request activate( + public JigsawStudioRequest activate( String packKey, String structureKey, JigsawStudioMode mode, JigsawStudioCompatibilityTarget compatibilityTarget, JigsawStudioCellDimensions cellDimensions, - IrisData source, + ToolPack source, JigsawStudioLayout initialLayout ) { return activate( @@ -63,20 +70,20 @@ public final class JigsawStudioActivation { ); } - public static synchronized Request activate( + public synchronized JigsawStudioRequest activate( String packKey, String structureKey, JigsawStudioMode mode, JigsawStudioCompatibilityTarget compatibilityTarget, JigsawStudioCellDimensions cellDimensions, - IrisData source, + ToolPack source, JigsawStudioLayout initialLayout, UUID ownerId ) { - if (STAGED.get() != null) { + if (staged.get() != null) { throw new IllegalStateException("A Jigsaw Studio replacement is already staged"); } - if (ownerId != null && !ownerId.equals(OPENING_OWNER.get())) { + if (ownerId != null && !ownerId.equals(openingOwner.get())) { throw new IllegalStateException("Jigsaw Studio activation does not own the active opening lease"); } UUID activeOwnerId = activeOwnerId(); @@ -92,31 +99,31 @@ public final class JigsawStudioActivation { source, initialLayout, ownerId); - ACTIVE.put(normalize(packKey), activeRequest); + active.put(normalize(packKey), activeRequest); return activeRequest.request(); } - public static synchronized StagedActivation stage( + public synchronized StagedActivation stage( String packKey, String structureKey, JigsawStudioMode mode, JigsawStudioCompatibilityTarget compatibilityTarget, JigsawStudioCellDimensions cellDimensions, - IrisData source, + ToolPack source, JigsawStudioLayout initialLayout, UUID ownerId, UUID preservedRequestId ) { - UUID openingOwner = OPENING_OWNER.get(); + UUID opening = openingOwner.get(); UUID activeOwner = activeOwnerId(); UUID requestedOwner = Objects.requireNonNull(ownerId, "Jigsaw Studio staged owner ID"); - if (!requestedOwner.equals(openingOwner)) { + if (!requestedOwner.equals(opening)) { throw new IllegalStateException("Jigsaw Studio staging does not own the active opening lease"); } if (activeOwner != null && !requestedOwner.equals(activeOwner)) { throw new IllegalStateException("Jigsaw Studio is owned by another player session"); } - if (STAGED.get() != null) { + if (staged.get() != null) { throw new IllegalStateException("A Jigsaw Studio replacement is already staged"); } ActiveRequest preserved = preservedRequestId == null ? null : active(preservedRequestId); @@ -139,82 +146,64 @@ public final class JigsawStudioActivation { source, initialLayout, requestedOwner); - StagedActivation staged = new StagedActivation( + StagedActivation activation = new StagedActivation( UUID.randomUUID(), candidate.request(), candidate.session()); - STAGED.set(new StagedState(staged, candidate, preserved, false)); - return staged; + staged.set(new StagedState(activation, candidate, preserved, false)); + return activation; } - public static synchronized boolean beginStagedGeneration(StagedActivation expected) { + public synchronized boolean beginStagedGeneration(StagedActivation expected) { StagedState state = stagedState(expected); if (state == null || state.generationVisible()) { return false; } - STAGED.set(new StagedState(state.staged(), state.candidate(), state.preserved(), true)); + staged.set(new StagedState(state.staged(), state.candidate(), state.preserved(), true)); return true; } - public static synchronized boolean commit(StagedActivation expected) { + public synchronized boolean commit(StagedActivation expected) { StagedState state = stagedState(expected); if (state == null || !state.generationVisible()) { return false; } if (state.preserved() != null) { - ACTIVE.remove(normalize(state.preserved().request().packKey()), state.preserved()); + active.remove(normalize(state.preserved().request().packKey()), state.preserved()); } - ACTIVE.put(normalize(state.candidate().request().packKey()), state.candidate()); - STAGED.set(null); + active.put(normalize(state.candidate().request().packKey()), state.candidate()); + staged.set(null); return true; } - public static synchronized boolean rollback(StagedActivation expected) { + public synchronized boolean rollback(StagedActivation expected) { StagedState state = stagedState(expected); if (state == null) { return false; } - STAGED.set(null); + staged.set(null); return true; } - public static Request getGeneratorRequest(String packKey) { - StagedState state = STAGED.get(); - if (state != null && state.generationVisible() - && normalize(state.candidate().request().packKey()).equals(normalize(packKey))) { - return state.candidate().request(); - } - return getRequest(packKey); - } - - public static JigsawStudioSession getGeneratorSession(String packKey) { - StagedState state = STAGED.get(); - if (state != null && state.generationVisible() - && normalize(state.candidate().request().packKey()).equals(normalize(packKey))) { - return state.candidate().session(); - } - return getSession(packKey); - } - - public static boolean tryBeginOpen(UUID ownerId) { + public boolean tryBeginOpen(UUID ownerId) { UUID requestedOwner = Objects.requireNonNull(ownerId, "Jigsaw Studio opening owner ID"); UUID activeOwnerId = activeOwnerId(); if (activeOwnerId != null && !requestedOwner.equals(activeOwnerId)) { return false; } - return OPENING_OWNER.compareAndSet(null, requestedOwner); + return openingOwner.compareAndSet(null, requestedOwner); } - public static void finishOpen(UUID ownerId) { + public void finishOpen(UUID ownerId) { if (ownerId != null) { - OPENING_OWNER.compareAndSet(ownerId, null); + openingOwner.compareAndSet(ownerId, null); } } - public static UUID openingOwnerId() { - return OPENING_OWNER.get(); + public UUID openingOwnerId() { + return openingOwner.get(); } - public static UUID activeOwnerId() { - for (ActiveRequest activeRequest : ACTIVE.values()) { + public UUID activeOwnerId() { + for (ActiveRequest activeRequest : active.values()) { UUID ownerId = activeRequest.request().ownerId(); if (ownerId != null) { return ownerId; @@ -223,30 +212,30 @@ public final class JigsawStudioActivation { return null; } - public static void deactivate(String packKey) { + public void deactivate(String packKey) { if (packKey != null) { - ACTIVE.remove(normalize(packKey)); - StagedState state = STAGED.get(); + active.remove(normalize(packKey)); + StagedState state = staged.get(); if (state != null && (normalize(state.candidate().request().packKey()).equals(normalize(packKey)) || state.preserved() != null && normalize(state.preserved().request().packKey()) .equals(normalize(packKey)))) { - STAGED.compareAndSet(state, null); + staged.compareAndSet(state, null); } } } - public static boolean deactivate(String packKey, UUID requestId) { + public boolean deactivate(String packKey, UUID requestId) { if (packKey == null || requestId == null) { return false; } - StagedState staged = STAGED.get(); - if (staged != null && staged.preserved() != null - && requestId.equals(staged.preserved().request().requestId()) - && normalize(packKey).equals(normalize(staged.preserved().request().packKey()))) { + StagedState stagedState = staged.get(); + if (stagedState != null && stagedState.preserved() != null + && requestId.equals(stagedState.preserved().request().requestId()) + && normalize(packKey).equals(normalize(stagedState.preserved().request().packKey()))) { return false; } AtomicBoolean removed = new AtomicBoolean(false); - ACTIVE.computeIfPresent(normalize(packKey), (key, activeRequest) -> { + active.computeIfPresent(normalize(packKey), (key, activeRequest) -> { if (!requestId.equals(activeRequest.request().requestId())) { return activeRequest; } @@ -256,47 +245,47 @@ public final class JigsawStudioActivation { return removed.get(); } - public static boolean isActive(String packKey) { + public boolean isActive(String packKey) { return getRequest(packKey) != null; } - public static Request getRequest(String packKey) { + public JigsawStudioRequest getRequest(String packKey) { ActiveRequest activeRequest = active(packKey); return activeRequest == null ? null : activeRequest.request(); } - public static JigsawStudioSession getSession(String packKey) { + public JigsawStudioSession getSession(String packKey) { ActiveRequest activeRequest = active(packKey); return activeRequest == null ? null : activeRequest.session(); } - public static JigsawStudioLayout getLayout(String packKey) { + public JigsawStudioLayout getLayout(String packKey) { JigsawStudioSession session = getSession(packKey); return session == null ? null : session.layout(); } - public static Request getRequest(UUID requestId) { + public JigsawStudioRequest getRequest(UUID requestId) { ActiveRequest activeRequest = active(requestId); return activeRequest == null ? null : activeRequest.request(); } - public static JigsawStudioSession getSession(UUID requestId) { + public JigsawStudioSession getSession(UUID requestId) { ActiveRequest activeRequest = active(requestId); return activeRequest == null ? null : activeRequest.session(); } - private static ActiveRequest active(String packKey) { + private ActiveRequest active(String packKey) { if (packKey == null) { return null; } - return ACTIVE.get(normalize(packKey)); + return active.get(normalize(packKey)); } - private static ActiveRequest active(UUID requestId) { + private ActiveRequest active(UUID requestId) { if (requestId == null) { return null; } - for (ActiveRequest activeRequest : ACTIVE.values()) { + for (ActiveRequest activeRequest : active.values()) { if (requestId.equals(activeRequest.request().requestId())) { return activeRequest; } @@ -310,11 +299,11 @@ public final class JigsawStudioActivation { JigsawStudioMode mode, JigsawStudioCompatibilityTarget compatibilityTarget, JigsawStudioCellDimensions cellDimensions, - IrisData source, + ToolPack source, JigsawStudioLayout initialLayout, UUID ownerId ) { - Request request = new Request( + JigsawStudioRequest request = new JigsawStudioRequest( UUID.randomUUID(), packKey, structureKey, @@ -322,6 +311,7 @@ public final class JigsawStudioActivation { compatibilityTarget, cellDimensions, source, + JigsawStudioRequest.rootOf(source), ownerId); JigsawStudioLayout layout = Objects.requireNonNull(initialLayout, "Initial Jigsaw Studio layout"); if (layout.mode() != mode) { @@ -338,17 +328,17 @@ public final class JigsawStudioActivation { return new ActiveRequest(request, session); } - private static StagedState stagedState(StagedActivation expected) { - StagedActivation staged = Objects.requireNonNull(expected, "Staged Jigsaw Studio activation"); - StagedState state = STAGED.get(); - return state != null && state.staged().stageId().equals(staged.stageId()) ? state : null; + private StagedState stagedState(StagedActivation expected) { + StagedActivation activation = Objects.requireNonNull(expected, "Staged Jigsaw Studio activation"); + StagedState state = staged.get(); + return state != null && state.staged().stageId().equals(activation.stageId()) ? state : null; } private static String normalize(String key) { return key.trim().toLowerCase(Locale.ROOT); } - private record ActiveRequest(Request request, JigsawStudioSession session) { + private record ActiveRequest(JigsawStudioRequest request, JigsawStudioSession session) { } private record StagedState( @@ -361,7 +351,7 @@ public final class JigsawStudioActivation { public record StagedActivation( UUID stageId, - Request request, + JigsawStudioRequest request, JigsawStudioSession session ) { public StagedActivation { @@ -373,37 +363,4 @@ public final class JigsawStudioActivation { } } } - - public record Request( - UUID requestId, - String packKey, - String structureKey, - JigsawStudioMode mode, - JigsawStudioCompatibilityTarget compatibilityTarget, - JigsawStudioCellDimensions cellDimensions, - IrisData source, - UUID ownerId - ) { - public Request { - requestId = Objects.requireNonNull(requestId, "Jigsaw Studio request ID"); - packKey = requireKey(packKey, "pack"); - structureKey = requireKey(structureKey, "structure"); - mode = Objects.requireNonNull(mode, "Jigsaw Studio mode"); - compatibilityTarget = Objects.requireNonNull( - compatibilityTarget, - "Jigsaw Studio compatibility target" - ); - cellDimensions = Objects.requireNonNull(cellDimensions, "Jigsaw Studio cell dimensions"); - source = Objects.requireNonNull(source, "Jigsaw Studio source data"); - } - - private static String requireKey(String value, String name) { - Objects.requireNonNull(value, "Jigsaw Studio " + name + " key"); - String normalized = value.trim(); - if (normalized.isEmpty()) { - throw new IllegalArgumentException("Jigsaw Studio " + name + " key cannot be blank"); - } - return normalized; - } - } } diff --git a/module/src/main/java/art/arcane/iris/core/service/JigsawStudioRequest.java b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioRequest.java new file mode 100644 index 000000000..a1a4f089b --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioRequest.java @@ -0,0 +1,76 @@ +package art.arcane.iris.core.service; + +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; +import com.volmit.tooling.ToolPack; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Path; +import java.util.Objects; +import java.util.UUID; + +/** + * What one open Jigsaw Studio was asked to edit, and who owns it. + * + * @param source the pack whose structure is edited + * @param packRoot the pack's folder, which the graph editors write below, as {@link ToolPack#edit} hands it out + */ +public record JigsawStudioRequest( + UUID requestId, + String packKey, + String structureKey, + JigsawStudioMode mode, + JigsawStudioCompatibilityTarget compatibilityTarget, + JigsawStudioCellDimensions cellDimensions, + ToolPack source, + Path packRoot, + UUID ownerId +) { + /** The folder of {@code pack}. */ + public static Path rootOf(ToolPack pack) { + try { + return pack.edit(root -> root); + } catch (IOException failure) { + throw new UncheckedIOException("Cannot reach the folder of the pack", failure); + } + } + + /** Makes {@code pack} read its files again after a tool changed them. */ + public static void reload(ToolPack pack) { + try { + pack.edit(root -> null); + } catch (IOException failure) { + throw new UncheckedIOException("Cannot reload the pack", failure); + } + } + + /** Makes the pack read the files again after the studio changed them. */ + public void reloadSource() { + reload(source); + } + + public JigsawStudioRequest { + requestId = Objects.requireNonNull(requestId, "Jigsaw Studio request ID"); + packKey = requireKey(packKey, "pack"); + structureKey = requireKey(structureKey, "structure"); + mode = Objects.requireNonNull(mode, "Jigsaw Studio mode"); + compatibilityTarget = Objects.requireNonNull( + compatibilityTarget, + "Jigsaw Studio compatibility target" + ); + cellDimensions = Objects.requireNonNull(cellDimensions, "Jigsaw Studio cell dimensions"); + source = Objects.requireNonNull(source, "Jigsaw Studio source pack"); + packRoot = Objects.requireNonNull(packRoot, "Jigsaw Studio pack folder"); + } + + private static String requireKey(String value, String name) { + Objects.requireNonNull(value, "Jigsaw Studio " + name + " key"); + String normalized = value.trim(); + if (normalized.isEmpty()) { + throw new IllegalArgumentException("Jigsaw Studio " + name + " key cannot be blank"); + } + return normalized; + } +} diff --git a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioResourceBundleAssembler.java b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioResourceBundleAssembler.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/service/JigsawStudioResourceBundleAssembler.java rename to module/src/main/java/art/arcane/iris/core/service/JigsawStudioResourceBundleAssembler.java diff --git a/module/src/main/java/art/arcane/iris/core/service/JigsawStudioScheduler.java b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioScheduler.java new file mode 100644 index 000000000..41a9dc4a1 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioScheduler.java @@ -0,0 +1,111 @@ +package art.arcane.iris.core.service; + +import com.volmit.ModuleLog; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolWorld; + +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * The studio's own clock: background work, and work that waits some game ticks before it hops to the thread that owns a + * player or a chunk. A tick is {@value #TICK_MILLIS} milliseconds here, as the server runs when it keeps up. + */ +final class JigsawStudioScheduler { + static final long TICK_MILLIS = 50L; + private static final int WORKER_THREADS = 2; + private static final long IDLE_WORKER_SECONDS = 30L; + private static final String THREAD_NAME_PREFIX = "jigsaw-studio-"; + + private final ModuleLog log; + private final ScheduledExecutorService executor; + private final Set departedPlayers = ConcurrentHashMap.newKeySet(); + + JigsawStudioScheduler(ModuleLog log) { + this.log = log; + AtomicInteger threadNumber = new AtomicInteger(); + ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(WORKER_THREADS, task -> { + Thread thread = new Thread(task, THREAD_NAME_PREFIX + threadNumber.incrementAndGet()); + thread.setDaemon(true); + return thread; + }); + pool.setRemoveOnCancelPolicy(true); + pool.setKeepAliveTime(IDLE_WORKER_SECONDS, TimeUnit.SECONDS); + pool.allowCoreThreadTimeOut(true); + this.executor = pool; + } + + /** Runs {@code task} off the server's threads, as soon as a worker is free. */ + void async(Runnable task) { + try { + executor.execute(guarded(task)); + } catch (RejectedExecutionException stopped) { + log.debug("A Jigsaw Studio background task was dropped because the studio stopped."); + } + } + + /** Runs {@code task} on a studio worker after {@code delayTicks}; it hops to a platform thread itself where it must. */ + void later(int delayTicks, Runnable task) { + try { + executor.schedule(guarded(task), delayTicks * TICK_MILLIS, TimeUnit.MILLISECONDS); + } catch (RejectedExecutionException stopped) { + log.debug("A Jigsaw Studio timer was dropped because the studio stopped."); + } + } + + /** + * Runs {@code task} on the player's thread after {@code delayTicks}. {@code retired} runs instead when the player has + * left by then or the scheduler is stopped. + */ + void onPlayerLater(ToolPlayer player, Runnable task, int delayTicks, Runnable retired) { + Runnable hop = () -> { + if (departedPlayers.contains(player.id())) { + retired.run(); + return; + } + JigsawStudioThreads.run(player, task); + }; + try { + executor.schedule(guarded(hop), delayTicks * TICK_MILLIS, TimeUnit.MILLISECONDS); + } catch (RejectedExecutionException stopped) { + retired.run(); + } + } + + /** + * Runs {@code task} on the thread that owns the chunk after {@code delayTicks}. {@code notScheduled} runs instead when + * the host cannot schedule it. + */ + void onRegionLater(ToolWorld world, int chunkX, int chunkZ, Runnable task, int delayTicks, Runnable notScheduled) { + Runnable hop = () -> JigsawStudioThreads.onRegion(log, world, chunkX, chunkZ, task, notScheduled); + try { + executor.schedule(guarded(hop), delayTicks * TICK_MILLIS, TimeUnit.MILLISECONDS); + } catch (RejectedExecutionException stopped) { + notScheduled.run(); + } + } + + void playerEntered(UUID playerId) { + departedPlayers.remove(playerId); + } + + void playerLeft(UUID playerId) { + departedPlayers.add(playerId); + } + + private Runnable guarded(Runnable task) { + return () -> { + try { + task.run(); + } catch (Throwable failure) { + log.error("A Jigsaw Studio background task failed.", failure); + } + }; + } +} diff --git a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioService.java b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioService.java similarity index 73% rename from core/src/main/java/art/arcane/iris/core/service/JigsawStudioService.java rename to module/src/main/java/art/arcane/iris/core/service/JigsawStudioService.java index cd75476e3..d54fa1af3 100644 --- a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioService.java +++ b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioService.java @@ -1,14 +1,9 @@ package art.arcane.iris.core.service; import art.arcane.iris.engine.framework.structure.StructureResources; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.core.modules.StructureAssemblies; -import art.arcane.iris.core.nms.INMS; -import art.arcane.iris.core.runtime.InPlaceChunkRegenerator; import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarArchetype; import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarDirection; import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarTopology; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioActivation; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBay; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBounds; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions; @@ -32,8 +27,6 @@ import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariant; import art.arcane.iris.core.structure.authoring.StructureTransactionWriter; import art.arcane.iris.core.structure.authoring.StructureWriteOptions; import art.arcane.iris.core.structure.authoring.StructureWriteResult; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.data.chunk.TerrainChunk; import art.arcane.iris.engine.framework.PlacedStructurePiece; import art.arcane.iris.engine.framework.StructureAssembler; import art.arcane.iris.engine.framework.structure.StructureAssemblyResult; @@ -42,102 +35,40 @@ import art.arcane.iris.engine.framework.structure.StructureGraphCompiler; import art.arcane.iris.engine.framework.structure.StructureGraphDiagnostic; import art.arcane.iris.engine.framework.structure.StructureGraphResolver; import art.arcane.iris.engine.framework.structure.StructureResourceBundleGraphCompiler; -import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; +import art.arcane.iris.engine.framework.structure.assembly.PieceTurn; 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.IrisJigsawThemeSet; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.ObjectTurn; -import art.arcane.iris.engine.object.prefab.BlockStateRotation; -import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint; -import art.arcane.iris.engine.object.prefab.TileData; import art.arcane.iris.engine.platform.studio.generators.JigsawStudioGenerator; -import art.arcane.iris.platform.bukkit.BukkitBlockState; -import art.arcane.iris.platform.bukkit.BukkitPlatform; -import art.arcane.iris.platform.bukkit.BukkitWorldBinding; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.spi.IrisServices; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.iris.util.common.plugin.IrisService; -import art.arcane.iris.util.common.scheduling.J; -import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.collection.KMap; import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.plugin.ComponentMessenger; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Chunk; -import org.bukkit.Color; -import org.bukkit.GameRules; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Particle; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.BlockState; -import org.bukkit.block.DoubleChest; -import org.bukkit.block.data.BlockData; -import org.bukkit.block.data.type.Jigsaw; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.block.Action; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockBurnEvent; -import org.bukkit.event.block.BlockCookEvent; -import org.bukkit.event.block.BlockDispenseEvent; -import org.bukkit.event.block.BlockExplodeEvent; -import org.bukkit.event.block.BlockFadeEvent; -import org.bukkit.event.block.BlockFormEvent; -import org.bukkit.event.block.BlockFromToEvent; -import org.bukkit.event.block.BlockGrowEvent; -import org.bukkit.event.block.BlockMultiPlaceEvent; -import org.bukkit.event.block.BlockPistonExtendEvent; -import org.bukkit.event.block.BlockPistonRetractEvent; -import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.block.BlockRedstoneEvent; -import org.bukkit.event.block.BlockSpreadEvent; -import org.bukkit.event.block.BrewingStartEvent; -import org.bukkit.event.block.CrafterCraftEvent; -import org.bukkit.event.entity.EntityChangeBlockEvent; -import org.bukkit.event.entity.EntityExplodeEvent; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.event.inventory.BrewEvent; -import org.bukkit.event.inventory.BrewingStandFuelEvent; -import org.bukkit.event.inventory.FurnaceBurnEvent; -import org.bukkit.event.inventory.FurnaceStartSmeltEvent; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.inventory.InventoryCloseEvent; -import org.bukkit.event.inventory.InventoryDragEvent; -import org.bukkit.event.inventory.InventoryMoveItemEvent; -import org.bukkit.event.inventory.InventoryPickupItemEvent; -import org.bukkit.event.player.PlayerBucketEmptyEvent; -import org.bukkit.event.player.PlayerBucketFillEvent; -import org.bukkit.event.player.PlayerChangedWorldEvent; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerMoveEvent; -import org.bukkit.event.player.PlayerPortalEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerRespawnEvent; -import org.bukkit.event.player.PlayerTeleportEvent; -import org.bukkit.event.player.PlayerToggleSneakEvent; -import org.bukkit.event.server.ServerCommandEvent; -import org.bukkit.event.world.ChunkLoadEvent; -import org.bukkit.event.world.StructureGrowEvent; -import org.bukkit.event.world.WorldUnloadEvent; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.BlockInventoryHolder; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.ItemStack; +import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockBox; +import com.volmit.geometry.BlockPosition; +import com.volmit.geometry.ChunkPos; +import com.volmit.object.BlockEntityData; +import com.volmit.object.GeneratedObject; +import com.volmit.object.ObjectBlock; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.ObjectCodec; +import com.volmit.tooling.ToolPack; +import com.volmit.tooling.world.BlockChange; +import com.volmit.tooling.world.Particle; +import com.volmit.tooling.world.ToolItem; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolText; +import com.volmit.tooling.world.ToolUse; +import com.volmit.tooling.world.ToolWorld; +import com.volmit.tooling.world.ToolWorldListener; +import com.volmit.tooling.world.ToolWorldSpec; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; @@ -159,7 +90,16 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; -public final class JigsawStudioService implements IrisService, JigsawStudioMenuController.Actions { +public final class JigsawStudioService implements JigsawStudioMenuController.Actions { + private static final String WORLD_NAME_PREFIX = "jigsaw-"; + private static final String MESSAGE_PREFIX = "[Iris Jigsaw Studio] "; + private static final ResourceId SAVE_SOUND = ResourceId.parse("minecraft:block.note_block.bell"); + private static final float SAVE_SOUND_VOLUME = 0.65F; + private static final float SAVE_SOUND_PITCH = 1.65F; + private static final int CHUNK_SHIFT = 4; + private static final float TELEPORT_PITCH_DEGREES = 45.0F; + private static final int RECONCILE_RETRY_TICKS = 1; + private static final double BLOCK_CENTER = 0.5D; private static final int AUTOSAVE_DEBOUNCE_TICKS = 40; private static final int AUTOSAVE_RETRY_TICKS = 5; private static final int REPLACEMENT_CLOSE_WAIT_TICKS = 2_400; @@ -177,13 +117,13 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC private static final int JIGSAW_TILE_WATCH_INTERVAL_TICKS = 5; private static final double VISUAL_RANGE = 96.0D; private static final double VISUAL_RANGE_SQUARED = VISUAL_RANGE * VISUAL_RANGE; - private static final Color SELECTED_COLOR = Color.AQUA; - private static final Color NEARBY_COLOR = Color.fromRGB(92, 102, 118); - private static final Color INVALID_BAY_COLOR = Color.RED; - private static final Color INVALID_CONNECTOR_COLOR = Color.RED; - private static final Color VALID_CONNECTOR_COLOR = Color.LIME; - private static final Color ASSEMBLY_PREVIEW_COLOR = Color.fromRGB(180, 90, 255); - private static final Color LIVE_PREVIEW_WARNING_COLOR = Color.fromRGB(255, 180, 55); + private static final int SELECTED_COLOR = 0x00FFFF; + private static final int NEARBY_COLOR = rgb(92, 102, 118); + private static final int INVALID_BAY_COLOR = 0xFF0000; + private static final int INVALID_CONNECTOR_COLOR = 0xFF0000; + private static final int VALID_CONNECTOR_COLOR = 0x00FF00; + private static final int ASSEMBLY_PREVIEW_COLOR = rgb(180, 90, 255); + private static final int LIVE_PREVIEW_WARNING_COLOR = rgb(255, 180, 55); private static final long ASSEMBLY_PREVIEW_MILLIS = 10_000L; private static final Set MUTATING_COMMANDS = Set.of( "biome", "brush", "chunk", "clone", "copy", "cut", "data", "deform", "drain", @@ -196,12 +136,14 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC "help", "list", "me", "msg", "ping", "pl", "plugins", "r", "reply", "rules", "say", "tell", "ver", "version", "w", "whisper"); private static final Comparator NEW_CONNECTOR_SOURCE_POSITION_ORDER = Comparator - .comparingInt((IrisJigsawConnector connector) -> connector.getPosition().getX()) - .thenComparingInt(connector -> connector.getPosition().getY()) - .thenComparingInt(connector -> connector.getPosition().getZ()); - private static JigsawStudioService INSTANCE; - + .comparingInt((IrisJigsawConnector connector) -> connector.getPosition().x()) + .thenComparingInt(connector -> connector.getPosition().y()) + .thenComparingInt(connector -> connector.getPosition().z()); + private final ModuleLog log; + private final JigsawStudioRegistry registry = new JigsawStudioRegistry(); + private final JigsawStudioScheduler scheduler; private final Map studios = new ConcurrentHashMap<>(); + private final Map> earlyChunks = new ConcurrentHashMap<>(); private final Set particlesDisabled = ConcurrentHashMap.newKeySet(); private final Set visualizationLoops = ConcurrentHashMap.newKeySet(); private final Map assemblyPreviews = new ConcurrentHashMap<>(); @@ -213,8 +155,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC private final Map evaluations = new ConcurrentHashMap<>(); private final JigsawStudioTripleSneakTracker tripleSneakTracker = new JigsawStudioTripleSneakTracker(); private final JigsawStudioToolCodec toolCodec = new JigsawStudioToolCodec(); - private final JigsawStudioPreviewRenderer previewRenderer = new JigsawStudioPreviewRenderer(); - private final AtomicBoolean disableStarted = new AtomicBoolean(); + private final JigsawStudioPreviewRenderer previewRenderer; private final Object saveLifecycleLock = new Object(); private final Set savesInProgress = new HashSet<>(); private final Set graphMutationsInProgress = new HashSet<>(); @@ -226,185 +167,112 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC private final Set unregisterRetries = ConcurrentHashMap.newKeySet(); private final Set unregisterDrainWarnings = ConcurrentHashMap.newKeySet(); private volatile JigsawStudioMenuController menuController; - private volatile boolean enabled; - public static JigsawStudioService get() { - JigsawStudioService service = INSTANCE; - return service == null ? IrisServices.get(JigsawStudioService.class) : service; + public JigsawStudioService(ModuleLog log) { + this.log = Objects.requireNonNull(log, "Jigsaw Studio log"); + this.scheduler = new JigsawStudioScheduler(log); + this.previewRenderer = new JigsawStudioPreviewRenderer(log); + this.menuController = new JigsawStudioMenuController(this, scheduler); + } + + public JigsawStudioRegistry registry() { + return registry; + } + + private void reportError(Throwable cause) { + log.error("A Jigsaw Studio operation failed.", cause); + } + + private void reportError(String message, Throwable cause) { + log.error(message, cause); + } + + private void warn(String format, Object... arguments) { + log.warn(String.format(Locale.ROOT, format, arguments)); + } + + private void debug(String format, Object... arguments) { + if (log.debugging()) { + log.debug(String.format(Locale.ROOT, format, arguments)); + } } public static void clearAutosaveHistory(Path packRoot, String structureKey) throws IOException { new JigsawStudioHistoryStore(packRoot, structureKey).delete(); } - @Override - public void onEnable() { - disableStarted.set(false); - enabled = true; - menuController = new JigsawStudioMenuController(BukkitPlatform.volmitPlugin(), this); - INSTANCE = this; + /** + * Opens the tool world of a staged studio and registers the studio once its players can enter. The world is named + * after the request, so every studio is a world of its own. + */ + public CompletableFuture open(ToolPack pack, JigsawStudioRegistry.StagedActivation staged) { + Objects.requireNonNull(pack, "Jigsaw Studio pack"); + Objects.requireNonNull(staged, "Jigsaw Studio staged activation"); + JigsawStudioGenerator generator = new JigsawStudioGenerator(pack, staged.request(), staged.session()); + ToolWorldSpec spec = new ToolWorldSpec( + worldName(staged.request().requestId()), + generator, + new JigsawStudioWorldListener(this, staged.request().requestId())); + return pack.worlds().open(spec).thenApply(world -> { + register(world, generator); + return world; + }); } - @Override - public void onDisable() { - quiesceForServerShutdown(); + /** The name of the tool world of the studio opened by {@code requestId}. */ + public static String worldName(UUID requestId) { + return WORLD_NAME_PREFIX + requestId; } - public void quiesceForServerShutdown() { - if (!disableStarted.compareAndSet(false, true)) { - return; - } - try { - finalizeAllJigsawTileWatches(); - } catch (Throwable exception) { - IrisLogging.reportError("Failed to finalize Jigsaw Studio tile watches during shutdown.", exception); - } - try { - drainAutosavesBeforeDisable(); - } catch (Throwable exception) { - IrisLogging.reportError("Failed to drain Jigsaw Studio autosaves during shutdown.", exception); - } - enabled = false; - JigsawStudioMenuController activeMenuController = menuController; - menuController = null; - if (activeMenuController != null) { - try { - activeMenuController.closeAll(); - } catch (Throwable exception) { - IrisLogging.reportError("Failed to close Jigsaw Studio menus during shutdown.", exception); - } - } - particlesDisabled.clear(); - visualizationLoops.clear(); - assemblyPreviews.clear(); - playerWorkcells.clear(); - autosaves.clear(); - deferredDuplications.clear(); - jigsawTileWatches.clear(); - toolConfirmations.clear(); - tripleSneakTracker.clearAll(); - evaluations.clear(); - try { - previewRenderer.removeAll(); - } catch (Throwable exception) { - IrisLogging.reportError("Failed to remove Jigsaw Studio previews during shutdown.", exception); - } - reopenRequiredRequests.clear(); - unregisterRetries.clear(); - unregisterDrainWarnings.clear(); - synchronized (saveLifecycleLock) { - studios.clear(); - savesInProgress.clear(); - graphMutationsInProgress.clear(); - materializationsInProgress.clear(); - exportsInProgress.clear(); - closingRequests.clear(); - discardingRequests.clear(); - } - INSTANCE = null; - } - - public void register(Engine engine, JigsawStudioGenerator generator) { - if (!enabled || disableStarted.get()) { - return; - } - Engine activeEngine = Objects.requireNonNull(engine, "Jigsaw Studio engine"); - JigsawStudioGenerator activeGenerator = Objects.requireNonNull(generator, "Jigsaw Studio generator"); - World world = BukkitWorldBinding.world(activeEngine.getTarget().getWorld()); - if (world == null) { - return; - } - ActiveStudio existing = studios.get(world.getUID()); - if (existing != null && existing.generator() == activeGenerator) { - return; - } - if (existing != null) { - UUID existingRequestId = existing.generator().getRequest().requestId(); - finalizeJigsawTileWatches(existingRequestId); - drainAutosavesBeforeRemoval(existing); - if (requiresLifecycleDrain(existing) && !discardingRequest(existingRequestId)) { - IrisLogging.warn("Jigsaw Studio registration deferred while request %s finishes its final autosave drain", - existingRequestId); - return; - } - } + void register(ToolWorld world, JigsawStudioGenerator generator) { + UUID worldId = generator.getRequest().requestId(); ActiveStudio next = new ActiveStudio( - world.getUID(), + worldId, world, - activeEngine, - activeGenerator, + generator, new ConcurrentHashMap<>(), ConcurrentHashMap.newKeySet(), new AtomicLong()); - UUID displacedRequestId = null; synchronized (saveLifecycleLock) { - if (!enabled || disableStarted.get()) { - return; - } - ActiveStudio previous = studios.get(world.getUID()); - if (previous != null && previous.generator() == activeGenerator) { - return; - } - ActiveStudio displaced = studios.put(world.getUID(), next); - if (displaced != null) { - displacedRequestId = displaced.generator().getRequest().requestId(); - savesInProgress.remove(displacedRequestId); - graphMutationsInProgress.remove(displacedRequestId); - materializationsInProgress.remove(displacedRequestId); - exportsInProgress.remove(displacedRequestId); - closingRequests.remove(displacedRequestId); - discardingRequests.remove(displacedRequestId); - reopenRequiredRequests.remove(displacedRequestId); - } + studios.put(worldId, next); } - if (displacedRequestId != null) { - clearAutosaves(displacedRequestId); - clearJigsawTileWatches(displacedRequestId); - unregisterRetries.remove(displacedRequestId); - unregisterDrainWarnings.remove(displacedRequestId); - tripleSneakTracker.clearRequest(displacedRequestId); - evaluations.remove(displacedRequestId); - previewRenderer.removeRequest(displacedRequestId); - } - IrisLogging.debug("Jigsaw Studio authoring registered: world=%s structure=%s bays=%d", - world.getName(), activeGenerator.getSession().structureKey(), activeGenerator.getLayout().bays().size()); + debug("Jigsaw Studio authoring registered: world=%s structure=%s bays=%d", + world.name(), generator.getSession().structureKey(), generator.getLayout().bays().size()); + replayChunksLoadedBeforeRegistration(next); scheduleInitialEvaluation(next); - scheduleOnlinePlayers(world.getUID()); + scheduleOnlinePlayers(worldId); } - public void activationCommitted(World world, UUID requestId) { - if (!enabled || disableStarted.get() || world == null || requestId == null) { + private void replayChunksLoadedBeforeRegistration(ActiveStudio studio) { + Set early = earlyChunks.remove(studio.worldId()); + if (early == null) { return; } - ActiveStudio studio = studios.get(world.getUID()); - if (studio == null || !requestId.equals(studio.generator().getRequest().requestId())) { + for (long chunkKey : early) { + markChunkAvailable(studio, (int) (chunkKey >> 32), (int) chunkKey); + } + } + + /** The studio whose world the player stands in; null when they stand elsewhere. */ + private ActiveStudio studioOf(ToolPlayer player) { + return player.world().flatMap(this::studioIn).orElse(null); + } + + private Optional studioIn(ToolWorld world) { + return studios.values().stream().filter(studio -> studio.world() == world).findFirst(); + } + + public void activationCommitted(UUID requestId) { + if (requestId == null) { + return; + } + ActiveStudio studio = studios.get(requestId); + if (studio == null) { return; } - disableNaturalStudioSpawning(world); scheduleInitialEvaluation(studio); } - public void markChunkGenerated( - Engine engine, - JigsawStudioGenerator generator, - int chunkX, - int chunkZ - ) { - if (!enabled || disableStarted.get() || engine == null || generator == null) { - return; - } - World world = BukkitWorldBinding.world(engine.getTarget().getWorld()); - if (world == null) { - return; - } - ActiveStudio studio = studios.get(world.getUID()); - if (!enabled || disableStarted.get() - || studio == null || studio.engine() != engine || studio.generator() != generator) { - return; - } - markChunkAvailable(studio, chunkX, chunkZ); - } - private void markChunkAvailable(ActiveStudio studio, int chunkX, int chunkZ) { long chunkKey = chunkKey(chunkX, chunkZ); boolean relevant = false; @@ -419,28 +287,28 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } } - public void unregister(World world) { - if (world == null) { + public void unregister(UUID worldId) { + if (worldId == null) { return; } - ActiveStudio active = studios.get(world.getUID()); + ActiveStudio active = studios.get(worldId); if (active != null) { UUID activeRequestId = active.generator().getRequest().requestId(); finalizeJigsawTileWatches(activeRequestId); drainAutosavesBeforeRemoval(active); if (requiresLifecycleDrain(active) && !discardingRequest(activeRequestId)) { if (unregisterDrainWarnings.add(activeRequestId)) { - IrisLogging.warn("Jigsaw Studio unregister deferred while request %s finishes its final autosave drain", + warn("Jigsaw Studio unregister deferred while request %s finishes its final autosave drain", activeRequestId); } - scheduleUnregisterRetry(world, activeRequestId); + scheduleUnregisterRetry(worldId, activeRequestId); return; } } ActiveStudio removed; - JigsawStudioActivation.Request request; + JigsawStudioRequest request; synchronized (saveLifecycleLock) { - removed = studios.remove(world.getUID()); + removed = studios.remove(worldId); if (removed == null) { return; } @@ -462,28 +330,23 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC tripleSneakTracker.clearRequest(request.requestId()); evaluations.remove(request.requestId()); previewRenderer.forgetRequest(request.requestId()); - JigsawStudioActivation.deactivate(request.packKey(), request.requestId()); - clearWorldPlayerContexts(world.getUID()); - IrisLogging.debug("Jigsaw Studio authoring unregistered: world=%s", world.getName()); + registry.deactivate(request.packKey(), request.requestId()); + clearWorldPlayerContexts(removed.world(), worldId); + debug("Jigsaw Studio authoring unregistered: world=%s", removed.world().name()); } - private void scheduleUnregisterRetry(World world, UUID requestId) { - if (!enabled || !unregisterRetries.add(requestId)) { + private void scheduleUnregisterRetry(UUID worldId, UUID requestId) { + if (!unregisterRetries.add(requestId)) { return; } - try { - J.s(() -> { - unregisterRetries.remove(requestId); - ActiveStudio current = studios.get(world.getUID()); - if (current != null - && current.generator().getRequest().requestId().equals(requestId)) { - unregister(world); - } - }, AUTOSAVE_RETRY_TICKS); - } catch (Throwable exception) { + scheduler.later(AUTOSAVE_RETRY_TICKS, () -> { unregisterRetries.remove(requestId); - IrisLogging.reportError(exception); - } + ActiveStudio current = studios.get(worldId); + if (current != null + && current.generator().getRequest().requestId().equals(requestId)) { + unregister(worldId); + } + }); } public CloseStart tryBeginClose(UUID requestId, UUID ownerId, boolean discard) { @@ -492,8 +355,8 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } finalizeJigsawTileWatches(requestId); synchronized (saveLifecycleLock) { - JigsawStudioActivation.Request request = JigsawStudioActivation.getRequest(requestId); - JigsawStudioSession session = JigsawStudioActivation.getSession(requestId); + JigsawStudioRequest request = registry.getRequest(requestId); + JigsawStudioSession session = registry.getSession(requestId); if (request == null || session == null) { return CloseStart.NOT_ACTIVE; } @@ -551,7 +414,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC if (materializationsInProgress.contains(requestId)) { return "The active Jigsaw Studio is loading or restoring a variant and cannot be closed yet."; } - JigsawStudioSession session = JigsawStudioActivation.getSession(requestId); + JigsawStudioSession session = registry.getSession(requestId); if (session != null && session.operationInProgress()) { return "The active Jigsaw Studio is loading a variant and cannot be closed or replaced yet."; } @@ -597,15 +460,11 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC : failure)); return; } - try { - J.s(() -> awaitCloseForReplacement( - requestId, - ownerId, - readiness, - waitedTicks + AUTOSAVE_RETRY_TICKS), AUTOSAVE_RETRY_TICKS); - } catch (Throwable exception) { - readiness.completeExceptionally(exception); - } + scheduler.later(AUTOSAVE_RETRY_TICKS, () -> awaitCloseForReplacement( + requestId, + ownerId, + readiness, + waitedTicks + AUTOSAVE_RETRY_TICKS)); } } } @@ -656,8 +515,8 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC Objects.requireNonNull(ownerId, "Jigsaw Studio export owner ID"); finalizeJigsawTileWatches(requestId); synchronized (saveLifecycleLock) { - JigsawStudioActivation.Request request = JigsawStudioActivation.getRequest(requestId); - JigsawStudioSession session = JigsawStudioActivation.getSession(requestId); + JigsawStudioRequest request = registry.getRequest(requestId); + JigsawStudioSession session = registry.getSession(requestId); if (request == null || session == null) { return ExportStart.NOT_ACTIVE; } @@ -698,14 +557,14 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } } - public boolean saveSelected(Player player) { + public boolean saveSelected(ToolPlayer player) { if (player == null) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> saveSelected(player)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> saveSelected(player)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null) { message(player, "Iris Jigsaw Studio is not active in this world."); return false; @@ -730,9 +589,8 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC JigsawStudioSession session = studio.generator().getSession(); String selected = session.selectedBayId().orElse(null); if (selected == null) { - Location location = player.getLocation(); - JigsawStudioBay underPlayer = session.layout().findAt( - location.getBlockX(), location.getBlockY(), location.getBlockZ()); + BlockPosition at = player.position(); + JigsawStudioBay underPlayer = session.layout().findAt(at.x(), at.y(), at.z()); if (underPlayer != null) { selected = underPlayer.stableId(); session.selectBay(selected); @@ -745,14 +603,14 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return saveBay(player, selected); } - public boolean saveBay(Player player, String bayId) { + public boolean saveBay(ToolPlayer player, String bayId) { if (player == null || bayId == null || bayId.isBlank()) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> saveBay(player, bayId)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> saveBay(player, bayId)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null) { message(player, "Iris Jigsaw Studio is not active in this world."); return false; @@ -765,14 +623,14 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC message(player, "No Jigsaw Studio bay matches '" + bayId + "'."); return false; } - return startSave(studio, player.getWorld(), bay, player, true) == SaveAttempt.STARTED; + return startSave(studio, studio.world(), bay, player, true) == SaveAttempt.STARTED; } private SaveAttempt startSave( ActiveStudio studio, - World world, + ToolWorld world, JigsawStudioBay bay, - Player player, + ToolPlayer player, boolean report ) { UUID requestId = studio.generator().getRequest().requestId(); @@ -871,21 +729,21 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC session.abortSave(saveIdentity); finishSave(requestId); refreshWorkcellContext(studio.worldId(), bay.stableId()); - IrisLogging.reportError(exception); + reportError(exception); report(player, report, "Jigsaw Studio could not schedule the workcell capture: " + failureMessage(exception)); return SaveAttempt.DEFERRED; } } - public boolean teleportTo(Player player, String bayId) { + public boolean teleportTo(ToolPlayer player, String bayId) { if (player == null || bayId == null || bayId.isBlank()) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> teleportTo(player, bayId)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> teleportTo(player, bayId)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null) { message(player, "Iris Jigsaw Studio is not active in this world."); return false; @@ -903,37 +761,34 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return false; } JigsawStudioBounds bounds = bay.bounds(); - Location destination = new Location( - player.getWorld(), + studio.generator().getSession().selectBay(bay.stableId()); + player.teleport( + studio.world(), bounds.originX() + bounds.dimensions().width() / 2.0D, bounds.maxY() + 2.0D, bounds.originZ() + bounds.dimensions().depth() / 2.0D, - player.getLocation().getYaw(), - 45.0F - ); - studio.generator().getSession().selectBay(bay.stableId()); - BukkitPlatform.teleportAsync(player, destination).thenRun(() -> J.runEntity( - player, - () -> reconcilePlayerContext(player, player.getLocation()))); + player.yaw(), + TELEPORT_PITCH_DEGREES + ).thenRun(() -> JigsawStudioThreads.run(player, () -> reconcilePlayerContext(player, player.position()))); message(player, "Selected Jigsaw Studio workcell '" + bay.stableId() + "'."); ensureVisualizationLoop(player); return true; } @Override - public boolean teleportToWorkcell(Player player, String workcellId) { + public boolean teleportToWorkcell(ToolPlayer player, String workcellId) { return teleportTo(player, workcellId); } @Override - public boolean setConnectorBlocksVisible(Player player, String workcellId, boolean visible) { + public boolean setConnectorBlocksVisible(ToolPlayer player, String workcellId, boolean visible) { if (player == null || workcellId == null || workcellId.isBlank()) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> setConnectorBlocksVisible(player, workcellId, visible)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> setConnectorBlocksVisible(player, workcellId, visible)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null || !authorizeOwner(player, studio)) { return false; } @@ -973,7 +828,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC message(player, (visible ? "Showing" : "Hiding") + " connector blocks in " + workcellId + "..."); return scheduleMaterialization(new MaterializationWork( studio, - player.getWorld(), + studio.world(), player, workcell, token, @@ -985,14 +840,14 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } @Override - public boolean resetConnectorBlocks(Player player, String workcellId) { + public boolean resetConnectorBlocks(ToolPlayer player, String workcellId) { if (player == null || workcellId == null || workcellId.isBlank()) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> resetConnectorBlocks(player, workcellId)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> resetConnectorBlocks(player, workcellId)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null || !authorizeOwner(player, studio)) { return false; } @@ -1010,7 +865,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC JigsawStudioGenerator.RenderedBay rendered = studio.generator().renderVariant( workcell, activeVariant); - String validationFailure = validateMaterialization(rendered); + String validationFailure = validateMaterialization(rendered, registryOf(studio)); if (!validationFailure.isEmpty()) { message(player, "Connector blocks cannot reset: " + validationFailure); return false; @@ -1036,14 +891,14 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } @Override - public boolean undoAutosave(Player player) { + public boolean undoAutosave(ToolPlayer player) { if (player == null) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> undoAutosave(player)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> undoAutosave(player)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null || !authorizeOwner(player, studio)) { return false; } @@ -1061,13 +916,12 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC workcell.stableId(), studio.generator().renderBay(workcell)))); } - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); message(player, "Restoring the previous Jigsaw Studio autosave iteration..."); return scheduleGraphMutation( player, studio, - () -> { - Path packRoot = request.source().getDataFolder().toPath(); + packRoot -> { JigsawStudioHistoryStore.UndoResult result = new JigsawStudioHistoryStore( packRoot, request.structureKey()).undoLatest(); @@ -1082,7 +936,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC throw new IOException("Jigsaw Studio undo failed: " + writeFailure(result.writeResult())); } - request.source().invalidateStructureResources(); + request.reloadSource(); JigsawStudioLayout restoredLayout = loadMappedLayout(studio); VariantReloadRequest reload = activeReloads.get(result.pieceKey()); Optional activeReload = reload == null @@ -1104,29 +958,29 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC }); } - public boolean setParticles(Player player, boolean visible) { + public boolean setParticles(ToolPlayer player, boolean visible) { if (player == null) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> setParticles(player, visible)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> setParticles(player, visible)); } - if (!studios.containsKey(player.getWorld().getUID())) { + if (studioOf(player) == null) { message(player, "Iris Jigsaw Studio is not active in this world."); return false; } if (visible) { - particlesDisabled.remove(player.getUniqueId()); + particlesDisabled.remove(player.id()); ensureVisualizationLoop(player); } else { - particlesDisabled.add(player.getUniqueId()); + particlesDisabled.add(player.id()); } message(player, "Jigsaw Studio particles " + (visible ? "enabled." : "disabled.")); return true; } public boolean switchVariant( - Player player, + ToolPlayer player, String workcellId, String targetPieceKey, boolean discardDirty @@ -1134,11 +988,11 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC if (player == null || workcellId == null || targetPieceKey == null) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> switchVariant( + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> switchVariant( player, workcellId, targetPieceKey, discardDirty)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null) { message(player, "Iris Jigsaw Studio is not active in this world."); return false; @@ -1181,7 +1035,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } private void reloadActiveVariant( - Player player, + ToolPlayer player, ActiveStudio studio, VariantReloadRequest reload ) { @@ -1205,7 +1059,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } private boolean materializeVariant( - Player player, + ToolPlayer player, ActiveStudio studio, JigsawStudioBay workcell, JigsawStudioSession.SwitchStart start, @@ -1236,7 +1090,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } JigsawStudioVariant previousVariant = token.previousVariant().orElse(null); if (previousVariant != null) { - String rollbackFailure = validateMaterialization(previous); + String rollbackFailure = validateMaterialization(previous, registryOf(studio)); if (!rollbackFailure.isEmpty()) { session.abortVariantSwitch(token); refreshWorkcellContext(studio.worldId(), workcell.stableId()); @@ -1249,7 +1103,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC message(player, "Loading variant '" + targetPieceKey + "' into " + workcell.stableId() + "..."); return scheduleMaterialization(new MaterializationWork( studio, - player.getWorld(), + studio.world(), player, workcell, token, @@ -1261,17 +1115,17 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } public boolean createVariant( - Player player, + ToolPlayer player, String workcellId, boolean duplicateActive ) { if (player == null || workcellId == null || workcellId.isBlank()) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> createVariant(player, workcellId, duplicateActive)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> createVariant(player, workcellId, duplicateActive)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null) { message(player, "Iris Jigsaw Studio is not active in this world."); return false; @@ -1296,7 +1150,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC message(player, sourceFailure); return false; } - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); if (duplicateActive && deferDuplicationUntilAutosaved( player, studio, @@ -1322,19 +1176,20 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return scheduleGraphMutation( player, studio, - () -> { - Path packRoot = request.source().getDataFolder().toPath(); + packRoot -> { String pieceKey = JigsawStudioGraphEditor.nextVariantKey( packRoot, request.structureKey(), archetypeKey); if (duplicateActive) { JigsawStudioGraphEditor.duplicatePiece( packRoot, + studio.generator().getPack().objects(), request.structureKey(), sourcePieceKey, pieceKey); } else { JigsawStudioGraphEditor.createBlankVariant( packRoot, + studio.generator().getPack().objects(), request.structureKey(), sourcePieceKey, pieceKey); @@ -1361,14 +1216,14 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } @Override - public boolean setWorkcellEnabled(Player player, String workcellId, boolean enabled) { + public boolean setWorkcellEnabled(ToolPlayer player, String workcellId, boolean enabled) { if (player == null || workcellId == null || workcellId.isBlank()) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> setWorkcellEnabled(player, workcellId, enabled)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> setWorkcellEnabled(player, workcellId, enabled)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null || !authorizeOwner(player, studio)) { return false; } @@ -1388,14 +1243,14 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC message(player, reservationFailure); return false; } - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); JigsawPlanarArchetype archetype = workcell.archetype().orElseThrow(); return scheduleGraphMutation( player, studio, - () -> { + packRoot -> { JigsawStudioStructureEditor.updateWorkcellEnabled( - request.source().getDataFolder().toPath(), + packRoot, request.structureKey(), archetype, enabled); @@ -1410,17 +1265,17 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC @Override public boolean updateWorkcellDimensions( - Player player, + ToolPlayer player, String workcellId, JigsawStudioCellDimensions dimensions ) { if (player == null || workcellId == null || workcellId.isBlank() || dimensions == null) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> updateWorkcellDimensions(player, workcellId, dimensions)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> updateWorkcellDimensions(player, workcellId, dimensions)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null || !authorizeOwner(player, studio)) { return false; } @@ -1445,26 +1300,26 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC message(player, reservationFailure); return false; } - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); JigsawPlanarArchetype archetype = workcell.archetype().orElse(null); return scheduleGraphMutation( player, studio, - () -> { + packRoot -> { JigsawStudioGraphEditor.WorkcellCapacityResult capacityResult = null; if (archetype == null) { JigsawStudioStructureEditor.updateCellSize( - request.source().getDataFolder().toPath(), + packRoot, request.structureKey(), dimensions); } else { capacityResult = JigsawStudioGraphEditor.updatePlanarWorkcellCapacity( - request.source().getDataFolder().toPath(), + packRoot, request.structureKey(), archetype, dimensions); } - request.source().invalidateStructureResources(); + request.reloadSource(); String resizeSummary = capacityResult == null ? "" : " Verified " + capacityResult.checkedVariants() + " existing variant" @@ -1481,18 +1336,18 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } @Override - public boolean setRequireCaps(Player player, boolean requireCaps) { + public boolean setRequireCaps(ToolPlayer player, boolean requireCaps) { if (player == null) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> setRequireCaps(player, requireCaps)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> setRequireCaps(player, requireCaps)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null || !authorizeOwner(player, studio)) { return false; } - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); if (request.compatibilityTarget() == JigsawStudioCompatibilityTarget.VANILLA_PORTABLE && requireCaps) { message(player, "Mandatory caps are Iris-only and cannot be enabled for a vanilla-portable graph."); @@ -1516,9 +1371,9 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return scheduleGraphMutation( player, studio, - () -> { + packRoot -> { JigsawStudioStructureEditor.updateRequireCaps( - request.source().getDataFolder().toPath(), + packRoot, request.structureKey(), requireCaps); return new CommandGraphMutationResult( @@ -1531,18 +1386,18 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } @Override - public boolean duplicateActiveFamily(Player player, String themeKey) { + public boolean duplicateActiveFamily(ToolPlayer player, String themeKey) { if (player == null || themeKey == null || themeKey.isBlank()) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> duplicateActiveFamily(player, themeKey)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> duplicateActiveFamily(player, themeKey)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null || !authorizeOwner(player, studio)) { return false; } - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); if (request.compatibilityTarget() == JigsawStudioCompatibilityTarget.VANILLA_PORTABLE) { message(player, "Coherent variant families are Iris-only and cannot be added to a vanilla-portable graph."); return false; @@ -1580,10 +1435,10 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return scheduleGraphMutation( player, studio, - () -> { + packRoot -> { JigsawStudioGraphEditor.VariantFamilyCreation creation = JigsawStudioGraphEditor.duplicateActiveFamily( - request.source().getDataFolder().toPath(), + packRoot, request.structureKey(), sourcePieces, themeKey); @@ -1607,18 +1462,18 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } @Override - public boolean updateThemeSetWeight(Player player, String themeKey, int weight) { + public boolean updateThemeSetWeight(ToolPlayer player, String themeKey, int weight) { if (player == null || themeKey == null || themeKey.isBlank() || weight < 1) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> updateThemeSetWeight(player, themeKey, weight)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> updateThemeSetWeight(player, themeKey, weight)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null || !authorizeOwner(player, studio)) { return false; } - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); if (request.compatibilityTarget() == JigsawStudioCompatibilityTarget.VANILLA_PORTABLE) { message(player, "Coherent theme sets are Iris-only."); return false; @@ -1655,9 +1510,9 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return scheduleGraphMutation( player, studio, - () -> { + packRoot -> { JigsawStudioStructureEditor.updateThemeSets( - request.source().getDataFolder().toPath(), + packRoot, request.structureKey(), updated); return new CommandGraphMutationResult( @@ -1670,7 +1525,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC @Override public boolean updateVariantThemes( - Player player, + ToolPlayer player, String workcellId, String pieceKey, List themes @@ -1678,11 +1533,11 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC if (player == null || pieceKey == null || themes == null) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> updateVariantThemes( + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> updateVariantThemes( player, workcellId, pieceKey, themes)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null || !authorizeOwner(player, studio)) { return false; } @@ -1690,7 +1545,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC if (variant == null) { return false; } - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); List targetThemes = List.copyOf(themes); if (request.compatibilityTarget() == JigsawStudioCompatibilityTarget.VANILLA_PORTABLE && !targetThemes.isEmpty()) { @@ -1723,9 +1578,9 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return scheduleGraphMutation( player, studio, - () -> { + packRoot -> { JigsawStudioGraphEditor.updatePieceThemes( - request.source().getDataFolder().toPath(), + packRoot, request.structureKey(), variant.pieceKey(), targetThemes); @@ -1739,7 +1594,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC @Override public boolean updateVariantRules( - Player player, + ToolPlayer player, String workcellId, String pieceKey, JigsawStudioPieceRules rules @@ -1747,11 +1602,11 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC if (player == null || pieceKey == null || rules == null) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> updateVariantRules( + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> updateVariantRules( player, workcellId, pieceKey, rules)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null || !authorizeOwner(player, studio)) { return false; } @@ -1759,7 +1614,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC if (variant == null) { return false; } - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); if (request.compatibilityTarget() == JigsawStudioCompatibilityTarget.VANILLA_PORTABLE && !DEFAULT_PIECE_RULES.equals(rules)) { message(player, "Piece placement rules are Iris-only for a vanilla-portable graph."); @@ -1778,9 +1633,9 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return scheduleGraphMutation( player, studio, - () -> { + packRoot -> { JigsawStudioGraphEditor.updatePieceRules( - request.source().getDataFolder().toPath(), + packRoot, request.structureKey(), variant.pieceKey(), rules); @@ -1792,14 +1647,14 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC }); } - public boolean toggleVariantRotatable(Player player, String workcellId) { + public boolean toggleVariantRotatable(ToolPlayer player, String workcellId) { if (player == null || workcellId == null || workcellId.isBlank()) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> toggleVariantRotatable(player, workcellId)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> toggleVariantRotatable(player, workcellId)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio != null && !authorizeOwner(player, studio)) { return false; } @@ -1807,7 +1662,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC if (variant == null) { return false; } - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); if (!canToggleVariantRotation(request.compatibilityTarget(), variant)) { message(player, "Vanilla-portable variants must remain rotatable."); return false; @@ -1822,9 +1677,9 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return scheduleGraphMutation( player, studio, - () -> { + packRoot -> { JigsawStudioGraphEditor.updateRotatable( - request.source().getDataFolder().toPath(), + packRoot, request.structureKey(), variant.pieceKey(), rotatable); @@ -1836,14 +1691,14 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC }); } - public boolean expandVariantToCell(Player player, String workcellId) { + public boolean expandVariantToCell(ToolPlayer player, String workcellId) { if (player == null || workcellId == null || workcellId.isBlank()) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> expandVariantToCell(player, workcellId)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> expandVariantToCell(player, workcellId)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio != null && !authorizeOwner(player, studio)) { return false; } @@ -1862,7 +1717,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC @Override public boolean resizeVariant( - Player player, + ToolPlayer player, String workcellId, String pieceKey, JigsawStudioCellDimensions dimensions @@ -1871,10 +1726,10 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC || pieceKey == null || pieceKey.isBlank() || dimensions == null) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> resizeVariant(player, workcellId, pieceKey, dimensions)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> resizeVariant(player, workcellId, pieceKey, dimensions)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null || !authorizeOwner(player, studio)) { return false; } @@ -1923,16 +1778,17 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC message(player, reservationFailure); return false; } - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); message(player, "Resizing variant '" + variant.resolvedDisplayName() + "' to " + dimensions.width() + "x" + dimensions.height() + "x" + dimensions.depth() + "..."); return scheduleGraphMutation( player, studio, - () -> { + packRoot -> { JigsawStudioGraphEditor.VariantResizeResult resize = JigsawStudioGraphEditor.resizePieceObject( - request.source().getDataFolder().toPath(), + packRoot, + studio.generator().getPack().objects(), request.structureKey(), variant.pieceKey(), dimensions); @@ -1954,7 +1810,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC @Override public boolean updateVariantDisplayName( - Player player, + ToolPlayer player, String workcellId, String pieceKey, String displayName @@ -1962,11 +1818,11 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC if (player == null || workcellId == null || pieceKey == null) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> updateVariantDisplayName( + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> updateVariantDisplayName( player, workcellId, pieceKey, displayName)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null || !authorizeOwner(player, studio)) { return false; } @@ -1993,13 +1849,13 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC message(player, reservationFailure); return false; } - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); return scheduleGraphMutation( player, studio, - () -> { + packRoot -> { JigsawStudioGraphEditor.updatePieceDisplayName( - request.source().getDataFolder().toPath(), + packRoot, request.structureKey(), pieceKey, normalizedName); @@ -2015,17 +1871,17 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC @Override public boolean updateWorkcellDisplayName( - Player player, + ToolPlayer player, String workcellId, String displayName ) { if (player == null || workcellId == null) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> updateWorkcellDisplayName(player, workcellId, displayName)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> updateWorkcellDisplayName(player, workcellId, displayName)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null || !authorizeOwner(player, studio)) { return false; } @@ -2047,20 +1903,20 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC message(player, reservationFailure); return false; } - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); JigsawPlanarArchetype archetype = workcell.archetype().orElse(null); return scheduleGraphMutation( player, studio, - () -> { + packRoot -> { if (archetype == null) { JigsawStudioStructureEditor.updateSpatialWorkcellDisplayName( - request.source().getDataFolder().toPath(), + packRoot, request.structureKey(), normalizedName); } else { JigsawStudioStructureEditor.updateWorkcellDisplayName( - request.source().getDataFolder().toPath(), + packRoot, request.structureKey(), archetype, normalizedName); @@ -2077,7 +1933,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC @Override public boolean adjustVariantWeight( - Player player, + ToolPlayer player, String workcellId, String pieceKey, String poolKey, @@ -2090,11 +1946,11 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC if (player == null || workcellId == null || pieceKey == null || poolKey == null) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> adjustVariantWeight( + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> adjustVariantWeight( player, workcellId, pieceKey, poolKey, entryIndex, delta)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio != null && !authorizeOwner(player, studio)) { return false; } @@ -2125,13 +1981,13 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC message(player, reservationFailure); return false; } - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); return scheduleGraphMutation( player, studio, - () -> { + packRoot -> { JigsawStudioPoolEditor.updateWeightAtIndex( - request.source().getDataFolder().toPath(), + packRoot, request.structureKey(), membership.poolKey(), membership.entryIndex(), @@ -2148,7 +2004,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC @Override public boolean adjustVariantChance( - Player player, + ToolPlayer player, String workcellId, String pieceKey, String poolKey, @@ -2159,8 +2015,8 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC || pieceKey == null || poolKey == null) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> adjustVariantChance( + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> adjustVariantChance( player, workcellId, pieceKey, @@ -2168,7 +2024,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC entryIndex, deltaPercentagePoints)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio != null && !authorizeOwner(player, studio)) { return false; } @@ -2187,7 +2043,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return false; } chance = Math.round(chance * 1_000_000.0D) / 1_000_000.0D; - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); if (request.compatibilityTarget() == JigsawStudioCompatibilityTarget.VANILLA_PORTABLE && chance != 1.0D) { message(player, "Chance gates are Iris-only and cannot be added to a vanilla-portable graph."); @@ -2203,9 +2059,9 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return scheduleGraphMutation( player, studio, - () -> { + packRoot -> { JigsawStudioPoolEditor.updateChanceAtIndex( - request.source().getDataFolder().toPath(), + packRoot, request.structureKey(), membership.poolKey(), membership.entryIndex(), @@ -2222,15 +2078,15 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } @Override - public boolean deleteVariant(Player player, String workcellId, String pieceKey) { + public boolean deleteVariant(ToolPlayer player, String workcellId, String pieceKey) { if (player == null || workcellId == null || workcellId.isBlank() || pieceKey == null || pieceKey.isBlank()) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> deleteVariant(player, workcellId, pieceKey)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> deleteVariant(player, workcellId, pieceKey)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null || !authorizeOwner(player, studio)) { return false; } @@ -2258,14 +2114,14 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC message(player, reservationFailure); return false; } - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); return scheduleGraphMutation( player, studio, - () -> { + packRoot -> { JigsawStudioGraphEditor.PieceDeletionResult deletion = JigsawStudioGraphEditor.deletePieceVariant( - request.source().getDataFolder().toPath(), + packRoot, request.structureKey(), pieceKey); return new CommandGraphMutationResult( @@ -2278,19 +2134,19 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC }); } - public boolean deleteProject(Player player) { + public boolean deleteProject(ToolPlayer player) { if (player == null) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> deleteProject(player)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> deleteProject(player)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null || !authorizeOwner(player, studio)) { return false; } - JigsawStudioActivation.Request request = studio.generator().getRequest(); - CloseStart closeStart = tryBeginClose(request.requestId(), player.getUniqueId(), false); + JigsawStudioRequest request = studio.generator().getRequest(); + CloseStart closeStart = tryBeginClose(request.requestId(), player.id(), false); if (closeStart != CloseStart.STARTED) { message(player, switch (closeStart) { case DIRTY -> "Wait for autosave to finish before deleting this project."; @@ -2302,24 +2158,23 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC }); return false; } - Path packRoot = request.source().getDataFolder().toPath(); message(player, "Inspecting owned resources and reverse references before project deletion..."); - J.a(() -> inspectProjectDeletion(player, studio, request, packRoot)); + scheduler.async(() -> inspectProjectDeletion(player, studio, request)); return true; } private void inspectProjectDeletion( - Player player, + ToolPlayer player, ActiveStudio studio, - JigsawStudioActivation.Request request, - Path packRoot + JigsawStudioRequest request ) { JigsawStudioProjectDeletionService.DeletionPlan plan; try { - plan = JigsawStudioProjectDeletionService.inspect(packRoot, request.structureKey()); + plan = studio.generator().getPack().edit(packRoot -> + JigsawStudioProjectDeletionService.inspect(packRoot, request.structureKey())); } catch (Throwable exception) { cancelClose(request.requestId()); - IrisLogging.reportError(exception); + reportError(exception); message(player, "Project deletion inspection failed: " + failureMessage(exception)); return; } @@ -2331,21 +2186,20 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC + plan.blockers().getFirst().location() + "."); return; } - boolean scheduled = J.runEntity( + scheduler.onPlayerLater( player, () -> closeAndDeleteProject(player, studio, request, plan), 0, - () -> cancelClose(request.requestId())); - if (!scheduled) { - cancelClose(request.requestId()); - message(player, "Project deletion stopped because the owner session ended."); - } + () -> { + cancelClose(request.requestId()); + message(player, "Project deletion stopped because the owner session ended."); + }); } private void closeAndDeleteProject( - Player player, + ToolPlayer player, ActiveStudio studio, - JigsawStudioActivation.Request request, + JigsawStudioRequest request, JigsawStudioProjectDeletionService.DeletionPlan plan ) { if (!isCurrentRequest(studio, request.requestId())) { @@ -2353,46 +2207,43 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC message(player, "Project deletion stopped because the Jigsaw Studio session changed."); return; } - IrisServices.get(StudioSVC.class).close().whenComplete((result, throwable) -> { - Throwable failure = throwable != null - ? throwable - : result == null ? new IllegalStateException("Studio close completed without a result") - : result.failureCause(); + studio.world().close().whenComplete((ignored, failure) -> { if (failure != null) { cancelClose(request.requestId()); - IrisLogging.reportError(failure); + reportError(failure); message(player, "Project deletion stopped because Studio could not close: " + failureMessage(failure)); return; } - J.a(() -> applyProjectDeletion(player, request, plan)); + scheduler.async(() -> applyProjectDeletion(player, studio.generator().getPack(), request, plan)); }); } private void applyProjectDeletion( - Player player, - JigsawStudioActivation.Request request, + ToolPlayer player, + ToolPack pack, + JigsawStudioRequest request, JigsawStudioProjectDeletionService.DeletionPlan plan ) { try { - JigsawStudioProjectDeletionService.ProjectDeletionResult result = - JigsawStudioProjectDeletionService.delete(plan); - try { - clearAutosaveHistory( - request.source().getDataFolder().toPath(), - request.structureKey()); - } catch (IOException historyFailure) { - IrisLogging.reportError(historyFailure); - message(player, "The project graph was deleted, but its autosave history could not be removed: " - + failureMessage(historyFailure)); - } - request.source().invalidateStructureResources(); + JigsawStudioProjectDeletionService.ProjectDeletionResult result = pack.edit(packRoot -> { + JigsawStudioProjectDeletionService.ProjectDeletionResult deleted = + JigsawStudioProjectDeletionService.delete(plan); + try { + clearAutosaveHistory(packRoot, request.structureKey()); + } catch (IOException historyFailure) { + reportError(historyFailure); + message(player, "The project graph was deleted, but its autosave history could not be removed: " + + failureMessage(historyFailure)); + } + return deleted; + }); message(player, "Deleted Jigsaw project '" + request.structureKey() + "' and " + result.removedResourceCount() + " owned resource(s)."); - IrisLogging.debug("Jigsaw Studio project deleted: structure=%s resources=%d", + debug("Jigsaw Studio project deleted: structure=%s resources=%d", request.structureKey(), result.removedResourceCount()); } catch (Throwable exception) { - IrisLogging.reportError(exception); + reportError(exception); message(player, "Studio closed, but the project was not deleted: " + failureMessage(exception) + ". Its files remain recoverable on disk."); } @@ -2400,7 +2251,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC @Override public boolean unlinkVariantMembership( - Player player, + ToolPlayer player, String workcellId, String pieceKey, String poolKey, @@ -2409,11 +2260,11 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC if (player == null || workcellId == null || pieceKey == null || poolKey == null) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> unlinkVariantMembership( + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> unlinkVariantMembership( player, workcellId, pieceKey, poolKey, entryIndex)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio != null && !authorizeOwner(player, studio)) { return false; } @@ -2432,13 +2283,13 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC message(player, reservationFailure); return false; } - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); return scheduleGraphMutation( player, studio, - () -> { + packRoot -> { JigsawStudioPoolEditor.removeEntry( - request.source().getDataFolder().toPath(), + packRoot, request.structureKey(), membership.poolKey(), membership.entryIndex(), @@ -2452,14 +2303,14 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC }); } - public boolean previewStudio(Player player, long seed) { + public boolean previewStudio(ToolPlayer player, long seed) { if (player == null) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> previewStudio(player, seed)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> previewStudio(player, seed)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null) { message(player, "Iris Jigsaw Studio is not active in this world."); return false; @@ -2467,61 +2318,59 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC if (!authorizeOwner(player, studio)) { return false; } - Location location = player.getLocation(); - IrisPosition origin = new IrisPosition( - location.getBlockX(), location.getBlockY(), location.getBlockZ()); - JigsawStudioActivation.Request request = studio.generator().getRequest(); - J.a(() -> { + BlockPosition playerAt = player.position(); + BlockPosition origin = new BlockPosition(playerAt.x(), playerAt.y(), playerAt.z()); + JigsawStudioRequest request = studio.generator().getRequest(); + ToolPack pack = studio.generator().getPack(); + scheduler.async(() -> { try { IrisStructure structure = StructureResources.structure( - request.source().getPackResources(), request.structureKey()); + pack.resources(), request.structureKey()); if (structure == null) { throw new IOException("The active structure resource no longer exists"); } - StructureAssembler assembler = StructureAssemblies.forData( - request.source(), structure, origin); + StructureAssembler assembler = StructureAssembler.forPack( + request.source().resources(), request.structureKey(), structure, origin, pack.log()); StructureAssemblyResult assembly = assembler.assemble(new RNG(seed)); if (!assembly.hasOutput()) { message(player, "The active graph assembled zero preview pieces."); return; } List pieces = assembly.pieces(); - if (!J.runEntity(player, () -> { + JigsawStudioThreads.run(player, () -> { if (isCurrentRequest(studio, request.requestId())) { showAssemblyPreview(player, pieces); message(player, "Showing a " + pieces.size() + "-piece particle preview for 10 seconds."); } - })) { - message(player, "The preview completed after the player session ended."); - } + }); } catch (Throwable exception) { - IrisLogging.reportError(exception); + reportError(exception); message(player, "Preview assembly failed: " + failureMessage(exception)); } }); return true; } - public Optional evaluation(Player player) { - if (player == null || !J.isOwnedByCurrentRegion(player)) { + public Optional evaluation(ToolPlayer player) { + if (player == null || !JigsawStudioThreads.owns(player)) { return Optional.empty(); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null || !ownerMatches(player, studio)) { return Optional.empty(); } return Optional.ofNullable(evaluations.get(studio.generator().getRequest().requestId())); } - public boolean goToPreview(Player player) { + public boolean goToPreview(ToolPlayer player) { if (player == null) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> goToPreview(player)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> goToPreview(player)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null || !authorizeOwner(player, studio)) { return false; } @@ -2534,16 +2383,14 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC : "The seed-1337 preview has no generated blocks: " + evaluation.detail()); return false; } - Location destination = new Location( + player.teleport( studio.world(), bounds.centerX() + 0.5D, bounds.maximumY() + 2.0D, bounds.centerZ() + 0.5D, - player.getLocation().getYaw(), - player.getLocation().getPitch()); - BukkitPlatform.teleportAsync(player, destination).thenRun(() -> J.runEntity( - player, - () -> message(player, "Teleported to the live seed-1337 preview."))); + player.yaw(), + player.pitch() + ).thenRun(() -> message(player, "Teleported to the live seed-1337 preview.")); return true; } @@ -2551,7 +2398,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC if (studio == null) { return; } - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); UUID requestId = request.requestId(); if (!claimInitialEvaluation( studio.evaluationGeneration(), @@ -2571,7 +2418,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC if (studio == null) { return; } - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); UUID requestId = request.requestId(); if (!isCurrentRequest(studio, requestId)) { return; @@ -2594,22 +2441,23 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC "Compiling the committed graph and assembling seed 1337", previousBounds)); refreshAllWorkcellContexts(studio); - J.a(() -> evaluateGraph(studio, requestId, generation)); + scheduler.async(() -> evaluateGraph(studio, requestId, generation)); } private void evaluateGraph(ActiveStudio studio, UUID requestId, long generation) { EvaluationComputation computation; try { - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); IrisStructure structure = StructureResources.structure( - request.source().getPackResources(), + studio.generator().getPack().resources(), request.structureKey()); if (structure == null) { throw new IOException("The active structure resource no longer exists"); } StructureGraphCompilation compilation = StructureGraphCompiler.compile( + request.structureKey(), structure, - StructureGraphResolver.forData(request.source())); + StructureGraphResolver.forPack(request.source().resources())); StructureGraphDiagnostic firstError = firstDiagnostic( compilation, StructureGraphDiagnostic.Severity.ERROR); @@ -2619,7 +2467,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC generation, firstError.code() + ": " + firstError.message()); } else { - IrisPosition origin = previewOrigin(studio.generator().getLayout(), structure); + BlockPosition origin = previewOrigin(studio.generator().getLayout(), structure); StructureAssembler assembler = StructureAssembler.forCompilation(compilation, origin); StructureAssemblyResult assembly = assembler.assemble(new RNG(PREVIEW_SEED)); computation = evaluationForAssembly( @@ -2627,10 +2475,11 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC generation, compilation, assembly, - studio.generator().getLayout().mode()); + studio.generator().getLayout().mode(), + studio.generator().getPack().resources()); } } catch (Throwable exception) { - IrisLogging.reportError(exception); + reportError(exception); computation = invalidEvaluation(requestId, generation, failureMessage(exception)); } completeEvaluation(studio, computation); @@ -2641,7 +2490,8 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC long generation, StructureGraphCompilation compilation, StructureAssemblyResult assembly, - JigsawStudioMode mode + JigsawStudioMode mode, + PackResources pack ) throws IOException { if (assembly.status().isFailure()) { return invalidEvaluation( @@ -2665,7 +2515,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC JigsawStudioPreviewRenderer.PreviewPlan.empty()); } List aligned = alignPreviewPieces(assembly.pieces(), mode); - JigsawStudioPreviewRenderer.PreviewPlan plan = JigsawStudioPreviewRenderer.plan(aligned); + JigsawStudioPreviewRenderer.PreviewPlan plan = JigsawStudioPreviewRenderer.plan(aligned, pack); StructureGraphDiagnostic firstWarning = firstDiagnostic( compilation, StructureGraphDiagnostic.Severity.WARNING); @@ -2758,9 +2608,9 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return null; } - private static IrisPosition previewOrigin(JigsawStudioLayout layout, IrisStructure structure) { + private static BlockPosition previewOrigin(JigsawStudioLayout layout, IrisStructure structure) { int radius = Math.max(1, structure.getMaxSizeChunks()) * 16; - return new IrisPosition( + return new BlockPosition( -radius - 32, 0, Math.max(16, layout.extentZ() / 2)); @@ -2782,6 +2632,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC for (PlacedStructurePiece piece : pieces) { aligned.add(new PlacedStructurePiece( piece.getPiece(), + piece.getObjectKey(), piece.getObject(), piece.getX(), piece.getY() + shiftY, @@ -2802,8 +2653,8 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } private static IrisStructure loadStudioStructure(ActiveStudio studio) { - JigsawStudioActivation.Request request = studio.generator().getRequest(); - return StructureResources.structure(request.source().getPackResources(), request.structureKey()); + JigsawStudioRequest request = studio.generator().getRequest(); + return StructureResources.structure(studio.generator().getPack().resources(), request.structureKey()); } private static boolean canResizeVariantToCapacity( @@ -2827,18 +2678,18 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC || canonical.depth() < target.depth()); } - public Optional menuState(Player player) { - if (player == null || !J.isOwnedByCurrentRegion(player)) { + public Optional menuState(ToolPlayer player) { + if (player == null || !JigsawStudioThreads.owns(player)) { return Optional.empty(); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null) { return Optional.empty(); } if (!ownerMatches(player, studio)) { return Optional.empty(); } - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); JigsawStudioSession session = studio.generator().getSession(); JigsawStudioLayout layout = session.layout(); IrisStructure structure = loadStudioStructure(studio); @@ -2909,14 +2760,14 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC workcells)); } - public boolean selectWorkcell(Player player, String workcellId) { + public boolean selectWorkcell(ToolPlayer player, String workcellId) { if (player == null || workcellId == null || workcellId.isBlank()) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> selectWorkcell(player, workcellId)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> selectWorkcell(player, workcellId)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null) { message(player, "Iris Jigsaw Studio is not active in this world."); return false; @@ -2933,10 +2784,10 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return true; } - public boolean openControlMenu(Player player) { - if (player != null && J.isOwnedByCurrentRegion(player)) { - finalizeJigsawTileWatchesForPlayer(player.getUniqueId()); - ActiveStudio studio = studios.get(player.getWorld().getUID()); + public boolean openControlMenu(ToolPlayer player) { + if (player != null && JigsawStudioThreads.owns(player)) { + finalizeJigsawTileWatchesForPlayer(player.id()); + ActiveStudio studio = studioOf(player); if (studio != null && reopenRequiredRequests.contains(studio.generator().getRequest().requestId())) { message(player, "Close and reopen Jigsaw Studio to apply the resized workcell layout."); @@ -2947,23 +2798,21 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return activeMenuController != null && activeMenuController.open(player); } - public boolean giveTool(Player player, JigsawStudioToolPayload payload) { + public boolean giveTool(ToolPlayer player, JigsawStudioToolPayload payload) { if (player == null || payload == null) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> giveTool(player, payload)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> giveTool(player, payload)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null || !studio.generator().getRequest().requestId().equals(payload.requestId()) || !authorizeOwner(player, studio)) { message(player, "This tool belongs to a different or closed Jigsaw Studio session."); return false; } - ItemStack tool = toolCodec.create(payload); - Map rejected = player.getInventory().addItem(tool); - if (!rejected.isEmpty()) { + if (!player.give(toolCodec.create(payload))) { message(player, "Your inventory is full; no Jigsaw Studio tool was added."); return false; } @@ -2971,14 +2820,14 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return true; } - public boolean flushAutosave(Player player, String workcellId) { + public boolean flushAutosave(ToolPlayer player, String workcellId) { if (player == null) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> flushAutosave(player, workcellId)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> flushAutosave(player, workcellId)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null || !authorizeOwner(player, studio)) { return false; } @@ -3015,7 +2864,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return false; } - public void closeMenu(Player player) { + public void closeMenu(ToolPlayer player) { JigsawStudioMenuController activeMenuController = menuController; if (activeMenuController != null) { activeMenuController.close(player); @@ -3023,15 +2872,15 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } private boolean useTool( - Player player, + ToolPlayer player, JigsawStudioToolPayload payload, - ItemStack tool, + ToolItem tool, boolean resetLabel ) { - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> useTool(player, payload, tool, resetLabel)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> useTool(player, payload, tool, resetLabel)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null || !studio.generator().getRequest().requestId().equals(payload.requestId()) || !authorizeOwner(player, studio)) { @@ -3091,7 +2940,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC }; } - private boolean toggleWorkcellFromTool(Player player, String workcellId) { + private boolean toggleWorkcellFromTool(ToolPlayer player, String workcellId) { Optional state = menuState(player); JigsawStudioMenuState.Workcell workcell = state .map(menu -> menu.workcell(workcellId)) @@ -3103,13 +2952,13 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return setWorkcellEnabled(player, workcellId, !workcell.enabled()); } - private boolean openWorkcellSettingsFromTool(Player player, String workcellId) { + private boolean openWorkcellSettingsFromTool(ToolPlayer player, String workcellId) { JigsawStudioMenuController activeMenuController = menuController; return activeMenuController != null && activeMenuController.openWorkcellSettings(player, workcellId); } - private boolean openVariantSettingsFromTool(Player player, JigsawStudioToolPayload payload) { + private boolean openVariantSettingsFromTool(ToolPlayer player, JigsawStudioToolPayload payload) { JigsawStudioMenuController activeMenuController = menuController; return activeMenuController != null && activeMenuController.openVariantSettings( @@ -3118,7 +2967,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC payload.pieceKey()); } - private boolean openVariantSizeSettingsFromTool(Player player, JigsawStudioToolPayload payload) { + private boolean openVariantSizeSettingsFromTool(ToolPlayer player, JigsawStudioToolPayload payload) { JigsawStudioMenuController activeMenuController = menuController; return activeMenuController != null && activeMenuController.openVariantSizeSettings( @@ -3128,9 +2977,9 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } private boolean renameVariantFromTool( - Player player, + ToolPlayer player, JigsawStudioToolPayload payload, - ItemStack tool, + ToolItem tool, boolean resetLabel ) { Optional displayName = toolDisplayName(player, payload, tool, resetLabel); @@ -3142,9 +2991,9 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } private boolean renameWorkcellFromTool( - Player player, + ToolPlayer player, JigsawStudioToolPayload payload, - ItemStack tool, + ToolItem tool, boolean resetLabel ) { Optional displayName = toolDisplayName(player, payload, tool, resetLabel); @@ -3155,20 +3004,16 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } private static Optional toolDisplayName( - Player player, + ToolPlayer player, JigsawStudioToolPayload payload, - ItemStack tool, + ToolItem tool, boolean resetLabel ) { if (resetLabel) { return Optional.of(""); } - String displayName = tool == null || !tool.hasItemMeta() || tool.getItemMeta() == null - ? "" - : tool.getItemMeta().getDisplayName(); - String normalized = ChatColor.stripColor(displayName); - normalized = normalized == null ? "" : normalized.trim(); - String defaultName = "Jigsaw Studio: " + payload.action().displayName(); + String normalized = tool == null ? "" : tool.name().plainText().trim(); + String defaultName = JigsawStudioToolCodec.NAME_PREFIX + payload.action().displayName(); if (normalized.isEmpty() || normalized.equals(defaultName)) { message(player, "Rename this bound stick in an anvil to the desired label, then right-click it. " + "Sneak-right-click resets the label."); @@ -3177,7 +3022,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return Optional.of(normalized); } - private boolean useThemeTool(Player player, JigsawStudioToolPayload payload) { + private boolean useThemeTool(ToolPlayer player, JigsawStudioToolPayload payload) { if (!payload.pieceKey().isBlank()) { return openVariantSettingsFromTool(player, payload); } @@ -3190,35 +3035,35 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC JigsawStudioMenuController.nextThemeSetKey(state.get().themeSets())); } - private boolean duplicateFamilyFromTool(Player player) { + private boolean duplicateFamilyFromTool(ToolPlayer player) { Optional state = menuState(player); return state.isPresent() && duplicateActiveFamily( player, JigsawStudioMenuController.nextThemeSetKey(state.get().themeSets())); } - private boolean toggleRequireCapsFromTool(Player player) { + private boolean toggleRequireCapsFromTool(ToolPlayer player) { Optional state = menuState(player); return state.isPresent() && setRequireCaps(player, !state.get().requireCaps()); } - private boolean confirmTool(Player player, JigsawStudioToolPayload payload) { + private boolean confirmTool(ToolPlayer player, JigsawStudioToolPayload payload) { long now = System.nanoTime(); - ToolConfirmation previous = toolConfirmations.get(player.getUniqueId()); + ToolConfirmation previous = toolConfirmations.get(player.id()); if (previous != null && previous.expiresAtNanos() >= now && previous.payload().equals(payload)) { - toolConfirmations.remove(player.getUniqueId(), previous); + toolConfirmations.remove(player.id(), previous); return true; } toolConfirmations.put( - player.getUniqueId(), + player.id(), new ToolConfirmation(payload, now + TOOL_CONFIRM_NANOS)); return false; } private JigsawStudioVariant activeOwnedVariant( - Player player, + ToolPlayer player, ActiveStudio studio, String workcellId ) { @@ -3245,7 +3090,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } private JigsawStudioVariant activeOwnedVariant( - Player player, + ToolPlayer player, ActiveStudio studio, String workcellId, String expectedPieceKey @@ -3275,7 +3120,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } private boolean deferDuplicationUntilAutosaved( - Player player, + ToolPlayer player, ActiveStudio studio, DeferredDuplication requested ) { @@ -3308,34 +3153,37 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC || !deferred.scheduled().compareAndSet(false, true)) { return; } - try { - J.s(() -> { - deferred.scheduled().set(false); - if (deferredDuplications.get(deferred.requestId()) != deferred) { - return; - } - Player player = Bukkit.getPlayer(deferred.playerId()); - if (player == null) { - deferredDuplications.remove(deferred.requestId(), deferred); - return; - } - boolean scheduled = J.runEntity( - player, - () -> resumeDeferredDuplication(player, deferred), - 0, - () -> deferredDuplications.remove(deferred.requestId(), deferred)); - if (!scheduled) { - deferredDuplications.remove(deferred.requestId(), deferred); - } - }, AUTOSAVE_RETRY_TICKS); - } catch (Throwable exception) { + scheduler.later(AUTOSAVE_RETRY_TICKS, () -> { deferred.scheduled().set(false); - deferredDuplications.remove(deferred.requestId(), deferred); - IrisLogging.reportError(exception); - } + if (deferredDuplications.get(deferred.requestId()) != deferred) { + return; + } + ToolPlayer player = onlinePlayer(studios.get(deferred.worldId()), deferred.playerId()); + if (player == null) { + deferredDuplications.remove(deferred.requestId(), deferred); + return; + } + scheduler.onPlayerLater( + player, + () -> resumeDeferredDuplication(player, deferred), + 0, + () -> deferredDuplications.remove(deferred.requestId(), deferred)); + }); } - private void resumeDeferredDuplication(Player player, DeferredDuplication deferred) { + private static ToolPlayer onlinePlayer(ActiveStudio studio, UUID playerId) { + if (studio == null) { + return null; + } + for (ToolPlayer candidate : studio.world().players()) { + if (candidate.id().equals(playerId)) { + return candidate; + } + } + return null; + } + + private void resumeDeferredDuplication(ToolPlayer player, DeferredDuplication deferred) { if (deferredDuplications.get(deferred.requestId()) != deferred) { return; } @@ -3344,7 +3192,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC boolean currentRequest = studio != null && studio.generator().getRequest().requestId().equals(deferred.requestId()) && session.sessionId().equals(deferred.sessionId()) - && player.getWorld().getUID().equals(deferred.worldId()); + && studioOf(player) == studio; boolean sourcesCurrent = currentRequest && sourceBindingsCurrent(session, deferred.sourcePieces()); boolean autosavePending; boolean operationPending; @@ -3474,7 +3322,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } public boolean runCommandGraphMutation( - Player player, + ToolPlayer player, UUID expectedRequestId, CommandGraphMutation task ) { @@ -3483,10 +3331,10 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC if (player == null) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> runCommandGraphMutation(player, expectedRequestId, task)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> runCommandGraphMutation(player, expectedRequestId, task)); } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null || !studio.generator().getRequest().requestId().equals(expectedRequestId)) { message(player, "This Jigsaw Studio session is no longer active."); @@ -3500,26 +3348,26 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC message(player, reservationFailure); return false; } - return scheduleGraphMutation(player, studio, task); + return scheduleGraphMutation(player, studio, packRoot -> task.run()); } private boolean scheduleGraphMutation( - Player player, + ToolPlayer player, ActiveStudio studio, - CommandGraphMutation task + RootedGraphMutation task ) { UUID requestId = studio.generator().getRequest().requestId(); - J.a(() -> { + scheduler.async(() -> { CommandGraphMutationResult result = null; Throwable failure = null; try { - result = task.run(); + result = studio.generator().getPack().edit(task::run); } catch (Throwable exception) { failure = exception; } CommandGraphMutationResult completedResult = result; Throwable completedFailure = failure; - boolean scheduled = J.runEntity( + scheduler.onPlayerLater( player, () -> completeGraphMutation( player, @@ -3528,19 +3376,24 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC completedResult, completedFailure), 0, - () -> finishGraphMutation(requestId)); - if (!scheduled) { - finishGraphMutation(requestId); - if (completedFailure != null) { - IrisLogging.reportError(completedFailure); - } - } + () -> { + finishGraphMutation(requestId); + if (completedFailure != null) { + reportError(completedFailure); + } + }); }); return true; } + /** A change to the pack's files the studio makes for a graph edit, given the pack folder it may change. */ + @FunctionalInterface + private interface RootedGraphMutation { + CommandGraphMutationResult run(Path packRoot) throws IOException; + } + private void completeGraphMutation( - Player player, + ToolPlayer player, ActiveStudio studio, UUID requestId, CommandGraphMutationResult result, @@ -3548,7 +3401,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC ) { try { if (failure != null) { - IrisLogging.reportError(failure); + reportError(failure); message(player, "Graph update failed: " + failureMessage(failure)); finishGraphMutation(requestId); return; @@ -3579,7 +3432,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } finishGraphMutationSuccess(player, studio, requestId, result); } catch (Throwable exception) { - IrisLogging.reportError(exception); + reportError(exception); message(player, "The graph updated on disk, but Studio could not refresh: " + failureMessage(exception) + ". Reopen this project before editing further."); reopenRequiredRequests.add(requestId); @@ -3588,7 +3441,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } private void finishGraphMutationSuccess( - Player player, + ToolPlayer player, ActiveStudio studio, UUID requestId, CommandGraphMutationResult result @@ -3611,79 +3464,91 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } private void scheduleLiveRelayout( - Player player, + ToolPlayer player, ActiveStudio studio, UUID requestId, JigsawStudioLayout previousLayout, CommandGraphMutationResult result ) { Set chunks = relayoutChunks(previousLayout, result.layout()); - AtomicInteger remaining = new AtomicInteger(chunks.size()); - AtomicReference failure = new AtomicReference<>(""); - AtomicReference cause = new AtomicReference<>(); if (chunks.isEmpty()) { completeLiveRelayout(player, studio, requestId, result, "", null); return; } - for (long chunkKey : chunks) { - int chunkX = (int) (chunkKey >> 32); - int chunkZ = (int) chunkKey; - boolean scheduled = J.runRegion(studio.world(), chunkX, chunkZ, () -> { + List positions = chunks.stream() + .map(chunkKey -> new ChunkPos((int) (chunkKey >> 32), (int) chunkKey.longValue())) + .toList(); + studio.world().repaint(positions).whenComplete((ignored, repaintFailure) -> { + if (repaintFailure != null) { + scheduleLiveRelayoutCompletion( + player, + studio, + requestId, + result, + "the chunks could not regenerate: " + failureMessage(repaintFailure), + repaintFailure); + return; + } + hydrateRepaintedChunks(player, studio, requestId, result, positions); + }); + } + + private void hydrateRepaintedChunks( + ToolPlayer player, + ActiveStudio studio, + UUID requestId, + CommandGraphMutationResult result, + List positions + ) { + AtomicInteger remaining = new AtomicInteger(positions.size()); + AtomicReference failure = new AtomicReference<>(""); + AtomicReference cause = new AtomicReference<>(); + Runnable chunkDone = () -> { + if (remaining.decrementAndGet() == 0) { + scheduleLiveRelayoutCompletion(player, studio, requestId, result, failure.get(), cause.get()); + } + }; + for (ChunkPos position : positions) { + JigsawStudioThreads.onRegion(log, studio.world(), position.x(), position.z(), () -> { try { - repaintStudioChunk(studio, chunkX, chunkZ); + hydrateRepaintedChunk(studio, position.x(), position.z()); } catch (Throwable exception) { - failure.compareAndSet("", "chunk " + chunkX + "," + chunkZ + failure.compareAndSet("", "chunk " + position.x() + "," + position.z() + " could not regenerate: " + failureMessage(exception)); cause.compareAndSet(null, exception); } - if (remaining.decrementAndGet() == 0) { - scheduleLiveRelayoutCompletion( - player, - studio, - requestId, - result, - failure.get(), - cause.get()); - } - }); - if (!scheduled) { - failure.compareAndSet("", "chunk " + chunkX + "," + chunkZ + chunkDone.run(); + }, () -> { + failure.compareAndSet("", "chunk " + position.x() + "," + position.z() + " could not be scheduled on its owning region"); - if (remaining.decrementAndGet() == 0) { - scheduleLiveRelayoutCompletion( - player, - studio, - requestId, - result, - failure.get(), - cause.get()); - } - } + chunkDone.run(); + }); } } private void scheduleLiveRelayoutCompletion( - Player player, + ToolPlayer player, ActiveStudio studio, UUID requestId, CommandGraphMutationResult result, String failure, Throwable cause ) { - boolean scheduled = J.runEntity( + scheduler.onPlayerLater( player, - () -> completeLiveRelayout(player, studio, requestId, result, failure, cause)); - if (!scheduled) { - reopenRequiredRequests.add(requestId); - finishGraphMutation(requestId); - if (cause != null) { - IrisLogging.reportError(cause); - } - } + () -> completeLiveRelayout(player, studio, requestId, result, failure, cause), + 0, + () -> { + reopenRequiredRequests.add(requestId); + finishGraphMutation(requestId); + if (cause != null) { + reportError(cause); + } + }); } private void completeLiveRelayout( - Player player, + ToolPlayer player, ActiveStudio studio, UUID requestId, CommandGraphMutationResult result, @@ -3694,7 +3559,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC reopenRequiredRequests.add(requestId); studio.populations().clear(); if (cause != null) { - IrisLogging.reportError(cause); + reportError(cause); } message(player, "The workcell size was saved, but live regeneration failed" + (failure.isEmpty() ? "." : ": " + failure + ".") @@ -3757,18 +3622,8 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } } - private static void repaintStudioChunk(ActiveStudio studio, int chunkX, int chunkZ) throws IOException { - World world = studio.world(); - Chunk chunk = world.getChunkAt(chunkX, chunkZ); - TerrainChunk generated = TerrainChunk.create(world); - studio.generator().paintChunk(generated, chunkX, chunkZ); - if (!INMS.get().applyChunkBlocks(chunk, generated)) { - InPlaceChunkRegenerator.applyBlockDiffs( - chunk, - generated.getChunkData(), - world.getMinHeight(), - world.getMaxHeight()); - } + private void hydrateRepaintedChunk(ActiveStudio studio, int chunkX, int chunkZ) throws IOException { + ToolWorld world = studio.world(); for (JigsawStudioBay workcell : studio.generator().getLayout().bays()) { JigsawStudioGenerator.RenderedBay rendered = studio.generator().renderBay(workcell); if (!rendered.valid()) { @@ -3780,7 +3635,6 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC applyRenderedBayChunk(world, workcell, rendered, chunkX, chunkZ, connectorsVisible); verifyRenderedBayChunk(world, workcell, rendered, chunkX, chunkZ, connectorsVisible); } - world.refreshChunk(chunkX, chunkZ); } private boolean graphMutationInProgress(UUID requestId) { @@ -3796,24 +3650,23 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } private static JigsawStudioLayout loadMappedLayout(ActiveStudio studio) throws IOException { - JigsawStudioActivation.Request request = studio.generator().getRequest(); - IrisData source = request.source(); - source.invalidateStructureResources(); - IrisStructure structure = StructureResources.structure(source.getPackResources(), request.structureKey()); + JigsawStudioRequest request = studio.generator().getRequest(); + request.reloadSource(); + IrisStructure structure = StructureResources.structure(request.source().resources(), request.structureKey()); if (structure == null) { throw new IOException("The structure could not be reloaded after the graph transaction"); } - return JigsawStudioGraphMapper.map(source, structure); + return JigsawStudioGraphMapper.map(request.source(), request.packRoot(), request.structureKey(), structure); } - public boolean showAssemblyPreview(Player player, List pieces) { + public boolean showAssemblyPreview(ToolPlayer player, List pieces) { if (player == null || pieces == null || pieces.isEmpty()) { return false; } - if (!J.isOwnedByCurrentRegion(player)) { - return J.runEntity(player, () -> showAssemblyPreview(player, pieces)); + if (!JigsawStudioThreads.owns(player)) { + return JigsawStudioThreads.call(player, () -> showAssemblyPreview(player, pieces)); } - if (!studios.containsKey(player.getWorld().getUID())) { + if (studioOf(player) == null) { message(player, "Iris Jigsaw Studio is not active in this world."); return false; } @@ -3828,86 +3681,89 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC piece.getMinZ(), new JigsawStudioCellDimensions(width, height, depth))); } - assemblyPreviews.put(player.getUniqueId(), new AssemblyPreview( - player.getWorld().getUID(), + assemblyPreviews.put(player.id(), new AssemblyPreview( + studioOf(player).worldId(), System.currentTimeMillis() + ASSEMBLY_PREVIEW_MILLIS, List.copyOf(bounds))); - particlesDisabled.remove(player.getUniqueId()); + particlesDisabled.remove(player.id()); ensureVisualizationLoop(player); return true; } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onWorldUnload(WorldUnloadEvent event) { - ActiveStudio studio = studios.get(event.getWorld().getUID()); + /** The world was unloaded: nothing can be saved from it any more, so the studio goes without a last drain. */ + void worldClosed(UUID worldId) { + earlyChunks.remove(worldId); + ActiveStudio studio = studios.get(worldId); if (studio != null) { UUID requestId = studio.generator().getRequest().requestId(); finalizeJigsawTileWatches(requestId); - if (requiresLifecycleDrain(studio) && !discardingRequest(requestId)) { - event.setCancelled(true); - expediteAutosaves(requestId); - IrisLogging.warn("Jigsaw Studio kept world %s loaded while pending edits finish autosaving", - event.getWorld().getName()); - return; + synchronized (saveLifecycleLock) { + discardingRequests.add(requestId); } } - unregister(event.getWorld()); + unregister(worldId); } - @EventHandler - public void onChunkLoad(ChunkLoadEvent event) { - ActiveStudio studio = studios.get(event.getWorld().getUID()); - if (studio != null) { - markChunkAvailable(studio, event.getChunk().getX(), event.getChunk().getZ()); + void chunkLoaded(UUID worldId, int chunkX, int chunkZ) { + ActiveStudio studio = studios.get(worldId); + if (studio == null) { + earlyChunks.computeIfAbsent(worldId, id -> ConcurrentHashMap.newKeySet()).add(chunkKey(chunkX, chunkZ)); + return; } + markChunkAvailable(studio, chunkX, chunkZ); } - @EventHandler - public void onPlayerJoin(PlayerJoinEvent event) { - ensureVisualizationLoop(event.getPlayer()); - reconcilePlayerContext(event.getPlayer(), event.getPlayer().getLocation()); + void playerEntered(ToolPlayer player) { + scheduler.playerEntered(player.id()); + closeMenu(player); + finalizeJigsawTileWatchesForPlayer(player.id()); + tripleSneakTracker.clearPlayer(player.id()); + visualizationLoops.remove(player.id()); + assemblyPreviews.remove(player.id()); + playerWorkcells.remove(player.id()); + ensureVisualizationLoop(player); } - @EventHandler - public void onPlayerChangedWorld(PlayerChangedWorldEvent event) { - closeMenu(event.getPlayer()); - finalizeJigsawTileWatchesForPlayer(event.getPlayer().getUniqueId()); - tripleSneakTracker.clearPlayer(event.getPlayer().getUniqueId()); - visualizationLoops.remove(event.getPlayer().getUniqueId()); - assemblyPreviews.remove(event.getPlayer().getUniqueId()); - playerWorkcells.remove(event.getPlayer().getUniqueId()); - ensureVisualizationLoop(event.getPlayer()); - reconcilePlayerContext(event.getPlayer(), event.getPlayer().getLocation()); + /** A player arrived by other means than walking; the host tells it at the time of the teleport, after the arrival it belongs to. */ + void playerTeleported(ToolPlayer player, BlockPosition to) { + finalizeJigsawTileWatchesForPlayer(player.id()); + reconcilePlayerContext(player, to); } - @EventHandler - public void onPlayerQuit(PlayerQuitEvent event) { - UUID playerId = event.getPlayer().getUniqueId(); - closeMenu(event.getPlayer()); + /** The contents of a container or machine changed without a block change: the container's workcell has unsaved work. */ + void containerChanged(UUID worldId, BlockPosition at) { + markDirty(studios.get(worldId), at); + } + + void playerLeft(ToolPlayer player) { + UUID playerId = player.id(); + scheduler.playerLeft(playerId); + closeMenu(player); finalizeJigsawTileWatchesForPlayer(playerId); tripleSneakTracker.clearPlayer(playerId); toolConfirmations.remove(playerId); visualizationLoops.remove(playerId); - particlesDisabled.remove(playerId); assemblyPreviews.remove(playerId); playerWorkcells.remove(playerId); deferredDuplications.entrySet().removeIf(entry -> entry.getValue().playerId().equals(playerId)); - boardService().clearJigsawContext(event.getPlayer()); + player.hideSidebar(); } - @EventHandler - public void onTripleSneak(PlayerToggleSneakEvent event) { - if (!event.isSneaking()) { + void playerMoved(ToolPlayer player, BlockPosition to) { + reconcilePlayerContext(player, to); + } + + void sneakToggled(ToolPlayer player, boolean sneaking) { + if (!sneaking) { return; } - Player player = event.getPlayer(); - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null || !ownerMatches(player, studio)) { - tripleSneakTracker.clearPlayer(player.getUniqueId()); + tripleSneakTracker.clearPlayer(player.id()); return; } JigsawStudioTripleSneakTracker.Progress progress = tripleSneakTracker.recordSneak( - player.getUniqueId(), + player.id(), studio.worldId(), studio.generator().getRequest().requestId(), System.nanoTime()); @@ -3916,558 +3772,205 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } } - @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onUseTool(PlayerInteractEvent event) { - if (event.getHand() != EquipmentSlot.HAND - || (event.getAction() != Action.RIGHT_CLICK_AIR - && event.getAction() != Action.RIGHT_CLICK_BLOCK)) { - return; + /** A player used their hand; false cancels it. */ + boolean playerUsed(UUID worldId, ToolPlayer player, ToolUse use) { + ActiveStudio studio = studios.get(worldId); + if (studio == null) { + return true; } - Optional decoded = toolCodec.decode(event.getItem()); - if (decoded.isEmpty()) { - return; - } - finalizeJigsawTileWatchesForPlayer(event.getPlayer().getUniqueId()); - event.setCancelled(true); - useTool(event.getPlayer(), decoded.get(), event.getItem(), event.getPlayer().isSneaking()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerMove(PlayerMoveEvent event) { - if (sameBlockPosition(event.getFrom(), event.getTo())) { - return; - } - reconcilePlayerContext(event.getPlayer(), event.getTo()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerTeleport(PlayerTeleportEvent event) { - finalizeJigsawTileWatchesForPlayer(event.getPlayer().getUniqueId()); - reconcilePlayerContext(event.getPlayer(), event.getTo()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerPortal(PlayerPortalEvent event) { - finalizeJigsawTileWatchesForPlayer(event.getPlayer().getUniqueId()); - reconcilePlayerContext(event.getPlayer(), event.getTo()); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerRespawn(PlayerRespawnEvent event) { - finalizeJigsawTileWatchesForPlayer(event.getPlayer().getUniqueId()); - reconcilePlayerContext(event.getPlayer(), event.getRespawnLocation()); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onNaturalCreatureSpawn(CreatureSpawnEvent event) { - if (studios.containsKey(event.getLocation().getWorld().getUID()) - && isNaturalStudioSpawn(event.getSpawnReason())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onUnauthorizedBlockPlace(BlockPlaceEvent event) { - if (isUnauthorizedStudioEdit(event.getPlayer(), event.getBlockPlaced())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onUnauthorizedBlockMultiPlace(BlockMultiPlaceEvent event) { - for (BlockState state : event.getReplacedBlockStates()) { - if (isUnauthorizedStudioEdit(event.getPlayer(), state.getBlock())) { - event.setCancelled(true); - return; - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedBlockBreak(BlockBreakEvent event) { - if (isControlChest(event.getBlock())) { - event.setCancelled(true); - message(event.getPlayer(), "The Jigsaw Studio control chest cannot be removed."); - return; - } - if (isUnauthorizedStudioEdit(event.getPlayer(), event.getBlock())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onUnauthorizedBucketEmpty(PlayerBucketEmptyEvent event) { - Block target = event.getBlockClicked().getRelative(event.getBlockFace()); - if (isUnauthorizedStudioEdit(event.getPlayer(), target)) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onUnauthorizedBucketFill(PlayerBucketFillEvent event) { - if (isUnauthorizedStudioEdit(event.getPlayer(), event.getBlockClicked())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onUnauthorizedInteract(PlayerInteractEvent event) { - if (event.getAction() == Action.RIGHT_CLICK_BLOCK - && !isControlChest(event.getClickedBlock()) - && isUnauthorizedStudioEdit(event.getPlayer(), event.getClickedBlock())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(BlockPlaceEvent event) { - markDirty(event.getBlockPlaced()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockMultiPlace(BlockMultiPlaceEvent event) { - for (BlockState state : event.getReplacedBlockStates()) { - markDirty(state.getBlock()); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockBreak(BlockBreakEvent event) { - markDirty(event.getBlock()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBucketEmpty(PlayerBucketEmptyEvent event) { - markDirty(event.getBlockClicked().getRelative(event.getBlockFace())); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBucketFill(PlayerBucketFillEvent event) { - markDirty(event.getBlockClicked()); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onControlChest(PlayerInteractEvent event) { - if (event.getAction() != Action.RIGHT_CLICK_BLOCK - || event.getHand() != EquipmentSlot.HAND - || !isControlChest(event.getClickedBlock())) { - return; - } - event.setCancelled(true); - ActiveStudio studio = studios.get(event.getPlayer().getWorld().getUID()); - if (!authorizeOwner(event.getPlayer(), studio)) { - return; - } - openControlMenu(event.getPlayer()); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedBlockExplode(BlockExplodeEvent event) { - if (materializationInProgress(studios.get(event.getBlock().getWorld().getUID()))) { - event.blockList().clear(); - return; - } - event.blockList().removeIf(this::isImmutableStudioBlock); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedEntityExplode(EntityExplodeEvent event) { - if (materializationInProgress(studios.get(event.getEntity().getWorld().getUID()))) { - event.blockList().clear(); - return; - } - event.blockList().removeIf(this::isImmutableStudioBlock); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedPistonExtend(BlockPistonExtendEvent event) { - if (materializationInProgress(studios.get(event.getBlock().getWorld().getUID())) - || movesProtectedBlocks(event.getBlocks(), event.getDirection())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedPistonRetract(BlockPistonRetractEvent event) { - if (materializationInProgress(studios.get(event.getBlock().getWorld().getUID())) - || movesProtectedBlocks(event.getBlocks(), event.getDirection())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedEntityChangeBlock(EntityChangeBlockEvent event) { - if (materializationInProgress(studios.get(event.getBlock().getWorld().getUID())) - || isImmutableStudioBlock(event.getBlock())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedBlockFromTo(BlockFromToEvent event) { - if (materializationInProgress(studios.get(event.getBlock().getWorld().getUID())) - || isImmutableStudioBlock(event.getBlock()) - || isImmutableStudioBlock(event.getToBlock())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedBlockForm(BlockFormEvent event) { - if (materializationInProgress(studios.get(event.getBlock().getWorld().getUID())) - || isImmutableStudioBlock(event.getBlock())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedBlockGrow(BlockGrowEvent event) { - if (materializationInProgress(studios.get(event.getBlock().getWorld().getUID())) - || isImmutableStudioBlock(event.getBlock())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedBlockSpread(BlockSpreadEvent event) { - if (materializationInProgress(studios.get(event.getBlock().getWorld().getUID())) - || isImmutableStudioBlock(event.getBlock()) - || isImmutableStudioBlock(event.getSource())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedBlockFade(BlockFadeEvent event) { - if (materializationInProgress(studios.get(event.getBlock().getWorld().getUID())) - || isImmutableStudioBlock(event.getBlock())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedBlockBurn(BlockBurnEvent event) { - if (materializationInProgress(studios.get(event.getBlock().getWorld().getUID())) - || isImmutableStudioBlock(event.getBlock())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onProtectedBlockRedstone(BlockRedstoneEvent event) { - if (materializationInProgress(studios.get(event.getBlock().getWorld().getUID())) - || isImmutableStudioBlock(event.getBlock())) { - event.setNewCurrent(event.getOldCurrent()); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedStructureGrow(StructureGrowEvent event) { - if (event.getLocation().getWorld() != null - && (materializationInProgress(studios.get(event.getLocation().getWorld().getUID())) - || containsImmutableStudioBlock(event.getBlocks()))) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedInventoryClick(InventoryClickEvent event) { - if (!blocksInventoryMutation( - event.getView().getTopInventory(), - event.getWhoClicked().getUniqueId())) { - return; - } - event.setCancelled(true); - if (event.getWhoClicked() instanceof Player player) { - message(player, "This Jigsaw Studio container is read-only during the current operation or owner session."); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedInventoryDrag(InventoryDragEvent event) { - if (!blocksInventoryMutation( - event.getView().getTopInventory(), - event.getWhoClicked().getUniqueId())) { - return; - } - event.setCancelled(true); - if (event.getWhoClicked() instanceof Player player) { - message(player, "This Jigsaw Studio container is read-only during the current operation or owner session."); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedInventoryMove(InventoryMoveItemEvent event) { - if (blocksInventoryMutation(event.getSource(), null) - || blocksInventoryMutation(event.getDestination(), null)) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedInventoryPickup(InventoryPickupItemEvent event) { - if (blocksInventoryMutation(event.getInventory(), null)) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedBlockCook(BlockCookEvent event) { - if (blocksMachineMutation(event.getBlock())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedFurnaceBurn(FurnaceBurnEvent event) { - if (blocksMachineMutation(event.getBlock())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedBrew(BrewEvent event) { - if (blocksMachineMutation(event.getBlock())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedBrewingStandFuel(BrewingStandFuelEvent event) { - if (blocksMachineMutation(event.getBlock())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedBlockDispense(BlockDispenseEvent event) { - if (blocksMachineMutation(event.getBlock())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onProtectedCrafterCraft(CrafterCraftEvent event) { - if (blocksMachineMutation(event.getBlock())) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerInteract(PlayerInteractEvent event) { - if (event.getAction() != Action.RIGHT_CLICK_BLOCK && event.getAction() != Action.PHYSICAL) { - return; - } - Block clicked = event.getClickedBlock(); - if (clicked != null) { - if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { - finalizeJigsawTileWatchesForPlayer(event.getPlayer().getUniqueId()); - if (clicked.getType() == Material.JIGSAW) { - startJigsawTileWatch(event.getPlayer(), clicked); - } - } - markDirty(clicked); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onInventoryClick(InventoryClickEvent event) { - markDirty(event.getView().getTopInventory()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onInventoryDrag(InventoryDragEvent event) { - markDirty(event.getView().getTopInventory()); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onInventoryClose(InventoryCloseEvent event) { - markDirty(event.getView().getTopInventory()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onInventoryMove(InventoryMoveItemEvent event) { - markDirty(event.getSource()); - markDirty(event.getDestination()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onInventoryPickup(InventoryPickupItemEvent event) { - markDirty(event.getInventory()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockCook(BlockCookEvent event) { - markDirty(event.getBlock()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onFurnaceBurn(FurnaceBurnEvent event) { - markDirty(event.getBlock()); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onFurnaceStartSmelt(FurnaceStartSmeltEvent event) { - markDirty(event.getBlock()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBrew(BrewEvent event) { - markDirty(event.getBlock()); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onBrewingStart(BrewingStartEvent event) { - markDirty(event.getBlock()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBrewingStandFuel(BrewingStandFuelEvent event) { - markDirty(event.getBlock()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockDispense(BlockDispenseEvent event) { - markDirty(event.getBlock()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onCrafterCraft(CrafterCraftEvent event) { - markDirty(event.getBlock()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockExplode(BlockExplodeEvent event) { - markDirty(event.blockList()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onEntityExplode(EntityExplodeEvent event) { - markDirty(event.blockList()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onEntityChangeBlock(EntityChangeBlockEvent event) { - markDirty(event.getBlock()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockFromTo(BlockFromToEvent event) { - markDirty(event.getToBlock()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockForm(BlockFormEvent event) { - markDirty(event.getBlock()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockGrow(BlockGrowEvent event) { - markDirty(event.getBlock()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockSpread(BlockSpreadEvent event) { - markDirty(event.getBlock()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockFade(BlockFadeEvent event) { - markDirty(event.getBlock()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockBurn(BlockBurnEvent event) { - markDirty(event.getBlock()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockRedstone(BlockRedstoneEvent event) { - markDirty(event.getBlock()); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPistonExtend(BlockPistonExtendEvent event) { - markDirty(event.getBlock()); - markDirty(event.getBlock().getRelative(event.getDirection())); - for (Block block : event.getBlocks()) { - markDirty(block); - markDirty(block.getRelative(event.getDirection())); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPistonRetract(BlockPistonRetractEvent event) { - markDirty(event.getBlock()); - markDirty(event.getBlock().getRelative(event.getDirection())); - for (Block block : event.getBlocks()) { - markDirty(block); - markDirty(block.getRelative(event.getDirection())); - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onStructureGrow(StructureGrowEvent event) { - for (BlockState state : event.getBlocks()) { - markDirty(state.getBlock()); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onUnauthorizedPlayerCommand(PlayerCommandPreprocessEvent event) { - finalizeJigsawTileWatchesForPlayer(event.getPlayer().getUniqueId()); - ActiveStudio studio = studios.get(event.getPlayer().getWorld().getUID()); - if (studio != null - && materializationInProgress(studio) - && !isSafeNonOwnerCommand(event.getMessage())) { - event.setCancelled(true); - message(event.getPlayer(), "Wait for the current Jigsaw Studio variant load or rollback to finish."); - return; - } - if (studio != null && blocksNonEditableWorkcellMutation( - hasNonEditableWorkcell(studio), event.getMessage())) { - event.setCancelled(true); - message(event.getPlayer(), "Mutating commands are disabled while this Studio has an empty or read-only workcell."); - return; - } - UUID ownerId = studio == null ? null : studio.generator().getRequest().ownerId(); - if (!blocksMutatingCommand(ownerId, event.getPlayer().getUniqueId(), event.getMessage())) { - return; - } - event.setCancelled(true); - message(event.getPlayer(), "This Jigsaw Studio is owned by another player session."); - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerCommand(PlayerCommandPreprocessEvent event) { - if (isMutatingCommand(event.getMessage())) { - markAllDirty(event.getPlayer().getWorld()); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onServerCommand(ServerCommandEvent event) { - if (!isSafeNonOwnerCommand(event.getCommand()) && anyMaterializationInProgress()) { - event.setCancelled(true); - return; - } - if (isMutatingCommand(event.getCommand()) && anyNonEditableWorkcell()) { - event.setCancelled(true); - return; - } - if (isMutatingCommand(event.getCommand())) { - markAllDirty(); - } - } - - public boolean markDirty(World world, int worldX, int worldY, int worldZ) { - if (world == null) { + if (usesStudioTool(player, use)) { return false; } - ActiveStudio studio = studios.get(world.getUID()); + boolean rightClickBlock = use.action() == ToolUse.Action.RIGHT_CLICK_BLOCK; + if (rightClickBlock && use.block().isPresent()) { + BlockPosition clicked = use.block().get(); + if (isControlChest(studio, clicked)) { + return !opensControlMenu(player, studio, use); + } + if (isUnauthorizedStudioEdit(player, studio, clicked)) { + return false; + } + } + observeInteraction(player, studio, use); + return true; + } + + private boolean usesStudioTool(ToolPlayer player, ToolUse use) { + boolean rightClick = use.action() == ToolUse.Action.RIGHT_CLICK_AIR + || use.action() == ToolUse.Action.RIGHT_CLICK_BLOCK; + if (use.hand() != ToolUse.Hand.MAIN || !rightClick || use.item().isEmpty()) { + return false; + } + Optional decoded = toolCodec.decode(use.item().get()); + if (decoded.isEmpty()) { + return false; + } + finalizeJigsawTileWatchesForPlayer(player.id()); + useTool(player, decoded.get(), use.item().get(), player.sneaking()); + return true; + } + + private boolean opensControlMenu(ToolPlayer player, ActiveStudio studio, ToolUse use) { + if (use.hand() != ToolUse.Hand.MAIN) { + return false; + } + if (authorizeOwner(player, studio)) { + openControlMenu(player); + } + return true; + } + + private void observeInteraction(ToolPlayer player, ActiveStudio studio, ToolUse use) { + boolean interacted = use.action() == ToolUse.Action.RIGHT_CLICK_BLOCK + || use.action() == ToolUse.Action.PHYSICAL; + if (!interacted || use.block().isEmpty()) { + return; + } + BlockPosition clicked = use.block().get(); + if (use.action() == ToolUse.Action.RIGHT_CLICK_BLOCK) { + finalizeJigsawTileWatchesForPlayer(player.id()); + if (blockIfOwned(studio, clicked).filter(JigsawStudioBlocks::isJigsaw).isPresent()) { + startJigsawTileWatch(player, studio, clicked); + } + } + markDirty(studio, clicked); + } + + private static Optional blockIfOwned(ActiveStudio studio, BlockPosition at) { + return studio.world().owns(at) ? Optional.of(studio.world().block(at)) : Optional.empty(); + } + + /** Something is about to change blocks; false cancels it. */ + boolean blockChanging(UUID worldId, BlockChange change) { + ActiveStudio studio = studios.get(worldId); if (studio == null) { return false; } + if (!allowsBlockChange(studio, change)) { + return false; + } + markChangedBlocksDirty(studio, change); + return true; + } + + private boolean allowsBlockChange(ActiveStudio studio, BlockChange change) { + ToolPlayer player = change.player().orElse(null); + return switch (change.cause()) { + case PLACE, BUCKET -> change.positions().stream() + .noneMatch(position -> isUnauthorizedStudioEdit(player, studio, position)); + case BREAK -> allowsBreak(player, studio, change.positions().getFirst()); + case CONTAINER -> !blocksContainerMutation(studio, change); + case MACHINE -> change.positions().stream().noneMatch(position -> blocksMachineMutation(studio, position)); + case PHYSICS, FLUID, GROWTH, FIRE, REDSTONE, PISTON, EXPLOSION, ENTITY -> + !materializationInProgress(studio) + && change.positions().stream().noneMatch(position -> isImmutableStudioBlock(studio, position)); + }; + } + + private boolean allowsBreak(ToolPlayer player, ActiveStudio studio, BlockPosition position) { + if (isControlChest(studio, position)) { + message(player, "The Jigsaw Studio control chest cannot be removed."); + return false; + } + return !isUnauthorizedStudioEdit(player, studio, position); + } + + private boolean blocksContainerMutation(ActiveStudio studio, BlockChange change) { + UUID actorId = change.player().map(ToolPlayer::id).orElse(null); + for (BlockPosition position : change.positions()) { + StudioBlockMutationContext context = studioBlockMutationContext(studio, position); + if (context != null && blocksStudioInventoryMutation( + true, + context.immutable(), + materializationInProgress(context.studio()), + reopenRequiredRequests.contains(context.requestId()), + context.ownerId(), + actorId)) { + change.player().ifPresent(player -> message( + player, + "This Jigsaw Studio container is read-only during the current operation or owner session.")); + return true; + } + } + return false; + } + + private void markChangedBlocksDirty(ActiveStudio studio, BlockChange change) { + List positions = change.positions(); + switch (change.cause()) { + case FLUID -> markDirty(studio, positions.getLast()); + case PHYSICS -> markDirty(studio, positions.getFirst()); + case PISTON -> change.changed().forEach(position -> markDirty(studio, position)); + default -> positions.forEach(position -> markDirty(studio, position)); + } + } + + /** A command is about to run; false cancels it. */ + boolean command(UUID worldId, Optional sender, String line) { + ActiveStudio studio = studios.get(worldId); + if (sender.isPresent()) { + return playerCommand(studio, sender.get(), line); + } + return consoleCommand(studio, line); + } + + private boolean playerCommand(ActiveStudio studio, ToolPlayer player, String line) { + finalizeJigsawTileWatchesForPlayer(player.id()); + if (studio != null + && materializationInProgress(studio) + && !isSafeNonOwnerCommand(line)) { + message(player, "Wait for the current Jigsaw Studio variant load or rollback to finish."); + return false; + } + if (studio != null && blocksNonEditableWorkcellMutation(hasNonEditableWorkcell(studio), line)) { + message(player, "Mutating commands are disabled while this Studio has an empty or read-only workcell."); + return false; + } + UUID ownerId = studio == null ? null : studio.generator().getRequest().ownerId(); + if (blocksMutatingCommand(ownerId, player.id(), line)) { + message(player, "This Jigsaw Studio is owned by another player session."); + return false; + } + if (studio != null && isMutatingCommand(line)) { + markAllDirty(studio); + } + return true; + } + + private boolean consoleCommand(ActiveStudio studio, String line) { + if (!isSafeNonOwnerCommand(line) && anyMaterializationInProgress()) { + return false; + } + if (isMutatingCommand(line) && anyNonEditableWorkcell()) { + return false; + } + if (studio != null && isMutatingCommand(line)) { + markAllDirty(studio); + } + return true; + } + + /** Whether the host may close the world now, as the message that says why not. */ + Optional closeRefusal(UUID worldId) { + return Optional.ofNullable(closeProtectionFailure(worldId)); + } + + /** + * Gets the studio ready to close, for a replacement or for the host stopping: saves what the calling thread may save + * at once, then waits for the autosaves that must run elsewhere. + */ + CompletableFuture closing(UUID worldId, Optional by) { + drainAutosavesBeforeRemoval(studios.get(worldId)); + return awaitCloseForReplacement(worldId, by.map(ToolPlayer::id).orElse(null)); + } + + private boolean markDirty(ActiveStudio studio, BlockPosition at) { + if (studio == null) { + return false; + } + int worldX = at.x(); + int worldY = at.y(); + int worldZ = at.z(); if (reopenRequiredRequests.contains(studio.generator().getRequest().requestId())) { return false; } @@ -4492,20 +3995,12 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return true; } - public int markAllDirty(World world) { - if (world == null) { - return 0; - } - ActiveStudio studio = studios.get(world.getUID()); - return studio == null ? 0 : markAllDirty(studio); - } - private boolean scheduleCapture( ActiveStudio studio, - World world, + ToolWorld world, JigsawStudioBay bay, CaptureTarget captureTarget, - Player player, + ToolPlayer player, UUID requestId, JigsawStudioSession.SaveIdentity saveIdentity, AutosaveFailureState autosaveFailureState @@ -4527,22 +4022,20 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC if (coordinator.stopped()) { return false; } - boolean scheduled = J.runRegion( + JigsawStudioThreads.onRegion( + log, world, area.chunkX(), area.chunkZ(), - () -> captureChunk(coordinator, area)); - if (!scheduled) { - coordinator.fail("Iris could not schedule bay chunk " - + area.chunkX() + "," + area.chunkZ() + " on its owning region.", null); - return false; - } + () -> captureChunk(coordinator, area), + () -> coordinator.fail("Iris could not schedule bay chunk " + + area.chunkX() + "," + area.chunkZ() + " on its owning region.", null)); } return !coordinator.stopped(); } private boolean scheduleMaterialization(MaterializationWork work) { - String validationFailure = validateMaterialization(work.target()); + String validationFailure = validateMaterialization(work.target(), registryOf(work.studio())); if (!validationFailure.isEmpty()) { work.studio().generator().getSession().abortVariantSwitch(work.token()); refreshWorkcellContext(work.studio().worldId(), work.workcell().stableId()); @@ -4560,20 +4053,18 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC List areas = chunkIntersections(work.workcell().bounds()); MaterializationCoordinator coordinator = new MaterializationCoordinator(work, areas); for (ChunkCaptureArea area : areas) { - boolean scheduled = J.runRegion( + coordinator.markScheduled(); + JigsawStudioThreads.onRegion( + log, work.world(), area.chunkX(), area.chunkZ(), - () -> materializeCandidateChunk(coordinator, area)); - if (!scheduled) { - coordinator.candidateComplete( - area, - "Iris could not schedule workcell chunk " - + area.chunkX() + "," + area.chunkZ() + " on its owning region.", - null); - } else { - coordinator.markScheduled(); - } + () -> materializeCandidateChunk(coordinator, area), + () -> coordinator.candidateComplete( + area, + "Iris could not schedule workcell chunk " + + area.chunkX() + "," + area.chunkZ() + " on its owning region.", + null)); } return coordinator.scheduledAny(); } @@ -4639,7 +4130,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } private boolean scheduleConnectorRepair( - Player player, + ToolPlayer player, ActiveStudio studio, JigsawStudioBay workcell, JigsawStudioGenerator.RenderedBay rendered, @@ -4666,14 +4157,16 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC : connectorsByChunk.entrySet()) { int chunkX = (int) (entry.getKey() >> 32); int chunkZ = (int) entry.getKey().longValue(); - boolean scheduled = J.runRegion(studio.world(), chunkX, chunkZ, () -> { + scheduledAny.set(true); + JigsawStudioThreads.onRegion(log, studio.world(), chunkX, chunkZ, () -> { try { - if (!studio.world().isChunkLoaded(chunkX, chunkZ)) { + if (!studio.isChunkLoaded(chunkX, chunkZ)) { throw new IOException("connector chunk " + chunkX + "," + chunkZ + " is not loaded"); } restoreConnectorChunk( studio.world(), + studio.generator().getPack().resources().blocks(), workcell, entry.getValue(), renderedBlocks, @@ -4690,10 +4183,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC failure.get(), cause.get()); } - }); - if (scheduled) { - scheduledAny.set(true); - } else { + }, () -> { failure.compareAndSet("", "connector chunk " + chunkX + "," + chunkZ + " could not be scheduled on its owning region"); if (remaining.decrementAndGet() == 0) { @@ -4704,7 +4194,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC failure.get(), cause.get()); } - } + }); } if (!scheduledAny.get()) { finishMaterialization(studio.generator().getRequest().requestId()); @@ -4713,17 +4203,17 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } private void completeConnectorRepair( - Player player, + ToolPlayer player, ActiveStudio studio, int connectorCount, String failure, Throwable cause ) { UUID requestId = studio.generator().getRequest().requestId(); - boolean scheduled = J.runEntity(player, () -> { + scheduler.onPlayerLater(player, () -> { finishMaterialization(requestId); if (cause != null) { - IrisLogging.reportError(cause); + reportError(cause); } if (!failure.isEmpty()) { message(player, "Connector reset was incomplete: " + failure + ". Retry after visiting the workcell."); @@ -4731,17 +4221,17 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } message(player, "Restored " + connectorCount + " connector block(s) from the last saved iteration."); - }); - if (!scheduled) { + }, 0, () -> { finishMaterialization(requestId); if (cause != null) { - IrisLogging.reportError(cause); + reportError(cause); } - } + }); } static void restoreConnectorChunk( - World world, + ToolWorld world, + BlockRegistry registry, JigsawStudioBay workcell, List connectors, Map renderedBlocks, @@ -4750,51 +4240,45 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC JigsawStudioBounds bounds = workcell.bounds(); for (JigsawStudioGenerator.RenderedConnector connector : connectors) { LocalPosition position = new LocalPosition(connector.x(), connector.y(), connector.z()); - Block target = world.getBlockAt( + BlockPosition target = new BlockPosition( bounds.originX() + connector.x(), bounds.originY() + connector.y(), bounds.originZ() + connector.z()); if (connectorsVisible) { - BlockData marker; - try { - marker = Bukkit.createBlockData( - "minecraft:jigsaw[orientation=" + connector.orientation() + "]"); - } catch (IllegalArgumentException exception) { - throw new IOException("Invalid saved connector orientation '" - + connector.orientation() + "'", exception); - } - target.setBlockData(marker, false); - BukkitPlatform.deserializeTile(markerNbt(connector.connector()), target.getLocation()); + BlockState marker = jigsawMarker(registry, connector.orientation()) + .orElseThrow(() -> new IOException("Invalid saved connector orientation '" + + connector.orientation() + "'")); + world.setBlock(target, marker, Optional.of(markerBlockEntity(connector.connector()))); continue; } JigsawStudioGenerator.RenderedBlock renderedBlock = renderedBlocks.get(position); - BlockData restored; - if (renderedBlock != null) { - if (renderedBlock.state().isCustom() - || !(renderedBlock.state().nativeHandle() instanceof BlockData blockData)) { - throw new IOException("Saved connector block '" + renderedBlock.state().key() - + "' cannot be restored directly in Bukkit Studio"); - } - restored = blockData; - } else { - try { - restored = Bukkit.createBlockData(connector.connector().getFinalState()); - } catch (IllegalArgumentException exception) { - throw new IOException("Invalid saved connector final state '" - + connector.connector().getFinalState() + "'", exception); - } - } - target.setBlockData(restored, false); - if (renderedBlock != null && renderedBlock.tileData() != null) { - TileData tileData = renderedBlock.tileData(); - if (!tileData.isApplicable(target.getBlockData()) || !tileData.toBukkitTry(target)) { - throw new IOException("Saved connector tile data could not be restored at " - + target.getX() + "," + target.getY() + "," + target.getZ()); - } + BlockState restored = renderedBlock != null + ? renderedBlock.state() + : registry.find(connector.connector().getFinalState()) + .orElseThrow(() -> new IOException("Invalid saved connector final state '" + + connector.connector().getFinalState() + "'")); + Optional blockEntity = renderedBlock == null + ? Optional.empty() + : Optional.ofNullable(renderedBlock.blockEntity()); + try { + world.setBlock(target, restored, blockEntity); + } catch (IllegalArgumentException exception) { + throw new IOException("Saved connector tile data could not be restored at " + + target.x() + "," + target.y() + "," + target.z(), exception); } } } + /** The jigsaw block of the platform facing {@code orientation}; empty when the platform has no such block. */ + private static Optional jigsawMarker(BlockRegistry registry, String orientation) { + return registry.find(JigsawStudioBlocks.jigsawMarker(orientation).key()) + .filter(JigsawStudioBlocks::isJigsaw); + } + + private static BlockEntityData markerBlockEntity(IrisJigsawConnector connector) { + return JigsawStudioTileCodec.encode(JigsawStudioBlocks.JIGSAW_BLOCK, markerNbt(connector)); + } + private void finishMaterialization(UUID requestId) { synchronized (saveLifecycleLock) { materializationsInProgress.remove(requestId); @@ -4813,7 +4297,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC null); return; } - if (!work.world().isChunkLoaded(area.chunkX(), area.chunkZ())) { + if (!work.studio().isChunkLoaded(area.chunkX(), area.chunkZ())) { coordinator.candidateComplete( area, "Workcell chunk " + area.chunkX() + "," + area.chunkZ() @@ -4825,6 +4309,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC coordinator.markCandidateTouched(area); writeMaterializedChunk( work.world(), + work.studio().generator().getPack().resources().blocks(), work.workcell(), work.target(), area, @@ -4851,7 +4336,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC null); return; } - if (!work.world().isChunkLoaded(area.chunkX(), area.chunkZ())) { + if (!work.studio().isChunkLoaded(area.chunkX(), area.chunkZ())) { coordinator.rollbackComplete( area, "Rollback chunk " + area.chunkX() + "," + area.chunkZ() + " is not loaded.", @@ -4861,6 +4346,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC try { writeMaterializedChunk( work.world(), + work.studio().generator().getPack().resources().blocks(), work.workcell(), work.previous(), area, @@ -4875,54 +4361,43 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } } - static String validateMaterialization(JigsawStudioGenerator.RenderedBay rendered) { + static String validateMaterialization(JigsawStudioGenerator.RenderedBay rendered, BlockRegistry registry) { if (!rendered.valid()) { return rendered.failure(); } for (JigsawStudioGenerator.RenderedBlock block : rendered.blocks()) { - PlatformBlockState state = block.state(); - if (state.isCustom()) { - return "custom block '" + state.key() - + "' requires provider-owned placement and cannot be swapped live in Studio"; - } - if (!(state.nativeHandle() instanceof BlockData)) { - return "block '" + state.key() + "' has no Bukkit block-data representation"; + BlockState state = block.state(); + if (registry.find(state.key()).isEmpty()) { + return "block '" + state.key() + "' has no block representation on this platform"; } } for (JigsawStudioGenerator.RenderedConnector connector : rendered.connectors()) { - try { - BlockData data = Bukkit.createBlockData( - "minecraft:jigsaw[orientation=" + connector.orientation() + "]"); - if (!(data instanceof Jigsaw)) { - return "connector orientation '" + connector.orientation() - + "' did not resolve to a jigsaw marker"; - } - } catch (IllegalArgumentException exception) { + if (jigsawMarker(registry, connector.orientation()).isEmpty()) { return "connector orientation '" + connector.orientation() + "' is invalid"; } } return ""; } - private static void writeMaterializedChunk( - World world, + private void writeMaterializedChunk( + ToolWorld world, + BlockRegistry registry, JigsawStudioBay workcell, JigsawStudioGenerator.RenderedBay rendered, ChunkCaptureArea area, boolean connectorsVisible ) throws IOException { JigsawStudioBounds bounds = workcell.bounds(); - Map expected = materializedBlockData(rendered, connectorsVisible); - BlockData air = Material.AIR.createBlockData(); + Map expected = materializedBlocks(registry, rendered, connectorsVisible); for (int x = area.minimumX(); x < area.maximumX(); x++) { for (int y = 0; y < bounds.dimensions().height(); y++) { for (int z = area.minimumZ(); z < area.maximumZ(); z++) { - Block target = world.getBlockAt( + BlockPosition target = new BlockPosition( bounds.originX() + x, bounds.originY() + y, bounds.originZ() + z); - BlockData blockData = expected.getOrDefault(new LocalPosition(x, y, z), air); - target.setBlockData(blockData, false); + BlockState state = expected.getOrDefault(new LocalPosition(x, y, z), JigsawStudioBlocks.AIR); + world.setBlock(target, state, Optional.empty()); } } } @@ -4930,58 +4405,51 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC verifyMaterializedChunk(world, workcell, rendered, area, expected, connectorsVisible); } - private static Map materializedBlockData( + private static Map materializedBlocks( + BlockRegistry registry, JigsawStudioGenerator.RenderedBay rendered, boolean connectorsVisible ) throws IOException { - Map expected = new HashMap<>(); + Map expected = new HashMap<>(); for (JigsawStudioGenerator.RenderedBlock block : rendered.blocks()) { - if (block.state().isCustom() || !(block.state().nativeHandle() instanceof BlockData blockData)) { - throw new IOException("Rendered block '" + block.state().key() - + "' cannot be placed directly in Bukkit Studio"); - } - expected.put(new LocalPosition(block.x(), block.y(), block.z()), blockData); + expected.put(new LocalPosition(block.x(), block.y(), block.z()), block.state()); } for (JigsawStudioGenerator.RenderedConnector connector : rendered.connectors()) { if (!connectorsVisible && expected.containsKey( new LocalPosition(connector.x(), connector.y(), connector.z()))) { continue; } - BlockData marker; - try { - marker = Bukkit.createBlockData(connectorsVisible - ? "minecraft:jigsaw[orientation=" + connector.orientation() + "]" - : connector.connector().getFinalState()); - } catch (IllegalArgumentException exception) { - throw new IOException("Invalid rendered connector orientation '" - + connector.orientation() + "'", exception); - } - expected.put(new LocalPosition(connector.x(), connector.y(), connector.z()), marker); + Optional marker = connectorsVisible + ? jigsawMarker(registry, connector.orientation()) + : registry.find(connector.connector().getFinalState()); + expected.put( + new LocalPosition(connector.x(), connector.y(), connector.z()), + marker.orElseThrow(() -> new IOException("Invalid rendered connector orientation '" + + connector.orientation() + "'"))); } return expected; } - private static void verifyMaterializedChunk( - World world, + private void verifyMaterializedChunk( + ToolWorld world, JigsawStudioBay workcell, JigsawStudioGenerator.RenderedBay rendered, ChunkCaptureArea area, - Map expected, + Map expected, boolean connectorsVisible ) throws IOException { JigsawStudioBounds bounds = workcell.bounds(); - BlockData air = Material.AIR.createBlockData(); for (int x = area.minimumX(); x < area.maximumX(); x++) { for (int y = 0; y < bounds.dimensions().height(); y++) { for (int z = area.minimumZ(); z < area.maximumZ(); z++) { - Block target = world.getBlockAt( + BlockPosition target = new BlockPosition( bounds.originX() + x, bounds.originY() + y, bounds.originZ() + z); - BlockData expectedData = expected.getOrDefault(new LocalPosition(x, y, z), air); - if (!target.getBlockData().equals(expectedData)) { + BlockState expectedState = expected.getOrDefault(new LocalPosition(x, y, z), JigsawStudioBlocks.AIR); + if (!sameBlock(world.block(target), expectedState)) { throw new IOException("Workcell block did not materialize at " - + target.getX() + "," + target.getY() + "," + target.getZ()); + + target.x() + "," + target.y() + "," + target.z()); } } } @@ -4989,6 +4457,18 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC verifyRenderedBayChunk(world, workcell, rendered, area.chunkX(), area.chunkZ(), connectorsVisible); } + /** + * Whether the block in the world is the one that was written: the same block with every property equal. The states + * written are the platform's own complete states, so a block the platform changed on its own does not pass. + */ + static boolean sameBlock(BlockState actual, BlockState written) { + return actual.equals(written); + } + + private static BlockRegistry registryOf(ActiveStudio studio) { + return studio.generator().getPack().resources().blocks(); + } + private boolean isCurrentVariantSwitch(MaterializationWork work) { return isCurrentRequest( work.studio(), @@ -5001,42 +4481,8 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC && materializationInProgress(work.studio()); } - private void markDirty(Block block) { - if (block != null) { - markDirty(block.getWorld(), block.getX(), block.getY(), block.getZ()); - } - } - - private void markDirty(List blocks) { - for (Block block : blocks) { - markDirty(block); - } - } - - private void markDirty(Inventory inventory) { - for (Block block : inventoryBlocks(inventory)) { - markDirty(block); - } - } - - private boolean blocksInventoryMutation(Inventory inventory, UUID actorId) { - for (Block block : inventoryBlocks(inventory)) { - StudioBlockMutationContext context = studioBlockMutationContext(block); - if (context != null && blocksStudioInventoryMutation( - true, - context.immutable(), - materializationInProgress(context.studio()), - reopenRequiredRequests.contains(context.requestId()), - context.ownerId(), - actorId)) { - return true; - } - } - return false; - } - - private boolean blocksMachineMutation(Block block) { - StudioBlockMutationContext context = studioBlockMutationContext(block); + private boolean blocksMachineMutation(ActiveStudio studio, BlockPosition at) { + StudioBlockMutationContext context = studioBlockMutationContext(studio, at); return context != null && blocksStudioInventoryMutation( true, context.immutable(), @@ -5046,25 +4492,16 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC null); } - private StudioBlockMutationContext studioBlockMutationContext(Block block) { - if (block == null) { + private StudioBlockMutationContext studioBlockMutationContext(ActiveStudio studio, BlockPosition block) { + if (studio == null || block == null) { return null; } - ActiveStudio studio = studios.get(block.getWorld().getUID()); - if (studio == null) { - return null; - } - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); boolean preview = previewRenderer.contains( - request.requestId(), block.getX(), block.getY(), block.getZ()); - JigsawStudioControlPosition control = studio.generator().getLayout().controlPosition(); - boolean controlChest = block.getType() == Material.CHEST - && block.getX() == control.worldX() - && block.getY() == control.worldY() - && block.getZ() == control.worldZ(); + request.requestId(), block.x(), block.y(), block.z()); + boolean controlChest = isControlChest(studio, block); JigsawStudioSession session = studio.generator().getSession(); - JigsawStudioBay bay = session.layout().findAt( - block.getX(), block.getY(), block.getZ()); + JigsawStudioBay bay = session.layout().findAt(block.x(), block.y(), block.z()); boolean workcell = bay != null; if (!preview && !controlChest && !workcell) { return null; @@ -5080,65 +4517,39 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC preview || controlChest || nonEditableWorkcell); } - private static List inventoryBlocks(Inventory inventory) { - if (inventory == null) { - return List.of(); - } - List blocks = new ArrayList<>(2); - InventoryHolder holder = inventory.getHolder(); - if (holder instanceof BlockInventoryHolder blockInventoryHolder) { - blocks.add(blockInventoryHolder.getBlock()); - } else if (holder instanceof DoubleChest doubleChest) { - addInventoryBlock(blocks, doubleChest.getLeftSide()); - addInventoryBlock(blocks, doubleChest.getRightSide()); - } - return blocks; - } - - private static void addInventoryBlock(List blocks, InventoryHolder holder) { - if (holder instanceof BlockInventoryHolder blockInventoryHolder - && !blocks.contains(blockInventoryHolder.getBlock())) { - blocks.add(blockInventoryHolder.getBlock()); - } - } - - private void startJigsawTileWatch(Player player, Block block) { - if (player == null || block == null || block.getType() != Material.JIGSAW) { + private void startJigsawTileWatch(ToolPlayer player, ActiveStudio studio, BlockPosition block) { + if (player == null || studio == null || block == null) { return; } - World world = block.getWorld(); - int worldX = block.getX(); - int worldY = block.getY(); - int worldZ = block.getZ(); - UUID playerId = player.getUniqueId(); - if (J.isOwnedByCurrentRegion(world, worldX >> 4, worldZ >> 4)) { - initializeJigsawTileWatch(playerId, world, worldX, worldY, worldZ); + ToolWorld world = studio.world(); + UUID playerId = player.id(); + if (JigsawStudioThreads.ownsRegion(world, block.x() >> CHUNK_SHIFT, block.z() >> CHUNK_SHIFT)) { + initializeJigsawTileWatch(playerId, studio, block.x(), block.y(), block.z()); return; } - boolean scheduled = J.runRegion( + JigsawStudioThreads.onRegion( + log, world, - worldX >> 4, - worldZ >> 4, - () -> initializeJigsawTileWatch(playerId, world, worldX, worldY, worldZ)); - if (!scheduled) { - IrisLogging.warn("Jigsaw Studio could not watch jigsaw marker NBT at %d,%d,%d in %s", - worldX, worldY, worldZ, world.getName()); - } + block.x() >> CHUNK_SHIFT, + block.z() >> CHUNK_SHIFT, + () -> initializeJigsawTileWatch(playerId, studio, block.x(), block.y(), block.z()), + () -> warn("Jigsaw Studio could not watch jigsaw marker NBT at %d,%d,%d in %s", + block.x(), block.y(), block.z(), world.name())); } private void initializeJigsawTileWatch( UUID playerId, - World world, + ActiveStudio studio, int worldX, int worldY, int worldZ ) { - ActiveStudio studio = studios.get(world.getUID()); - if (!enabled || studio == null) { + ToolWorld world = studio.world(); + if (studios.get(studio.worldId()) != studio) { return; } - Block block = world.getBlockAt(worldX, worldY, worldZ); - if (block.getType() != Material.JIGSAW) { + BlockPosition at = new BlockPosition(worldX, worldY, worldZ); + if (!JigsawStudioBlocks.isJigsaw(world.block(at))) { return; } JigsawStudioSession session = studio.generator().getSession(); @@ -5151,19 +4562,19 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } KMap snapshot; try { - snapshot = BukkitPlatform.serializeTile(block.getLocation()); + snapshot = world.blockEntity(at).flatMap(JigsawStudioTileCodec::nbt).orElse(null); } catch (Throwable exception) { - IrisLogging.reportError(exception); + reportError(exception); return; } if (snapshot == null) { - IrisLogging.warn("Jigsaw Studio could not read jigsaw marker NBT at %d,%d,%d in %s", - worldX, worldY, worldZ, world.getName()); + warn("Jigsaw Studio could not read jigsaw marker NBT at %d,%d,%d in %s", + worldX, worldY, worldZ, world.name()); return; } - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); JigsawTileWatchKey key = new JigsawTileWatchKey( - request.requestId(), world.getUID(), worldX, worldY, worldZ); + request.requestId(), studio.worldId(), worldX, worldY, worldZ); JigsawTileWatch watch = new JigsawTileWatch( key, studio, @@ -5177,16 +4588,18 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } private void scheduleJigsawTileWatch(JigsawTileWatch watch) { - boolean scheduled = J.runRegion( + scheduler.onRegionLater( watch.studio().world(), - watch.key().worldX() >> 4, - watch.key().worldZ() >> 4, + watch.key().worldX() >> CHUNK_SHIFT, + watch.key().worldZ() >> CHUNK_SHIFT, () -> runJigsawTileWatch(watch, false), - JIGSAW_TILE_WATCH_INTERVAL_TICKS); - if (!scheduled && jigsawTileWatches.get(watch.key()) == watch) { - warnJigsawTileWatchScheduleFailure(watch); - scheduleJigsawTileWatchReconciliation(watch, false); - } + JIGSAW_TILE_WATCH_INTERVAL_TICKS, + () -> { + if (jigsawTileWatches.get(watch.key()) == watch) { + warnJigsawTileWatchScheduleFailure(watch); + scheduleJigsawTileWatchReconciliation(watch, false); + } + }); } private void runJigsawTileWatch(JigsawTileWatch watch, boolean release) { @@ -5194,16 +4607,16 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return; } ActiveStudio studio = studios.get(watch.key().worldId()); - if (!enabled || studio != watch.studio() + if (studio != watch.studio() || !isCurrentRequest(studio, watch.key().requestId())) { jigsawTileWatches.remove(watch.key(), watch); return; } - Block block = studio.world().getBlockAt( + BlockPosition watched = new BlockPosition( watch.key().worldX(), watch.key().worldY(), watch.key().worldZ()); JigsawStudioBay bay = studio.generator().getSession().layout().findAt( watch.key().worldX(), watch.key().worldY(), watch.key().worldZ()); - if (block.getType() != Material.JIGSAW + if (!JigsawStudioBlocks.isJigsaw(studio.world().block(watched)) || bay == null || !bay.stableId().equals(watch.workcellId())) { jigsawTileWatches.remove(watch.key(), watch); @@ -5211,29 +4624,25 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } KMap snapshot; try { - snapshot = BukkitPlatform.serializeTile(block.getLocation()); + snapshot = studio.world().blockEntity(watched).flatMap(JigsawStudioTileCodec::nbt).orElse(null); } catch (Throwable exception) { jigsawTileWatches.remove(watch.key(), watch); - IrisLogging.reportError(exception); + reportError(exception); return; } if (snapshot == null) { jigsawTileWatches.remove(watch.key(), watch); - IrisLogging.warn("Jigsaw Studio stopped watching unreadable jigsaw marker NBT at %d,%d,%d in %s", + warn("Jigsaw Studio stopped watching unreadable jigsaw marker NBT at %d,%d,%d in %s", watch.key().worldX(), watch.key().worldY(), watch.key().worldZ(), - studio.world().getName()); + studio.world().name()); return; } JigsawTilePollDecision decision = jigsawTilePollDecision( watch.snapshot(), snapshot, release); if (decision.changed()) { - markDirty( - studio.world(), - watch.key().worldX(), - watch.key().worldY(), - watch.key().worldZ()); + markDirty(studio, watched); } if (!decision.continueWatching()) { jigsawTileWatches.remove(watch.key(), watch); @@ -5292,45 +4701,36 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } } - private void finalizeAllJigsawTileWatches() { - for (JigsawTileWatch watch : List.copyOf(jigsawTileWatches.values())) { - try { - finalizeJigsawTileWatch(watch); - } catch (Throwable exception) { - IrisLogging.reportError("Failed to finalize a Jigsaw Studio tile watch during shutdown.", exception); - } - } - } - private void finalizeJigsawTileWatch(JigsawTileWatch watch) { if (jigsawTileWatches.get(watch.key()) != watch) { return; } - World world = watch.studio().world(); - int chunkX = watch.key().worldX() >> 4; - int chunkZ = watch.key().worldZ() >> 4; - if (J.isOwnedByCurrentRegion(world, chunkX, chunkZ)) { + ToolWorld world = watch.studio().world(); + int chunkX = watch.key().worldX() >> CHUNK_SHIFT; + int chunkZ = watch.key().worldZ() >> CHUNK_SHIFT; + if (JigsawStudioThreads.ownsRegion(world, chunkX, chunkZ)) { runJigsawTileWatch(watch, true); return; } - boolean scheduled = J.runRegion( + JigsawStudioThreads.onRegion( + log, world, chunkX, chunkZ, - () -> runJigsawTileWatch(watch, true)); - if (!scheduled) { - warnJigsawTileWatchScheduleFailure(watch); - scheduleJigsawTileWatchReconciliation(watch, true); - } + () -> runJigsawTileWatch(watch, true), + () -> { + warnJigsawTileWatchScheduleFailure(watch); + scheduleJigsawTileWatchReconciliation(watch, true); + }); } private void warnJigsawTileWatchScheduleFailure(JigsawTileWatch watch) { if (watch.scheduleFailureLogged().compareAndSet(false, true)) { - IrisLogging.warn("Jigsaw Studio could not schedule jigsaw marker NBT at %d,%d,%d in %s; Iris will keep retrying", + warn("Jigsaw Studio could not schedule jigsaw marker NBT at %d,%d,%d in %s; Iris will keep retrying", watch.key().worldX(), watch.key().worldY(), watch.key().worldZ(), - watch.studio().world().getName()); + watch.studio().world().name()); } } @@ -5338,22 +4738,17 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC if (!watch.reconciliationScheduled().compareAndSet(false, true)) { return; } - try { - J.s(() -> { - watch.reconciliationScheduled().set(false); - if (jigsawTileWatches.get(watch.key()) != watch) { - return; - } - if (release) { - finalizeJigsawTileWatch(watch); - } else { - scheduleJigsawTileWatch(watch); - } - }, AUTOSAVE_RETRY_TICKS); - } catch (Throwable exception) { + scheduler.later(AUTOSAVE_RETRY_TICKS, () -> { watch.reconciliationScheduled().set(false); - IrisLogging.reportError(exception); - } + if (jigsawTileWatches.get(watch.key()) != watch) { + return; + } + if (release) { + finalizeJigsawTileWatch(watch); + } else { + scheduleJigsawTileWatch(watch); + } + }); } static boolean tileSnapshotChanged( @@ -5371,12 +4766,6 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return new JigsawTilePollDecision(tileSnapshotChanged(previous, current), !release); } - private void markAllDirty() { - for (ActiveStudio studio : studios.values()) { - markAllDirty(studio); - } - } - private int markAllDirty(ActiveStudio studio) { int changed = 0; JigsawStudioSession session = studio.generator().getSession(); @@ -5433,20 +4822,20 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return; } JigsawStudioBounds bounds = bay.bounds(); - boolean scheduled = J.runRegion( + scheduler.onRegionLater( ticket.studio().world(), - bounds.originX() >> 4, - bounds.originZ() >> 4, + bounds.originX() >> CHUNK_SHIFT, + bounds.originZ() >> CHUNK_SHIFT, () -> runAutosave(ticket), - delayTicks); - if (!scheduled) { - ticket.scheduled().set(false); - if (ticket.scheduleFailureLogged().compareAndSet(false, true)) { - IrisLogging.warn("Jigsaw Studio autosave could not schedule workcell %s for request %s; Iris will keep retrying", - ticket.key().workcellId(), ticket.key().requestId()); - } - scheduleAutosaveReconciliation(ticket); - } + delayTicks, + () -> { + ticket.scheduled().set(false); + if (ticket.scheduleFailureLogged().compareAndSet(false, true)) { + warn("Jigsaw Studio autosave could not schedule workcell %s for request %s; Iris will keep retrying", + ticket.key().workcellId(), ticket.key().requestId()); + } + scheduleAutosaveReconciliation(ticket); + }); } private JigsawStudioBay resolveAutosaveBay(AutosaveTicket ticket) { @@ -5520,12 +4909,13 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return true; } - private static AutosaveFailureDecision reportAutosaveFailure( + private AutosaveFailureDecision reportAutosaveFailure( AutosaveTicket ticket, AutosavePersistentFailure failure ) { - JigsawStudioActivation.Request request = ticket.studio().generator().getRequest(); + JigsawStudioRequest request = ticket.studio().generator().getRequest(); return recordPersistentAutosaveFailure( + log, ticket.failureState(), ticket.key().requestId(), request.structureKey(), @@ -5535,14 +4925,15 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC failure.cause()); } - private static void reportPersistentSaveFailure( + private void reportPersistentSaveFailure( ActiveStudio studio, JigsawStudioSession.SaveIdentity saveIdentity, AutosaveFailureState failureState, AutosavePersistentFailure failure ) { - JigsawStudioActivation.Request request = studio.generator().getRequest(); + JigsawStudioRequest request = studio.generator().getRequest(); recordPersistentAutosaveFailure( + log, failureState, request.requestId(), request.structureKey(), @@ -5553,6 +4944,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } static AutosaveFailureDecision recordPersistentAutosaveFailure( + ModuleLog log, AutosaveFailureState state, UUID requestId, String structureKey, @@ -5575,9 +4967,9 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC pieceKey, detail); if (cause == null) { - IrisLogging.warn("%s", context); + log.warn(context); } else { - IrisLogging.reportError(context, cause); + log.error(context, cause); } return decision; } @@ -5609,16 +5001,12 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } private void scheduleAutosaveReconciliation(AutosaveTicket ticket) { - try { - J.s(() -> { - if (autosaves.get(ticket.key()) == ticket - && !ticket.scheduled().get()) { - scheduleAutosave(ticket, AUTOSAVE_RETRY_TICKS); - } - }, AUTOSAVE_RETRY_TICKS); - } catch (Throwable exception) { - IrisLogging.reportError(exception); - } + scheduler.later(AUTOSAVE_RETRY_TICKS, () -> { + if (autosaves.get(ticket.key()) == ticket + && !ticket.scheduled().get()) { + scheduleAutosave(ticket, AUTOSAVE_RETRY_TICKS); + } + }); } private void runAutosave(AutosaveTicket ticket) { @@ -5692,23 +5080,6 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC && dirtyIdentity.mutationGeneration() == saveIdentity.mutationGeneration(); } - private void drainAutosavesBeforeDisable() { - for (ActiveStudio studio : List.copyOf(studios.values())) { - try { - drainAutosavesBeforeRemoval(studio); - } catch (Throwable exception) { - IrisLogging.reportError( - "Failed to drain Jigsaw Studio autosaves in world " - + studio.worldId() + " during shutdown.", - exception); - } - } - if (!autosaves.isEmpty()) { - IrisLogging.warn("Jigsaw Studio disabled with %d autosave operation(s) still pending after the final drain attempt", - autosaves.size()); - } - } - private void drainAutosavesBeforeRemoval(ActiveStudio studio) { if (studio == null) { return; @@ -5717,7 +5088,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC if (discardingRequest(requestId)) { return; } - if (J.isFolia() || !J.isPrimaryThread()) { + if (!ownsEveryStudioChunk(studio)) { expediteAutosaves(requestId); return; } @@ -5728,6 +5099,18 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } } + /** Whether the calling thread may read every workcell chunk, which the final synchronous autosave needs. */ + private static boolean ownsEveryStudioChunk(ActiveStudio studio) { + for (JigsawStudioBay bay : studio.generator().getLayout().bays()) { + for (ChunkCaptureArea area : chunkIntersections(bay.bounds())) { + if (!JigsawStudioThreads.ownsRegion(studio.world(), area.chunkX(), area.chunkZ())) { + return false; + } + } + } + return true; + } + private boolean drainAutosaveSynchronously(AutosaveTicket ticket) { if (autosaves.get(ticket.key()) != ticket) { return true; @@ -5788,12 +5171,13 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC List snapshots = new ArrayList<>(areas.size()); try { for (ChunkCaptureArea area : areas) { - if (!studio.world().isChunkLoaded(area.chunkX(), area.chunkZ())) { + if (!studio.isChunkLoaded(area.chunkX(), area.chunkZ())) { throw new IOException("Workcell chunk " + area.chunkX() + "," + area.chunkZ() + " is not loaded during the final autosave drain"); } snapshots.add(captureChunkIntersection( studio.world(), + studio.generator().getPack().resources().blocks(), captureTarget.bounds(), captureTarget.piece(), captureTarget.object(), @@ -5942,12 +5326,12 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return; } ActiveStudio studio = coordinator.studio(); - World world = coordinator.world(); + ToolWorld world = coordinator.world(); if (!isCurrentSave(studio, coordinator.requestId(), coordinator.saveIdentity())) { coordinator.fail("Jigsaw Studio changed before every bay chunk could be captured; save cancelled.", null); return; } - if (!world.isChunkLoaded(area.chunkX(), area.chunkZ())) { + if (!studio.isChunkLoaded(area.chunkX(), area.chunkZ())) { coordinator.fail("Bay chunk " + area.chunkX() + "," + area.chunkZ() + " is not loaded. Visit the whole bay and try again.", null); return; @@ -5955,6 +5339,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC try { ChunkSnapshot snapshot = captureChunkIntersection( world, + studio.generator().getPack().resources().blocks(), coordinator.captureTarget().bounds(), coordinator.captureTarget().piece(), coordinator.captureTarget().object(), @@ -5982,7 +5367,10 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return; } try { + ToolPack pack = studio.generator().getPack(); Capture capture = aggregateSnapshots( + pack.resources().blocks(), + pack.objects(), coordinator.captureTarget().bounds(), coordinator.areas(), snapshots, @@ -6021,60 +5409,33 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC ) { ActiveStudio studio = coordinator.studio(); JigsawStudioBay bay = coordinator.bay(); - Player player = coordinator.player(); + ToolPlayer player = coordinator.player(); try { if (!isCurrentSave(studio, coordinator.requestId(), coordinator.saveIdentity())) { message(player, "Jigsaw Studio changed before the captured bay could be written; save cancelled."); return; } - JigsawStudioActivation.Request request = studio.generator().getRequest(); - IrisData source = request.source(); - Path packRoot = source.getDataFolder().toPath(); - JigsawStudioResourceBundleAssembler.Assembly assembly = - JigsawStudioResourceBundleAssembler.assemble( - packRoot, - request.structureKey(), - coordinator.saveIdentity().variantKey(), - capture.objectContent(), - connectors, - capture.hasBlockEntities()); - StructureResourceBundleGraphCompiler.requireViable(assembly.bundle()); - if (!isCurrentSave(studio, coordinator.requestId(), coordinator.saveIdentity())) { - message(player, "Jigsaw Studio changed during validation; save cancelled before writing."); + JigsawStudioRequest request = studio.generator().getRequest(); + PersistedGraph persisted = studio.generator().getPack().edit( + packRoot -> writeCapturedGraph(coordinator, capture, connectors, packRoot)); + if (persisted == null) { return; } - JigsawStudioHistoryStore historyStore = new JigsawStudioHistoryStore( - packRoot, - request.structureKey()); - JigsawStudioHistoryStore.Snapshot previous = historyStore.snapshotCurrent( - coordinator.saveIdentity().variantKey()); - if (!previous.matches(assembly.bundle())) { - historyStore.append(previous); - } - StructureWriteResult result; - synchronized (saveLifecycleLock) { - if (!isCurrentSave(studio, coordinator.requestId(), coordinator.saveIdentity())) { - message(player, "Jigsaw Studio changed before the validated save entered the writer; save cancelled."); - return; - } - result = new StructureTransactionWriter(packRoot) - .write(assembly.bundle(), StructureWriteOptions.overwriteExpected( - assembly.expectedManifestHash())); - } + JigsawStudioResourceBundleAssembler.Assembly assembly = persisted.assembly(); + StructureWriteResult result = persisted.result(); if (!result.successful()) { String failure = writeFailure(result); coordinator.recordPersistentFailure(failure, result.failure().orElse(null)); message(player, failure); return; } - source.invalidateStructureResources(); studio.generator().invalidateRender(bay.stableId(), coordinator.saveIdentity().variantKey()); JigsawStudioSession session = studio.generator().getSession(); boolean unchanged = session.markWorkcellSaved(coordinator.saveIdentity()); try { reloadSessionLayout(studio); } catch (IOException | RuntimeException refreshFailure) { - IrisLogging.reportError(refreshFailure); + reportError(refreshFailure); message(player, "The graph saved, but Studio could not refresh its variant catalog. " + "Close and reopen this project before continuing: " + failureMessage(refreshFailure)); @@ -6089,7 +5450,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC if (unchanged) { scheduleEvaluation(studio); } - IrisLogging.debug("Jigsaw Studio saved: structure=%s piece=%s object=%s connectors=%d status=%s", + debug("Jigsaw Studio saved: structure=%s piece=%s object=%s connectors=%d status=%s", request.structureKey(), coordinator.saveIdentity().variantKey(), assembly.objectKey(), connectors.size(), result.status()); } catch (Throwable exception) { @@ -6101,6 +5462,58 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } } + /** + * Validates the captured workcell against the graph and writes it under the pack folder; null when the studio changed + * on the way and the save was dropped, in which case the player has been told. + */ + private PersistedGraph writeCapturedGraph( + CaptureCoordinator coordinator, + Capture capture, + List connectors, + Path packRoot + ) throws IOException { + ActiveStudio studio = coordinator.studio(); + ToolPlayer player = coordinator.player(); + JigsawStudioRequest request = studio.generator().getRequest(); + JigsawStudioResourceBundleAssembler.Assembly assembly = + JigsawStudioResourceBundleAssembler.assemble( + packRoot, + request.structureKey(), + coordinator.saveIdentity().variantKey(), + capture.objectContent(), + connectors, + capture.hasBlockEntities()); + StructureResourceBundleGraphCompiler.requireViable(assembly.bundle()); + if (!isCurrentSave(studio, coordinator.requestId(), coordinator.saveIdentity())) { + message(player, "Jigsaw Studio changed during validation; save cancelled before writing."); + return null; + } + JigsawStudioHistoryStore historyStore = new JigsawStudioHistoryStore( + packRoot, + request.structureKey()); + JigsawStudioHistoryStore.Snapshot previous = historyStore.snapshotCurrent( + coordinator.saveIdentity().variantKey()); + if (!previous.matches(assembly.bundle())) { + historyStore.append(previous); + } + synchronized (saveLifecycleLock) { + if (!isCurrentSave(studio, coordinator.requestId(), coordinator.saveIdentity())) { + message(player, "Jigsaw Studio changed before the validated save entered the writer; save cancelled."); + return null; + } + StructureWriteResult result = new StructureTransactionWriter(packRoot) + .write(assembly.bundle(), StructureWriteOptions.overwriteExpected( + assembly.expectedManifestHash())); + return new PersistedGraph(assembly, result); + } + } + + private record PersistedGraph( + JigsawStudioResourceBundleAssembler.Assembly assembly, + StructureWriteResult result + ) { + } + static List chunkIntersections(JigsawStudioBounds bounds) { JigsawStudioBounds captureBounds = Objects.requireNonNull(bounds, "Jigsaw Studio capture bounds"); List areas = new ArrayList<>(); @@ -6133,25 +5546,28 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } static ChunkSnapshot captureChunkIntersection( - World world, + ToolWorld world, + BlockRegistry registry, JigsawStudioBounds bounds, IrisJigsawPiece sourcePiece, - IrisObject sourceObject, + SourceObject sourceObject, ChunkCaptureArea area ) throws IOException { - return captureChunkIntersection(world, bounds, sourcePiece, sourceObject, area, 0); + return captureChunkIntersection(world, registry, bounds, sourcePiece, sourceObject, area, 0); } static ChunkSnapshot captureChunkIntersection( - World world, + ToolWorld world, + BlockRegistry registry, JigsawStudioBounds bounds, IrisJigsawPiece sourcePiece, - IrisObject sourceObject, + SourceObject sourceObject, ChunkCaptureArea area, int displayRotationQuarterTurns ) throws IOException { return captureChunkIntersection( world, + registry, bounds, sourcePiece, sourceObject, @@ -6161,17 +5577,18 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } static ChunkSnapshot captureChunkIntersection( - World world, + ToolWorld world, + BlockRegistry registry, JigsawStudioBounds bounds, IrisJigsawPiece sourcePiece, - IrisObject sourceObject, + SourceObject sourceObject, ChunkCaptureArea area, int displayRotationQuarterTurns, boolean connectorsVisible ) throws IOException { - World captureWorld = Objects.requireNonNull(world, "Jigsaw Studio capture world"); + ToolWorld captureWorld = Objects.requireNonNull(world, "Jigsaw Studio capture world"); JigsawStudioBounds captureBounds = Objects.requireNonNull(bounds, "Jigsaw Studio capture bounds"); - IrisObject captureSource = Objects.requireNonNull(sourceObject, "Jigsaw Studio source object"); + SourceObject captureSource = Objects.requireNonNull(sourceObject, "Jigsaw Studio source object"); ChunkCaptureArea captureArea = Objects.requireNonNull(area, "Jigsaw Studio chunk capture area"); int quarterTurns = Math.floorMod(displayRotationQuarterTurns, 4); int sourceWidth = (quarterTurns & 1) == 0 @@ -6188,29 +5605,31 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC for (int x = captureArea.minimumX(); x < captureArea.maximumX(); x++) { for (int y = 0; y < bounds.dimensions().height(); y++) { for (int z = captureArea.minimumZ(); z < captureArea.maximumZ(); z++) { - Block block = captureWorld.getBlockAt( + BlockPosition at = new BlockPosition( captureBounds.originX() + x, captureBounds.originY() + y, captureBounds.originZ() + z); - BlockData blockData = block.getBlockData(); + BlockState state = captureWorld.block(at); IrisJigsawConnector hiddenConnector = hiddenConnectors.get(new LocalPosition(x, y, z)); if (hiddenConnector != null) { - hiddenConnector.setFinalState(blockData.getAsString()); + hiddenConnector.setFinalState(state.key()); connectors.add(CapturedConnector.from(hiddenConnector)); } - if (hiddenConnector == null && blockData instanceof Jigsaw jigsaw) { - KMap nbt = BukkitPlatform.serializeTile(block.getLocation()); + if (hiddenConnector == null && JigsawStudioBlocks.isJigsaw(state)) { + KMap nbt = captureWorld.blockEntity(at) + .flatMap(JigsawStudioTileCodec::nbt) + .orElse(null); if (nbt == null) { throw new IOException("Cannot read jigsaw marker NBT at " - + block.getX() + "," + block.getY() + "," + block.getZ() + + at.x() + "," + at.y() + "," + at.z() + ". The active NMS binding must support tile serialization."); } IrisJigsawConnector connector; try { - connector = JigsawStudioMarkerParser.parse(nbt, jigsaw.getOrientation(), x, y, z); + connector = JigsawStudioMarkerParser.parse(nbt, orientationOf(state), x, y, z); } catch (IllegalArgumentException exception) { throw new IOException("Invalid jigsaw marker at " - + block.getX() + "," + block.getY() + "," + block.getZ() + + at.x() + "," + at.y() + "," + at.z() + ": " + failureMessage(exception), exception); } restoreCapturedMetadataForDisplay( @@ -6218,26 +5637,17 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC sourcePiece, captureBounds.dimensions(), quarterTurns); - BlockData finalData; - try { - finalData = Bukkit.createBlockData(connector.getFinalState()); - } catch (IllegalArgumentException exception) { - throw new IOException("Invalid final_state '" + connector.getFinalState() - + "' at " + block.getX() + "," + block.getY() + "," + block.getZ(), exception); - } - connector.setFinalState(finalData.getAsString()); + BlockState finalState = registry.find(connector.getFinalState()) + .orElseThrow(() -> new IOException("Invalid final_state '" + connector.getFinalState() + + "' at " + at.x() + "," + at.y() + "," + at.z())); + connector.setFinalState(finalState.key()); connectors.add(CapturedConnector.from(connector)); - if (finalData.getMaterial() != Material.STRUCTURE_VOID) { - blocks.add(new CapturedBlock( - x, - y, - z, - BukkitBlockState.of(finalData), - null)); + if (!JigsawStudioBlocks.isStructureVoid(finalState)) { + blocks.add(new CapturedBlock(x, y, z, finalState, null)); } continue; } - if (isAir(blockData.getMaterial())) { + if (JigsawStudioBlocks.isAir(state)) { LocalPosition sourcePosition = inversePosition( x, y, @@ -6245,26 +5655,21 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC sourceWidth, sourceDepth, quarterTurns); - PlatformBlockState retainedAir = retainedSourceAir( + BlockState retainedAir = retainedSourceAir( captureSource, sourcePosition.x(), sourcePosition.y(), sourcePosition.z(), - blockData); + state); if (retainedAir != null) { blocks.add(new CapturedBlock(x, y, z, retainedAir, null)); } continue; } - if (blockData.getMaterial() == Material.STRUCTURE_VOID) { + if (JigsawStudioBlocks.isStructureVoid(state)) { continue; } - blocks.add(new CapturedBlock( - x, - y, - z, - BukkitBlockState.of(blockData), - TileData.getTileState(block, false))); + blocks.add(new CapturedBlock(x, y, z, state, captureWorld.blockEntity(at).orElse(null))); } } } @@ -6287,7 +5692,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC int sourceDepth = (quarterTurns & 1) == 0 ? displayDimensions.depth() : displayDimensions.width(); - ObjectTurn rotation = ObjectTurn.of(0, -90.0D * quarterTurns, 0); + PieceTurn rotation = PieceTurn.aroundY(-90 * quarterTurns); Map displayed = new HashMap<>(source.getConnectors().size()); for (IrisJigsawConnector sourceConnector : source.getConnectors()) { LocalPosition sourcePosition = connectorPosition(sourceConnector, "source piece"); @@ -6299,9 +5704,9 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC sourceDepth, quarterTurns); IrisJigsawConnector connector = CapturedConnector.from(sourceConnector).toConnector() - .setPosition(new IrisPosition(position.x(), position.y(), position.z())) - .setDirection(rotation.rotate(sourceConnector.getDirection())) - .setTop(rotation.rotate(sourceConnector.getTop())); + .setPosition(new BlockPosition(position.x(), position.y(), position.z())) + .setDirection(sourceConnector.getDirection().turnedBy(rotation.quarterTurns())) + .setTop(sourceConnector.getTop().turnedBy(rotation.quarterTurns())); if (displayed.put(position, connector) != null) { throw new IOException("Jigsaw Studio source piece has duplicate displayed connector position " + connectorLocation(position)); @@ -6310,41 +5715,64 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return Map.copyOf(displayed); } - static PlatformBlockState retainedSourceAir( - IrisObject sourceObject, + static BlockState retainedSourceAir( + SourceObject sourceObject, int x, int y, int z, - BlockData current + BlockState current ) { - IrisObject source = Objects.requireNonNull(sourceObject, "Jigsaw Studio source object"); - BlockData currentState = Objects.requireNonNull(current, "Jigsaw Studio current block state"); - if (!isAir(currentState.getMaterial()) + SourceObject source = Objects.requireNonNull(sourceObject, "Jigsaw Studio source object"); + BlockState currentState = Objects.requireNonNull(current, "Jigsaw Studio current block state"); + if (!JigsawStudioBlocks.isAir(currentState) || x < 0 || y < 0 || z < 0 - || x >= source.getW() - || y >= source.getH() - || z >= source.getD()) { + || x >= source.width() + || y >= source.height() + || z >= source.depth()) { return null; } - PlatformBlockState original = source.getBlocks().get(source.getSigned(x, y, z)); - return original != null && original.isAir() ? original : null; + return source.airBlocks().get(new LocalPosition(x, y, z)); } - private static boolean isAir(Material material) { - return material == Material.AIR || material == Material.CAVE_AIR || material == Material.VOID_AIR; + /** + * The object a piece was saved as: its declared size, and the air it keeps deliberately. A workcell block that is air + * now keeps the air it had in the object, so the saved object still clears the same blocks when it is placed. + */ + record SourceObject(int width, int height, int depth, Map airBlocks) { + SourceObject { + airBlocks = Map.copyOf(airBlocks); + } + + static SourceObject of(PlaceableObject object) { + BlockPosition center = object.center(); + Map air = new HashMap<>(); + for (ObjectBlock block : object.geometry().blocks()) { + if (JigsawStudioBlocks.isAir(block.state())) { + air.put(new LocalPosition( + block.position().x() + center.x(), + block.position().y() + center.y(), + block.position().z() + center.z()), block.state()); + } + } + return new SourceObject(object.width(), object.height(), object.depth(), air); + } } static Capture aggregateSnapshots( + BlockRegistry registry, + ObjectCodec codec, JigsawStudioBounds bounds, List expectedAreas, List snapshots ) throws IOException { - return aggregateSnapshots(bounds, expectedAreas, snapshots, 0); + return aggregateSnapshots(registry, codec, bounds, expectedAreas, snapshots, 0); } static Capture aggregateSnapshots( + BlockRegistry registry, + ObjectCodec codec, JigsawStudioBounds bounds, List expectedAreas, List snapshots, @@ -6391,11 +5819,9 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC int sourceDepth = (quarterTurns & 1) == 0 ? captureBounds.dimensions().depth() : captureBounds.dimensions().width(); - IrisObject object = new IrisObject( - sourceWidth, - captureBounds.dimensions().height(), - sourceDepth); - ObjectTurn inverseRotation = ObjectTurn.of(0, 90.0D * quarterTurns, 0); + int sourceHeight = captureBounds.dimensions().height(); + List objectBlocks = new ArrayList<>(); + PieceTurn inverseRotation = PieceTurn.aroundY(90 * quarterTurns); List connectors = new ArrayList<>(); Set capturedBlocks = new HashSet<>(); Set capturedConnectors = new HashSet<>(); @@ -6415,17 +5841,18 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC throw new IOException("Duplicate captured block at " + block.x() + "," + block.y() + "," + block.z()); } - PlatformBlockState sourceState = quarterTurns == 0 + BlockState sourceState = quarterTurns == 0 ? block.state() - : BlockStateRotation.rotate(inverseRotation, block.state()); + : JigsawStudioBlocks.rotated(registry, block.state(), inverseRotation); if (sourceState == null) { throw new IOException("Captured block state cannot be inverse-rotated at " + block.x() + "," + block.y() + "," + block.z()); } - object.setUnsigned(position.x(), position.y(), position.z(), sourceState); - TileData tileData = block.tileData(); - if (tileData != null) { - object.setUnsignedTile(position.x(), position.y(), position.z(), tileData.clone()); + objectBlocks.add(new ObjectBlock( + fromCorner(position, sourceWidth, sourceHeight, sourceDepth), + sourceState, + Optional.ofNullable(block.blockEntity()))); + if (block.blockEntity() != null) { hasBlockEntities = true; } } @@ -6450,16 +5877,16 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } IrisJigsawConnector connector = capturedConnector.toConnector(); if (quarterTurns != 0) { - connector.setPosition(new IrisPosition(position.x(), position.y(), position.z())); - connector.setDirection(inverseRotation.rotate(connector.getDirection())); - connector.setTop(inverseRotation.rotate(connector.getTop())); - PlatformBlockState finalState = B.getStateOrNull(connector.getFinalState(), false); + connector.setPosition(new BlockPosition(position.x(), position.y(), position.z())); + connector.setDirection(connector.getDirection().turnedBy(inverseRotation.quarterTurns())); + connector.setTop(connector.getTop().turnedBy(inverseRotation.quarterTurns())); + BlockState finalState = registry.find(connector.getFinalState()).orElse(null); if (finalState == null) { throw new IOException("Captured connector final state cannot be parsed at " + capturedConnector.x() + "," + capturedConnector.y() + "," + capturedConnector.z()); } - PlatformBlockState sourceFinalState = BlockStateRotation.rotate(inverseRotation, finalState); + BlockState sourceFinalState = JigsawStudioBlocks.rotated(registry, finalState, inverseRotation); if (sourceFinalState == null) { throw new IOException("Captured connector final state cannot be inverse-rotated at " + capturedConnector.x() + "," + capturedConnector.y() + "," @@ -6470,10 +5897,31 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC connectors.add(connector); } } - try (ByteArrayOutputStream output = new ByteArrayOutputStream()) { - object.write(output); - return new Capture(output.toByteArray(), connectors, hasBlockEntities); - } + GeneratedObject object = new GeneratedObject( + objectBounds(sourceWidth, sourceHeight, sourceDepth), + new BlockPosition(0, 0, 0), + objectBlocks, + List.of()); + return new Capture(codec.encode(object), connectors, hasBlockEntities); + } + + /** A position counted from the object's corner, as the offset from its center the object format keeps. */ + private static BlockPosition fromCorner(LocalPosition corner, int width, int height, int depth) { + return new BlockPosition( + corner.x() - width / 2, + corner.y() - height / 2, + corner.z() - depth / 2); + } + + /** The box of an object of the given size, in the offsets from its center that its blocks are kept in. */ + private static BlockBox objectBounds(int width, int height, int depth) { + return new BlockBox( + -(width / 2), + -(height / 2), + -(depth / 2), + width - width / 2, + height - height / 2, + depth - depth / 2); } static List preserveCapturedConnectorOrder( @@ -6521,8 +5969,8 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC if (connector == null || connector.getPosition() == null) { throw new IOException("Jigsaw Studio " + owner + " contains a connector without a position"); } - IrisPosition position = connector.getPosition(); - return new LocalPosition(position.getX(), position.getY(), position.getZ()); + BlockPosition position = connector.getPosition(); + return new LocalPosition(position.x(), position.y(), position.z()); } private static String connectorLocation(LocalPosition position) { @@ -6602,58 +6050,43 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC + (connectorCount == 1 ? "" : "s") + ")"; } - static void storeConnectorFinalState( - IrisObject object, - int x, - int y, - int z, - BlockData finalData - ) { - Objects.requireNonNull(object, "Jigsaw Studio captured object"); - BlockData activeFinalData = Objects.requireNonNull(finalData, "Jigsaw connector final state"); - if (activeFinalData.getMaterial() != Material.STRUCTURE_VOID) { - object.setUnsigned(x, y, z, BukkitBlockState.of(activeFinalData)); - } - } private void scheduleHydration( ActiveStudio studio, - World world, + ToolWorld world, int chunkX, int chunkZ, int attempt ) { - if (!enabled || studios.get(world.getUID()) != studio) { + if (studios.get(studio.worldId()) != studio) { return; } long key = chunkKey(chunkX, chunkZ); if (!studio.hydrationsInProgress().add(key)) { return; } - boolean scheduled = J.runRegion( + scheduler.onRegionLater( world, chunkX, chunkZ, () -> runHydrationAttempt(studio, world, chunkX, chunkZ, attempt, key), - HYDRATION_RETRY_TICKS); - if (!scheduled) { - studio.hydrationsInProgress().remove(key); - } + HYDRATION_RETRY_TICKS, + () -> studio.hydrationsInProgress().remove(key)); } private void runHydrationAttempt( ActiveStudio studio, - World world, + ToolWorld world, int chunkX, int chunkZ, int attempt, long key ) { studio.hydrationsInProgress().remove(key); - if (!enabled || studios.get(world.getUID()) != studio) { + if (studios.get(studio.worldId()) != studio) { return; } - if (!world.isChunkLoaded(chunkX, chunkZ)) { + if (!studio.isChunkLoaded(chunkX, chunkZ)) { if (attempt < MAX_HYDRATION_ATTEMPTS) { scheduleHydration(studio, world, chunkX, chunkZ, attempt + 1); } @@ -6664,9 +6097,9 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } } - private static boolean hydrateChunk( + private boolean hydrateChunk( ActiveStudio studio, - World world, + ToolWorld world, int chunkX, int chunkZ ) { @@ -6706,15 +6139,15 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } catch (Throwable exception) { if (population.fail("chunk " + chunkX + "," + chunkZ + " could not hydrate: " + failureMessage(exception))) { - IrisLogging.reportError(exception); + reportError(exception); } } } return verificationRequired; } - private static void applyRenderedBayChunk( - World world, + private void applyRenderedBayChunk( + ToolWorld world, JigsawStudioBay bay, JigsawStudioGenerator.RenderedBay rendered, int chunkX, @@ -6722,31 +6155,28 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC boolean connectorsVisible ) throws IOException { JigsawStudioBounds bounds = bay.bounds(); - Set connectorPositions = new HashSet<>(rendered.connectors().size()); - if (connectorsVisible) { - for (JigsawStudioGenerator.RenderedConnector connector : rendered.connectors()) { - connectorPositions.add(new LocalPosition(connector.x(), connector.y(), connector.z())); - } - } + Set connectorPositions = connectorPositions(rendered, connectorsVisible); for (JigsawStudioGenerator.RenderedBlock block : rendered.blocks()) { - TileData tileData = block.tileData(); - if (tileData == null + BlockEntityData blockEntity = block.blockEntity(); + if (blockEntity == null || connectorPositions.contains(new LocalPosition(block.x(), block.y(), block.z()))) { continue; } int worldX = bounds.originX() + block.x(); int worldZ = bounds.originZ() + block.z(); - if ((worldX >> 4) != chunkX || (worldZ >> 4) != chunkZ) { + if ((worldX >> CHUNK_SHIFT) != chunkX || (worldZ >> CHUNK_SHIFT) != chunkZ) { continue; } - Block target = world.getBlockAt(worldX, bounds.originY() + block.y(), worldZ); - if (!tileData.isApplicable(target.getBlockData())) { + BlockPosition target = new BlockPosition(worldX, bounds.originY() + block.y(), worldZ); + if (!sameMaterial(world.block(target), block.state())) { throw new IOException("source tile state does not match rendered block at " - + target.getX() + "," + target.getY() + "," + target.getZ()); + + target.x() + "," + target.y() + "," + target.z()); } - if (!tileData.toBukkitTry(target)) { + try { + world.setBlock(target, world.block(target), Optional.of(blockEntity)); + } catch (IllegalArgumentException exception) { throw new IOException("source tile state could not hydrate at " - + target.getX() + "," + target.getY() + "," + target.getZ()); + + target.x() + "," + target.y() + "," + target.z(), exception); } } if (!connectorsVisible) { @@ -6755,31 +6185,27 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC for (JigsawStudioGenerator.RenderedConnector renderedConnector : rendered.connectors()) { int worldX = bounds.originX() + renderedConnector.x(); int worldZ = bounds.originZ() + renderedConnector.z(); - if ((worldX >> 4) != chunkX || (worldZ >> 4) != chunkZ) { + if ((worldX >> CHUNK_SHIFT) != chunkX || (worldZ >> CHUNK_SHIFT) != chunkZ) { continue; } - Block target = world.getBlockAt( - worldX, - bounds.originY() + renderedConnector.y(), - worldZ); - BlockData blockData = target.getBlockData(); - if (!(blockData instanceof Jigsaw jigsaw)) { + BlockPosition target = new BlockPosition(worldX, bounds.originY() + renderedConnector.y(), worldZ); + BlockState actual = world.block(target); + if (!JigsawStudioBlocks.isJigsaw(actual)) { throw new IOException("expected a jigsaw marker at " - + target.getX() + "," + target.getY() + "," + target.getZ()); + + target.x() + "," + target.y() + "," + target.z()); } - String actualOrientation = jigsaw.getOrientation().name().toLowerCase(Locale.ROOT); + String actualOrientation = orientationOf(actual); if (!actualOrientation.equals(renderedConnector.orientation())) { throw new IOException("jigsaw marker orientation at " - + target.getX() + "," + target.getY() + "," + target.getZ() + + target.x() + "," + target.y() + "," + target.z() + " is " + actualOrientation + " instead of " + renderedConnector.orientation()); } - KMap expected = markerNbt(renderedConnector.connector()); - BukkitPlatform.deserializeTile(expected, target.getLocation()); + world.setBlock(target, actual, Optional.of(markerBlockEntity(renderedConnector.connector()))); } } - private static void verifyRenderedBayChunk( - World world, + private void verifyRenderedBayChunk( + ToolWorld world, JigsawStudioBay bay, JigsawStudioGenerator.RenderedBay rendered, int chunkX, @@ -6787,34 +6213,29 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC boolean connectorsVisible ) throws IOException { JigsawStudioBounds bounds = bay.bounds(); - Set connectorPositions = new HashSet<>(rendered.connectors().size()); - if (connectorsVisible) { - for (JigsawStudioGenerator.RenderedConnector connector : rendered.connectors()) { - connectorPositions.add(new LocalPosition(connector.x(), connector.y(), connector.z())); - } - } + Set connectorPositions = connectorPositions(rendered, connectorsVisible); for (JigsawStudioGenerator.RenderedBlock block : rendered.blocks()) { - TileData tileData = block.tileData(); - if (tileData == null + BlockEntityData expectedEntity = block.blockEntity(); + if (expectedEntity == null || connectorPositions.contains(new LocalPosition(block.x(), block.y(), block.z()))) { continue; } int worldX = bounds.originX() + block.x(); int worldZ = bounds.originZ() + block.z(); - if ((worldX >> 4) != chunkX || (worldZ >> 4) != chunkZ) { + if ((worldX >> CHUNK_SHIFT) != chunkX || (worldZ >> CHUNK_SHIFT) != chunkZ) { continue; } - Block target = world.getBlockAt(worldX, bounds.originY() + block.y(), worldZ); - if (!tileData.isApplicable(target.getBlockData())) { + BlockPosition target = new BlockPosition(worldX, bounds.originY() + block.y(), worldZ); + if (!sameMaterial(world.block(target), block.state())) { throw new IOException("hydrated tile state no longer matches its block at " - + target.getX() + "," + target.getY() + "," + target.getZ()); + + target.x() + "," + target.y() + "," + target.z()); } - KMap hydrated = BukkitPlatform.serializeTile(target.getLocation()); - if (hydrated == null - || tileData.getProperties() != null - && !nbtContains(tileData.getProperties(), hydrated)) { + Optional> hydrated = world.blockEntity(target) + .flatMap(JigsawStudioTileCodec::nbt); + Optional> expected = JigsawStudioTileCodec.nbt(expectedEntity); + if (hydrated.isEmpty() || expected.isPresent() && !nbtContains(expected.get(), hydrated.get())) { throw new IOException("the active NMS binding did not preserve source tile NBT at " - + target.getX() + "," + target.getY() + "," + target.getZ()); + + target.x() + "," + target.y() + "," + target.z()); } } if (!connectorsVisible) { @@ -6823,29 +6244,47 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC for (JigsawStudioGenerator.RenderedConnector renderedConnector : rendered.connectors()) { int worldX = bounds.originX() + renderedConnector.x(); int worldZ = bounds.originZ() + renderedConnector.z(); - if ((worldX >> 4) != chunkX || (worldZ >> 4) != chunkZ) { + if ((worldX >> CHUNK_SHIFT) != chunkX || (worldZ >> CHUNK_SHIFT) != chunkZ) { continue; } - Block target = world.getBlockAt( - worldX, - bounds.originY() + renderedConnector.y(), - worldZ); - BlockData blockData = target.getBlockData(); - if (!(blockData instanceof Jigsaw jigsaw) - || !jigsaw.getOrientation().name().toLowerCase(Locale.ROOT) - .equals(renderedConnector.orientation())) { + BlockPosition target = new BlockPosition(worldX, bounds.originY() + renderedConnector.y(), worldZ); + BlockState actual = world.block(target); + if (!JigsawStudioBlocks.isJigsaw(actual) + || !orientationOf(actual).equals(renderedConnector.orientation())) { throw new IOException("jigsaw marker changed before hydration completed at " - + target.getX() + "," + target.getY() + "," + target.getZ()); + + target.x() + "," + target.y() + "," + target.z()); } KMap expected = markerNbt(renderedConnector.connector()); - KMap hydrated = BukkitPlatform.serializeTile(target.getLocation()); - if (!markerNbtMatches(expected, hydrated)) { + Optional> hydrated = world.blockEntity(target).flatMap(JigsawStudioTileCodec::nbt); + if (hydrated.isEmpty() || !markerNbtMatches(expected, hydrated.get())) { throw new IOException("the active NMS binding did not preserve jigsaw marker NBT at " - + target.getX() + "," + target.getY() + "," + target.getZ()); + + target.x() + "," + target.y() + "," + target.z()); } } } + private static Set connectorPositions( + JigsawStudioGenerator.RenderedBay rendered, + boolean connectorsVisible + ) { + Set positions = new HashSet<>(rendered.connectors().size()); + if (connectorsVisible) { + for (JigsawStudioGenerator.RenderedConnector connector : rendered.connectors()) { + positions.add(new LocalPosition(connector.x(), connector.y(), connector.z())); + } + } + return positions; + } + + private static boolean sameMaterial(BlockState actual, BlockState expected) { + return actual.material().equals(expected.material()); + } + + private static String orientationOf(BlockState jigsaw) { + String orientation = jigsaw.properties().get(JigsawStudioBlocks.ORIENTATION_PROPERTY); + return orientation == null ? "" : orientation; + } + static KMap markerNbt(IrisJigsawConnector connector) { IrisJigsawConnector activeConnector = Objects.requireNonNull(connector, "Jigsaw Studio connector"); KMap nbt = new KMap<>(); @@ -6957,24 +6396,24 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC ? displayDimensions.depth() : displayDimensions.width(); LocalPosition position = inversePosition( - captured.getPosition().getX(), - captured.getPosition().getY(), - captured.getPosition().getZ(), + captured.getPosition().x(), + captured.getPosition().y(), + captured.getPosition().z(), sourceWidth, sourceDepth, quarterTurns); - ObjectTurn inverseRotation = ObjectTurn.of(0, 90.0D * quarterTurns, 0); + PieceTurn inverseRotation = PieceTurn.aroundY(90 * quarterTurns); IrisJigsawConnector sourceOriented = CapturedConnector.from(captured).toConnector() - .setPosition(new IrisPosition(position.x(), position.y(), position.z())) - .setDirection(inverseRotation.rotate(captured.getDirection())) - .setTop(inverseRotation.rotate(captured.getTop())); + .setPosition(new BlockPosition(position.x(), position.y(), position.z())) + .setDirection(captured.getDirection().turnedBy(inverseRotation.quarterTurns())) + .setTop(captured.getTop().turnedBy(inverseRotation.quarterTurns())); restoreCapturedMetadata(sourceOriented, sourcePiece); captured.setName(sourceOriented.getName()); captured.setTargetName(sourceOriented.getTargetName()); captured.setChannel(sourceOriented.getChannel()); } - private static IrisJigsawConnector connectorAt(IrisJigsawPiece piece, IrisPosition position) { + private static IrisJigsawConnector connectorAt(IrisJigsawPiece piece, BlockPosition position) { if (piece == null || piece.getConnectors() == null || position == null) { return null; } @@ -7005,7 +6444,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC || !studio.generator().getRequest().requestId().equals(requestId)) { return false; } - JigsawStudioActivation.Request active = JigsawStudioActivation.getRequest( + JigsawStudioRequest active = registry.getRequest( studio.generator().getRequest().packKey()); return active != null && active.requestId().equals(requestId); } @@ -7060,7 +6499,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC JigsawStudioVariant variant ) throws IOException { - IrisData source = studio.generator().getRequest().source(); + PackResources resources = studio.generator().getPack().resources(); JigsawStudioLayout currentLayout = studio.generator().getSession().layout(); JigsawStudioBay currentBay = currentLayout.get(bay.stableId()); if (currentBay == null) { @@ -7071,17 +6510,17 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC throw new IOException("variant '" + activeVariant.pieceKey() + "' does not belong to workcell '" + currentBay.stableId() + "'"); } - IrisJigsawPiece piece = StructureResources.piece(source.getPackResources(), activeVariant.pieceKey()); + IrisJigsawPiece piece = StructureResources.piece(resources, activeVariant.pieceKey()); if (piece == null || piece.getObject() == null || piece.getObject().isBlank()) { throw new IOException("piece '" + activeVariant.pieceKey() + "' is missing or has no object"); } - IrisObject object = source.getObjectLoader().load(piece.getObject(), false); - if (object == null || object.getW() < 1 || object.getH() < 1 || object.getD() < 1) { + PlaceableObject object = resources.objects().object(resources.idOf(piece.getObject())).orElse(null); + if (object == null || object.width() < 1 || object.height() < 1 || object.depth() < 1) { throw new IOException("object '" + piece.getObject() + "' is missing or has invalid dimensions"); } JigsawStudioBounds bayBounds = currentBay.bounds(); JigsawStudioCellDimensions sourceDimensions = new JigsawStudioCellDimensions( - object.getW(), object.getH(), object.getD()); + object.width(), object.height(), object.depth()); JigsawStudioCellDimensions canonicalDimensions = activeVariant.canonicalDimensions(sourceDimensions); if (canonicalDimensions.width() > bayBounds.dimensions().width() || canonicalDimensions.height() > bayBounds.dimensions().height() @@ -7100,7 +6539,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC bayBounds.originZ(), canonicalDimensions), piece, - object, + SourceObject.of(object), activeVariant.sourceToCanonicalQuarterTurns(), studio.generator().getSession().workcellSnapshot(currentBay.stableId()).connectorsVisible()); } @@ -7114,41 +6553,44 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } private void scheduleOnlinePlayers(UUID worldId) { - J.runGlobal(() -> { - for (Player player : Bukkit.getOnlinePlayers()) { - J.runEntity(player, () -> { - if (player.getWorld().getUID().equals(worldId)) { - ensureVisualizationLoop(player); - reconcilePlayerContext(player, player.getLocation()); - } - }); - } - }); + ActiveStudio studio = studios.get(worldId); + if (studio == null) { + return; + } + for (ToolPlayer player : studio.world().players()) { + JigsawStudioThreads.run(player, () -> { + if (studioOf(player) == studio) { + ensureVisualizationLoop(player); + reconcilePlayerContext(player, player.position()); + } + }); + } } - public void reconcilePlayerContext(Player player, Location location) { + public void reconcilePlayerContext(ToolPlayer player, BlockPosition target) { if (player == null) { return; } - Location target = location == null ? player.getLocation() : location; - if (!J.isOwnedByCurrentRegion(player) - || target.getWorld() == null - || !target.getWorld().getUID().equals(player.getWorld().getUID())) { - J.runEntity(player, () -> reconcilePlayerContext(player, player.getLocation()), 1); + if (!JigsawStudioThreads.owns(player)) { + scheduler.onPlayerLater( + player, + () -> reconcilePlayerContext(player, player.position()), + RECONCILE_RETRY_TICKS, + () -> { }); return; } - ActiveStudio studio = studios.get(target.getWorld().getUID()); + BlockPosition at = target == null ? player.position() : target; + ActiveStudio studio = studioOf(player); if (studio == null) { clearPlayerContext(player); return; } JigsawStudioSession session = studio.generator().getSession(); - JigsawStudioBay workcell = session.layout().findAt( - target.getBlockX(), target.getBlockY(), target.getBlockZ()); + JigsawStudioBay workcell = session.layout().findAt(at.x(), at.y(), at.z()); boolean owner = ownerMatches(player, studio); selectEnteredWorkcell(session, workcell, owner); String workcellId = workcell == null ? "" : workcell.stableId(); - playerWorkcells.put(player.getUniqueId(), new PlayerWorkcellContext( + playerWorkcells.put(player.id(), new PlayerWorkcellContext( studio.worldId(), studio.generator().getRequest().requestId(), workcellId)); @@ -7161,7 +6603,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC String workcellName = workcell == null ? "" : workcell.displayName(); String variantName = variant == null ? "" : variant.resolvedDisplayName(); String hint = "Triple-sneak for controls"; - boardService().applyJigsawContext(player, new JigsawStudioBoardContext( + JigsawStudioBoardContext context = new JigsawStudioBoardContext( studio.worldId(), studio.generator().getRequest().requestId(), studio.generator().getRequest().structureKey(), @@ -7170,7 +6612,8 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC workcellName, variantName, state, - hint)); + hint); + player.sidebar(context.sidebarTitle(), context.sidebarLines()); } static boolean selectEnteredWorkcell( @@ -7181,65 +6624,50 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return owner && workcell != null && session.selectBay(workcell.stableId()); } - static boolean isNaturalStudioSpawn(CreatureSpawnEvent.SpawnReason reason) { - return reason == CreatureSpawnEvent.SpawnReason.NATURAL; - } - - static void disableNaturalStudioSpawning(World world) { - Objects.requireNonNull(world, "world").setGameRule(GameRules.SPAWN_MOBS, false); - } - public void refreshWorkcellContext(UUID worldId, String workcellId) { if (worldId == null || workcellId == null) { return; } - J.runGlobal(() -> { - for (Player player : Bukkit.getOnlinePlayers()) { - J.runEntity(player, () -> { - if (!player.getWorld().getUID().equals(worldId)) { - return; - } - PlayerWorkcellContext context = playerWorkcells.get(player.getUniqueId()); - if (context != null && workcellId.equals(context.workcellId())) { - reconcilePlayerContext(player, player.getLocation()); - } - }); - } - }); + ActiveStudio studio = studios.get(worldId); + if (studio == null) { + return; + } + for (ToolPlayer player : studio.world().players()) { + JigsawStudioThreads.run(player, () -> { + PlayerWorkcellContext context = playerWorkcells.get(player.id()); + if (context != null && workcellId.equals(context.workcellId())) { + reconcilePlayerContext(player, player.position()); + } + }); + } } - private void clearWorldPlayerContexts(UUID worldId) { - J.runGlobal(() -> { - for (Player player : Bukkit.getOnlinePlayers()) { - J.runEntity(player, () -> { - PlayerWorkcellContext context = playerWorkcells.get(player.getUniqueId()); - if (context != null && context.worldId().equals(worldId)) { - closeMenu(player); - clearPlayerContext(player); - } - }); - } - }); + private void clearWorldPlayerContexts(ToolWorld world, UUID worldId) { + for (ToolPlayer player : world.players()) { + JigsawStudioThreads.run(player, () -> { + PlayerWorkcellContext context = playerWorkcells.get(player.id()); + if (context != null && context.worldId().equals(worldId)) { + closeMenu(player); + clearPlayerContext(player); + } + }); + } } - private void clearPlayerContext(Player player) { + private void clearPlayerContext(ToolPlayer player) { if (player == null) { return; } - playerWorkcells.remove(player.getUniqueId()); - boardService().clearJigsawContext(player); + playerWorkcells.remove(player.id()); + player.hideSidebar(); } - private static BoardSVC boardService() { - return IrisServices.get(BoardSVC.class); - } - - private static boolean ownerMatches(Player player, ActiveStudio studio) { + private static boolean ownerMatches(ToolPlayer player, ActiveStudio studio) { if (player == null || studio == null) { return false; } UUID ownerId = studio.generator().getRequest().ownerId(); - return ownerMatches(ownerId, player.getUniqueId()); + return ownerMatches(ownerId, player.id()); } static boolean canCreateVariants(JigsawStudioLayout layout) { @@ -7272,7 +6700,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return ownerId == null || ownerId.equals(actorId); } - private static boolean authorizeOwner(Player player, ActiveStudio studio) { + private static boolean authorizeOwner(ToolPlayer player, ActiveStudio studio) { if (ownerMatches(player, studio)) { return true; } @@ -7280,21 +6708,17 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return false; } - private boolean isUnauthorizedStudioEdit(Player player, Block block) { - if (player == null || block == null) { - return false; - } - ActiveStudio studio = studios.get(block.getWorld().getUID()); - if (studio == null) { + private boolean isUnauthorizedStudioEdit(ToolPlayer player, ActiveStudio studio, BlockPosition block) { + if (player == null || studio == null || block == null) { return false; } UUID requestId = studio.generator().getRequest().requestId(); - if (previewRenderer.contains(requestId, block.getX(), block.getY(), block.getZ())) { + if (previewRenderer.contains(requestId, block.x(), block.y(), block.z())) { message(player, "The seed-1337 Jigsaw preview is read-only and refreshes automatically."); return true; } JigsawStudioSession session = studio.generator().getSession(); - JigsawStudioBay bay = session.layout().findAt(block.getX(), block.getY(), block.getZ()); + JigsawStudioBay bay = session.layout().findAt(block.x(), block.y(), block.z()); JigsawStudioVariant variant = bay == null ? null : session.activeVariant(bay.stableId()).orElse(null); @@ -7312,7 +6736,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC message(player, "Wait for the current Jigsaw Studio variant load or rollback to finish."); return true; } - if (!blocksStudioEdit(studio.generator().getRequest().ownerId(), player.getUniqueId())) { + if (!blocksStudioEdit(studio.generator().getRequest().ownerId(), player.id())) { return false; } message(player, "This Jigsaw Studio is owned by another player session."); @@ -7374,55 +6798,27 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC || actorId != null && blocksStudioEdit(ownerId, actorId)); } - private boolean movesProtectedBlocks(List blocks, BlockFace direction) { - for (Block block : blocks) { - if (isImmutableStudioBlock(block) - || isImmutableStudioBlock(block.getRelative(direction)) - || isImmutableStudioBlock(block.getRelative(direction.getOppositeFace()))) { - return true; - } - } - return false; - } - - private boolean containsImmutableStudioBlock(List states) { - for (BlockState state : states) { - if (isImmutableStudioBlock(state.getBlock())) { - return true; - } - } - return false; - } - - private boolean isImmutableStudioBlock(Block block) { - StudioBlockMutationContext context = studioBlockMutationContext(block); + private boolean isImmutableStudioBlock(ActiveStudio studio, BlockPosition block) { + StudioBlockMutationContext context = studioBlockMutationContext(studio, block); return context != null && context.immutable(); } - private boolean isPreviewBlock(Block block) { - if (block == null) { - return false; - } - ActiveStudio studio = studios.get(block.getWorld().getUID()); - if (studio == null) { - return false; - } - UUID requestId = studio.generator().getRequest().requestId(); - return previewRenderer.contains(requestId, block.getX(), block.getY(), block.getZ()); - } - - private boolean isControlChest(Block block) { - if (block == null || block.getType() != Material.CHEST) { - return false; - } - ActiveStudio studio = studios.get(block.getWorld().getUID()); - if (studio == null) { + /** + * Whether the block is the studio's control chest. A block this thread does not own cannot be read, and the control + * position only ever holds the chest, so the position decides there. + */ + private boolean isControlChest(ActiveStudio studio, BlockPosition block) { + if (studio == null || block == null) { return false; } JigsawStudioControlPosition control = studio.generator().getLayout().controlPosition(); - return block.getX() == control.worldX() - && block.getY() == control.worldY() - && block.getZ() == control.worldZ(); + boolean atControlPosition = block.x() == control.worldX() + && block.y() == control.worldY() + && block.z() == control.worldZ(); + if (!atControlPosition) { + return false; + } + return blockIfOwned(studio, block).map(JigsawStudioBlocks::isChest).orElse(true); } private static JigsawStudioBoardState boardState( @@ -7459,40 +6855,30 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return separator < 0 ? resourceKey : resourceKey.substring(separator + 1); } - private static boolean sameBlockPosition(Location first, Location second) { - if (first == null || second == null || first.getWorld() == null || second.getWorld() == null) { - return false; - } - return first.getWorld().getUID().equals(second.getWorld().getUID()) - && first.getBlockX() == second.getBlockX() - && first.getBlockY() == second.getBlockY() - && first.getBlockZ() == second.getBlockZ(); - } - - private void ensureVisualizationLoop(Player player) { + private void ensureVisualizationLoop(ToolPlayer player) { if (player == null) { return; } - if (!J.isOwnedByCurrentRegion(player)) { - J.runEntity(player, () -> ensureVisualizationLoop(player)); + if (!JigsawStudioThreads.owns(player)) { + JigsawStudioThreads.run(player, () -> ensureVisualizationLoop(player)); return; } - UUID playerId = player.getUniqueId(); - if (!enabled || particlesDisabled.contains(playerId) - || !studios.containsKey(player.getWorld().getUID()) + UUID playerId = player.id(); + if (particlesDisabled.contains(playerId) + || studioOf(player) == null || !visualizationLoops.add(playerId)) { return; } visualizationTick(player); } - private void visualizationTick(Player player) { - UUID playerId = player.getUniqueId(); - if (!enabled || particlesDisabled.contains(playerId)) { + private void visualizationTick(ToolPlayer player) { + UUID playerId = player.id(); + if (particlesDisabled.contains(playerId)) { visualizationLoops.remove(playerId); return; } - ActiveStudio studio = studios.get(player.getWorld().getUID()); + ActiveStudio studio = studioOf(player); if (studio == null) { visualizationLoops.remove(playerId); return; @@ -7501,50 +6887,58 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC renderVisualization(player, studio); } catch (Throwable exception) { visualizationLoops.remove(playerId); - IrisLogging.reportError(exception); + reportError(exception); return; } - boolean scheduled = J.runEntity( + scheduler.onPlayerLater( player, () -> visualizationTick(player), VISUAL_INTERVAL_TICKS, () -> visualizationLoops.remove(playerId)); - if (!scheduled) { - visualizationLoops.remove(playerId); - } } - private void renderVisualization(Player player, ActiveStudio studio) { + private void renderVisualization(ToolPlayer player, ActiveStudio studio) { + ParticleBudget budget = new ParticleBudget(PARTICLE_BUDGET); + drawVisualization(player, studio, budget); + player.particles(budget.dust()); + } + + private void drawVisualization(ToolPlayer player, ActiveStudio studio, ParticleBudget budget) { JigsawStudioSession session = studio.generator().getSession(); JigsawStudioLayout layout = session.layout(); - Location playerLocation = player.getLocation(); - JigsawStudioBay focused = layout.findAt( - playerLocation.getBlockX(), - playerLocation.getBlockY(), - playerLocation.getBlockZ()); - ParticleBudget budget = new ParticleBudget(PARTICLE_BUDGET); + BlockPosition playerBlock = player.position(); + ViewPoint playerLocation = new ViewPoint( + playerBlock.x() + BLOCK_CENTER, playerBlock.y(), playerBlock.z() + BLOCK_CENTER); + JigsawStudioBay focused = layout.findAt(playerBlock.x(), playerBlock.y(), playerBlock.z()); if (focused != null) { - Color focusedColor = bayValid(studio, focused) ? SELECTED_COLOR : INVALID_BAY_COLOR; - drawConnectors(player, playerLocation, studio, focused, budget); - drawBounds(player, playerLocation, focused.bounds(), focusedColor, 1.15F, 1.0D, budget); + int focusedColor = bayValid(studio, focused) ? SELECTED_COLOR : INVALID_BAY_COLOR; + drawConnectors(playerLocation, studio, focused, budget); + drawBounds(playerLocation, focused.bounds(), focusedColor, 1.15F, 1.0D, budget); } - drawLivePreview(player, playerLocation, studio, budget); - drawAssemblyPreview(player, playerLocation, budget); + drawLivePreview(playerLocation, studio, budget); + drawAssemblyPreview(player, playerLocation, studio, budget); for (JigsawStudioBay bay : layout.bays()) { if (bay == focused || !isNearby(playerLocation, bay.bounds())) { continue; } - Color nearbyColor = bayValid(studio, bay) ? NEARBY_COLOR : INVALID_BAY_COLOR; - drawBounds(player, playerLocation, bay.bounds(), nearbyColor, 0.55F, 4.0D, budget); + int nearbyColor = bayValid(studio, bay) ? NEARBY_COLOR : INVALID_BAY_COLOR; + drawBounds(playerLocation, bay.bounds(), nearbyColor, 0.55F, 4.0D, budget); if (budget.empty()) { return; } } } + /** Where the viewer is, as particle distances count it. */ + private record ViewPoint(double x, double y, double z) { + } + + private static int rgb(int red, int green, int blue) { + return (red << 16) | (green << 8) | blue; + } + private void drawLivePreview( - Player player, - Location playerLocation, + ViewPoint playerLocation, ActiveStudio studio, ParticleBudget budget ) { @@ -7558,13 +6952,12 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC preview.maximumX() - preview.minimumX() + 1, preview.maximumY() - preview.minimumY() + 1, preview.maximumZ() - preview.minimumZ() + 1); - Color color = switch (evaluation.state()) { + int color = switch (evaluation.state()) { case VALID -> ASSEMBLY_PREVIEW_COLOR; case PENDING, WARNING, STALE -> LIVE_PREVIEW_WARNING_COLOR; case INVALID -> INVALID_BAY_COLOR; }; drawBounds( - player, playerLocation, new JigsawStudioBounds( preview.minimumX(), @@ -7578,21 +6971,22 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } private void drawAssemblyPreview( - Player player, - Location playerLocation, + ToolPlayer player, + ViewPoint playerLocation, + ActiveStudio studio, ParticleBudget budget ) { - AssemblyPreview preview = assemblyPreviews.get(player.getUniqueId()); + AssemblyPreview preview = assemblyPreviews.get(player.id()); if (preview == null) { return; } - if (!preview.worldId().equals(player.getWorld().getUID()) + if (!preview.worldId().equals(studio.worldId()) || preview.expiresAtMillis() < System.currentTimeMillis()) { - assemblyPreviews.remove(player.getUniqueId(), preview); + assemblyPreviews.remove(player.id(), preview); return; } for (JigsawStudioBounds bounds : preview.bounds()) { - drawBounds(player, playerLocation, bounds, ASSEMBLY_PREVIEW_COLOR, 0.85F, 2.0D, budget); + drawBounds(playerLocation, bounds, ASSEMBLY_PREVIEW_COLOR, 0.85F, 2.0D, budget); if (budget.empty()) { return; } @@ -7600,8 +6994,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } private static void drawConnectors( - Player player, - Location playerLocation, + ViewPoint playerLocation, ActiveStudio studio, JigsawStudioBay bay, ParticleBudget budget @@ -7612,9 +7005,8 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } for (JigsawStudioGenerator.RenderedConnector renderedConnector : rendered.connectors()) { IrisJigsawConnector connector = renderedConnector.connector(); - IrisDirection direction = connector.getDirection(); + JigsawDirection direction = connector.getDirection(); drawConnectorLine( - player, playerLocation, bay.bounds().originX() + renderedConnector.x() + 0.5D, bay.bounds().originY() + renderedConnector.y() + 0.5D, @@ -7629,17 +7021,15 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } private static void drawConnectorLine( - Player player, - Location playerLocation, + ViewPoint playerLocation, double startX, double startY, double startZ, - IrisDirection direction, - Color color, + JigsawDirection direction, + int color, ParticleBudget budget ) { drawLine( - player, playerLocation, startX, startY, @@ -7658,7 +7048,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return rendered.valid() && studio.population(bay).readiness().failure().isEmpty(); } - private static Color connectorColor(IrisJigsawConnector connector) { + private static int connectorColor(IrisJigsawConnector connector) { if (connector.getPool() == null || connector.getPool().isBlank() || connector.getName() == null || connector.getName().isBlank() || connector.getTargetName() == null || connector.getTargetName().isBlank()) { @@ -7672,14 +7062,13 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC int red = 80 + (hash & 127); int green = 80 + ((hash >>> 8) & 127); int blue = 80 + ((hash >>> 16) & 127); - return Color.fromRGB(red, green, blue); + return rgb(red, green, blue); } private static void drawBounds( - Player player, - Location playerLocation, + ViewPoint playerLocation, JigsawStudioBounds bounds, - Color color, + int color, float size, double step, ParticleBudget budget @@ -7690,30 +7079,29 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC double maxX = bounds.maxX() + 1.0D; double maxY = bounds.maxY() + 1.0D; double maxZ = bounds.maxZ() + 1.0D; - drawLine(player, playerLocation, minX, minY, minZ, maxX, minY, minZ, color, size, step, budget); - drawLine(player, playerLocation, minX, minY, maxZ, maxX, minY, maxZ, color, size, step, budget); - drawLine(player, playerLocation, minX, maxY, minZ, maxX, maxY, minZ, color, size, step, budget); - drawLine(player, playerLocation, minX, maxY, maxZ, maxX, maxY, maxZ, color, size, step, budget); - drawLine(player, playerLocation, minX, minY, minZ, minX, maxY, minZ, color, size, step, budget); - drawLine(player, playerLocation, maxX, minY, minZ, maxX, maxY, minZ, color, size, step, budget); - drawLine(player, playerLocation, minX, minY, maxZ, minX, maxY, maxZ, color, size, step, budget); - drawLine(player, playerLocation, maxX, minY, maxZ, maxX, maxY, maxZ, color, size, step, budget); - drawLine(player, playerLocation, minX, minY, minZ, minX, minY, maxZ, color, size, step, budget); - drawLine(player, playerLocation, maxX, minY, minZ, maxX, minY, maxZ, color, size, step, budget); - drawLine(player, playerLocation, minX, maxY, minZ, minX, maxY, maxZ, color, size, step, budget); - drawLine(player, playerLocation, maxX, maxY, minZ, maxX, maxY, maxZ, color, size, step, budget); + drawLine(playerLocation, minX, minY, minZ, maxX, minY, minZ, color, size, step, budget); + drawLine(playerLocation, minX, minY, maxZ, maxX, minY, maxZ, color, size, step, budget); + drawLine(playerLocation, minX, maxY, minZ, maxX, maxY, minZ, color, size, step, budget); + drawLine(playerLocation, minX, maxY, maxZ, maxX, maxY, maxZ, color, size, step, budget); + drawLine(playerLocation, minX, minY, minZ, minX, maxY, minZ, color, size, step, budget); + drawLine(playerLocation, maxX, minY, minZ, maxX, maxY, minZ, color, size, step, budget); + drawLine(playerLocation, minX, minY, maxZ, minX, maxY, maxZ, color, size, step, budget); + drawLine(playerLocation, maxX, minY, maxZ, maxX, maxY, maxZ, color, size, step, budget); + drawLine(playerLocation, minX, minY, minZ, minX, minY, maxZ, color, size, step, budget); + drawLine(playerLocation, maxX, minY, minZ, maxX, minY, maxZ, color, size, step, budget); + drawLine(playerLocation, minX, maxY, minZ, minX, maxY, maxZ, color, size, step, budget); + drawLine(playerLocation, maxX, maxY, minZ, maxX, maxY, maxZ, color, size, step, budget); } private static void drawLine( - Player player, - Location playerLocation, + ViewPoint playerLocation, double startX, double startY, double startZ, double endX, double endY, double endZ, - Color color, + int color, float size, double step, ParticleBudget budget @@ -7726,32 +7114,31 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC double deltaZ = endZ - startZ; double length = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ); int samples = Math.max(1, (int) Math.ceil(length / step)); - Particle.DustOptions dust = new Particle.DustOptions(color, size); for (int index = 0; index <= samples; index++) { double progress = (double) index / samples; double x = startX + deltaX * progress; double y = startY + deltaY * progress; double z = startZ + deltaZ * progress; - double distanceX = playerLocation.getX() - x; - double distanceY = playerLocation.getY() - y; - double distanceZ = playerLocation.getZ() - z; + double distanceX = playerLocation.x() - x; + double distanceY = playerLocation.y() - y; + double distanceZ = playerLocation.z() - z; if (distanceX * distanceX + distanceY * distanceY + distanceZ * distanceZ > VISUAL_RANGE_SQUARED) { continue; } if (!budget.consume()) { return; } - player.spawnParticle(Particle.DUST, x, y, z, 1, 0.0D, 0.0D, 0.0D, 0.0D, dust); + budget.add(new Particle(x, y, z, color, size)); } } - private static boolean isNearby(Location location, JigsawStudioBounds bounds) { + private static boolean isNearby(ViewPoint location, JigsawStudioBounds bounds) { double centerX = bounds.originX() + bounds.dimensions().width() / 2.0D; double centerY = bounds.originY() + bounds.dimensions().height() / 2.0D; double centerZ = bounds.originZ() + bounds.dimensions().depth() / 2.0D; - double deltaX = location.getX() - centerX; - double deltaY = location.getY() - centerY; - double deltaZ = location.getZ() - centerZ; + double deltaX = location.x() - centerX; + double deltaY = location.y() - centerY; + double deltaZ = location.z() - centerZ; return deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ <= VISUAL_RANGE_SQUARED; } @@ -7804,23 +7191,19 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return message == null || message.isBlank() ? exception.getClass().getSimpleName() : message; } - private static void message(Player player, String text) { + private static void message(ToolPlayer player, String text) { if (player != null) { - J.runEntity(player, () -> ComponentMessenger.sendLiteral(player, "[Iris Jigsaw Studio] " + text)); + player.message(ToolText.plain(MESSAGE_PREFIX + text)); } } - static void playSaveSound(Player player) { + static void playSaveSound(ToolPlayer player) { if (player != null) { - J.runEntity(player, () -> player.playSound( - player.getLocation(), - "minecraft:block.note_block.bell", - 0.65F, - 1.65F)); + player.sound(SAVE_SOUND, SAVE_SOUND_VOLUME, SAVE_SOUND_PITCH); } } - private static void report(Player player, boolean enabled, String text) { + private static void report(ToolPlayer player, boolean enabled, String text) { if (enabled) { message(player, text); } @@ -7838,10 +7221,10 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } } - private record ActiveStudio( + /** An open studio: its world, what paints it, and the bookkeeping of populating the workcells. */ + record ActiveStudio( UUID worldId, - World world, - Engine engine, + ToolWorld world, JigsawStudioGenerator generator, ConcurrentHashMap populations, Set hydrationsInProgress, @@ -7850,13 +7233,17 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC ActiveStudio { Objects.requireNonNull(worldId, "Jigsaw Studio world ID"); Objects.requireNonNull(world, "Jigsaw Studio world"); - Objects.requireNonNull(engine, "Jigsaw Studio engine"); Objects.requireNonNull(generator, "Jigsaw Studio generator"); Objects.requireNonNull(populations, "Jigsaw Studio bay populations"); Objects.requireNonNull(hydrationsInProgress, "Jigsaw Studio hydrations"); Objects.requireNonNull(evaluationGeneration, "Jigsaw Studio evaluation generation"); } + /** Whether the platform has the chunk loaded now. */ + boolean isChunkLoaded(int chunkX, int chunkZ) { + return world.loaded(new ChunkPos(chunkX, chunkZ)); + } + BayPopulation population(JigsawStudioBay bay) { return populations.computeIfAbsent(bay.stableId(), key -> { JigsawStudioGenerator.RenderedBay rendered = generator.renderBay(bay); @@ -7949,7 +7336,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } } if (exception != null) { - IrisLogging.reportError(exception); + reportError(exception); } if (finishSuccess) { finishSuccess(); @@ -8016,18 +7403,17 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return; } for (ChunkCaptureArea area : rollbackAreas) { - boolean scheduled = J.runRegion( + JigsawStudioThreads.onRegion( + log, work.world(), area.chunkX(), area.chunkZ(), - () -> materializeRollbackChunk(this, area)); - if (!scheduled) { - rollbackComplete( - area, - "Iris could not schedule rollback for workcell chunk " - + area.chunkX() + "," + area.chunkZ() + ".", - null); - } + () -> materializeRollbackChunk(this, area), + () -> rollbackComplete( + area, + "Iris could not schedule rollback for workcell chunk " + + area.chunkX() + "," + area.chunkZ() + ".", + null)); } } @@ -8052,7 +7438,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } } if (exception != null) { - IrisLogging.reportError(exception); + reportError(exception); } if (finalizeRollback) { finishRollback(); @@ -8113,7 +7499,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return work.studio(); } - private World world() { + private ToolWorld world() { return work.world(); } @@ -8125,7 +7511,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return work.captureTarget(); } - private Player player() { + private ToolPlayer player() { return work.player(); } @@ -8167,7 +7553,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } if (incomplete == 0 && assemblyStarted.compareAndSet(false, true)) { List completed = List.copyOf(snapshots.values()); - J.a(() -> assembleAndPersist(this, completed)); + scheduler.async(() -> assembleAndPersist(this, completed)); } } @@ -8176,7 +7562,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return; } if (exception != null) { - IrisLogging.reportError(exception); + reportError(exception); } complete(); message(player(), failure); @@ -8211,10 +7597,10 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC private record CaptureWork( ActiveStudio studio, - World world, + ToolWorld world, JigsawStudioBay bay, CaptureTarget captureTarget, - Player player, + ToolPlayer player, UUID requestId, JigsawStudioSession.SaveIdentity saveIdentity, AutosaveFailureState autosaveFailureState @@ -8242,8 +7628,8 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC private record MaterializationWork( ActiveStudio studio, - World world, - Player player, + ToolWorld world, + ToolPlayer player, JigsawStudioBay workcell, JigsawStudioSession.VariantSwitchToken token, JigsawStudioGenerator.RenderedBay previous, @@ -8456,7 +7842,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC private record CaptureTarget( JigsawStudioBounds bounds, IrisJigsawPiece piece, - IrisObject object, + SourceObject object, int displayRotationQuarterTurns, boolean connectorsVisible ) { @@ -8603,7 +7989,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC private static DeferredDuplication single( UUID requestId, UUID sessionId, - Player player, + ToolPlayer player, UUID worldId, String workcellId, String sourcePiece @@ -8611,7 +7997,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return new DeferredDuplication( requestId, sessionId, - player.getUniqueId(), + player.id(), worldId, DeferredDuplicationKind.SINGLE, workcellId, @@ -8623,7 +8009,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC private static DeferredDuplication family( UUID requestId, UUID sessionId, - Player player, + ToolPlayer player, UUID worldId, Map sourcePieces, String themeKey @@ -8631,7 +8017,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC return new DeferredDuplication( requestId, sessionId, - player.getUniqueId(), + player.id(), worldId, DeferredDuplicationKind.FAMILY, "", @@ -8702,17 +8088,11 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC int x, int y, int z, - PlatformBlockState state, - TileData tileData + BlockState state, + BlockEntityData blockEntity ) { CapturedBlock { Objects.requireNonNull(state, "Jigsaw Studio captured block state"); - tileData = tileData == null ? null : tileData.clone(); - } - - @Override - public TileData tileData() { - return tileData == null ? null : tileData.clone(); } } @@ -8720,8 +8100,8 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC int x, int y, int z, - IrisDirection direction, - IrisDirection top, + JigsawDirection direction, + JigsawDirection top, String pool, String name, String targetName, @@ -8744,11 +8124,11 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC static CapturedConnector from(IrisJigsawConnector connector) { IrisJigsawConnector source = Objects.requireNonNull(connector, "Jigsaw Studio captured connector"); - IrisPosition position = source.getPosition(); + BlockPosition position = source.getPosition(); return new CapturedConnector( - position.getX(), - position.getY(), - position.getZ(), + position.x(), + position.y(), + position.z(), source.getDirection(), source.getTop(), source.getPool(), @@ -8763,7 +8143,7 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC IrisJigsawConnector toConnector() { return new IrisJigsawConnector() - .setPosition(new IrisPosition(x, y, z)) + .setPosition(new BlockPosition(x, y, z)) .setDirection(direction) .setTop(top) .setPool(pool) @@ -8811,12 +8191,21 @@ public final class JigsawStudioService implements IrisService, JigsawStudioMenuC } private static final class ParticleBudget { + private final List dust = new ArrayList<>(); private int remaining; private ParticleBudget(int remaining) { this.remaining = remaining; } + private void add(Particle particle) { + dust.add(particle); + } + + private List dust() { + return List.copyOf(dust); + } + private boolean consume() { if (remaining < 1) { return false; diff --git a/module/src/main/java/art/arcane/iris/core/service/JigsawStudioThreads.java b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioThreads.java new file mode 100644 index 000000000..739954e17 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioThreads.java @@ -0,0 +1,89 @@ +package art.arcane.iris.core.service; + +import com.volmit.ModuleLog; +import com.volmit.geometry.BlockPosition; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolWorld; + +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.BooleanSupplier; + +/** + * Moves work onto the thread that owns a player or a chunk, the way the studio needs it: a method that must run on a + * player's thread asks {@link #owns} and, when it does not, hands itself to {@link #call}, which runs it at once when the + * caller already is that thread. + */ +final class JigsawStudioThreads { + private static final int CHUNK_SHIFT = 4; + + private JigsawStudioThreads() { + } + + /** + * Whether the calling thread is the one that owns the player. A player runs a task at once on their own thread and + * later on any other, so a probe task tells which this is. + */ + static boolean owns(ToolPlayer player) { + boolean[] ranDuringCall = {false}; + boolean[] stillInCall = {true}; + player.run(() -> ranDuringCall[0] = stillInCall[0]); + stillInCall[0] = false; + return ranDuringCall[0]; + } + + /** + * Runs {@code task} on the player's thread and returns what it returned. When the task has to wait for the thread it + * returns {@code true}, standing for "scheduled". + */ + static boolean call(ToolPlayer player, BooleanSupplier task) { + boolean[] result = {true}; + player.run(() -> result[0] = task.getAsBoolean()); + return result[0]; + } + + /** Runs {@code task} on the player's thread, now when the caller is that thread. */ + static void run(ToolPlayer player, Runnable task) { + player.run(task); + } + + /** + * Runs {@code task} on the thread that owns the chunk. {@code notScheduled} runs instead when the host cannot + * schedule it; a task that throws is reported to {@code log}. + */ + static void onRegion( + ModuleLog log, + ToolWorld world, + int chunkX, + int chunkZ, + Runnable task, + Runnable notScheduled + ) { + AtomicBoolean started = new AtomicBoolean(); + world.call(chunkOrigin(chunkX, chunkZ), () -> { + started.set(true); + runReporting(log, task); + return null; + }).whenComplete((ignored, failure) -> { + if (failure != null && !started.get()) { + notScheduled.run(); + } + }); + } + + /** Whether the calling thread owns the chunk. */ + static boolean ownsRegion(ToolWorld world, int chunkX, int chunkZ) { + return world.owns(chunkOrigin(chunkX, chunkZ)); + } + + static BlockPosition chunkOrigin(int chunkX, int chunkZ) { + return new BlockPosition(chunkX << CHUNK_SHIFT, 0, chunkZ << CHUNK_SHIFT); + } + + private static void runReporting(ModuleLog log, Runnable task) { + try { + task.run(); + } catch (Throwable failure) { + log.error("A Jigsaw Studio region task failed.", failure); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/core/service/JigsawStudioTileCodec.java b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioTileCodec.java new file mode 100644 index 000000000..abca386d3 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioTileCodec.java @@ -0,0 +1,62 @@ +package art.arcane.iris.core.service; + +import art.arcane.volmlib.util.collection.KMap; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.Strictness; +import com.google.gson.ToNumberPolicy; +import com.volmit.object.BlockEntityData; +import com.volmit.resource.ResourceId; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.Map; +import java.util.Optional; + +/** + * The block entities of the studio's jigsaw markers in the host's tile format, {@code iris:tile} version 1: the block's + * key and its NBT as JSON, which is the form the host keeps tile data in everywhere else. + */ +final class JigsawStudioTileCodec { + static final ResourceId TILE_FORMAT = ResourceId.parse("iris:tile"); + static final int TILE_FORMAT_VERSION = 1; + + private static final Gson GSON = new GsonBuilder() + .disableHtmlEscaping() + .setStrictness(Strictness.LENIENT) + .setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE) + .create(); + + private JigsawStudioTileCodec() { + } + + static BlockEntityData encode(String blockKey, Map nbt) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream out = new DataOutputStream(bytes)) { + out.writeUTF(blockKey); + out.writeUTF(GSON.toJson(nbt)); + } catch (IOException failure) { + throw new UncheckedIOException("Cannot store the NBT of " + blockKey, failure); + } + return new BlockEntityData(TILE_FORMAT, TILE_FORMAT_VERSION, bytes.toByteArray()); + } + + /** The NBT {@code data} holds; empty when it is not in the tile format. */ + static Optional> nbt(BlockEntityData data) { + if (!TILE_FORMAT.equals(data.format()) || data.version() != TILE_FORMAT_VERSION) { + return Optional.empty(); + } + try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(data.payload()))) { + in.readUTF(); + @SuppressWarnings("unchecked") + KMap nbt = GSON.fromJson(in.readUTF(), KMap.class); + return Optional.ofNullable(nbt); + } catch (IOException failure) { + throw new UncheckedIOException("Cannot read a block entity of format " + TILE_FORMAT, failure); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/core/service/JigsawStudioToolCodec.java b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioToolCodec.java new file mode 100644 index 000000000..0fcc55f90 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioToolCodec.java @@ -0,0 +1,132 @@ +package art.arcane.iris.core.service; + +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolAction; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolPayload; +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolItem; +import com.volmit.tooling.world.ToolText; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; + +/** Turns a studio tool payload into the tool item a player holds, and the item back into the payload. */ +public final class JigsawStudioToolCodec { + static final ResourceId TOOL_ITEM = ResourceId.parse("minecraft:stick"); + static final String NAME_PREFIX = "Jigsaw Studio: "; + static final String SCHEMA_FIELD = "schema"; + static final String ACTION_FIELD = "action"; + static final String REQUEST_FIELD = "request"; + static final String WORKCELL_FIELD = "workcell"; + static final String PIECE_FIELD = "piece"; + static final String POOL_FIELD = "pool"; + static final String ENTRY_INDEX_FIELD = "entryIndex"; + static final String AMOUNT_FIELD = "amount"; + + private static final Gson GSON = new Gson(); + + public ToolItem create(JigsawStudioToolPayload payload) { + JigsawStudioToolPayload binding = requireCurrentSchema(payload); + return new ToolItem( + TOOL_ITEM, + ToolText.colored(TextColor.AQUA, NAME_PREFIX + binding.action().displayName()), + lore(binding), + false, + encode(binding)); + } + + public Optional decode(ToolItem tool) { + if (tool == null || !TOOL_ITEM.equals(tool.item())) { + return Optional.empty(); + } + return decode(tool.payload()); + } + + public boolean isTool(ToolItem tool) { + return decode(tool).isPresent(); + } + + String encode(JigsawStudioToolPayload payload) { + JigsawStudioToolPayload binding = requireCurrentSchema(payload); + JsonObject json = new JsonObject(); + json.addProperty(SCHEMA_FIELD, binding.schemaVersion()); + json.addProperty(ACTION_FIELD, binding.action().name()); + json.addProperty(REQUEST_FIELD, binding.requestId().toString()); + json.addProperty(WORKCELL_FIELD, binding.workcellId()); + json.addProperty(PIECE_FIELD, binding.pieceKey()); + json.addProperty(POOL_FIELD, binding.poolKey()); + json.addProperty(ENTRY_INDEX_FIELD, binding.entryIndex()); + json.addProperty(AMOUNT_FIELD, binding.amount()); + return GSON.toJson(json); + } + + Optional decode(String payload) { + if (payload == null || payload.isEmpty()) { + return Optional.empty(); + } + try { + JsonObject json = GSON.fromJson(payload, JsonObject.class); + if (json == null + || !json.has(SCHEMA_FIELD) + || !json.has(ACTION_FIELD) + || !json.has(REQUEST_FIELD) + || json.get(SCHEMA_FIELD).getAsInt() != JigsawStudioToolPayload.CURRENT_SCHEMA_VERSION) { + return Optional.empty(); + } + return Optional.of(new JigsawStudioToolPayload( + json.get(SCHEMA_FIELD).getAsInt(), + JigsawStudioToolAction.valueOf(json.get(ACTION_FIELD).getAsString()), + UUID.fromString(json.get(REQUEST_FIELD).getAsString()), + optionalString(json, WORKCELL_FIELD), + optionalString(json, PIECE_FIELD), + optionalString(json, POOL_FIELD), + json.has(ENTRY_INDEX_FIELD) + ? json.get(ENTRY_INDEX_FIELD).getAsInt() + : JigsawStudioToolPayload.NO_ENTRY_INDEX, + json.has(AMOUNT_FIELD) ? json.get(AMOUNT_FIELD).getAsInt() : 0)); + } catch (IllegalArgumentException | IllegalStateException | UnsupportedOperationException + | JsonParseException exception) { + return Optional.empty(); + } + } + + private static JigsawStudioToolPayload requireCurrentSchema(JigsawStudioToolPayload payload) { + JigsawStudioToolPayload binding = Objects.requireNonNull(payload, "Jigsaw Studio tool payload"); + if (binding.schemaVersion() != JigsawStudioToolPayload.CURRENT_SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported Jigsaw Studio tool schema " + + binding.schemaVersion()); + } + return binding; + } + + private static String optionalString(JsonObject json, String field) { + return json.has(field) ? json.get(field).getAsString() : ""; + } + + private static List lore(JigsawStudioToolPayload payload) { + List lore = new ArrayList<>(); + if (!payload.workcellId().isEmpty()) { + lore.add(ToolText.colored(TextColor.GRAY, "Workcell: " + payload.workcellId())); + } + if (!payload.pieceKey().isEmpty()) { + lore.add(ToolText.colored(TextColor.GRAY, "Variant: " + payload.pieceKey())); + } + if (!payload.poolKey().isEmpty()) { + lore.add(ToolText.colored(TextColor.GRAY, "Pool: " + payload.poolKey() + + (payload.entryIndex() < 0 ? "" : " [" + payload.entryIndex() + "]"))); + } + if (payload.amount() != 0) { + lore.add(ToolText.colored(TextColor.GRAY, "Amount: " + payload.amount())); + } + lore.add(payload.action().destructive() + ? ToolText.colored(TextColor.RED, "Right-click twice to confirm") + : ToolText.colored(TextColor.YELLOW, "Right-click to use")); + return List.copyOf(lore); + } +} diff --git a/module/src/main/java/art/arcane/iris/core/service/JigsawStudioWorldListener.java b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioWorldListener.java new file mode 100644 index 000000000..f174c243c --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/service/JigsawStudioWorldListener.java @@ -0,0 +1,91 @@ +package art.arcane.iris.core.service; + +import com.volmit.geometry.BlockPosition; +import com.volmit.tooling.world.BlockChange; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolUse; +import com.volmit.tooling.world.ToolWorldListener; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +/** + * What a Jigsaw Studio world hears from its host: the world's players, blocks and commands, handed to the studio service + * that decides. The studio's id is the id of its request. + */ +final class JigsawStudioWorldListener implements ToolWorldListener { + private final JigsawStudioService service; + private final UUID studioId; + + JigsawStudioWorldListener(JigsawStudioService service, UUID studioId) { + this.service = Objects.requireNonNull(service, "Jigsaw Studio service"); + this.studioId = Objects.requireNonNull(studioId, "Jigsaw Studio ID"); + } + + @Override + public void entered(ToolPlayer player) { + service.playerEntered(player); + } + + @Override + public void left(ToolPlayer player) { + service.playerLeft(player); + } + + @Override + public void moved(ToolPlayer player, BlockPosition to) { + service.playerMoved(player, to); + } + + @Override + public void teleported(ToolPlayer player, BlockPosition to) { + service.playerTeleported(player, to); + } + + @Override + public void containerChanged(Optional player, BlockPosition at) { + service.containerChanged(studioId, at); + } + + @Override + public void sneakToggled(ToolPlayer player, boolean sneaking) { + service.sneakToggled(player, sneaking); + } + + @Override + public boolean used(ToolPlayer player, ToolUse use) { + return service.playerUsed(studioId, player, use); + } + + @Override + public boolean blockChanging(BlockChange change) { + return service.blockChanging(studioId, change); + } + + @Override + public boolean command(Optional sender, String line) { + return service.command(studioId, sender, line); + } + + @Override + public void chunkLoaded(int chunkX, int chunkZ) { + service.chunkLoaded(studioId, chunkX, chunkZ); + } + + @Override + public Optional closeRefusal() { + return service.closeRefusal(studioId); + } + + @Override + public CompletableFuture closing(Optional by) { + return service.closing(studioId, by); + } + + @Override + public void closed() { + service.worldClosed(studioId); + } +} diff --git a/module/src/main/java/art/arcane/iris/core/structure/BulkStructureImporter.java b/module/src/main/java/art/arcane/iris/core/structure/BulkStructureImporter.java new file mode 100644 index 000000000..1301a343a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/structure/BulkStructureImporter.java @@ -0,0 +1,565 @@ +/* + * 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.structure; + +import art.arcane.iris.core.structure.tooling.SenderText; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.Sender; +import com.volmit.tooling.ToolPack; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolText; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; + +import art.arcane.iris.core.structure.authoring.StructureBundleNames; +import art.arcane.iris.core.structure.authoring.StructureIndexService; + +public final class BulkStructureImporter { + private static final int TEMPLATE_PROGRESS_INTERVAL = 50; + + public record Report( + int total, + int imported, + int skipped, + int failed, + Map successfulBundles, + boolean retryRequired, + Set captureCandidates + ) { + public Report(int total, int imported, int skipped, int failed) { + this(total, imported, skipped, failed, Map.of(), false, Set.of()); + } + + public Report(int total, int imported, int skipped, int failed, Map successfulBundles) { + this(total, imported, skipped, failed, successfulBundles, false, Set.of()); + } + + public Report(int total, int imported, int skipped, int failed, + Map successfulBundles, boolean retryRequired) { + this(total, imported, skipped, failed, successfulBundles, retryRequired, Set.of()); + } + + public Report { + successfulBundles = Collections.unmodifiableMap(new TreeMap<>(successfulBundles)); + captureCandidates = Collections.unmodifiableSet(new TreeSet<>(captureCandidates)); + } + } + + private BulkStructureImporter() { + } + + public static Report importAllVanilla(ToolPack pack, PlatformStructures platform, StructureImporter.Mode mode, + boolean includeNonJigsaw, Sender sender) { + List vanilla = new ArrayList<>(platform.structures()); + Collections.sort(vanilla); + + int total = vanilla.size(); + int imported = 0; + int skipped = 0; + int failed = 0; + TreeSet captureCandidates = new TreeSet<>(); + + SenderText.send(sender, ToolText.builder() + .green("Importing ").white(String.valueOf(total)) + .green(" vanilla & datapack structures (mode=" + mode + ", includeNonJigsaw=" + includeNonJigsaw + ")...") + .build()); + + for (ResourceId nk : vanilla) { + String keyString = nk.toString(); + String name = StructureImporter.deriveName(nk); + + try { + VillageImporter.Result jigsaw = VillageImporter.importVillage(pack, platform, nk, name, mode); + if (jigsaw.success()) { + imported++; + SenderText.send(sender, TextColor.GRAY, "[jigsaw] " + keyString + " -> " + name); + continue; + } + + String message = jigsaw.message() == null ? "" : jigsaw.message(); + if (message.contains("is not a jigsaw structure")) { + if (!includeNonJigsaw) { + skipped++; + continue; + } + StructureImporter.Result single = StructureImporter.importStructure(pack, platform, nk, name, mode); + if (single.success()) { + imported++; + SenderText.send(sender, TextColor.GRAY, "[single] " + keyString + " -> " + name); + } else if (single.message() != null && single.message().startsWith("Skipped")) { + skipped++; + } else if (isCaptureCandidate(message, single.message())) { + skipped++; + captureCandidates.add(keyString); + SenderText.send(sender, TextColor.YELLOW, "[skip] " + keyString + + ": no single-template NBT - vanilla builds this in code or from separate piece templates (imported via the templates pass); nothing to import as one structure."); + } else { + failed++; + SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + single.message()); + } + continue; + } + + if (message.startsWith("Skipped")) { + skipped++; + continue; + } + + failed++; + SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + message); + } catch (Throwable e) { + failed++; + SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + e.getMessage()); + } + } + + refreshIndex(pack, platform); + + SenderText.send(sender, completion("Bulk import complete: ", imported, skipped, failed, total)); + return new Report(total, imported, skipped, failed, Map.of(), false, captureCandidates); + } + + public static Report importTemplateGroups(ToolPack pack, PlatformStructures platform, StructureImporter.Mode mode, + Sender sender) { + String[][] groups = { + {"shipwreck", "minecraft:shipwreck", "shipwreck"}, + {"ruined_portal", "minecraft:ruined_portal", "ruined_portal"}, + {"ocean_ruin", "minecraft:ocean_ruin_cold", "underwater_ruin"}, + {"nether_fossil", "minecraft:nether_fossil", "nether_fossils"}, + }; + + int imported = 0; + int skipped = 0; + int failed = 0; + + SenderText.send(sender, TextColor.GREEN, + "Building single-template structures from imported pieces (one variant placed per generation)..."); + for (String[] g : groups) { + try { + StructureImporter.Result result = StructureImporter.importTemplateGroup(pack, g[0], g[1], g[2], mode); + if (result.success()) { + imported++; + SenderText.send(sender, TextColor.GRAY, "[group] " + g[1] + " -> " + g[0] + " (" + result.blocks() + " variants)"); + } else if (result.message() != null && result.message().startsWith("Skipped")) { + skipped++; + } else { + skipped++; + SenderText.send(sender, TextColor.YELLOW, "[skip] " + g[0] + ": " + result.message()); + } + } catch (Throwable e) { + failed++; + SenderText.send(sender, TextColor.RED, "[fail] " + g[0] + ": " + e.getMessage()); + } + } + + refreshIndex(pack, platform); + SenderText.send(sender, ToolText.builder() + .green("Single-template structures: ").white(String.valueOf(imported)) + .green(" built, ").white(String.valueOf(skipped)) + .green(" skipped, ").white(String.valueOf(failed)) + .green(" failed.").build()); + return new Report(groups.length, imported, skipped, failed); + } + + public static Report importAllTemplates(ToolPack pack, PlatformStructures platform, StructureImporter.Mode mode, + Sender sender) { + List all; + try { + all = new ArrayList<>(platform.templates()); + } catch (Throwable e) { + SenderText.send(sender, TextColor.RED, + "Failed to enumerate structure templates via the server ResourceManager: " + e.getMessage()); + return enumerationFailureReport(); + } + Collections.sort(all); + + int total = all.size(); + int imported = 0; + int skipped = 0; + int failed = 0; + + if (total == 0) { + SenderText.send(sender, TextColor.YELLOW, "No structure templates were found under the 'structure' resource path."); + return new Report(0, 0, 0, 0); + } + + SenderText.send(sender, ToolText.builder() + .green("Importing ").white(String.valueOf(total)) + .green(" structure templates (mode=" + mode + ")...").build()); + + for (ResourceId nk : all) { + String keyString = nk.toString(); + String name = templateNameFor(keyString); + + try { + StructureImporter.Result result = StructureImporter.importStructure(pack, platform, nk, name, mode, true); + if (result.success()) { + imported++; + } else if (result.message() != null && result.message().startsWith("Skipped")) { + skipped++; + } else { + failed++; + SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + result.message()); + } + } catch (Throwable e) { + failed++; + SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + e.getMessage()); + } + + int processed = imported + skipped + failed; + if (processed % TEMPLATE_PROGRESS_INTERVAL == 0) { + SenderText.send(sender, TextColor.GRAY, "..." + processed + "/" + total + " (" + imported + + " imported, " + skipped + " skipped, " + failed + " failed)"); + } + } + + refreshIndex(pack, platform); + + SenderText.send(sender, completion("Template import complete: ", imported, skipped, failed, total)); + return new Report(total, imported, skipped, failed); + } + + public static Report importDatapackStructures(ToolPack pack, PlatformStructures platform, StructureImporter.Mode mode, + Sender sender) { + return importDatapackStructures( + pack, + platform, + mode, + sender, + null, + null, + StructureImporter.Ownership.EDITABLE + ); + } + + public static Report importManagedDatapackStructures( + ToolPack pack, + PlatformStructures platform, + StructureImporter.Mode mode, + Sender sender, + Set allowedStructureKeys, + Set allowedTemplateKeys + ) { + return importDatapackStructures( + pack, + platform, + mode, + sender, + allowedStructureKeys, + allowedTemplateKeys, + StructureImporter.Ownership.MANAGED_DATAPACK + ); + } + + private static Report importDatapackStructures( + ToolPack pack, + PlatformStructures platform, + StructureImporter.Mode mode, + Sender sender, + Set allowedStructureKeys, + Set allowedTemplateKeys, + StructureImporter.Ownership ownership + ) { + KeySelection structureSelection = selectDatapackKeys(keysOf(platform.structures()), allowedStructureKeys); + List datapack = structureSelection.present(); + + int structureAttempts = structureSelection.total(); + int templateAttempts = 0; + int imported = 0; + int skipped = 0; + int failed = structureSelection.missing().size(); + boolean retryRequired = false; + Map successfulBundles = new TreeMap<>(); + + if (structureAttempts == 0) { + SenderText.send(sender, TextColor.YELLOW, + "No datapack (non-minecraft) structures are registered. Ingest a datapack and restart first, then run this again."); + } else { + SenderText.send(sender, ToolText.builder() + .green("Importing ").white(String.valueOf(structureAttempts)) + .green(" datapack structures (mode=" + mode + ")...").build()); + for (String missingKey : structureSelection.missing()) { + SenderText.send(sender, TextColor.RED, "[fail] " + missingKey + + ": allowed structure key is absent from the live registry"); + } + for (String keyString : datapack) { + ResourceId nk = ResourceId.parse(keyString); + String name = StructureImporter.deriveName(nk); + + try { + VillageImporter.Result jigsaw = VillageImporter.importVillage( + pack, + platform, + nk, + name, + mode, + ownership + ); + if (jigsaw.success()) { + imported++; + successfulBundles.put(bundleKey(name), keyString); + SenderText.send(sender, TextColor.GRAY, "[jigsaw] " + keyString + " -> " + name); + continue; + } + retryRequired |= jigsaw.retryableFailure(); + + String message = jigsaw.message() == null ? "" : jigsaw.message(); + if (message.contains("is not a jigsaw structure")) { + StructureImporter.Result single = StructureImporter.importStructure( + pack, + platform, + nk, + name, + mode, + false, + ownership + ); + if (single.success()) { + imported++; + successfulBundles.put(bundleKey(name), keyString); + SenderText.send(sender, TextColor.GRAY, "[single] " + keyString + " -> " + name); + } else if (single.message() != null && single.message().startsWith("Skipped")) { + skipped++; + } else if (single.message() != null && single.message().contains("No loadable structure NBT")) { + skipped++; + } else { + failed++; + retryRequired |= single.retryableFailure(); + SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + single.message()); + } + continue; + } + + if (message.startsWith("Skipped")) { + skipped++; + continue; + } + + failed++; + SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + message); + } catch (Throwable e) { + failed++; + retryRequired = true; + SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + e.getMessage()); + } + } + } + + if (allowedTemplateKeys == null || !allowedTemplateKeys.isEmpty()) { + List templateKeys = List.of(); + boolean enumerationSucceeded = false; + try { + templateKeys = keysOf(platform.templates()); + enumerationSucceeded = true; + } catch (Throwable e) { + templateAttempts++; + failed++; + retryRequired = true; + SenderText.send(sender, TextColor.YELLOW, + "Could not enumerate datapack templates via the server ResourceManager: " + e.getMessage()); + } + if (enumerationSucceeded) { + KeySelection templateSelection = selectDatapackKeys(templateKeys, allowedTemplateKeys); + List datapackTemplates = templateSelection.present(); + templateAttempts += templateSelection.total(); + failed += templateSelection.missing().size(); + for (String missingKey : templateSelection.missing()) { + SenderText.send(sender, TextColor.RED, "[fail] " + missingKey + + ": allowed template key is absent from the live server resources"); + } + if (!datapackTemplates.isEmpty()) { + SenderText.send(sender, ToolText.builder() + .green("Importing ").white(String.valueOf(datapackTemplates.size())) + .green(" datapack structure templates...").build()); + for (String keyString : datapackTemplates) { + ResourceId nk = ResourceId.parse(keyString); + String name = templateNameFor(keyString); + try { + StructureImporter.Result result = StructureImporter.importStructure( + pack, + platform, + nk, + name, + mode, + true, + ownership + ); + if (result.success()) { + imported++; + successfulBundles.put(bundleKey(name), keyString); + } else if (result.message() != null && result.message().startsWith("Skipped")) { + skipped++; + } else { + failed++; + retryRequired |= result.retryableFailure(); + SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + result.message()); + } + } catch (Throwable e) { + failed++; + retryRequired = true; + SenderText.send(sender, TextColor.RED, "[fail] " + keyString + ": " + e.getMessage()); + } + } + } + } + } + + refreshIndex(pack, platform); + SenderText.send(sender, ToolText.builder() + .green("Datapack structure import complete: ").white(String.valueOf(imported)) + .green(" imported, ").white(String.valueOf(skipped)) + .green(" skipped, ").white(String.valueOf(failed)) + .green(" failed.").build()); + return datapackReport( + structureAttempts, + templateAttempts, + imported, + skipped, + failed, + successfulBundles, + retryRequired); + } + + private static ToolText completion(String label, int imported, int skipped, int failed, int total) { + return ToolText.builder() + .green(label).white(String.valueOf(imported)) + .green(" imported, ").white(String.valueOf(skipped)) + .green(" skipped, ").white(String.valueOf(failed)) + .green(" failed (").white(String.valueOf(total)) + .green(" total).").build(); + } + + private static List keysOf(List ids) { + return ids.stream().map(ResourceId::toString).toList(); + } + + private static void refreshIndex(ToolPack pack, PlatformStructures platform) { + try { + StructureIndexService.write(pack, platform); + } catch (IOException | RuntimeException e) { + pack.log().error("Could not refresh the structure index", e); + } + } + + static boolean isAllowedDatapackKey(String key, Set allowedKeys) { + return allowedKeys == null ? !key.startsWith("minecraft:") : allowedKeys.contains(key); + } + + static boolean isCaptureCandidate(String jigsawMessage, String singleMessage) { + return jigsawMessage != null + && jigsawMessage.contains("is not a jigsaw structure") + && singleMessage != null + && singleMessage.contains("No loadable structure NBT"); + } + + static KeySelection selectDatapackKeys(Iterable discoveredKeys, Set allowedKeys) { + TreeSet discovered = normalizeKeys(discoveredKeys); + TreeSet present = new TreeSet<>(); + TreeSet missing = new TreeSet<>(); + if (allowedKeys == null) { + for (String key : discovered) { + if (isAllowedDatapackKey(key, null)) { + present.add(key); + } + } + } else { + TreeSet allowed = normalizeKeys(allowedKeys); + for (String key : allowed) { + if (discovered.contains(key)) { + present.add(key); + } else { + missing.add(key); + } + } + } + return new KeySelection(new ArrayList<>(present), new ArrayList<>(missing)); + } + + static Report datapackReport( + int structureAttempts, + int templateAttempts, + int imported, + int skipped, + int failed, + Map successfulBundles + ) { + return new Report(structureAttempts + templateAttempts, imported, skipped, failed, successfulBundles); + } + + static Report datapackReport( + int structureAttempts, + int templateAttempts, + int imported, + int skipped, + int failed, + Map successfulBundles, + boolean retryRequired + ) { + return new Report( + structureAttempts + templateAttempts, + imported, + skipped, + failed, + successfulBundles, + retryRequired); + } + + static Report enumerationFailureReport() { + return new Report(1, 0, 0, 1, Map.of(), true); + } + + public static String templateNameFor(String key) { + return StructureBundleNames.templateName(key); + } + + private static TreeSet normalizeKeys(Iterable keys) { + TreeSet normalized = new TreeSet<>(); + for (String key : keys) { + if (key == null || key.isBlank()) { + continue; + } + normalized.add(key.trim().toLowerCase(Locale.ROOT)); + } + return normalized; + } + + private static String bundleKey(String name) { + return "iris:" + name; + } + + record KeySelection(List present, List missing) { + KeySelection { + present = List.copyOf(present); + missing = List.copyOf(missing); + } + + int total() { + return present.size() + missing.size(); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/core/structure/DeclaredObjects.java b/module/src/main/java/art/arcane/iris/core/structure/DeclaredObjects.java new file mode 100644 index 000000000..860320efa --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/structure/DeclaredObjects.java @@ -0,0 +1,120 @@ +package art.arcane.iris.core.structure; + +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockBox; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import com.volmit.object.GeneratedObject; +import com.volmit.object.ObjectBlock; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * Objects as the structure tools write them: a declared size, with blocks placed from the object's minimum corner. Iris + * keeps an object's blocks as offsets from its center, which sits half the size in from that corner. + */ +public final class DeclaredObjects { + private static final BlockPosition ANCHOR = new BlockPosition(0, 0, 0); + + private DeclaredObjects() { + } + + public static Builder builder(int width, int height, int depth) { + return new Builder(width, height, depth); + } + + /** An object of the given size without a block. */ + public static GeneratedObject empty(int width, int height, int depth) { + return builder(width, height, depth).build(); + } + + /** The size {@code object} declares. */ + public static BlockPosition sizeOf(GeneratedObject object) { + BlockBox bounds = object.bounds(); + return new BlockPosition(bounds.maxX() - bounds.minX(), bounds.maxY() - bounds.minY(), bounds.maxZ() - bounds.minZ()); + } + + /** + * {@code object} cut down to the box its blocks fill, centered the way every object is; an object without blocks + * stays as it is. + */ + public static GeneratedObject shrinkwrapped(GeneratedObject object) { + List blocks = object.blocks(); + if (blocks.isEmpty()) { + return object; + } + int minX = Integer.MAX_VALUE; + int minY = Integer.MAX_VALUE; + int minZ = Integer.MAX_VALUE; + int maxX = Integer.MIN_VALUE; + int maxY = Integer.MIN_VALUE; + int maxZ = Integer.MIN_VALUE; + for (ObjectBlock block : blocks) { + BlockPosition position = block.position(); + minX = Math.min(minX, position.x()); + minY = Math.min(minY, position.y()); + minZ = Math.min(minZ, position.z()); + maxX = Math.max(maxX, position.x()); + maxY = Math.max(maxY, position.y()); + maxZ = Math.max(maxZ, position.z()); + } + Builder wrapped = builder(maxX - minX + 1, maxY - minY + 1, maxZ - minZ + 1); + for (ObjectBlock block : blocks) { + BlockPosition position = block.position(); + wrapped.state(position.x() - minX, position.y() - minY, position.z() - minZ, block.state()); + int cornerX = position.x() - minX; + int cornerY = position.y() - minY; + int cornerZ = position.z() - minZ; + block.blockEntity().ifPresent(entity -> wrapped.blockEntity(cornerX, cornerY, cornerZ, entity)); + } + return wrapped.build(); + } + + /** {@code local}, an offset from the object's center, as a position counted from its minimum corner. */ + public static BlockPosition fromCorner(GeneratedObject object, BlockPosition local) { + BlockBox bounds = object.bounds(); + return new BlockPosition(local.x() - bounds.minX(), local.y() - bounds.minY(), local.z() - bounds.minZ()); + } + + public static final class Builder { + private final int width; + private final int height; + private final int depth; + private final Map states = new LinkedHashMap<>(); + private final Map entities = new LinkedHashMap<>(); + + private Builder(int width, int height, int depth) { + this.width = width; + this.height = height; + this.depth = depth; + } + + /** Sets the block at a position counted from the minimum corner. */ + public Builder state(int x, int y, int z, BlockState state) { + states.put(new BlockPosition(x, y, z), state); + return this; + } + + /** Gives the block at a position counted from the minimum corner a block entity. */ + public Builder blockEntity(int x, int y, int z, BlockEntityData entity) { + entities.put(new BlockPosition(x, y, z), entity); + return this; + } + + public GeneratedObject build() { + int centerX = width / 2; + int centerY = height / 2; + int centerZ = depth / 2; + List blocks = new ArrayList<>(states.size()); + states.forEach((position, state) -> blocks.add(new ObjectBlock( + new BlockPosition(position.x() - centerX, position.y() - centerY, position.z() - centerZ), state, + Optional.ofNullable(entities.get(position))))); + BlockBox declared = new BlockBox(-centerX, -centerY, -centerZ, width - centerX, height - centerY, depth - centerZ); + return new GeneratedObject(declared, ANCHOR, blocks, List.of()); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/core/structure/StructureCaptureImporter.java b/module/src/main/java/art/arcane/iris/core/structure/StructureCaptureImporter.java new file mode 100644 index 000000000..f18490981 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/structure/StructureCaptureImporter.java @@ -0,0 +1,194 @@ +/* + * 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.structure; + +import art.arcane.iris.core.structure.tooling.SenderText; +import art.arcane.iris.engine.framework.structure.StructureResources; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.GeneratedObject; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.CapturedStructure; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.Sender; +import com.volmit.tooling.TemplateBlock; +import com.volmit.tooling.ToolPack; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolText; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Optional; +import java.util.Set; +import java.util.TreeSet; + +public final class StructureCaptureImporter { + public record Report(int total, int imported, int skipped, int failed) { + } + + private static final int MAX_SPAN = 48; + private static final int PROGRESS_INTERVAL = 10; + + private StructureCaptureImporter() { + } + + public static Report importAllStructures(ToolPack pack, PlatformStructures platform, StructureImporter.Mode mode, + Sender sender) { + return importStructures(pack, platform, mode, sender, null); + } + + public static Report importStructures(ToolPack pack, PlatformStructures platform, StructureImporter.Mode mode, + Sender sender, Set allowedStructureKeys) { + StructureImporter.Mode activeMode = mode == null ? StructureImporter.Mode.ADD_ONLY : mode; + if (!platform.supportsCapture()) { + SenderText.send(sender, TextColor.YELLOW, + "Structure capture is not supported by the active NMS binding; skipping the capture pass."); + return new Report(0, 0, 0, 0); + } + + List keys = platform.structures().stream().map(ResourceId::toString).toList(); + if (keys.isEmpty()) { + return new Report(0, 0, 0, 0); + } + + PackResources resources = pack.resources(); + ArrayList targets = new ArrayList<>(); + for (String key : selectCaptureKeys(keys, allowedStructureKeys)) { + String name = StructureImporter.deriveName(key); + boolean alreadyImported = resources.ids(StructureResources.STRUCTURES).contains(resources.idOf(name)); + if (alreadyImported && activeMode != StructureImporter.Mode.OVERWRITE) { + continue; + } + targets.add(key); + } + + int total = targets.size(); + if (total == 0) { + SenderText.send(sender, TextColor.GRAY, + "No code-generated structures left to capture (everything is already imported as a structure)."); + return new Report(0, 0, 0, 0); + } + + SenderText.send(sender, ToolText.builder() + .green("Capturing ").white(String.valueOf(total)) + .green(" code-generated structures (no NBT template) into a scratch world (skipping any wider/taller than " + + MAX_SPAN + " blocks)...").build()); + + Optional opened = platform.openCaptureArea(sender); + if (opened.isEmpty()) { + return new Report(total, 0, 0, total); + } + + int imported = 0; + int skipped = 0; + int failed = 0; + int cellIndex = 0; + + try (PlatformStructures.CaptureArea area = opened.get()) { + for (String key : targets) { + String name = StructureImporter.deriveName(key); + try { + GeneratedObject captured = captureOne(area, key, cellIndex++); + if (captured == null || captured.blocks().isEmpty()) { + skipped++; + SenderText.send(sender, TextColor.YELLOW, "[skip] " + key + + ": did not place a capturable structure here (too large, wrong dimension, or no valid placement in a flat world). Stays vanilla-generated."); + continue; + } + GeneratedObject object = DeclaredObjects.shrinkwrapped(captured); + BlockPosition size = DeclaredObjects.sizeOf(object); + StructureImporter.Result result = StructureImporter.writeSinglePieceStructure( + pack, name, key, object, "CENTER_HEIGHT", activeMode); + if (!result.success()) { + failed++; + SenderText.send(sender, TextColor.RED, "[fail] " + key + ": " + result.message()); + continue; + } + imported++; + SenderText.send(sender, TextColor.GRAY, "[capture] " + key + " -> objects/" + name + ".iob (" + + size.x() + "x" + size.y() + "x" + size.z() + ")"); + } catch (Throwable e) { + failed++; + SenderText.send(sender, TextColor.RED, "[fail] " + key + ": " + e.getMessage()); + pack.log().error("Could not capture structure " + key, e); + } + + int processed = imported + skipped + failed; + if (processed % PROGRESS_INTERVAL == 0) { + SenderText.send(sender, TextColor.GRAY, "..." + processed + "/" + total + " (" + imported + + " captured, " + skipped + " skipped, " + failed + " failed)"); + } + } + } + + SenderText.send(sender, ToolText.builder() + .green("Structure capture complete: ").white(String.valueOf(imported)) + .green(" captured, ").white(String.valueOf(skipped)) + .green(" skipped, ").white(String.valueOf(failed)) + .green(" failed (").white(String.valueOf(total)) + .green(" total).").build()); + return new Report(total, imported, skipped, failed); + } + + static List selectCaptureKeys(Iterable keys, Set allowedStructureKeys) { + TreeSet allowed = null; + if (allowedStructureKeys != null) { + allowed = normalizeKeys(allowedStructureKeys); + } + TreeSet selected = new TreeSet<>(); + for (String key : keys) { + if (key == null || key.isBlank()) { + continue; + } + String normalized = key.trim().toLowerCase(Locale.ROOT); + if (allowed == null || allowed.contains(normalized)) { + selected.add(normalized); + } + } + return new ArrayList<>(selected); + } + + private static TreeSet normalizeKeys(Iterable keys) { + TreeSet normalized = new TreeSet<>(); + for (String key : keys) { + if (key == null || key.isBlank()) { + continue; + } + normalized.add(key.trim().toLowerCase(Locale.ROOT)); + } + return normalized; + } + + private static GeneratedObject captureOne(PlatformStructures.CaptureArea area, String key, int cellIndex) { + long seed = key.hashCode() * 0x9E3779B97F4A7C15L + cellIndex * 0x100000001B3L + 0x5DEECE66DL; + Optional captured = area.capture(ResourceId.parse(key), seed, MAX_SPAN); + return captured.map(StructureCaptureImporter::objectOf).orElse(null); + } + + private static GeneratedObject objectOf(CapturedStructure captured) { + DeclaredObjects.Builder object = DeclaredObjects.builder(captured.size().x(), captured.size().y(), captured.size().z()); + for (TemplateBlock block : captured.blocks()) { + object.state(block.position().x(), block.position().y(), block.position().z(), block.state()); + block.blockEntity().ifPresent(entity -> + object.blockEntity(block.position().x(), block.position().y(), block.position().z(), entity)); + } + return object.build(); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/structure/StructureImporter.java b/module/src/main/java/art/arcane/iris/core/structure/StructureImporter.java similarity index 63% rename from core/src/main/java/art/arcane/iris/core/structure/StructureImporter.java rename to module/src/main/java/art/arcane/iris/core/structure/StructureImporter.java index ae81914fa..d31eb9b11 100644 --- a/core/src/main/java/art/arcane/iris/core/structure/StructureImporter.java +++ b/module/src/main/java/art/arcane/iris/core/structure/StructureImporter.java @@ -18,9 +18,9 @@ package art.arcane.iris.core.structure; -import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.structure.authoring.IrisStructureBundleFactory; import art.arcane.iris.core.structure.authoring.StructureBackend; +import art.arcane.iris.core.structure.authoring.StructureBundleNames; import art.arcane.iris.core.structure.authoring.StructureCapability; import art.arcane.iris.core.structure.authoring.StructureKey; import art.arcane.iris.core.structure.authoring.StructureLoss; @@ -31,26 +31,23 @@ import art.arcane.iris.core.structure.authoring.StructureWriteMode; import art.arcane.iris.core.structure.authoring.StructureWriteResult; import art.arcane.iris.engine.framework.structure.StructureGraphValidationException; import art.arcane.iris.engine.framework.structure.StructureResourceBundleGraphCompiler; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.LegacyTileData; -import art.arcane.iris.spi.IrisLogging; +import com.volmit.object.GeneratedObject; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.NamespacedKey; -import org.bukkit.block.BlockState; -import org.bukkit.block.data.BlockData; -import org.bukkit.structure.Palette; -import org.bukkit.structure.Structure; -import org.bukkit.util.BlockVector; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.StructureTemplate; +import com.volmit.tooling.TemplateBlock; +import com.volmit.tooling.ToolPack; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; @@ -58,9 +55,15 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; public final class StructureImporter { private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + private static final String STRUCTURE_VOID = "minecraft:structure_void"; + private static final String JIGSAW = "minecraft:jigsaw"; + private static final String STRUCTURE_BLOCK = "minecraft:structure_block"; + private static final Set AIR_BLOCKS = Set.of("minecraft:air", "minecraft:cave_air", "minecraft:void_air"); + private static final String PLATFORM_NAMESPACE = "minecraft"; public enum Mode { OVERWRITE, @@ -72,14 +75,16 @@ public final class StructureImporter { MANAGED_DATAPACK; StructureWriteResult write( - IrisData data, + ToolPack pack, StructureResourceBundle bundle, StructureWriteMode mode - ) { - StructureTransactionWriter writer = new StructureTransactionWriter(data.getDataFolder().toPath()); - return this == MANAGED_DATAPACK - ? writer.writeManagedDatapack(bundle, mode) - : writer.write(bundle, mode); + ) throws IOException { + return pack.edit(root -> { + StructureTransactionWriter writer = new StructureTransactionWriter(root); + return this == MANAGED_DATAPACK + ? writer.writeManagedDatapack(bundle, mode) + : writer.write(bundle, mode); + }); } } @@ -100,7 +105,7 @@ public final class StructureImporter { } record CapturedStructure( - IrisObject object, + GeneratedObject object, int blocks, int nonAirBlocks, int tiles, @@ -132,51 +137,53 @@ public final class StructureImporter { }; } - public static String deriveName(NamespacedKey key) { - return (key.getNamespace() + "_" + key.getKey()).replace('/', '_').replace(':', '_'); + public static String deriveName(ResourceId key) { + return (key.namespace() + "_" + key.path()).replace('/', '_').replace(':', '_'); } public static String deriveName(String key) { - return key.toLowerCase().replace('/', '_').replace(':', '_'); + return StructureBundleNames.structureName(key); } - public static Result importStructure(IrisData data, NamespacedKey key, String name, Mode mode) { - return importStructure(data, key, name, mode, false, Ownership.EDITABLE); + public static Result importStructure(ToolPack pack, PlatformStructures platform, ResourceId key, String name, Mode mode) { + return importStructure(pack, platform, key, name, mode, false, Ownership.EDITABLE); } - public static Result importStructure(IrisData data, NamespacedKey key, String name, Mode mode, boolean objectOnly) { - return importStructure(data, key, name, mode, objectOnly, Ownership.EDITABLE); + public static Result importStructure(ToolPack pack, PlatformStructures platform, ResourceId key, String name, Mode mode, + boolean objectOnly) { + return importStructure(pack, platform, key, name, mode, objectOnly, Ownership.EDITABLE); } static Result importStructure( - IrisData data, - NamespacedKey key, + ToolPack pack, + PlatformStructures platform, + ResourceId key, String name, Mode mode, boolean objectOnly, Ownership ownership ) { Mode activeMode = mode == null ? Mode.ADD_ONLY : mode; - Structure structure; + Optional loaded; try { - structure = Bukkit.getStructureManager().loadStructure(key); + loaded = platform.template(key); } catch (Throwable e) { - IrisLogging.reportError(e); + pack.log().error("Could not load structure template " + key, e); return new Result(false, "Failed to load structure " + key + ": " + e.getMessage(), 0, List.of(), true); } - if (structure == null || structure.getPalettes().isEmpty()) { + if (loaded.isEmpty()) { return new Result(false, "No loadable structure NBT for key " + key + " (jigsaw structures must be imported by their piece keys)", 0, List.of()); } CapturedStructure captured; try { - captured = captureStructure(structure); + captured = captureStructure(loaded.get()); } catch (Throwable e) { - IrisLogging.reportError(e); + pack.log().error("Could not capture structure template " + key, e); return new Result(false, "Failed to capture structure " + key + ": " + e.getMessage(), 0, List.of(), true); } - IrisObject object = captured.object(); + GeneratedObject object = captured.object(); int count = captured.blocks(); int tiles = captured.tiles(); int w = captured.width(); @@ -193,11 +200,11 @@ public final class StructureImporter { try { StructureKey sourceKey = StructureKey.parse(key.toString()); StructureKey bundleKey = new StructureKey("iris", name); - StructureSource.Kind sourceKind = key.getNamespace().equals("minecraft") + StructureSource.Kind sourceKind = key.namespace().equals(PLATFORM_NAMESPACE) ? StructureSource.Kind.VANILLA : StructureSource.Kind.DATAPACK; StructureSource source = StructureSource.of(sourceKind, sourceKey); IrisStructureBundleFactory.SinglePieceOptions options = new IrisStructureBundleFactory.SinglePieceOptions( - bundleKey, source, name, object, Math.max(w, d), "CENTER_HEIGHT", objectOnly, + bundleKey, source, name, object, pack.objects(), Math.max(w, d), "CENTER_HEIGHT", objectOnly, captured.capabilities(), losses); StructureResourceBundle bundle = IrisStructureBundleFactory.singlePiece(options); if (!objectOnly) { @@ -205,20 +212,17 @@ public final class StructureImporter { } StructureWriteMode writeMode = activeMode == Mode.ADD_ONLY ? StructureWriteMode.ADD_ONLY : StructureWriteMode.OVERWRITE; - StructureWriteResult writeResult = ownership.write(data, bundle, writeMode); - reportWriteFailure(writeResult); + StructureWriteResult writeResult = ownership.write(pack, bundle, writeMode); + reportWriteFailure(pack, writeResult); if (!writeResult.successful()) { return new Result(false, writeFailureMessage(name, activeMode, writeResult), count, losses, writeResult.failure().isPresent()); } - if (writeResult.committed()) { - data.invalidateStructureResources(); - } writeNote = writeResultNote(writeResult); } catch (StructureGraphValidationException e) { return new Result(false, "Failed writing import for '" + name + "': " + e.getMessage(), count, losses); } catch (Throwable e) { - IrisLogging.reportError(e); + pack.log().error("Could not write the import of " + key, e); return new Result(false, "Failed writing import for '" + name + "': " + e.getMessage(), count, losses, true); } @@ -228,64 +232,58 @@ public final class StructureImporter { + " tiles, " + w + "x" + h + "x" + d + lossSummary + ")" + writeNote, count, losses); } - static CapturedStructure captureStructure(Structure structure) { - Structure activeStructure = Objects.requireNonNull(structure); - if (activeStructure.getPalettes().isEmpty()) { + static CapturedStructure captureStructure(StructureTemplate template) { + StructureTemplate activeTemplate = Objects.requireNonNull(template); + if (activeTemplate.paletteCount() < 1) { throw new IllegalArgumentException("Structure has no palettes"); } - BlockVector size = activeStructure.getSize(); - int w = Math.max(1, size.getBlockX()); - int h = Math.max(1, size.getBlockY()); - int d = Math.max(1, size.getBlockZ()); - IrisObject object = new IrisObject(w, h, d); + BlockPosition size = activeTemplate.size(); + int w = Math.max(1, size.x()); + int h = Math.max(1, size.y()); + int d = Math.max(1, size.z()); + DeclaredObjects.Builder object = DeclaredObjects.builder(w, h, d); int count = 0; int nonAirBlocks = 0; int tiles = 0; int structureMarkers = 0; int invalidFinalStates = 0; - Palette palette = activeStructure.getPalettes().get(0); - for (BlockState block : palette.getBlocks()) { - Location loc = block.getLocation(); - int x = loc.getBlockX(); - int y = loc.getBlockY(); - int z = loc.getBlockZ(); + for (TemplateBlock block : activeTemplate.blocks()) { + int x = block.position().x(); + int y = block.position().y(); + int z = block.position().z(); if (x < 0 || y < 0 || z < 0 || x >= w || y >= h || z >= d) { continue; } - BlockData blockData = block.getBlockData(); - Material mat = blockData.getMaterial(); - if (mat == Material.STRUCTURE_VOID) { + String material = block.state().material().toString(); + if (material.equals(STRUCTURE_VOID)) { continue; } - boolean structural = mat == Material.JIGSAW || mat == Material.STRUCTURE_BLOCK; + boolean structural = material.equals(JIGSAW) || material.equals(STRUCTURE_BLOCK); if (structural) { structureMarkers++; } - if (mat == Material.JIGSAW) { + BlockState placed = block.state(); + if (material.equals(JIGSAW)) { FinalStateResult finalState = readJigsawFinalState(block); - BlockData resolved = finalState.blockData(); if (finalState.invalidSourceState()) { invalidFinalStates++; } - if (resolved == null || isAir(resolved)) { + if (finalState.state() == null || isAir(finalState.state())) { continue; } - blockData = resolved; - } else if (mat == Material.STRUCTURE_BLOCK) { + placed = finalState.state(); + } else if (material.equals(STRUCTURE_BLOCK)) { continue; } - object.setUnsigned(x, y, z, art.arcane.iris.platform.bukkit.BukkitBlockState.of(blockData)); + object.state(x, y, z, placed); count++; - if (!isAir(blockData)) { + if (!isAir(placed)) { nonAirBlocks++; } - if (!structural) { - LegacyTileData tile = captureTile(block); - if (tile != null) { - object.setUnsignedTile(x, y, z, tile); - tiles++; - } + if (!structural && block.blockEntity().isPresent()) { + object.blockEntity(x, y, z, block.blockEntity().get()); + tiles++; } } @@ -295,7 +293,7 @@ public final class StructureImporter { capabilities.add(StructureCapability.BLOCK_ENTITIES); } return new CapturedStructure( - object, + object.build(), count, nonAirBlocks, tiles, @@ -304,32 +302,31 @@ public final class StructureImporter { d, structureMarkers, capabilities, - importLosses(activeStructure, structureMarkers, invalidFinalStates) + importLosses(activeTemplate, structureMarkers, invalidFinalStates) ); } - private static boolean isAir(BlockData data) { - Material m = data.getMaterial(); - return m == Material.AIR || m == Material.CAVE_AIR || m == Material.VOID_AIR; + private static boolean isAir(BlockState state) { + return AIR_BLOCKS.contains(state.material().toString()); } private static List importLosses( - Structure structure, + StructureTemplate structure, int structureMarkers, int invalidFinalStates ) { List losses = new ArrayList<>(); - if (structure.getPaletteCount() > 1) { + if (structure.paletteCount() > 1) { losses.add(StructureLoss.warning( StructureCapability.BLOCKS, "palette_variants_not_imported", - "Only palette 0 was converted; " + (structure.getPaletteCount() - 1) + " additional palette(s) remain native-only.")); + "Only palette 0 was converted; " + (structure.paletteCount() - 1) + " additional palette(s) remain native-only.")); } - if (structure.getEntityCount() > 0) { + if (structure.entityCount() > 0) { losses.add(StructureLoss.warning( StructureCapability.ENTITIES, "entities_not_imported", - structure.getEntityCount() + " structure entit" + (structure.getEntityCount() == 1 ? "y was" : "ies were") + structure.entityCount() + " structure entit" + (structure.entityCount() == 1 ? "y was" : "ies were") + " not converted into the Iris snapshot.")); } if (structureMarkers > 0) { @@ -347,10 +344,8 @@ public final class StructureImporter { return losses; } - private static void reportWriteFailure(StructureWriteResult result) { - result.failure().ifPresent((Throwable failure) -> { - IrisLogging.reportError(failure); - }); + private static void reportWriteFailure(ToolPack pack, StructureWriteResult result) { + result.failure().ifPresent((Throwable failure) -> pack.log().error("Structure write failed", failure)); } private static String writeResultNote(StructureWriteResult result) { @@ -371,36 +366,23 @@ public final class StructureImporter { return "Failed writing import for '" + name + "' in " + mode.name().toLowerCase() + " mode: " + failure; } - private static FinalStateResult readJigsawFinalState(BlockState block) { - String finalState; - try { - Object nbt = block.getClass().getMethod("getSnapshotNBT").invoke(block); - if (nbt == null) { - return new FinalStateResult(null, false); - } - Object res = nbt.getClass().getMethod("getString", String.class).invoke(nbt, "final_state"); - finalState = null; - if (res instanceof String s) { - finalState = s; - } else if (res instanceof Optional o && o.isPresent()) { - finalState = String.valueOf(o.get()); - } - if (finalState == null || finalState.isBlank()) { - return new FinalStateResult(null, false); - } - } catch (Throwable e) { - IrisLogging.reportError(e); - if (VillageImporter.shouldPrintFullTrace(e)) { - } + private static FinalStateResult readJigsawFinalState(TemplateBlock block) { + if (block.jigsawFinalState().isEmpty() || block.jigsawFinalState().get().isBlank()) { return new FinalStateResult(null, false); } try { - return new FinalStateResult(Bukkit.createBlockData(normalizeJigsawFinalState(finalState)), false); + return new FinalStateResult(BlockState.parse(withNamespace(normalizeJigsawFinalState(block.jigsawFinalState().get()))), false); } catch (IllegalArgumentException e) { return new FinalStateResult(null, true); } } + private static String withNamespace(String blockState) { + int propertiesStart = blockState.indexOf('['); + String blockId = propertiesStart < 0 ? blockState : blockState.substring(0, propertiesStart); + return blockId.indexOf(':') < 0 ? PLATFORM_NAMESPACE + ":" + blockState : blockState; + } + static String normalizeJigsawFinalState(String finalState) { if (finalState == null) { return null; @@ -419,30 +401,33 @@ public final class StructureImporter { return finalState.replaceAll("([\\[,])half=(top|bottom)(?=[,\\]])", "$1type=$2"); } - private record FinalStateResult(BlockData blockData, boolean invalidSourceState) { + private record FinalStateResult(BlockState state, boolean invalidSourceState) { } - private static LegacyTileData captureTile(BlockState block) { + public static Result importTemplateGroup(ToolPack pack, String groupName, String vanillaSource, String prefix, Mode mode) { try { - return LegacyTileData.fromBukkit(block); + return pack.edit(root -> importTemplateGroup(pack, root, groupName, vanillaSource, prefix, mode)); } catch (Throwable e) { - IrisLogging.reportError(e); - return null; + pack.log().error("Could not build group structure " + groupName, e); + return new Result(false, "Failed writing group structure '" + groupName + "': " + e.getMessage(), 0, + List.of(), true); } } - public static Result importTemplateGroup(IrisData data, String groupName, String vanillaSource, String prefix, Mode mode) { + private static Result importTemplateGroup(ToolPack pack, Path root, String groupName, String vanillaSource, + String prefix, Mode mode) { Mode activeMode = mode == null ? Mode.ADD_ONLY : mode; - File objectsRoot = new File(data.getDataFolder(), "objects"); + String objectExtension = pack.objects().extension(); + File objectsRoot = new File(root.toFile(), "objects"); File prefixDir = new File(objectsRoot, prefix); if (!prefixDir.isDirectory()) { return new Result(false, "No imported templates under objects/" + prefix + " for " + groupName, 0, List.of()); } List iobs = new ArrayList<>(); - collectIob(prefixDir, iobs); + collectObjects(prefixDir, objectExtension, iobs); if (iobs.isEmpty()) { - return new Result(false, "No .iob templates under objects/" + prefix + " for " + groupName, 0, List.of()); + return new Result(false, "No " + objectExtension + " templates under objects/" + prefix + " for " + groupName, 0, List.of()); } iobs.sort(Comparator.comparing(File::getAbsolutePath)); @@ -451,71 +436,60 @@ public final class StructureImporter { int maxSpan = 1; for (File iob : iobs) { String rel = iob.getAbsolutePath().substring(rootPath.length()).replace(File.separatorChar, '/'); - if (rel.endsWith(".iob")) { - rel = rel.substring(0, rel.length() - ".iob".length()); + if (rel.endsWith(objectExtension)) { + rel = rel.substring(0, rel.length() - objectExtension.length()); } pieceNames.add(rel); try { maxSpan = Math.max(maxSpan, readObjectSpan(iob)); } catch (IOException e) { - IrisLogging.reportError(e); + pack.log().error("Could not read the imported object " + rel, e); return new Result(false, "Cannot read imported object '" + rel + "': " + e.getMessage(), 0, List.of(), true); } } - try { - for (String piece : pieceNames) { - File pieceFile = new File(data.getDataFolder(), "jigsaw-pieces/" + piece + ".json"); - if (!pieceFile.isFile()) { - return new Result(false, "Missing imported jigsaw piece '" + piece - + "'; import the source templates before building group '" + groupName + "'", 0, List.of()); - } + for (String piece : pieceNames) { + File pieceFile = new File(root.toFile(), "jigsaw-pieces/" + piece + ".json"); + if (!pieceFile.isFile()) { + return new Result(false, "Missing imported jigsaw piece '" + piece + + "'; import the source templates before building group '" + groupName + "'", 0, List.of()); } - - StructureKey sourceKey = StructureKey.parse(vanillaSource, "minecraft"); - StructureSource.Kind sourceKind = sourceKey.namespace().equals("minecraft") - ? StructureSource.Kind.VANILLA : StructureSource.Kind.DATAPACK; - StructureResourceBundle bundle = StructureResourceBundle.builder(new StructureKey("iris", groupName)) - .source(StructureSource.of(sourceKind, sourceKey)) - .backend(StructureBackend.IRIS_ASSEMBLY) - .capability(StructureCapability.BLOCKS) - .capability(StructureCapability.IRIS_PLACEMENT) - .textResource("jigsaw-pools/" + groupName + ".json", GSON.toJson(poolJsonMulti(pieceNames))) - .textResource("structures/" + groupName + ".json", - GSON.toJson(structureJson(groupName, vanillaSource, maxSpan))) - .build(); - StructureWriteMode writeMode = activeMode == Mode.ADD_ONLY - ? StructureWriteMode.ADD_ONLY : StructureWriteMode.OVERWRITE; - StructureWriteResult writeResult = new StructureTransactionWriter(data.getDataFolder().toPath()) - .write(bundle, writeMode); - reportWriteFailure(writeResult); - if (!writeResult.successful()) { - return new Result(false, writeFailureMessage(groupName, activeMode, writeResult), 0, List.of(), - writeResult.failure().isPresent()); - } - if (writeResult.committed()) { - data.invalidateStructureResources(); - } - return new Result(true, "Built structure '" + groupName + "' from " + pieceNames.size() - + " template variants" + writeResultNote(writeResult), pieceNames.size(), List.of()); - } catch (Throwable e) { - IrisLogging.reportError(e); - return new Result(false, "Failed writing group structure '" + groupName + "': " + e.getMessage(), 0, - List.of(), true); } + StructureKey sourceKey = StructureKey.parse(vanillaSource, "minecraft"); + StructureSource.Kind sourceKind = sourceKey.namespace().equals("minecraft") + ? StructureSource.Kind.VANILLA : StructureSource.Kind.DATAPACK; + StructureResourceBundle bundle = StructureResourceBundle.builder(new StructureKey("iris", groupName)) + .source(StructureSource.of(sourceKind, sourceKey)) + .backend(StructureBackend.IRIS_ASSEMBLY) + .capability(StructureCapability.BLOCKS) + .capability(StructureCapability.IRIS_PLACEMENT) + .textResource("jigsaw-pools/" + groupName + ".json", GSON.toJson(poolJsonMulti(pieceNames))) + .textResource("structures/" + groupName + ".json", + GSON.toJson(structureJson(groupName, vanillaSource, maxSpan))) + .build(); + StructureWriteMode writeMode = activeMode == Mode.ADD_ONLY + ? StructureWriteMode.ADD_ONLY : StructureWriteMode.OVERWRITE; + StructureWriteResult writeResult = new StructureTransactionWriter(root).write(bundle, writeMode); + reportWriteFailure(pack, writeResult); + if (!writeResult.successful()) { + return new Result(false, writeFailureMessage(groupName, activeMode, writeResult), 0, List.of(), + writeResult.failure().isPresent()); + } + return new Result(true, "Built structure '" + groupName + "' from " + pieceNames.size() + + " template variants" + writeResultNote(writeResult), pieceNames.size(), List.of()); } - private static void collectIob(File dir, List out) { + private static void collectObjects(File dir, String extension, List out) { File[] files = dir.listFiles(); if (files == null) { return; } for (File f : files) { if (f.isDirectory()) { - collectIob(f, out); - } else if (f.getName().endsWith(".iob")) { + collectObjects(f, extension, out); + } else if (f.getName().endsWith(extension)) { out.add(f); } } @@ -547,15 +521,16 @@ public final class StructureImporter { } public static Result writeSinglePieceStructure( - IrisData data, + ToolPack pack, String name, String vanillaSource, - IrisObject object, + GeneratedObject object, String placeMode, Mode mode ) { Mode activeMode = mode == null ? Mode.ADD_ONLY : mode; - int span = Math.max(object.getW(), object.getD()); + BlockPosition size = DeclaredObjects.sizeOf(object); + int span = Math.max(size.x(), size.z()); try { StructureKey sourceKey = StructureKey.parse(vanillaSource, "minecraft"); StructureSource.Kind sourceKind = sourceKey.namespace().equals("minecraft") @@ -565,6 +540,7 @@ public final class StructureImporter { StructureSource.of(sourceKind, sourceKey), name, object, + pack.objects(), span, placeMode, false, @@ -574,22 +550,18 @@ public final class StructureImporter { StructureResourceBundleGraphCompiler.requireViable(bundle); StructureWriteMode writeMode = activeMode == Mode.ADD_ONLY ? StructureWriteMode.ADD_ONLY : StructureWriteMode.OVERWRITE; - StructureWriteResult writeResult = new StructureTransactionWriter(data.getDataFolder().toPath()) - .write(bundle, writeMode); - reportWriteFailure(writeResult); + StructureWriteResult writeResult = Ownership.EDITABLE.write(pack, bundle, writeMode); + reportWriteFailure(pack, writeResult); if (!writeResult.successful()) { return new Result(false, writeFailureMessage(name, activeMode, writeResult), 0, List.of(), writeResult.failure().isPresent()); } - if (writeResult.committed()) { - data.invalidateStructureResources(); - } return new Result(true, "Captured '" + vanillaSource + "' as '" + name + "'" - + writeResultNote(writeResult), object.getBlocks().size(), List.of()); + + writeResultNote(writeResult), object.blocks().size(), List.of()); } catch (StructureGraphValidationException e) { return new Result(false, "Failed writing capture for '" + name + "': " + e.getMessage(), 0, List.of()); } catch (Throwable e) { - IrisLogging.reportError(e); + pack.log().error("Could not write the capture of " + vanillaSource, e); return new Result(false, "Failed writing capture for '" + name + "': " + e.getMessage(), 0, List.of(), true); } diff --git a/module/src/main/java/art/arcane/iris/core/structure/VillageImporter.java b/module/src/main/java/art/arcane/iris/core/structure/VillageImporter.java new file mode 100644 index 000000000..a1af1280b --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/structure/VillageImporter.java @@ -0,0 +1,755 @@ +/* + * 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.structure; + +import art.arcane.iris.core.structure.authoring.StructureBackend; +import art.arcane.iris.core.structure.authoring.StructureCapability; +import art.arcane.iris.core.structure.authoring.StructureKey; +import art.arcane.iris.core.structure.authoring.StructureLoss; +import art.arcane.iris.core.structure.authoring.StructureResourceBundle; +import art.arcane.iris.core.structure.authoring.StructureSource; +import art.arcane.iris.core.structure.authoring.StructureWriteMode; +import art.arcane.iris.core.structure.authoring.StructureWriteResult; +import art.arcane.iris.engine.framework.structure.StructureGraphValidationException; +import art.arcane.iris.engine.framework.structure.StructureResourceBundleGraphCompiler; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy; +import com.volmit.object.GeneratedObject; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.volmit.geometry.BlockFace; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.JigsawStructureInfo; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.StructureAccessException; +import com.volmit.tooling.StructureTemplate; +import com.volmit.tooling.TemplatePool; +import com.volmit.tooling.ToolPack; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Deque; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Random; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +public final class VillageImporter { + private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + private static final Set PRINTED_FAILURE_SIGNATURES = ConcurrentHashMap.newKeySet(); + private static final String EMPTY_POOL_ELEMENT_TYPE = "EmptyPoolElement"; + private static final String LIST_POOL_ELEMENT_TYPE = "ListPoolElement"; + private static final String FEATURE_POOL_ELEMENT_TYPE = "FeaturePoolElement"; + private static final String AIR_FINAL_STATE = "minecraft:air"; + + public record Result( + boolean success, + String message, + int pools, + int pieces, + List losses, + boolean retryableFailure + ) { + public Result(boolean success, String message, int pools, int pieces, List losses) { + this(success, message, pools, pieces, losses, false); + } + + public Result { + losses = List.copyOf(losses); + } + } + + private VillageImporter() { + } + + public static Result importVillage(ToolPack pack, PlatformStructures platform, ResourceId structureKey, String name, + StructureImporter.Mode mode) { + return importVillage(pack, platform, structureKey, name, mode, StructureImporter.Ownership.EDITABLE); + } + + static Result importVillage( + ToolPack pack, + PlatformStructures platform, + ResourceId structureKey, + String name, + StructureImporter.Mode mode, + StructureImporter.Ownership ownership + ) { + StructureImporter.Mode activeMode = mode == null ? StructureImporter.Mode.ADD_ONLY : mode; + List losses = new ArrayList<>(); + boolean retryableFailure = false; + String writeNote = ""; + + JigsawStructureInfo structure; + try { + Optional info = platform.jigsaw(structureKey); + if (info.isEmpty()) { + return failed(platform.structures().contains(structureKey) + ? "Structure " + structureKey + " is not a jigsaw structure; use 'import' for single-template structures" + : "No structure registered for key " + structureKey, losses); + } + structure = info.get(); + } catch (StructureAccessException e) { + reportFailure(pack, e); + return failed(e.getMessage(), losses, e.retryable()); + } catch (Throwable e) { + reportFailure(pack, e); + return failed("Failed to read jigsaw structure graph: " + e, losses, true); + } + int maxDepth = structure.maxDepth(); + int maxDistanceFromCenter = structure.maxDistance(); + Random random = new Random(structure.shuffleSeed()); + String startPoolKey = structure.startPool().toString(); + + Set visitedPools = new HashSet<>(); + Deque poolQueue = new ArrayDeque<>(); + poolQueue.add(startPoolKey); + + Map> emittedPools = new LinkedHashMap<>(); + Map> emittedPieces = new LinkedHashMap<>(); + Map emittedObjects = new LinkedHashMap<>(); + Map importedTemplates = new LinkedHashMap<>(); + Set capabilities = new HashSet<>(); + capabilities.add(StructureCapability.BLOCKS); + capabilities.add(StructureCapability.CONNECTORS); + capabilities.add(StructureCapability.IRIS_PLACEMENT); + List fatalErrors = new ArrayList<>(); + losses.add(StructureLoss.warning( + StructureCapability.NATIVE_PLACEMENT, + "native_placement_settings_not_imported", + "Native jigsaw placement settings other than the start pool, maximum depth, and maximum distance are not represented by the Iris assembly.")); + int pieceBlocks = 0; + int emittedPoolMembers = 0; + + while (!poolQueue.isEmpty()) { + String poolKey = poolQueue.poll(); + if (!visitedPools.add(poolKey)) { + continue; + } + Optional registered; + try { + registered = platform.pool(ResourceId.parse(poolKey)); + } catch (StructureAccessException e) { + reportFailure(pack, e); + retryableFailure = true; + fatalErrors.add(e.getMessage()); + continue; + } catch (Throwable e) { + reportFailure(pack, e); + retryableFailure = true; + fatalErrors.add("pool " + poolKey + ": " + e.getMessage()); + continue; + } + if (registered.isEmpty()) { + fatalErrors.add("pool " + poolKey + " is not registered"); + continue; + } + TemplatePool pool = registered.get(); + + String irisPoolName = poolName(name, poolKey); + List pieceEntries = new ArrayList<>(); + + if (pool.fallbackFailure().isPresent()) { + retryableFailure = true; + losses.add(StructureLoss.warning( + StructureCapability.CONNECTORS, + "fallback_pool_not_imported", + "The fallback for source pool " + poolKey + " could not be resolved: " + pool.fallbackFailure().get()) + .affecting("jigsaw-pools/" + irisPoolName + ".json")); + } + String fallbackKey = pool.fallback().map(ResourceId::toString).orElse(null); + if (fallbackKey != null && !fallbackKey.equals(poolKey)) { + poolQueue.add(fallbackKey); + } + + List templates = pool.members(); + for (TemplatePool.Member member : templates) { + if (member instanceof TemplatePool.Absent) { + continue; + } + if (member instanceof TemplatePool.Unreadable unreadable) { + retryableFailure = true; + losses.add(unreadableMemberLoss(unreadable, poolKey).affecting("jigsaw-pools/" + irisPoolName + ".json")); + continue; + } + TemplatePool.Element element = (TemplatePool.Element) member; + int weight = element.weight(); + if (element.omittedElements() > 0) { + losses.add(listElementFallbackLoss(element.listLevels(), element.omittedElements(), poolKey) + .affecting("jigsaw-pools/" + irisPoolName + ".json")); + } + if (element.template().isEmpty()) { + if (element.type().endsWith(EMPTY_POOL_ELEMENT_TYPE)) { + pieceEntries.add(emptyPoolEntry(weight)); + emittedPoolMembers++; + } else { + StructureCapability unsupportedCapability = unsupportedCapability(element.type()); + losses.add(StructureLoss.warning( + unsupportedCapability, + "unsupported_pool_element", + "Skipped unsupported " + element.type() + " in source pool " + poolKey + ".") + .affecting("jigsaw-pools/" + irisPoolName + ".json")); + } + continue; + } + ResourceId pieceNbtKey = element.template().get(); + String templateLocation = pieceNbtKey.toString(); + String irisPieceName = pieceName(name, templateLocation); + + ImportedTemplate importedTemplate = importedTemplates.get(irisPieceName); + if (importedTemplate == null) { + Optional sourceTemplate; + try { + sourceTemplate = platform.template(pieceNbtKey); + } catch (Throwable e) { + reportFailure(pack, e); + retryableFailure = true; + fatalErrors.add(templateLocation + ": failed to load structure template: " + failureDetail(e)); + continue; + } + if (sourceTemplate.isEmpty()) { + fatalErrors.add(templateLocation + ": no loadable structure template was registered"); + continue; + } + + StructureImporter.CapturedStructure captured; + try { + captured = StructureImporter.captureStructure(sourceTemplate.get()); + } catch (Throwable e) { + reportFailure(pack, e); + retryableFailure = true; + fatalErrors.add(templateLocation + ": failed to capture structure template: " + failureDetail(e)); + continue; + } + for (StructureLoss loss : captured.losses()) { + losses.add(loss.affecting("objects/" + irisPieceName + pack.objects().extension())); + } + + Connectors result = readConnectors(pack, element, random, name, irisPieceName); + retryableFailure |= result.retryableFailure(); + importedTemplate = new ImportedTemplate( + captured.object(), + captured.blocks(), + captured.nonAirBlocks(), + result.json(), + captured.capabilities()); + importedTemplates.put(irisPieceName, importedTemplate); + poolQueue.addAll(result.targetPoolKeys()); + losses.addAll(result.losses()); + } + + PoolMemberNormalization normalization = normalizePoolMember( + poolKey, + irisPoolName, + poolKey.equals(startPoolKey), + templates.size(), + fallbackKey, + templateLocation, + irisPieceName, + weight, + importedTemplate.nonAirBlocks(), + importedTemplate.connectors()); + losses.addAll(normalization.losses()); + if (!emittedPieces.containsKey(irisPieceName)) { + pieceBlocks += importedTemplate.emittedBlocks(normalization); + capabilities.addAll(importedTemplate.emittedCapabilities(normalization)); + if (normalization.disposition() == PoolMemberDisposition.PHYSICAL) { + emittedObjects.put(irisPieceName, importedTemplate.object()); + emittedPieces.put(irisPieceName, pieceJson( + irisPieceName, + importedTemplate.connectors(), + importedTemplate.nonAirBlocks())); + } + } + if (!normalization.poolEntry().isEmpty()) { + pieceEntries.add(normalization.poolEntry()); + emittedPoolMembers++; + } + } + + Map poolJson = new LinkedHashMap<>(); + poolJson.put("pieces", pieceEntries); + if (fallbackKey != null && !fallbackKey.equals(poolKey)) { + poolJson.put("fallback", poolName(name, fallbackKey)); + } + emittedPools.put(irisPoolName, poolJson); + } + + if (!fatalErrors.isEmpty()) { + return failed("Failed to capture the complete graph for " + structureKey + ": " + fatalErrors.getFirst() + + (fatalErrors.size() == 1 ? "" : " (" + (fatalErrors.size() - 1) + " more)"), losses, + retryableFailure); + } + if (emittedPoolMembers == 0) { + return failed("Imported 0 attachable or empty pool members for " + structureKey, losses); + } + for (StructureLoss loss : losses) { + if (loss.capability() == StructureCapability.CONNECTORS) { + capabilities.remove(StructureCapability.CONNECTORS); + break; + } + } + + try { + StructureKey sourceKey = StructureKey.parse(structureKey.toString()); + StructureSource.Kind sourceKind = structureKey.namespace().equals("minecraft") + ? StructureSource.Kind.VANILLA : StructureSource.Kind.DATAPACK; + StructureSource source = new StructureSource(sourceKind, sourceKey, structure.gameVersion(), ""); + Map objectResources = new LinkedHashMap<>(); + for (Map.Entry entry : emittedObjects.entrySet()) { + objectResources.put(entry.getKey(), pack.objects().encode(entry.getValue())); + } + Map rootStructure = structureJson( + structureKey.toString(), + poolName(name, startPoolKey), + maxDepth, + maxDistanceFromCenter); + StructureResourceBundle bundle = buildBundle( + new StructureKey("iris", name), + source, + objectResources, + emittedPieces, + emittedPools, + rootStructure, + capabilities, + losses); + StructureResourceBundleGraphCompiler.requireViable(bundle); + StructureWriteMode writeMode = activeMode == StructureImporter.Mode.OVERWRITE + ? StructureWriteMode.OVERWRITE : StructureWriteMode.ADD_ONLY; + StructureWriteResult writeResult = ownership.write(pack, bundle, writeMode); + reportWriteFailure(pack, writeResult); + if (!writeResult.successful()) { + return new Result(false, writeFailureMessage(name, writeResult), emittedPools.size(), + emittedPieces.size(), losses, writeResult.failure().isPresent()); + } + writeNote = writeResultNote(writeResult); + } catch (StructureGraphValidationException e) { + return new Result(false, "Failed writing jigsaw resources for '" + name + "': " + e.getMessage(), + emittedPools.size(), emittedPieces.size(), losses, retryableFailure); + } catch (Throwable e) { + reportFailure(pack, e); + return new Result(false, "Failed writing jigsaw resources for '" + name + "': " + e, + emittedPools.size(), emittedPieces.size(), losses, true); + } + + String msg = "Imported jigsaw structure " + structureKey + " as '" + name + "': " + emittedPieces.size() + " pieces, " + emittedPools.size() + " pools, " + pieceBlocks + " blocks"; + if (!losses.isEmpty()) { + msg += " (" + losses.size() + " fidelity warning(s) recorded)"; + } + return new Result(true, msg + writeNote, emittedPools.size(), emittedPieces.size(), losses); + } + + static StructureResourceBundle buildBundle( + StructureKey bundleKey, + StructureSource source, + Map objects, + Map> pieces, + Map> pools, + Map structure, + Set capabilities, + List losses + ) { + StructureResourceBundle.Builder bundle = StructureResourceBundle.builder(bundleKey) + .source(source) + .backend(StructureBackend.IRIS_ASSEMBLY) + .capabilities(capabilities) + .losses(losses); + for (Map.Entry entry : objects.entrySet()) { + bundle.resource("objects/" + entry.getKey() + ".iob", entry.getValue()); + } + for (Map.Entry> entry : pieces.entrySet()) { + bundle.textResource("jigsaw-pieces/" + entry.getKey() + ".json", GSON.toJson(entry.getValue())); + } + for (Map.Entry> entry : pools.entrySet()) { + bundle.textResource("jigsaw-pools/" + entry.getKey() + ".json", GSON.toJson(entry.getValue())); + } + bundle.textResource("structures/" + bundleKey.path() + ".json", GSON.toJson(structure)); + return bundle.build(); + } + + private record Connectors( + List> json, + Set targetPoolKeys, + List losses, + boolean retryableFailure + ) { + } + + record ImportedTemplate( + GeneratedObject object, + int blocks, + int nonAirBlocks, + List> connectors, + List capabilities + ) { + ImportedTemplate { + connectors = List.copyOf(connectors); + capabilities = List.copyOf(capabilities); + } + + int emittedBlocks(PoolMemberNormalization normalization) { + return normalization.disposition() == PoolMemberDisposition.PHYSICAL ? blocks : 0; + } + + List emittedCapabilities(PoolMemberNormalization normalization) { + return normalization.disposition() == PoolMemberDisposition.PHYSICAL ? capabilities : List.of(); + } + } + + enum PoolMemberDisposition { + PHYSICAL, + EMPTY, + OMITTED + } + + record PoolMemberNormalization( + PoolMemberDisposition disposition, + Map poolEntry, + List losses + ) { + PoolMemberNormalization { + poolEntry = Collections.unmodifiableMap(new LinkedHashMap<>(poolEntry)); + losses = List.copyOf(losses); + } + } + + private static StructureLoss unreadableMemberLoss(TemplatePool.Unreadable unreadable, String poolKey) { + if (unreadable.part() == TemplatePool.Part.ENTRY) { + return StructureLoss.warning( + StructureCapability.LIST_ELEMENTS, + "pool_entry_not_imported", + "A source entry in pool " + poolKey + " could not be read: " + unreadable.detail()); + } + return StructureLoss.warning( + StructureCapability.BLOCKS, + "template_location_not_imported", + "A source template location in pool " + poolKey + " could not be read: " + unreadable.detail()); + } + + private static Connectors readConnectors( + ToolPack pack, + TemplatePool.Element element, + Random random, + String baseName, + String pieceName + ) { + List> connectors = new ArrayList<>(); + Set targets = new HashSet<>(); + List losses = new ArrayList<>(); + boolean retryableFailure = false; + String affectedResource = "jigsaw-pieces/" + pieceName + ".json"; + try { + TemplatePool.Connectors read = element.connectors().read(random::nextLong); + if (read.availability() == TemplatePool.Availability.UNAVAILABLE) { + losses.add(StructureLoss.warning( + StructureCapability.CONNECTORS, + "connector_extraction_unavailable", + "The source pool element does not expose jigsaw connector extraction on this server version.") + .affecting(affectedResource)); + return new Connectors(connectors, targets, losses, false); + } + if (read.availability() == TemplatePool.Availability.NO_COLLECTION) { + losses.add(StructureLoss.warning( + StructureCapability.CONNECTORS, + "connector_extraction_returned_null", + "The source pool element returned no connector collection.") + .affecting(affectedResource)); + return new Connectors(connectors, targets, losses, false); + } + for (TemplatePool.Connector connector : read.connectors()) { + if (connector instanceof TemplatePool.UnreadableConnector unreadable) { + retryableFailure = true; + losses.add(StructureLoss.warning( + StructureCapability.CONNECTORS, + "connector_not_imported", + "A source jigsaw connector could not be converted: " + unreadable.detail()) + .affecting(affectedResource)); + continue; + } + TemplatePool.JigsawConnector jigsaw = (TemplatePool.JigsawConnector) connector; + connectors.add(connectorJson(jigsaw, baseName)); + jigsaw.pool().ifPresent(pool -> targets.add(pool.toString())); + } + } catch (Throwable e) { + reportFailure(pack, e); + retryableFailure = true; + losses.add(StructureLoss.warning( + StructureCapability.CONNECTORS, + "connector_extraction_failed", + "Source jigsaw connectors could not be extracted: " + failureDetail(e)) + .affecting(affectedResource)); + } + return new Connectors(connectors, targets, losses, retryableFailure); + } + + static Map connectorJson(TemplatePool.JigsawConnector jigsaw, String baseName) { + Map connector = new LinkedHashMap<>(); + Map position = new LinkedHashMap<>(); + position.put("x", jigsaw.position().x()); + position.put("y", jigsaw.position().y()); + position.put("z", jigsaw.position().z()); + connector.put("position", position); + connector.put("direction", irisDirection(jigsaw.front())); + connector.put("top", irisDirection(jigsaw.top())); + connector.put("pool", jigsaw.pool().map(pool -> poolName(baseName, pool.toString())).orElse("")); + connector.put("name", jigsaw.name()); + connector.put("targetName", jigsaw.target()); + connector.put("joint", jigsaw.aligned() ? "ALIGNED" : "ROLLABLE"); + connector.put("finalState", jigsaw.finalState() + .map(StructureImporter::normalizeJigsawFinalState) + .orElse(AIR_FINAL_STATE)); + connector.put("selectionPriority", jigsaw.selectionPriority()); + connector.put("placementPriority", jigsaw.placementPriority()); + return connector; + } + + private static String irisDirection(BlockFace front) { + return switch (front) { + case UP -> "UP_POSITIVE_Y"; + case DOWN -> "DOWN_NEGATIVE_Y"; + case SOUTH -> "SOUTH_POSITIVE_Z"; + case EAST -> "EAST_POSITIVE_X"; + case WEST -> "WEST_NEGATIVE_X"; + default -> "NORTH_NEGATIVE_Z"; + }; + } + + static StructureLoss listElementFallbackLoss(int listLevels, int omitted, String poolKey) { + String elementLabel = omitted == 1 ? "element" : "elements"; + String levelLabel = listLevels == 1 ? "list level" : "nested list levels"; + return StructureLoss.warning( + StructureCapability.LIST_ELEMENTS, + "list_pool_overlays_not_imported", + "Converted the first physical template from a ListPoolElement in source pool " + poolKey + + " and omitted " + omitted + " colocated " + elementLabel + + ", including their processors, across " + listLevels + " " + levelLabel + "." + ); + } + + static String poolName(String base, String poolKey) { + StructureKey key = StructureKey.parse(poolKey); + return base + "/pool/" + key.namespace() + "/" + key.path(); + } + + static String pieceName(String base, String templateLocation) { + StructureKey key = StructureKey.parse(templateLocation); + return base + "/piece/" + key.namespace() + "/" + key.path(); + } + + static Map pieceJson( + String pieceName, + List> connectors, + int nonAirBlocks + ) { + Map piece = new LinkedHashMap<>(); + piece.put("object", pieceName); + piece.put("connectors", connectors); + piece.put("rotatable", true); + if (nonAirBlocks == 0) { + piece.put("collidable", false); + } + return piece; + } + + static PoolMemberNormalization normalizePoolMember( + String sourcePoolKey, + String irisPoolName, + boolean startPoolMember, + int sourcePoolMembershipCount, + String sourceFallbackKey, + String templateLocation, + String irisPieceName, + int weight, + int nonAirBlocks, + List> connectors + ) { + if (!connectors.isEmpty() || startPoolMember) { + return new PoolMemberNormalization( + PoolMemberDisposition.PHYSICAL, + piecePoolEntry(irisPieceName, weight), + List.of()); + } + if (sourceFallbackKey != null + && !sourceFallbackKey.isBlank() + && !sourceFallbackKey.equals(sourcePoolKey)) { + return new PoolMemberNormalization( + PoolMemberDisposition.PHYSICAL, + piecePoolEntry(irisPieceName, weight), + List.of()); + } + String affectedResource = "jigsaw-pools/" + irisPoolName + ".json"; + if (nonAirBlocks == 0 && sourcePoolMembershipCount == 1) { + StructureLoss loss = StructureLoss.warning( + StructureCapability.IRIS_PLACEMENT, + "connectorless_all_air_member_normalized_empty", + "Source pool member " + templateLocation + " in " + sourcePoolKey + + " captured no non-air blocks and exposed no jigsaw connectors;" + + " its singleton membership was normalized to an explicit empty Iris pool entry" + + fallbackContext(sourcePoolKey, sourceFallbackKey) + ".") + .affecting(affectedResource); + return new PoolMemberNormalization( + PoolMemberDisposition.EMPTY, + emptyPoolEntry(weight), + List.of(loss)); + } + if (nonAirBlocks == 0) { + StructureLoss loss = StructureLoss.warning( + StructureCapability.IRIS_PLACEMENT, + "connectorless_all_air_mixed_member_omitted", + "Source pool member " + templateLocation + " in " + sourcePoolKey + + " captured no non-air blocks and exposed no jigsaw connectors;" + + " it was omitted from the mixed " + sourcePoolMembershipCount + "-member pool" + + fallbackContext(sourcePoolKey, sourceFallbackKey) + + ", changing source selection weights and RNG consumption.") + .affecting(affectedResource); + return new PoolMemberNormalization( + PoolMemberDisposition.OMITTED, + Map.of(), + List.of(loss)); + } + StructureLoss loss = StructureLoss.warning( + StructureCapability.BLOCKS, + "connectorless_non_air_member_omitted", + "Source pool member " + templateLocation + " in " + sourcePoolKey + + " captured " + nonAirBlocks + " non-air block(s) but exposed no jigsaw connectors;" + + " it was omitted because it cannot attach to the Iris assembly graph" + + fallbackContext(sourcePoolKey, sourceFallbackKey) + + ", changing source selection weights and RNG consumption while dropping those blocks.") + .affecting(affectedResource); + return new PoolMemberNormalization( + PoolMemberDisposition.OMITTED, + Map.of(), + List.of(loss)); + } + + private static String fallbackContext(String sourcePoolKey, String sourceFallbackKey) { + if (sourceFallbackKey == null || sourceFallbackKey.isBlank()) { + return " with no source fallback"; + } + if (sourceFallbackKey.equals(sourcePoolKey)) { + return " with its source self-fallback"; + } + return " before source fallback " + sourceFallbackKey; + } + + static Map emptyPoolEntry(int weight) { + Map entry = new LinkedHashMap<>(); + entry.put("empty", true); + entry.put("weight", weight); + return entry; + } + + static Map piecePoolEntry(String pieceName, int weight) { + Map entry = new LinkedHashMap<>(); + entry.put("piece", pieceName); + entry.put("weight", weight); + return entry; + } + + static Map structureJson( + String source, + String startPool, + int maxDepth, + int maxDistanceFromCenter + ) { + Map root = new LinkedHashMap<>(); + root.put("startPool", startPool); + root.put("maxDepth", Math.max(1, Math.min(30, maxDepth))); + int maxSizeChunks = Math.max(1, Math.min(32, (Math.max(1, maxDistanceFromCenter) + 15) / 16)); + root.put("maxSizeChunks", maxSizeChunks); + root.put("placeMode", "STRUCTURE_PIECE"); + root.put("branchFailurePolicy", IrisJigsawBranchFailurePolicy.TERMINATE_BRANCH.name()); + root.put("vanillaSource", source); + return root; + } + + private static StructureCapability unsupportedCapability(String elementType) { + if (elementType.endsWith(LIST_POOL_ELEMENT_TYPE)) { + return StructureCapability.LIST_ELEMENTS; + } + if (elementType.endsWith(FEATURE_POOL_ELEMENT_TYPE)) { + return StructureCapability.FEATURE_ELEMENTS; + } + return StructureCapability.BLOCKS; + } + + private static Result failed(String message, List losses) { + return new Result(false, message, 0, 0, losses); + } + + private static Result failed(String message, List losses, boolean retryableFailure) { + return new Result(false, message, 0, 0, losses, retryableFailure); + } + + private static void reportFailure(ToolPack pack, Throwable failure) { + pack.log().error("Jigsaw structure import failed", failure); + } + + /** + * True the first time a failure signature is seen. A bulk import repeats the same failure once + * per registered structure, so printing every trace buries the boot log in hundreds of copies + * of one problem; the per-structure "[fail] key: message" line still reports each occurrence. + */ + static boolean shouldPrintFullTrace(Throwable failure) { + if (failure == null) { + return false; + } + StackTraceElement[] trace = failure.getStackTrace(); + String signature = failure.getClass().getName() + '|' + failure.getMessage() + + '|' + (trace.length == 0 ? "" : trace[0].toString()); + return PRINTED_FAILURE_SIGNATURES.add(signature); + } + + static void resetFailureLogState() { + PRINTED_FAILURE_SIGNATURES.clear(); + } + + private static void reportWriteFailure(ToolPack pack, StructureWriteResult result) { + result.failure().ifPresent(failure -> reportFailure(pack, failure)); + } + + private static String writeResultNote(StructureWriteResult result) { + return result.status() == StructureWriteResult.Status.COMMITTED_CLEANUP_REQUIRED + ? " (committed; staging cleanup is required, see console)" : ""; + } + + private static String writeFailureMessage(String name, StructureWriteResult result) { + if (result.status() == StructureWriteResult.Status.ADD_ONLY_CONFLICT) { + return "Skipped (add-only): '" + name + "' already exists"; + } + if (!result.conflicts().isEmpty()) { + StructureWriteResult.Conflict conflict = result.conflicts().getFirst(); + return "Import conflict for '" + name + "': " + conflict.relativePath() + " is " + + conflict.reason().name().toLowerCase() + ". Existing authored files were preserved."; + } + String failure = result.failure().map(VillageImporter::failureDetail).orElse(result.status().name()); + return "Failed writing jigsaw import for '" + name + "': " + failure; + } + + private static String failureDetail(Throwable failure) { + String message = failure.getMessage(); + return message == null || message.isBlank() ? failure.getClass().getSimpleName() : message; + } +} diff --git a/core/src/main/java/art/arcane/iris/core/structure/authoring/IrisStructureBundleFactory.java b/module/src/main/java/art/arcane/iris/core/structure/authoring/IrisStructureBundleFactory.java similarity index 91% rename from core/src/main/java/art/arcane/iris/core/structure/authoring/IrisStructureBundleFactory.java rename to module/src/main/java/art/arcane/iris/core/structure/authoring/IrisStructureBundleFactory.java index 92a8cc709..46fa1b97a 100644 --- a/core/src/main/java/art/arcane/iris/core/structure/authoring/IrisStructureBundleFactory.java +++ b/module/src/main/java/art/arcane/iris/core/structure/authoring/IrisStructureBundleFactory.java @@ -1,10 +1,10 @@ package art.arcane.iris.core.structure.authoring; -import art.arcane.iris.engine.object.prefab.IrisObject; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.volmit.object.GeneratedObject; +import com.volmit.tooling.ObjectCodec; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; @@ -26,7 +26,8 @@ public final class IrisStructureBundleFactory { .backend(StructureBackend.SNAPSHOT) .capabilities(activeOptions.capabilities()) .losses(activeOptions.losses()) - .resource("objects/" + activeOptions.resourceKey() + ".iob", serialize(activeOptions.object())) + .resource("objects/" + activeOptions.resourceKey() + activeOptions.codec().extension(), + activeOptions.codec().encode(activeOptions.object())) .textResource("jigsaw-pieces/" + activeOptions.resourceKey() + ".json", GSON.toJson(pieceJson(activeOptions.resourceKey()))); if (!activeOptions.objectOnly()) { @@ -39,12 +40,6 @@ public final class IrisStructureBundleFactory { return bundle.build(); } - private static byte[] serialize(IrisObject object) throws IOException { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - object.write(output); - return output.toByteArray(); - } - private static Map pieceJson(String resourceKey) { Map piece = new LinkedHashMap<>(); piece.put("object", resourceKey); @@ -78,7 +73,8 @@ public final class IrisStructureBundleFactory { StructureKey bundleKey, StructureSource source, String resourceKey, - IrisObject object, + GeneratedObject object, + ObjectCodec codec, int maxSpan, String placeMode, boolean objectOnly, @@ -90,6 +86,7 @@ public final class IrisStructureBundleFactory { Objects.requireNonNull(source); Objects.requireNonNull(resourceKey); Objects.requireNonNull(object); + Objects.requireNonNull(codec); Objects.requireNonNull(placeMode); Objects.requireNonNull(capabilities); Objects.requireNonNull(losses); diff --git a/core/src/main/java/art/arcane/iris/core/structure/authoring/StructureBackend.java b/module/src/main/java/art/arcane/iris/core/structure/authoring/StructureBackend.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/authoring/StructureBackend.java rename to module/src/main/java/art/arcane/iris/core/structure/authoring/StructureBackend.java diff --git a/module/src/main/java/art/arcane/iris/core/structure/authoring/StructureBundleNames.java b/module/src/main/java/art/arcane/iris/core/structure/authoring/StructureBundleNames.java new file mode 100644 index 000000000..8485c78e3 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/structure/authoring/StructureBundleNames.java @@ -0,0 +1,63 @@ +/* + * 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.structure.authoring; + +import java.util.Locale; + +/** + * The names the structure importers give the bundles they write, which Iris's datapack ingest predicts to know which + * bundles an import will leave and which it must clean up. + */ +public final class StructureBundleNames { + private static final String DEFAULT_NAMESPACE = "minecraft"; + private static final String BUNDLE_PREFIX = "iris:"; + + private StructureBundleNames() { + } + + /** The bundle a registered structure imports as, such as {@code iris:minecraft_village_plains_town_centers}. */ + public static String ofStructure(String key) { + return BUNDLE_PREFIX + structureName(key); + } + + /** The bundle a structure template imports as. */ + public static String ofTemplate(String key) { + return BUNDLE_PREFIX + templateName(key); + } + + /** The name an imported structure is filed under. */ + public static String structureName(String key) { + return key.toLowerCase().replace('/', '_').replace(':', '_'); + } + + /** The name an imported structure template is filed under; templates of the platform's own namespace need no prefix. */ + public static String templateName(String key) { + int colon = key.indexOf(':'); + String namespace = colon >= 0 ? key.substring(0, colon) : DEFAULT_NAMESPACE; + String path = colon >= 0 ? key.substring(colon + 1) : key; + String safePath = path.toLowerCase().replaceAll("[^a-z0-9_/-]", "_"); + while (safePath.contains("//")) { + safePath = safePath.replace("//", "/"); + } + if (safePath.startsWith("/")) { + safePath = safePath.substring(1); + } + return DEFAULT_NAMESPACE.equals(namespace) ? safePath : namespace + "/" + safePath; + } +} diff --git a/core/src/main/java/art/arcane/iris/core/structure/authoring/StructureCapability.java b/module/src/main/java/art/arcane/iris/core/structure/authoring/StructureCapability.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/authoring/StructureCapability.java rename to module/src/main/java/art/arcane/iris/core/structure/authoring/StructureCapability.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/authoring/StructureFileOperations.java b/module/src/main/java/art/arcane/iris/core/structure/authoring/StructureFileOperations.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/authoring/StructureFileOperations.java rename to module/src/main/java/art/arcane/iris/core/structure/authoring/StructureFileOperations.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/authoring/StructureHash.java b/module/src/main/java/art/arcane/iris/core/structure/authoring/StructureHash.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/authoring/StructureHash.java rename to module/src/main/java/art/arcane/iris/core/structure/authoring/StructureHash.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/StructureIndexService.java b/module/src/main/java/art/arcane/iris/core/structure/authoring/StructureIndexService.java similarity index 64% rename from core/src/main/java/art/arcane/iris/core/structure/StructureIndexService.java rename to module/src/main/java/art/arcane/iris/core/structure/authoring/StructureIndexService.java index 22031d9e1..0577296d5 100644 --- a/core/src/main/java/art/arcane/iris/core/structure/StructureIndexService.java +++ b/module/src/main/java/art/arcane/iris/core/structure/authoring/StructureIndexService.java @@ -16,15 +16,17 @@ * along with this program. If not, see . */ -package art.arcane.iris.core.structure; +package art.arcane.iris.core.structure.authoring; -import art.arcane.iris.core.modules.ModuleServices; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.core.loader.IrisData; import com.google.gson.GsonBuilder; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.service.StructureLocator; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.ToolPack; import java.io.File; +import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; @@ -33,43 +35,43 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; +import java.util.TreeSet; public final class StructureIndexService { private static final String INDEX_PATH = ".iris/structure-index.json"; - private static final Set GENERATED = ConcurrentHashMap.newKeySet(); + private static final String PLATFORM_NAMESPACE_PREFIX = "minecraft:"; private StructureIndexService() { } - public static File writeOnce(IrisData data) { - if (data == null || !IrisPlatforms.isBound() || IrisPlatforms.get().structureHooks() == null) { - return null; - } - - File dataFolder = data.getDataFolder(); - String key = dataFolder == null ? null : dataFolder.getAbsolutePath(); - if (key == null || !GENERATED.add(key)) { - return null; - } - - try { - return write(data); - } catch (Throwable e) { - GENERATED.remove(key); - IrisLogging.reportError(e); - return null; - } + /** Writes the index of every structure the platform registers and the pack's modules know into the pack, and returns its file. */ + public static File write(ToolPack pack, PlatformStructures platform) throws IOException { + List structures = keysOf(platform.structures()); + List sets = keysOf(platform.structureSets()); + List iris = irisStructureKeys(pack); + return pack.edit(root -> writeIndex(pack, indexFile(root.toFile()), structures, sets, iris)); } - public static File write(IrisData data) { - List structures = IrisPlatforms.get().structureHooks().structureKeys(); - List sets = IrisPlatforms.get().structureHooks().structureSetKeys(); + private static List keysOf(List ids) { + return ids.stream().map(ResourceId::toString).toList(); + } + private static List irisStructureKeys(ToolPack pack) { + PackResources resources = pack.resources(); + Set keys = new TreeSet<>(); + for (StructureLocator provider : pack.services(StructureLocator.class)) { + for (ResourceId structure : provider.structures(resources)) { + keys.add(resources.idOf(structure.path()).equals(structure) ? structure.path() : structure.toString()); + } + } + return new ArrayList<>(keys); + } + + private static File writeIndex(ToolPack pack, File file, List structures, List sets, List iris) { List vanilla = new ArrayList<>(); List datapack = new ArrayList<>(); for (String k : structures) { - if (k.startsWith("minecraft:")) { + if (k.startsWith(PLATFORM_NAMESPACE_PREFIX)) { vanilla.add(k); } else { datapack.add(k); @@ -79,20 +81,17 @@ public final class StructureIndexService { List vanillaSets = new ArrayList<>(); List datapackSets = new ArrayList<>(); for (String k : sets) { - if (k.startsWith("minecraft:")) { + if (k.startsWith(PLATFORM_NAMESPACE_PREFIX)) { vanillaSets.add(k); } else { datapackSets.add(k); } } - List iris = new ArrayList<>(ModuleServices.structureKeys(data)); - Collections.sort(vanilla); Collections.sort(datapack); Collections.sort(vanillaSets); Collections.sort(datapackSets); - Collections.sort(iris); Map structuresNode = new LinkedHashMap<>(); structuresNode.put("vanilla", vanilla); @@ -115,13 +114,12 @@ public final class StructureIndexService { root.put("structureSets", setsNode); root.put("iris", iris); - File file = indexFile(data.getDataFolder()); try { file.getParentFile().mkdirs(); String json = new GsonBuilder().setPrettyPrinting().create().toJson(root); Files.writeString(file.toPath(), json, StandardCharsets.UTF_8); } catch (Throwable e) { - IrisLogging.reportError(e); + pack.log().error("Could not write the structure index " + file, e); } return file; } diff --git a/core/src/main/java/art/arcane/iris/core/structure/authoring/StructureKey.java b/module/src/main/java/art/arcane/iris/core/structure/authoring/StructureKey.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/authoring/StructureKey.java rename to module/src/main/java/art/arcane/iris/core/structure/authoring/StructureKey.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/authoring/StructureLoss.java b/module/src/main/java/art/arcane/iris/core/structure/authoring/StructureLoss.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/authoring/StructureLoss.java rename to module/src/main/java/art/arcane/iris/core/structure/authoring/StructureLoss.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/authoring/StructureOwnershipManifest.java b/module/src/main/java/art/arcane/iris/core/structure/authoring/StructureOwnershipManifest.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/authoring/StructureOwnershipManifest.java rename to module/src/main/java/art/arcane/iris/core/structure/authoring/StructureOwnershipManifest.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/authoring/StructureRecoveryResult.java b/module/src/main/java/art/arcane/iris/core/structure/authoring/StructureRecoveryResult.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/authoring/StructureRecoveryResult.java rename to module/src/main/java/art/arcane/iris/core/structure/authoring/StructureRecoveryResult.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/authoring/StructureResourceBundle.java b/module/src/main/java/art/arcane/iris/core/structure/authoring/StructureResourceBundle.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/authoring/StructureResourceBundle.java rename to module/src/main/java/art/arcane/iris/core/structure/authoring/StructureResourceBundle.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/authoring/StructureSource.java b/module/src/main/java/art/arcane/iris/core/structure/authoring/StructureSource.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/authoring/StructureSource.java rename to module/src/main/java/art/arcane/iris/core/structure/authoring/StructureSource.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/authoring/StructureTransactionJournal.java b/module/src/main/java/art/arcane/iris/core/structure/authoring/StructureTransactionJournal.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/authoring/StructureTransactionJournal.java rename to module/src/main/java/art/arcane/iris/core/structure/authoring/StructureTransactionJournal.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/authoring/StructureTransactionReadSet.java b/module/src/main/java/art/arcane/iris/core/structure/authoring/StructureTransactionReadSet.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/authoring/StructureTransactionReadSet.java rename to module/src/main/java/art/arcane/iris/core/structure/authoring/StructureTransactionReadSet.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/authoring/StructureTransactionWriter.java b/module/src/main/java/art/arcane/iris/core/structure/authoring/StructureTransactionWriter.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/authoring/StructureTransactionWriter.java rename to module/src/main/java/art/arcane/iris/core/structure/authoring/StructureTransactionWriter.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/authoring/StructureWriteMode.java b/module/src/main/java/art/arcane/iris/core/structure/authoring/StructureWriteMode.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/authoring/StructureWriteMode.java rename to module/src/main/java/art/arcane/iris/core/structure/authoring/StructureWriteMode.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/authoring/StructureWriteOptions.java b/module/src/main/java/art/arcane/iris/core/structure/authoring/StructureWriteOptions.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/authoring/StructureWriteOptions.java rename to module/src/main/java/art/arcane/iris/core/structure/authoring/StructureWriteOptions.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/authoring/StructureWriteResult.java b/module/src/main/java/art/arcane/iris/core/structure/authoring/StructureWriteResult.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/authoring/StructureWriteResult.java rename to module/src/main/java/art/arcane/iris/core/structure/authoring/StructureWriteResult.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionDiagnostic.java b/module/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionDiagnostic.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionDiagnostic.java rename to module/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionDiagnostic.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionDisposition.java b/module/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionDisposition.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionDisposition.java rename to module/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionDisposition.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionInputKind.java b/module/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionInputKind.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionInputKind.java rename to module/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionInputKind.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionLimits.java b/module/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionLimits.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionLimits.java rename to module/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionLimits.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionPlan.java b/module/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionPlan.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionPlan.java rename to module/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionPlan.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionReceipt.java b/module/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionReceipt.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionReceipt.java rename to module/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionReceipt.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionRequest.java b/module/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionRequest.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionRequest.java rename to module/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionRequest.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionResult.java b/module/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionResult.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionResult.java rename to module/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionResult.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionService.java b/module/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionService.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionService.java rename to module/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionService.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionStrategy.java b/module/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionStrategy.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionStrategy.java rename to module/src/main/java/art/arcane/iris/core/structure/conversion/IrisStructureAdoptionStrategy.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/export/AtomicDatapackPublisher.java b/module/src/main/java/art/arcane/iris/core/structure/export/AtomicDatapackPublisher.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/export/AtomicDatapackPublisher.java rename to module/src/main/java/art/arcane/iris/core/structure/export/AtomicDatapackPublisher.java diff --git a/module/src/main/java/art/arcane/iris/core/structure/export/ObjectContents.java b/module/src/main/java/art/arcane/iris/core/structure/export/ObjectContents.java new file mode 100644 index 000000000..202e98b9b --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/structure/export/ObjectContents.java @@ -0,0 +1,82 @@ +/* + * 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.structure.export; + +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import com.volmit.object.ObjectBlock; +import com.volmit.object.PlaceableObject; + +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +/** + * What an exporter reads of a pack object: its declared size and its blocks and block entities at positions counted from + * the object's corner, with the blocks only the platform can place or that need a block entity noted. + * + * @param customBlocks where the stored block is a custom-content block + * @param blocksNeedingEntity where the stored block is of a kind that carries a block entity + */ +public record ObjectContents(int width, int height, int depth, Map blocks, + Map blockEntities, Set customBlocks, + Set blocksNeedingEntity) { + public ObjectContents { + blocks = Map.copyOf(blocks); + blockEntities = Map.copyOf(blockEntities); + customBlocks = Set.copyOf(customBlocks); + blocksNeedingEntity = Set.copyOf(blocksNeedingEntity); + } + + /** An object with these blocks and nothing special about any of them. */ + public static ObjectContents plain(int width, int height, int depth, Map blocks, + Map blockEntities) { + return new ObjectContents(width, height, depth, blocks, blockEntities, Set.of(), Set.of()); + } + + /** {@code object} as its blocks lie in its declared box; {@code registry} says which are custom or hold block entities. */ + public static ObjectContents of(PlaceableObject object, BlockRegistry registry) { + BlockPosition center = object.center(); + Map blocks = new LinkedHashMap<>(); + Map entities = new LinkedHashMap<>(); + Set custom = new LinkedHashSet<>(); + Set needingEntity = new LinkedHashSet<>(); + for (ObjectBlock block : object.geometry().blocks()) { + BlockPosition position = block.position().add(center); + blocks.put(position, block.state()); + block.blockEntity().ifPresent(entity -> entities.put(position, entity)); + if (registry.hasTrait(block.state(), BlockTrait.CUSTOM)) { + custom.add(position); + } + if (registry.hasTrait(block.state(), BlockTrait.STORAGE)) { + needingEntity.add(position); + } + } + return new ObjectContents(object.width(), object.height(), object.depth(), blocks, entities, custom, needingEntity); + } + + /** The block the object's offsets count from, relative to its corner. */ + public BlockPosition center() { + return new BlockPosition(width / 2, height / 2, depth / 2); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/structure/export/VanillaBlockState.java b/module/src/main/java/art/arcane/iris/core/structure/export/VanillaBlockState.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/export/VanillaBlockState.java rename to module/src/main/java/art/arcane/iris/core/structure/export/VanillaBlockState.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawDatapackExporter.java b/module/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawDatapackExporter.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawDatapackExporter.java rename to module/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawDatapackExporter.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportCompiler.java b/module/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportCompiler.java similarity index 92% rename from core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportCompiler.java rename to module/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportCompiler.java index c88879fb6..c23a2fc99 100644 --- a/core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportCompiler.java +++ b/module/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportCompiler.java @@ -13,11 +13,10 @@ import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceEntry; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceRules; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.structure.IrisStructure; -import art.arcane.iris.spi.PlatformBlockState; import art.arcane.volmlib.util.math.IrisBlockVector; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; @@ -65,10 +64,11 @@ final class VanillaJigsawExportCompiler { return rejected(diagnostics); } - validateStructure(structure, request.settings(), diagnostics); + validateStructure(request.source().structureKey(), structure, request.settings(), diagnostics); StructureGraphCompilation graphCompilation; try { - graphCompilation = StructureGraphCompiler.compile(structure, request.source().resolver()); + graphCompilation = StructureGraphCompiler.compile( + request.source().structureKey(), structure, request.source().resolver()); } catch (RuntimeException exception) { addError(diagnostics, VanillaJigsawExportDiagnostic.Code.GRAPH_VALIDATION, @@ -78,7 +78,7 @@ final class VanillaJigsawExportCompiler { } addGraphDiagnostics(graphCompilation, diagnostics); CompiledStructureGraph graph = graphCompilation.getGraph(); - validateGraph(graph, diagnostics); + validateGraph(graph, request.source(), diagnostics); if (hasErrors(diagnostics)) { return rejected(diagnostics); } @@ -166,6 +166,7 @@ final class VanillaJigsawExportCompiler { } private void validateStructure( + String structureKey, IrisStructure structure, VanillaJigsawExportSettings settings, List diagnostics @@ -173,50 +174,50 @@ final class VanillaJigsawExportCompiler { if (structure.resolvedCompatibility() != IrisJigsawCompatibility.VANILLA_PORTABLE) { addError(diagnostics, VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_COMPATIBILITY, - structureKey(structure), + structureKey, "Strict export requires compatibility VANILLA_PORTABLE."); } if (!structure.stampsPiecesWhereAssembled()) { addError(diagnostics, VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_PLACE_MODE, - structureKey(structure), + structureKey, "Vanilla export requires placeMode STRUCTURE_PIECE; Iris terrain and stilt modes have no vanilla jigsaw equivalent."); } if (structure.getEdit() != null && !structure.getEdit().isEmpty()) { addError(diagnostics, VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_EDIT, - structureKey(structure), + structureKey, "Structure-wide Iris block edits cannot be represented losslessly by vanilla template pools."); } if (structure.getLoot() != null && !structure.getLoot().isEmpty()) { addError(diagnostics, VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_LOOT, - structureKey(structure), + structureKey, "Structure-wide Iris loot injection cannot be represented losslessly by this vanilla exporter."); } if (structure.getThemeSets() != null && !structure.getThemeSets().isEmpty()) { addError(diagnostics, VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_THEME_METADATA, - structureKey(structure), + structureKey, "Coherent Iris theme selection has no lossless vanilla jigsaw representation."); } if (structure.isRequireCaps()) { addError(diagnostics, VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_REQUIRED_CAPS, - structureKey(structure), + structureKey, "Vanilla jigsaws cannot enforce Iris requireCaps terminal-closure semantics."); } if (structure.getMaxDepth() < 1 || structure.getMaxDepth() > MAX_DEPTH) { addError(diagnostics, VanillaJigsawExportDiagnostic.Code.INVALID_MAX_DEPTH, - structureKey(structure), + structureKey, "Minecraft 26.2 jigsaw size must be within 0..20; Iris export requires 1..20."); } long horizontalDistance = (long) structure.getMaxSizeChunks() * 16L; if (horizontalDistance < 1L || horizontalDistance > MAX_HORIZONTAL_DISTANCE) { addError(diagnostics, VanillaJigsawExportDiagnostic.Code.INVALID_MAX_DISTANCE, - structureKey(structure), + structureKey, "Iris maxSizeChunks maps to " + horizontalDistance + " blocks, outside Minecraft 26.2's 1..128 horizontal limit."); } @@ -225,7 +226,7 @@ final class VanillaJigsawExportCompiler { if (horizontalDistance + terrainPadding > MAX_HORIZONTAL_DISTANCE) { addError(diagnostics, VanillaJigsawExportDiagnostic.Code.INVALID_MAX_DISTANCE, - structureKey(structure), + structureKey, "Horizontal distance plus vanilla terrain-adaptation padding must not exceed 128 blocks."); } } @@ -249,6 +250,7 @@ final class VanillaJigsawExportCompiler { private void validateGraph( CompiledStructureGraph graph, + VanillaJigsawExportSource source, List diagnostics ) { Map workcells = @@ -274,7 +276,7 @@ final class VanillaJigsawExportCompiler { pieceKey, "Iris piece keys must be valid lowercase resource paths for vanilla export."); } - validatePiece(graph, pieceKey, pieceEntry.getValue(), diagnostics); + validatePiece(graph, source, pieceKey, pieceEntry.getValue(), diagnostics); } } @@ -333,6 +335,7 @@ final class VanillaJigsawExportCompiler { private void validatePiece( CompiledStructureGraph graph, + VanillaJigsawExportSource source, String pieceKey, IrisJigsawPiece piece, List diagnostics @@ -366,7 +369,7 @@ final class VanillaJigsawExportCompiler { pieceKey, "Vanilla template pools cannot serialize Iris collidable=false assembly metadata."); } - IrisObject object = graph.getObjects().get(trim(piece.getObject())); + ObjectContents object = source.contents(trim(piece.getObject())); if (object == null) { return; } @@ -376,37 +379,41 @@ final class VanillaJigsawExportCompiler { private void validateObject( String pieceKey, - IrisObject object, + ObjectContents object, List diagnostics ) { - if (!object.getStates().isEmpty()) { + ObjectContents contents = object; + if (!contents.blockEntities().isEmpty()) { addError(diagnostics, VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_TILE_DATA, pieceKey, "The .iob contains tile payloads; exact registry-aware block-entity NBT export is not available in core."); } - for (Map.Entry entry : object.getBlocks()) { - PlatformBlockState state = entry.getValue(); - String resource = pieceKey + "@" + entry.getKey(); - IrisBlockVector position = entry.getKey(); - int x = position.getBlockX() + object.getCenter().getX(); - int y = position.getBlockY() + object.getCenter().getY(); - int z = position.getBlockZ() + object.getCenter().getZ(); - if (x < 0 || x >= object.getW() || y < 0 || y >= object.getH() || z < 0 || z >= object.getD()) { + for (Map.Entry entry : contents.blocks().entrySet()) { + BlockState state = entry.getValue(); + BlockPosition position = entry.getKey(); + String resource = pieceKey + "@" + new IrisBlockVector( + position.x() - object.center().x(), + position.y() - object.center().y(), + position.z() - object.center().z()); + int x = position.x(); + int y = position.y(); + int z = position.z(); + if (x < 0 || x >= object.width() || y < 0 || y >= object.height() || z < 0 || z >= object.depth()) { addError(diagnostics, VanillaJigsawExportDiagnostic.Code.INVALID_BLOCK_STATE, resource, "The .iob contains a block outside its declared dimensions."); continue; } - if (state.isCustom()) { + if (contents.customBlocks().contains(position)) { addError(diagnostics, VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_CUSTOM_BLOCK, resource, "Custom-content block '" + state.key() + "' is not available in unmodded vanilla."); continue; } - if (state.hasTileEntity()) { + if (contents.blocksNeedingEntity().contains(position)) { addError(diagnostics, VanillaJigsawExportDiagnostic.Code.UNSUPPORTED_BLOCK_ENTITY, resource, @@ -435,13 +442,14 @@ final class VanillaJigsawExportCompiler { CompiledStructureGraph graph, String pieceKey, IrisJigsawPiece piece, - IrisObject object, + ObjectContents object, List diagnostics ) { if (piece.getConnectors() == null) { return; } Set positions = new LinkedHashSet<>(); + Map storedBlocks = object.blocks(); for (int index = 0; index < piece.getConnectors().size(); index++) { IrisJigsawConnector connector = piece.getConnectors().get(index); if (connector == null) { @@ -471,18 +479,18 @@ final class VanillaJigsawExportCompiler { resource, exception.getMessage() == null ? "Connector orientation is incomplete." : exception.getMessage()); } - IrisPosition position = connector.getPosition(); + BlockPosition position = connector.getPosition(); if (position == null || !inside(position, object)) { continue; } - String positionKey = position.getX() + "," + position.getY() + "," + position.getZ(); + String positionKey = position.x() + "," + position.y() + "," + position.z(); if (!positions.add(positionKey)) { addError(diagnostics, VanillaJigsawExportDiagnostic.Code.DUPLICATE_CONNECTOR_POSITION, resource, "Multiple vanilla jigsaw block entities cannot occupy " + positionKey + "."); } - validateFinalState(object, connector, resource, diagnostics); + validateFinalState(storedBlocks, connector, resource, diagnostics); } } @@ -502,7 +510,7 @@ final class VanillaJigsawExportCompiler { } private void validateFinalState( - IrisObject object, + Map storedBlocks, IrisJigsawConnector connector, String resource, List diagnostics @@ -517,9 +525,8 @@ final class VanillaJigsawExportCompiler { exception.getMessage()); return; } - IrisPosition position = connector.getPosition(); - PlatformBlockState objectState = object.getBlocks().get( - object.getSigned(position.getX(), position.getY(), position.getZ())); + BlockPosition position = connector.getPosition(); + BlockState objectState = storedBlocks.get(position); String expectedSource = objectState == null ? "minecraft:structure_void" : objectState.key(); try { VanillaBlockState expected = VanillaBlockState.parse(expectedSource); @@ -562,7 +569,7 @@ final class VanillaJigsawExportCompiler { if (!pieceEnabled(workcells, pieceEntry.getValue())) { continue; } - IrisObject object = graph.getObjects().get(trim(pieceEntry.getValue().getObject())); + ObjectContents object = request.source().contents(trim(pieceEntry.getValue().getObject())); byte[] template = encoder.encode( object, pieceEntry.getValue(), @@ -752,10 +759,10 @@ final class VanillaJigsawExportCompiler { return request.namespace() + ":" + request.resourcePath() + "/piece/" + pieceKey; } - private boolean inside(IrisPosition position, IrisObject object) { - return position.getX() >= 0 && position.getX() < object.getW() - && position.getY() >= 0 && position.getY() < object.getH() - && position.getZ() >= 0 && position.getZ() < object.getD(); + private boolean inside(BlockPosition position, ObjectContents object) { + return position.x() >= 0 && position.x() < object.width() + && position.y() >= 0 && position.y() < object.height() + && position.z() >= 0 && position.z() < object.depth(); } private boolean hasErrors(List diagnostics) { @@ -784,11 +791,6 @@ final class VanillaJigsawExportCompiler { message)); } - private String structureKey(IrisStructure structure) { - String key = structure.getLoadKey(); - return key == null || key.isBlank() ? "" : key; - } - private String trim(String value) { return value == null ? "" : value.trim(); } diff --git a/core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportDiagnostic.java b/module/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportDiagnostic.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportDiagnostic.java rename to module/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportDiagnostic.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportFormat.java b/module/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportFormat.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportFormat.java rename to module/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportFormat.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportRequest.java b/module/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportRequest.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportRequest.java rename to module/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportRequest.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportResult.java b/module/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportResult.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportResult.java rename to module/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportResult.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportSettings.java b/module/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportSettings.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportSettings.java rename to module/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportSettings.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportSource.java b/module/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportSource.java similarity index 55% rename from core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportSource.java rename to module/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportSource.java index dffe0b0db..29c470f0c 100644 --- a/core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportSource.java +++ b/module/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportSource.java @@ -1,48 +1,57 @@ package art.arcane.iris.core.structure.export; -import art.arcane.iris.engine.framework.structure.StructureResources; -import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.structure.StructureGraphResolver; +import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.engine.object.structure.IrisStructure; +import com.volmit.resource.PackResources; import java.util.Objects; +import java.util.function.Function; public final class VanillaJigsawExportSource { private final String structureKey; - private final IrisData data; + private final PackResources pack; private final IrisStructure structure; private final StructureGraphResolver resolver; + private final Function objects; private VanillaJigsawExportSource( String structureKey, - IrisData data, + PackResources pack, IrisStructure structure, - StructureGraphResolver resolver + StructureGraphResolver resolver, + Function objects ) { this.structureKey = requireKey(structureKey); - this.data = data; + this.pack = pack; this.structure = structure; this.resolver = resolver; + this.objects = objects; } - public static VanillaJigsawExportSource forData(IrisData data, String structureKey) { + public static VanillaJigsawExportSource forPack(PackResources pack, String structureKey) { + Objects.requireNonNull(pack); return new VanillaJigsawExportSource( structureKey, - Objects.requireNonNull(data), + pack, null, - StructureGraphResolver.forData(data)); + StructureGraphResolver.forPack(pack), + key -> pack.objects().object(pack.idOf(key)).map(object -> ObjectContents.of(object, pack.blocks())).orElse(null)); } + /** A source of {@code structure} whose pieces' objects {@code objects} reads, for a structure that is not in a pack. */ public static VanillaJigsawExportSource forStructure( String structureKey, IrisStructure structure, - StructureGraphResolver resolver + StructureGraphResolver resolver, + Function objects ) { return new VanillaJigsawExportSource( structureKey, null, Objects.requireNonNull(structure), - Objects.requireNonNull(resolver)); + Objects.requireNonNull(resolver), + Objects.requireNonNull(objects)); } public String structureKey() { @@ -53,13 +62,18 @@ public final class VanillaJigsawExportSource { if (structure != null) { return structure; } - return StructureResources.structure(data.getPackResources(), structureKey); + return StructureResources.structure(pack, structureKey); } public StructureGraphResolver resolver() { return resolver; } + /** What the object the pack key {@code objectKey} names holds; null when there is none. */ + public ObjectContents contents(String objectKey) { + return objects.apply(objectKey); + } + private static String requireKey(String value) { String key = Objects.requireNonNull(value).trim(); if (key.isEmpty()) { diff --git a/core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportValidation.java b/module/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportValidation.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportValidation.java rename to module/src/main/java/art/arcane/iris/core/structure/export/VanillaJigsawExportValidation.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/export/VanillaResourceIdentifier.java b/module/src/main/java/art/arcane/iris/core/structure/export/VanillaResourceIdentifier.java similarity index 100% rename from core/src/main/java/art/arcane/iris/core/structure/export/VanillaResourceIdentifier.java rename to module/src/main/java/art/arcane/iris/core/structure/export/VanillaResourceIdentifier.java diff --git a/core/src/main/java/art/arcane/iris/core/structure/export/VanillaStructureTemplateEncoder.java b/module/src/main/java/art/arcane/iris/core/structure/export/VanillaStructureTemplateEncoder.java similarity index 79% rename from core/src/main/java/art/arcane/iris/core/structure/export/VanillaStructureTemplateEncoder.java rename to module/src/main/java/art/arcane/iris/core/structure/export/VanillaStructureTemplateEncoder.java index 130c15aaa..38c4cff57 100644 --- a/core/src/main/java/art/arcane/iris/core/structure/export/VanillaStructureTemplateEncoder.java +++ b/module/src/main/java/art/arcane/iris/core/structure/export/VanillaStructureTemplateEncoder.java @@ -1,13 +1,8 @@ package art.arcane.iris.core.structure.export; -import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.volmlib.util.math.IrisBlockVector; -import art.arcane.volmlib.util.math.Vector3i; import art.arcane.volmlib.util.nbt.io.NBTUtil; import art.arcane.volmlib.util.nbt.io.NamedTag; import art.arcane.volmlib.util.nbt.tag.CompoundTag; @@ -32,7 +27,7 @@ final class VanillaStructureTemplateEncoder { .thenComparingInt(entry -> entry.position().z()); byte[] encode( - IrisObject object, + ObjectContents object, IrisJigsawPiece piece, Function poolIdentifier ) throws IOException { @@ -52,7 +47,7 @@ final class VanillaStructureTemplateEncoder { } CompoundTag root = new CompoundTag(); - root.put("size", intList(object.getW(), object.getH(), object.getD())); + root.put("size", intList(object.width(), object.height(), object.depth())); root.put("palette", palette(paletteStates)); root.put("blocks", blocks(orderedBlocks, paletteIndexes)); root.put("entities", new ListTag<>(CompoundTag.class)); @@ -63,15 +58,10 @@ final class VanillaStructureTemplateEncoder { return output.toByteArray(); } - private Map objectBlocks(IrisObject object) { + private Map objectBlocks(ObjectContents object) { Map blocks = new LinkedHashMap<>(); - Vector3i center = object.getCenter(); - for (Map.Entry entry : object.getBlocks()) { - IrisBlockVector signed = entry.getKey(); - BlockPosition position = new BlockPosition( - signed.getBlockX() + center.getX(), - signed.getBlockY() + center.getY(), - signed.getBlockZ() + center.getZ()); + for (var entry : object.blocks().entrySet()) { + BlockPosition position = new BlockPosition(entry.getKey().x(), entry.getKey().y(), entry.getKey().z()); VanillaBlockState state = VanillaBlockState.parse(entry.getValue().key()); blocks.put(position, new BlockEntry(position, state, null)); } @@ -84,9 +74,9 @@ final class VanillaStructureTemplateEncoder { Function poolIdentifier ) { for (IrisJigsawConnector connector : piece.getConnectors()) { - IrisPosition sourcePosition = connector.getPosition(); + var sourcePosition = connector.getPosition(); BlockPosition position = new BlockPosition( - sourcePosition.getX(), sourcePosition.getY(), sourcePosition.getZ()); + sourcePosition.x(), sourcePosition.y(), sourcePosition.z()); String orientation = orientation(connector.getDirection(), connector.getTop()); VanillaBlockState state = VanillaBlockState.parse( "minecraft:jigsaw[orientation=" + orientation + "]"); @@ -108,23 +98,23 @@ final class VanillaStructureTemplateEncoder { return nbt; } - static String orientation(IrisDirection front, IrisDirection top) { - if (front == IrisDirection.UP_POSITIVE_Y || front == IrisDirection.DOWN_NEGATIVE_Y) { - if (top == IrisDirection.NORTH_NEGATIVE_Z - || top == IrisDirection.SOUTH_POSITIVE_Z - || top == IrisDirection.EAST_POSITIVE_X - || top == IrisDirection.WEST_NEGATIVE_X) { + static String orientation(JigsawDirection front, JigsawDirection top) { + if (front == JigsawDirection.UP_POSITIVE_Y || front == JigsawDirection.DOWN_NEGATIVE_Y) { + if (top == JigsawDirection.NORTH_NEGATIVE_Z + || top == JigsawDirection.SOUTH_POSITIVE_Z + || top == JigsawDirection.EAST_POSITIVE_X + || top == JigsawDirection.WEST_NEGATIVE_X) { return directionName(front) + "_" + directionName(top); } throw new IllegalArgumentException("Vertical jigsaw fronts require a horizontal top direction"); } - if (top != IrisDirection.UP_POSITIVE_Y) { + if (top != JigsawDirection.UP_POSITIVE_Y) { throw new IllegalArgumentException("Horizontal jigsaw fronts require an upward top direction"); } return directionName(front) + "_up"; } - private static String directionName(IrisDirection direction) { + private static String directionName(JigsawDirection direction) { return switch (direction) { case UP_POSITIVE_Y -> "up"; case DOWN_NEGATIVE_Y -> "down"; diff --git a/module/src/main/java/art/arcane/iris/core/structure/tooling/AdoptionCommands.java b/module/src/main/java/art/arcane/iris/core/structure/tooling/AdoptionCommands.java new file mode 100644 index 000000000..de9d28a4a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/structure/tooling/AdoptionCommands.java @@ -0,0 +1,341 @@ +/* + * 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.structure.tooling; + +import art.arcane.iris.core.service.JigsawStudioRequest; +import art.arcane.iris.core.structure.authoring.StructureKey; +import art.arcane.iris.core.structure.authoring.StructureOwnershipManifest; +import art.arcane.iris.core.structure.authoring.StructureTransactionWriter; +import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionDiagnostic; +import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionInputKind; +import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionPlan; +import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionRequest; +import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionResult; +import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionService; +import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionStrategy; +import com.volmit.tooling.Argument; +import com.volmit.tooling.Command; +import com.volmit.tooling.CommandContext; +import com.volmit.tooling.ToolPack; +import com.volmit.tooling.world.TextColor; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; + +/** {@code adopt}: inspects an Iris graph for safe Studio ownership adoption, then applies the inspected plan. */ +final class AdoptionCommands { + private static final Map ADOPTION_PLANS = new ConcurrentHashMap<>(); + private static final Map ADOPTION_SERVICES = new ConcurrentHashMap<>(); + private static final String AUTO = "auto"; + + private static final Argument SOURCE = Argument.word("source").describe("Existing Iris structure key"); + private static final Argument TARGET = Argument.word("target").orElse(AUTO) + .describe("New owned Iris key, or auto"); + private static final Argument STRATEGY = Argument.word("strategy").orElse(AUTO) + .describe("auto, in-place, or clone").suggesting(context -> List.of(AUTO, "in-place", "clone")); + private static final Argument PLAN = Argument.word("plan").describe("Plan UUID returned by adopt inspect"); + + private final JigsawStudios studios; + + AdoptionCommands(JigsawStudios studios) { + this.studios = studios; + } + + Command command() { + return Command.named("adopt").describe("Inspect and apply safe ownership adoption plans") + .child(Command.named("inspect").describe("Inspect an Iris graph for safe Studio ownership adoption") + .argument(SOURCE).argument(TARGET).argument(STRATEGY) + .runs(this::inspect)) + .child(Command.named("apply").describe("Apply one inspected adoption plan without overwriting") + .argument(PLAN).runs(this::apply)); + } + + private void inspect(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + String sourceKey; + Optional targetKey; + IrisStructureAdoptionStrategy adoptionStrategy; + Path root; + try { + sourceKey = parseAdoptionSource(context.get(SOURCE)); + targetKey = parseAdoptionTarget(context.get(TARGET)); + adoptionStrategy = parseAdoptionStrategy(context.get(STRATEGY)); + root = canonicalAdoptionRoot(JigsawStudioRequest.rootOf(context.pack())); + } catch (IOException | IllegalArgumentException exception) { + use.error("Could not inspect adoption source: " + exception.getMessage()); + return; + } + UUID ownerId = use.player().id(); + use.say(TextColor.GRAY, "Inspecting Jigsaw adoption source '" + sourceKey + "' asynchronously..."); + runAdoptionInspect(use, ownerId, root, sourceKey, targetKey, adoptionStrategy); + } + + private void apply(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + UUID parsedPlanId; + try { + parsedPlanId = UUID.fromString(context.get(PLAN)); + } catch (IllegalArgumentException exception) { + use.error("Adoption plan ID must be a UUID."); + return; + } + if (studioIsActiveOrOpening(use)) { + use.error("Close the active or opening Jigsaw Studio before applying an adoption plan."); + return; + } + pruneAdoptionPlanBindings(); + AdoptionPlanBinding binding = ADOPTION_PLANS.get(parsedPlanId); + UUID playerId = use.player().id(); + if (binding == null || !binding.ownerId().equals(playerId)) { + use.error("No active adoption plan '" + parsedPlanId + + "' belongs to your player session. Run adopt inspect again."); + return; + } + if (binding.service().plan(parsedPlanId).isEmpty()) { + ADOPTION_PLANS.remove(parsedPlanId, binding); + use.error("Adoption plan '" + parsedPlanId + + "' expired or was already consumed. Run adopt inspect again."); + return; + } + if (!ADOPTION_PLANS.remove(parsedPlanId, binding)) { + use.error("Adoption plan '" + parsedPlanId + "' is already being applied."); + return; + } + use.say(TextColor.GRAY, "Applying adoption plan '" + parsedPlanId + + "' asynchronously without overwrite..."); + runAdoptionApply(use, parsedPlanId, binding); + } + + private static void pruneAdoptionPlanBindings() { + for (Map.Entry entry : ADOPTION_PLANS.entrySet()) { + AdoptionPlanBinding binding = entry.getValue(); + if (binding.service().plan(entry.getKey()).isEmpty()) { + ADOPTION_PLANS.remove(entry.getKey(), binding); + } + } + } + + private static boolean studioIsActiveOrOpening(StudioUse use) { + return use.registry().activeOwnerId() != null + || use.registry().openingOwnerId() != null; + } + + private static void runAdoptionApply(StudioUse use, UUID planId, AdoptionPlanBinding binding) { + if (studioIsActiveOrOpening(use)) { + ADOPTION_PLANS.putIfAbsent(planId, binding); + use.error("Close the active or opening Jigsaw Studio before applying an adoption plan."); + return; + } + IrisStructureAdoptionResult result; + Throwable failure = null; + try { + result = binding.service().apply(binding.plan()); + } catch (Throwable throwable) { + result = null; + failure = throwable; + binding.pack().log().error("Failed to apply Jigsaw adoption plan '" + planId + "'.", throwable); + } + finishAdoptionApply(use, binding, result, failure); + } + + private static void runAdoptionInspect( + StudioUse use, + UUID ownerId, + Path root, + String sourceKey, + Optional targetKey, + IrisStructureAdoptionStrategy strategy + ) { + IrisStructureAdoptionService service = null; + IrisStructureAdoptionPlan plan = null; + Throwable failure = null; + try { + IrisStructureAdoptionInputKind inputKind = adoptionInputKind(root, sourceKey); + service = ADOPTION_SERVICES.computeIfAbsent(root, IrisStructureAdoptionService::new); + plan = service.inspect(new IrisStructureAdoptionRequest( + sourceKey, + targetKey, + strategy, + inputKind)); + } catch (Throwable throwable) { + failure = throwable; + use.pack().log().error("Failed to inspect Jigsaw adoption source '" + sourceKey + "'.", throwable); + } + finishAdoptionInspect(use, ownerId, service, plan, failure); + } + + private static void finishAdoptionInspect( + StudioUse use, + UUID ownerId, + IrisStructureAdoptionService service, + IrisStructureAdoptionPlan plan, + Throwable failure + ) { + if (failure != null || service == null || plan == null) { + use.error("Jigsaw adoption inspection failed: " + + (failure == null ? "no result" : failure.getMessage())); + return; + } + pruneAdoptionPlanBindings(); + if (service.plan(plan.planId()).isPresent()) { + ADOPTION_PLANS.put(plan.planId(), new AdoptionPlanBinding( + ownerId, use.pack(), service, plan)); + } + reportAdoptionPlan(use, plan); + } + + private static void finishAdoptionApply( + StudioUse use, + AdoptionPlanBinding binding, + IrisStructureAdoptionResult result, + Throwable failure + ) { + if (failure != null || result == null) { + use.error("Jigsaw adoption failed: " + (failure == null ? "no result" : failure.getMessage())); + return; + } + reportAdoptionResult(use, result); + if (!result.successful()) { + return; + } + StructureKey target = result.receipt().orElseThrow().targetStructure(); + JigsawStudioRequest.reload(binding.pack()); + StudioLifecycleCommands.openProject(use.onPack(binding.pack()), target.path()); + } + + private static void reportAdoptionPlan(StudioUse use, IrisStructureAdoptionPlan plan) { + use.say(plan.canApply() ? TextColor.GREEN : TextColor.RED, + "Adoption plan " + plan.planId() + " -> " + + plan.disposition() + " for " + plan.targetStructure().value() + "."); + use.say(TextColor.GRAY, "Resources=" + plan.resourceCount() + + ", bytes=" + plan.totalSourceBytes() + + ", errors=" + plan.errorCount() + + ", warnings=" + plan.warningCount() + "."); + for (IrisStructureAdoptionDiagnostic diagnostic : plan.diagnostics()) { + use.say(adoptionColor(diagnostic), diagnostic.summary()); + } + if (plan.canApply()) { + use.say(TextColor.AQUA, "Apply with /iris jigsaw adopt apply " + plan.planId()); + } + } + + private static void reportAdoptionResult(StudioUse use, IrisStructureAdoptionResult result) { + use.say(result.successful() ? TextColor.GREEN : TextColor.RED, + "Adoption plan " + result.planId() + ": " + result.status() + "."); + for (IrisStructureAdoptionDiagnostic diagnostic : result.diagnostics()) { + use.say(adoptionColor(diagnostic), diagnostic.summary()); + } + } + + private static TextColor adoptionColor(IrisStructureAdoptionDiagnostic diagnostic) { + return switch (diagnostic.severity()) { + case ERROR -> TextColor.RED; + case WARNING -> TextColor.YELLOW; + case INFO -> TextColor.GRAY; + }; + } + + static String parseAdoptionSource(String value) { + String normalized = Objects.requireNonNull(value, "Adoption source").trim() + .toLowerCase(Locale.ROOT); + StructureKey source = StructureKey.parse(normalized, "iris"); + if (!"iris".equals(source.namespace())) { + throw new IllegalArgumentException("Adoption sources must use the iris namespace."); + } + return source.path(); + } + + static Optional parseAdoptionTarget(String value) { + String normalized = Objects.requireNonNull(value, "Adoption target").trim() + .toLowerCase(Locale.ROOT); + if (normalized.isEmpty() || AUTO.equals(normalized)) { + return Optional.empty(); + } + StructureKey target = StructureKey.parse(normalized, "iris"); + if (!"iris".equals(target.namespace())) { + throw new IllegalArgumentException("Adoption targets must use the iris namespace."); + } + return Optional.of(target); + } + + static IrisStructureAdoptionStrategy parseAdoptionStrategy(String value) { + return switch (Objects.requireNonNull(value, "Adoption strategy").trim().toLowerCase(Locale.ROOT)) { + case AUTO -> IrisStructureAdoptionStrategy.AUTO; + case "in-place", "in_place", "inplace", "claim" -> IrisStructureAdoptionStrategy.IN_PLACE; + case "clone", "copy" -> IrisStructureAdoptionStrategy.CLONE; + default -> throw new IllegalArgumentException("Adoption strategy must be auto, in-place, or clone."); + }; + } + + static IrisStructureAdoptionInputKind adoptionInputKind(Path packRoot, String source) throws IOException { + Path root = canonicalAdoptionRoot(packRoot); + StructureKey sourceKey = new StructureKey("iris", parseAdoptionSource(source)); + Path manifestPath = new StructureTransactionWriter(root).ownershipManifestPath(sourceKey); + if (!Files.exists(manifestPath, LinkOption.NOFOLLOW_LINKS)) { + return IrisStructureAdoptionInputKind.UNOWNED_IRIS; + } + if (!Files.isRegularFile(manifestPath, LinkOption.NOFOLLOW_LINKS)) { + throw new IOException("Ownership manifest is not a regular file: " + manifestPath); + } + StructureOwnershipManifest manifest; + try { + manifest = StructureOwnershipManifest.fromJson(Files.readAllBytes(manifestPath)); + } catch (RuntimeException exception) { + throw new IOException("Invalid ownership manifest at " + manifestPath, exception); + } + if (!manifest.structure().equals(sourceKey)) { + throw new IOException("Ownership manifest at " + manifestPath + + " belongs to " + manifest.structure().value()); + } + return manifest.provenance().origin() == StructureOwnershipManifest.Origin.MANAGED_DATAPACK + ? IrisStructureAdoptionInputKind.MANAGED_DATAPACK + : IrisStructureAdoptionInputKind.UNOWNED_IRIS; + } + + private static Path canonicalAdoptionRoot(Path packRoot) throws IOException { + Path normalized = Objects.requireNonNull(packRoot, "Adoption pack root").toAbsolutePath().normalize(); + return Files.exists(normalized, LinkOption.NOFOLLOW_LINKS) ? normalized.toRealPath() : normalized; + } + + private record AdoptionPlanBinding( + UUID ownerId, + ToolPack pack, + IrisStructureAdoptionService service, + IrisStructureAdoptionPlan plan + ) { + } +} diff --git a/module/src/main/java/art/arcane/iris/core/structure/tooling/GraphEditCommands.java b/module/src/main/java/art/arcane/iris/core/structure/tooling/GraphEditCommands.java new file mode 100644 index 000000000..759301d50 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/structure/tooling/GraphEditCommands.java @@ -0,0 +1,792 @@ +/* + * 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.structure.tooling; + +import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarTopology; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBay; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioGraphEditor; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioPoolEditor; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioStructureEditor; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariant; +import art.arcane.iris.core.service.JigsawStudioService; +import art.arcane.iris.core.structure.tooling.GraphMutations.PieceWorkcellResolution; +import art.arcane.iris.core.structure.tooling.StudioSessions.ActiveContext; +import art.arcane.iris.engine.framework.structure.ObjectFrame; +import art.arcane.iris.engine.framework.structure.StructureResources; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; +import com.volmit.geometry.BlockPosition; +import com.volmit.tooling.Argument; +import com.volmit.tooling.Command; +import com.volmit.tooling.CommandContext; +import com.volmit.tooling.world.ToolWorld; + +import java.io.IOException; +import java.util.Optional; +import java.util.concurrent.ExecutionException; +import java.util.function.Supplier; + +import static art.arcane.iris.core.structure.tooling.GraphMutations.loadPersistedLayout; +import static art.arcane.iris.core.structure.tooling.GraphMutations.mappedMutationResult; +import static art.arcane.iris.core.structure.tooling.GraphMutations.runGraphMutation; +import static art.arcane.iris.core.structure.tooling.StudioUse.selectedBay; +import static art.arcane.iris.core.structure.tooling.StudioUse.selectedVariant; + +/** The commands that edit the open graph: connectors, pools, pieces, workcells, variants, the rules and the preview. */ +final class GraphEditCommands { + private static final String NONE = "none"; + private static final String JIGSAW_BLOCK = "minecraft:jigsaw"; + private static final int CONNECTOR_REACH_BLOCKS = 8; + private static final int VANILLA_PORTABLE_MAX_DEPTH = 20; + private static final int VANILLA_PORTABLE_MAX_SIZE_CHUNKS = 8; + private static final String NEXT = "next"; + + private static final Argument CHANNEL = Argument.word("channel").describe("Exact channel, or none to clear"); + private static final Argument NEW_POOL = Argument.word("poolKey").describe("New owned pool resource key"); + private static final Argument NEW_POOL_FALLBACK = Argument.word("fallbackPoolKey").orElse(NONE) + .describe("Owned fallback pool key, or none"); + private static final Argument OWNED_POOL = Argument.word("poolKey").describe("Owned pool resource key"); + private static final Argument NEW_PIECE = Argument.word("pieceKey").describe("New owned piece and object key"); + private static final Argument EXISTING_PIECE = Argument.word("pieceKey").describe("Existing jigsaw piece key"); + private static final Argument OPTIONAL_WEIGHT = weight().orElse(1L); + private static final Argument ROTATABLE = Argument.flag("rotatable") + .describe("Whether the selected piece may rotate"); + private static final Argument CAPACITY_WIDTH = size("width", "Capacity width"); + private static final Argument CAPACITY_HEIGHT = size("height", "Capacity height"); + private static final Argument CAPACITY_DEPTH = size("depth", "Capacity depth"); + private static final Argument LABEL = Argument.word("displayName") + .describe("Display label; quote labels containing spaces"); + private static final Argument VARIANT_POOL = Argument.word("poolKey").describe("Pool resource key"); + private static final Argument REQUIRED_WEIGHT = weight(); + private static final Argument VARIANT_WIDTH = size("width", "Variant width"); + private static final Argument VARIANT_HEIGHT = size("height", "Variant height"); + private static final Argument VARIANT_DEPTH = size("depth", "Variant depth"); + private static final Argument THEME_KEY = Argument.word("themeKey").orElse(NEXT) + .describe("Family key or next"); + private static final Argument MAX_DEPTH = Argument.integer("maxDepth", Integer.MIN_VALUE, Integer.MAX_VALUE) + .describe("Maximum expansion depth"); + private static final Argument MAX_SIZE_CHUNKS = Argument.integer("maxSizeChunks", Integer.MIN_VALUE, Integer.MAX_VALUE) + .describe("Maximum radius in chunks"); + private static final Argument FALLBACK_POOL = Argument.word("fallbackPoolKey") + .describe("Owned fallback pool key, or none"); + private static final Argument ASSEMBLY_SEED = Argument.integer("seed", Long.MIN_VALUE, Long.MAX_VALUE) + .orElse(StudioLifecycleCommands.DEFAULT_STUDIO_SEED).describe("Assembly seed"); + + private final JigsawStudios studios; + + GraphEditCommands(JigsawStudios studios) { + this.studios = studios; + } + + Command connector() { + return Command.named("connector").describe("Inspect and configure targeted jigsaw connectors") + .child(Command.named("channel").describe("Set the Iris-only channel on the targeted jigsaw marker") + .argument(CHANNEL).runs(this::connectorChannel)); + } + + Command pool() { + return Command.named("pool").describe("Manage owned jigsaw pools") + .child(Command.named("create").describe("Create an empty owned jigsaw pool") + .argument(NEW_POOL).argument(NEW_POOL_FALLBACK).runs(this::poolCreate)); + } + + Command piece() { + return Command.named("piece").describe("Manage contextual Studio pieces") + .child(Command.named("create").describe("Create an owned piece from the selected Studio topology") + .argument(OWNED_POOL).argument(NEW_PIECE).argument(OPTIONAL_WEIGHT).runs(this::pieceCreate)) + .child(Command.named("add").describe("Add an existing jigsaw piece to an owned pool transactionally") + .argument(OWNED_POOL).argument(EXISTING_PIECE).argument(OPTIONAL_WEIGHT).runs(this::pieceAdd)) + .child(Command.named("remove").describe("Remove the selected piece from an owned pool transactionally") + .argument(OWNED_POOL).runs(this::pieceRemove)) + .child(Command.named("rotatable").describe("Allow or forbid cardinal rotation of the selected piece") + .argument(ROTATABLE).runs(this::pieceRotatable)) + .child(Command.named("expand").describe("Resize the selected piece object exactly to workcell capacity") + .runs(this::pieceExpand)); + } + + Command workcell() { + return Command.named("workcell").describe("Manage the selected Studio workcell") + .child(Command.named("capacity").describe("Set capacity without resizing any variant object") + .argument(CAPACITY_WIDTH).argument(CAPACITY_HEIGHT).argument(CAPACITY_DEPTH) + .runs(this::workcellCapacity)) + .child(Command.named("label").describe("Set the selected workcell's author-facing label") + .argument(LABEL).runs(this::workcellLabel)) + .child(Command.named("label-reset").alias("reset-label") + .describe("Reset the selected workcell to its canonical solver label") + .runs(this::workcellLabelReset)); + } + + Command variant() { + return Command.named("variant").describe("Manage selected jigsaw variants") + .child(Command.named("weight").describe("Set the selected piece weight in a pool") + .argument(VARIANT_POOL).argument(REQUIRED_WEIGHT).runs(this::variantWeight)) + .child(Command.named("resize").describe("Resize only the active variant object within workcell capacity") + .argument(VARIANT_WIDTH).argument(VARIANT_HEIGHT).argument(VARIANT_DEPTH).runs(this::variantResize)) + .child(Command.named("label").describe("Set the active variant's author-facing label") + .argument(LABEL).runs(this::variantLabel)) + .child(Command.named("label-reset").alias("reset-label") + .describe("Reset the active variant to its resource-key label").runs(this::variantLabelReset)) + .child(Command.named("duplicate").describe("Duplicate the active variant in only this workcell") + .runs(this::variantDuplicate)) + .child(Command.named("duplicate-family").alias("family") + .describe("Duplicate every enabled workcell's active variant as one coherent family") + .argument(THEME_KEY).runs(this::variantDuplicateFamily)); + } + + Command rules() { + return Command.named("rules").alias("rule").describe("Manage structure-wide jigsaw rules") + .child(Command.named("limits").describe("Set maximum expansion depth and horizontal radius") + .argument(MAX_DEPTH).argument(MAX_SIZE_CHUNKS).runs(this::rulesLimits)) + .child(Command.named("fallback").describe("Set or clear one owned pool's direct fallback") + .argument(OWNED_POOL).argument(FALLBACK_POOL).runs(this::rulesFallback)); + } + + Command preview() { + return Command.named("preview").describe("Assemble a read-only jigsaw preview") + .child(Command.named("goto").alias("teleport").describe("Teleport to the live seed-1337 preview") + .runs(this::previewGoto)) + .child(Command.named("assemble").describe("Assemble a deterministic preview at your location") + .argument(ASSEMBLY_SEED).runs(this::previewAssemble)); + } + + private static Argument weight() { + return Argument.integer("weight", Integer.MIN_VALUE, Integer.MAX_VALUE).describe("Positive selection weight"); + } + + private static Argument size(String name, String description) { + return Argument.integer(name, Integer.MIN_VALUE, Integer.MAX_VALUE).describe(description); + } + + private static JigsawStudioCellDimensions dimensions(long width, long height, long depth) { + return new JigsawStudioCellDimensions((int) width, (int) height, (int) depth); + } + + private void connectorChannel(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + BlockPosition target = targetedJigsawMarker(use); + if (target == null) { + use.error("Look directly at a jigsaw marker within eight blocks."); + return; + } + var bay = active.session().layout().findAt(target.x(), target.y(), target.z()); + JigsawStudioVariant activeVariant = bay == null + ? null + : active.session().activeVariant(bay.stableId()).orElse(null); + if (activeVariant == null) { + use.error("The targeted marker must be inside a workcell with an active variant."); + return; + } + if (!activeVariant.owned()) { + use.error("The active variant is read-only. Adopt it into this project before editing it."); + return; + } + ObjectFrame object = GraphMutations.objectFrame(active, activeVariant.objectKey()); + if (object == null) { + use.error("The active variant object '" + activeVariant.objectKey() + "' is missing."); + return; + } + BlockPosition canonicalPosition = new BlockPosition( + target.x() - bay.bounds().originX(), + target.y() - bay.bounds().originY(), + target.z() - bay.bounds().originZ()); + BlockPosition position; + try { + position = activeVariant.canonicalToSourcePosition( + canonicalPosition, + new JigsawStudioCellDimensions(object.width(), object.height(), object.depth())); + } catch (IllegalArgumentException exception) { + use.error("Connector channel update failed: " + exception.getMessage()); + return; + } + String channel = context.get(CHANNEL); + String normalized = channel == null || channel.isBlank() || NONE.equalsIgnoreCase(channel) + ? NONE + : channel.trim(); + runGraphMutation(use, active, () -> { + JigsawStudioGraphEditor.updateConnectorChannel( + active.request().packRoot(), + active.request().structureKey(), + activeVariant.pieceKey(), + position, + channel); + return mappedMutationResult( + active, + "", + "", + "Persisted connector channel '" + normalized + "' on piece '" + + activeVariant.pieceKey() + "' at " + position.x() + "," + position.y() + + "," + position.z() + "."); + }); + } + + /** Where the player looks when it is a jigsaw marker within reach; null otherwise. */ + private static BlockPosition targetedJigsawMarker(StudioUse use) { + Optional target = use.readFromPlayer(() -> use.player().targetBlock(CONNECTOR_REACH_BLOCKS)); + Optional world = use.readFromPlayer(() -> use.player().world()); + if (target.isEmpty() || world.isEmpty()) { + return null; + } + try { + boolean marker = world.get().call(target.get(), () -> world.get().block(target.get())) + .get().material().toString().equals(JIGSAW_BLOCK); + return marker ? target.get() : null; + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + return null; + } catch (ExecutionException failure) { + return null; + } + } + + private void poolCreate(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + String poolKey = context.get(NEW_POOL); + String fallbackPoolKey = context.get(NEW_POOL_FALLBACK); + String fallback = NONE.equalsIgnoreCase(fallbackPoolKey) ? "" : fallbackPoolKey; + runGraphMutation(use, active, () -> { + JigsawStudioGraphEditor.createPool( + active.request().packRoot(), + active.request().structureKey(), + poolKey, + fallback); + return mappedMutationResult( + active, + "", + "", + "Created owned pool '" + poolKey + "' with fallback '" + + (fallback.isBlank() ? NONE : fallback) + "'."); + }); + } + + private void pieceCreate(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + String poolKey = context.get(OWNED_POOL); + String pieceKey = context.get(NEW_PIECE); + int weight = context.get(OPTIONAL_WEIGHT).intValue(); + JigsawPlanarTopology topology = null; + JigsawStudioBay targetWorkcell = active.session().layout().get(JigsawStudioLayout.SPATIAL_WORKCELL_ID); + if (active.session().layout().mode() == JigsawStudioMode.PLANAR_JIGSAW) { + BlockPosition location = use.readFromPlayer(use.player()::position); + JigsawStudioBay contextual = active.session().layout().findAt(location.x(), location.y(), location.z()); + if (contextual == null) { + contextual = selectedBay(active); + } else { + active.session().selectBay(contextual.stableId()); + } + if (contextual == null || contextual.topology().isEmpty()) { + use.error("Stand in or select a planar topology workcell before creating a variant."); + return; + } + topology = contextual.topology().get(); + targetWorkcell = contextual; + } + if (targetWorkcell == null) { + use.error("The selected Jigsaw Studio workcell is no longer available."); + return; + } + JigsawPlanarTopology selectedTopology = topology; + String activationWorkcellId = targetWorkcell.stableId(); + JigsawStudioCellDimensions dimensions = targetWorkcell.capacity(); + String topologyText = selectedTopology == null ? "blank spatial" : selectedTopology.name(); + runGraphMutation(use, active, () -> { + JigsawStudioGraphEditor.createPiece( + active.request().packRoot(), + use.pack().objects(), + active.request().structureKey(), + poolKey, + pieceKey, + weight, + dimensions, + selectedTopology); + return mappedMutationResult( + active, + activationWorkcellId, + pieceKey, + "Created owned " + topologyText + " piece '" + pieceKey + + "' and added it to pool '" + poolKey + "' atomically."); + }); + } + + private void pieceAdd(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + String poolKey = context.get(OWNED_POOL); + String pieceKey = context.get(EXISTING_PIECE); + int weight = context.get(OPTIONAL_WEIGHT).intValue(); + IrisJigsawPiece piece = StructureResources.piece(active.request().source().resources(), pieceKey); + if (piece == null) { + use.error("No jigsaw piece '" + pieceKey + "' exists in this pack."); + return; + } + if (piece.getObject() == null || piece.getObject().isBlank()) { + use.error("Jigsaw piece '" + pieceKey + "' does not declare an object."); + return; + } + ObjectFrame object = GraphMutations.objectFrame(active, piece.getObject()); + if (object == null) { + use.error("Jigsaw piece '" + pieceKey + "' has no loadable object."); + return; + } + PieceWorkcellResolution resolution; + try { + resolution = GraphMutations.resolvePieceWorkcell(active.session().layout(), piece, object); + } catch (IllegalArgumentException exception) { + use.error("Jigsaw piece '" + pieceKey + "' cannot be assigned to a Studio workcell: " + + exception.getMessage()); + return; + } + if (!resolution.fits()) { + BlockPosition required = resolution.requiredDimensions(); + JigsawStudioCellDimensions capacity = resolution.workcell().capacity(); + use.error("Jigsaw piece '" + pieceKey + "' requires " + required.x() + "x" + + required.y() + "x" + required.z() + " in " + resolution.workcell().displayName() + + ", but that workcell capacity is " + capacity.width() + "x" + capacity.height() + + "x" + capacity.depth() + "."); + return; + } + String objectKey = piece.getObject(); + runGraphMutation(use, active, () -> { + if (!JigsawStudioGraphEditor.ownsPiece( + active.request().packRoot(), + active.request().structureKey(), + pieceKey, + objectKey)) { + throw new IOException("Piece add accepts only piece/object resources already owned by this project; " + + "use piece create for a new owned piece"); + } + JigsawStudioPoolEditor.PoolUpdate update = JigsawStudioPoolEditor.addPiece( + active.request().packRoot(), + active.request().structureKey(), + poolKey, + pieceKey, + weight); + if (!update.changed()) { + throw new IOException("The owned pool is missing or already references '" + pieceKey + "'"); + } + JigsawStudioLayout layout = loadPersistedLayout(active); + String activationWorkcellId = GraphMutations.workcellIdForVariant(layout, pieceKey); + return new JigsawStudioService.CommandGraphMutationResult( + layout, + activationWorkcellId, + pieceKey, + "Added '" + pieceKey + "' to pool '" + poolKey + "' in one graph transaction."); + }); + } + + private void pieceRemove(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + String poolKey = context.get(OWNED_POOL); + JigsawStudioVariant selected = selectedVariant(active); + if (selected == null) { + use.error("Select a workcell with an active variant before removing its pool entry."); + return; + } + String pieceKey = selected.pieceKey(); + runGraphMutation(use, active, () -> { + JigsawStudioPoolEditor.PoolUpdate update = JigsawStudioPoolEditor.removePiece( + active.request().packRoot(), + active.request().structureKey(), + poolKey, + pieceKey); + if (!update.changed()) { + throw new IOException("The owned pool does not reference selected piece '" + pieceKey + "'"); + } + return mappedMutationResult( + active, + "", + "", + "Removed '" + pieceKey + "' from pool '" + poolKey + "' in one graph transaction."); + }); + } + + private void pieceRotatable(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + boolean rotatable = context.get(ROTATABLE); + JigsawStudioVariant selected = selectedVariant(active); + if (selected == null) { + use.error("Select a workcell with an active variant before changing rotation."); + return; + } + if (!rotatable + && active.request().compatibilityTarget() + == JigsawStudioCompatibilityTarget.VANILLA_PORTABLE) { + use.error("Vanilla-portable pieces must remain rotatable."); + return; + } + String pieceKey = selected.pieceKey(); + runGraphMutation(use, active, () -> { + JigsawStudioGraphEditor.updateRotatable( + active.request().packRoot(), + active.request().structureKey(), + pieceKey, + rotatable); + return mappedMutationResult( + active, + "", + "", + "Persisted piece '" + pieceKey + "' rotatable=" + rotatable + "."); + }); + } + + private void pieceExpand(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + JigsawStudioBay workcell = selectedBay(active); + if (workcell == null) { + use.error("Select a workcell before expanding its active variant."); + return; + } + use.onPlayer(() -> use.studio().expandVariantToCell(use.player(), workcell.stableId())); + } + + private void workcellCapacity(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + JigsawStudioBay selected = selectedBay(active); + if (selected == null) { + use.error("Select a workcell before changing its capacity."); + return; + } + JigsawStudioCellDimensions dimensions; + try { + dimensions = dimensions(context.get(CAPACITY_WIDTH), context.get(CAPACITY_HEIGHT), context.get(CAPACITY_DEPTH)); + } catch (IllegalArgumentException exception) { + use.error(exception.getMessage()); + return; + } + use.onPlayer(() -> use.studio().updateWorkcellDimensions(use.player(), selected.stableId(), dimensions)); + } + + private void workcellLabel(CommandContext context) { + renameWorkcell(context, "Select a workcell before renaming it.", LABEL); + } + + private void workcellLabelReset(CommandContext context) { + renameWorkcell(context, "Select a workcell before resetting its label.", null); + } + + /** Names the selected workcell by {@code label}, or resets its label when there is none. */ + private void renameWorkcell(CommandContext context, String noSelectionMessage, Argument label) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + JigsawStudioBay selected = selectedBay(active); + if (selected == null) { + use.error(noSelectionMessage); + return; + } + String displayName = label == null ? "" : context.get(label); + use.onPlayer(() -> use.studio().updateWorkcellDisplayName(use.player(), selected.stableId(), displayName)); + } + + private void variantWeight(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + String poolKey = context.get(VARIANT_POOL); + int weight = context.get(REQUIRED_WEIGHT).intValue(); + JigsawStudioVariant selected = selectedVariant(active); + if (selected == null) { + use.error("Select a workcell with an active variant before changing its weight."); + return; + } + String pieceKey = selected.pieceKey(); + runGraphMutation(use, active, () -> { + JigsawStudioPoolEditor.WeightUpdate update = JigsawStudioPoolEditor.updateWeight( + active.request().packRoot(), + active.request().structureKey(), + poolKey, + pieceKey, + weight); + if (!update.changed()) { + throw new IOException("Pool '" + poolKey + "' does not reference selected piece '" + + pieceKey + "'"); + } + return mappedMutationResult( + active, + "", + "", + "Updated " + update.changedEntries() + " pool entry weight atomically in " + + update.poolPath() + "."); + }); + } + + private void variantResize(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + JigsawStudioBay selectedWorkcell = selectedBay(active); + JigsawStudioVariant selectedVariant = selectedVariant(active); + if (selectedWorkcell == null || selectedVariant == null) { + use.error("Select a workcell with an active variant before resizing it."); + return; + } + JigsawStudioCellDimensions dimensions; + try { + dimensions = dimensions(context.get(VARIANT_WIDTH), context.get(VARIANT_HEIGHT), context.get(VARIANT_DEPTH)); + } catch (IllegalArgumentException exception) { + use.error(exception.getMessage()); + return; + } + use.onPlayer(() -> use.studio().resizeVariant( + use.player(), + selectedWorkcell.stableId(), + selectedVariant.pieceKey(), + dimensions)); + } + + private void variantLabel(CommandContext context) { + renameVariant(context, "Select a workcell with an active variant before renaming it.", LABEL); + } + + private void variantLabelReset(CommandContext context) { + renameVariant(context, "Select a workcell with an active variant before resetting its label.", null); + } + + /** Names the active variant by {@code label}, or resets its label when there is none. */ + private void renameVariant(CommandContext context, String noSelectionMessage, Argument label) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + JigsawStudioBay selectedWorkcell = selectedBay(active); + JigsawStudioVariant selectedVariant = selectedVariant(active); + if (selectedWorkcell == null || selectedVariant == null) { + use.error(noSelectionMessage); + return; + } + String displayName = label == null ? "" : context.get(label); + use.onPlayer(() -> use.studio().updateVariantDisplayName( + use.player(), + selectedWorkcell.stableId(), + selectedVariant.pieceKey(), + displayName)); + } + + private void variantDuplicate(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + JigsawStudioBay selected = selectedBay(active); + if (selected == null || selectedVariant(active) == null) { + use.error("Select a workcell with an active variant before duplicating it."); + return; + } + use.onPlayer(() -> use.studio().createVariant(use.player(), selected.stableId(), true)); + } + + private void variantDuplicateFamily(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + String themeKey = context.get(THEME_KEY); + String selectedTheme = themeKey; + if (NEXT.equalsIgnoreCase(themeKey)) { + try { + selectedTheme = GraphMutations.nextThemeKey(active); + } catch (IOException | ArithmeticException exception) { + use.error(exception.getMessage()); + return; + } + } + String familyKey = selectedTheme; + use.onPlayer(() -> use.studio().duplicateActiveFamily(use.player(), familyKey)); + } + + private void rulesLimits(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + int maxDepth = context.get(MAX_DEPTH).intValue(); + int maxSizeChunks = context.get(MAX_SIZE_CHUNKS).intValue(); + if (active.request().compatibilityTarget() == JigsawStudioCompatibilityTarget.VANILLA_PORTABLE + && (maxDepth > VANILLA_PORTABLE_MAX_DEPTH || maxSizeChunks > VANILLA_PORTABLE_MAX_SIZE_CHUNKS)) { + use.error("Vanilla-portable rules require maxDepth <= 20 and maxSizeChunks <= 8."); + return; + } + runGraphMutation(use, active, () -> { + JigsawStudioStructureEditor.updateLimits( + active.request().packRoot(), + active.request().structureKey(), + maxDepth, + maxSizeChunks); + return mappedMutationResult( + active, + "", + "", + "Persisted jigsaw limits: maxDepth=" + maxDepth + + ", maxSizeChunks=" + maxSizeChunks + "."); + }); + } + + private void rulesFallback(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + String poolKey = context.get(OWNED_POOL); + String fallbackPoolKey = context.get(FALLBACK_POOL); + String fallback = NONE.equalsIgnoreCase(fallbackPoolKey) ? "" : fallbackPoolKey; + runGraphMutation(use, active, () -> { + JigsawStudioPoolEditor.PoolUpdate update = JigsawStudioPoolEditor.updateFallback( + active.request().packRoot(), + active.request().structureKey(), + poolKey, + fallback); + if (!update.changed()) { + return mappedMutationResult(active, "", "", "Pool fallback is unchanged."); + } + return mappedMutationResult( + active, + "", + "", + "Persisted pool '" + poolKey + "' fallback as '" + + (fallback.isBlank() ? NONE : fallback) + "'."); + }); + } + + private void previewGoto(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + use.onPlayer(() -> use.studio().goToPreview(use.player())); + } + + private void previewAssemble(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + long seed = context.get(ASSEMBLY_SEED); + use.onPlayer(() -> use.studio().previewStudio(use.player(), seed)); + } +} diff --git a/module/src/main/java/art/arcane/iris/core/structure/tooling/GraphMutations.java b/module/src/main/java/art/arcane/iris/core/structure/tooling/GraphMutations.java new file mode 100644 index 000000000..f21e2d90a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/structure/tooling/GraphMutations.java @@ -0,0 +1,170 @@ +/* + * 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.structure.tooling; + +import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarArchetype; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBay; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioGraphMapper; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariant; +import art.arcane.iris.core.service.JigsawStudioRequest; +import art.arcane.iris.core.service.JigsawStudioService; +import art.arcane.iris.core.structure.tooling.StudioSessions.ActiveContext; +import art.arcane.iris.engine.framework.structure.ObjectFrame; +import art.arcane.iris.engine.framework.structure.PlanarJigsawWorkcellResolver; +import art.arcane.iris.engine.framework.structure.StructureResources; +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.IrisJigsawThemeSet; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.PackResources; + +import java.io.IOException; +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; + +/** What the commands that edit the open graph share: running a change as one graph transaction, and reading the graph back. */ +final class GraphMutations { + private static final String NUMBERED_FAMILY_PREFIX = "variant-"; + + private GraphMutations() { + } + + static void runGraphMutation( + StudioUse use, + ActiveContext context, + JigsawStudioService.CommandGraphMutation mutation + ) { + use.onPlayer(() -> use.studio().runCommandGraphMutation(use.player(), context.request().requestId(), mutation)); + } + + static JigsawStudioLayout loadPersistedLayout(ActiveContext context) throws IOException { + JigsawStudioRequest request = context.request(); + request.reloadSource(); + IrisStructure structure = StructureResources.structure(request.source().resources(), request.structureKey()); + if (structure == null) { + throw new IOException("The structure could not be reloaded after the graph transaction"); + } + return JigsawStudioGraphMapper.map(request.source(), request.packRoot(), request.structureKey(), structure); + } + + /** The declared size of the pack object {@code objectKey} names in the studio's pack; null when it has none. */ + static ObjectFrame objectFrame(ActiveContext context, String objectKey) { + PackResources resources = context.request().source().resources(); + return resources.objects().sizeOf(resources.idOf(objectKey)).map(ObjectFrame::of).orElse(null); + } + + static JigsawStudioService.CommandGraphMutationResult mappedMutationResult( + ActiveContext context, + String activateWorkcellId, + String activatePieceKey, + String message + ) throws IOException { + return new JigsawStudioService.CommandGraphMutationResult( + loadPersistedLayout(context), + activateWorkcellId, + activatePieceKey, + message); + } + + static String workcellIdForVariant(JigsawStudioLayout layout, String pieceKey) throws IOException { + JigsawStudioVariant variant = layout.variantCatalog().find(pieceKey).orElse(null); + if (variant == null) { + throw new IOException("Persisted variant '" + pieceKey + "' did not map to a Studio workcell"); + } + return variant.archetype() + .map(archetype -> archetype.stableId()) + .orElse(JigsawStudioLayout.SPATIAL_WORKCELL_ID); + } + + static PieceWorkcellResolution resolvePieceWorkcell( + JigsawStudioLayout layout, + IrisJigsawPiece piece, + ObjectFrame object + ) { + JigsawStudioLayout activeLayout = Objects.requireNonNull(layout, "Jigsaw Studio layout"); + IrisJigsawPiece activePiece = Objects.requireNonNull(piece, "Jigsaw piece"); + ObjectFrame activeObject = Objects.requireNonNull(object, "Jigsaw piece object"); + String workcellId; + BlockPosition requiredDimensions; + if (activeLayout.mode() == JigsawStudioMode.PLANAR_JIGSAW) { + IrisJigsawWorkcellArchetype modelArchetype = IrisJigsawWorkcellArchetype.fromPiece(activePiece); + workcellId = JigsawPlanarArchetype.fromModel(modelArchetype).stableId(); + requiredDimensions = PlanarJigsawWorkcellResolver.canonicalDimensions(activePiece, activeObject); + } else { + workcellId = JigsawStudioLayout.SPATIAL_WORKCELL_ID; + requiredDimensions = new BlockPosition( + activeObject.width(), + activeObject.height(), + activeObject.depth()); + } + JigsawStudioBay workcell = activeLayout.get(workcellId); + if (workcell == null) { + throw new IllegalArgumentException("Workcell '" + workcellId + "' is not configured"); + } + return new PieceWorkcellResolution(workcell, requiredDimensions); + } + + static String nextThemeKey(ActiveContext context) throws IOException { + IrisStructure structure = StructureResources.structure( + context.request().source().resources(), + context.request().structureKey()); + if (structure == null) { + throw new IOException("The active jigsaw structure could not be loaded"); + } + Set declared = new HashSet<>(); + if (structure.getThemeSets() != null) { + for (IrisJigsawThemeSet themeSet : structure.getThemeSets()) { + if (themeSet != null && themeSet.getKey() != null) { + declared.add(themeSet.getKey()); + } + } + } + int candidate = 1; + while (candidate > 0) { + String key = NUMBERED_FAMILY_PREFIX + candidate; + if (!declared.contains(key)) { + return key; + } + candidate = Math.incrementExact(candidate); + } + throw new IOException("Jigsaw Studio cannot allocate another numbered family key"); + } + + record PieceWorkcellResolution( + JigsawStudioBay workcell, + BlockPosition requiredDimensions + ) { + PieceWorkcellResolution { + workcell = Objects.requireNonNull(workcell, "Jigsaw Studio workcell"); + requiredDimensions = Objects.requireNonNull(requiredDimensions, "Jigsaw piece dimensions"); + } + + boolean fits() { + JigsawStudioCellDimensions capacity = workcell.capacity(); + return requiredDimensions.x() <= capacity.width() + && requiredDimensions.y() <= capacity.height() + && requiredDimensions.z() <= capacity.depth(); + } + } +} diff --git a/module/src/main/java/art/arcane/iris/core/structure/tooling/ImportCommands.java b/module/src/main/java/art/arcane/iris/core/structure/tooling/ImportCommands.java new file mode 100644 index 000000000..852c72dc3 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/structure/tooling/ImportCommands.java @@ -0,0 +1,90 @@ +/* + * 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.structure.tooling; + +import art.arcane.iris.core.structure.BulkStructureImporter; +import art.arcane.iris.core.structure.StructureCaptureImporter; +import art.arcane.iris.core.structure.StructureImporter; +import com.volmit.tooling.Command; +import com.volmit.tooling.CommandContext; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.Sender; +import com.volmit.tooling.ToolPack; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolText; + +import java.util.Optional; + +/** {@code import} and {@code capture}: turn the platform's structures into editable jigsaw structures of the pack. */ +final class ImportCommands { + private ImportCommands() { + } + + static Command importAll() { + return Command.named("import").alias("import-all", "reimport", "imp", "all") + .describe("Import EVERY structure - vanilla AND ingested datapacks - into this pack as editable Iris resources, always overwriting. Rebuilds jigsaw structures (villages, outposts, datapack jigsaws) as editable pool/piece graphs, imports every structure template NBT as an object, and assembles the multi-template structures (shipwrecks, ruined portals, ocean ruins, nether fossils). Run after ingesting a datapack and restarting. Regenerate chunks or use a fresh world for the imported copies to place.") + .runs(ImportCommands::runImportAll); + } + + static Command capture() { + return Command.named("capture").alias("cap") + .describe("Capture live registered structures into editable Iris objects by generating each one in a throwaway scratch world and reading back its blocks. This standalone command overwrites its owned outputs; structures wider/taller than the capture cap and anything that will not generate in a flat overworld are skipped. Each captured structure becomes a single-piece Iris structure you can place from a biome/region/dimension 'structures' list. /iris jigsaw import runs a restricted final capture pass only for non-jigsaw structures that have no loadable NBT template.") + .runs(ImportCommands::runCapture); + } + + private static void runImportAll(CommandContext context) { + Optional platform = PlatformStructuresAccess.require(context); + if (platform.isEmpty()) { + return; + } + ToolPack pack = context.pack(); + Sender sender = context.sender(); + SenderText.send(sender, ToolText.builder() + .green("Importing all vanilla & datapack structures into ") + .white(pack.resources().packId().namespace()) + .green(" (overwrite)...").build()); + BulkStructureImporter.Report jigsaws = BulkStructureImporter.importAllVanilla( + pack, platform.get(), StructureImporter.Mode.OVERWRITE, true, sender); + BulkStructureImporter.Report templates = BulkStructureImporter.importAllTemplates( + pack, platform.get(), StructureImporter.Mode.OVERWRITE, sender); + BulkStructureImporter.Report groups = BulkStructureImporter.importTemplateGroups( + pack, platform.get(), StructureImporter.Mode.OVERWRITE, sender); + StructureCaptureImporter.Report captured = StructureCaptureImporter.importStructures( + pack, platform.get(), StructureImporter.Mode.OVERWRITE, sender, jigsaws.captureCandidates()); + int imported = jigsaws.imported() + templates.imported() + groups.imported() + captured.imported(); + int failed = jigsaws.failed() + templates.failed() + groups.failed() + captured.failed(); + SenderText.send(sender, ToolText.builder() + .green("Import complete: ").white(String.valueOf(imported)) + .green(" structures/objects written, ").white(String.valueOf(failed)) + .green(" failed.").build()); + SenderText.send(sender, TextColor.GRAY, + "Reference them from a biome/region/dimension 'structures' list, or run /iris module structure list to refresh the index. Regenerate chunks for changes to take effect."); + } + + private static void runCapture(CommandContext context) { + Optional platform = PlatformStructuresAccess.require(context); + if (platform.isEmpty()) { + return; + } + StructureCaptureImporter.Report report = StructureCaptureImporter.importAllStructures( + context.pack(), platform.get(), StructureImporter.Mode.OVERWRITE, context.sender()); + SenderText.send(context.sender(), TextColor.GRAY, "Captured " + report.imported() + + " structures. Place them from a 'structures' list and regenerate chunks. Delete a structures/*.json to re-capture it."); + } +} diff --git a/module/src/main/java/art/arcane/iris/core/structure/tooling/JigsawCommands.java b/module/src/main/java/art/arcane/iris/core/structure/tooling/JigsawCommands.java new file mode 100644 index 000000000..5027c9b03 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/structure/tooling/JigsawCommands.java @@ -0,0 +1,62 @@ +/* + * 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.structure.tooling; + +import com.volmit.tooling.Command; + +import java.util.Optional; +import java.util.function.Supplier; + +/** + * The {@code jigsaw} command tree: the Jigsaw Studio (create, open, close, edit and export a jigsaw structure in a tool + * world), and the {@code import} and {@code capture} that turn the platform's structures into jigsaw structures. Platforms + * mount it below their module branch, so the studio commands run as {@code /iris module jigsaw ...}. + */ +public final class JigsawCommands { + private static final String ROOT_NAME = "jigsaw"; + + private JigsawCommands() { + } + + /** + * The tree. + * + * @param studios the pack's Jigsaw Studio, which the first command that needs it creates + */ + public static Command root(JigsawStudios studios) { + StudioLifecycleCommands lifecycle = new StudioLifecycleCommands(studios); + GraphEditCommands graph = new GraphEditCommands(studios); + Command root = Command.named(ROOT_NAME).alias("jig", "jgs").describe("Iris Jigsaw Studio tools"); + for (Command command : lifecycle.commands()) { + root = root.child(command); + } + return root + .child(new JigsawExportCommand(studios).command()) + .child(new AdoptionCommands(studios).command()) + .child(graph.connector()) + .child(graph.pool()) + .child(graph.piece()) + .child(graph.workcell()) + .child(graph.variant()) + .child(graph.rules()) + .child(graph.preview()) + .child(ImportCommands.importAll()) + .child(ImportCommands.capture()); + } +} diff --git a/module/src/main/java/art/arcane/iris/core/structure/tooling/JigsawExportCommand.java b/module/src/main/java/art/arcane/iris/core/structure/tooling/JigsawExportCommand.java new file mode 100644 index 000000000..5cee2d8ca --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/structure/tooling/JigsawExportCommand.java @@ -0,0 +1,279 @@ +/* + * 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.structure.tooling; + +import art.arcane.iris.core.service.JigsawStudioService; +import art.arcane.iris.core.structure.export.VanillaJigsawDatapackExporter; +import art.arcane.iris.core.structure.export.VanillaJigsawExportDiagnostic; +import art.arcane.iris.core.structure.export.VanillaJigsawExportFormat; +import art.arcane.iris.core.structure.export.VanillaJigsawExportRequest; +import art.arcane.iris.core.structure.export.VanillaJigsawExportResult; +import art.arcane.iris.core.structure.export.VanillaJigsawExportSource; +import art.arcane.iris.core.structure.tooling.StudioSessions.ActiveContext; +import com.volmit.tooling.Argument; +import com.volmit.tooling.Command; +import com.volmit.tooling.CommandContext; +import com.volmit.tooling.Sender; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolPlayer; + +import java.nio.file.Path; +import java.util.Locale; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; +import java.util.regex.Pattern; + +/** {@code export}: writes the clean graph of the open studio as a vanilla datapack below the pack's output folder. */ +final class JigsawExportCommand { + private static final Pattern EXPORT_OUTPUT_NAME = Pattern.compile("[a-zA-Z0-9_-][a-zA-Z0-9._-]{0,127}"); + private static final Set EXPORTING_PLAYERS = ConcurrentHashMap.newKeySet(); + private static final Set EXPORT_DESTINATIONS = ConcurrentHashMap.newKeySet(); + + private static final Argument NAMESPACE = Argument.word("namespace").orElse("iris") + .describe("Datapack namespace"); + private static final Argument OUTPUT = Argument.word("output").orElse("jigsaw-export") + .describe("Output name under the Studio exports folder"); + private static final Argument FORMAT = Argument.word("format").orElse("zip") + .describe("directory or zip").suggesting(context -> java.util.List.of("directory", "zip")); + private static final Argument REPLACE = Argument.word("replace").orElse("false") + .describe("Replace an existing export"); + + private final JigsawStudios studios; + + JigsawExportCommand(JigsawStudios studios) { + this.studios = studios; + } + + Command command() { + return Command.named("export").describe("Export the clean active graph as a vanilla datapack") + .argument(NAMESPACE).argument(OUTPUT).argument(FORMAT).argument(REPLACE) + .runs(this::export); + } + + private void export(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + if (active.session().isDirty()) { + use.error("Wait for the pending autosave or discard the edits before exporting the on-disk graph."); + return; + } + VanillaJigsawExportFormat exportFormat; + try { + exportFormat = parseFormat(context.get(FORMAT)); + } catch (IllegalArgumentException exception) { + use.error(exception.getMessage()); + return; + } + Path exportRoot = use.pack().outputFolder().toAbsolutePath().normalize(); + Path destination; + try { + destination = resolveExportDestination(exportRoot, context.get(OUTPUT), exportFormat); + } catch (IllegalArgumentException exception) { + use.error(exception.getMessage()); + return; + } + VanillaJigsawExportRequest request; + try { + request = VanillaJigsawExportRequest.builder( + VanillaJigsawExportSource.forPack( + active.request().source().resources(), active.request().structureKey()), destination) + .namespace(context.get(NAMESPACE)) + .resourcePath(active.request().structureKey()) + .format(exportFormat) + .replaceExisting(StudioLifecycleCommands.flagValue(REPLACE.name(), context.get(REPLACE))) + .build(); + } catch (IllegalArgumentException exception) { + use.error(exception.getMessage()); + return; + } + ToolPlayer targetPlayer = use.player(); + UUID playerId = targetPlayer.id(); + UUID requestId = active.request().requestId(); + JigsawStudioService studioService = use.studio(); + JigsawStudioService.ExportStart exportStart = studioService.tryBeginExport(requestId, playerId); + if (exportStart != JigsawStudioService.ExportStart.STARTED) { + use.error(exportStartError(exportStart)); + return; + } + if (!beginExport(playerId, destination)) { + studioService.finishExport(requestId); + use.error("A vanilla Jigsaw export for this player or output is already in progress."); + return; + } + ExportLease lease = new ExportLease(() -> { + finishExport(playerId, destination); + studioService.finishExport(requestId); + }); + ExportOperation operation = new ExportOperation( + use, + context.sender(), + requestId, + active.request().structureKey(), + request, + lease); + use.say(TextColor.GRAY, "Exporting '" + operation.structureKey() + + "' in the background to " + destination + "..."); + try { + runExport(operation); + } catch (RuntimeException exception) { + operation.lease().release(); + use.pack().log().error("Failed to schedule vanilla Jigsaw export for '" + + operation.structureKey() + "'.", exception); + use.error("Vanilla export could not be scheduled: " + exception.getMessage()); + } + } + + static String exportStartError(JigsawStudioService.ExportStart exportStart) { + Objects.requireNonNull(exportStart, "Jigsaw Studio export start status"); + return switch (exportStart) { + case NOT_ACTIVE -> "The active Jigsaw Studio is no longer available."; + case NOT_OWNER -> "Only the Jigsaw Studio owner can export this project."; + case DIRTY -> "Wait for the pending autosave or discard the edits before exporting the on-disk graph."; + case CLOSING -> "The active Jigsaw Studio is closing and cannot be exported."; + case SAVE_IN_PROGRESS -> "Wait for the current Jigsaw Studio save to finish before exporting."; + case OPERATION_IN_PROGRESS -> "Wait for the current Jigsaw Studio operation to finish before exporting."; + case IN_PROGRESS -> "A Jigsaw Studio export is already in progress."; + case STARTED -> throw new IllegalArgumentException("STARTED is not an export failure"); + }; + } + + static boolean beginExport(UUID playerId, Path destination) { + Objects.requireNonNull(playerId); + Path normalizedDestination = Objects.requireNonNull(destination).toAbsolutePath().normalize(); + if (!EXPORTING_PLAYERS.add(playerId)) { + return false; + } + if (EXPORT_DESTINATIONS.add(normalizedDestination)) { + return true; + } + EXPORTING_PLAYERS.remove(playerId); + return false; + } + + static void finishExport(UUID playerId, Path destination) { + EXPORTING_PLAYERS.remove(Objects.requireNonNull(playerId)); + EXPORT_DESTINATIONS.remove(Objects.requireNonNull(destination).toAbsolutePath().normalize()); + } + + private static void runExport(ExportOperation operation) { + VanillaJigsawExportResult result = null; + Throwable failure = null; + try { + result = new VanillaJigsawDatapackExporter().export(operation.request()); + } catch (Throwable throwable) { + failure = throwable; + operation.use().pack().log().error("Vanilla Jigsaw export failed for '" + operation.structureKey() + "'.", throwable); + } finally { + operation.lease().release(); + } + reportExport(operation, result, failure); + } + + private static void reportExport( + ExportOperation operation, + VanillaJigsawExportResult result, + Throwable failure + ) { + Sender sender = operation.sender(); + if (failure != null || result == null) { + SenderText.send(sender, TextColor.RED, "Background vanilla export for '" + + operation.structureKey() + "' failed: " + + (failure == null ? "no result" : failure.getMessage())); + return; + } + for (VanillaJigsawExportDiagnostic diagnostic : result.diagnostics()) { + TextColor color = diagnostic.isBlocking() ? TextColor.RED : TextColor.YELLOW; + SenderText.send(sender, color, diagnostic.code() + ": " + diagnostic.message()); + } + ActiveContext current = StudioSessions.active(operation.use().registry(), operation.use().player().id()); + boolean sameSession = current != null + && current.request().requestId().equals(operation.requestId()); + String contextLabel = sameSession ? "Vanilla export" : "Background vanilla export for '" + + operation.structureKey() + "'"; + SenderText.send(sender, result.isSuccess() ? TextColor.GREEN : TextColor.RED, + contextLabel + " " + result.status() + ": " + result.output()); + } + + private static VanillaJigsawExportFormat parseFormat(String value) { + return switch (value.trim().toLowerCase(Locale.ROOT)) { + case "zip" -> VanillaJigsawExportFormat.ZIP; + case "directory", "dir", "folder" -> VanillaJigsawExportFormat.DIRECTORY; + default -> throw new IllegalArgumentException("Export format must be directory or zip."); + }; + } + + static Path resolveExportDestination( + Path exportRoot, + String output, + VanillaJigsawExportFormat format + ) { + Path root = Objects.requireNonNull(exportRoot, "Jigsaw export root").toAbsolutePath().normalize(); + String requested = Objects.requireNonNull(output, "Jigsaw export output name"); + String name = requested.trim(); + if (!name.equals(requested) || !EXPORT_OUTPUT_NAME.matcher(name).matches()) { + throw new IllegalArgumentException( + "Export output must be one file name using letters, numbers, '.', '_', or '-'."); + } + String fileName = format == VanillaJigsawExportFormat.ZIP && !name.endsWith(".zip") + ? name + ".zip" : name; + Path destination = root.resolve(fileName).normalize(); + if (destination.equals(root) || !root.equals(destination.getParent())) { + throw new IllegalArgumentException("Export output must be one artifact inside the Studio exports folder."); + } + return destination; + } + + private record ExportOperation( + StudioUse use, + Sender sender, + UUID requestId, + String structureKey, + VanillaJigsawExportRequest request, + ExportLease lease + ) { + } + + static final class ExportLease { + private final Runnable release; + private final AtomicBoolean released; + + ExportLease(Runnable release) { + this.release = Objects.requireNonNull(release, "Jigsaw export lease release action"); + this.released = new AtomicBoolean(); + } + + void release() { + if (released.compareAndSet(false, true)) { + release.run(); + } + } + } +} diff --git a/module/src/main/java/art/arcane/iris/core/structure/tooling/JigsawStudios.java b/module/src/main/java/art/arcane/iris/core/structure/tooling/JigsawStudios.java new file mode 100644 index 000000000..23e122e1f --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/structure/tooling/JigsawStudios.java @@ -0,0 +1,38 @@ +/* + * 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.structure.tooling; + +import art.arcane.iris.core.service.JigsawStudioService; +import com.volmit.tooling.ToolPack; + +/** + * The Jigsaw Studio of one pack, which its jigsaw commands share. It is created by the first command that needs it, so a + * pack nobody opens a studio for never builds one. + */ +public final class JigsawStudios { + private JigsawStudioService studio; + + /** The studio, created with {@code pack}'s log when no command has asked for it yet. */ + public synchronized JigsawStudioService of(ToolPack pack) { + if (studio == null) { + studio = new JigsawStudioService(pack.log()); + } + return studio; + } +} diff --git a/module/src/main/java/art/arcane/iris/core/structure/tooling/PlatformStructuresAccess.java b/module/src/main/java/art/arcane/iris/core/structure/tooling/PlatformStructuresAccess.java new file mode 100644 index 000000000..6887350e4 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/structure/tooling/PlatformStructuresAccess.java @@ -0,0 +1,41 @@ +/* + * 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.structure.tooling; + +import com.volmit.tooling.CommandContext; +import com.volmit.tooling.PlatformStructures; + +import java.util.Optional; + +/** Asks a command's platform for its structures, and tells the sender when it has none. */ +public final class PlatformStructuresAccess { + public static final String UNAVAILABLE = "PlatformStructures is unavailable on this platform"; + + private PlatformStructuresAccess() { + } + + /** The platform's structures; empty after telling the sender that this platform has none. */ + public static Optional require(CommandContext context) { + Optional platform = context.platformStructures(); + if (platform.isEmpty()) { + context.sender().error(UNAVAILABLE); + } + return platform; + } +} diff --git a/module/src/main/java/art/arcane/iris/core/structure/tooling/SenderText.java b/module/src/main/java/art/arcane/iris/core/structure/tooling/SenderText.java new file mode 100644 index 000000000..a500c30b0 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/structure/tooling/SenderText.java @@ -0,0 +1,61 @@ +/* + * 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.structure.tooling; + +import com.volmit.tooling.Sender; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolText; + +import java.util.Optional; + +/** + * Sends a sender a line in colour: a player sees the colours as they are, and a sender that is not a player gets the + * line as an error, a success or plain information, by the colour the line starts with. + */ +public final class SenderText { + private SenderText() { + } + + public static void send(Sender sender, ToolText text) { + Optional player = sender.player(); + if (player.isPresent()) { + player.get().message(text); + return; + } + String plain = text.plainText(); + switch (leadingColor(text)) { + case RED -> sender.error(plain); + case GREEN -> sender.success(plain); + default -> sender.info(plain); + } + } + + /** A whole line in {@code color}. */ + public static void send(Sender sender, TextColor color, String line) { + send(sender, ToolText.colored(color, line)); + } + + private static TextColor leadingColor(ToolText text) { + if (text.isEmpty() || text.spans().getFirst().color() == null) { + return TextColor.WHITE; + } + return text.spans().getFirst().color(); + } +} diff --git a/module/src/main/java/art/arcane/iris/core/structure/tooling/StructureKeys.java b/module/src/main/java/art/arcane/iris/core/structure/tooling/StructureKeys.java new file mode 100644 index 000000000..ea75bfe3c --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/structure/tooling/StructureKeys.java @@ -0,0 +1,33 @@ +/* + * 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.structure.tooling; + +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; + +/** The keys the jigsaw commands show and the studio files its sessions under. */ +public final class StructureKeys { + private StructureKeys() { + } + + /** The key of a resource of the pack: its path when it is of the pack's namespace, else the id as written. */ + public static String keyOf(PackResources resources, ResourceId id) { + return resources.idOf(id.path()).equals(id) ? id.path() : id.toString(); + } +} diff --git a/module/src/main/java/art/arcane/iris/core/structure/tooling/StudioLifecycleCommands.java b/module/src/main/java/art/arcane/iris/core/structure/tooling/StudioLifecycleCommands.java new file mode 100644 index 000000000..63282ab1a --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/structure/tooling/StudioLifecycleCommands.java @@ -0,0 +1,772 @@ +/* + * 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.structure.tooling; + +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBay; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioGraphMapper; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioProjectCreator; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioSession; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariant; +import art.arcane.iris.core.service.JigsawStudioGraphEvaluation; +import art.arcane.iris.core.service.JigsawStudioRegistry; +import art.arcane.iris.core.service.JigsawStudioRequest; +import art.arcane.iris.core.service.JigsawStudioService; +import art.arcane.iris.core.structure.StructureImporter; +import art.arcane.iris.core.structure.VillageImporter; +import art.arcane.iris.core.structure.authoring.StructureKey; +import art.arcane.iris.core.structure.authoring.StructureWriteResult; +import art.arcane.iris.core.structure.tooling.StudioSessions.ActiveContext; +import art.arcane.iris.core.structure.tooling.StudioSessions.SessionBinding; +import art.arcane.iris.engine.framework.structure.StructureResources; +import art.arcane.iris.engine.object.structure.IrisStructure; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawCompatibility; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.Argument; +import com.volmit.tooling.Command; +import com.volmit.tooling.ObjectCodec; +import com.volmit.tooling.CommandContext; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.ToolPack; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolWorld; +import com.volmit.tooling.world.ToolWorldDenied; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import java.util.Locale; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.function.Supplier; + +/** The Jigsaw Studio commands that create, open, close and inspect a player's studio, and that select and resize its workcells. */ +final class StudioLifecycleCommands { + static final long DEFAULT_STUDIO_SEED = 1337L; + private static final String PLANAR = "planar"; + private static final String SPATIAL = "spatial"; + private static final String IRIS = "iris"; + private static final String VANILLA = "vanilla"; + private static final String NONE = "none"; + private static final String SELECTED = "selected"; + private static final long DEFAULT_CELL_SIZE = 15L; + + private static final Argument NEW_KEY = Argument.word("key") + .describe("New key written as structures/.json"); + private static final Argument EXISTING_KEY = Argument.resource("key", StructureResources.STRUCTURES) + .describe("Existing key loaded from structures/.json"); + private static final Argument MODE = Argument.word("mode").orElse(PLANAR) + .describe("planar or spatial").suggesting(context -> List.of(PLANAR, SPATIAL)); + private static final Argument COMPATIBILITY = Argument.word("compatibility").orElse(IRIS) + .describe("iris or vanilla").suggesting(context -> List.of(IRIS, VANILLA)); + private static final Argument WIDTH = size("width", "Cell width").orElse(DEFAULT_CELL_SIZE); + private static final Argument HEIGHT = size("height", "Cell height").orElse(DEFAULT_CELL_SIZE); + private static final Argument DEPTH = size("depth", "Cell depth").orElse(DEFAULT_CELL_SIZE); + private static final Argument SEED = seed(); + private static final Argument SOURCE = Argument.word("source") + .describe("Registered structure key such as minecraft:village_plains"); + private static final Argument TARGET = Argument.word("target").orElse("auto") + .describe("New Iris structure key, or auto"); + private static final Argument DISCARD = Argument.word("discard").orElse("false") + .describe("Discard unsaved Studio layout changes"); + private static final Argument CONFIRM = Argument.word("confirm").orElse("false") + .describe("Confirm permanent project deletion"); + private static final Argument REQUIRED_WIDTH = size("width", "Cell width"); + private static final Argument REQUIRED_HEIGHT = size("height", "Cell height"); + private static final Argument REQUIRED_DEPTH = size("depth", "Cell depth"); + private static final Argument BAY = Argument.word("bay").orElse(SELECTED) + .describe("Workcell ID or selected"); + private static final Argument GOTO_BAY = Argument.word("bay").describe("Workcell ID"); + private static final Argument VISIBLE = Argument.flag("visible") + .describe("Whether particles are visible"); + + private final JigsawStudios studios; + + StudioLifecycleCommands(JigsawStudios studios) { + this.studios = studios; + } + + List commands() { + return List.of( + Command.named("create").describe("Create and open a new atomic Jigsaw Studio project") + .argument(NEW_KEY).argument(MODE).argument(COMPATIBILITY) + .argument(WIDTH).argument(HEIGHT).argument(DEPTH).argument(SEED) + .runs(this::create), + Command.named("convert").alias("import-vanilla") + .describe("Import a registered vanilla or datapack jigsaw graph into Iris Studio") + .argument(SOURCE).argument(TARGET).argument(SEED) + .runs(this::convert), + Command.named("open").alias("edit", "reopen") + .describe("Open an existing Iris jigsaw graph in transient Studio") + .argument(EXISTING_KEY).argument(SEED) + .runs(this::open), + Command.named("close").describe("Close the active Jigsaw Studio") + .argument(DISCARD).runs(this::close), + Command.named("delete").alias("remove").describe("Delete the active owned jigsaw project") + .argument(CONFIRM).runs(this::delete), + Command.named("status").describe("Show active Jigsaw Studio and dynamic evaluation state") + .runs(this::status), + Command.named("menu").describe("Open the Jigsaw Studio workcell and variant menu") + .runs(this::menu), + Command.named("select").describe("Select the Jigsaw Studio workcell containing you") + .runs(this::select), + Command.named("bounds").alias("cell", "resize") + .describe("Set the selected Studio workcell capacity") + .argument(REQUIRED_WIDTH).argument(REQUIRED_HEIGHT).argument(REQUIRED_DEPTH) + .runs(this::bounds), + Command.named("save").describe("Flush the automatic save for a workcell now") + .argument(BAY).runs(this::save), + Command.named("goto").alias("teleport").describe("Select and teleport to a Studio workcell") + .argument(GOTO_BAY).runs(this::gotoBay), + Command.named("particles").describe("Enable or disable Jigsaw Studio particles") + .argument(VISIBLE).runs(this::particles)); + } + + private static Argument size(String name, String description) { + return Argument.integer(name, Integer.MIN_VALUE, Integer.MAX_VALUE).describe(description); + } + + private static Argument seed() { + return Argument.integer("seed", Long.MIN_VALUE, Long.MAX_VALUE).orElse(DEFAULT_STUDIO_SEED) + .describe("Studio world seed"); + } + + private void create(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ToolPack pack = context.pack(); + String structure = context.get(NEW_KEY); + JigsawStudioMode studioMode; + JigsawStudioCompatibilityTarget target; + JigsawStudioCellDimensions dimensions; + try { + studioMode = parseMode(context.get(MODE)); + target = parseCompatibility(context.get(COMPATIBILITY)); + dimensions = cellDimensions(context.get(WIDTH), context.get(HEIGHT), context.get(DEPTH)); + } catch (IllegalArgumentException exception) { + use.error(exception.getMessage()); + return; + } + + CreateOutcome outcome; + try { + JigsawStudioProjectCreator.Options options = + new JigsawStudioProjectCreator.Options(structure, studioMode, target, dimensions); + outcome = pack.edit(root -> createProject(root, pack.objects(), options, structure)); + } catch (IOException | RuntimeException exception) { + pack.log().error("Failed to create Jigsaw Studio project '" + structure + "'.", exception); + use.error("Jigsaw project creation failed: " + exception.getMessage()); + return; + } + StructureWriteResult result = outcome.result(); + if (!result.successful()) { + use.error("Jigsaw project was not created: " + result.status()); + if (!result.conflicts().isEmpty()) { + use.error(result.conflicts().getFirst().relativePath() + ": " + + result.conflicts().getFirst().reason()); + } + return; + } + if (outcome.historyFailure() != null) { + pack.log().error("Failed to clear stale Jigsaw Studio history for '" + structure + "'.", outcome.historyFailure()); + use.error("Jigsaw project was created, but stale autosave history could not be cleared: " + + outcome.historyFailure().getMessage()); + return; + } + use.say(TextColor.GREEN, "Created Jigsaw project '" + structure + "' atomically."); + openProject(use, structure); + } + + private static CreateOutcome createProject(Path root, ObjectCodec codec, JigsawStudioProjectCreator.Options options, + String structure) throws IOException { + StructureWriteResult result = JigsawStudioProjectCreator.create(root, codec, options); + if (!result.successful()) { + return new CreateOutcome(result, null); + } + try { + JigsawStudioService.clearAutosaveHistory(root, structure); + } catch (IOException exception) { + return new CreateOutcome(result, exception); + } + return new CreateOutcome(result, null); + } + + private record CreateOutcome(StructureWriteResult result, IOException historyFailure) { + } + + private void convert(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + if (studioIsActiveOrOpening(use.registry())) { + use.error("Close the active or opening Jigsaw Studio before importing another graph."); + return; + } + Optional platform = PlatformStructuresAccess.require(context); + if (platform.isEmpty()) { + return; + } + ResourceId sourceKey; + String targetKey; + try { + sourceKey = parseRegisteredStructureKey(context.get(SOURCE)); + targetKey = resolveConversionTarget(sourceKey, context.get(TARGET)); + } catch (IllegalArgumentException exception) { + use.error(exception.getMessage()); + return; + } + + VillageImporter.Result result = VillageImporter.importVillage( + context.pack(), + platform.get(), + sourceKey, + targetKey, + StructureImporter.Mode.ADD_ONLY); + if (!result.success()) { + use.error(conversionFailureMessage(result)); + return; + } + use.say(TextColor.GREEN, result.message()); + openProject(use, targetKey); + } + + private void open(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + openProject(begun.get(), StructureKeys.keyOf(context.pack().resources(), context.get(EXISTING_KEY))); + } + + /** Stages the studio of {@code structure}, opens its tool world and moves the player in once the studio is committed. */ + static void openProject(StudioUse use, String structure) { + ToolPack pack = use.pack(); + ToolPlayer player = use.player(); + JigsawStudioService studioService = use.studio(); + JigsawStudioRegistry registry = use.registry(); + UUID playerId = player.id(); + UUID ownerId = registry.activeOwnerId(); + if (ownerId != null && !ownerId.equals(playerId)) { + use.error("Jigsaw Studio is already owned by another player session."); + return; + } + UUID openingOwner = registry.openingOwnerId(); + if (openingOwner != null) { + use.error(openingOwner.equals(playerId) + ? "Your Jigsaw Studio is already opening." + : "Jigsaw Studio is already opening for another player."); + return; + } + ActiveContext previous = StudioSessions.active(registry, playerId); + if (ownerId != null && previous == null) { + use.error("Your active Jigsaw Studio binding is unavailable. Close it before opening another project."); + return; + } + ActiveContext dirty = StudioSessions.findDirtyContext(registry); + if (dirty != null) { + use.error("The current Jigsaw Studio is waiting for autosave. Wait for it to finish or close with discard=true."); + return; + } + IrisStructure irisStructure = StructureResources.structure(pack.resources(), structure); + if (irisStructure == null) { + use.error("No Iris jigsaw structure '" + structure + "' exists in this pack."); + return; + } + + JigsawStudioLayout layout; + try { + layout = JigsawStudioGraphMapper.map(pack, JigsawStudioRequest.rootOf(pack), structure, irisStructure); + } catch (RuntimeException exception) { + pack.log().error("Failed to map Jigsaw Studio graph '" + structure + "'.", exception); + use.error("Could not map this jigsaw graph: " + exception.getMessage()); + return; + } + String packKey = StudioUse.packKey(pack); + if (!registry.tryBeginOpen(playerId)) { + use.error("Jigsaw Studio began opening for another player. Try again after it finishes."); + return; + } + UUID closingRequestId = previous == null ? null : previous.request().requestId(); + if (closingRequestId != null) { + JigsawStudioService.CloseStart closeStart = studioService.tryBeginClose( + closingRequestId, + playerId, + false); + if (closeStart != JigsawStudioService.CloseStart.STARTED) { + registry.finishOpen(playerId); + use.error(closeStart == JigsawStudioService.CloseStart.SAVE_IN_PROGRESS + ? "The current Jigsaw Studio is saving. Wait for it to finish before opening another project." + : closeStart == JigsawStudioService.CloseStart.OPERATION_IN_PROGRESS + ? "The current Jigsaw Studio is loading a variant. Wait for it to finish before opening another project." + : closeStart == JigsawStudioService.CloseStart.DIRTY + ? "The current Jigsaw Studio is waiting for autosave. Wait for it to finish before opening another project." + : "The current Jigsaw Studio could not be reserved for replacement."); + return; + } + } + JigsawStudioRegistry.StagedActivation staged; + try { + staged = registry.stage( + packKey, + structure, + layout.mode(), + compatibilityOf(irisStructure), + layout.cellDimensions(), + pack, + layout, + playerId, + closingRequestId); + } catch (RuntimeException exception) { + registry.finishOpen(playerId); + studioService.cancelClose(closingRequestId); + pack.log().error("Failed to stage Jigsaw Studio for '" + structure + "'.", exception); + use.error("Jigsaw Studio staging failed: " + exception.getMessage()); + return; + } + use.say(TextColor.GREEN, "Opening transient Jigsaw Studio for '" + structure + "' with " + + layout.bays().size() + " workcells."); + + try { + beginStagedOpen(registry, staged); + studioService.open(pack, staged) + .whenComplete((world, throwable) -> player.run(() -> { + Throwable failure = throwable; + if (failure == null) { + failure = commitOpenedStudio(use, world, staged); + } + finishOpenAttempt(use, structure, closingRequestId, staged, world, failure); + })); + } catch (Throwable exception) { + registry.finishOpen(playerId); + studioService.cancelClose(closingRequestId); + registry.rollback(staged); + pack.log().error("Failed to open Jigsaw Studio for '" + structure + "'.", exception); + use.error("Jigsaw Studio open failed: " + exception.getMessage()); + } + } + + private void close(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + boolean discard = flagValue(DISCARD.name(), context.get(DISCARD)); + ToolPlayer player = use.player(); + ActiveContext active = StudioSessions.active(use.registry(), player.id()); + if (active == null) { + use.error("You do not have an active Jigsaw Studio session."); + return; + } + if (active.session().isDirty() && !discard) { + use.error("This Jigsaw Studio is waiting for autosave. Wait for it to finish or run close with discard=true."); + return; + } + JigsawStudioService studioService = use.studio(); + UUID requestId = active.request().requestId(); + JigsawStudioService.CloseStart closeStart = studioService.tryBeginClose( + requestId, + player.id(), + discard); + if (closeStart != JigsawStudioService.CloseStart.STARTED) { + use.error(closeStart == JigsawStudioService.CloseStart.SAVE_IN_PROGRESS + ? "This Jigsaw Studio is saving. Wait for the save to finish before closing it." + : closeStart == JigsawStudioService.CloseStart.OPERATION_IN_PROGRESS + ? "This Jigsaw Studio is loading a variant. Wait for it to finish before closing it." + : closeStart == JigsawStudioService.CloseStart.DIRTY + ? "This Jigsaw Studio is waiting for autosave. Wait for it to finish or run close with discard=true." + : closeStart == JigsawStudioService.CloseStart.NOT_OWNER + ? "This Jigsaw Studio is owned by another player session." + : "This Jigsaw Studio session is no longer active."); + return; + } + try { + closeToolWorld(use.pack(), requestId).whenComplete((ignored, throwable) -> player.run(() -> { + if (throwable != null) { + studioService.cancelClose(requestId); + use.error("Jigsaw Studio close failed: " + unwrapCompletionFailure(throwable).getMessage()); + return; + } + use.registry().deactivate(active.packKey(), requestId); + StudioSessions.unbind(player.id(), new SessionBinding(active.packKey(), requestId)); + use.say(TextColor.GREEN, "Jigsaw Studio closed."); + })); + } catch (Throwable exception) { + studioService.cancelClose(requestId); + context.pack().log().error("Failed to close Jigsaw Studio '" + active.request().structureKey() + "'.", exception); + use.error("Jigsaw Studio close failed: " + exception.getMessage()); + } + } + + /** Closes the tool world of the studio {@code requestId} opened; completes at once when the world is gone already. */ + private static CompletableFuture closeToolWorld(ToolPack pack, UUID requestId) { + return pack.worlds().find(JigsawStudioService.worldName(requestId)) + .map(ToolWorld::close) + .orElseGet(() -> CompletableFuture.completedFuture(null)); + } + + private void delete(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty() || begun.get().requireActive() == null) { + return; + } + StudioUse use = begun.get(); + if (!flagValue(CONFIRM.name(), context.get(CONFIRM))) { + use.error("Project deletion removes every resource owned by this jigsaw. Run again with confirm=true."); + return; + } + use.onPlayer(() -> use.studio().deleteProject(use.player())); + } + + private void status(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + JigsawStudioLayout layout = active.session().layout(); + String selection = active.session().selectedBayId().orElse(NONE); + JigsawStudioVariant activeVariant = NONE.equals(selection) + ? null + : active.session().activeVariant(selection).orElse(null); + JigsawStudioBay selectedBay = NONE.equals(selection) ? null : layout.get(selection); + JigsawStudioCellDimensions selectedDimensions = selectedBay == null + ? null + : selectedBay.bounds().dimensions(); + Optional evaluation = use.readFromPlayer(() -> use.studio().evaluation(use.player())); + use.say(TextColor.AQUA, "Jigsaw Studio: " + active.request().structureKey()); + use.say(TextColor.GRAY, "mode=" + layout.mode() + + ", compatibility=" + active.request().compatibilityTarget() + + ", defaultCell=" + layout.cellDimensions().width() + "x" + + layout.cellDimensions().height() + "x" + layout.cellDimensions().depth() + + ", workcells=" + layout.bays().size() + + ", variants=" + layout.variantCatalog().size()); + use.say(TextColor.GRAY, "selected=" + selection + + ", activeVariant=" + (activeVariant == null ? NONE : activeVariant.pieceKey()) + + ", size=" + (selectedDimensions == null ? NONE : selectedDimensions.width() + "x" + + selectedDimensions.height() + "x" + selectedDimensions.depth()) + + ", enabled=" + (selectedBay == null ? "n/a" : selectedBay.enabled()) + + ", autosavePending=" + active.session().isDirty()); + if (evaluation.isPresent()) { + JigsawStudioGraphEvaluation current = evaluation.get(); + use.say(TextColor.GRAY, "evaluation=" + current.state() + + ", seed=" + current.seed() + + ", theme=" + (current.selectedTheme().isBlank() ? "unthemed" : current.selectedTheme()) + + ", pieces=" + current.pieceCount() + + ", detail=" + current.detail()); + } else { + use.say(TextColor.GRAY, "evaluation=PENDING, seed=" + DEFAULT_STUDIO_SEED); + } + } + + private void menu(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty() || begun.get().requireActive() == null) { + return; + } + StudioUse use = begun.get(); + use.onPlayer(() -> use.studio().openControlMenu(use.player())); + } + + private void select(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + BlockPosition location = use.readFromPlayer(use.player()::position); + JigsawStudioBay bay = active.session().layout().findAt(location.x(), location.y(), location.z()); + if (bay == null) { + use.error("Stand inside a Jigsaw Studio workcell before selecting it."); + return; + } + active.session().selectBay(bay.stableId()); + use.say(TextColor.GREEN, "Selected " + bay.stableId() + " (" + bay.kind() + ")."); + } + + private void bounds(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + JigsawStudioBay selected = StudioUse.selectedBay(active); + if (selected == null) { + use.error("Select a Jigsaw Studio workcell before changing its capacity."); + return; + } + JigsawStudioCellDimensions dimensions; + try { + dimensions = cellDimensions(context.get(REQUIRED_WIDTH), context.get(REQUIRED_HEIGHT), context.get(REQUIRED_DEPTH)); + } catch (IllegalArgumentException exception) { + use.error(exception.getMessage()); + return; + } + if (dimensions.equals(selected.capacity())) { + use.say(TextColor.YELLOW, "Workcell capacity is unchanged."); + return; + } + use.onPlayer(() -> use.studio().updateWorkcellDimensions(use.player(), selected.stableId(), dimensions)); + } + + private void save(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty()) { + return; + } + StudioUse use = begun.get(); + ActiveContext active = use.requireActive(); + if (active == null) { + return; + } + String bay = context.get(BAY); + if (SELECTED.equalsIgnoreCase(bay)) { + JigsawStudioBay selected = StudioUse.selectedBay(active); + if (selected == null) { + use.error("Select a Jigsaw Studio workcell before flushing its autosave."); + return; + } + use.onPlayer(() -> use.studio().flushAutosave(use.player(), selected.stableId())); + return; + } + use.onPlayer(() -> use.studio().flushAutosave(use.player(), bay)); + } + + private void gotoBay(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty() || begun.get().requireActive() == null) { + return; + } + StudioUse use = begun.get(); + String bay = context.get(GOTO_BAY); + use.onPlayer(() -> use.studio().teleportTo(use.player(), bay)); + } + + private void particles(CommandContext context) { + Optional begun = StudioUse.begin(studios, context); + if (begun.isEmpty() || begun.get().requireActive() == null) { + return; + } + StudioUse use = begun.get(); + boolean visible = context.get(VISIBLE); + use.onPlayer(() -> use.studio().setParticles(use.player(), visible)); + } + + private static boolean studioIsActiveOrOpening(JigsawStudioRegistry registry) { + return registry.activeOwnerId() != null + || registry.openingOwnerId() != null; + } + + private static void beginStagedOpen(JigsawStudioRegistry registry, JigsawStudioRegistry.StagedActivation staged) { + if (!registry.beginStagedGeneration(staged)) { + throw new IllegalStateException("The staged Jigsaw Studio activation is no longer current"); + } + } + + private static void finishOpenAttempt( + StudioUse use, + String structureKey, + UUID closingRequestId, + JigsawStudioRegistry.StagedActivation staged, + ToolWorld result, + Throwable throwable + ) { + JigsawStudioRegistry registry = use.registry(); + registry.finishOpen(use.player().id()); + if (throwable == null && result != null) { + use.studio().cancelClose(closingRequestId); + return; + } + use.studio().cancelClose(closingRequestId); + registry.rollback(staged); + Throwable failure = unwrapCompletionFailure(throwable == null + ? new IllegalStateException("Studio open completed without a result") + : throwable); + ToolPack pack = use.pack(); + if (failure instanceof ToolWorldDenied) { + pack.log().warn("Jigsaw Studio open for '" + structureKey + "' was denied: " + failure.getMessage()); + failure.getMessage().lines().forEach(use::error); + return; + } + pack.log().error("Failed to open Jigsaw Studio for '" + structureKey + "'.", failure); + use.error("Jigsaw Studio open failed: " + failure.getMessage()); + } + + /** Commits the staged studio once its world is open and moves the player in; the failure, or null when all went well. */ + private static Throwable commitOpenedStudio( + StudioUse use, + ToolWorld world, + JigsawStudioRegistry.StagedActivation staged + ) { + try { + enterCommittedStudio(use, world, staged); + return null; + } catch (RuntimeException exception) { + return exception; + } + } + + private static void enterCommittedStudio( + StudioUse use, + ToolWorld world, + JigsawStudioRegistry.StagedActivation staged + ) { + if (world == null) { + throw new IllegalStateException("Jigsaw Studio opened without a world"); + } + JigsawStudioRegistry registry = use.registry(); + JigsawStudioRequest request = staged.request(); + JigsawStudioSession session = staged.session(); + JigsawStudioBay destination = initialBay(session.layout()); + double targetX = destination == null + ? 0.5D + : destination.bounds().originX() + destination.bounds().dimensions().width() / 2.0D; + double targetY = destination == null ? 66D : destination.bounds().maxY() + 2.0D; + double targetZ = destination == null + ? 0.5D + : destination.bounds().originZ() + destination.bounds().dimensions().depth() / 2.0D; + if (destination != null) { + session.selectBay(destination.stableId()); + } + if (!registry.commit(staged)) { + throw new IllegalStateException("The staged Jigsaw Studio activation could not be committed"); + } + use.studio().activationCommitted(request.requestId()); + StudioSessions.bind(use.player().id(), new SessionBinding( + request.packKey(), request.requestId())); + ToolPlayer player = use.player(); + try { + player.teleport(world, targetX, targetY, targetZ, 0.0F, 0.0F) + .thenRun(() -> player.creative(true)); + } catch (RuntimeException exception) { + use.pack().log().error("Failed to move the player to the committed Jigsaw Studio workcell.", exception); + } + } + + private static JigsawStudioBay initialBay(JigsawStudioLayout layout) { + for (JigsawStudioBay bay : layout.bays()) { + if (layout.defaultVariant(bay).isPresent()) { + return bay; + } + } + return layout.bays().isEmpty() ? null : layout.bays().getFirst(); + } + + private static Throwable unwrapCompletionFailure(Throwable failure) { + Throwable current = failure; + while (current instanceof CompletionException && current.getCause() != null) { + current = current.getCause(); + } + return current; + } + + private static JigsawStudioCellDimensions cellDimensions(long width, long height, long depth) { + return new JigsawStudioCellDimensions((int) width, (int) height, (int) depth); + } + + /** Whether the text says true, written either as a value or as {@code name=value}, which is how the commands tell it. */ + static boolean flagValue(String name, String text) { + String value = text.trim().toLowerCase(Locale.ROOT); + String prefix = name + "="; + return Boolean.parseBoolean(value.startsWith(prefix) ? value.substring(prefix.length()) : value); + } + + static JigsawStudioMode parseMode(String value) { + return switch (value.trim().toLowerCase(Locale.ROOT)) { + case "planar", "2d", "planar_jigsaw" -> JigsawStudioMode.PLANAR_JIGSAW; + case "spatial", "3d", "spatial_jigsaw" -> JigsawStudioMode.SPATIAL_JIGSAW; + default -> throw new IllegalArgumentException("Mode must be planar or spatial."); + }; + } + + static JigsawStudioCompatibilityTarget parseCompatibility(String value) { + return switch (value.trim().toLowerCase(Locale.ROOT)) { + case "extended", "iris", "iris_extended" -> JigsawStudioCompatibilityTarget.IRIS_EXTENDED; + case "vanilla", "portable", "vanilla_portable" -> JigsawStudioCompatibilityTarget.VANILLA_PORTABLE; + default -> throw new IllegalArgumentException("Compatibility must be iris or vanilla."); + }; + } + + private static JigsawStudioCompatibilityTarget compatibilityOf(IrisStructure structure) { + return structure.resolvedCompatibility() == IrisJigsawCompatibility.VANILLA_PORTABLE + ? JigsawStudioCompatibilityTarget.VANILLA_PORTABLE + : JigsawStudioCompatibilityTarget.IRIS_EXTENDED; + } + + static ResourceId parseRegisteredStructureKey(String value) { + String normalized = Objects.requireNonNull(value, "Registered structure key").trim() + .toLowerCase(Locale.ROOT); + try { + return ResourceId.ofPlatformKey(normalized); + } catch (IllegalArgumentException invalid) { + throw new IllegalArgumentException( + "Registered structure source must use a valid namespace:path key."); + } + } + + static String resolveConversionTarget(ResourceId source, String value) { + Objects.requireNonNull(source, "Registered structure key"); + String normalized = Objects.requireNonNull(value, "Conversion target").trim() + .toLowerCase(Locale.ROOT); + if (normalized.isEmpty() || "auto".equals(normalized)) { + return StructureImporter.deriveName(source); + } + StructureKey target = StructureKey.parse(normalized, "iris"); + if (!"iris".equals(target.namespace())) { + throw new IllegalArgumentException("Converted Studio targets must use the iris namespace."); + } + return target.path(); + } + + static String conversionFailureMessage(VillageImporter.Result result) { + String message = Objects.requireNonNull(result, "Village import result").message(); + String obsoleteInstruction = "; use 'import' for single-template structures"; + int instructionIndex = message.indexOf(obsoleteInstruction); + if (instructionIndex < 0) { + return message; + } + return message.substring(0, instructionIndex) + + ". This Studio converter accepts registered jigsaw structures only."; + } +} diff --git a/module/src/main/java/art/arcane/iris/core/structure/tooling/StudioSessions.java b/module/src/main/java/art/arcane/iris/core/structure/tooling/StudioSessions.java new file mode 100644 index 000000000..eb23e8133 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/structure/tooling/StudioSessions.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.core.structure.tooling; + +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioSession; +import art.arcane.iris.core.service.JigsawStudioRegistry; +import art.arcane.iris.core.service.JigsawStudioRequest; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** The studio each player of the commands has open: which pack's studio, and which request opened it. */ +final class StudioSessions { + private static final Map PLAYER_PACKS = new ConcurrentHashMap<>(); + + private StudioSessions() { + } + + /** The studio of the pack {@code packKey}, opened by one request, with its session. */ + public record ActiveContext(String packKey, JigsawStudioRequest request, JigsawStudioSession session) { + } + + record SessionBinding(String packKey, UUID requestId) { + } + + static void bind(UUID playerId, SessionBinding binding) { + PLAYER_PACKS.put(playerId, binding); + } + + static void unbind(UUID playerId, SessionBinding binding) { + PLAYER_PACKS.remove(playerId, binding); + } + + /** The studio the player has open, or null when they have none or it has since been replaced. */ + static ActiveContext active(JigsawStudioRegistry registry, UUID playerId) { + if (playerId == null) { + return null; + } + SessionBinding binding = PLAYER_PACKS.get(playerId); + if (binding == null) { + return null; + } + ActiveContext context = context(registry, binding); + if (context == null) { + PLAYER_PACKS.remove(playerId, binding); + return null; + } + return context; + } + + private static ActiveContext context(JigsawStudioRegistry registry, SessionBinding binding) { + JigsawStudioRequest request = registry.getRequest(binding.packKey()); + JigsawStudioSession session = registry.getSession(binding.packKey()); + if (request == null || session == null + || !binding.requestId().equals(request.requestId()) + || !request.requestId().equals(session.sessionId())) { + return null; + } + return new ActiveContext(binding.packKey(), request, session); + } + + /** A studio of any player that still has unsaved edits, or null. */ + static ActiveContext findDirtyContext(JigsawStudioRegistry registry) { + for (SessionBinding binding : PLAYER_PACKS.values()) { + JigsawStudioRequest request = registry.getRequest(binding.packKey()); + JigsawStudioSession session = registry.getSession(binding.packKey()); + if (request != null && session != null + && binding.requestId().equals(request.requestId()) + && session.isDirty()) { + return new ActiveContext(binding.packKey(), request, session); + } + } + return null; + } +} diff --git a/module/src/main/java/art/arcane/iris/core/structure/tooling/StudioUse.java b/module/src/main/java/art/arcane/iris/core/structure/tooling/StudioUse.java new file mode 100644 index 000000000..caa7b8532 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/core/structure/tooling/StudioUse.java @@ -0,0 +1,157 @@ +/* + * 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.structure.tooling; + +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBay; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariant; +import art.arcane.iris.core.service.JigsawStudioRegistry; +import art.arcane.iris.core.service.JigsawStudioService; +import art.arcane.iris.core.structure.tooling.StudioSessions.ActiveContext; +import com.volmit.tooling.CommandContext; +import com.volmit.tooling.Sender; +import com.volmit.tooling.ToolPack; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolPlayer; + +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Supplier; + +/** + * One run of a command that acts on a player's studio: the pack's studio, the player who ran the command and what they say + * back. A command that needs a player and has none has told the sender when {@link #begin} answers empty. + */ +final class StudioUse { + static final String PLAYERS_ONLY = "This command can only be used by players."; + static final String NO_ACTIVE_STUDIO = "Open a Jigsaw Studio project first."; + private static final long PLAYER_THREAD_TIMEOUT_SECONDS = 10L; + + private final JigsawStudios studios; + private final CommandContext context; + private final ToolPlayer player; + private final ToolPack pack; + + private StudioUse(JigsawStudios studios, CommandContext context, ToolPlayer player, ToolPack pack) { + this.studios = studios; + this.context = context; + this.player = player; + this.pack = pack; + } + + /** This use on another pack, such as the one an earlier command prepared a change for. */ + StudioUse onPack(ToolPack other) { + return new StudioUse(studios, context, player, other); + } + + /** The key the studio files {@code pack} under: the name of the pack's folder. */ + static String packKey(ToolPack pack) { + return pack.outputFolder().getFileName().toString(); + } + + ToolPack pack() { + return pack; + } + + /** The use for a command that needs the pack's studio and the player who ran it. */ + static Optional begin(JigsawStudios studios, CommandContext context) { + Optional player = context.sender().player(); + if (player.isEmpty()) { + context.sender().error(PLAYERS_ONLY); + return Optional.empty(); + } + return Optional.of(new StudioUse(studios, context, player.get(), context.pack())); + } + + CommandContext context() { + return context; + } + + ToolPlayer player() { + return player; + } + + Sender sender() { + return context.sender(); + } + + JigsawStudioService studio() { + return studios.of(pack); + } + + JigsawStudioRegistry registry() { + return studio().registry(); + } + + void say(TextColor color, String message) { + SenderText.send(context.sender(), color, message); + } + + void error(String message) { + say(TextColor.RED, message); + } + + /** The studio this player has open, after telling them to open one when they have none. */ + ActiveContext requireActive() { + ActiveContext active = StudioSessions.active(registry(), player.id()); + if (active == null) { + error(NO_ACTIVE_STUDIO); + } + return active; + } + + /** Runs {@code task} on the thread that owns the player, as the studio's calls about a player expect. */ + void onPlayer(Runnable task) { + player.run(task); + } + + /** What {@code reader} reads from the player, on the thread that owns them; waits for it. */ + T readFromPlayer(Supplier reader) { + CompletableFuture result = new CompletableFuture<>(); + player.run(() -> { + try { + result.complete(reader.get()); + } catch (Throwable failure) { + result.completeExceptionally(failure); + } + }); + try { + return result.get(PLAYER_THREAD_TIMEOUT_SECONDS, TimeUnit.SECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while reading from the player", interrupted); + } catch (ExecutionException | TimeoutException failure) { + throw new IllegalStateException("Could not read from the player: " + failure.getMessage(), failure); + } + } + + static JigsawStudioBay selectedBay(ActiveContext context) { + String selected = context.session().selectedBayId().orElse(null); + return selected == null ? null : context.session().layout().get(selected); + } + + static JigsawStudioVariant selectedVariant(ActiveContext context) { + JigsawStudioBay selected = selectedBay(context); + return selected == null + ? null + : context.session().activeVariant(selected.stableId()).orElse(null); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java b/module/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java similarity index 74% rename from core/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java rename to module/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java index ee3217df1..91fb7db7c 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java +++ b/module/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java @@ -19,29 +19,30 @@ package art.arcane.iris.engine.framework; import art.arcane.iris.builtin.anchor.PlaceTrait; +import art.arcane.iris.engine.framework.structure.ColumnHeights; import art.arcane.iris.engine.framework.structure.NativeStartPlanner; -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; -import art.arcane.iris.engine.framework.structure.StructureAssemblyResult; -import art.arcane.iris.engine.object.world.biome.IrisBiome; +import art.arcane.iris.engine.framework.structure.StructureWorld; +import art.arcane.iris.engine.framework.structure.assembly.AssembledPiece; +import art.arcane.iris.engine.framework.structure.assembly.Assembly; +import art.arcane.iris.engine.framework.structure.assembly.StructureAssembly; +import art.arcane.iris.engine.framework.structure.assembly.StructureStamp; +import art.arcane.iris.engine.framework.structure.assembly.Viability; import art.arcane.iris.builtin.structure.NativeStructureSource; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.iris.builtin.structure.StructureAnchorMode; import art.arcane.iris.builtin.structure.StructureCarveShape; import art.arcane.iris.builtin.structure.StructurePlacement; +import art.arcane.iris.builtin.structure.StructurePlacementSettings; import art.arcane.iris.builtin.structure.StructureTerrain; import art.arcane.iris.builtin.structure.StructureTerrainMode; import art.arcane.iris.builtin.structure.NativeStructureSuppression; import art.arcane.iris.builtin.structure.StructureDistribution; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; -import art.arcane.iris.core.modules.IrisModuleHost; -import com.volmit.ModuleLog; -import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; +import com.volmit.config.Level; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; import java.util.ArrayList; import java.util.Collections; @@ -87,139 +88,139 @@ public final class IrisStructureLocator { } /** Structure keys referenced by any Iris assembly or native jigsaw placement. */ - public static Set placedKeys(Engine engine) { - if (engine == null) { + public static Set placedKeys(PackWorld world) { + if (world == null) { return Collections.emptySet(); } - return index(engine).loadKeys; + return index(world).loadKeys; } /** * Every key under which a structure the engine's placements place can be found: the placed keys and the platform * structures Iris structures stand in for ({@code vanillaSource}), the latter in lower case. */ - public static Set placedKeysAndAliases(Engine engine) { - if (engine == null) { + public static Set placedKeysAndAliases(PackWorld world) { + if (world == null) { return Collections.emptySet(); } - PlacementIndex placementIndex = index(engine); + PlacementIndex placementIndex = index(world); Set keys = new LinkedHashSet<>(placementIndex.loadKeys); keys.addAll(placementIndex.vanillaAliases); return Collections.unmodifiableSet(keys); } /** The platform structures the engine's placements start natively ({@code nativeStructures}), in lower case. */ - public static Set nativeKeys(Engine engine) { - if (engine == null) { + public static Set nativeKeys(PackWorld world) { + if (world == null) { return Collections.emptySet(); } - return index(engine).nativeKeys; + return index(world).nativeKeys; } - public static boolean isPlaced(Engine engine, String key) { - if (engine == null || key == null || key.isEmpty()) { + public static boolean isPlaced(PackWorld world, String key) { + if (world == null || key == null || key.isEmpty()) { return false; } - PlacementIndex placementIndex = index(engine); + PlacementIndex placementIndex = index(world); String normalizedKey = normalize(key); return placementIndex.normalizedLoadKeys.contains(normalizedKey) || placementIndex.vanillaAliases.contains(normalizedKey); } - public static boolean hasLocatablePlacement(Engine engine, String key) { - if (engine == null || key == null || key.isBlank()) { + public static boolean hasLocatablePlacement(PackWorld world, String key) { + if (world == null || key == null || key.isBlank()) { return false; } - return locatableIndex(engine).normalizedKeys().contains(normalize(key)); + return locatableIndex(world).normalizedKeys().contains(normalize(key)); } - public static boolean hasLocatableEditablePlacement(Engine engine, String key) { - if (engine == null || key == null || key.isBlank()) { + public static boolean hasLocatableEditablePlacement(PackWorld world, String key) { + if (world == null || key == null || key.isBlank()) { return false; } - return locatableIndex(engine).normalizedEditableKeys().contains(normalize(key)); + return locatableIndex(world).normalizedEditableKeys().contains(normalize(key)); } - public static boolean hasLocatableNativePlacement(Engine engine, String key) { - if (engine == null || key == null || key.isBlank()) { + public static boolean hasLocatableNativePlacement(PackWorld world, String key) { + if (world == null || key == null || key.isBlank()) { return false; } - return locatableIndex(engine).normalizedNativeKeys().contains(normalize(key)); + return locatableIndex(world).normalizedNativeKeys().contains(normalize(key)); } - public static Set locatableKeys(Engine engine) { - return locatableIndex(engine).keys(); + public static Set locatableKeys(PackWorld world) { + return locatableIndex(world).keys(); } - public static Set locatableEditableKeys(Engine engine) { - return locatableIndex(engine).editableKeys(); + public static Set locatableEditableKeys(PackWorld world) { + return locatableIndex(world).editableKeys(); } - public static Set locatableNativeKeys(Engine engine) { - return locatableIndex(engine).nativeKeys(); + public static Set locatableNativeKeys(PackWorld world) { + return locatableIndex(world).nativeKeys(); } - public static boolean hasNativePlacement(Engine engine, String key) { - if (engine == null || key == null || key.isBlank()) { + public static boolean hasNativePlacement(PackWorld world, String key) { + if (world == null || key == null || key.isBlank()) { return false; } - return index(engine).nativeKeys.contains(normalize(key)); + return index(world).nativeKeys.contains(normalize(key)); } - public static boolean hasEditablePlacement(Engine engine, String key) { - if (engine == null || key == null || key.isBlank()) { + public static boolean hasEditablePlacement(PackWorld world, String key) { + if (world == null || key == null || key.isBlank()) { return false; } - for (StructurePlacement placement : index(engine).placements) { - if (placement.hasIrisStructures() && matches(placement, key, engine.getData())) { + for (StructurePlacement placement : index(world).placements) { + if (placement.hasIrisStructures() && matches(placement, key, world)) { return true; } } return false; } - public static boolean suppressesVanilla(Engine engine, String vanillaKey) { - if (engine == null || vanillaKey == null || vanillaKey.isEmpty()) { + public static boolean suppressesVanilla(PackWorld world, String vanillaKey) { + if (world == null || vanillaKey == null || vanillaKey.isEmpty()) { return false; } - return index(engine).suppressedVanillaSources.contains(normalize(vanillaKey)); + return index(world).suppressedVanillaSources.contains(normalize(vanillaKey)); } - public static boolean startsInChunk(Engine engine, String key, int cx, int cz) { - if (!isPlaced(engine, key)) { + public static boolean startsInChunk(PackWorld world, String key, int cx, int cz) { + if (!isPlaced(world, key)) { return false; } - return resolveInChunk(engine, key, cx, cz) != null; + return resolveInChunk(world, key, cx, cz) != null; } - public static LocateResult locate(Engine engine, String key, int fromBlockX, int fromBlockZ, int maxRadiusChunks) { - return locate(engine, key, fromBlockX, fromBlockZ, maxRadiusChunks, (chunkX, chunkZ) -> true); + public static LocateResult locate(PackWorld world, String key, int fromBlockX, int fromBlockZ, int maxRadiusChunks) { + return locate(world, key, fromBlockX, fromBlockZ, maxRadiusChunks, (chunkX, chunkZ) -> true); } - public static LocateResult locate(Engine engine, String key, int fromBlockX, int fromBlockZ, + public static LocateResult locate(PackWorld world, String key, int fromBlockX, int fromBlockZ, int maxRadiusChunks, CandidateFilter candidateFilter) { try { - return locateFiltered(engine, key, fromBlockX, fromBlockZ, maxRadiusChunks, candidateFilter); + return locateFiltered(world, key, fromBlockX, fromBlockZ, maxRadiusChunks, candidateFilter); } catch (CandidateSearchLimitException ignored) { return SEARCH_LIMIT_RESULT; } } public static LocateResult locateInPlacementRings( - Engine engine, String key, int fromBlockX, int fromBlockZ, + PackWorld world, String key, int fromBlockX, int fromBlockZ, int maxSearchRadius, CandidateFilter candidateFilter) { try { return locateInPlacementRingsFiltered( - engine, key, fromBlockX, fromBlockZ, maxSearchRadius, candidateFilter); + world, key, fromBlockX, fromBlockZ, maxSearchRadius, candidateFilter); } catch (CandidateSearchLimitException ignored) { return SEARCH_LIMIT_RESULT; } } private static LocateResult locateInPlacementRingsFiltered( - Engine engine, String key, int fromBlockX, int fromBlockZ, + PackWorld world, String key, int fromBlockX, int fromBlockZ, int maxSearchRadius, CandidateFilter candidateFilter) { - if (!isPlaced(engine, key)) { + if (!isPlaced(world, key)) { return NOT_FOUND_RESULT; } CandidateFilter activeFilter = Objects.requireNonNull( @@ -227,26 +228,21 @@ public final class IrisStructureLocator { int maximumRing = Math.max(0, Math.min(maxSearchRadius, 2048)); int centerChunkX = fromBlockX >> 4; int centerChunkZ = fromBlockZ >> 4; - PlacementCatalog catalog = collectPlacementCatalog(engine, key); + PlacementCatalog catalog = collectPlacementCatalog(world, key); if (catalog.randomSpread().isEmpty() && catalog.concentricRings().isEmpty() && !catalog.hasDensity()) { return NOT_FOUND_RESULT; } - SeedManager seedManager = engine.getSeedManager(); - if (seedManager == null) { - throw new IllegalStateException( - "Iris structure locate requires a bound seed manager for '" + key + "'"); - } - long seed = seedManager.getMantle(); + long seed = StructureWorld.placementSeed(world); CandidateBudget candidateBudget = new CandidateBudget(); LocatedCandidate best = nearestConcentricCandidate( - engine, key, fromBlockX, fromBlockZ, seed, catalog, activeFilter, candidateBudget); + world, key, fromBlockX, fromBlockZ, seed, catalog, activeFilter, candidateBudget); for (int ring = 0; ring <= maximumRing; ring++) { boolean foundInRing = false; for (RandomSpreadParameters parameters : catalog.randomSpread()) { LocatedCandidate candidate = firstRandomSpreadCandidateInRing( - engine, key, fromBlockX, fromBlockZ, + world, key, fromBlockX, fromBlockZ, centerChunkX, centerChunkZ, ring, seed, parameters, activeFilter, candidateBudget); if (candidate == null) { @@ -259,7 +255,7 @@ public final class IrisStructureLocator { } if (catalog.hasDensity()) { LocatedCandidate candidate = firstDensityCandidateInRing( - engine, key, fromBlockX, fromBlockZ, + world, key, fromBlockX, fromBlockZ, centerChunkX, centerChunkZ, ring, activeFilter, candidateBudget); if (candidate != null) { @@ -277,7 +273,7 @@ public final class IrisStructureLocator { } private static LocatedCandidate nearestConcentricCandidate( - Engine engine, String key, int fromBlockX, int fromBlockZ, + PackWorld world, String key, int fromBlockX, int fromBlockZ, long seed, PlacementCatalog catalog, CandidateFilter candidateFilter, CandidateBudget candidateBudget) { LocatedCandidate best = null; @@ -291,7 +287,7 @@ public final class IrisStructureLocator { if (candidate == null || !checkedChunks.add(chunkKey(candidate[0], candidate[1]))) { continue; } - ResolvedStart resolved = resolveInChunk(engine, key, candidate[0], candidate[1]); + ResolvedStart resolved = resolveInChunk(world, key, candidate[0], candidate[1]); if (resolved == null || !candidateFilter.accept(candidate[0], candidate[1])) { continue; } @@ -306,7 +302,7 @@ public final class IrisStructureLocator { } private static LocatedCandidate firstRandomSpreadCandidateInRing( - Engine engine, String key, int fromBlockX, int fromBlockZ, + PackWorld world, String key, int fromBlockX, int fromBlockZ, int centerChunkX, int centerChunkZ, int ring, long seed, RandomSpreadParameters parameters, CandidateFilter candidateFilter, CandidateBudget candidateBudget) { @@ -324,7 +320,7 @@ public final class IrisStructureLocator { int[] candidate = StructurePlacementGrid.randomSpreadCellChunk( centerCellX + offsetX, centerCellZ + offsetZ, spacing, parameters.separation(), parameters.salt(), seed); - ResolvedStart resolved = resolveInChunk(engine, key, candidate[0], candidate[1]); + ResolvedStart resolved = resolveInChunk(world, key, candidate[0], candidate[1]); if (resolved != null && candidateFilter.accept(candidate[0], candidate[1])) { return new LocatedCandidate( resolved, blockDistanceSquared(resolved, fromBlockX, fromBlockZ)); @@ -335,7 +331,7 @@ public final class IrisStructureLocator { } private static LocatedCandidate firstDensityCandidateInRing( - Engine engine, String key, int fromBlockX, int fromBlockZ, + PackWorld world, String key, int fromBlockX, int fromBlockZ, int centerChunkX, int centerChunkZ, int ring, CandidateFilter candidateFilter, CandidateBudget candidateBudget) { for (int offsetX = -ring; offsetX <= ring; offsetX++) { @@ -348,7 +344,7 @@ public final class IrisStructureLocator { int chunkX = centerChunkX + offsetX; int chunkZ = centerChunkZ + offsetZ; candidateBudget.claim(); - ResolvedStart resolved = resolveInChunk(engine, key, chunkX, chunkZ); + ResolvedStart resolved = resolveInChunk(world, key, chunkX, chunkZ); if (resolved != null && candidateFilter.accept(chunkX, chunkZ)) { return new LocatedCandidate( resolved, blockDistanceSquared(resolved, fromBlockX, fromBlockZ)); @@ -358,9 +354,9 @@ public final class IrisStructureLocator { return null; } - private static LocateResult locateFiltered(Engine engine, String key, int fromBlockX, int fromBlockZ, + private static LocateResult locateFiltered(PackWorld world, String key, int fromBlockX, int fromBlockZ, int maxRadiusChunks, CandidateFilter candidateFilter) { - if (!isPlaced(engine, key)) { + if (!isPlaced(world, key)) { return NOT_FOUND_RESULT; } CandidateFilter activeFilter = Objects.requireNonNull(candidateFilter, "Structure locate filter must not be null"); @@ -368,15 +364,11 @@ public final class IrisStructureLocator { int pcx = fromBlockX >> 4; int pcz = fromBlockZ >> 4; LocatedCandidate best = null; - PlacementCatalog catalog = collectPlacementCatalog(engine, key); + PlacementCatalog catalog = collectPlacementCatalog(world, key); if (catalog.randomSpread().isEmpty() && catalog.concentricRings().isEmpty() && !catalog.hasDensity()) { return NOT_FOUND_RESULT; } - SeedManager seedManager = engine.getSeedManager(); - if (seedManager == null) { - throw new IllegalStateException("Iris structure locate requires a bound seed manager for '" + key + "'"); - } - long seed = seedManager.getMantle(); + long seed = StructureWorld.placementSeed(world); CandidateBudget candidateBudget = new CandidateBudget(); for (RandomSpreadParameters parameters : catalog.randomSpread) { @@ -407,7 +399,7 @@ public final class IrisStructureLocator { cx, cz, fromBlockX, fromBlockZ) >= best.distanceSquared()) { continue; } - ResolvedStart resolved = resolveInChunk(engine, key, cx, cz); + ResolvedStart resolved = resolveInChunk(world, key, cx, cz); if (resolved != null && activeFilter.accept(cx, cz)) { long distanceSquared = blockDistanceSquared( resolved, fromBlockX, fromBlockZ); @@ -434,7 +426,7 @@ public final class IrisStructureLocator { candidate[0], candidate[1], fromBlockX, fromBlockZ) >= best.distanceSquared()) { continue; } - ResolvedStart resolved = resolveInChunk(engine, key, candidate[0], candidate[1]); + ResolvedStart resolved = resolveInChunk(world, key, candidate[0], candidate[1]); if (resolved != null && activeFilter.accept(candidate[0], candidate[1])) { long distanceSquared = blockDistanceSquared( resolved, fromBlockX, fromBlockZ); @@ -463,7 +455,7 @@ public final class IrisStructureLocator { continue; } candidateBudget.claim(); - ResolvedStart resolved = resolveInChunk(engine, key, cx, cz); + ResolvedStart resolved = resolveInChunk(world, key, cx, cz); if (resolved != null && activeFilter.accept(cx, cz)) { long distanceSquared = blockDistanceSquared( resolved, fromBlockX, fromBlockZ); @@ -488,15 +480,15 @@ public final class IrisStructureLocator { && Math.abs((long) chunkZ - centerChunkZ) <= radius; } - public static ResolvedPlacement resolvePlacement(Engine engine, StructurePlacement placement, int cx, int cz) { - if (engine == null || engine.getData() == null || engine.getSeedManager() == null) { - throw new IllegalStateException("Iris structure placement requires a fully bound engine"); + public static ResolvedPlacement resolvePlacement(PackWorld world, StructurePlacement placement, int cx, int cz) { + if (world == null) { + throw new IllegalStateException("Iris structure placement requires a world"); } NativeStartPlanner.validateBackend(placement); if (!placement.hasIrisStructures()) { throw new IllegalStateException("Iris structure placement is missing its structure list"); } - long seed = engine.getSeedManager().getMantle(); + long seed = StructureWorld.placementSeed(world); if (!StructurePlacementGrid.startsInChunk(placement, cx, cz, seed)) { return null; } @@ -504,7 +496,7 @@ public final class IrisStructureLocator { RNG rng = StructurePlacementGrid.placementRng(placement, cx, cz, seed); int originX = (cx << 4) + rng.nextInt(16); int originZ = (cz << 4) + rng.nextInt(16); - PlacementAnchor anchor = resolveAnchor(engine, placement, cx, cz, originX, originZ, rng); + PlacementAnchor anchor = resolveAnchor(world, placement, cx, cz, originX, originZ, rng); if (anchor == null) { return null; } @@ -516,35 +508,36 @@ public final class IrisStructureLocator { if (selectedKey == null || selectedKey.isBlank()) { throw new IllegalStateException("Iris structure placement selected a blank structure key"); } - IrisStructure structure = StructureResources.structure(engine.getData().getPackResources(), selectedKey); - if (structure == null) { + PackResources pack = world.resources(); + ResourceId structureId = pack.idOf(selectedKey); + StructureAssembly provider = providerOf(world, structureId); + if (provider == null) { throw new IllegalStateException("Iris structure placement references missing structure '" + selectedKey + "'"); } - StructureGraphCompilation compilation = StructureGraphCatalog.compile(engine.getData(), structure, IrisModuleHost.hostLog()); - if (!compilation.isAssemblyViable()) { + if (!provider.viability(pack, structureId).isViable()) { throw new IllegalStateException("Iris structure '" + selectedKey + "' has no runtime-viable assembly graph"); } - StructureAssembler assembler = StructureAssembler.forData( - engine.getData(), structure, new IrisPosition(originX, baseY, originZ), IrisModuleHost.hostLog()); - StructureAssemblyResult assembly = assembler.assemble(rng); + Assembly assembly = provider.assemble(pack, structureId, new BlockPosition(originX, baseY, originZ), rng) + .orElseThrow(); if (!requirePlacementOutput(placement, selectedKey, cx, cz, assembly.hasOutput(), "runtime assembly produced " + assembly.status() + ": " + assembly.detail())) { return null; } - KList pieces = new KList<>(assembly.pieces()); + StructureStamp stamp = provider.stamp(pack, structureId).orElseThrow(); + KList pieces = new KList<>(assembly.pieces()); pieces = alignCavePieces(pieces, placement, baseY); - pieces = alignSurfacePieces(pieces, placement, structure, baseY); + pieces = alignSurfacePieces(pieces, placement, stamp, baseY); if (!requirePlacementOutput(placement, selectedKey, cx, cz, pieces != null && !pieces.isEmpty(), "surface alignment produced no pieces")) { return null; } - boolean exactY = hasExactY(placement, structure, pieces); + boolean exactY = hasExactY(placement, stamp, pieces); - int worldMin = engine.getMinHeight() + 1; - int worldMax = engine.getMinHeight() + engine.getHeight() - 1; + int worldMin = world.minWorldY() + 1; + int worldMax = world.minWorldY() + StructureWorld.height(world) - 1; if (exactY) { Integer verticalShift = resolveVerticalShift(pieces, placement, baseY, worldMin, worldMax); if (!requirePlacementOutput(placement, selectedKey, cx, cz, verticalShift != null, @@ -558,7 +551,7 @@ public final class IrisStructureLocator { } if (placement.isAnchoredUnderground() && !placement.resolvedAnchor().isCave()) { Integer burialShift = resolveUndergroundBurialShift( - engine, pieces, placement, baseY, worldMin, worldMax); + world, pieces, placement, baseY, worldMin, worldMax); if (!requirePlacementOutput(placement, selectedKey, cx, cz, burialShift != null, "assembled pieces and carving envelope cannot remain fully buried beneath terrain")) { return null; @@ -569,7 +562,7 @@ public final class IrisStructureLocator { } } - long configuredRadius = (long) Math.max(1, structure.getMaxSizeChunks()) * 16L; + long configuredRadius = (long) Math.max(1, provider.reachChunks(pack, structureId).orElse(1)) * 16L; int structureRadius = (int) Math.min(Integer.MAX_VALUE, configuredRadius); boolean withinBounds = fitsHorizontalBounds(pieces, originX, originZ, structureRadius) && (!exactY || fitsVerticalBounds(pieces, worldMin, worldMax)); @@ -577,7 +570,33 @@ public final class IrisStructureLocator { "assembled pieces exceed the configured structure or world bounds")) { return null; } - return new ResolvedPlacement(placement, selectedKey, structure, pieces, rng, originX, baseY, originZ, exactY); + return new ResolvedPlacement(placement, selectedKey, stamp, pieces, rng, originX, baseY, originZ, exactY); + } + + /** + * The first provider of {@link StructureAssembly} among the modules of the engine's pack that knows {@code structure}; + * null when none does. + */ + public static StructureAssembly providerOf(PackWorld world, ResourceId structure) { + return providerOf(world.services(StructureAssembly.class), world.resources(), structure); + } + + /** The first of {@code providers} that knows {@code structure} in {@code pack}; null when none does. */ + public static StructureAssembly providerOf(List providers, PackResources pack, ResourceId structure) { + for (StructureAssembly provider : providers) { + if (provider.knows(pack, structure)) { + return provider; + } + } + return null; + } + + /** How the pieces of the pack structure {@code key} are stamped; null when no module knows the structure. */ + public static StructureStamp stampOf(PackWorld world, String key) { + PackResources pack = world.resources(); + ResourceId structure = pack.idOf(key); + StructureAssembly provider = providerOf(world, structure); + return provider == null ? null : provider.stamp(pack, structure).orElse(null); } public static boolean requirePlacementOutput(StructurePlacement placement, String structureKey, @@ -599,7 +618,7 @@ public final class IrisStructureLocator { + ". Native generation is suppressed and will not be used as a fallback"); } - static boolean fitsWorldBounds(KList pieces, int worldMin, int worldMax, + static boolean fitsWorldBounds(KList pieces, int worldMin, int worldMax, int originX, int originZ, int structureRadius) { int[] bounds = computeBounds(pieces); if (bounds == null) { @@ -609,25 +628,24 @@ public final class IrisStructureLocator { && fitsHorizontalBounds(bounds, originX, originZ, structureRadius); } - private static ResolvedStart resolveInChunk(Engine engine, String key, int cx, int cz) { - IrisData data = engine.getData(); + private static ResolvedStart resolveInChunk(PackWorld world, String key, int cx, int cz) { String normalizedKey = normalize(key); - if (hasNativePlacement(engine, key)) { - for (NativeStartPlanner.Plan plan : NativeStartPlanner.plansAt(engine, cx, cz)) { + if (hasNativePlacement(world, key)) { + for (NativeStartPlanner.Plan plan : NativeStartPlanner.plansAt(world, cx, cz)) { if (normalize(plan.source().structure()).equals(normalizedKey)) { return new ResolvedStart(cx << 4, plan.baseY(), cz << 4); } } } - KList placements = StructurePlacementScope.placementsAt(engine, cx, cz); + List placements = StructurePlacementScope.placementsAt(world, cx, cz); for (StructurePlacement placement : placements) { - if (!matches(placement, key, data)) { + if (!matches(placement, key, world)) { continue; } if (placement.hasNativeStructures()) { continue; } - ResolvedPlacement resolved = resolvePlacement(engine, placement, cx, cz); + ResolvedPlacement resolved = resolvePlacement(world, placement, cx, cz); if (resolved != null && matchesResolved(resolved, key)) { return new ResolvedStart( resolved.originX(), resolved.baseY(), resolved.originZ()); @@ -637,7 +655,7 @@ public final class IrisStructureLocator { } private static PlacementAnchor resolveAnchor( - Engine engine, + PackWorld world, StructurePlacement placement, int chunkX, int chunkZ, @@ -647,25 +665,25 @@ public final class IrisStructureLocator { ) { if (placement.resolvedAnchor().isCave()) { StructureCaveAnchorResolver.Anchor caveAnchor = StructureCaveAnchorResolver.resolve( - engine, placement, chunkX, chunkZ, rng.nextParallelRNG(CAVE_ANCHOR_DOMAIN)); + world, placement, chunkX, chunkZ, rng.nextParallelRNG(CAVE_ANCHOR_DOMAIN)); return caveAnchor == null ? null : new PlacementAnchor(caveAnchor.x(), caveAnchor.y(), caveAnchor.z()); } - Integer baseY = resolveBaseY(engine, placement, originX, originZ, rng); + Integer baseY = resolveBaseY(world, placement, originX, originZ, rng); return baseY == null ? null : new PlacementAnchor(originX, baseY, originZ); } - private static Integer resolveBaseY(Engine engine, StructurePlacement placement, int originX, int originZ, RNG rng) { - int worldMin = engine.getMinHeight() + 1; - int worldMax = engine.getMinHeight() + engine.getHeight() - 1; + private static Integer resolveBaseY(PackWorld world, StructurePlacement placement, int originX, int originZ, RNG rng) { + int worldMin = world.minWorldY() + 1; + int worldMax = world.minWorldY() + StructureWorld.height(world) - 1; if (worldMin > worldMax) { return null; } if (!placement.underwater() - && NativeStartPlanner.isSubmerged(engine, originX, originZ)) { + && NativeStartPlanner.isSubmerged(world, originX, originZ)) { return null; } if (placement.resolvedAnchor() == StructureAnchorMode.SURFACE) { - int surfaceY = engine.getHeight(originX, originZ, true) + engine.getMinHeight(); + int surfaceY = StructureWorld.highest(world, originX, originZ); return surfaceY < placement.minHeight() || surfaceY > placement.maxHeight() ? null : surfaceY; } int bandMin = Math.max(worldMin, Math.min(placement.minHeight(), placement.maxHeight())); @@ -676,7 +694,7 @@ public final class IrisStructureLocator { return randomInclusive(rng, bandMin, bandMax); } - static Integer resolveVerticalShift(KList pieces, StructurePlacement placement, + static Integer resolveVerticalShift(KList pieces, StructurePlacement placement, int baseY, int worldMin, int worldMax) { int[] bounds = computeBounds(pieces); if (bounds == null) { @@ -701,11 +719,11 @@ public final class IrisStructureLocator { return 0; } - static Integer resolveUndergroundBurialShift(Engine engine, KList pieces, + static Integer resolveUndergroundBurialShift(PackWorld world, KList pieces, StructurePlacement placement, int baseY, int worldMin, int worldMax) { int[] bounds = computeBounds(pieces); - if (engine == null || bounds == null || placement == null || !placement.isAnchoredUnderground() + if (world == null || bounds == null || placement == null || !placement.isAnchoredUnderground() || placement.resolvedAnchor().isCave()) { return null; } @@ -729,11 +747,10 @@ public final class IrisStructureLocator { return null; } - Long2IntOpenHashMap surfaceHeights = new Long2IntOpenHashMap(); - surfaceHeights.defaultReturnValue(Integer.MIN_VALUE); + ColumnHeights surfaceHeights = new ColumnHeights(Integer.MIN_VALUE); if (bore || forceCarve && carveShape == StructureCarveShape.BOX) { maximumShift = resolveBurialEnvelopeShift( - engine, + world, bounds[0] - sideExtension, bounds[3] + sideExtension, bounds[2] - sideExtension, @@ -746,14 +763,14 @@ public final class IrisStructureLocator { return null; } } else { - for (PlacedStructurePiece piece : pieces) { + for (AssembledPiece piece : pieces) { maximumShift = resolveBurialEnvelopeShift( - engine, - piece.getMinX() - sideExtension, - piece.getMaxX() + sideExtension, - piece.getMinZ() - sideExtension, - piece.getMaxZ() + sideExtension, - piece.getMaxY() + topExtension, + world, + piece.minX() - sideExtension, + piece.maxX() + sideExtension, + piece.minZ() - sideExtension, + piece.maxZ() + sideExtension, + piece.maxY() + topExtension, maximumShift, surfaceHeights ); @@ -765,9 +782,9 @@ public final class IrisStructureLocator { return minimumShift > maximumShift ? null : maximumShift; } - private static int resolveBurialEnvelopeShift(Engine engine, int minX, int maxX, int minZ, int maxZ, + private static int resolveBurialEnvelopeShift(PackWorld world, int minX, int maxX, int minZ, int maxZ, int envelopeTopY, int maximumShift, - Long2IntOpenHashMap surfaceHeights) { + ColumnHeights surfaceHeights) { for (int x = minX; x <= maxX; x++) { for (int z = minZ; z <= maxZ; z++) { long columnKey = ((long) x << 32) ^ (z & 0xffffffffL); @@ -776,7 +793,7 @@ public final class IrisStructureLocator { if (surfaceHeights.size() >= MAX_BURIAL_COLUMNS) { return Integer.MIN_VALUE; } - surfaceY = engine.getHeight(x, z, true) + engine.getMinHeight(); + surfaceY = StructureWorld.highest(world, x, z); surfaceHeights.put(columnKey, surfaceY); } int allowedTopY = surfaceY - UNDERGROUND_SURFACE_CLEARANCE; @@ -793,8 +810,8 @@ public final class IrisStructureLocator { return placement.structures().get(rng.nextInt(placement.structures().size())); } - static KList alignCavePieces( - KList pieces, + static KList alignCavePieces( + KList pieces, StructurePlacement placement, int anchorY ) { @@ -815,24 +832,24 @@ public final class IrisStructureLocator { return shiftPieces(pieces, anchorY - targetY); } - private static KList alignSurfacePieces(KList pieces, + private static KList alignSurfacePieces(KList pieces, StructurePlacement placement, - IrisStructure structure, int baseY) { + StructureStamp stamp, int baseY) { if (placement.isAnchoredUnderground() || pieces.size() <= 1 - || structure.getPlaceMode().placeMode().has(PlaceTrait.FREE_HEIGHT)) { + || stamp.placeMode().placeMode().has(PlaceTrait.FREE_HEIGHT)) { return pieces; } int[] bounds = computeBounds(pieces); return bounds == null ? pieces : shiftPieces(pieces, baseY - bounds[1]); } - static boolean hasExactY(StructurePlacement placement, IrisStructure structure, - KList pieces) { + static boolean hasExactY(StructurePlacement placement, StructureStamp stamp, + KList pieces) { return placement.isAnchoredUnderground() || pieces.size() > 1 - || structure.getPlaceMode().placeMode().has(PlaceTrait.FREE_HEIGHT); + || stamp.placeMode().placeMode().has(PlaceTrait.FREE_HEIGHT); } - private static boolean fitsVerticalBounds(KList pieces, int worldMin, int worldMax) { + private static boolean fitsVerticalBounds(KList pieces, int worldMin, int worldMax) { int[] bounds = computeBounds(pieces); return bounds != null && fitsVerticalBounds(bounds, worldMin, worldMax); } @@ -841,7 +858,7 @@ public final class IrisStructureLocator { return bounds[1] >= worldMin && bounds[4] <= worldMax; } - private static boolean fitsHorizontalBounds(KList pieces, int originX, int originZ, + private static boolean fitsHorizontalBounds(KList pieces, int originX, int originZ, int structureRadius) { int[] bounds = computeBounds(pieces); return bounds != null && fitsHorizontalBounds(bounds, originX, originZ, structureRadius); @@ -852,18 +869,15 @@ public final class IrisStructureLocator { && bounds[2] >= originZ - structureRadius && bounds[5] <= originZ + structureRadius; } - private static KList shiftPieces(KList pieces, int shiftY) { - KList shifted = new KList<>(); - for (PlacedStructurePiece piece : pieces) { - shifted.add(new PlacedStructurePiece( - piece.getPiece(), piece.getObject(), piece.getX(), piece.getY() + shiftY, piece.getZ(), piece.getRotation(), - piece.getMinX(), piece.getMinY() + shiftY, piece.getMinZ(), - piece.getMaxX(), piece.getMaxY() + shiftY, piece.getMaxZ())); + private static KList shiftPieces(KList pieces, int shiftY) { + KList shifted = new KList<>(); + for (AssembledPiece piece : pieces) { + shifted.add(piece.shiftedUp(shiftY)); } return shifted; } - private static int[] computeBounds(KList pieces) { + private static int[] computeBounds(KList pieces) { if (pieces == null || pieces.isEmpty()) { return null; } @@ -873,13 +887,13 @@ public final class IrisStructureLocator { int maxX = Integer.MIN_VALUE; int maxY = Integer.MIN_VALUE; int maxZ = Integer.MIN_VALUE; - for (PlacedStructurePiece piece : pieces) { - minX = Math.min(minX, piece.getMinX()); - minY = Math.min(minY, piece.getMinY()); - minZ = Math.min(minZ, piece.getMinZ()); - maxX = Math.max(maxX, piece.getMaxX()); - maxY = Math.max(maxY, piece.getMaxY()); - maxZ = Math.max(maxZ, piece.getMaxZ()); + for (AssembledPiece piece : pieces) { + minX = Math.min(minX, piece.minX()); + minY = Math.min(minY, piece.minY()); + minZ = Math.min(minZ, piece.minZ()); + maxX = Math.max(maxX, piece.maxX()); + maxY = Math.max(maxY, piece.maxY()); + maxZ = Math.max(maxZ, piece.maxZ()); } return new int[]{minX, minY, minZ, maxX, maxY, maxZ}; } @@ -891,13 +905,13 @@ public final class IrisStructureLocator { return minimum + rng.nextInt((maximum - minimum) + 1); } - private static PlacementCatalog collectPlacementCatalog(Engine engine, String key) { + private static PlacementCatalog collectPlacementCatalog(PackWorld world, String key) { Set randomSpread = new LinkedHashSet<>(); List concentricRings = new ArrayList<>(); boolean hasDensity = false; - for (StructurePlacement placement : index(engine).placements) { - if (!isSearchablePlacement(engine, placement) - || !matches(placement, key, engine.getData())) { + for (StructurePlacement placement : index(world).placements) { + if (!isSearchablePlacement(world, placement) + || !matches(placement, key, world)) { continue; } if (placement.distribution() == StructureDistribution.RANDOM_SPREAD) { @@ -913,22 +927,22 @@ public final class IrisStructureLocator { return new PlacementCatalog(List.copyOf(randomSpread), List.copyOf(concentricRings), hasDensity); } - static boolean isSearchableDensityPlacement(Engine engine, StructurePlacement placement) { + static boolean isSearchableDensityPlacement(PackWorld world, StructurePlacement placement) { return placement != null && placement.distribution() == StructureDistribution.DENSITY - && isSearchablePlacement(engine, placement); + && isSearchablePlacement(world, placement); } - static boolean isSearchablePlacement(Engine engine, StructurePlacement placement) { - if (engine == null || placement == null || engine.getHeight() <= 0) { + static boolean isSearchablePlacement(PackWorld world, StructurePlacement placement) { + if (world == null || placement == null || StructureWorld.height(world) <= 0) { return false; } if (placement.distribution() == StructureDistribution.DENSITY && !(placement.density() > 0.0)) { return false; } - long worldMin = (long) engine.getMinHeight() + (placement.isAnchoredUnderground() ? 1L : 0L); - long worldMax = (long) engine.getMinHeight() + engine.getHeight() + long worldMin = (long) world.minWorldY() + (placement.isAnchoredUnderground() ? 1L : 0L); + long worldMax = (long) world.minWorldY() + StructureWorld.height(world) - (placement.resolvedAnchor().isCave() ? 2L : 1L); if (worldMin > worldMax) { return false; @@ -1016,8 +1030,8 @@ public final class IrisStructureLocator { private record PlacementAnchor(int x, int y, int z) { } - private static boolean matches(StructurePlacement placement, String key, IrisData data) { - if (placement == null || key == null || data == null) { + private static boolean matches(StructurePlacement placement, String key, PackWorld world) { + if (placement == null || key == null || world == null) { return false; } String normalizedKey = normalize(key); @@ -1030,13 +1044,12 @@ public final class IrisStructureLocator { if (structureKey == null || structureKey.isBlank()) { continue; } - IrisStructure structure = StructureResources.structure(data.getPackResources(), structureKey); - if (structure == null) { + StructureStamp stamp = stampOf(world, structureKey); + if (stamp == null) { continue; } if (normalize(structureKey).equals(normalizedKey) - || normalize(structure.getLoadKey()).equals(normalizedKey) - || normalize(structure.getVanillaSource()).equals(normalizedKey)) { + || normalize(stamp.vanillaSource()).equals(normalizedKey)) { return true; } } @@ -1046,41 +1059,36 @@ public final class IrisStructureLocator { static boolean matchesResolved(ResolvedPlacement resolved, String key) { String normalizedKey = normalize(key); return normalize(resolved.structureKey()).equals(normalizedKey) - || normalize(resolved.structure().getLoadKey()).equals(normalizedKey) - || normalize(resolved.structure().getVanillaSource()).equals(normalizedKey); + || normalize(resolved.stamp().vanillaSource()).equals(normalizedKey); } private static String normalize(String key) { return key == null ? "" : key.toLowerCase(Locale.ROOT); } - private static PlacementIndex index(Engine engine) { - if (engine == null) { + private static PlacementIndex index(PackWorld world) { + if (world == null) { return EMPTY_INDEX; } - if (engine.getData() == null || engine.getDimension() == null) { - throw new IllegalStateException("Iris structure index requires a fully bound engine and dimension"); - } - return engine.getGeneration().state(PlacementIndex.class, IrisStructureLocator::build); + return world.state(PlacementIndex.class, IrisStructureLocator::build); } - private static LocatableIndex locatableIndex(Engine engine) { - if (engine == null) { + private static LocatableIndex locatableIndex(PackWorld world) { + if (world == null) { return EMPTY_LOCATABLE_INDEX; } - return engine.getGeneration().state(LocatableIndex.class, IrisStructureLocator::buildLocatableIndex); + return world.state(LocatableIndex.class, IrisStructureLocator::buildLocatableIndex); } - private static LocatableIndex buildLocatableIndex(Engine engine) { - IrisData data = engine.getData(); + private static LocatableIndex buildLocatableIndex(PackWorld world) { Set keys = new LinkedHashSet<>(); Set normalizedKeys = new LinkedHashSet<>(); Set editableKeys = new LinkedHashSet<>(); Set normalizedEditableKeys = new LinkedHashSet<>(); Set nativeKeys = new LinkedHashSet<>(); Set normalizedNativeKeys = new LinkedHashSet<>(); - for (StructurePlacement placement : index(engine).placements) { - if (!isSearchablePlacement(engine, placement)) { + for (StructurePlacement placement : index(world).placements) { + if (!isSearchablePlacement(world, placement)) { continue; } if (placement.hasNativeStructures()) { @@ -1091,17 +1099,15 @@ public final class IrisStructureLocator { continue; } for (String structureKey : placement.structures()) { - IrisStructure structure = StructureResources.structure(data.getPackResources(), structureKey); - if (structure == null) { + StructureStamp stamp = stampOf(world, structureKey); + if (stamp == null) { throw new IllegalStateException( "Iris structure placement references missing structure '" + structureKey + "'"); } addLocatableKey(structureKey, keys, normalizedKeys); addLocatableKey(structureKey, editableKeys, normalizedEditableKeys); - addLocatableKey(structure.getLoadKey(), keys, normalizedKeys); - addLocatableKey(structure.getLoadKey(), editableKeys, normalizedEditableKeys); - addLocatableKey(structure.getVanillaSource(), keys, normalizedKeys); - addLocatableKey(structure.getVanillaSource(), editableKeys, normalizedEditableKeys); + addLocatableKey(stamp.vanillaSource(), keys, normalizedKeys); + addLocatableKey(stamp.vanillaSource(), editableKeys, normalizedEditableKeys); } } return new LocatableIndex( @@ -1122,31 +1128,15 @@ public final class IrisStructureLocator { normalizedKeys.add(normalize(trimmedKey)); } - private static PlacementIndex build(Engine engine) { - IrisData data = engine.getData(); - ModuleLog log = IrisModuleHost.hostLog(); + private static PlacementIndex build(PackWorld world) { Set loadKeys = new LinkedHashSet<>(); Set normalizedLoadKeys = new LinkedHashSet<>(); Set vanillaAliases = new LinkedHashSet<>(); Set suppressedVanillaSources = new LinkedHashSet<>(); List placements = new ArrayList<>(); - collect(StructurePlacementScope.placementsOf(engine.getDimension()), data, log, loadKeys, normalizedLoadKeys, vanillaAliases, - suppressedVanillaSources, placements, true); - KList regions = engine.getDimension().getAllRegions(engine); - if (regions != null) { - for (IrisRegion region : regions) { - collect(StructurePlacementScope.placementsOf(region), data, log, - loadKeys, normalizedLoadKeys, vanillaAliases, - suppressedVanillaSources, placements, false); - } - } - KList biomes = engine.getDimension().getReachableBiomes(engine); - if (biomes != null) { - for (IrisBiome biome : biomes) { - collect(StructurePlacementScope.placementsOf(biome), data, log, - loadKeys, normalizedLoadKeys, vanillaAliases, - suppressedVanillaSources, placements, false); - } + for (var declared : world.settings().declared(StructurePlacementSettings.class)) { + collect(declared.value().placements(), world, loadKeys, normalizedLoadKeys, vanillaAliases, + suppressedVanillaSources, placements, declared.level() == Level.DIMENSION); } return new PlacementIndex( Collections.unmodifiableSet(loadKeys), @@ -1172,7 +1162,7 @@ public final class IrisStructureLocator { return Collections.unmodifiableSet(nativeKeys); } - private static void collect(List source, IrisData data, ModuleLog log, Set loadKeys, + private static void collect(List source, PackWorld world, Set loadKeys, Set normalizedLoadKeys, Set vanillaAliases, Set suppressedVanillaSources, List placements, boolean allowNativeSuppression) { @@ -1209,8 +1199,8 @@ public final class IrisStructureLocator { ? "REPLACE_SOURCE contains a blank Iris structure reference" : "Iris structure placement contains a blank structure reference"); } - IrisStructure structure = StructureResources.structure(data.getPackResources(), structureKey); - if (structure == null) { + StructureStamp stamp = stampOf(world, structureKey); + if (stamp == null) { throw new IllegalStateException((replacesNative ? "REPLACE_SOURCE references missing Iris structure '" : "Iris structure placement references missing structure '") @@ -1218,20 +1208,18 @@ public final class IrisStructureLocator { } loadKeys.add(structureKey); normalizedLoadKeys.add(normalize(structureKey)); - if (structure.getLoadKey() != null && !structure.getLoadKey().isBlank()) { - loadKeys.add(structure.getLoadKey()); - normalizedLoadKeys.add(normalize(structure.getLoadKey())); - } - if (structure.getVanillaSource() != null && !structure.getVanillaSource().isBlank()) { - vanillaAliases.add(normalize(structure.getVanillaSource())); + if (!stamp.vanillaSource().isBlank()) { + vanillaAliases.add(normalize(stamp.vanillaSource())); } if (replacesNative) { - String vanillaSource = structure.getVanillaSource(); - if (vanillaSource == null || !NAMESPACED_RESOURCE_KEY.matcher(vanillaSource).matches()) { + String vanillaSource = stamp.vanillaSource(); + if (!NAMESPACED_RESOURCE_KEY.matcher(vanillaSource).matches()) { throw new IllegalStateException("REPLACE_SOURCE structure '" + structureKey + "' must declare a valid namespaced vanillaSource"); } - if (!StructureGraphCatalog.guaranteesRuntimeOutput(data, structure, log)) { + PackResources pack = world.resources(); + ResourceId structureId = pack.idOf(structureKey); + if (providerOf(world, structureId).viability(pack, structureId) != Viability.GUARANTEED) { throw new IllegalStateException("REPLACE_SOURCE structure '" + structureKey + "' is not runtime-viable; native generation will not be used as a fallback"); } @@ -1242,8 +1230,8 @@ public final class IrisStructureLocator { } } - public record ResolvedPlacement(StructurePlacement placement, String structureKey, IrisStructure structure, - KList pieces, RNG rng, + public record ResolvedPlacement(StructurePlacement placement, String structureKey, StructureStamp stamp, + KList pieces, RNG rng, int originX, int baseY, int originZ, boolean exactY) { } diff --git a/core/src/main/java/art/arcane/iris/engine/framework/PlacedStructurePiece.java b/module/src/main/java/art/arcane/iris/engine/framework/PlacedStructurePiece.java similarity index 84% rename from core/src/main/java/art/arcane/iris/engine/framework/PlacedStructurePiece.java rename to module/src/main/java/art/arcane/iris/engine/framework/PlacedStructurePiece.java index d66d35dfb..400f09d62 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/PlacedStructurePiece.java +++ b/module/src/main/java/art/arcane/iris/engine/framework/PlacedStructurePiece.java @@ -18,9 +18,9 @@ package art.arcane.iris.engine.framework; +import art.arcane.iris.engine.framework.structure.ObjectFrame; +import art.arcane.iris.engine.framework.structure.assembly.PieceTurn; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.ObjectTurn; import lombok.AllArgsConstructor; import lombok.Data; @@ -28,11 +28,14 @@ import lombok.Data; @AllArgsConstructor public class PlacedStructurePiece { private final IrisJigsawPiece piece; - private final IrisObject object; + /** The pack key of the piece's object. */ + private final String objectKey; + /** The declared size of the piece's object. */ + private final ObjectFrame object; private final int x; private final int y; private final int z; - private final ObjectTurn rotation; + private final PieceTurn rotation; private final int minX; private final int minY; private final int minZ; diff --git a/core/src/main/java/art/arcane/iris/engine/framework/StructureAssembler.java b/module/src/main/java/art/arcane/iris/engine/framework/StructureAssembler.java similarity index 83% rename from core/src/main/java/art/arcane/iris/engine/framework/StructureAssembler.java rename to module/src/main/java/art/arcane/iris/engine/framework/StructureAssembler.java index b44736e56..0a8e4528e 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/StructureAssembler.java +++ b/module/src/main/java/art/arcane/iris/engine/framework/StructureAssembler.java @@ -18,8 +18,9 @@ package art.arcane.iris.engine.framework; -import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.structure.CompiledStructureGraph; +import art.arcane.iris.engine.framework.structure.ObjectFrame; +import art.arcane.iris.engine.framework.structure.assembly.PieceTurn; import art.arcane.iris.engine.framework.structure.JigsawPoolSelection; import art.arcane.iris.engine.framework.structure.PlanarJigsawWorkcellResolver; import art.arcane.iris.engine.framework.structure.StructureAssemblyResult; @@ -29,7 +30,7 @@ import art.arcane.iris.engine.framework.structure.StructureGraphCompilation; import art.arcane.iris.engine.framework.structure.StructureGraphCompiler; import art.arcane.iris.engine.framework.structure.StructureGraphDiagnostic; import art.arcane.iris.engine.framework.structure.StructureGraphResolver; -import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawMode; @@ -37,15 +38,14 @@ 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 art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.ObjectTurn; -import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; import com.volmit.ModuleLog; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.PackResources; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; @@ -79,9 +79,9 @@ public final class StructureAssembler { this.resolver = options.resolver(); this.graph = options.graph(); this.structure = options.structure(); - this.originX = options.origin().getX(); - this.originY = options.origin().getY(); - this.originZ = options.origin().getZ(); + this.originX = options.origin().x(); + this.originY = options.origin().y(); + this.originZ = options.origin().z(); this.planarWorkcells = this.structure.resolvedMode() == IrisJigsawMode.PLANAR_JIGSAW ? PlanarJigsawWorkcellResolver.resolve(this.structure) : Map.of(); @@ -90,23 +90,25 @@ public final class StructureAssembler { ? this.structure.getMaxSizeChunks() * 16 : 0; } - public static StructureAssembler forData(IrisData data, IrisStructure structure, IrisPosition origin, ModuleLog log) { - IrisData activeData = Objects.requireNonNull(data, "Structure assembly data must not be null"); + /** An assembler of {@code structure}, the pack's structure {@code structureKey}, from {@code origin}. */ + public static StructureAssembler forPack(PackResources pack, String structureKey, IrisStructure structure, BlockPosition origin, + ModuleLog log) { + PackResources activePack = Objects.requireNonNull(pack, "Structure assembly pack must not be null"); IrisStructure activeStructure = Objects.requireNonNull( structure, "Structure assembly structure must not be null"); - return forCompilation(StructureGraphCatalog.compile(activeData, activeStructure, log), origin); + return forCompilation(StructureGraphCatalog.compile(activePack, structureKey, activeStructure, log), origin); } - public static StructureAssembler forResolver(StructureGraphResolver resolver, IrisStructure structure, - IrisPosition origin) { + public static StructureAssembler forResolver(String structureKey, StructureGraphResolver resolver, IrisStructure structure, + BlockPosition origin) { StructureGraphResolver activeResolver = Objects.requireNonNull( resolver, "Structure assembly resolver must not be null"); IrisStructure activeStructure = Objects.requireNonNull( structure, "Structure assembly structure must not be null"); - return forCompilation(StructureGraphCompiler.compile(activeStructure, activeResolver), origin); + return forCompilation(StructureGraphCompiler.compile(structureKey, activeStructure, activeResolver), origin); } - public static StructureAssembler forCompilation(StructureGraphCompilation compilation, IrisPosition origin) { + public static StructureAssembler forCompilation(StructureGraphCompilation compilation, BlockPosition origin) { StructureGraphCompilation activeCompilation = Objects.requireNonNull( compilation, "Structure graph compilation must not be null"); if (activeCompilation.hasErrors()) { @@ -120,17 +122,17 @@ public final class StructureAssembler { public StructureAssemblyResult assemble(RNG rng) { Objects.requireNonNull(rng, "Structure assembly RNG must not be null"); if (radius == 0) { - throw new IllegalStateException("Structure '" + structure.getLoadKey() + throw new IllegalStateException("Structure '" + graph.getStructureKey() + "' has maxSizeChunks outside 1.." + MAX_SIZE_CHUNKS); } if (structure.getMaxDepth() < 1 || structure.getMaxDepth() > MAX_DEPTH) { - throw new IllegalStateException("Structure '" + structure.getLoadKey() + throw new IllegalStateException("Structure '" + graph.getStructureKey() + "' has maxDepth outside 1.." + MAX_DEPTH); } String startPoolKey = normalize(structure.getStartPool()); IrisJigsawPool startPool = resolver.loadPool(startPoolKey); if (startPool == null || startPool.getPieces() == null || startPool.getPieces().isEmpty()) { - throw new IllegalStateException("Structure '" + structure.getLoadKey() + throw new IllegalStateException("Structure '" + graph.getStructureKey() + "' has no resolvable start pool '" + startPoolKey + "'"); } @@ -160,7 +162,7 @@ public final class StructureAssembler { } IrisJigsawPieceEntry startEntry = weightedPick(startEntries, rng); if (startEntry == null) { - throw new IllegalStateException("Structure '" + structure.getLoadKey() + throw new IllegalStateException("Structure '" + graph.getStructureKey() + "' start pool has no positively weighted entry"); } if (startEntry.isEmpty()) { @@ -171,23 +173,23 @@ public final class StructureAssembler { String startPieceKey = normalize(startEntry.getPiece()); IrisJigsawPiece startPiece = resolver.loadPiece(startPieceKey); if (startPiece == null) { - throw new IllegalStateException("Structure '" + structure.getLoadKey() + throw new IllegalStateException("Structure '" + graph.getStructureKey() + "' start pool references missing piece '" + startPieceKey + "'"); } String startObjectKey = normalize(startPiece.getObject()); - IrisObject startObject = resolver.loadObject(startObjectKey); + ObjectFrame startObject = resolver.loadObject(startObjectKey); if (startObject == null) { - throw new IllegalStateException("Structure '" + structure.getLoadKey() + throw new IllegalStateException("Structure '" + graph.getStructureKey() + "' start piece references missing object '" + startObjectKey + "'"); } if (startPiece.getConnectors() == null) { - throw new IllegalStateException("Structure '" + structure.getLoadKey() + throw new IllegalStateException("Structure '" + graph.getStructureKey() + "' start piece has no connector list"); } int startRotY = startPiece.isRotatable() ? Y_DEGREES[rng.i(Y_DEGREES.length)] : 0; - ObjectTurn startRot = ObjectTurn.of(0, startRotY, 0); - PlacedStructurePiece start = build(startPiece, startObject, originX, originY, originZ, startRot); + PieceTurn startRot = PieceTurn.aroundY(startRotY); + PlacedStructurePiece start = build(startPiece, startObjectKey, startObject, originX, originY, originZ, startRot); placed.add(start); registerPlacedPiece(consumedConnectors, start, null); incrementPlacement(placementCounts, startPieceKey); @@ -216,7 +218,7 @@ public final class StructureAssembler { IrisJigsawPool pool = resolver.loadPool(connector.pool); if (pool == null) { - throw new IllegalStateException("Structure '" + structure.getLoadKey() + throw new IllegalStateException("Structure '" + graph.getStructureKey() + "' references missing connector pool '" + connector.pool + "'"); } @@ -380,7 +382,7 @@ public final class StructureAssembler { if (objectKey.isEmpty()) { throw assemblyFailure("piece '" + pieceName + "' has no object key"); } - IrisObject object = resolver.loadObject(objectKey); + ObjectFrame object = resolver.loadObject(objectKey); if (object == null) { throw assemblyFailure("piece '" + pieceName + "' references missing object '" + objectKey + "'"); @@ -404,27 +406,27 @@ public final class StructureAssembler { continue; } - IrisDirection needed = connector.facing.reverse(); + JigsawDirection needed = connector.facing.reverse(); int[] rotations = piece.isRotatable() ? rotationCandidates(connector.joint, rng) : NO_ROTATION; for (int yDeg : rotations) { - ObjectTurn rot = ObjectTurn.of(0, yDeg, 0); - IrisDirection rotatedFace = rot.rotate(cb.getDirection()); + PieceTurn rot = PieceTurn.aroundY(yDeg); + JigsawDirection rotatedFace = rotate(rot, cb.getDirection()); if (rotatedFace != needed) { continue; } - if (connector.joint == JigsawJoint.ALIGNED && rot.rotate(cb.getTop()) != connector.top) { + if (connector.joint == JigsawJoint.ALIGNED && rotate(rot, cb.getTop()) != connector.top) { continue; } - IrisPosition rcr = connectorOffset(object, cb, rot); + BlockPosition rcr = connectorOffset(object, cb, rot); int wcx = connector.wx + connector.facing.x(); int wcy = connector.wy + connector.facing.y(); int wcz = connector.wz + connector.facing.z(); - int px = wcx - rcr.getX(); - int py = wcy - rcr.getY(); - int pz = wcz - rcr.getZ(); + int px = wcx - rcr.x(); + int py = wcy - rcr.y(); + int pz = wcz - rcr.z(); - PlacedStructurePiece candidate = build(piece, object, px, py, pz, rot); + PlacedStructurePiece candidate = build(piece, objectKey, object, px, py, pz, rot); if (!withinRadius(candidate) || collides(placed, candidate)) { continue; } @@ -527,7 +529,7 @@ public final class StructureAssembler { || isMatched(matchedExisting, existingPiece, existingConnector)) { continue; } - IrisPosition target = connectorTarget(existingPiece, existingConnector); + BlockPosition target = connectorTarget(existingPiece, existingConnector); if (!contains(candidatePiece, target)) { continue; } @@ -556,7 +558,7 @@ public final class StructureAssembler { || normalize(candidateConnector.getPool()).isEmpty()) { continue; } - IrisPosition target = connectorTarget(candidatePiece, candidateConnector); + BlockPosition target = connectorTarget(candidatePiece, candidateConnector); PlacedStructurePiece occupied = containingPiece(placed, target); if (occupied == null) { continue; @@ -706,7 +708,8 @@ public final class StructureAssembler { if (piece == null || piece.getConnectors() == null) { continue; } - IrisObject object = resolver.loadObject(normalize(piece.getObject())); + String objectKey = normalize(piece.getObject()); + ObjectFrame object = resolver.loadObject(objectKey); if (object == null) { continue; } @@ -717,18 +720,19 @@ public final class StructureAssembler { } int[] rotations = piece.isRotatable() ? Y_DEGREES : NO_ROTATION; for (int yDegrees : rotations) { - ObjectTurn rotation = ObjectTurn.of(0, yDegrees, 0); - if (rotation.rotate(connector.getDirection()) != source.facing().reverse() + PieceTurn rotation = PieceTurn.aroundY(yDegrees); + if (rotate(rotation, connector.getDirection()) != source.facing().reverse() || source.joint() == JigsawJoint.ALIGNED - && rotation.rotate(connector.getTop()) != source.top()) { + && rotate(rotation, connector.getTop()) != source.top()) { continue; } - IrisPosition offset = connectorOffset(object, connector, rotation); - int logicalX = source.wx() + source.facing().x() - offset.getX(); - int logicalY = source.wy() + source.facing().y() - offset.getY(); - int logicalZ = source.wz() + source.facing().z() - offset.getZ(); + BlockPosition offset = connectorOffset(object, connector, rotation); + int logicalX = source.wx() + source.facing().x() - offset.x(); + int logicalY = source.wy() + source.facing().y() - offset.y(); + int logicalZ = source.wz() + source.facing().z() - offset.z(); PlacedStructurePiece reservation = build( piece, + objectKey, object, logicalX, logicalY, @@ -749,49 +753,49 @@ public final class StructureAssembler { PlacedStructurePiece targetPiece, Set unavailable ) { - IrisPosition target = connectorTarget(sourcePiece, sourceConnector); - IrisDirection sourceFacing = sourcePiece.getRotation().rotate(sourceConnector.getDirection()); - IrisDirection sourceTop = sourcePiece.getRotation().rotate(sourceConnector.getTop()); + BlockPosition target = connectorTarget(sourcePiece, sourceConnector); + JigsawDirection sourceFacing = rotate(sourcePiece.getRotation(), sourceConnector.getDirection()); + JigsawDirection sourceTop = rotate(sourcePiece.getRotation(), sourceConnector.getTop()); for (IrisJigsawConnector candidate : targetPiece.getPiece().getConnectors()) { if (unavailable.contains(candidate) || !Objects.equals(sourceConnector.getChannel(), candidate.getChannel()) || !Objects.equals(sourceConnector.getTargetName(), candidate.getName())) { continue; } - IrisPosition candidatePosition = connectorPosition(targetPiece, candidate); + BlockPosition candidatePosition = connectorPosition(targetPiece, candidate); if (!target.equals(candidatePosition) - || targetPiece.getRotation().rotate(candidate.getDirection()) != sourceFacing.reverse()) { + || rotate(targetPiece.getRotation(), candidate.getDirection()) != sourceFacing.reverse()) { continue; } if (sourceConnector.getJoint() != JigsawJoint.ALIGNED - || targetPiece.getRotation().rotate(candidate.getTop()) == sourceTop) { + || rotate(targetPiece.getRotation(), candidate.getTop()) == sourceTop) { return candidate; } } return null; } - private IrisPosition connectorPosition(PlacedStructurePiece piece, IrisJigsawConnector connector) { - IrisPosition center = logicalCenter(piece); - IrisPosition offset = connectorOffset(piece.getObject(), connector, piece.getRotation()); - return new IrisPosition( - center.getX() + offset.getX(), - center.getY() + offset.getY(), - center.getZ() + offset.getZ()); + private BlockPosition connectorPosition(PlacedStructurePiece piece, IrisJigsawConnector connector) { + BlockPosition center = logicalCenter(piece); + BlockPosition offset = connectorOffset(piece.getObject(), connector, piece.getRotation()); + return new BlockPosition( + center.x() + offset.x(), + center.y() + offset.y(), + center.z() + offset.z()); } - private IrisPosition connectorTarget(PlacedStructurePiece piece, IrisJigsawConnector connector) { - IrisPosition position = connectorPosition(piece, connector); - IrisDirection facing = piece.getRotation().rotate(connector.getDirection()); - return new IrisPosition( - position.getX() + facing.x(), - position.getY() + facing.y(), - position.getZ() + facing.z()); + private BlockPosition connectorTarget(PlacedStructurePiece piece, IrisJigsawConnector connector) { + BlockPosition position = connectorPosition(piece, connector); + JigsawDirection facing = rotate(piece.getRotation(), connector.getDirection()); + return new BlockPosition( + position.x() + facing.x(), + position.y() + facing.y(), + position.z() + facing.z()); } private PlacedStructurePiece containingPiece( KList pieces, - IrisPosition position + BlockPosition position ) { for (PlacedStructurePiece piece : pieces) { if (contains(piece, position)) { @@ -801,10 +805,10 @@ public final class StructureAssembler { return null; } - private boolean contains(PlacedStructurePiece piece, IrisPosition position) { - return position.getX() >= piece.getMinX() && position.getX() <= piece.getMaxX() - && position.getY() >= piece.getMinY() && position.getY() <= piece.getMaxY() - && position.getZ() >= piece.getMinZ() && position.getZ() <= piece.getMaxZ(); + private boolean contains(PlacedStructurePiece piece, BlockPosition position) { + return position.x() >= piece.getMinX() && position.x() <= piece.getMaxX() + && position.y() >= piece.getMinY() && position.y() <= piece.getMaxY() + && position.z() >= piece.getMinZ() && position.z() <= piece.getMaxZ(); } private boolean isMatched( @@ -824,24 +828,24 @@ public final class StructureAssembler { int targetY, int targetZ ) { - requireConnector(candidate, candidatePiece.getObject().getLoadKey()); + requireConnector(candidate, candidatePiece.getObjectKey()); if (!Objects.equals(source.channel(), candidate.getChannel()) || !Objects.equals(source.targetName(), candidate.getName())) { return false; } - IrisPosition rotated = connectorOffset( + BlockPosition rotated = connectorOffset( candidatePiece.getObject(), candidate, candidatePiece.getRotation()); - IrisPosition center = logicalCenter(candidatePiece); - if (center.getX() + rotated.getX() != targetX - || center.getY() + rotated.getY() != targetY - || center.getZ() + rotated.getZ() != targetZ) { + BlockPosition center = logicalCenter(candidatePiece); + if (center.x() + rotated.x() != targetX + || center.y() + rotated.y() != targetY + || center.z() + rotated.z() != targetZ) { return false; } - if (candidatePiece.getRotation().rotate(candidate.getDirection()) != source.facing().reverse()) { + if (rotate(candidatePiece.getRotation(), candidate.getDirection()) != source.facing().reverse()) { return false; } return source.joint() != JigsawJoint.ALIGNED - || candidatePiece.getRotation().rotate(candidate.getTop()) == source.top(); + || rotate(candidatePiece.getRotation(), candidate.getTop()) == source.top(); } private void registerPlacedPiece( @@ -890,15 +894,15 @@ public final class StructureAssembler { Deque pending, Map> openConnectors, PlacedStructurePiece p, - IrisObject object, int depth, int pieceDepth, IrisJigsawConnector skip, + ObjectFrame object, int depth, int pieceDepth, IrisJigsawConnector skip, int placementPriority) { if (p.getPiece().getConnectors() == null) { - throw assemblyFailure("placed piece for object '" + object.getLoadKey() + "' has no connector list"); + throw assemblyFailure("placed piece for object '" + p.getObjectKey() + "' has no connector list"); } List connectors = new ArrayList<>(); Map definitions = new IdentityHashMap<>(); for (IrisJigsawConnector con : orderedConnectors(p.getPiece().getConnectors(), skip)) { - requireConnector(con, object.getLoadKey()); + requireConnector(con, p.getObjectKey()); if (con.getPool() == null || con.getPool().isBlank()) { continue; } @@ -914,21 +918,21 @@ public final class StructureAssembler { private OpenConnector openConnector( PlacedStructurePiece piece, - IrisObject object, + ObjectFrame object, IrisJigsawConnector connector, int depth, int pieceDepth ) { - IrisPosition offset = connectorOffset(object, connector, piece.getRotation()); - IrisPosition center = logicalCenter(piece); + BlockPosition offset = connectorOffset(object, connector, piece.getRotation()); + BlockPosition center = logicalCenter(piece); return new OpenConnector( piece, connector, - center.getX() + offset.getX(), - center.getY() + offset.getY(), - center.getZ() + offset.getZ(), - piece.getRotation().rotate(connector.getDirection()), - piece.getRotation().rotate(connector.getTop()), + center.x() + offset.x(), + center.y() + offset.y(), + center.z() + offset.z(), + rotate(piece.getRotation(), connector.getDirection()), + rotate(piece.getRotation(), connector.getTop()), normalize(connector.getPool()), connector.getName(), connector.getTargetName(), @@ -968,29 +972,30 @@ public final class StructureAssembler { throw assemblyFailure("piece expansion queue was unexpectedly empty"); } - private PlacedStructurePiece build(IrisJigsawPiece piece, IrisObject object, int x, int y, int z, ObjectTurn rot) { - int width = Math.max(1, object.getW()); - int height = Math.max(1, object.getH()); - int depth = Math.max(1, object.getD()); + private PlacedStructurePiece build(IrisJigsawPiece piece, String objectKey, ObjectFrame object, int x, int y, int z, PieceTurn rot) { + int width = Math.max(1, object.width()); + int height = Math.max(1, object.height()); + int depth = Math.max(1, object.depth()); if (structure.resolvedMode() == IrisJigsawMode.PLANAR_JIGSAW) { - IrisPosition dimensions = rotatedDimensions(object, rot); - IrisPosition offset = planarPlacementOffset(object, rot); - int minX = x - dimensions.getX() / 2; - int minY = y - dimensions.getY() / 2; - int minZ = z - dimensions.getZ() / 2; + BlockPosition dimensions = rotatedDimensions(object, rot); + BlockPosition offset = planarPlacementOffset(object, rot); + int minX = x - dimensions.x() / 2; + int minY = y - dimensions.y() / 2; + int minZ = z - dimensions.z() / 2; return new PlacedStructurePiece( piece, + objectKey, object, - x + offset.getX(), - y + offset.getY(), - z + offset.getZ(), + x + offset.x(), + y + offset.y(), + z + offset.z(), rot, minX, minY, minZ, - minX + dimensions.getX() - 1, - minY + dimensions.getY() - 1, - minZ + dimensions.getZ() - 1); + minX + dimensions.x() - 1, + minY + dimensions.y() - 1, + minZ + dimensions.z() - 1); } int localMinX = -(width / 2); int localMinY = -(height / 2); @@ -998,15 +1003,15 @@ public final class StructureAssembler { int localMaxX = localMinX + width - 1; int localMaxY = localMinY + height - 1; int localMaxZ = localMinZ + depth - 1; - IrisPosition rotatedMin = rot.rotate(new IrisPosition(localMinX, localMinY, localMinZ)); - IrisPosition rotatedMax = rot.rotate(new IrisPosition(localMaxX, localMaxY, localMaxZ)); - int minX = Math.min(rotatedMin.getX(), rotatedMax.getX()); - int minY = Math.min(rotatedMin.getY(), rotatedMax.getY()); - int minZ = Math.min(rotatedMin.getZ(), rotatedMax.getZ()); - int maxX = Math.max(rotatedMin.getX(), rotatedMax.getX()); - int maxY = Math.max(rotatedMin.getY(), rotatedMax.getY()); - int maxZ = Math.max(rotatedMin.getZ(), rotatedMax.getZ()); - return new PlacedStructurePiece(piece, object, x, y, z, rot, + BlockPosition rotatedMin = rot.rotate(new BlockPosition(localMinX, localMinY, localMinZ)); + BlockPosition rotatedMax = rot.rotate(new BlockPosition(localMaxX, localMaxY, localMaxZ)); + int minX = Math.min(rotatedMin.x(), rotatedMax.x()); + int minY = Math.min(rotatedMin.y(), rotatedMax.y()); + int minZ = Math.min(rotatedMin.z(), rotatedMax.z()); + int maxX = Math.max(rotatedMin.x(), rotatedMax.x()); + int maxY = Math.max(rotatedMin.y(), rotatedMax.y()); + int maxZ = Math.max(rotatedMin.z(), rotatedMax.z()); + return new PlacedStructurePiece(piece, objectKey, object, x, y, z, rot, x + minX, y + minY, z + minZ, x + maxX, y + maxY, z + maxZ); } @@ -1041,70 +1046,74 @@ public final class StructureAssembler { return shuffled; } - private IrisPosition centerOf(IrisObject object) { - return new IrisPosition(object.getW() / 2, object.getH() / 2, object.getD() / 2); + private BlockPosition centerOf(ObjectFrame object) { + return object.center(); } - private IrisPosition connectorOffset( - IrisObject object, + private BlockPosition connectorOffset( + ObjectFrame object, IrisJigsawConnector connector, - ObjectTurn rotation + PieceTurn rotation ) { if (structure.resolvedMode() == IrisJigsawMode.PLANAR_JIGSAW) { - IrisPosition dimensions = rotatedDimensions(object, rotation); - IrisPosition position = IrisJigsawConnector.canonicalPlanarPosition( + BlockPosition dimensions = rotatedDimensions(object, rotation); + BlockPosition position = IrisJigsawConnector.canonicalPlanarPosition( dimensions, - rotation.rotate(connector.getDirection())); - return new IrisPosition( - position.getX() - dimensions.getX() / 2, - position.getY() - dimensions.getY() / 2, - position.getZ() - dimensions.getZ() / 2); + rotate(rotation, connector.getDirection())); + return new BlockPosition( + position.x() - dimensions.x() / 2, + position.y() - dimensions.y() / 2, + position.z() - dimensions.z() / 2); } - IrisPosition center = centerOf(object); - IrisPosition relative = new IrisPosition( - connector.getPosition().getX() - center.getX(), - connector.getPosition().getY() - center.getY(), - connector.getPosition().getZ() - center.getZ()); + BlockPosition center = centerOf(object); + BlockPosition relative = new BlockPosition( + connector.getPosition().x() - center.x(), + connector.getPosition().y() - center.y(), + connector.getPosition().z() - center.z()); return rotation.rotate(relative); } - private IrisPosition logicalCenter(PlacedStructurePiece piece) { + private BlockPosition logicalCenter(PlacedStructurePiece piece) { if (structure.resolvedMode() != IrisJigsawMode.PLANAR_JIGSAW) { - return new IrisPosition(piece.getX(), piece.getY(), piece.getZ()); + return new BlockPosition(piece.getX(), piece.getY(), piece.getZ()); } - IrisPosition offset = planarPlacementOffset(piece.getObject(), piece.getRotation()); - return new IrisPosition( - piece.getX() - offset.getX(), - piece.getY() - offset.getY(), - piece.getZ() - offset.getZ()); + BlockPosition offset = planarPlacementOffset(piece.getObject(), piece.getRotation()); + return new BlockPosition( + piece.getX() - offset.x(), + piece.getY() - offset.y(), + piece.getZ() - offset.z()); } - private IrisPosition rotatedDimensions(IrisObject object, ObjectTurn rotation) { - int width = Math.max(1, object.getW()); - int height = Math.max(1, object.getH()); - int depth = Math.max(1, object.getD()); + private BlockPosition rotatedDimensions(ObjectFrame object, PieceTurn rotation) { + int width = Math.max(1, object.width()); + int height = Math.max(1, object.height()); + int depth = Math.max(1, object.depth()); return quarterTurns(rotation) % 2 == 0 - ? new IrisPosition(width, height, depth) - : new IrisPosition(depth, height, width); + ? new BlockPosition(width, height, depth) + : new BlockPosition(depth, height, width); } - private IrisPosition planarPlacementOffset(IrisObject object, ObjectTurn rotation) { - int width = Math.max(1, object.getW()); - int depth = Math.max(1, object.getD()); + private BlockPosition planarPlacementOffset(ObjectFrame object, PieceTurn rotation) { + int width = Math.max(1, object.width()); + int depth = Math.max(1, object.depth()); return switch (quarterTurns(rotation)) { - case 0 -> new IrisPosition(); - case 1 -> new IrisPosition(0, 0, width % 2 == 0 ? -1 : 0); - case 2 -> new IrisPosition( + case 0 -> new BlockPosition(0, 0, 0); + case 1 -> new BlockPosition(0, 0, width % 2 == 0 ? -1 : 0); + case 2 -> new BlockPosition( width % 2 == 0 ? -1 : 0, 0, depth % 2 == 0 ? -1 : 0); - case 3 -> new IrisPosition(depth % 2 == 0 ? -1 : 0, 0, 0); + case 3 -> new BlockPosition(depth % 2 == 0 ? -1 : 0, 0, 0); default -> throw new IllegalStateException("Unsupported planar quarter-turn count"); }; } - private int quarterTurns(ObjectTurn rotation) { - return switch (rotation.rotate(IrisDirection.NORTH_NEGATIVE_Z)) { + private static JigsawDirection rotate(PieceTurn turn, JigsawDirection direction) { + return direction.turnedBy(turn.quarterTurns()); + } + + private int quarterTurns(PieceTurn rotation) { + return switch (rotate(rotation, JigsawDirection.NORTH_NEGATIVE_Z)) { case NORTH_NEGATIVE_Z -> 0; case WEST_NEGATIVE_X -> 1; case SOUTH_POSITIVE_Z -> 2; @@ -1280,7 +1289,7 @@ public final class StructureAssembler { } private IllegalStateException assemblyFailure(String detail) { - return new IllegalStateException("Structure '" + structure.getLoadKey() + "' assembly failed: " + detail); + return new IllegalStateException("Structure '" + graph.getStructureKey() + "' assembly failed: " + detail); } private static IllegalStateException invalidGraph(StructureGraphCompilation compilation) { @@ -1300,7 +1309,7 @@ public final class StructureAssembler { } private record OpenConnector(PlacedStructurePiece sourcePiece, IrisJigsawConnector sourceConnector, - int wx, int wy, int wz, IrisDirection facing, IrisDirection top, + int wx, int wy, int wz, JigsawDirection facing, JigsawDirection top, String pool, String name, String targetName, String channel, JigsawJoint joint, int depth, int pieceDepth, int placementPriority) { @@ -1347,7 +1356,7 @@ public final class StructureAssembler { private record AssemblyOptions(StructureGraphResolver resolver, CompiledStructureGraph graph, IrisStructure structure, - IrisPosition origin) { + BlockPosition origin) { private AssemblyOptions { Objects.requireNonNull(resolver, "Structure assembly resolver must not be null"); Objects.requireNonNull(graph, "Compiled structure graph must not be null"); diff --git a/core/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java b/module/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java similarity index 75% rename from core/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java rename to module/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java index 0f73ff88f..fb0f46a21 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java +++ b/module/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java @@ -1,16 +1,19 @@ package art.arcane.iris.engine.framework; import art.arcane.iris.builtin.carve.CaveLavaHeightSettings; -import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.builtin.structure.StructureAnchorMode; import art.arcane.iris.builtin.structure.StructurePlacement; +import art.arcane.iris.engine.framework.structure.StructureWorld; import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.matter.MatterCavern; +import com.volmit.mantle.CarvedVoid; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Objects; +import java.util.Optional; import java.util.function.IntPredicate; public final class StructureCaveAnchorResolver { @@ -19,22 +22,21 @@ public final class StructureCaveAnchorResolver { private static final int MAX_SCAN_STEP = 16; private static final int MAX_CLEARANCE = 64; private static final int MAX_GENERIC_CENTER_SEARCH = 4096; - private static final byte LIQUID_FORCED_AIR = 3; private StructureCaveAnchorResolver() { } - public static Anchor resolve(Engine engine, StructurePlacement placement, int chunkX, int chunkZ, RNG rng) { - Objects.requireNonNull(engine, "Cave structure anchor requires an engine"); + public static Anchor resolve(PackWorld world, StructurePlacement placement, int chunkX, int chunkZ, RNG rng) { + Objects.requireNonNull(world, "Cave structure anchor requires a world"); Objects.requireNonNull(placement, "Cave structure anchor requires a placement"); Objects.requireNonNull(rng, "Cave structure anchor requires a random source"); StructureAnchorMode mode = placement.resolvedAnchor(); - if (!mode.isCave() || engine.getMantle() == null || engine.getMantle().getMantle() == null) { + if (!mode.isCave() || world.running().isEmpty()) { return null; } - int worldMin = engine.getMinHeight() + 1; - int worldMax = engine.getMinHeight() + engine.getHeight() - 2; + int worldMin = world.minWorldY() + 1; + int worldMax = world.minWorldY() + StructureWorld.height(world) - 2; int minimumY = Math.max(worldMin, Math.min(placement.minHeight(), placement.maxHeight())); int maximumY = Math.min(worldMax, Math.max(placement.minHeight(), placement.maxHeight())); if (minimumY > maximumY) { @@ -51,7 +53,7 @@ public final class StructureCaveAnchorResolver { int blockX = chunkMinX + (candidateColumn & 15); int blockZ = chunkMinZ + (candidateColumn >>> 4); List anchors = anchorsInColumn( - engine, placement, mode, blockX, blockZ, + world, placement, mode, blockX, blockZ, minimumY, maximumY, scanStep, clearance); if (!anchors.isEmpty()) { return new Anchor(blockX, anchors.get(rng.nextInt(anchors.size())), blockZ); @@ -73,7 +75,7 @@ public final class StructureCaveAnchorResolver { } static List anchorsInColumn( - Engine engine, + PackWorld world, StructurePlacement placement, StructureAnchorMode mode, int blockX, @@ -85,20 +87,20 @@ public final class StructureCaveAnchorResolver { ) { if (mode == StructureAnchorMode.CAVE_CENTER) { return centerAnchorsInColumn( - engine, placement, blockX, blockZ, + world, placement, blockX, blockZ, minimumY, maximumY, scanStep, clearance); } List anchors = new ArrayList<>(); int step = Math.max(1, scanStep); for (int worldY = minimumY; worldY <= maximumY; worldY += step) { - int mantleY = toMantleY(worldY, engine.getMinHeight()); - if (!matchesGeometry(engine, mode, blockX, mantleY, blockZ, clearance)) { + int mantleY = toMantleY(worldY, world.minWorldY()); + if (!matchesGeometry(world, mode, blockX, mantleY, blockZ, clearance)) { continue; } - if (!matchesAnchorFluid(engine, placement, blockX, mantleY, blockZ)) { + if (!matchesAnchorFluid(world, placement, blockX, mantleY, blockZ)) { continue; } - if (!matchesBiome(engine, placement, blockX, mantleY, blockZ)) { + if (!matchesBiome(world, placement, blockX, mantleY, blockZ)) { continue; } anchors.add(worldY); @@ -107,7 +109,7 @@ public final class StructureCaveAnchorResolver { } private static List centerAnchorsInColumn( - Engine engine, + PackWorld world, StructurePlacement placement, int blockX, int blockZ, @@ -118,11 +120,11 @@ public final class StructureCaveAnchorResolver { ) { List anchors = new ArrayList<>(); int step = Math.max(1, scanStep); - int worldOffset = engine.getMinHeight(); + int worldOffset = world.minWorldY(); int minimumMantleY = 0; - int maximumMantleY = engine.getHeight() - 1; + int maximumMantleY = StructureWorld.height(world) - 1; int processedThroughWorldY = Integer.MIN_VALUE; - IntPredicate carved = y -> isCarved(engine, blockX, y, blockZ); + IntPredicate carved = y -> isCarved(world, blockX, y, blockZ); for (int worldY = minimumY; worldY <= maximumY; worldY += step) { if (worldY <= processedThroughWorldY) { continue; @@ -139,12 +141,12 @@ public final class StructureCaveAnchorResolver { } int lowerCenterWorldY = lower + Math.floorDiv(upper - lower, 2) + worldOffset; addCenterAnchor( - anchors, engine, placement, blockX, blockZ, + anchors, world, placement, blockX, blockZ, lowerCenterWorldY, minimumY, maximumY); int upperCenterWorldY = lower + Math.ceilDiv(upper - lower, 2) + worldOffset; if (upperCenterWorldY != lowerCenterWorldY) { addCenterAnchor( - anchors, engine, placement, blockX, blockZ, + anchors, world, placement, blockX, blockZ, upperCenterWorldY, minimumY, maximumY); } } @@ -153,7 +155,7 @@ public final class StructureCaveAnchorResolver { private static void addCenterAnchor( List anchors, - Engine engine, + PackWorld world, StructurePlacement placement, int blockX, int blockZ, @@ -164,25 +166,25 @@ public final class StructureCaveAnchorResolver { if (worldY < minimumY || worldY > maximumY) { return; } - int mantleY = toMantleY(worldY, engine.getMinHeight()); - if (matchesAnchorFluid(engine, placement, blockX, mantleY, blockZ) - && matchesBiome(engine, placement, blockX, mantleY, blockZ)) { + int mantleY = toMantleY(worldY, world.minWorldY()); + if (matchesAnchorFluid(world, placement, blockX, mantleY, blockZ) + && matchesBiome(world, placement, blockX, mantleY, blockZ)) { anchors.add(worldY); } } static boolean matchesGeometry( - Engine engine, + PackWorld world, StructureAnchorMode mode, int blockX, int mantleY, int blockZ, int clearance ) { - IntPredicate carved = y -> isCarved(engine, blockX, y, blockZ); + IntPredicate carved = y -> isCarved(world, blockX, y, blockZ); if (mode == StructureAnchorMode.CAVE_CENTER) { return matchesCenterGeometry( - carved, mantleY, Math.max(1, clearance), 0, engine.getHeight() - 1); + carved, mantleY, Math.max(1, clearance), 0, StructureWorld.height(world) - 1); } return matchesGeometry(carved, mode, mantleY, clearance); } @@ -272,49 +274,49 @@ public final class StructureCaveAnchorResolver { return true; } - private static boolean isCarved(Engine engine, int blockX, int mantleY, int blockZ) { - if (mantleY < 0 || mantleY >= engine.getHeight()) { + private static boolean isCarved(PackWorld world, int blockX, int mantleY, int blockZ) { + if (mantleY < 0 || mantleY >= StructureWorld.height(world)) { return false; } - MatterCavern cavern = cavernAt(engine, blockX, mantleY, blockZ); - return cavern != null && cavern.isCavern(); + return carvedAt(world, blockX, mantleY, blockZ).isPresent(); } private static boolean matchesAnchorFluid( - Engine engine, + PackWorld world, StructurePlacement placement, int blockX, int mantleY, int blockZ ) { - MatterCavern cavern = cavernAt(engine, blockX, mantleY, blockZ); + int lavaHeight = StructureWorld.running(world).settings().at(CaveLavaHeightSettings.class, blockX, blockZ) + .dimension().map(CaveLavaHeightSettings::height).orElse(CaveLavaHeightSettings.DEFAULT_HEIGHT); return acceptsAnchorFluid( placement.underwater(), - cavern, + carvedAt(world, blockX, mantleY, blockZ).orElse(null), mantleY, - engine.getDimension().getModuleSettings().find(CaveLavaHeightSettings.class).map(CaveLavaHeightSettings::height).orElse(CaveLavaHeightSettings.DEFAULT_HEIGHT)); + lavaHeight); } static boolean acceptsAnchorFluid( boolean underwater, - MatterCavern cavern, + CarvedVoid carved, int mantleY, int defaultLavaHeight ) { - if (cavern == null || !cavern.isCavern()) { + if (carved == null) { return false; } if (underwater) { return true; } - if (cavern.getLiquid() == LIQUID_FORCED_AIR) { + if (carved.fill() == CarvedVoid.Fill.AIR) { return true; } - return cavern.isAir() && mantleY > defaultLavaHeight; + return carved.fill() == CarvedVoid.Fill.OPEN && mantleY > defaultLavaHeight; } - private static MatterCavern cavernAt(Engine engine, int blockX, int mantleY, int blockZ) { - return engine.getMantle().getMantle().get(blockX, mantleY, blockZ, MatterCavern.class); + private static Optional carvedAt(PackWorld world, int blockX, int mantleY, int blockZ) { + return StructureWorld.running(world).carvedAt(blockX, mantleY, blockZ); } static int toMantleY(int worldY, int worldMinHeight) { @@ -322,7 +324,7 @@ public final class StructureCaveAnchorResolver { } private static boolean matchesBiome( - Engine engine, + PackWorld world, StructurePlacement placement, int blockX, int mantleY, @@ -331,11 +333,11 @@ public final class StructureCaveAnchorResolver { if (placement.caveBiomes().isEmpty()) { return true; } - IrisBiome biome = engine.getCaveOrMantleBiome(blockX, mantleY, blockZ); - if (biome == null || biome.getLoadKey() == null) { + Optional biome = caveOrCarvedBiome(world, blockX, mantleY, blockZ); + if (biome.isEmpty()) { return false; } - String actual = biome.getLoadKey().toLowerCase(Locale.ROOT); + String actual = StructureWorld.keyOf(world, biome.get()).toLowerCase(Locale.ROOT); for (String allowed : placement.caveBiomes()) { if (matchesBiomeKey(actual, allowed)) { return true; @@ -344,6 +346,15 @@ public final class StructureCaveAnchorResolver { return false; } + /** The biome the carver gave the void at the block, else the cave biome of the column at that height. */ + private static Optional caveOrCarvedBiome(PackWorld world, int blockX, int mantleY, int blockZ) { + Optional carvedBiome = carvedAt(world, blockX, mantleY, blockZ).flatMap(CarvedVoid::biome); + if (carvedBiome.isPresent()) { + return carvedBiome; + } + return StructureWorld.running(world).layout().caveBiome(blockX, mantleY, blockZ); + } + static boolean matchesBiomeKey(String actual, String allowed) { if (actual == null || actual.isBlank() || allowed == null || allowed.isBlank()) { return false; diff --git a/module/src/main/java/art/arcane/iris/engine/framework/StructurePlacementScope.java b/module/src/main/java/art/arcane/iris/engine/framework/StructurePlacementScope.java new file mode 100644 index 000000000..b5df5742c --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/StructurePlacementScope.java @@ -0,0 +1,121 @@ +package art.arcane.iris.engine.framework; + +import art.arcane.iris.builtin.structure.StructurePlacement; +import art.arcane.iris.builtin.structure.StructurePlacementSettings; +import art.arcane.iris.engine.framework.structure.StructureWorld; +import com.volmit.config.FeatureSettings; +import com.volmit.config.Level; +import com.volmit.config.SettingsStack; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; +import com.volmit.world.TerrainSampler; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +/** + * The structure placements that apply at a chunk: its biome's, its cave biome's cave-anchored ones, its region's and + * the dimension's. Each world keeps which of those levels declare placements at all, so chunks skip the biome and + * region lookups a pack never needs. + */ +public final class StructurePlacementScope { + private static final int CHUNK_CENTER_OFFSET_BLOCKS = 8; + + private StructurePlacementScope() { + } + + /** The placements {@code settings} declare; empty for none. */ + public static List placementsOf(Optional settings) { + return settings.map(StructurePlacementSettings::placements).orElse(List.of()); + } + + public static List placementsAt(PackWorld world, int chunkX, int chunkZ) { + RunningWorld running = StructureWorld.running(world); + int blockX = (chunkX << 4) + CHUNK_CENTER_OFFSET_BLOCKS; + int blockZ = (chunkZ << 4) + CHUNK_CENTER_OFFSET_BLOCKS; + List placements = new ArrayList<>(); + Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); + ScopeIndex index = world.state(ScopeIndex.class, StructurePlacementScope::buildScopeIndex); + if (index.declaresBelowDimension()) { + addColumnPlacements(placements, seen, running, index, blockX, blockZ); + } + addUnique(placements, seen, index.dimensionPlacements()); + return placements; + } + + private static void addColumnPlacements(List placements, Set seen, + RunningWorld running, ScopeIndex index, int blockX, int blockZ) { + SettingsStack declared = running.settings().at(StructurePlacementSettings.class, blockX, blockZ); + if (index.biome()) { + addUnique(placements, seen, placementsOf(declared.level(Level.BIOME))); + } + if (index.caveBiome()) { + addCaveUnique(placements, seen, placementsOf(caveBiomeSettings(running, blockX, blockZ))); + } + if (index.region()) { + addUnique(placements, seen, placementsOf(declared.level(Level.REGION))); + } + } + + private static Optional caveBiomeSettings(RunningWorld running, int blockX, int blockZ) { + TerrainSampler layout = running.layout(); + ResourceId surfaceBiome = layout.surfaceBiome(blockX, blockZ); + Optional caveBiome = layout.caveBiome(blockX, layout.bounds().minY(), blockZ) + .filter(cave -> !cave.equals(surfaceBiome)); + FeatureSettings settings = running.settings(); + return caveBiome.flatMap(cave -> settings.declaredBy(cave, StructurePlacementSettings.class)); + } + + private static ScopeIndex buildScopeIndex(PackWorld world) { + boolean biome = false; + boolean caveBiome = false; + boolean region = false; + List dimensionPlacements = List.of(); + for (var entry : world.settings().declared(StructurePlacementSettings.class)) { + List placements = entry.value().placements(); + if (placements.isEmpty()) { + continue; + } + switch (entry.level()) { + case BIOME -> { + biome = true; + caveBiome |= placements.stream().anyMatch(placement -> placement.resolvedAnchor().isCave()); + } + case REGION -> region = true; + case DIMENSION -> dimensionPlacements = placements; + default -> { + } + } + } + return new ScopeIndex(biome, caveBiome, region, dimensionPlacements); + } + + private static void addUnique(List destination, Set seen, + List source) { + for (StructurePlacement placement : source) { + if (placement != null && seen.add(placement)) { + destination.add(placement); + } + } + } + + private static void addCaveUnique(List destination, Set seen, + List source) { + for (StructurePlacement placement : source) { + if (placement != null && placement.resolvedAnchor().isCave() && seen.add(placement)) { + destination.add(placement); + } + } + } + + record ScopeIndex(boolean biome, boolean caveBiome, boolean region, List dimensionPlacements) { + boolean declaresBelowDimension() { + return biome || caveBiome || region; + } + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/ColumnHeights.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/ColumnHeights.java new file mode 100644 index 000000000..b49e4a203 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/ColumnHeights.java @@ -0,0 +1,173 @@ +/* + * 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; + +/** + * A height for each world column (keys packed from X and Z), which only grows. It visits its columns in the order the + * open-addressing table of the primitive map this replaces did, because the order in which a structure's foundations + * are written to the mantle is part of what a world generated: a column map of the standard library would order them + * differently. + */ +public final class ColumnHeights { + private static final long PHI = 0x9E3779B97F4A7C15L; + private static final int INITIAL_SLOTS = 32; + private static final float LOAD_FACTOR = 0.75f; + + /** Receives one column and its height. */ + @FunctionalInterface + public interface ColumnVisitor { + void visit(long column, int height); + } + + private final int missing; + private long[] keys = new long[INITIAL_SLOTS + 1]; + private int[] heights = new int[INITIAL_SLOTS + 1]; + private int slots = INITIAL_SLOTS; + private int mask = INITIAL_SLOTS - 1; + private int maxFill = maxFill(INITIAL_SLOTS); + private boolean hasColumnZero; + private int size; + + /** @param missing what {@link #get} answers for a column that has no height */ + public ColumnHeights(int missing) { + this.missing = missing; + } + + public int size() { + return size; + } + + public boolean containsKey(long column) { + if (column == 0L) { + return hasColumnZero; + } + int slot = slotOf(column); + while (keys[slot] != 0L) { + if (keys[slot] == column) { + return true; + } + slot = (slot + 1) & mask; + } + return false; + } + + public int get(long column) { + if (column == 0L) { + return hasColumnZero ? heights[slots] : missing; + } + int slot = slotOf(column); + while (keys[slot] != 0L) { + if (keys[slot] == column) { + return heights[slot]; + } + slot = (slot + 1) & mask; + } + return missing; + } + + public void put(long column, int height) { + if (column == 0L) { + if (!hasColumnZero) { + hasColumnZero = true; + grow(); + } + heights[slots] = height; + return; + } + int slot = slotOf(column); + while (keys[slot] != 0L) { + if (keys[slot] == column) { + heights[slot] = height; + return; + } + slot = (slot + 1) & mask; + } + keys[slot] = column; + heights[slot] = height; + grow(); + } + + /** Visits the columns in table order: the column 0 first, then the slots from the last to the first. */ + public void forEach(ColumnVisitor visitor) { + int remaining = size; + if (hasColumnZero) { + visitor.visit(0L, heights[slots]); + remaining--; + } + for (int slot = slots - 1; slot >= 0 && remaining > 0; slot--) { + if (keys[slot] != 0L) { + visitor.visit(keys[slot], heights[slot]); + remaining--; + } + } + } + + private void grow() { + if (size++ >= maxFill) { + rehash(slotsFor(size + 1)); + } + } + + private void rehash(int newSlots) { + long[] oldKeys = keys; + int[] oldHeights = heights; + int oldSlots = slots; + int newMask = newSlots - 1; + long[] newKeys = new long[newSlots + 1]; + int[] newHeights = new int[newSlots + 1]; + int source = oldSlots; + for (int remaining = size - (hasColumnZero ? 1 : 0); remaining-- != 0; ) { + while (oldKeys[--source] == 0L) { + continue; + } + int slot = hash(oldKeys[source], newMask); + while (newKeys[slot] != 0L) { + slot = (slot + 1) & newMask; + } + newKeys[slot] = oldKeys[source]; + newHeights[slot] = oldHeights[source]; + } + newHeights[newSlots] = oldHeights[oldSlots]; + keys = newKeys; + heights = newHeights; + slots = newSlots; + mask = newMask; + maxFill = maxFill(newSlots); + } + + private int slotOf(long column) { + return hash(column, mask); + } + + private static int hash(long column, int tableMask) { + long mixed = column * PHI; + mixed ^= mixed >>> 32; + return (int) (mixed ^ (mixed >>> 16)) & tableMask; + } + + private static int maxFill(int tableSlots) { + return Math.min((int) Math.ceil(tableSlots * LOAD_FACTOR), tableSlots - 1); + } + + /** The table size for {@code expected} entries: the next power of two of {@code expected / loadFactor}, at least 2. */ + private static int slotsFor(int expected) { + long wanted = Math.max(2L, (long) Math.ceil(expected / LOAD_FACTOR)); + return (int) Long.highestOneBit(wanted - 1) << 1; + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/CompiledStructureGraph.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/CompiledStructureGraph.java similarity index 75% rename from core/src/main/java/art/arcane/iris/engine/framework/structure/CompiledStructureGraph.java rename to module/src/main/java/art/arcane/iris/engine/framework/structure/CompiledStructureGraph.java index ec18f15a6..6ee2c34d1 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/CompiledStructureGraph.java +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/CompiledStructureGraph.java @@ -2,7 +2,6 @@ package art.arcane.iris.engine.framework.structure; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; -import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.structure.IrisStructure; import java.util.Collections; @@ -13,14 +12,18 @@ import java.util.Objects; import java.util.Set; public final class CompiledStructureGraph { + private static final String UNKEYED = ""; + + private final String structureKey; private final IrisStructure structure; private final Map pools; private final Map pieces; - private final Map objects; + private final Map objects; private final Set reachablePools; private final Set reachablePieces; private CompiledStructureGraph(Builder builder) { + structureKey = builder.structureKey; structure = builder.structure; pools = Collections.unmodifiableMap(new LinkedHashMap<>(builder.pools)); pieces = Collections.unmodifiableMap(new LinkedHashMap<>(builder.pieces)); @@ -29,17 +32,17 @@ public final class CompiledStructureGraph { reachablePieces = Collections.unmodifiableSet(new LinkedHashSet<>(builder.reachablePieces)); } - static Builder builder(IrisStructure structure) { - return new Builder(structure); + static Builder builder(String structureKey, IrisStructure structure) { + return new Builder(structureKey, structure); } public IrisStructure getStructure() { return structure; } + /** The pack key of the structure, or a placeholder when the graph was compiled for a structure without one. */ public String getStructureKey() { - String key = structure.getLoadKey(); - return key == null || key.isBlank() ? "" : key; + return structureKey == null || structureKey.isBlank() ? UNKEYED : structureKey; } public Map getPools() { @@ -50,7 +53,7 @@ public final class CompiledStructureGraph { return pieces; } - public Map getObjects() { + public Map getObjects() { return objects; } @@ -63,14 +66,16 @@ public final class CompiledStructureGraph { } static final class Builder { + private final String structureKey; private final IrisStructure structure; private final Map pools = new LinkedHashMap<>(); private final Map pieces = new LinkedHashMap<>(); - private final Map objects = new LinkedHashMap<>(); + private final Map objects = new LinkedHashMap<>(); private final Set reachablePools = new LinkedHashSet<>(); private final Set reachablePieces = new LinkedHashSet<>(); - private Builder(IrisStructure structure) { + private Builder(String structureKey, IrisStructure structure) { + this.structureKey = structureKey; this.structure = Objects.requireNonNull(structure); } @@ -82,7 +87,7 @@ public final class CompiledStructureGraph { return pieces; } - Map objects() { + Map objects() { return objects; } diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructuresValidation.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructuresValidation.java similarity index 100% rename from core/src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructuresValidation.java rename to module/src/main/java/art/arcane/iris/engine/framework/structure/ImportedStructuresValidation.java diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/IrisObjectFrameReader.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/IrisObjectFrameReader.java similarity index 97% rename from core/src/main/java/art/arcane/iris/engine/framework/structure/IrisObjectFrameReader.java rename to module/src/main/java/art/arcane/iris/engine/framework/structure/IrisObjectFrameReader.java index 38292bd5b..e8a486f81 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/IrisObjectFrameReader.java +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/IrisObjectFrameReader.java @@ -1,6 +1,5 @@ package art.arcane.iris.engine.framework.structure; -import art.arcane.iris.engine.object.prefab.IrisObject; import com.google.gson.JsonElement; import com.google.gson.JsonParser; @@ -23,7 +22,7 @@ public final class IrisObjectFrameReader { private IrisObjectFrameReader() { } - public static IrisObject readBounds(InputStream stream, String resourceName) throws IOException { + public static ObjectFrame readBounds(InputStream stream, String resourceName) throws IOException { String activeResourceName = resourceName == null || resourceName.isBlank() ? "" : resourceName; try { @@ -41,7 +40,7 @@ public final class IrisObjectFrameReader { } } - private static IrisObject readBounds(byte[] content, String resourceName) throws IOException { + private static ObjectFrame readBounds(byte[] content, String resourceName) throws IOException { ByteArrayInputStream bytes = new ByteArrayInputStream(content); DataInputStream input = new DataInputStream(bytes); int width = input.readInt(); @@ -88,7 +87,7 @@ public final class IrisObjectFrameReader { } int tileStart = content.length - bytes.available(); requireCompleteTileFraming(content, tileStart, tileCount, width, height, depth, resourceName); - return new IrisObject(width, height, depth); + return new ObjectFrame(width, height, depth); } private static void requireCompleteTileFraming( diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/JigsawPoolSelection.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/JigsawPoolSelection.java similarity index 100% rename from core/src/main/java/art/arcane/iris/engine/framework/structure/JigsawPoolSelection.java rename to module/src/main/java/art/arcane/iris/engine/framework/structure/JigsawPoolSelection.java diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/JigsawStructureAssembly.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/JigsawStructureAssembly.java new file mode 100644 index 000000000..887a86b96 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/JigsawStructureAssembly.java @@ -0,0 +1,118 @@ +/* + * 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.engine.framework.PlacedStructurePiece; +import art.arcane.iris.engine.framework.StructureAssembler; +import art.arcane.iris.engine.framework.structure.assembly.AssembledPiece; +import art.arcane.iris.engine.framework.structure.assembly.Assembly; +import art.arcane.iris.engine.framework.structure.assembly.StructureAssembly; +import art.arcane.iris.engine.framework.structure.assembly.StructureStamp; +import art.arcane.iris.engine.framework.structure.assembly.Viability; +import art.arcane.iris.engine.object.structure.IrisStructure; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.ModuleLog; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; + +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.OptionalInt; +import java.util.Set; + +/** + * How {@code iris:jigsaw} builds the structures of the pack's {@code structures} folder: it assembles them from their + * jigsaw pools and pieces ({@link StructureAssembler}) and tells the placement how they are stamped. It knows exactly the + * structures the pack has a structure file for. + */ +public final class JigsawStructureAssembly implements StructureAssembly { + private final ModuleLog log; + + public JigsawStructureAssembly(ModuleLog log) { + this.log = Objects.requireNonNull(log, "log"); + } + + @Override + public boolean knows(PackResources pack, ResourceId structure) { + return structureOf(pack, structure) != null; + } + + @Override + public Set structures(PackResources pack) { + Set known = new LinkedHashSet<>(); + for (String key : StructureResources.structureKeys(pack)) { + known.add(pack.idOf(key)); + } + return known; + } + + @Override + public OptionalInt reachChunks(PackResources pack, ResourceId structure) { + IrisStructure known = structureOf(pack, structure); + return known == null ? OptionalInt.empty() : OptionalInt.of(known.getMaxSizeChunks()); + } + + @Override + public Optional stamp(PackResources pack, ResourceId structure) { + IrisStructure known = structureOf(pack, structure); + if (known == null) { + return Optional.empty(); + } + List loot = known.getLoot() == null ? List.of() + : known.getLoot().stream().filter(table -> table != null && !table.isBlank()).toList(); + return Optional.of(new StructureStamp(known.getPlaceMode(), known.getEdit(), loot, + known.getVanillaSource() == null ? "" : known.getVanillaSource())); + } + + @Override + public Viability viability(PackResources pack, ResourceId structure) { + IrisStructure known = structureOf(pack, structure); + if (known == null) { + return Viability.NOT_VIABLE; + } + String key = structure.path(); + if (!StructureGraphCatalog.compile(pack, key, known, log).isAssemblyViable()) { + return Viability.NOT_VIABLE; + } + return StructureGraphCatalog.guaranteesRuntimeOutput(pack, key, known, log) ? Viability.GUARANTEED : Viability.VIABLE; + } + + @Override + public Optional assemble(PackResources pack, ResourceId structure, BlockPosition origin, RNG random) { + IrisStructure known = structureOf(pack, structure); + if (known == null) { + return Optional.empty(); + } + StructureAssemblyResult result = StructureAssembler.forPack(pack, structure.path(), known, origin, log).assemble(random); + return Optional.of(new Assembly(result.status(), result.detail(), result.pieces().stream() + .map(piece -> assembled(pack, piece)).toList())); + } + + private static AssembledPiece assembled(PackResources pack, PlacedStructurePiece piece) { + return new AssembledPiece(pack.idOf(piece.getObjectKey()), piece.getX(), piece.getY(), piece.getZ(), piece.getRotation(), + piece.getMinX(), piece.getMinY(), piece.getMinZ(), piece.getMaxX(), piece.getMaxY(), piece.getMaxZ()); + } + + private static IrisStructure structureOf(PackResources pack, ResourceId structure) { + return StructureResources.structure(pack, structure.path()); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/JigsawValidator.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/JigsawValidator.java new file mode 100644 index 000000000..b832e88df --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/JigsawValidator.java @@ -0,0 +1,59 @@ +/* + * 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 com.volmit.block.BlockRegistry; +import com.volmit.validation.Problem; +import com.volmit.validation.ValidationContext; +import com.volmit.validation.Validator; + +import java.io.File; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * Module {@code iris:jigsaw}'s check of a pack: every structure a dimension, region or biome places must assemble + * ({@link StructureGraphValidation}), a dimension that replaces a vanilla structure with an Iris one may only use + * structures that always assemble and fit ({@link NativeReplacementValidation}), and every structure, pool and piece + * names resources that exist ({@link StructureReferenceValidation}). Graph diagnostics keep their severity; everything + * else is an error, as when Iris's own pack validator ran these checks. + */ +public final class JigsawValidator implements Validator { + @Override + public void validate(ValidationContext pack) { + File packFolder = pack.settings().extension(File.class).orElse(null); + StructureGraphValidation.Validation graphs = packFolder == null + ? new StructureGraphValidation.Validation(List.of(), Set.of(), Map.of()) + : StructureGraphValidation.validate(pack.resources(), packFolder, StructureValidator.placedStructureKeys(pack)); + graphs.problems().forEach(pack::report); + Optional platformBlocks = pack.platform().map(platform -> pack.resources().blocks()); + reportUnlessAssemblyReported(pack, StructureReferenceValidation.validate(pack.resources(), platformBlocks), graphs.problems()); + NativeReplacementValidation.validate(packFolder, graphs.replacementOutputStructures(), graphs.sampledVerticalEnvelopes()) + .forEach(pack::report); + } + + /** 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); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/NativeReplacementValidation.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/NativeReplacementValidation.java similarity index 96% rename from core/src/main/java/art/arcane/iris/engine/framework/structure/NativeReplacementValidation.java rename to module/src/main/java/art/arcane/iris/engine/framework/structure/NativeReplacementValidation.java index befa246d1..db701981e 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/NativeReplacementValidation.java +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/NativeReplacementValidation.java @@ -20,7 +20,6 @@ package art.arcane.iris.engine.framework.structure; import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; -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; @@ -77,14 +76,14 @@ public final class NativeReplacementValidation { if (!resourceFolder.isDirectory()) { continue; } - List resourceFiles = PackValidationIo.listJsonRecursive(resourceFolder); + List resourceFiles = PackJsonFiles.listRecursive(resourceFolder); resourceFiles.sort(Comparator.comparing(File::getPath)); for (File resourceFile : resourceFiles) { - JSONObject resource = PackValidationIo.readJson(resourceFile); + JSONObject resource = PackJsonFiles.read(resourceFile); if (resource == null) { continue; } - String resourceKey = PackValidationIo.deriveKey(resourceFolder, resourceFile); + String resourceKey = PackJsonFiles.keyOf(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)); @@ -97,10 +96,10 @@ public final class NativeReplacementValidation { 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); + for (File structureFile : PackJsonFiles.listRecursive(structuresFolder)) { + JSONObject structure = PackJsonFiles.read(structureFile); if (structure != null) { - structures.put(PackValidationIo.deriveKey(structuresFolder, structureFile), structure); + structures.put(PackJsonFiles.keyOf(structuresFolder, structureFile), structure); } } return structures; diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/NativeStartPlanner.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/NativeStartPlanner.java similarity index 83% rename from core/src/main/java/art/arcane/iris/engine/framework/structure/NativeStartPlanner.java rename to module/src/main/java/art/arcane/iris/engine/framework/structure/NativeStartPlanner.java index c5f273b39..dd3f4d61f 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/NativeStartPlanner.java +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/NativeStartPlanner.java @@ -18,9 +18,9 @@ package art.arcane.iris.engine.framework.structure; -import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.StructurePlacementGrid; import art.arcane.iris.engine.framework.StructurePlacementScope; +import com.volmit.world.PackWorld; import art.arcane.iris.builtin.structure.StructureAnchorMode; import art.arcane.iris.builtin.structure.StructurePlacement; import art.arcane.iris.builtin.structure.NativeStructureSource; @@ -48,10 +48,10 @@ public final class NativeStartPlanner { public record Plan(StructurePlacement placement, NativeStructureSource source, int chunkX, int chunkZ, int baseY) { } - public static List plansAt(Engine engine, int chunkX, int chunkZ) { + public static List plansAt(PackWorld world, int chunkX, int chunkZ) { Map plansByStructure = new LinkedHashMap<>(); - for (StructurePlacement placement : StructurePlacementScope.placementsAt(engine, chunkX, chunkZ)) { - Plan plan = planAt(engine, placement, chunkX, chunkZ); + for (StructurePlacement placement : StructurePlacementScope.placementsAt(world, chunkX, chunkZ)) { + Plan plan = planAt(world, placement, chunkX, chunkZ); if (plan == null) { continue; } @@ -64,23 +64,20 @@ public final class NativeStartPlanner { return List.copyOf(plansByStructure.values()); } - public static Plan planAt(Engine engine, StructurePlacement placement, int chunkX, int chunkZ) { + public static Plan planAt(PackWorld world, StructurePlacement placement, int chunkX, int chunkZ) { validateBackend(placement); if (!placement.hasNativeStructures()) { return null; } - Engine activeEngine = Objects.requireNonNull(engine, "Native structure planner requires an engine"); - if (activeEngine.getSeedManager() == null) { - throw new IllegalStateException("Native structure planner requires a bound seed manager"); - } - long mantleSeed = activeEngine.getSeedManager().getMantle(); + Objects.requireNonNull(world, "Native structure planner requires a world"); + long mantleSeed = StructureWorld.placementSeed(world); if (!StructurePlacementGrid.startsInChunk(placement, chunkX, chunkZ, mantleSeed)) { return null; } RNG placementRng = StructurePlacementGrid.placementRng( placement, chunkX, chunkZ, mantleSeed).nextParallelRNG(NATIVE_SELECTION_DOMAIN); NativeStructureSource source = selectSource(placement.nativeStructures(), placementRng); - Integer baseY = resolveBaseY(activeEngine, placement, chunkX, chunkZ, placementRng); + Integer baseY = resolveBaseY(world, placement, chunkX, chunkZ, placementRng); if (baseY == null) { return null; } @@ -102,8 +99,8 @@ public final class NativeStartPlanner { } } - public static boolean isSubmerged(Engine engine, int blockX, int blockZ) { - return engine.getHeight(blockX, blockZ, true) < engine.getDimension().getFluidHeight(); + public static boolean isSubmerged(PackWorld world, int blockX, int blockZ) { + return StructureWorld.highestAboveBottom(world, blockX, blockZ) < StructureWorld.fluidHeightAboveBottom(world); } static NativeStructureSource selectSource(List sources, RNG rng) { @@ -133,20 +130,20 @@ public final class NativeStartPlanner { throw new IllegalStateException("Native structure source selection produced no result"); } - private static Integer resolveBaseY(Engine engine, StructurePlacement placement, + private static Integer resolveBaseY(PackWorld world, StructurePlacement placement, int chunkX, int chunkZ, RNG rng) { - int worldMin = engine.getMinHeight() + 1; - int worldMax = engine.getMinHeight() + engine.getHeight() - 1; + int worldMin = world.minWorldY() + 1; + int worldMax = world.minWorldY() + StructureWorld.height(world) - 1; if (worldMin > worldMax) { throw new IllegalStateException("Native structure placement has invalid world height bounds"); } int blockX = (chunkX << 4) + 8; int blockZ = (chunkZ << 4) + 8; - if (!placement.underwater() && isSubmerged(engine, blockX, blockZ)) { + if (!placement.underwater() && isSubmerged(world, blockX, blockZ)) { return null; } if (!placement.underground()) { - int surfaceY = engine.getHeight(blockX, blockZ, true) + engine.getMinHeight(); + int surfaceY = StructureWorld.highest(world, blockX, blockZ); if (surfaceY < placement.minHeight() || surfaceY > placement.maxHeight()) { return null; } diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/ObjectFrame.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/ObjectFrame.java new file mode 100644 index 000000000..bc51eddb2 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/ObjectFrame.java @@ -0,0 +1,37 @@ +/* + * 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 com.volmit.geometry.BlockBox; +import com.volmit.geometry.BlockPosition; + +/** + * The declared size of a pack object, which is all a jigsaw graph reads of it: connectors are placed against the size, and + * its center, which the object's offsets count from, is half the size. + */ +public record ObjectFrame(int width, int height, int depth) { + public static ObjectFrame of(BlockBox size) { + return new ObjectFrame(size.maxX() - size.minX(), size.maxY() - size.minY(), size.maxZ() - size.minZ()); + } + + /** The block the object's offsets count from, relative to its corner. */ + public BlockPosition center() { + return new BlockPosition(width / 2, height / 2, depth / 2); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/PackJsonFiles.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/PackJsonFiles.java new file mode 100644 index 000000000..1087006ae --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/PackJsonFiles.java @@ -0,0 +1,68 @@ +/* + * 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.volmlib.util.json.JSONObject; + +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.stream.Stream; + +/** The JSON files of a pack folder as written, for the checks that read values the host would have read as defaults. */ +final class PackJsonFiles { + private static final String JSON_EXTENSION = ".json"; + + private PackJsonFiles() { + } + + /** Every {@code .json} file below {@code root}, in no particular order; none when it cannot be listed. */ + static List listRecursive(File root) { + List files = new ArrayList<>(); + try (Stream walk = Files.walk(root.toPath())) { + walk.filter(Files::isRegularFile) + .filter(path -> path.getFileName().toString().endsWith(JSON_EXTENSION)) + .forEach(path -> files.add(path.toFile())); + } catch (Throwable ignored) { + return files; + } + return files; + } + + /** The JSON object {@code file} holds, or null when it cannot be read or parsed. */ + static JSONObject read(File file) { + try { + return new JSONObject(Files.readString(file.toPath(), StandardCharsets.UTF_8)); + } catch (java.io.IOException | RuntimeException unreadable) { + return null; + } + } + + /** The key of {@code file} in {@code folder}: its path below it without {@code .json}, or null for other files. */ + static String keyOf(File folder, File file) { + String relative = folder.toPath().relativize(file.toPath()).toString().replace(File.separatorChar, '/'); + if (!relative.endsWith(JSON_EXTENSION)) { + return null; + } + return relative.substring(0, relative.length() - JSON_EXTENSION.length()); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/PlanarJigsawWorkcellResolver.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/PlanarJigsawWorkcellResolver.java similarity index 82% rename from core/src/main/java/art/arcane/iris/engine/framework/structure/PlanarJigsawWorkcellResolver.java rename to module/src/main/java/art/arcane/iris/engine/framework/structure/PlanarJigsawWorkcellResolver.java index 53c3f8606..bcc85b7cb 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/PlanarJigsawWorkcellResolver.java +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/PlanarJigsawWorkcellResolver.java @@ -3,9 +3,8 @@ package art.arcane.iris.engine.framework.structure; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcell; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.structure.IrisStructure; +import com.volmit.geometry.BlockPosition; import java.util.Collections; import java.util.EnumMap; @@ -27,16 +26,16 @@ public final class PlanarJigsawWorkcellResolver { EnumMap resolved = new EnumMap<>(IrisJigsawWorkcellArchetype.class); if (source.getPlanarWorkcells() == null || source.getPlanarWorkcells().isEmpty()) { - IrisPosition fallback = source.getCellSize() == null - ? new IrisPosition(DEFAULT_SIZE, DEFAULT_SIZE, DEFAULT_SIZE) + BlockPosition fallback = source.getCellSize() == null + ? new BlockPosition(DEFAULT_SIZE, DEFAULT_SIZE, DEFAULT_SIZE) : source.getCellSize(); for (IrisJigsawWorkcellArchetype archetype : IrisJigsawWorkcellArchetype.values()) { ResolvedWorkcell workcell = new ResolvedWorkcell( archetype, "", - fallback.getX(), - fallback.getY(), - fallback.getZ(), + fallback.x(), + fallback.y(), + fallback.z(), true); validate(workcell); resolved.put(archetype, workcell); @@ -86,14 +85,14 @@ public final class PlanarJigsawWorkcellResolver { return workcell; } - public static IrisPosition canonicalDimensions(IrisJigsawPiece piece, IrisObject object) { + public static BlockPosition canonicalDimensions(IrisJigsawPiece piece, ObjectFrame object) { IrisJigsawPiece sourcePiece = Objects.requireNonNull(piece, "Planar jigsaw piece"); - IrisObject sourceObject = Objects.requireNonNull(object, "Planar jigsaw object"); + ObjectFrame sourceObject = Objects.requireNonNull(object, "Planar jigsaw object"); IrisJigsawWorkcellArchetype archetype = IrisJigsawWorkcellArchetype.fromPiece(sourcePiece); int quarterTurns = archetype.sourceToCanonicalQuarterTurns(sourcePiece); return Math.floorMod(quarterTurns, 2) == 0 - ? new IrisPosition(sourceObject.getW(), sourceObject.getH(), sourceObject.getD()) - : new IrisPosition(sourceObject.getD(), sourceObject.getH(), sourceObject.getW()); + ? new BlockPosition(sourceObject.width(), sourceObject.height(), sourceObject.depth()) + : new BlockPosition(sourceObject.depth(), sourceObject.height(), sourceObject.width()); } public record ResolvedWorkcell( @@ -109,13 +108,13 @@ public final class PlanarJigsawWorkcellResolver { displayName = normalizeDisplayName(displayName); } - public IrisPosition dimensions() { - return new IrisPosition(width, height, depth); + public BlockPosition dimensions() { + return new BlockPosition(width, height, depth); } - public boolean contains(IrisPosition dimensions) { - IrisPosition size = Objects.requireNonNull(dimensions, "Planar jigsaw object dimensions"); - return size.getX() <= width && size.getY() <= height && size.getZ() <= depth; + public boolean contains(BlockPosition dimensions) { + BlockPosition size = Objects.requireNonNull(dimensions, "Planar jigsaw object dimensions"); + return size.x() <= width && size.y() <= height && size.z() <= depth; } } diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureAssemblyResult.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureAssemblyResult.java similarity index 100% rename from core/src/main/java/art/arcane/iris/engine/framework/structure/StructureAssemblyResult.java rename to module/src/main/java/art/arcane/iris/engine/framework/structure/StructureAssemblyResult.java diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCatalog.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCatalog.java similarity index 50% rename from core/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCatalog.java rename to module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCatalog.java index e2ebb3068..7e9446aef 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCatalog.java +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCatalog.java @@ -1,70 +1,69 @@ 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.framework.StructureAssembler; -import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.volmlib.util.math.RNG; -import com.github.benmanes.caffeine.cache.Cache; -import com.github.benmanes.caffeine.cache.Caffeine; - import com.volmit.ModuleLog; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.PackResources; + +import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.Objects; +import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Compiled structure graphs, kept per resource snapshot of the pack: every reload of the pack's resources starts a new - * snapshot ({@link IrisData#getPackResources()}), so nothing stale is ever read and nothing is invalidated by hand. + * snapshot ({@link PackResources#snapshotId()}), so nothing stale is ever read and nothing is invalidated by hand. */ public final class StructureGraphCatalog { - private static final Cache> CACHE = - Caffeine.newBuilder().weakKeys().build(); - private static final Cache> RUNTIME_OUTPUT = - Caffeine.newBuilder().weakKeys().build(); + private static final Map> CACHE = + Collections.synchronizedMap(new WeakHashMap<>()); + private static final Map> RUNTIME_OUTPUT = + Collections.synchronizedMap(new WeakHashMap<>()); + private static final BlockPosition SAMPLE_ORIGIN = new BlockPosition(0, 64, 0); private static final List RUNTIME_SAMPLE_SEEDS = List.of( 0L, 1L, 2L, 3L, 5L, 8L, 13L, 21L, 34L, 55L, 89L, 144L, 233L, 377L, 610L, 987L); private StructureGraphCatalog() { } - public static StructureGraphCompilation compile(IrisData data, IrisStructure structure, ModuleLog log) { - IrisData activeData = Objects.requireNonNull(data); + /** The compilation of {@code structure}, the pack's structure {@code structureKey} (blank for one that is not in the pack, which is not kept). */ + public static StructureGraphCompilation compile(PackResources pack, String structureKey, IrisStructure structure, ModuleLog log) { + PackResources activePack = Objects.requireNonNull(pack); IrisStructure activeStructure = Objects.requireNonNull(structure); - String structureKey = activeStructure.getLoadKey(); if (structureKey == null || structureKey.isBlank()) { - return compileAndReport(activeData, activeStructure, log); + return compileAndReport(activePack, structureKey, activeStructure, log); } - ConcurrentMap catalog = CACHE.get( - activeData.getPackResources(), ignored -> new ConcurrentHashMap<>()); - return catalog.computeIfAbsent(structureKey, ignored -> compileAndReport(activeData, activeStructure, log)); + ConcurrentMap catalog = CACHE.computeIfAbsent( + activePack, ignored -> new ConcurrentHashMap<>()); + return catalog.computeIfAbsent(structureKey, ignored -> compileAndReport(activePack, structureKey, activeStructure, log)); } - public static boolean guaranteesRuntimeOutput(IrisData data, IrisStructure structure, ModuleLog log) { - IrisData activeData = Objects.requireNonNull(data); + public static boolean guaranteesRuntimeOutput(PackResources pack, String structureKey, IrisStructure structure, ModuleLog log) { + PackResources activePack = Objects.requireNonNull(pack); IrisStructure activeStructure = Objects.requireNonNull(structure); - if (!compile(activeData, activeStructure, log).guaranteesAssemblyOutput()) { + if (!compile(activePack, structureKey, activeStructure, log).guaranteesAssemblyOutput()) { return false; } - String structureKey = activeStructure.getLoadKey(); if (structureKey == null || structureKey.isBlank()) { - return sampleRuntimeAssembly(activeData, activeStructure, log); + return sampleRuntimeAssembly(activePack, structureKey, activeStructure, log); } - ConcurrentMap catalog = RUNTIME_OUTPUT.get( - activeData.getPackResources(), ignored -> new ConcurrentHashMap<>()); + ConcurrentMap catalog = RUNTIME_OUTPUT.computeIfAbsent( + activePack, ignored -> new ConcurrentHashMap<>()); return catalog.computeIfAbsent( - structureKey, ignored -> sampleRuntimeAssembly(activeData, activeStructure, log)); + structureKey, ignored -> sampleRuntimeAssembly(activePack, structureKey, activeStructure, log)); } - private static StructureGraphCompilation compileAndReport(IrisData data, IrisStructure structure, ModuleLog log) { + private static StructureGraphCompilation compileAndReport(PackResources pack, String structureKey, IrisStructure structure, ModuleLog log) { StructureGraphCompilation compilation = StructureGraphCompiler.compile( - structure, StructureGraphResolver.forData(data)); - String structureKey = structure.getLoadKey() == null || structure.getLoadKey().isBlank() - ? "" : structure.getLoadKey(); + structureKey, structure, StructureGraphResolver.forPack(pack)); + String reportedKey = structureKey == null || structureKey.isBlank() ? "" : structureKey; for (StructureGraphDiagnostic diagnostic : compilation.getDiagnostics()) { - String message = "[StructureGraph:" + structureKey + "] " + diagnostic.message(); + String message = "[StructureGraph:" + reportedKey + "] " + diagnostic.message(); if (diagnostic.severity() == StructureGraphDiagnostic.Severity.ERROR) { log.error(message, null); } else { @@ -72,17 +71,16 @@ public final class StructureGraphCatalog { } } if (!compilation.isAssemblyViable()) { - log.error("[StructureGraph:" + structureKey + log.error("[StructureGraph:" + reportedKey + "] Graph rejected because deterministic assembly did not complete.", null); } return compilation; } - private static boolean sampleRuntimeAssembly(IrisData data, IrisStructure structure, ModuleLog log) { + private static boolean sampleRuntimeAssembly(PackResources pack, String structureKey, IrisStructure structure, ModuleLog log) { for (long seed : RUNTIME_SAMPLE_SEEDS) { try { - StructureAssembler assembler = StructureAssembler.forData( - data, structure, new IrisPosition(0, 64, 0), log); + StructureAssembler assembler = StructureAssembler.forPack(pack, structureKey, structure, SAMPLE_ORIGIN, log); StructureAssemblyResult result = assembler.assemble(new RNG(seed)); if (!result.hasOutput()) { return false; diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompilation.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompilation.java similarity index 96% rename from core/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompilation.java rename to module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompilation.java index c58e4a977..b4e919ce9 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompilation.java +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompilation.java @@ -6,7 +6,6 @@ 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 art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet; -import art.arcane.iris.engine.object.prefab.IrisObject; import java.util.ArrayList; import java.util.Collections; @@ -96,7 +95,7 @@ public final class StructureGraphCompilation { if (piece == null || !JigsawPoolSelection.pieceEligible(piece, theme, 0, 0)) { continue; } - IrisObject object = graph.getObjects().get(normalize(piece.getObject())); + ObjectFrame object = graph.getObjects().get(normalize(piece.getObject())); if (object == null || !fitsStartRadius(object)) { return false; } @@ -185,9 +184,9 @@ public final class StructureGraphCompilation { return false; } - private boolean fitsStartRadius(IrisObject object) { + private boolean fitsStartRadius(ObjectFrame object) { long radius = (long) graph.getStructure().getMaxSizeChunks() * 16L; - return axisFitsRadius(object.getW(), radius) && axisFitsRadius(object.getD(), radius); + return axisFitsRadius(object.width(), radius) && axisFitsRadius(object.depth(), radius); } private List themes() { diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompiler.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompiler.java similarity index 94% rename from core/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompiler.java rename to module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompiler.java index 94585498e..ef67565f3 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompiler.java +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphCompiler.java @@ -2,7 +2,7 @@ package art.arcane.iris.engine.framework.structure; import art.arcane.iris.engine.framework.PlacedStructurePiece; import art.arcane.iris.engine.framework.StructureAssembler; -import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawCompatibility; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; @@ -13,12 +13,11 @@ import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceRules; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcellArchetype; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; +import com.volmit.geometry.BlockPosition; import java.util.ArrayDeque; import java.util.ArrayList; @@ -44,9 +43,10 @@ public final class StructureGraphCompiler { private StructureGraphCompiler() { } - public static StructureGraphCompilation compile(IrisStructure structure, StructureGraphResolver resolver) { + /** @param structureKey the pack key of {@code structure}, which the diagnostics name it by; blank for one without a key */ + public static StructureGraphCompilation compile(String structureKey, IrisStructure structure, StructureGraphResolver resolver) { CompilationState state = new CompilationState( - Objects.requireNonNull(structure), Objects.requireNonNull(resolver)); + structureKey, Objects.requireNonNull(structure), Objects.requireNonNull(resolver)); state.loadClosure(); state.detectFallbackCycles(); state.analyzeReachability(); @@ -66,6 +66,7 @@ public final class StructureGraphCompiler { } private static final class CompilationState { + private final String structureKey; private final IrisStructure structure; private final StructureGraphResolver resolver; private final CompiledStructureGraph.Builder graph; @@ -89,10 +90,11 @@ public final class StructureGraphCompiler { private Map planarWorkcells = Map.of(); - private CompilationState(IrisStructure structure, StructureGraphResolver resolver) { + private CompilationState(String structureKey, IrisStructure structure, StructureGraphResolver resolver) { + this.structureKey = structureKey; this.structure = structure; this.resolver = resolver; - this.graph = CompiledStructureGraph.builder(structure); + this.graph = CompiledStructureGraph.builder(structureKey, structure); } private void loadClosure() { @@ -145,7 +147,7 @@ public final class StructureGraphCompiler { } private void validateThemes() { - KList themeSets = structure.getThemeSets(); + List themeSets = structure.getThemeSets(); if (themeSets == null) { addDiagnostic(StructureGraphDiagnostic.Code.INVALID_THEME, "Structure '" + structureKey() + "' declares a null themeSets list.", @@ -235,7 +237,7 @@ public final class StructureGraphCompiler { graph.pools().put(key, pool); List entries = new ArrayList<>(); poolEntries.put(key, entries); - KList configuredEntries = pool.getPieces(); + List configuredEntries = pool.getPieces(); if (configuredEntries == null || configuredEntries.isEmpty()) { if (key.equals(normalize(structure.getStartPool()))) { addDiagnostic(StructureGraphDiagnostic.Code.EMPTY_START_POOL, @@ -339,13 +341,13 @@ public final class StructureGraphCompiler { } graph.pieces().put(key, piece); - IrisObject object = loadPieceObject(key, piece); + ObjectFrame object = loadPieceObject(key, piece); validatePieceMetadata(key, piece); scanConnectors(key, piece, object); } private void validatePieceMetadata(String pieceKey, IrisJigsawPiece piece) { - KList themes = piece.getThemes(); + List themes = piece.getThemes(); if (themes == null) { addDiagnostic(StructureGraphDiagnostic.Code.INVALID_THEME, "Jigsaw piece '" + pieceKey + "' declares a null themes list.", @@ -419,7 +421,7 @@ public final class StructureGraphCompiler { && !rules.isTerminal(); } - private IrisObject loadPieceObject(String pieceKey, IrisJigsawPiece piece) { + private ObjectFrame loadPieceObject(String pieceKey, IrisJigsawPiece piece) { String objectKey = normalize(piece.getObject()); pieceObjects.put(pieceKey, objectKey); if (objectKey.isEmpty()) { @@ -438,7 +440,7 @@ public final class StructureGraphCompiler { return graph.objects().get(objectKey); } - IrisObject object = resolver.loadObject(objectKey); + ObjectFrame object = resolver.loadObject(objectKey); if (object == null) { missingObjects.add(objectKey); addDiagnostic(StructureGraphDiagnostic.Code.MISSING_OBJECT, @@ -447,20 +449,20 @@ public final class StructureGraphCompiler { return null; } graph.objects().put(objectKey, object); - if (object.getW() < 1 || object.getH() < 1 || object.getD() < 1) { + if (object.width() < 1 || object.height() < 1 || object.depth() < 1) { addDiagnostic(StructureGraphDiagnostic.Code.INVALID_OBJECT_BOUNDS, "Object '" + objectKey + "' used by jigsaw piece '" + pieceKey - + "' has invalid dimensions " + object.getW() + "x" + object.getH() + "x" - + object.getD() + ".", + + "' has invalid dimensions " + object.width() + "x" + object.height() + "x" + + object.depth() + ".", "object-bounds:" + objectKey); } return object; } - private void scanConnectors(String pieceKey, IrisJigsawPiece piece, IrisObject object) { + private void scanConnectors(String pieceKey, IrisJigsawPiece piece, ObjectFrame object) { List references = new ArrayList<>(); pieceConnectors.put(pieceKey, references); - KList connectors = piece.getConnectors(); + List connectors = piece.getConnectors(); if (connectors == null) { addDiagnostic(StructureGraphDiagnostic.Code.INVALID_CONNECTOR, "Jigsaw piece '" + pieceKey + "' declares a null connector list.", @@ -552,7 +554,7 @@ public final class StructureGraphCompiler { } private boolean validatePlanarConnector(String pieceKey, int index, IrisJigsawConnector connector, - IrisObject object, boolean validDirection, boolean validTop, + ObjectFrame object, boolean validDirection, boolean validTop, boolean validPosition) { if (structure.resolvedMode() != IrisJigsawMode.PLANAR_JIGSAW) { return true; @@ -568,7 +570,7 @@ public final class StructureGraphCompiler { "connector:planar-direction:" + pieceKey + ":" + index); valid = false; } - if (validTop && connector.getTop() != IrisDirection.UP_POSITIVE_Y) { + if (validTop && connector.getTop() != JigsawDirection.UP_POSITIVE_Y) { addDiagnostic(StructureGraphDiagnostic.Code.INVALID_PLANAR_CONNECTOR, "Jigsaw piece '" + pieceKey + "' connectors[" + index + "] has top " + connector.getTop().name() @@ -582,8 +584,8 @@ public final class StructureGraphCompiler { || object == null || !validPosition) { return valid; } - IrisPosition objectSize = new IrisPosition(object.getW(), object.getH(), object.getD()); - IrisPosition expected = IrisJigsawConnector.canonicalPlanarPosition( + BlockPosition objectSize = new BlockPosition(object.width(), object.height(), object.depth()); + BlockPosition expected = IrisJigsawConnector.canonicalPlanarPosition( objectSize, connector.getDirection()); if (!expected.equals(connector.getPosition())) { addDiagnostic(StructureGraphDiagnostic.Code.INVALID_PLANAR_CONNECTOR, @@ -596,7 +598,7 @@ public final class StructureGraphCompiler { return valid; } - private String invalidPositionMessage(String pieceKey, int index, IrisPosition position, IrisObject object) { + private String invalidPositionMessage(String pieceKey, int index, BlockPosition position, ObjectFrame object) { if (position == null) { return "Jigsaw piece '" + pieceKey + "' connectors[" + index + "] does not declare a position."; @@ -606,17 +608,17 @@ public final class StructureGraphCompiler { + "] position " + position + " cannot be checked because its object is missing."; } return "Jigsaw piece '" + pieceKey + "' connectors[" + index + "] position " + position - + " is outside object bounds 0.." + (object.getW() - 1) + ", 0.." + (object.getH() - 1) - + ", 0.." + (object.getD() - 1) + "."; + + " is outside object bounds 0.." + (object.width() - 1) + ", 0.." + (object.height() - 1) + + ", 0.." + (object.depth() - 1) + "."; } - private boolean isValidPosition(IrisPosition position, IrisObject object) { + private boolean isValidPosition(BlockPosition position, ObjectFrame object) { if (position == null || object == null) { return false; } - return position.getX() >= 0 && position.getX() < object.getW() - && position.getY() >= 0 && position.getY() < object.getH() - && position.getZ() >= 0 && position.getZ() < object.getD(); + return position.x() >= 0 && position.x() < object.width() + && position.y() >= 0 && position.y() < object.height() + && position.z() >= 0 && position.z() < object.depth(); } private void detectFallbackCycles() { @@ -785,21 +787,21 @@ public final class StructureGraphCompiler { for (String pieceKey : graph.reachablePieces()) { IrisJigsawPiece piece = graph.pieces().get(pieceKey); String objectKey = pieceObjects.get(pieceKey); - IrisObject object = graph.objects().get(objectKey); + ObjectFrame object = graph.objects().get(objectKey); if (piece == null || object == null) { continue; } PlanarJigsawWorkcellResolver.ResolvedWorkcell workcell = PlanarJigsawWorkcellResolver.workcell(planarWorkcells, piece); - IrisPosition dimensions = PlanarJigsawWorkcellResolver.canonicalDimensions(piece, object); + BlockPosition dimensions = PlanarJigsawWorkcellResolver.canonicalDimensions(piece, object); if (workcell.contains(dimensions)) { continue; } addDiagnostic(StructureGraphDiagnostic.Code.INVALID_PLANAR_OBJECT_SIZE, "Object '" + objectKey + "' used by reachable planar piece '" + pieceKey - + "' is " + object.getW() + "x" + object.getH() + "x" + object.getD() - + " and canonically occupies " + dimensions.getX() + "x" + dimensions.getY() - + "x" + dimensions.getZ() + "; it does not fit " + workcell.archetype() + + "' is " + object.width() + "x" + object.height() + "x" + object.depth() + + " and canonically occupies " + dimensions.x() + "x" + dimensions.y() + + "x" + dimensions.z() + "; it does not fit " + workcell.archetype() + " workcell " + workcell.width() + "x" + workcell.height() + "x" + workcell.depth() + ".", "object:planar-size:" + pieceKey); @@ -985,9 +987,9 @@ public final class StructureGraphCompiler { return false; } - IrisDirection sourceDirection = rotateDirection( + JigsawDirection sourceDirection = rotateDirection( sourceConnector.getDirection(), source.rotation()); - IrisDirection candidateDirection = rotateDirection( + JigsawDirection candidateDirection = rotateDirection( candidateConnector.getDirection(), candidateRotation); if (candidateDirection != sourceDirection.reverse()) { return false; @@ -995,8 +997,8 @@ public final class StructureGraphCompiler { if (sourceConnector.getJoint() != JigsawJoint.ALIGNED) { return true; } - IrisDirection sourceTop = rotateDirection(sourceConnector.getTop(), source.rotation()); - IrisDirection candidateTop = rotateDirection(candidateConnector.getTop(), candidateRotation); + JigsawDirection sourceTop = rotateDirection(sourceConnector.getTop(), source.rotation()); + JigsawDirection candidateTop = rotateDirection(candidateConnector.getTop(), candidateRotation); return candidateTop == sourceTop; } @@ -1116,7 +1118,7 @@ public final class StructureGraphCompiler { for (long seed : ASSEMBLY_SEEDS) { try { StructureAssembler assembler = StructureAssembler.forCompilation( - compilation, new IrisPosition(0, 64, 0)); + compilation, new BlockPosition(0, 64, 0)); StructureAssemblyResult result = assembler.assemble(new RNG(seed)); List pieces = new ArrayList<>(result.pieces().size()); for (PlacedStructurePiece placed : result.pieces()) { @@ -1175,8 +1177,7 @@ public final class StructureGraphCompiler { } private String structureKey() { - String key = structure.getLoadKey(); - return key == null || key.isBlank() ? "" : key; + return structureKey == null || structureKey.isBlank() ? "" : structureKey; } } @@ -1188,18 +1189,18 @@ public final class StructureGraphCompiler { return piece.isRotatable() ? Y_ROTATIONS : NO_ROTATION; } - private static IrisDirection rotateDirection(IrisDirection direction, int degrees) { + private static JigsawDirection rotateDirection(JigsawDirection direction, int degrees) { if (direction.isVertical()) { return direction; } int turns = Math.floorMod(degrees, 360) / 90; - IrisDirection rotated = direction; + JigsawDirection rotated = direction; for (int turn = 0; turn < turns; turn++) { rotated = switch (rotated) { - case NORTH_NEGATIVE_Z -> IrisDirection.WEST_NEGATIVE_X; - case WEST_NEGATIVE_X -> IrisDirection.SOUTH_POSITIVE_Z; - case SOUTH_POSITIVE_Z -> IrisDirection.EAST_POSITIVE_X; - case EAST_POSITIVE_X -> IrisDirection.NORTH_NEGATIVE_Z; + case NORTH_NEGATIVE_Z -> JigsawDirection.WEST_NEGATIVE_X; + case WEST_NEGATIVE_X -> JigsawDirection.SOUTH_POSITIVE_Z; + case SOUTH_POSITIVE_Z -> JigsawDirection.EAST_POSITIVE_X; + case EAST_POSITIVE_X -> JigsawDirection.NORTH_NEGATIVE_Z; case UP_POSITIVE_Y, DOWN_NEGATIVE_Y -> rotated; }; } diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphResolver.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphResolver.java similarity index 60% rename from core/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphResolver.java rename to module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphResolver.java index 4e6fcc23c..8f08af3c2 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphResolver.java +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphResolver.java @@ -1,9 +1,8 @@ package art.arcane.iris.engine.framework.structure; -import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; -import art.arcane.iris.engine.object.prefab.IrisObject; +import com.volmit.resource.PackResources; import java.util.Objects; @@ -12,10 +11,11 @@ public interface StructureGraphResolver { IrisJigsawPiece loadPiece(String key); - IrisObject loadObject(String key); + /** The declared size of the pack object {@code key} names; null when the pack has none. */ + ObjectFrame loadObject(String key); - static StructureGraphResolver forData(IrisData data) { - return new IrisDataStructureGraphResolver(Objects.requireNonNull(data)); + static StructureGraphResolver forPack(PackResources pack) { + return new PackStructureGraphResolver(Objects.requireNonNull(pack)); } static StructureGraphResolver forCompiledGraph(CompiledStructureGraph graph) { @@ -23,26 +23,29 @@ public interface StructureGraphResolver { } } -final class IrisDataStructureGraphResolver implements StructureGraphResolver { - private final IrisData data; +final class PackStructureGraphResolver implements StructureGraphResolver { + private final PackResources pack; - IrisDataStructureGraphResolver(IrisData data) { - this.data = data; + PackStructureGraphResolver(PackResources pack) { + this.pack = pack; } @Override public IrisJigsawPool loadPool(String key) { - return StructureResources.pool(data.getPackResources(), key); + return StructureResources.pool(pack, key); } @Override public IrisJigsawPiece loadPiece(String key) { - return StructureResources.piece(data.getPackResources(), key); + return StructureResources.piece(pack, key); } @Override - public IrisObject loadObject(String key) { - return data.load(IrisObject.class, key, false); + public ObjectFrame loadObject(String key) { + if (key == null || key.isBlank()) { + return null; + } + return pack.objects().sizeOf(pack.idOf(key)).map(ObjectFrame::of).orElse(null); } } @@ -64,7 +67,7 @@ final class CompiledStructureGraphResolver implements StructureGraphResolver { } @Override - public IrisObject loadObject(String key) { + public ObjectFrame loadObject(String key) { return graph.getObjects().get(normalize(key)); } diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidation.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidation.java similarity index 89% rename from core/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidation.java rename to module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidation.java index 0e9c08320..05732524c 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidation.java +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidation.java @@ -18,21 +18,21 @@ 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.geometry.BlockPosition; +import com.volmit.resource.PackResources; 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.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -65,43 +65,43 @@ public final class StructureGraphValidation { private StructureGraphValidation() { } - /** Checks every structure of the pack {@code data} holds. */ - public static Validation validate(IrisData data) { - return validate(data, null); + /** Checks every structure of {@code pack}, whose objects are the files below {@code packFolder}. */ + public static Validation validate(PackResources pack, File packFolder) { + return validate(pack, packFolder, 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) { + /** Checks the structures of {@code pack} whose keys are in {@code activeStructureKeys}, or all when it is null. */ + public static Validation validate(PackResources pack, File packFolder, 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(StructureResources.STRUCTURES)) { + PackStructureResolver resolver = new PackStructureResolver(pack, packFolder); + for (ResourceId id : pack.ids(StructureResources.STRUCTURES)) { String structureKey = id.path(); if (activeStructureKeys != null && !activeStructureKeys.contains(structureKey)) { continue; } - IrisStructure structure = StructureResources.structure(data.getPackResources(), structureKey); + IrisStructure structure = StructureResources.structure(pack, structureKey); if (structure == null) { continue; } - validateStructure(structure, resolver, problems, replacementOutputStructures, sampledVerticalEnvelopes); + validateStructure(structureKey, structure, resolver, problems, replacementOutputStructures, sampledVerticalEnvelopes); } return new Validation(problems, replacementOutputStructures, sampledVerticalEnvelopes); } private static void validateStructure( + String structureKey, 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); + compilation = StructureGraphCompiler.compile(structureKey, structure, resolver); } catch (MalformedObjectResourceException e) { problems.add(Problem.error(file, e.getMessage())); return; @@ -139,7 +139,7 @@ public final class StructureGraphValidation { for (long seed : GEOMETRY_SAMPLE_SEEDS) { try { StructureAssembler assembler = StructureAssembler.forCompilation( - compilation, new IrisPosition(0, GEOMETRY_SAMPLE_ORIGIN_Y, 0)); + compilation, new BlockPosition(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()); @@ -257,28 +257,28 @@ public final class StructureGraphValidation { /** 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 PackResources pack; private final Path objectsRoot; - private final Map objects = new HashMap<>(); + 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); + private PackStructureResolver(PackResources pack, File packFolder) { + this.pack = pack; + this.objectsRoot = packFolder.toPath().toAbsolutePath().normalize().resolve(OBJECTS_FOLDER); } @Override public IrisJigsawPool loadPool(String key) { - return StructureResources.pool(data.getPackResources(), key); + return StructureResources.pool(pack, key); } @Override public IrisJigsawPiece loadPiece(String key) { - return StructureResources.piece(data.getPackResources(), key); + return StructureResources.piece(pack, key); } @Override - public IrisObject loadObject(String key) { + public ObjectFrame loadObject(String key) { if (objects.containsKey(key)) { return objects.get(key); } @@ -286,7 +286,7 @@ public final class StructureGraphValidation { return null; } Path file = resolveObject(key); - IrisObject object = file == null ? null : readObjectBounds(file); + ObjectFrame object = file == null ? null : readObjectBounds(file); if (object == null) { missingObjects.add(key); return null; @@ -306,7 +306,7 @@ public final class StructureGraphValidation { return file; } - private IrisObject readObjectBounds(Path file) { + private ObjectFrame readObjectBounds(Path file) { try (BufferedInputStream input = new BufferedInputStream(Files.newInputStream(file))) { return IrisObjectFrameReader.readBounds(input, file.toString()); } catch (IOException e) { diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureLocating.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureLocating.java similarity index 82% rename from core/src/main/java/art/arcane/iris/engine/framework/structure/StructureLocating.java rename to module/src/main/java/art/arcane/iris/engine/framework/structure/StructureLocating.java index a2de3f091..53cb7b5e5 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureLocating.java +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureLocating.java @@ -18,8 +18,8 @@ package art.arcane.iris.engine.framework.structure; -import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.IrisStructureLocator; +import art.arcane.iris.engine.framework.structure.assembly.StructureAssembly; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; import com.volmit.service.LocateResult; @@ -47,48 +47,50 @@ public final class StructureLocating implements StructureLocator { @Override public Set structures(PackResources pack) { - return idsOf(pack, StructureResources.structureKeys(pack)); + Set known = new LinkedHashSet<>(); + for (StructureAssembly provider : pack.services(StructureAssembly.class)) { + known.addAll(provider.structures(pack)); + } + return known; } @Override public Set locatable(PackWorld world) { - return idsOf(world.resources(), IrisStructureLocator.locatableEditableKeys(engine(world))); + return idsOf(world.resources(), IrisStructureLocator.locatableEditableKeys(world)); } @Override public Set placed(PackWorld world) { - return idsOf(world.resources(), IrisStructureLocator.placedKeysAndAliases(engine(world))); + return idsOf(world.resources(), IrisStructureLocator.placedKeysAndAliases(world)); } @Override public LocateResult locate(PackWorld world, ResourceId structure, int fromX, int fromZ, int maxRadiusChunks) { - Engine engine = engine(world); - String key = keyOf(world.resources(), IrisStructureLocator.placedKeysAndAliases(engine), structure); - return apiResult(engine, IrisStructureLocator.locate(engine, key, fromX, fromZ, maxRadiusChunks)); + String key = keyOf(world.resources(), IrisStructureLocator.placedKeysAndAliases(world), structure); + return apiResult(world, IrisStructureLocator.locate(world, key, fromX, fromZ, maxRadiusChunks)); } @Override public Set startedStructures(PackWorld world) { - return platformIds(IrisStructureLocator.nativeKeys(engine(world))); + return platformIds(IrisStructureLocator.nativeKeys(world)); } @Override public Set locatableStarts(PackWorld world) { - return platformIds(IrisStructureLocator.locatableNativeKeys(engine(world))); + return platformIds(IrisStructureLocator.locatableNativeKeys(world)); } /** Searches the rings of the placements that start {@code structure} natively, as the platform's own locate does. */ @Override public LocateResult locateStart(PackWorld world, ResourceId structure, int fromX, int fromZ, int maxRings, ChunkFilter accepts) { - Engine engine = engine(world); - return apiResult(engine, IrisStructureLocator.locateInPlacementRings( - engine, structure.toString(), fromX, fromZ, maxRings, accepts::accepts)); + return apiResult(world, IrisStructureLocator.locateInPlacementRings( + world, structure.toString(), fromX, fromZ, maxRings, accepts::accepts)); } - private static LocateResult apiResult(Engine engine, IrisStructureLocator.LocateResult result) { + private static LocateResult apiResult(PackWorld world, IrisStructureLocator.LocateResult result) { return switch (result.status()) { - case FOUND -> LocateResult.found(new BlockPosition(result.originX(), result.baseY() - engine.getMinHeight(), result.originZ())); + case FOUND -> LocateResult.found(new BlockPosition(result.originX(), result.baseY() - world.minWorldY(), result.originZ())); case NOT_FOUND -> LocateResult.NOT_FOUND; case SEARCH_LIMIT_REACHED -> LocateResult.SEARCH_LIMIT_REACHED; }; @@ -102,10 +104,6 @@ public final class StructureLocating implements StructureLocator { return ids; } - private static Engine engine(PackWorld world) { - return world.extension(Engine.class).orElseThrow(); - } - private static Set idsOf(PackResources pack, Collection keys) { Set ids = new LinkedHashSet<>(); for (String key : keys) { diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructurePlacementValidation.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructurePlacementValidation.java similarity index 97% rename from core/src/main/java/art/arcane/iris/engine/framework/structure/StructurePlacementValidation.java rename to module/src/main/java/art/arcane/iris/engine/framework/structure/StructurePlacementValidation.java index 37ea68c43..bc3d4f08b 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructurePlacementValidation.java +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructurePlacementValidation.java @@ -23,6 +23,7 @@ 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 art.arcane.iris.engine.framework.structure.assembly.StructureAssembly; import com.volmit.config.FeatureSettings.Entry; import com.volmit.config.Reference; import com.volmit.resource.ResourceId; @@ -61,7 +62,8 @@ final class StructurePlacementValidation { private StructurePlacementValidation(ValidationContext pack) { this.pack = pack; - this.packStructureKeys = pack.resources().ids(StructureResources.STRUCTURES).stream() + this.packStructureKeys = pack.services(StructureAssembly.class).stream() + .flatMap(provider -> provider.structures(pack.resources()).stream()) .map(ResourceId::path) .collect(Collectors.toUnmodifiableSet()); } diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureReferenceValidation.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureReferenceValidation.java similarity index 85% rename from core/src/main/java/art/arcane/iris/engine/framework/structure/StructureReferenceValidation.java rename to module/src/main/java/art/arcane/iris/engine/framework/structure/StructureReferenceValidation.java index fb9dfb6ea..6fc354dfa 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureReferenceValidation.java +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureReferenceValidation.java @@ -23,6 +23,7 @@ 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.block.BlockRegistry; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceKind; @@ -45,20 +46,26 @@ final class StructureReferenceValidation { private static final String JSON_EXTENSION = ".json"; private final PackResources pack; + private final Optional blocks; private final Set poolKeys; private final Set pieceKeys; private final Set objectKeys; private final List problems = new ArrayList<>(); - private StructureReferenceValidation(PackResources pack) { + private StructureReferenceValidation(PackResources pack, Optional blocks) { this.pack = pack; + this.blocks = blocks; 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); + /** + * Checks the pack; the blocks its connectors turn into are checked against {@code blocks} when there is a platform + * to know them. + */ + static List validate(PackResources pack, Optional blocks) { + StructureReferenceValidation validation = new StructureReferenceValidation(pack, blocks); validation.validateStructures(); validation.validatePools(); validation.validatePieces(); @@ -141,9 +148,21 @@ final class StructureReferenceValidation { problems.add(Problem.error(file, "Jigsaw piece '" + key + "' connectors[" + index + "] references missing pool '" + poolKey + "'.")); } + if (connectors.get(index) != null) { + validateFinalState(file, key, index, trimmed(connectors.get(index).getFinalState())); + } } } + /** A connector turns into its final state when its piece is placed, so it must be a block the platform knows. */ + private void validateFinalState(Subject file, String pieceKey, int index, String finalState) { + if (blocks.isEmpty() || finalState.isEmpty() || blocks.get().find(finalState).isPresent()) { + return; + } + problems.add(Problem.error(file, "Jigsaw piece '" + pieceKey + "' connectors[" + index + "] finalState '" + finalState + + "' is not a block.")); + } + private static Set keys(PackResources pack, ResourceKind kind) { return pack.ids(kind).stream().map(ResourceId::path).collect(Collectors.toUnmodifiableSet()); } diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureResourceBundleGraphCompiler.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureResourceBundleGraphCompiler.java similarity index 90% rename from core/src/main/java/art/arcane/iris/engine/framework/structure/StructureResourceBundleGraphCompiler.java rename to module/src/main/java/art/arcane/iris/engine/framework/structure/StructureResourceBundleGraphCompiler.java index f78a69716..e3fde1ca1 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureResourceBundleGraphCompiler.java +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureResourceBundleGraphCompiler.java @@ -22,12 +22,11 @@ import art.arcane.iris.core.structure.authoring.StructureResourceBundle; import art.arcane.iris.engine.framework.StructureAssembler; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.volmlib.util.math.RNG; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.volmit.geometry.BlockPosition; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -49,8 +48,8 @@ public final class StructureResourceBundleGraphCompiler { public static List compile(StructureResourceBundle bundle) { BundleGraph graph = parse(Objects.requireNonNull(bundle)); List compilations = new ArrayList<>(graph.structures().size()); - for (IrisStructure structure : graph.structures().values()) { - compilations.add(StructureGraphCompiler.compile(structure, graph.resolver())); + for (Map.Entry structure : graph.structures().entrySet()) { + compilations.add(StructureGraphCompiler.compile(structure.getKey(), structure.getValue(), graph.resolver())); } return List.copyOf(compilations); } @@ -60,8 +59,9 @@ public final class StructureResourceBundleGraphCompiler { if (graph.structures().isEmpty()) { throw new StructureGraphValidationException("Structure bundle does not contain a root structure resource"); } - for (IrisStructure structure : graph.structures().values()) { - StructureGraphCompilation compilation = StructureGraphCompiler.compile(structure, graph.resolver()); + for (Map.Entry structure : graph.structures().entrySet()) { + StructureGraphCompilation compilation = StructureGraphCompiler.compile( + structure.getKey(), structure.getValue(), graph.resolver()); if (!compilation.isAssemblyViable()) { throw new StructureGraphValidationException( "Structure bundle graph is not viable: " + viabilityFailure(compilation)); @@ -90,14 +90,11 @@ public final class StructureResourceBundleGraphCompiler { Map structures = new LinkedHashMap<>(); Map pools = new LinkedHashMap<>(); Map pieces = new LinkedHashMap<>(); - Map objects = new LinkedHashMap<>(); + Map objects = new LinkedHashMap<>(); for (StructureResourceBundle.Resource resource : activeBundle.resources().values()) { String path = resource.relativePath(); if (matches(path, "structures/", ".json")) { - IrisStructure structure = readJson(resource, IrisStructure.class); - String key = key(path, "structures/", ".json"); - structure.setLoadKey(key); - structures.put(key, structure); + structures.put(key(path, "structures/", ".json"), readJson(resource, IrisStructure.class)); } else if (matches(path, "jigsaw-pools/", ".json")) { pools.put(key(path, "jigsaw-pools/", ".json"), readJson(resource, IrisJigsawPool.class)); } else if (matches(path, "jigsaw-pieces/", ".json")) { @@ -114,7 +111,7 @@ public final class StructureResourceBundleGraphCompiler { for (long seed : ASSEMBLY_SEEDS) { try { StructureAssembler assembler = StructureAssembler.forCompilation( - compilation, new IrisPosition(0, 64, 0)); + compilation, new BlockPosition(0, 64, 0)); StructureAssemblyResult result = assembler.assemble(new RNG(seed)); if (result.status().isFailure()) { throw new StructureGraphValidationException("Structure bundle graph '" + structureKey @@ -157,7 +154,7 @@ public final class StructureResourceBundleGraphCompiler { return value; } - private static IrisObject readObjectBounds(StructureResourceBundle.Resource resource) { + private static ObjectFrame readObjectBounds(StructureResourceBundle.Resource resource) { try (ByteArrayInputStream input = new ByteArrayInputStream(resource.content())) { return IrisObjectFrameReader.readBounds(input, resource.relativePath()); } catch (IOException e) { @@ -168,7 +165,7 @@ public final class StructureResourceBundleGraphCompiler { private record BundleResolver( Map pools, Map pieces, - Map objects + Map objects ) implements StructureGraphResolver { private BundleResolver { pools = Map.copyOf(pools); @@ -187,7 +184,7 @@ public final class StructureResourceBundleGraphCompiler { } @Override - public IrisObject loadObject(String key) { + public ObjectFrame loadObject(String key) { return objects.get(key); } } diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java index 219c84836..9f6c1fa10 100644 --- a/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java @@ -28,7 +28,7 @@ import com.volmit.resource.ResourceKind; import java.util.List; /** - * The resource kinds of {@code iris:structure}, which keep the folders and files Iris packs have always used, and + * The resource kinds of {@code iris:jigsaw}, which keep the folders and files Iris packs have always used, and * lookups by pack key for code that names structures, pools and pieces by key. Every lookup goes through the pack's * {@link PackResources}, so it sees the pack's current snapshot: a hotload, or a tool that rewrote the files and asked * for a new snapshot, reads them again. @@ -38,11 +38,11 @@ import java.util.List; */ public final class StructureResources { /** Jigsaw structures, in {@code structures/}. */ - public static final ResourceKind STRUCTURES = ResourceKind.of("iris:structure/structure", "structures", IrisStructure.class); + public static final ResourceKind STRUCTURES = ResourceKind.of("iris:jigsaw/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); + public static final ResourceKind POOLS = ResourceKind.of("iris:jigsaw/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); + public static final ResourceKind PIECES = ResourceKind.of("iris:jigsaw/piece", "jigsaw-pieces", IrisJigsawPiece.class); private StructureResources() { } diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureValidator.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureValidator.java new file mode 100644 index 000000000..56aa77b00 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureValidator.java @@ -0,0 +1,53 @@ +/* + * 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.builtin.structure.StructurePlacement; +import art.arcane.iris.builtin.structure.StructurePlacementSettings; +import com.volmit.config.FeatureSettings; +import com.volmit.validation.ValidationContext; +import com.volmit.validation.Validator; + +import java.util.LinkedHashSet; +import java.util.Set; + +/** + * Module {@code iris:structure}'s check of a pack: every structure placement can generate + * ({@link StructurePlacementValidation}), and its {@code importedStructures} name real keys + * ({@link ImportedStructuresValidation}). Everything it reports is an error, as when Iris's own pack validator ran these + * checks. The structures themselves are checked by the module that builds them. + */ +public final class StructureValidator implements Validator { + @Override + public void validate(ValidationContext pack) { + StructurePlacementValidation.validate(pack); + ImportedStructuresValidation.validate(pack); + } + + /** The keys of the structures the dimensions, regions and biomes of the pack place, whether or not a dimension reaches them. */ + public static Set placedStructureKeys(ValidationContext pack) { + Set structureKeys = new LinkedHashSet<>(); + for (FeatureSettings.Entry declared : pack.settings().declared(StructurePlacementSettings.class).entries()) { + for (StructurePlacement placement : declared.value().placements()) { + placement.structures().stream().filter(key -> key != null && !key.isBlank()).forEach(structureKeys::add); + } + } + return Set.copyOf(structureKeys); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java similarity index 92% rename from core/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java rename to module/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java index 7ca896b65..57047e8f3 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java @@ -18,7 +18,6 @@ package art.arcane.iris.engine.framework.structure; -import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.IrisStructureLocator; import art.arcane.iris.engine.framework.structure.fit.StartLayouts; import art.arcane.iris.engine.framework.structure.fit.StructureFitting; @@ -56,20 +55,20 @@ public final class StructureVanillaStructures implements VanillaStructures { */ @Override public VanillaStructureRule rule(ResourceId structure, VanillaStructureContext context) { - Engine engine = context.settings().extension(Engine.class).orElseThrow(); + PackWorld world = context.world().orElseThrow(); String key = structure.toString(); - boolean replaced = IrisStructureLocator.suppressesVanilla(engine, key); + boolean replaced = IrisStructureLocator.suppressesVanilla(world, key); boolean blocked = replaced || ImportedStructures.of(context.settings()).disables(key); - boolean placed = replaced || IrisStructureLocator.isPlaced(engine, key); + boolean placed = replaced || IrisStructureLocator.isPlaced(world, key); VanillaStructureRule rule = blocked ? VanillaStructureRule.BLOCK : VanillaStructureRule.GENERATE; return placed ? rule.and(VanillaStructureRule.ALSO_PLACE) : rule; } @Override public List starts(int chunkX, int chunkZ, VanillaStructureStartContext context) { - Engine engine = engine(context.world()); - return NativeStartPlanner.plansAt(engine, chunkX, chunkZ).stream() - .map(plan -> start(plan, engine.getMinHeight())) + PackWorld world = context.world(); + return NativeStartPlanner.plansAt(world, chunkX, chunkZ).stream() + .map(plan -> start(plan, world.minWorldY())) .toList(); } @@ -102,10 +101,6 @@ public final class StructureVanillaStructures implements VanillaStructures { return ImportedStructures.of(context.settings()).setup(); } - private static Engine engine(PackWorld world) { - return world.extension(Engine.class).orElseThrow(); - } - /** {@code plan} as the start the platform generates: heights above the bottom and the placement's fit. */ static VanillaStructureStart start(NativeStartPlanner.Plan plan, int minHeight) { StructurePlacement placement = plan.placement(); diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureWorld.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureWorld.java new file mode 100644 index 000000000..2674dd8cc --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/StructureWorld.java @@ -0,0 +1,50 @@ +package art.arcane.iris.engine.framework.structure; + +import art.arcane.iris.builtin.structure.StructureSeeds; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; + +/** + * What structure placement asks a world about its size, its seed and its terrain. Heights here are the world's own + * (absolute) Y unless a method says it is above the dimension's bottom. + */ +public final class StructureWorld { + private StructureWorld() { + } + + public static RunningWorld running(PackWorld world) { + return world.running().orElseThrow(() -> new IllegalStateException("Structure placement requires a running world")); + } + + /** The key the pack's files name {@code id} by: its path in the pack's own namespace, the whole id in another. */ + public static String keyOf(PackWorld world, ResourceId id) { + return id.namespace().equals(world.resources().packId().namespace()) ? id.path() : id.toString(); + } + + /** The seed placements start from. */ + public static long placementSeed(PackWorld world) { + return world.seed(StructureSeeds.PLACEMENT); + } + + /** How many blocks high the world is. */ + public static int height(PackWorld world) { + var bounds = running(world).layout().bounds(); + return bounds.maxY() - bounds.minY(); + } + + /** The highest block of the column, with what objects and structures added, above the dimension's bottom. */ + public static int highestAboveBottom(PackWorld world, int blockX, int blockZ) { + return running(world).highest(blockX, blockZ, true); + } + + /** The highest block of the column in world Y. */ + public static int highest(PackWorld world, int blockX, int blockZ) { + return highestAboveBottom(world, blockX, blockZ) + world.minWorldY(); + } + + /** The height up to which the dimension is filled with fluid, above the dimension's bottom. */ + public static int fluidHeightAboveBottom(PackWorld world) { + return running(world).layout().fluidHeight(); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/assembly/AssembledPiece.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/assembly/AssembledPiece.java new file mode 100644 index 000000000..ccd23889b --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/assembly/AssembledPiece.java @@ -0,0 +1,40 @@ +/* + * 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.assembly; + +import com.volmit.resource.ResourceId; + +import java.util.Objects; + +/** + * One piece of an assembled structure: the pack object, where its origin lands, how it is turned and the blocks it covers. + * Heights are world Y, and the bounds are inclusive. + */ +public record AssembledPiece(ResourceId object, int x, int y, int z, PieceTurn turn, + int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { + public AssembledPiece { + Objects.requireNonNull(object, "object"); + Objects.requireNonNull(turn, "turn"); + } + + /** This piece moved up by {@code shiftY} blocks. */ + public AssembledPiece shiftedUp(int shiftY) { + return new AssembledPiece(object, x, y + shiftY, z, turn, minX, minY + shiftY, minZ, maxX, maxY + shiftY, maxZ); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/assembly/Assembly.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/assembly/Assembly.java new file mode 100644 index 000000000..803e82a00 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/assembly/Assembly.java @@ -0,0 +1,38 @@ +/* + * 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.assembly; + +import art.arcane.iris.engine.framework.structure.StructureAssemblyStatus; + +import java.util.List; +import java.util.Objects; + +/** What a {@link StructureAssembly} built: how the assembly ended, why when it did not complete, and the pieces in placement order. */ +public record Assembly(StructureAssemblyStatus status, String detail, List pieces) { + public Assembly { + Objects.requireNonNull(status, "status"); + Objects.requireNonNull(detail, "detail"); + pieces = List.copyOf(pieces); + } + + /** Whether the assembly completed with pieces to place. */ + public boolean hasOutput() { + return status == StructureAssemblyStatus.COMPLETE && !pieces.isEmpty(); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/assembly/PieceTurn.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/assembly/PieceTurn.java new file mode 100644 index 000000000..0652511bb --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/assembly/PieceTurn.java @@ -0,0 +1,70 @@ +/* + * 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.assembly; + +import com.volmit.block.BlockTurn; +import com.volmit.geometry.BlockPosition; + +/** + * How a structure's assembly turns a piece: around the vertical axis by whole quarter turns, in the direction Iris's + * object rotation turns (north becomes west). + * + * @param yDegrees degrees around Y; a multiple of 90 + */ +public record PieceTurn(int yDegrees) { + public static final PieceTurn NONE = new PieceTurn(0); + + private static final int QUARTER_TURN_DEGREES = 90; + private static final int QUARTER_TURNS_PER_CIRCLE = 4; + + public PieceTurn { + if (yDegrees % QUARTER_TURN_DEGREES != 0) { + throw new IllegalArgumentException("A piece turns by whole quarter turns, not " + yDegrees + " degrees"); + } + } + + public static PieceTurn aroundY(int yDegrees) { + return new PieceTurn(yDegrees); + } + + /** The quarter turns this turn makes, 0 to 3. */ + public int quarterTurns() { + return Math.floorMod(yDegrees / QUARTER_TURN_DEGREES, QUARTER_TURNS_PER_CIRCLE); + } + + /** The directions this turn turns, for the facing, axis and connections of block states. */ + public BlockTurn blockTurn() { + return (x, y, z) -> switch (quarterTurns()) { + case 1 -> new BlockTurn.Direction(z, y, -x); + case 2 -> new BlockTurn.Direction(-x, y, -z); + case 3 -> new BlockTurn.Direction(-z, y, x); + default -> new BlockTurn.Direction(x, y, z); + }; + } + + /** {@code position} turned around the origin. */ + public BlockPosition rotate(BlockPosition position) { + return switch (quarterTurns()) { + case 1 -> new BlockPosition(position.z(), position.y(), -position.x()); + case 2 -> new BlockPosition(-position.x(), position.y(), -position.z()); + case 3 -> new BlockPosition(-position.z(), position.y(), position.x()); + default -> position; + }; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/assembly/StructureAssembly.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/assembly/StructureAssembly.java new file mode 100644 index 000000000..087ab751b --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/assembly/StructureAssembly.java @@ -0,0 +1,60 @@ +/* + * 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.assembly; + +import art.arcane.volmlib.util.math.RNG; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.service.Providers; +import com.volmit.service.Service; + +import java.util.Optional; +import java.util.OptionalInt; +import java.util.Set; + +/** + * Builds the pieces of a structure the pack names; the placement decides where they go and fits them to the terrain. + * Every method answers empty, or {@link Viability#NOT_VIABLE}, for a structure this provider does not know, so a module + * offering another kind of structure answers only for its own. The placement asks the first provider that knows it. + */ +@Service(Providers.FIRST) +public interface StructureAssembly { + /** Whether this provider knows {@code structure}. Validation and the commands ask this. */ + boolean knows(PackResources pack, ResourceId structure); + + /** Every structure of the pack this provider knows, in id order. */ + Set structures(PackResources pack); + + /** How far, in chunks from its start, the structure may reach; empty when this provider does not know it. */ + OptionalInt reachChunks(PackResources pack, ResourceId structure); + + /** How the pieces are stamped; empty when this provider does not know it. */ + Optional stamp(PackResources pack, ResourceId structure); + + /** Whether the structure can produce pieces at all. */ + Viability viability(PackResources pack, ResourceId structure); + + /** + * The pieces from {@code origin}, drawing from {@code random}; empty when this provider does not know the structure. + * The placement draws its origin, anchor and structure from the same random before this continues on it, so the + * draws stay in one order whoever assembles. + */ + Optional assemble(PackResources pack, ResourceId structure, BlockPosition origin, RNG random); +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/assembly/StructureStamp.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/assembly/StructureStamp.java new file mode 100644 index 000000000..b99436a64 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/assembly/StructureStamp.java @@ -0,0 +1,42 @@ +/* + * 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.assembly; + +import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.blocks.ObjectReplace; + +import java.util.List; +import java.util.Objects; + +/** + * How the pieces of an assembled structure are stamped into the world. + * + * @param placeMode the place mode each piece is stamped with + * @param edits the find-and-replace block edits applied to every piece + * @param loot the loot tables the containers of the pieces draw from, blank names left out + * @param vanillaSource the platform structure this structure stands in for, blank for a hand-authored one + */ +public record StructureStamp(ObjectPlaceMode placeMode, List edits, List loot, String vanillaSource) { + public StructureStamp { + Objects.requireNonNull(placeMode, "placeMode"); + edits = List.copyOf(edits); + loot = List.copyOf(loot); + Objects.requireNonNull(vanillaSource, "vanillaSource"); + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/framework/structure/assembly/Viability.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/assembly/Viability.java new file mode 100644 index 000000000..43e7359da --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/assembly/Viability.java @@ -0,0 +1,33 @@ +/* + * 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.assembly; + +/** Whether a structure can produce pieces. */ +public enum Viability { + /** Its pieces cannot be assembled, or its graph has errors. */ + NOT_VIABLE, + /** Assembly completes for the samples tried, but a start or branch may still come up empty. */ + VIABLE, + /** Every start and branch ends in pieces, so a placement of it always produces a structure. */ + GUARANTEED; + + public boolean isViable() { + return this != NOT_VIABLE; + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/fit/CarveFootprints.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/CarveFootprints.java similarity index 100% rename from core/src/main/java/art/arcane/iris/engine/framework/structure/fit/CarveFootprints.java rename to module/src/main/java/art/arcane/iris/engine/framework/structure/fit/CarveFootprints.java diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/fit/StructureFitting.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/StructureFitting.java similarity index 98% rename from core/src/main/java/art/arcane/iris/engine/framework/structure/fit/StructureFitting.java rename to module/src/main/java/art/arcane/iris/engine/framework/structure/fit/StructureFitting.java index 4e38b0211..dd7540875 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/fit/StructureFitting.java +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/StructureFitting.java @@ -91,7 +91,8 @@ public final class StructureFitting { private void prepare() { vacuumFoundations = SurfaceFitting.prepareSurfaceStructures(blocks, area, starts, surfaceHeight, SurfaceFitting.MAX_SURFACE_TEMPLATE_CELLS, fit.log()); - TerrainIntegration.prepareTerrain(blocks, area, starts, fit.seed(), this::naturalBlock, this::paletteBlock); + TerrainIntegration.prepareTerrain(blocks, area, starts, fit.seed(), fit.world().resources().noise(), + this::naturalBlock, this::paletteBlock); RigidSupport.bridgeRigidPieceSupport(blocks, area, starts); } diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegration.java b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegration.java similarity index 95% rename from core/src/main/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegration.java rename to module/src/main/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegration.java index 44ee7f79d..4fa9e60dc 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegration.java +++ b/module/src/main/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegration.java @@ -23,10 +23,11 @@ import art.arcane.iris.builtin.structure.StructureTerrain; import art.arcane.iris.builtin.structure.StructureTerrainMode; import art.arcane.iris.engine.mantle.components.StructureCarveEnvelope; import art.arcane.iris.engine.mantle.components.StructureCarvingFootprint; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.volmlib.util.math.RNG; import com.volmit.block.BlockState; import com.volmit.block.PaletteSpec; +import com.volmit.noise.NoiseFactory; +import com.volmit.noise.NoiseSampler; +import com.volmit.noise.NoiseStyle; import com.volmit.resource.ResourceId; import com.volmit.vanilla.TerrainAdaptation; import com.volmit.geometry.BlockPosition; @@ -49,6 +50,9 @@ final class TerrainIntegration { private static final long CARVE_CEILING_ROLL_SIGNATURE = 0x2A17L; private static final long CARVE_FLOOR_ROLL_SIGNATURE = 0x5B3DL; private static final long CARVE_LOBE_SIGNATURE = 0x7C41L; + private static final NoiseStyle SIGNATURE_NOISE = NoiseStyle.of("IRIS"); + /** The lobes want a plain single octave channel: the fractured signature noise has no usable low frequency band. */ + private static final NoiseStyle SINGLE_OCTAVE_NOISE = NoiseStyle.of("SIMPLEX"); private static final long CARVE_IDENTITY_X = 341873128712L; private static final long CARVE_IDENTITY_Z = 132897987541L; private static final int SOURCE_BURY_HORIZONTAL_RADIUS = 6; @@ -83,14 +87,14 @@ final class TerrainIntegration { * Integrates the terrain of every start, then clears the legacy template air of those that replay their own * adaptation or are encased. The natural material SOURCE fills with is read once for all starts, before any fill. */ - static void prepareTerrain(FitBlocks blocks, Box area, List starts, long seed, + static void prepareTerrain(FitBlocks blocks, Box area, List starts, long seed, NoiseFactory noise, IntFunction naturalBlock, FitPalettes palettes) { if (starts.isEmpty()) { return; } SourceTerrainSnapshot sourceTerrain = captureSourceTerrain(blocks, area, starts); for (FitStart start : starts) { - integrateTerrain(blocks, area, start, seed, naturalBlock, palettes, sourceTerrain); + integrateTerrain(blocks, area, start, seed, noise, naturalBlock, palettes, sourceTerrain); } for (FitStart start : starts) { if (clearsLegacyTemplateAir(start)) { @@ -99,7 +103,7 @@ final class TerrainIntegration { } } - static void integrateTerrain(FitBlocks blocks, Box area, FitStart start, long seed, + static void integrateTerrain(FitBlocks blocks, Box area, FitStart start, long seed, NoiseFactory noise, IntFunction naturalBlock, FitPalettes palettes, SourceTerrainSnapshot sourceTerrain) { StructureTerrain terrain = start.terrain(); @@ -109,11 +113,12 @@ final class TerrainIntegration { case PRESERVE, VACUUM -> { } case ENCASE -> encasePieces(blocks, area, start, terrain, seed, naturalBlock, palettes); - case BORE, FORCE_CARVE -> carve(blocks, area, start, terrain, seed); + case BORE, FORCE_CARVE -> carve(blocks, area, start, terrain, seed, noise); } } - private static void carve(FitBlocks blocks, Box area, FitStart start, StructureTerrain terrain, long seed) { + private static void carve(FitBlocks blocks, Box area, FitStart start, StructureTerrain terrain, long seed, + NoiseFactory noise) { StructureCarveShape shape = terrain.resolvedMode() == StructureTerrainMode.BORE ? StructureCarveShape.BOX : terrain.resolvedShape(); if (shape == StructureCarveShape.BOX) { @@ -122,7 +127,7 @@ final class TerrainIntegration { } carveOrganicColumns(blocks, area, organicCarve( CarveFootprints.of(start, Math.max(0, terrain.horizontalPadding())), - terrain, shape, carveNoiseIdentity(seed, start))); + terrain, shape, carveNoiseIdentity(seed, start), noise)); } static SourceTerrainSnapshot captureSourceTerrain(FitBlocks blocks, Box area, List starts) { @@ -404,22 +409,20 @@ final class TerrainIntegration { } static OrganicCarve organicCarve(StructureCarvingFootprint footprint, StructureTerrain terrain, - StructureCarveShape shape, long identity) { + StructureCarveShape shape, long identity, NoiseFactory noise) { double strength = terrain.resolvedErosionStrength(); double lobeStrength = terrain.resolvedLobeStrength(); - RNG noiseRng = new RNG(identity); - CNG blob = null; - CNG ceilingRoll = null; - CNG floorRoll = null; - CNG lobe = null; + NoiseSampler blob = null; + NoiseSampler ceilingRoll = null; + NoiseSampler floorRoll = null; + NoiseSampler lobe = null; if (shape == StructureCarveShape.ERODED && strength > 0D) { - blob = CNG.signature(noiseRng); - ceilingRoll = CNG.signature(noiseRng.nextParallelRNG(CARVE_CEILING_ROLL_SIGNATURE)); - floorRoll = CNG.signature(noiseRng.nextParallelRNG(CARVE_FLOOR_ROLL_SIGNATURE)); + blob = noise.sampler(SIGNATURE_NOISE, identity); + ceilingRoll = noise.sampler(SIGNATURE_NOISE, identity + CARVE_CEILING_ROLL_SIGNATURE); + floorRoll = noise.sampler(SIGNATURE_NOISE, identity + CARVE_FLOOR_ROLL_SIGNATURE); } if (shape == StructureCarveShape.ERODED && lobeStrength > 0D) { - // A plain single octave channel: the fractured signature noise has no usable low frequency band. - lobe = new CNG(noiseRng.nextParallelRNG(CARVE_LOBE_SIGNATURE), 1D, 1); + lobe = noise.sampler(SINGLE_OCTAVE_NOISE, identity + CARVE_LOBE_SIGNATURE); } return new OrganicCarve(footprint, shape, Math.max(0, terrain.horizontalPadding()), @@ -474,10 +477,10 @@ final class TerrainIntegration { continue; } if (distanceSquared > 0D && eroded) { - double noise = carve.blob().fitDouble(0D, 1D, + double blobSample = carve.blob().sample( x * carve.frequency(), y * carve.frequency(), z * carve.frequency()); if (!StructureCarveEnvelope.shouldCarveOverboreCell( - carve.shape(), distanceSquared, noise, carve.strength())) { + carve.shape(), distanceSquared, blobSample, carve.strength())) { continue; } } @@ -627,7 +630,7 @@ final class TerrainIntegration { record OrganicCarve(StructureCarvingFootprint footprint, StructureCarveShape shape, int horizontalPadding, int ceilingPadding, int floorPadding, - double strength, double frequency, CNG blob, CNG ceilingRoll, CNG floorRoll, - CNG lobe, double lobeFrequency, double lobeStrength) { + double strength, double frequency, NoiseSampler blob, + NoiseSampler ceilingRoll, NoiseSampler floorRoll, NoiseSampler lobe, double lobeFrequency, double lobeStrength) { } } diff --git a/module/src/main/java/art/arcane/iris/engine/loot/PlacedObjectLoot.java b/module/src/main/java/art/arcane/iris/engine/loot/PlacedObjectLoot.java index baba31c0f..5514cba6c 100644 --- a/module/src/main/java/art/arcane/iris/engine/loot/PlacedObjectLoot.java +++ b/module/src/main/java/art/arcane/iris/engine/loot/PlacedObjectLoot.java @@ -22,7 +22,8 @@ import art.arcane.iris.builtin.loot.ObjectLoot; import art.arcane.iris.builtin.loot.ObjectVanillaLoot; import art.arcane.iris.builtin.objects.ObjectPlacement; import art.arcane.iris.builtin.objects.ObjectSettings; -import art.arcane.iris.builtin.structure.StructureHost; +import art.arcane.iris.engine.framework.structure.assembly.StructureAssembly; +import art.arcane.iris.engine.framework.structure.assembly.StructureStamp; import com.volmit.config.Level; import com.volmit.config.SettingsStack; import com.volmit.placement.PlacementRecord; @@ -82,17 +83,27 @@ final class PlacedObjectLoot { /** A structure piece's object gives every table its structure names, each once. */ private static Optional structurePlacement(PackWorld world, ResourceId structure, ResourceId object) { - Optional> tables = world.extension(StructureHost.class).orElseThrow().lootTables(structure); - if (tables.isEmpty() || world.resources().objects().object(object).isEmpty()) { + Optional stamp = stampOf(world, structure); + if (stamp.isEmpty() || world.resources().objects().object(object).isEmpty()) { return Optional.empty(); } List loot = new ArrayList<>(); - for (String table : tables.get()) { + for (String table : stamp.get().loot()) { loot.add(new ObjectLoot(table, STRUCTURE_TABLE_WEIGHT)); } return Optional.of(ObjectPlacement.builder().place(List.of(object.path())).loot(loot).build()); } + private static Optional stampOf(PackWorld world, ResourceId structure) { + for (StructureAssembly provider : world.services(StructureAssembly.class)) { + Optional stamp = provider.stamp(world.resources(), structure); + if (stamp.isPresent()) { + return stamp; + } + } + return Optional.empty(); + } + private static Optional columnPlacement(PackResources resources, SettingsStack declared, ResourceId object) { Optional fromRegion = declared.level(Level.REGION).flatMap(settings -> placing(resources, settings, object)); diff --git a/core/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelope.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelope.java similarity index 85% rename from core/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelope.java rename to module/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelope.java index a33ed27ec..86127d040 100644 --- a/core/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelope.java +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelope.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.structure.StructureCarveShape; -import art.arcane.iris.util.project.noise.CNG; +import com.volmit.noise.NoiseSampler; /** * Carve envelope math shared by the Iris-assembled structure path and the native (vanilla template) @@ -44,7 +44,7 @@ public final class StructureCarveEnvelope { * stays inside the footprint bounds the carve was sized against and never falls below * {@code horizontalPadding * (1 - lobeStrength)}. */ - public static double lobedSideReach(CNG lobe, double lobeFrequency, double lobeStrength, + public static double lobedSideReach(NoiseSampler lobe, double lobeFrequency, double lobeStrength, int x, int z, int horizontalPadding) { if (horizontalPadding <= 0) { return 0D; @@ -56,7 +56,7 @@ public final class StructureCarveEnvelope { * Ceiling counterpart of {@link #lobedSideReach}, deliberately half as strong so the roof swells * with the same lobes without collapsing onto the pieces. */ - public static double lobedUpReach(CNG lobe, double lobeFrequency, double lobeStrength, + public static double lobedUpReach(NoiseSampler lobe, double lobeFrequency, double lobeStrength, int x, int z, double upReach) { if (upReach <= 0D) { return upReach; @@ -65,19 +65,18 @@ public final class StructureCarveEnvelope { * lobeFactor(lobe, lobeFrequency, lobeStrength * CEILING_LOBE_RATIO, x, z)); } - private static double lobeFactor(CNG lobe, double lobeFrequency, double lobeStrength, + private static double lobeFactor(NoiseSampler lobe, double lobeFrequency, double lobeStrength, int x, int z) { double clampedStrength = Math.max(0D, Math.min(1D, lobeStrength)); if (lobe == null || clampedStrength <= 0D) { return 1D; } double scaledFrequency = lobeFrequency * LOBE_FREQUENCY_SCALE; - double sample = Math.max(0D, Math.min(1D, lobe.fitDouble( - 0D, 1D, x * scaledFrequency, z * scaledFrequency))); + double sample = Math.max(0D, Math.min(1D, lobe.sample(x * scaledFrequency, z * scaledFrequency))); return 1D - clampedStrength * (1D - sample); } - public static double erodedUpReach(CNG roll, double frequency, double strength, int x, int z, int head) { + public static double erodedUpReach(NoiseSampler roll, double frequency, double strength, int x, int z, int head) { if (head <= 0) { return 0D; } @@ -86,8 +85,8 @@ public final class StructureCarveEnvelope { return Math.max(1D, head); } double rollFrequency = frequency * CEILING_ROLL_FREQUENCY_RATIO; - double sample = roll.fitDouble(0D, 1D, x * rollFrequency, z * rollFrequency) * 0.7D - + roll.fitDouble(0D, 1D, x * rollFrequency * 3D, z * rollFrequency * 3D) * 0.3D; + double sample = roll.sample(x * rollFrequency, z * rollFrequency) * 0.7D + + roll.sample(x * rollFrequency * 3D, z * rollFrequency * 3D) * 0.3D; double contrast = Math.max(0D, Math.min(1D, (sample - 0.5D) * 2.6D + 0.5D)); double roundedReach = Math.max(1D, head); double erodedReach = Math.max(1D, head * (0.4D + 1.4D * contrast)); @@ -99,7 +98,7 @@ public final class StructureCarveEnvelope { * never exceeds the configured floor padding, so a padding of zero leaves every column standing on * its own supporting block instead of undermining the structure. */ - public static double erodedDownReach(CNG roll, double frequency, double strength, int x, int z, int floorCut) { + public static double erodedDownReach(NoiseSampler roll, double frequency, double strength, int x, int z, int floorCut) { if (floorCut <= 0) { return 0D; } @@ -108,7 +107,7 @@ public final class StructureCarveEnvelope { return floorCut; } double rollFrequency = frequency * FLOOR_ROLL_FREQUENCY_RATIO; - double sample = roll.fitDouble(0D, 1D, x * rollFrequency, z * rollFrequency); + double sample = roll.sample(x * rollFrequency, z * rollFrequency); return floorCut * (1D - clampedStrength * FLOOR_ROLL_AMPLITUDE * (1D - sample)); } diff --git a/core/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarvingFootprint.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarvingFootprint.java similarity index 84% rename from core/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarvingFootprint.java rename to module/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarvingFootprint.java index db4fe42fe..0f56f42dc 100644 --- a/core/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarvingFootprint.java +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarvingFootprint.java @@ -1,15 +1,8 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.engine.framework.PlacedStructurePiece; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.ObjectTurn; -import art.arcane.iris.util.common.data.B; -import art.arcane.volmlib.util.math.IrisBlockVector; -import art.arcane.volmlib.util.collection.KList; -import it.unimi.dsi.fastutil.longs.Long2LongMap; -import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap; - import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; public final class StructureCarvingFootprint { static final int DEFAULT_MAX_CELLS = 1_048_576; @@ -38,14 +31,6 @@ public final class StructureCarvingFootprint { sourceMaxY = data.sourceMaxY(); } - static StructureCarvingFootprint from(KList pieces, int padding) { - return from(pieces, padding, DEFAULT_MAX_CELLS); - } - - static StructureCarvingFootprint from(KList pieces, int padding, int maxCells) { - return fromColumns(sink -> emitPieceColumns(pieces, sink), padding, maxCells); - } - /** * Builds a footprint from any per-column occupancy source. The source reports one contribution per * occupied column; overlapping contributions merge into a single column whose vertical extents span @@ -80,10 +65,10 @@ public final class StructureCarvingFootprint { int[] sourceMinY = new int[sourceCount]; int[] sourceMaxY = new int[sourceCount]; int sourceId = 0; - for (Long2LongMap.Entry entry : sources.columns().long2LongEntrySet()) { - int localX = unpackX(entry.getLongKey()) - bounds.minX(); - int localZ = unpackZ(entry.getLongKey()) - bounds.minZ(); - long heights = entry.getLongValue(); + for (Map.Entry entry : sources.columns().entrySet()) { + int localX = unpackX(entry.getKey()) - bounds.minX(); + int localZ = unpackZ(entry.getKey()) - bounds.minZ(); + long heights = entry.getValue(); sourceX[sourceId] = localX; sourceZ[sourceId] = localZ; sourceMinY[sourceId] = unpackMinY(heights); @@ -170,7 +155,7 @@ public final class StructureCarvingFootprint { } private static SourceCollection collectSources(ColumnSource source) { - Long2LongOpenHashMap columns = new Long2LongOpenHashMap(); + Map columns = new HashMap<>(); MutableBounds bounds = new MutableBounds(); boolean usable = source.emit((worldX, worldZ, minY, maxY) -> { mergeColumn(columns, worldX, worldZ, minY, maxY); @@ -182,36 +167,6 @@ public final class StructureCarvingFootprint { return columns.isEmpty() ? null : new SourceCollection(columns, bounds.freeze()); } - private static boolean emitPieceColumns(KList pieces, ColumnSink sink) { - if (pieces == null) { - return true; - } - for (PlacedStructurePiece piece : pieces) { - if (piece == null) { - continue; - } - IrisObject object = piece.getObject(); - ObjectTurn rotation = piece.getRotation(); - if (object == null || rotation == null || object.getBlocks() == null) { - continue; - } - for (IrisBlockVector local : object.getBlocks().keys()) { - if (local == null || B.isAir(object.getBlocks().get(local))) { - continue; - } - IrisBlockVector rotated = rotation.rotate(local.clone()); - long worldX = (long) piece.getX() + rotated.getBlockX(); - long worldY = (long) piece.getY() + rotated.getBlockY(); - long worldZ = (long) piece.getZ() + rotated.getBlockZ(); - if (!fitsInteger(worldX) || !fitsInteger(worldY) || !fitsInteger(worldZ)) { - return false; - } - sink.column((int) worldX, (int) worldZ, (int) worldY, (int) worldY); - } - } - return true; - } - private static Bounds paddedBounds(MutableBoundsSnapshot sourceBounds, int padding, int maxCells) { long paddedMinX = (long) sourceBounds.minX() - padding; long paddedMaxX = (long) sourceBounds.maxX() + padding; @@ -233,7 +188,7 @@ public final class StructureCarvingFootprint { (int) width, (int) depth, cellCount); } - private static void mergeColumn(Long2LongOpenHashMap columns, int x, int z, int minY, int maxY) { + private static void mergeColumn(Map columns, int x, int z, int minY, int maxY) { long key = pack(x, z); if (!columns.containsKey(key)) { columns.put(key, packHeights(minY, maxY)); @@ -430,7 +385,7 @@ public final class StructureCarvingFootprint { int[] nearestSourceIds, int[] sourceMinY, int[] sourceMaxY) { } - private record SourceCollection(Long2LongOpenHashMap columns, MutableBoundsSnapshot bounds) { + private record SourceCollection(Map columns, MutableBoundsSnapshot bounds) { } private record MutableBoundsSnapshot(int minX, int maxX, int minZ, int maxZ) { diff --git a/core/src/main/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlanner.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlanner.java similarity index 68% rename from core/src/main/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlanner.java rename to module/src/main/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlanner.java index 3ac2c9737..467f51db3 100644 --- a/core/src/main/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlanner.java +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlanner.java @@ -1,7 +1,9 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.spi.PlatformBlockState; -import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; +import art.arcane.iris.engine.framework.structure.ColumnHeights; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; import java.util.function.IntConsumer; import java.util.function.IntPredicate; @@ -12,10 +14,10 @@ final class StructureFoundationPlanner { private StructureFoundationPlanner() { } - static void recordBaseCell(Long2IntOpenHashMap columns, int x, int y, int z, - PlatformBlockState state, boolean supportNonOccluding) { + static void recordBaseCell(ColumnHeights columns, int x, int y, int z, + BlockState state, BlockRegistry blocks, boolean supportNonOccluding) { if (columns == null || state == null - || !(supportNonOccluding ? state.isSolid() : state.isOccluding())) { + || !blocks.hasTrait(state, supportNonOccluding ? BlockTrait.SOLID : BlockTrait.OCCLUDING)) { return; } long columnKey = pack(x, z); @@ -38,19 +40,20 @@ final class StructureFoundationPlanner { return NO_GROUND; } - static boolean isGroundSolid(PlatformBlockState overlay, boolean carved, int mantleY, int terrainHeight) { + static boolean isGroundSolid(BlockState overlay, BlockRegistry blocks, boolean carved, int mantleY, + int terrainHeight) { if (mantleY <= 0) { return true; } if (overlay != null) { - return overlay.isSolid(); + return blocks.hasTrait(overlay, BlockTrait.SOLID); } return !carved && mantleY <= terrainHeight; } - static boolean isSurfaceSupportBoundary(PlatformBlockState overlay, boolean carved, + static boolean isSurfaceSupportBoundary(BlockState overlay, BlockRegistry blocks, boolean carved, int mantleY, int terrainHeight) { - return carved || isGroundSolid(overlay, false, mantleY, terrainHeight); + return carved || isGroundSolid(overlay, blocks, false, mantleY, terrainHeight); } static int fillSupportColumn(int foundationY, int groundY, IntConsumer supportAtY) { diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java index 17d8d5eae..6a6bf6e00 100644 --- a/module/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java @@ -19,24 +19,30 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.IrisStages; -import art.arcane.iris.builtin.structure.StructureHost; import art.arcane.iris.builtin.structure.StructurePlacementSettings; import art.arcane.iris.builtin.structure.StructureSettings; -import art.arcane.iris.engine.framework.structure.StructureResources; +import art.arcane.iris.core.modules.StructureCommands; +import art.arcane.iris.engine.framework.structure.StructureLocating; +import art.arcane.iris.engine.framework.structure.StructureValidator; +import art.arcane.iris.engine.framework.structure.StructureVanillaStructures; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.ModuleLog; import com.volmit.ModuleSetup; -import com.volmit.config.PackSettings; +import com.volmit.service.StructureLocator; +import com.volmit.service.VanillaStructures; import com.volmit.stage.MantleStageContext; /** - * Module {@code iris:structure}: the jigsaw structures, pools and pieces of a pack (its resource kinds), the structure - * placements a pack declares, and the mantle stage that places the structures starting in each chunk. Iris builds and - * places the structures ({@link StructureHost}); their validation, the locator and the platform structure answers are - * Iris's own module {@code iris:structure-model}. + * Module {@code iris:structure}: where structures go and how they meet the terrain. It owns the structure placements a + * pack declares, the mantle stage that places the structures starting in each chunk, the locator that finds them, the + * answers about the platform's own structures ({@link StructureVanillaStructures}: the dimension's + * {@code importedStructures} settings disable, move, fit and set them up, and the pack's placements replace them, place + * them alongside, start them where their {@code nativeStructures} grids say and fit them into the terrain), the checks of + * the placements, and the {@code /iris module structure} commands. *

- * It is not in the built-ins jar: Iris registers it with its own modules, because Iris's jigsaw studio, importers and - * exporters read the resources it registers as the same classes. + * It gets the pieces of a structure only from the {@link art.arcane.iris.engine.framework.structure.assembly.StructureAssembly} + * providers of the pack's modules, such as {@code iris:jigsaw}, and knows none of them. */ public final class StructureModule implements IrisModule { private static final String VERSION = "built-in"; @@ -48,19 +54,19 @@ public final class StructureModule implements IrisModule { @Override public void setup(ModuleSetup setup) { + ModuleLog log = setup.log(); setup.stages().define(IrisStages.Structure.PLACE).softAfter(IrisStages.Objects.PLACE, IrisStages.Floating.OBJECTS) - .reach(StructureModule::reach).run(StructureModule::place); + .reach(StructurePlacing::reach).run(context -> place(context, log)); var registry = setup.registry(); - StructureResources.kinds().forEach(registry::registerResourceKind); registry.registerSettings(StructureSettings.class); registry.registerSettings(StructurePlacementSettings.class); + registry.registerValidator(new StructureValidator()); + registry.registerService(StructureLocator.class, new StructureLocating()); + registry.registerService(VanillaStructures.class, new StructureVanillaStructures()); + setup.tooling().registerCommand(StructureCommands.root()); } - private static void place(MantleStageContext context) { - context.world().extension(StructureHost.class).orElseThrow().placeChunk(context); - } - - private static int reach(PackSettings settings) { - return settings.extension(StructureHost.class).orElseThrow().reach(); + private static void place(MantleStageContext context, ModuleLog log) { + context.world().state(StructurePlacing.class, generating -> new StructurePlacing(generating, log)).place(context); } } diff --git a/module/src/main/java/art/arcane/iris/engine/mantle/components/StructurePieceColumns.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/StructurePieceColumns.java new file mode 100644 index 000000000..180c1ea03 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/StructurePieceColumns.java @@ -0,0 +1,51 @@ +package art.arcane.iris.engine.mantle.components; + +import art.arcane.iris.engine.framework.structure.assembly.AssembledPiece; +import com.volmit.geometry.BlockPosition; + +import java.util.List; +import java.util.function.Function; + +/** The columns an assembled structure occupies, for the carve footprint. */ +final class StructurePieceColumns { + private StructurePieceColumns() { + } + + /** One block of a piece object: where it lies from the object's center, and whether it is air. */ + record PieceBlock(BlockPosition offset, boolean air) { + } + + /** + * Reports a column for every block of every piece that is not air, at the height the block lands, in the + * order of the pieces; false when a block lands outside the integer range. + */ + static boolean emit(List pieces, Function> blocksOf, + StructureCarvingFootprint.ColumnSink sink) { + if (pieces == null) { + return true; + } + for (AssembledPiece piece : pieces) { + if (piece == null) { + continue; + } + List blocks = blocksOf.apply(piece); + if (blocks == null) { + continue; + } + for (PieceBlock block : blocks) { + if (block.air()) { + continue; + } + BlockPosition rotated = piece.turn().rotate(block.offset()); + long worldX = (long) piece.x() + rotated.x(); + long worldY = (long) piece.y() + rotated.y(); + long worldZ = (long) piece.z() + rotated.z(); + if (worldX != (int) worldX || worldY != (int) worldY || worldZ != (int) worldZ) { + return false; + } + sink.column((int) worldX, (int) worldZ, (int) worldY, (int) worldY); + } + } + return true; + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java b/module/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java similarity index 55% rename from core/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java rename to module/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java index d7be008d3..8ab3e17ce 100644 --- a/core/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java +++ b/module/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java @@ -18,105 +18,108 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; -import art.arcane.iris.engine.framework.structure.StructureResources; -import art.arcane.iris.builtin.objects.ObjectPlacement; -import art.arcane.iris.builtin.prepare.ObjectRotation; -import art.arcane.iris.core.IrisSettings; -import art.arcane.iris.core.modules.ModuleObjectPlacement; -import art.arcane.iris.core.modules.ObjectPlacementResult; -import art.arcane.iris.engine.object.prefab.ObjectTurn; -import art.arcane.volmlib.util.cache.CacheKey; -import art.arcane.iris.engine.framework.IrisStructureLocator; -import art.arcane.iris.engine.framework.PlacedStructurePiece; -import art.arcane.iris.engine.framework.StructurePlacementScope; -import art.arcane.iris.core.modules.PlacementMarkers; -import art.arcane.iris.engine.framework.TreeBlockMaterial; -import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.loot.ObjectLoot; -import art.arcane.iris.engine.mantle.MantleWriter; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.engine.object.structure.IrisStructure; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectRun; +import art.arcane.iris.builtin.prepare.ObjectRotation; import art.arcane.iris.builtin.structure.StructureCarveShape; import art.arcane.iris.builtin.structure.StructurePlacement; +import art.arcane.iris.builtin.structure.StructurePlacementSettings; import art.arcane.iris.builtin.structure.StructureStilts; -import com.volmit.ModuleLog; -import com.volmit.block.PaletteSampler; -import com.volmit.block.PaletteSpec; import art.arcane.iris.builtin.structure.StructureTerrain; import art.arcane.iris.builtin.structure.StructureTerrainMode; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.volmlib.util.math.IrisBlockVector; -import art.arcane.iris.util.project.matter.TileWrapper; -import art.arcane.iris.util.project.noise.CNG; +import art.arcane.iris.engine.framework.IrisStructureLocator; +import art.arcane.iris.engine.framework.StructurePlacementScope; +import art.arcane.iris.engine.framework.structure.ColumnHeights; +import art.arcane.iris.engine.framework.structure.StructureWorld; +import art.arcane.iris.engine.framework.structure.assembly.AssembledPiece; +import art.arcane.iris.engine.framework.structure.assembly.PieceTurn; +import art.arcane.iris.engine.framework.structure.assembly.StructureAssembly; +import art.arcane.iris.engine.framework.structure.assembly.StructureStamp; +import art.arcane.volmlib.util.cache.CacheKey; import art.arcane.volmlib.util.collection.KList; -import art.arcane.iris.util.project.context.ChunkContext; import art.arcane.volmlib.util.documentation.ChunkCoordinates; -import art.arcane.volmlib.util.mantle.runtime.MantleChunk; -import art.arcane.volmlib.util.matter.Matter; -import art.arcane.volmlib.util.matter.MatterCavern; -import art.arcane.volmlib.util.matter.MatterStructurePOI; -import art.arcane.volmlib.util.math.BlockPosition; import art.arcane.volmlib.util.math.RNG; -import it.unimi.dsi.fastutil.longs.Long2IntMap; -import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap; +import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; +import com.volmit.block.PaletteSampler; +import com.volmit.block.PaletteSpec; +import com.volmit.geometry.BlockBox; +import com.volmit.geometry.BlockPosition; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.Mantle; +import com.volmit.noise.NoiseSampler; +import com.volmit.noise.NoiseStyle; +import com.volmit.object.ObjectBlock; +import com.volmit.object.PlaceableObject; +import com.volmit.placement.PlacementOutcome; +import com.volmit.placement.PlacementRecord; +import com.volmit.placement.PlacementTerrain; +import com.volmit.config.PackSettings; +import com.volmit.resource.PackResources; +import com.volmit.stage.MantleStageContext; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.function.BiConsumer; +import java.util.Optional; /** * Places the Iris structures of the dimension, its regions and biomes into the mantle for * {@link StructureModule}: their pieces, foundations, bores and carves, clearing object trees they - * intersect. One per engine runtime. Its reach is the largest structure any placement can produce. + * intersect. One per world. Its reach is the largest structure any placement can produce. */ public class StructurePlacing { - private static final MatterCavern CARVE_CAVERN = new MatterCavern(true, "", (byte) 3); + private static final CarvedVoid CARVE_VOID = CarvedVoid.AIR; + private static final NoiseStyle CARVE_NOISE = NoiseStyle.of("IRIS"); + private static final long CARVE_ROLL_SIGNATURE = 0x2A17L; + private static final int REJECTED_PIECE = -1; - private final Engine engine; + private final PackWorld world; private final ModuleLog log; - public StructurePlacing(Engine engine, ModuleLog log) { - this.engine = engine; + public StructurePlacing(PackWorld world, ModuleLog log) { + this.world = world; this.log = log; } - /** Places what originates in the chunk at chunk coordinates {@code x}, {@code z} into {@code writer}. */ + /** Places what originates in the chunk {@code context} generates into its mantle. */ @ChunkCoordinates - public void place(MantleWriter writer, int x, int z, ChunkContext context) { - for (StructurePlacement placement : StructurePlacementScope.placementsAt( - engine, x, z)) { + public void place(MantleStageContext context) { + int x = context.chunkX(); + int z = context.chunkZ(); + for (StructurePlacement placement : StructurePlacementScope.placementsAt(world, x, z)) { if (!placement.hasIrisStructures()) { continue; } - placeFromPlacement(writer, placement, x, z); + placeFromPlacement(context, placement, x, z); } } @ChunkCoordinates - private void placeFromPlacement(MantleWriter writer, StructurePlacement placement, int cx, int cz) { + private void placeFromPlacement(MantleStageContext context, StructurePlacement placement, int cx, int cz) { IrisStructureLocator.ResolvedPlacement resolved = IrisStructureLocator.resolvePlacement( - engine, placement, cx, cz); + world, placement, cx, cz); if (resolved == null) { return; } - boolean trace = IrisSettings.get().getGeneral().isDebug(); + boolean trace = log.debugging(); if (trace) { log.debug("[StructTrace] ORIGIN chunk=" + cx + "," + cz + " structures=" + placement.structures() + " anchor=" + placement.resolvedAnchor() + " band=" + placement.minHeight() + ".." + placement.maxHeight()); } String key = resolved.structureKey(); - IrisStructure structure = resolved.structure(); - KList pieces = resolvedPiecesOrNull(resolved, cx, cz); + StructureStamp stamp = resolved.stamp(); + KList pieces = resolvedPiecesOrNull(resolved, cx, cz); if (pieces == null) { return; } @@ -127,116 +130,115 @@ public class StructurePlacing { } if (!placement.isAnchoredUnderground()) { - clearIntersectingObjectTrees(writer, resolved); + clearIntersectingObjectTrees(context, resolved); } StructureTerrain terrain = placement.resolvedTerrain(); StructureTerrainMode terrainMode = terrain.resolvedMode(); if (terrainMode == StructureTerrainMode.FORCE_CARVE) { - forceCarveStructure(writer, pieces, terrain); + forceCarveStructure(context, pieces, terrain); } else if (terrainMode == StructureTerrainMode.BORE) { - boreStructure(writer, pieces, terrain); + boreStructure(context, pieces, terrain); } else if (terrainMode != StructureTerrainMode.PRESERVE && terrainMode != StructureTerrainMode.SOURCE) { throw new IllegalStateException("Iris assembly terrain mode " + terrainMode + " is not implemented for structure '" + key + "'"); } - - ObjectPlaceMode mode = structure.getPlaceMode(); + ObjectPlaceMode mode = stamp.placeMode(); int failedPieces = 0; StructureStilts stilt = placement.stilt().orElse(null); - Long2IntOpenHashMap foundationColumns = stilt == null - ? null : new Long2IntOpenHashMap(); + ColumnHeights foundationColumns = stilt == null + ? null : new ColumnHeights(0); boolean supportNonOccluding = stilt != null && stilt.supportNonOccluding(); if (placement.isAnchoredUnderground()) { ObjectPlaceMode undergroundMode = mode.placeMode().has(PlaceTrait.CAVE_ANCHORED) ? mode : ObjectPlaceMode.STRUCTURE_PIECE; - for (PlacedStructurePiece p : pieces) { - if (placeObject(writer, structure, p, undergroundMode, false, rng, - foundationColumns, supportNonOccluding) == -1) { + for (AssembledPiece p : pieces) { + if (placeObject(context, key, stamp, p, undergroundMode, false, + foundationColumns, supportNonOccluding) == REJECTED_PIECE) { failedPieces++; } } } else if (mode.placeMode().has(PlaceTrait.FREE_HEIGHT)) { - for (PlacedStructurePiece p : pieces) { - if (placeObject(writer, structure, p, ObjectPlaceMode.STRUCTURE_PIECE, false, rng, - foundationColumns, supportNonOccluding) == -1) { + for (AssembledPiece p : pieces) { + if (placeObject(context, key, stamp, p, ObjectPlaceMode.STRUCTURE_PIECE, false, + foundationColumns, supportNonOccluding) == REJECTED_PIECE) { failedPieces++; } } } else if (pieces.size() == 1) { - if (placeObject(writer, structure, pieces.getFirst(), mode, true, rng, - foundationColumns, supportNonOccluding) == -1) { + if (placeObject(context, key, stamp, pieces.getFirst(), mode, true, + foundationColumns, supportNonOccluding) == REJECTED_PIECE) { failedPieces++; } } else { - for (PlacedStructurePiece p : pieces) { - if (placeObject(writer, structure, p, ObjectPlaceMode.STRUCTURE_PIECE, false, rng, - foundationColumns, supportNonOccluding) == -1) { + for (AssembledPiece p : pieces) { + if (placeObject(context, key, stamp, p, ObjectPlaceMode.STRUCTURE_PIECE, false, + foundationColumns, supportNonOccluding) == REJECTED_PIECE) { failedPieces++; } } } requireAppliedPieces(resolved, cx, cz, failedPieces); if (failedPieces == 0 && stilt != null) { - placeFoundation(writer, foundationColumns, stilt, rng, !placement.isAnchoredUnderground()); + placeFoundation(context, foundationColumns, stilt, rng, !placement.isAnchoredUnderground()); } } - private void placeFoundation(MantleWriter writer, Long2IntOpenHashMap columns, + private void placeFoundation(MantleStageContext context, ColumnHeights columns, StructureStilts settings, RNG rng, boolean surfaceStructure) { PaletteSpec palette = settings.palette().orElseThrow( () -> new NullPointerException("Structure stilt palette must not be null")); - PaletteSampler picker = engine.getData().getPackResources().blocks().palette(palette, rng.getSeed()); - int mantleOffset = engine.getMinHeight(); + BlockRegistry blocks = world.resources().blocks(); + PaletteSampler picker = blocks.palette(palette, rng.getSeed()); + Mantle mantle = context.mantle(); + PlacementTerrain terrain = context.placementTerrain(); + RunningWorld running = StructureWorld.running(world); + int mantleOffset = world.minWorldY(); int maxDepth = Math.max(1, settings.maxDepth()); - for (Long2IntMap.Entry column : columns.long2IntEntrySet()) { - int worldX = StructureFoundationPlanner.unpackX(column.getLongKey()); - int worldZ = StructureFoundationPlanner.unpackZ(column.getLongKey()); - int foundationY = column.getIntValue(); - PlatformBlockState foundationState = writer.getDataIfPresent( - worldX, foundationY, worldZ, PlatformBlockState.class); - if (foundationState == null || !foundationState.isSolid()) { - continue; + columns.forEach((column, foundationY) -> { + int worldX = StructureFoundationPlanner.unpackX(column); + int worldZ = StructureFoundationPlanner.unpackZ(column); + BlockState foundationState = mantle.blocks().get(worldX, foundationY, worldZ); + if (foundationState == null || !blocks.hasTrait(foundationState, BlockTrait.SOLID)) { + return; } - int terrainHeight = engine.getMantle().trueHeight(worldX, worldZ); + int terrainHeight = running.layout().surfaceHeight(worldX, worldZ); int groundY = StructureFoundationPlanner.findGroundY( foundationY, maxDepth, 0, y -> { - PlatformBlockState overlay = writer.getDataIfPresent( - worldX, y, worldZ, PlatformBlockState.class); - boolean carved = writer.getDataIfPresent( - worldX, y, worldZ, MatterCavern.class) != null; + BlockState overlay = mantle.blocks().get(worldX, y, worldZ); + boolean carved = mantle.carved().get(worldX, y, worldZ) != null; return surfaceStructure ? StructureFoundationPlanner.isSurfaceSupportBoundary( - overlay, carved, y, terrainHeight) + overlay, blocks, carved, y, terrainHeight) : StructureFoundationPlanner.isGroundSolid( - overlay, carved, y, terrainHeight); + overlay, blocks, carved, y, terrainHeight); }); if (groundY == StructureFoundationPlanner.NO_GROUND) { - continue; + return; } StructureFoundationPlanner.fillSupportColumn(foundationY, groundY, y -> { - writeFoundationSupport(writer, picker, worldX, y, worldZ, mantleOffset); + writeFoundationSupport(terrain, mantle, picker, worldX, y, worldZ, mantleOffset); }); - } + }); } /** Writes the stilt palette's block at the column's mantle height, clearing any carve there. */ - static void writeFoundationSupport(MantleWriter writer, PaletteSampler picker, int worldX, int mantleY, int worldZ, - int mantleOffset) { + static void writeFoundationSupport(PlacementTerrain terrain, Mantle mantle, PaletteSampler picker, int worldX, + int mantleY, int worldZ, int mantleOffset) { int worldY = mantleY + mantleOffset; - PlatformBlockState support = B.getState(picker.at(worldX, worldY, worldZ).key()); + BlockState support = picker.at(worldX, worldY, worldZ); if (support == null) { throw new IllegalStateException("Structure stilt palette resolved no block at " + worldX + "," + worldY + "," + worldZ); } - writer.clearData(worldX, mantleY, worldZ, MatterCavern.class); - writer.set(worldX, mantleY, worldZ, support); + mantle.carved().remove(worldX, mantleY, worldZ); + terrain.set(worldX, mantleY, worldZ, support); } - static KList resolvedPiecesOrNull( + static KList resolvedPiecesOrNull( IrisStructureLocator.ResolvedPlacement resolved, int chunkX, int chunkZ @@ -244,7 +246,7 @@ public class StructurePlacing { if (resolved == null) { return null; } - KList pieces = resolved.pieces(); + KList pieces = resolved.pieces(); if (!IrisStructureLocator.requirePlacementOutput( resolved.placement(), resolved.structureKey(), chunkX, chunkZ, pieces != null && !pieces.isEmpty(), "placement application received no assembled pieces")) { @@ -261,7 +263,7 @@ public class StructurePlacing { + " assembled piece(s)"); } - private void boreStructure(MantleWriter writer, KList pieces, + private void boreStructure(MantleStageContext context, KList pieces, StructureTerrain terrain) { int[] bounds = computePieceBounds(pieces); if (bounds == null) { @@ -274,24 +276,24 @@ public class StructurePlacing { int maxX = bounds[3] + pad; int maxY = bounds[4] + Math.max(0, terrain.ceilingPadding()); int maxZ = bounds[5] + pad; - int worldMin = engine.getMinHeight() + 1; - int worldMax = engine.getMinHeight() + engine.getHeight() - 1; + int worldMin = world.minWorldY() + 1; + int worldMax = world.minWorldY() + StructureWorld.height(world) - 1; minY = Math.max(minY, worldMin); maxY = Math.min(maxY, worldMax); if (maxX < minX || maxY < minY || maxZ < minZ) { return; } - int mantleOffset = engine.getMinHeight(); + int mantleOffset = world.minWorldY(); for (int bx = minX; bx <= maxX; bx++) { for (int by = minY; by <= maxY; by++) { for (int bz = minZ; bz <= maxZ; bz++) { - writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN); + carve(context, bx, by - mantleOffset, bz); } } } } - private void forceCarveStructure(MantleWriter writer, KList pieces, + private void forceCarveStructure(MantleStageContext context, KList pieces, StructureTerrain terrain) { int[] bounds = computePieceBounds(pieces); if (bounds == null) { @@ -302,34 +304,34 @@ public class StructurePlacing { int head = Math.max(0, terrain.ceilingPadding()); int floorCut = Math.max(0, terrain.floorPadding()); double strength = terrain.resolvedErosionStrength(); - int mantleOffset = engine.getMinHeight(); - int worldMin = engine.getMinHeight() + 1; - int worldMax = engine.getMinHeight() + engine.getHeight() - 1; + int mantleOffset = world.minWorldY(); + int worldMin = world.minWorldY() + 1; + int worldMax = world.minWorldY() + StructureWorld.height(world) - 1; int upExtension = shape.maximumCeilingExtension(head, strength); if (shape == StructureCarveShape.BOX) { - carveOverboreBox(writer, bounds, margin, head, floorCut, mantleOffset, worldMin, worldMax); + carveOverboreBox(context, bounds, margin, head, floorCut, mantleOffset, worldMin, worldMax); return; } long work = overboreCandidateVolume(bounds, margin, upExtension, floorCut); - StructureCarvingFootprint footprint = StructureCarvingFootprint.from( - pieces, margin, Integer.MAX_VALUE); + StructureCarvingFootprint footprint = StructureCarvingFootprint.fromColumns( + sink -> StructurePieceColumns.emit(pieces, this::blocksOf, sink), margin, Integer.MAX_VALUE); if (footprint == null) { throw new IllegalStateException("Structure force-carve footprint is empty or exceeds addressable memory"); } double frequency = terrain.resolvedErosionFrequency(); boolean eroded = shape == StructureCarveShape.ERODED && strength > 0D; - CNG blob = null; - CNG roll = null; + NoiseSampler blob = null; + NoiseSampler roll = null; if (eroded) { - RNG noiseRng = new RNG(engine.getSeedManager().getMantle() + CacheKey.key(bounds[0], bounds[2])); - blob = CNG.signature(noiseRng); - roll = CNG.signature(noiseRng.nextParallelRNG(0x2A17)); + long noiseSeed = StructureWorld.placementSeed(world) + CacheKey.key(bounds[0], bounds[2]); + blob = world.resources().noise().sampler(CARVE_NOISE, noiseSeed); + roll = world.resources().noise().sampler(CARVE_NOISE, noiseSeed + CARVE_ROLL_SIGNATURE); } - if (IrisSettings.get().getGeneral().isDebug()) { + if (log.debugging()) { log.info("Overbore carving structure cavern: shape=" + shape + " pieces=" + pieces.size() + " footprint=" + footprint.width() + "x" + footprint.depth() + " margin=" + margin + " head=" + head + " floorCut=" + floorCut + " work=" + work); @@ -361,28 +363,27 @@ public class StructurePlacing { double distanceSquared = normalizedHorizontalDistanceSquared + normalizedY * normalizedY; if (distanceSquared <= 0D) { - writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN); + carve(context, bx, by - mantleOffset, bz); continue; } if (distanceSquared > 1D) { continue; } if (!eroded) { - writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN); + carve(context, bx, by - mantleOffset, bz); continue; } - double noise = blob.fitDouble( - 0D, 1D, bx * frequency, by * frequency, bz * frequency); + double noise = blob.sample(bx * frequency, by * frequency, bz * frequency); if (StructureCarveEnvelope.shouldCarveOverboreCell( shape, distanceSquared, noise, strength)) { - writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN); + carve(context, bx, by - mantleOffset, bz); } } } } } - private void carveOverboreBox(MantleWriter writer, int[] bounds, int margin, int head, int floorCut, + private void carveOverboreBox(MantleStageContext context, int[] bounds, int margin, int head, int floorCut, int mantleOffset, int worldMin, int worldMax) { int minX = bounds[0] - margin; int minY = Math.max(worldMin, bounds[1] - floorCut); @@ -393,12 +394,18 @@ public class StructurePlacing { for (int bx = minX; bx <= maxX; bx++) { for (int by = minY; by <= maxY; by++) { for (int bz = minZ; bz <= maxZ; bz++) { - writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN); + carve(context, bx, by - mantleOffset, bz); } } } } + /** Carves the block open for good: the void is planned and any block a placement wrote there is taken back. */ + private static void carve(MantleStageContext context, int x, int mantleY, int z) { + context.placementTerrain().clearBlock(x, mantleY, z); + context.mantle().carved().set(x, mantleY, z, CARVE_VOID); + } + private static long overboreCandidateVolume(int[] bounds, int margin, int upExtension, int floorCut) { return inclusiveVolume( @@ -418,94 +425,82 @@ public class StructurePlacing { return width * height * depth; } - private void clearIntersectingObjectTrees(MantleWriter writer, IrisStructureLocator.ResolvedPlacement resolved) { - int mantleOffset = engine.getMinHeight(); - int worldHeight = engine.getHeight(); - Map intersectingObjects = new HashMap<>(); - for (PlacedStructurePiece piece : resolved.pieces()) { - for (IrisBlockVector local : piece.getObject().getBlocks().keys()) { - PlatformBlockState structureState = piece.getObject().getBlocks().get(local); - if (!isOccupiedStructureState(structureState)) { + private void clearIntersectingObjectTrees(MantleStageContext context, IrisStructureLocator.ResolvedPlacement resolved) { + BlockRegistry blocks = world.resources().blocks(); + int mantleOffset = world.minWorldY(); + int worldHeight = StructureWorld.height(world); + Map intersectingObjects = new HashMap<>(); + for (AssembledPiece piece : resolved.pieces()) { + for (ObjectBlock block : objectOf(piece).geometry().blocks()) { + if (!isOccupiedStructureState(block.state(), blocks)) { continue; } - IrisBlockVector rotated = piece.getRotation().rotate(local.clone()); - int y = piece.getY() - mantleOffset + rotated.getBlockY(); + BlockPosition rotated = piece.turn().rotate(block.position()); + int y = piece.y() - mantleOffset + rotated.y(); if (y >= 0 && y < worldHeight) { - collectIntersectingObjectTreeMarker( - writer, piece.getX() + rotated.getBlockX(), y, - piece.getZ() + rotated.getBlockZ(), intersectingObjects); + collectIntersectingObjectTree( + context, piece.x() + rotated.x(), y, + piece.z() + rotated.z(), intersectingObjects); } } } - for (Map.Entry entry : intersectingObjects.entrySet()) { - clearMarkerOwnedObject(writer, entry.getKey(), entry.getValue(), worldHeight); + for (Map.Entry entry : intersectingObjects.entrySet()) { + clearRecordOwnedObject(context, entry.getKey(), entry.getValue(), worldHeight); } } - static boolean isOccupiedStructureState(PlatformBlockState state) { - return !B.isAir(state); + static boolean isOccupiedStructureState(BlockState state, BlockRegistry blocks) { + return state != null && !blocks.hasTrait(state, BlockTrait.AIR); } - private void collectIntersectingObjectTreeMarker(MantleWriter writer, int x, int y, int z, - Map intersectingObjects) { - PlatformBlockState state = writer.getDataIfPresent(x, y, z, PlatformBlockState.class); - if (state == null || !state.isTreeBlock()) { + private void collectIntersectingObjectTree(MantleStageContext context, int x, int y, int z, + Map intersectingObjects) { + BlockState state = context.mantle().blocks().get(x, y, z); + if (state == null || !isTreeBlock(state)) { return; } - String marker = writer.getDataIfPresent(x, y, z, String.class); - if (isOrdinaryObjectMarker(marker)) { - intersectingObjects.computeIfAbsent(marker, ignored -> new ObjectMarkerBounds()) + Optional record = StructureWorld.running(world).placementAt(x, y, z); + if (isOrdinaryObjectRecord(record)) { + intersectingObjects.computeIfAbsent(record.get(), ignored -> new ObjectMarkerBounds()) .include(x, y, z); } } - private void clearMarkerOwnedObject(MantleWriter writer, String marker, + private boolean isTreeBlock(BlockState state) { + BlockRegistry blocks = world.resources().blocks(); + return blocks.hasTrait(state, BlockTrait.LOG) || blocks.hasTrait(state, BlockTrait.LEAVES); + } + + private void clearRecordOwnedObject(MantleStageContext context, PlacementRecord record, ObjectMarkerBounds intersections, int worldHeight) { - PlacementMarkers.Decoded decoded = PlacementMarkers.decode(marker); - if (decoded == null) { + Optional object = world.resources().objects().object(record.object()); + if (object.isEmpty()) { return; } - IrisObject object = engine.getData().load(IrisObject.class, decoded.objectKey(), false); - if (object == null) { - return; - } - int horizontalSpan = Math.max(1, Math.max(object.getW(), object.getD())); - int verticalSpan = Math.max(1, object.getH()); + int horizontalSpan = Math.max(1, Math.max(object.get().width(), object.get().depth())); + int verticalSpan = Math.max(1, object.get().height()); ObjectMarkerBounds search = intersections.expand(horizontalSpan - 1, verticalSpan - 1, worldHeight); - KList positions = new KList<>(); - int minChunkX = Math.floorDiv(search.minX, 16); - int maxChunkX = Math.floorDiv(search.maxX, 16); - int minChunkZ = Math.floorDiv(search.minZ, 16); - int maxChunkZ = Math.floorDiv(search.maxZ, 16); - for (int chunkX = minChunkX; chunkX <= maxChunkX; chunkX++) { - for (int chunkZ = minChunkZ; chunkZ <= maxChunkZ; chunkZ++) { - MantleChunk chunk = writer.acquireChunk(chunkX, chunkZ); - if (chunk == null) { - continue; - } - int blockX = chunkX << 4; - int blockZ = chunkZ << 4; - chunk.iterate(String.class, (localX, y, localZ, value) -> { - int x = blockX + localX; - int z = blockZ + localZ; - if (marker.equals(value) && search.contains(x, y, z)) { + BlockBox prepared = context.mantle().bounds(); + RunningWorld running = StructureWorld.running(world); + PlacementTerrain terrain = context.placementTerrain(); + List positions = new ArrayList<>(); + for (int x = search.minX; x <= search.maxX; x++) { + for (int y = search.minY; y <= search.maxY; y++) { + for (int z = search.minZ; z <= search.maxZ; z++) { + if (prepared.contains(x, y, z) && running.placementAt(x, y, z).filter(record::equals).isPresent()) { positions.add(new ObjectBlockPosition(x, y, z)); } - }); + } } } for (ObjectBlockPosition position : positions) { - writer.clearBlock(position.x(), position.y(), position.z()); - writer.clearData(position.x(), position.y(), position.z(), String.class); - writer.clearData(position.x(), position.y(), position.z(), TreeBlockMaterial.class); - writer.clearData(position.x(), position.y(), position.z(), TileWrapper.class); - writer.clearData(position.x(), position.y(), position.z(), MatterStructurePOI.class); + terrain.clearBlock(position.x(), position.y(), position.z()); + terrain.clearAttached(position.x(), position.y(), position.z()); } } - static boolean isOrdinaryObjectMarker(String marker) { - PlacementMarkers.Decoded decoded = PlacementMarkers.decode(marker); - return decoded != null && !decoded.structureAware(); + static boolean isOrdinaryObjectRecord(Optional record) { + return record.isPresent() && record.get().structure().isEmpty(); } static ObjectMarkerBounds markerSearchBounds(int minX, int minY, int minZ, @@ -523,7 +518,23 @@ public class StructurePlacing { Math.max(0, horizontalSpan - 1), Math.max(0, verticalSpan - 1), worldHeight); } - private int[] computePieceBounds(KList pieces) { + private List blocksOf(AssembledPiece piece) { + BlockRegistry blocks = world.resources().blocks(); + List pieceBlocks = new ArrayList<>(); + for (ObjectBlock block : objectOf(piece).geometry().blocks()) { + pieceBlocks.add(new StructurePieceColumns.PieceBlock( + block.position(), blocks.hasTrait(block.state(), BlockTrait.AIR))); + } + return pieceBlocks; + } + + /** The object of {@code piece}, loaded from the world's pack. */ + private PlaceableObject objectOf(AssembledPiece piece) { + return world.resources().objects().object(piece.object()) + .orElseThrow(() -> new IllegalStateException("Structure piece object " + piece.object() + " is missing")); + } + + private int[] computePieceBounds(KList pieces) { if (pieces == null || pieces.isEmpty()) { return null; } @@ -533,29 +544,29 @@ public class StructurePlacing { int maxX = Integer.MIN_VALUE; int maxY = Integer.MIN_VALUE; int maxZ = Integer.MIN_VALUE; - for (PlacedStructurePiece p : pieces) { - minX = Math.min(minX, p.getMinX()); - minY = Math.min(minY, p.getMinY()); - minZ = Math.min(minZ, p.getMinZ()); - maxX = Math.max(maxX, p.getMaxX()); - maxY = Math.max(maxY, p.getMaxY()); - maxZ = Math.max(maxZ, p.getMaxZ()); + for (AssembledPiece p : pieces) { + minX = Math.min(minX, p.minX()); + minY = Math.min(minY, p.minY()); + minZ = Math.min(minZ, p.minZ()); + maxX = Math.max(maxX, p.maxX()); + maxY = Math.max(maxY, p.maxY()); + maxZ = Math.max(maxZ, p.maxZ()); } return new int[]{minX, minY, minZ, maxX, maxY, maxZ}; } - /** A placement of the piece object {@code objectKey} whose containers draw from the structure's loot tables. */ - public static ObjectPlacement lootPlacement(IrisStructure structure, String objectKey) { - return lootPlacementBuilder(structure, objectKey).build(); + /** A placement of the piece object {@code objectKey} whose containers draw from the stamp's loot tables. */ + public static ObjectPlacement lootPlacement(StructureStamp stamp, String objectKey) { + return lootPlacementBuilder(stamp, objectKey).build(); } - private static ObjectPlacement.Builder lootPlacementBuilder(IrisStructure structure, String objectKey) { + private static ObjectPlacement.Builder lootPlacementBuilder(StructureStamp stamp, String objectKey) { ObjectPlacement.Builder placement = ObjectPlacement.builder().place(List.of(objectKey)); - if (structure.getLoot() == null) { + if (stamp.loot().isEmpty()) { return placement; } List loot = new ArrayList<>(); - for (String lootTable : structure.getLoot()) { + for (String lootTable : stamp.loot()) { if (lootTable != null && !lootTable.isBlank()) { loot.add(new ObjectLoot(lootTable, 1)); } @@ -563,42 +574,55 @@ public class StructurePlacing { return placement.loot(loot); } - private int placeObject(MantleWriter writer, IrisStructure structure, PlacedStructurePiece p, - ObjectPlaceMode mode, boolean sampledHeight, RNG rng, Long2IntOpenHashMap foundationColumns, + private int placeObject(MantleStageContext context, String structureKey, StructureStamp stamp, AssembledPiece p, + ObjectPlaceMode mode, boolean sampledHeight, ColumnHeights foundationColumns, boolean supportNonOccluding) { - IrisObject object = p.getObject(); - String objectKey = object.getLoadKey(); - ObjectPlacement.Builder builder = lootPlacementBuilder(structure, objectKey).mode(mode).rotation(moduleRotation(p.getRotation())); - if (!structure.getEdit().isEmpty()) { - builder.edit(structure.getEdit()); + PlaceableObject object = objectOf(p); + String objectKey = object.name(); + ObjectPlacement.Builder builder = lootPlacementBuilder(stamp, objectKey).mode(mode).rotation(moduleRotation(p.turn())); + if (!stamp.edits().isEmpty()) { + builder.edit(new KList<>(stamp.edits())); } if (!mode.placeMode().has(PlaceTrait.FREE_HEIGHT)) { builder.forcePlace(true); } ObjectPlacement config = builder.build(); - String marker = structurePlacementMarker(structure, p, objectKey); - BiConsumer listener = (position, state) -> { + PlacementTerrain terrain = context.placementTerrain(); + ObjectRun run = sampledHeight + ? ObjectRun.automatic(object, config, p.x(), p.z()) + : ObjectRun.of(object, config, p.x(), p.y() - world.minWorldY(), p.z()); + PlacementOutcome outcome = run.placeIn(world, terrain); + if (!outcome.isPlaced()) { + return REJECTED_PIECE; + } + recordPieceBlocks(terrain, run, structureKey, p, objectKey, foundationColumns, supportNonOccluding); + return run.anchorY().orElseThrow(() -> new IllegalStateException( + "The placement graph placed " + objectKey + " without anchoring it")); + } + + /** Notes each block the piece wrote as a base cell of the foundation, and marks its storage blocks as the structure's. */ + private void recordPieceBlocks(PlacementTerrain terrain, ObjectRun run, String structureKey, AssembledPiece piece, + String objectKey, ColumnHeights foundationColumns, boolean supportNonOccluding) { + BlockRegistry blocks = world.resources().blocks(); + PlacementRecord record = structurePlacementRecord(structureKey, piece, objectKey); + for (BlockPosition position : run.objectBlocks()) { + BlockState state = terrain.get(position.x(), position.y(), position.z()); StructureFoundationPlanner.recordBaseCell( - foundationColumns, position.getX(), position.getY(), position.getZ(), state, + foundationColumns, position.x(), position.y(), position.z(), state, blocks, supportNonOccluding); - if (marker != null && shouldWriteStructureMarker(state)) { - writer.setData(position.getX(), position.getY(), position.getZ(), marker); + if (record != null && shouldWriteStructureMarker(state, blocks)) { + terrain.recordPlacement(position.x(), position.y(), position.z(), record); } - }; - ObjectPlacementResult result = sampledHeight - ? ModuleObjectPlacement.placeAutomatic(object, p.getX(), p.getZ(), writer, config, rng, listener, null, engine.getData()) - : ModuleObjectPlacement.place(object, p.getX(), p.getY() - engine.getMinHeight(), p.getZ(), writer, config, rng, - listener, null, engine.getData()); - return result.heightOrRejected(); + } } /** The placement rotation that turns a placed piece the way {@code turn} does. */ - public static ObjectRotation moduleRotation(ObjectTurn turn) { - return ObjectRotation.of(turn.xDegrees(), turn.yDegrees(), turn.zDegrees()); + public static ObjectRotation moduleRotation(PieceTurn turn) { + return ObjectRotation.of(0, turn.yDegrees(), 0); } - static boolean shouldWriteStructureMarker(PlatformBlockState state) { - return state != null && state.isStorageChest(); + static boolean shouldWriteStructureMarker(BlockState state, BlockRegistry blocks) { + return state != null && blocks.hasTrait(state, BlockTrait.STORAGE); } static int structurePlacementId(String structureKey, String objectKey, int x, int y, int z) { @@ -611,32 +635,27 @@ public class StructurePlacing { return hash & Integer.MAX_VALUE; } - private static String structurePlacementMarker(IrisStructure structure, PlacedStructurePiece piece, String objectKey) { - String structureKey = structure.getLoadKey(); + private PlacementRecord structurePlacementRecord(String structureKey, AssembledPiece piece, String objectKey) { if (structureKey == null || structureKey.isBlank() || objectKey == null || objectKey.isBlank()) { return null; } - int placementId = structurePlacementId(structureKey, objectKey, piece.getX(), piece.getY(), piece.getZ()); - return PlacementMarkers.encodeStructure(objectKey, placementId, structureKey); + PackResources pack = world.resources(); + int placementId = structurePlacementId(structureKey, objectKey, piece.x(), piece.y(), piece.z()); + return PlacementRecord.ofPiece(pack.idOf(objectKey), placementId, pack.idOf(structureKey)); } /** How far, in blocks along X and Z, placements may write beyond their chunk. */ - public int reach() { - IrisDimension dimension = engine.getDimension(); + public static int reach(PackSettings settings) { + PackResources pack = settings.resources(); + List providers = pack.services(StructureAssembly.class); int maxBlocks = 0; - - for (IrisRegion region : dimension.getAllRegions(engine)) { - maxBlocks = Math.max(maxBlocks, maxBlocksFrom(StructurePlacementScope.placementsOf(region))); + for (var declared : settings.declared(StructurePlacementSettings.class)) { + maxBlocks = Math.max(maxBlocks, maxBlocksFrom(pack, providers, declared.value().placements())); } - for (IrisBiome biome : dimension.getReachableBiomes(engine)) { - maxBlocks = Math.max(maxBlocks, maxBlocksFrom(StructurePlacementScope.placementsOf(biome))); - } - maxBlocks = Math.max(maxBlocks, maxBlocksFrom(StructurePlacementScope.placementsOf(dimension))); - return maxBlocks; } - private int maxBlocksFrom(List placements) { + private static int maxBlocksFrom(PackResources pack, List providers, List placements) { int max = 0; for (StructurePlacement placement : placements) { if (!placement.hasIrisStructures()) { @@ -647,9 +666,10 @@ public class StructurePlacing { || terrain.resolvedMode() == StructureTerrainMode.BORE ? Math.max(0, terrain.horizontalPadding()) : 0; for (String key : placement.structures()) { - IrisStructure structure = StructureResources.structure(engine.getData().getPackResources(), key); - if (structure != null) { - max = Math.max(max, Math.max(1, structure.getMaxSizeChunks()) * 16 + carvePadding); + var structure = pack.idOf(key); + StructureAssembly provider = IrisStructureLocator.providerOf(providers, pack, structure); + if (provider != null) { + max = Math.max(max, Math.max(1, provider.reachChunks(pack, structure).orElse(1)) * 16 + carvePadding); } } } diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java b/module/src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java index a1e726548..83ffd64e8 100644 --- a/module/src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/IrisStructure.java @@ -22,25 +22,25 @@ import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; import art.arcane.iris.builtin.blocks.ObjectReplace; import art.arcane.iris.builtin.loot.LootTable; -import art.arcane.iris.engine.object.KeyedResource; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawBranchFailurePolicy; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawCompatibility; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawMode; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawThemeSet; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawWorkcell; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.annotations.RegistryListVanillaStructure; -import art.arcane.iris.engine.object.annotations.Required; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; +import com.volmit.config.ResourceRef; +import com.volmit.geometry.BlockPosition; import art.arcane.volmlib.util.collection.KList; + +import java.util.List; import lombok.AllArgsConstructor; import lombok.Data; -import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; @@ -49,10 +49,9 @@ import lombok.experimental.Accessors; @AllArgsConstructor @Desc("A jigsaw structure. Starting from a pool, the assembler places a start piece and recursively attaches more pieces through matching connectors until it reaches the max depth or size. Pieces are Iris objects, so they carry the full object placement and block-control feature set.") @Data -@EqualsAndHashCode(callSuper = false) -public class IrisStructure extends KeyedResource { +public class IrisStructure { @Required - @RegistryListResource(IrisJigsawPool.class) + @ResourceRef(IrisJigsawPool.class) @Desc("The pool the assembler draws the start piece from.") private String startPool = ""; @@ -76,18 +75,16 @@ public class IrisStructure extends KeyedResource { private IrisJigsawBranchFailurePolicy branchFailurePolicy = IrisJigsawBranchFailurePolicy.FAIL_ASSEMBLY; @Desc("Default Studio cell dimensions. Legacy planar structures use this value for every workcell when planarWorkcells is empty.") - private IrisPosition cellSize = new IrisPosition(15, 15, 15); + private BlockPosition cellSize = new BlockPosition(15, 15, 15); @Desc("Optional author-facing name for the single spatial Jigsaw Studio workcell. Spatial is shown when this is blank.") private String spatialWorkcellDisplayName = ""; - @ArrayType(type = IrisJigsawWorkcell.class) @Desc("The six persistent planar Studio workcells. Leave empty only for the legacy cellSize fallback.") - private KList planarWorkcells = new KList<>(); + private List planarWorkcells = new KList<>(); - @ArrayType(type = IrisJigsawThemeSet.class, min = 1) @Desc("Weighted themes available to an assembly. Leave empty for one implicit unthemed assembly path.") - private KList themeSets = new KList<>(); + private List themeSets = new KList<>(); @Desc("Whether every open connector must close with a real terminal piece through a mandatory direct fallback.") private boolean requireCaps = false; @@ -95,16 +92,14 @@ public class IrisStructure extends KeyedResource { @Desc("The place mode used when stamping each piece object into the world.") private ObjectPlaceMode placeMode = ObjectPlaceMode.STRUCTURE_PIECE; - @ArrayType(min = 1, type = ObjectReplace.class) @Desc("Find-and-replace block edits applied to every piece of this structure, using the exact same syntax as an object's 'edit'. For example, replace stone bricks with obsidian.") - private KList edit = new KList<>(); + private List edit = new KList<>(); - @ArrayType(type = String.class, min = 1) - @RegistryListResource(LootTable.class) + @ResourceRef(LootTable.class) @Desc("Loot tables applied to containers placed by this structure's pieces.") - private KList loot = new KList<>(); + private List loot = new KList<>(); - @RegistryListVanillaStructure + @Ref(Reference.STRUCTURE) @Desc("If this structure was generated by importing a vanilla or datapack structure, this is that structure's key (provenance). Empty for hand-authored structures.") private String vanillaSource = ""; @@ -126,14 +121,4 @@ public class IrisStructure extends KeyedResource { ? IrisJigsawBranchFailurePolicy.FAIL_ASSEMBLY : branchFailurePolicy; } - - @Override - public String getFolderName() { - return "structures"; - } - - @Override - public String getTypeName() { - return "Structure"; - } } diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawBranchFailurePolicy.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawBranchFailurePolicy.java index 09bfb0b92..1a937363c 100644 --- a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawBranchFailurePolicy.java +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawBranchFailurePolicy.java @@ -1,6 +1,6 @@ package art.arcane.iris.engine.object.structure.jigsaw; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("Controls how an Iris jigsaw assembly handles an optional connector branch that exhausts its primary pool and direct fallback without attaching a piece.") public enum IrisJigsawBranchFailurePolicy { diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawCompatibility.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawCompatibility.java index b8563a4cc..f877fb607 100644 --- a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawCompatibility.java +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawCompatibility.java @@ -1,6 +1,6 @@ package art.arcane.iris.engine.object.structure.jigsaw; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("Declares the resource compatibility target of an Iris jigsaw structure.") public enum IrisJigsawCompatibility { diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConnector.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConnector.java index dc99b49cc..195dd795b 100644 --- a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConnector.java +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawConnector.java @@ -18,11 +18,10 @@ package art.arcane.iris.engine.object.structure.jigsaw; -import art.arcane.iris.engine.object.value.IrisDirection; -import art.arcane.iris.engine.object.value.IrisPosition; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.annotations.Required; +import com.volmit.config.Desc; +import com.volmit.config.Required; +import com.volmit.config.ResourceRef; +import com.volmit.geometry.BlockPosition; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -36,20 +35,20 @@ import java.util.Objects; @Desc("A jigsaw connection point on a piece. When two connectors face each other and their names match, the assembler may join the pieces.") @Data public class IrisJigsawConnector { - public static IrisPosition canonicalPlanarPosition(IrisPosition cellSize, IrisDirection direction) { - IrisPosition dimensions = Objects.requireNonNull(cellSize, "Planar jigsaw cell size"); - IrisDirection face = Objects.requireNonNull(direction, "Planar jigsaw connector direction"); - if (dimensions.getX() < 1 || dimensions.getY() < 1 || dimensions.getZ() < 1) { + public static BlockPosition canonicalPlanarPosition(BlockPosition cellSize, JigsawDirection direction) { + BlockPosition dimensions = Objects.requireNonNull(cellSize, "Planar jigsaw cell size"); + JigsawDirection face = Objects.requireNonNull(direction, "Planar jigsaw connector direction"); + if (dimensions.x() < 1 || dimensions.y() < 1 || dimensions.z() < 1) { throw new IllegalArgumentException("Planar jigsaw cell dimensions must be positive"); } - int centerX = dimensions.getX() / 2; - int centerY = dimensions.getY() / 2; - int centerZ = dimensions.getZ() / 2; + int centerX = dimensions.x() / 2; + int centerY = dimensions.y() / 2; + int centerZ = dimensions.z() / 2; return switch (face) { - case NORTH_NEGATIVE_Z -> new IrisPosition(centerX, centerY, 0); - case EAST_POSITIVE_X -> new IrisPosition(dimensions.getX() - 1, centerY, centerZ); - case SOUTH_POSITIVE_Z -> new IrisPosition(centerX, centerY, dimensions.getZ() - 1); - case WEST_NEGATIVE_X -> new IrisPosition(0, centerY, centerZ); + case NORTH_NEGATIVE_Z -> new BlockPosition(centerX, centerY, 0); + case EAST_POSITIVE_X -> new BlockPosition(dimensions.x() - 1, centerY, centerZ); + case SOUTH_POSITIVE_Z -> new BlockPosition(centerX, centerY, dimensions.z() - 1); + case WEST_NEGATIVE_X -> new BlockPosition(0, centerY, centerZ); case UP_POSITIVE_Y, DOWN_NEGATIVE_Y -> throw new IllegalArgumentException( "Planar jigsaw connector direction must be horizontal"); }; @@ -57,18 +56,18 @@ public class IrisJigsawConnector { @Required @Desc("The position of this connector relative to the piece object's origin (0,0,0 is the lowest-corner of the object).") - private IrisPosition position = new IrisPosition(); + private BlockPosition position = new BlockPosition(0, 0, 0); @Required @Desc("The direction this connector faces. The connecting piece is placed on this side.") - private IrisDirection direction = IrisDirection.NORTH_NEGATIVE_Z; + private JigsawDirection direction = JigsawDirection.NORTH_NEGATIVE_Z; @Required @Desc("The connector's authored top direction, used to preserve aligned vanilla jigsaw orientation.") - private IrisDirection top = IrisDirection.UP_POSITIVE_Y; + private JigsawDirection top = JigsawDirection.UP_POSITIVE_Y; @Required - @RegistryListResource(IrisJigsawPool.class) + @ResourceRef(IrisJigsawPool.class) @Desc("The jigsaw pool to draw the connecting piece from.") private String pool = ""; diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawMode.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawMode.java index 34b79faa5..a95cd1f90 100644 --- a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawMode.java +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawMode.java @@ -1,6 +1,6 @@ package art.arcane.iris.engine.object.structure.jigsaw; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("Controls the topology used by an Iris jigsaw structure.") public enum IrisJigsawMode { diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPiece.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPiece.java index b123f3a0f..fde861af3 100644 --- a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPiece.java +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPiece.java @@ -18,16 +18,15 @@ package art.arcane.iris.engine.object.structure.jigsaw; -import art.arcane.iris.engine.object.KeyedResource; +import com.volmit.config.Desc; +import com.volmit.config.Required; +import com.volmit.config.ResourceRef; import com.volmit.object.GeneratedObject; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.RegistryListResource; -import art.arcane.iris.engine.object.annotations.Required; import art.arcane.volmlib.util.collection.KList; + +import java.util.List; import lombok.AllArgsConstructor; import lombok.Data; -import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; @@ -36,19 +35,17 @@ import lombok.experimental.Accessors; @AllArgsConstructor @Desc("A jigsaw piece. A piece is a single Iris object plus the connection points (connectors) that let the assembler attach other pieces to it.") @Data -@EqualsAndHashCode(callSuper = false) -public class IrisJigsawPiece extends KeyedResource { +public class IrisJigsawPiece { @Desc("Optional author-facing name shown by Jigsaw Studio. The resource key is shown when this is blank.") private String displayName = ""; @Required - @RegistryListResource(GeneratedObject.class) + @ResourceRef(GeneratedObject.class) @Desc("The object (schematic) that makes up this piece.") private String object = ""; - @ArrayType(type = IrisJigsawConnector.class, min = 1) @Desc("The jigsaw connection points on this piece.") - private KList connectors = new KList<>(); + private List connectors = new KList<>(); @Desc("If true, this piece may be rotated around the Y axis when placed so the assembler can match its connectors. Disable for pieces that must keep a fixed orientation.") private boolean rotatable = true; @@ -56,9 +53,8 @@ public class IrisJigsawPiece extends KeyedResource { @Desc("If true, this piece's object bounds block overlapping jigsaw pieces. Disable for connector-only scaffolds whose stored volume is intentionally shared with physical pieces.") private boolean collidable = true; - @ArrayType(type = String.class, min = 1) @Desc("Theme keys that may select this piece. An empty list makes the piece available to every selected theme.") - private KList themes = new KList<>(); + private List themes = new KList<>(); @Desc("Deterministic depth, placement-count, and terminal-role rules for this piece.") private IrisJigsawPieceRules rules = new IrisJigsawPieceRules(); @@ -81,14 +77,4 @@ public class IrisJigsawPiece extends KeyedResource { public IrisJigsawPieceRules resolvedRules() { return rules == null ? new IrisJigsawPieceRules() : rules; } - - @Override - public String getFolderName() { - return "jigsaw-pieces"; - } - - @Override - public String getTypeName() { - return "Jigsaw Piece"; - } } diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceEntry.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceEntry.java index c022d4de8..f06f6a364 100644 --- a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceEntry.java +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceEntry.java @@ -18,10 +18,10 @@ package art.arcane.iris.engine.object.structure.jigsaw; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.RegistryListResource; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.ResourceRef; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -33,7 +33,7 @@ import lombok.experimental.Accessors; @Desc("A weighted reference to a jigsaw piece inside a jigsaw pool.") @Data public class IrisJigsawPieceEntry { - @RegistryListResource(IrisJigsawPiece.class) + @ResourceRef(IrisJigsawPiece.class) @Desc("The jigsaw piece this entry refers to. Omit when empty is true.") private String piece; diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceRules.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceRules.java index 214cc9a4e..e9e3f1139 100644 --- a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceRules.java +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPieceRules.java @@ -1,8 +1,8 @@ package art.arcane.iris.engine.object.structure.jigsaw; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPool.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPool.java index bc66b71b2..12d89c502 100644 --- a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPool.java +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawPool.java @@ -18,14 +18,13 @@ package art.arcane.iris.engine.object.structure.jigsaw; -import art.arcane.iris.engine.object.KeyedResource; -import art.arcane.iris.engine.object.annotations.ArrayType; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.RegistryListResource; +import com.volmit.config.Desc; +import com.volmit.config.ResourceRef; import art.arcane.volmlib.util.collection.KList; + +import java.util.List; import lombok.AllArgsConstructor; import lombok.Data; -import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; @@ -34,13 +33,11 @@ import lombok.experimental.Accessors; @AllArgsConstructor @Desc("A jigsaw pool. A pool is a weighted set of pieces the assembler chooses from when a connector targets this pool.") @Data -@EqualsAndHashCode(callSuper = false) -public class IrisJigsawPool extends KeyedResource { - @ArrayType(type = IrisJigsawPieceEntry.class, min = 1) +public class IrisJigsawPool { @Desc("The weighted pieces in this pool.") - private KList pieces = new KList<>(); + private List pieces = new KList<>(); - @RegistryListResource(IrisJigsawPool.class) + @ResourceRef(IrisJigsawPool.class) @Desc("The direct fallback pool tried after this pool, or used alone at maximum depth. The fallback pool's own fallback is not part of the same selection. Leave empty to stop expanding at maximum depth.") private String fallback = ""; @@ -50,14 +47,4 @@ public class IrisJigsawPool extends KeyedResource { public boolean requiresFallback(boolean structureRequiresCaps) { return structureRequiresCaps || mandatoryFallback; } - - @Override - public String getFolderName() { - return "jigsaw-pools"; - } - - @Override - public String getTypeName() { - return "Jigsaw Pool"; - } } diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawThemeSet.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawThemeSet.java index c9ea75085..5a7394561 100644 --- a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawThemeSet.java +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawThemeSet.java @@ -1,8 +1,8 @@ package art.arcane.iris.engine.object.structure.jigsaw; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MinNumber; -import art.arcane.iris.engine.object.annotations.Required; +import com.volmit.config.Desc; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcell.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcell.java index e998e142e..7a06ab80c 100644 --- a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcell.java +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcell.java @@ -1,8 +1,8 @@ package art.arcane.iris.engine.object.structure.jigsaw; -import art.arcane.iris.engine.object.annotations.Desc; -import art.arcane.iris.engine.object.annotations.MaxNumber; -import art.arcane.iris.engine.object.annotations.MinNumber; +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcellArchetype.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcellArchetype.java index 4275be726..5317c6521 100644 --- a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcellArchetype.java +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/IrisJigsawWorkcellArchetype.java @@ -1,6 +1,6 @@ package art.arcane.iris.engine.object.structure.jigsaw; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("The orientation-independent connector shape represented by a planar jigsaw workcell.") public enum IrisJigsawWorkcellArchetype { diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/JigsawDirection.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/JigsawDirection.java new file mode 100644 index 000000000..e33af180c --- /dev/null +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/JigsawDirection.java @@ -0,0 +1,116 @@ +/* + * 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.object.structure.jigsaw; + +import com.volmit.config.Desc; +import com.volmit.geometry.BlockFace; + +/** + * One of the six axis directions, named by its axis and sign as jigsaw packs write them ({@code EAST_POSITIVE_X}). The + * constants are part of the pack format, which is why the API's {@link BlockFace} ({@code EAST}) cannot stand in for it. + */ +@Desc("A direction object") +public enum JigsawDirection { + @Desc("0, 1, 0") + UP_POSITIVE_Y(0, 1, 0, BlockFace.UP), + @Desc("0, -1, 0") + DOWN_NEGATIVE_Y(0, -1, 0, BlockFace.DOWN), + @Desc("0, 0, -1") + NORTH_NEGATIVE_Z(0, 0, -1, BlockFace.NORTH), + @Desc("0, 0, 1") + SOUTH_POSITIVE_Z(0, 0, 1, BlockFace.SOUTH), + @Desc("1, 0, 0") + EAST_POSITIVE_X(1, 0, 0, BlockFace.EAST), + @Desc("-1, 0, 0") + WEST_NEGATIVE_X(-1, 0, 0, BlockFace.WEST); + + private final int x; + private final int y; + private final int z; + private final BlockFace face; + + JigsawDirection(int x, int y, int z, BlockFace face) { + this.x = x; + this.y = y; + this.z = z; + this.face = face; + } + + @Override + public String toString() { + return switch (this) { + case DOWN_NEGATIVE_Y -> "Down"; + case EAST_POSITIVE_X -> "East"; + case NORTH_NEGATIVE_Z -> "North"; + case SOUTH_POSITIVE_Z -> "South"; + case UP_POSITIVE_Y -> "Up"; + case WEST_NEGATIVE_X -> "West"; + }; + } + + public boolean isVertical() { + return this == DOWN_NEGATIVE_Y || this == UP_POSITIVE_Y; + } + + public JigsawDirection reverse() { + return switch (this) { + case DOWN_NEGATIVE_Y -> UP_POSITIVE_Y; + case EAST_POSITIVE_X -> WEST_NEGATIVE_X; + case NORTH_NEGATIVE_Z -> SOUTH_POSITIVE_Z; + case SOUTH_POSITIVE_Z -> NORTH_NEGATIVE_Z; + case UP_POSITIVE_Y -> DOWN_NEGATIVE_Y; + case WEST_NEGATIVE_X -> EAST_POSITIVE_X; + }; + } + + /** This direction turned around Y by {@code quarterTurns} quarter turns, the way an object's rotation turns it (north becomes west); vertical directions stay. */ + public JigsawDirection turnedBy(int quarterTurns) { + if (isVertical()) { + return this; + } + JigsawDirection turned = this; + for (int turn = 0; turn < Math.floorMod(quarterTurns, 4); turn++) { + turned = switch (turned) { + case NORTH_NEGATIVE_Z -> WEST_NEGATIVE_X; + case WEST_NEGATIVE_X -> SOUTH_POSITIVE_Z; + case SOUTH_POSITIVE_Z -> EAST_POSITIVE_X; + case EAST_POSITIVE_X -> NORTH_NEGATIVE_Z; + case UP_POSITIVE_Y, DOWN_NEGATIVE_Y -> turned; + }; + } + return turned; + } + + public int x() { + return x; + } + + public int y() { + return y; + } + + public int z() { + return z; + } + + /** The API face this direction is. */ + public BlockFace face() { + return face; + } +} diff --git a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/JigsawJoint.java b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/JigsawJoint.java index 851d5a251..b2ac7dd0f 100644 --- a/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/JigsawJoint.java +++ b/module/src/main/java/art/arcane/iris/engine/object/structure/jigsaw/JigsawJoint.java @@ -18,7 +18,7 @@ package art.arcane.iris.engine.object.structure.jigsaw; -import art.arcane.iris.engine.object.annotations.Desc; +import com.volmit.config.Desc; @Desc("How a jigsaw connection may be rotated when matching two pieces together.") public enum JigsawJoint { diff --git a/core/src/main/java/art/arcane/iris/engine/platform/studio/generators/JigsawStudioGenerator.java b/module/src/main/java/art/arcane/iris/engine/platform/studio/generators/JigsawStudioGenerator.java similarity index 69% rename from core/src/main/java/art/arcane/iris/engine/platform/studio/generators/JigsawStudioGenerator.java rename to module/src/main/java/art/arcane/iris/engine/platform/studio/generators/JigsawStudioGenerator.java index e82514a64..f8380b6ae 100644 --- a/core/src/main/java/art/arcane/iris/engine/platform/studio/generators/JigsawStudioGenerator.java +++ b/module/src/main/java/art/arcane/iris/engine/platform/studio/generators/JigsawStudioGenerator.java @@ -3,7 +3,6 @@ package art.arcane.iris.engine.platform.studio.generators; import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarDirection; import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarTopology; -import art.arcane.iris.core.runtime.jigsaw.JigsawStudioActivation; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBay; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioBounds; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions; @@ -11,95 +10,88 @@ import art.arcane.iris.core.runtime.jigsaw.JigsawStudioControlPosition; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioSession; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariant; -import art.arcane.iris.core.service.JigsawStudioService; -import art.arcane.iris.engine.data.chunk.TerrainChunk; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.GenerationSessionLease; -import art.arcane.iris.engine.framework.WrongEngineBroException; -import art.arcane.iris.engine.object.value.IrisDirection; +import art.arcane.iris.core.service.JigsawStudioBlocks; +import art.arcane.iris.core.service.JigsawStudioRequest; +import art.arcane.iris.engine.framework.structure.assembly.PieceTurn; +import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.prefab.ObjectTurn; -import art.arcane.iris.engine.object.prefab.BlockStateRotation; -import art.arcane.iris.engine.object.value.IrisPosition; import art.arcane.iris.engine.object.structure.jigsaw.JigsawJoint; -import art.arcane.iris.engine.object.prefab.TileData; -import art.arcane.iris.engine.platform.studio.EnginedStudioGenerator; -import art.arcane.iris.platform.bukkit.BukkitWorldBinding; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.volmlib.util.data.VectorMap; -import art.arcane.volmlib.util.math.IrisBlockVector; -import art.arcane.volmlib.util.math.Vector3i; -import art.arcane.iris.util.project.context.IrisContext; import art.arcane.volmlib.util.collection.KList; -import org.bukkit.World; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import com.volmit.object.ObjectBlock; +import com.volmit.object.PlaceableObject; +import com.volmit.resource.PackResources; +import com.volmit.tooling.ToolPack; +import com.volmit.tooling.world.ChunkCanvas; +import com.volmit.tooling.world.ChunkPainter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicBoolean; -public final class JigsawStudioGenerator extends EnginedStudioGenerator { +public final class JigsawStudioGenerator implements ChunkPainter { private static final int CHECKER_SIZE = 4; + private static final int CHUNK_SIZE = 16; - private final JigsawStudioActivation.Request request; + private final ToolPack pack; + private final JigsawStudioRequest request; private final JigsawStudioSession session; - private final PlatformBlockState lightFloor; - private final PlatformBlockState darkFloor; - private final PlatformBlockState frame; - private final PlatformBlockState topologyBase; - private final PlatformBlockState topologyPath; - private final PlatformBlockState connectorCap; - private final PlatformBlockState invalidMarker; - private final PlatformBlockState controlChest; + private final BlockState lightFloor; + private final BlockState darkFloor; + private final BlockState frame; + private final BlockState topologyBase; + private final BlockState topologyPath; + private final BlockState connectorCap; + private final BlockState invalidMarker; + private final BlockState controlChest; private final FinalStateRenderer finalStateRenderer; - private final AtomicBoolean serviceRegistered = new AtomicBoolean(false); private final ConcurrentMap renderedBays = new ConcurrentHashMap<>(); - private final ConcurrentMap jigsawStates = new ConcurrentHashMap<>(); + private final ConcurrentMap jigsawStates = new ConcurrentHashMap<>(); public JigsawStudioGenerator( - Engine engine, - JigsawStudioActivation.Request request, + ToolPack pack, + JigsawStudioRequest request, JigsawStudioSession session ) { this( - engine, + pack, request, session, - B.getState("minecraft:smooth_stone"), - B.getState("minecraft:polished_deepslate"), - B.getState("minecraft:white_concrete"), - B.getState("minecraft:light_gray_wool"), - B.getState("minecraft:red_wool"), - B.getState("minecraft:sea_lantern"), - B.getState("minecraft:red_stained_glass"), - B.getState("minecraft:chest[facing=south,type=single,waterlogged=false]"), - JigsawStudioGenerator::rotatedFinalState + BlockState.parse("minecraft:smooth_stone"), + BlockState.parse("minecraft:polished_deepslate"), + BlockState.parse("minecraft:white_concrete"), + BlockState.parse("minecraft:light_gray_wool"), + BlockState.parse("minecraft:red_wool"), + BlockState.parse("minecraft:sea_lantern"), + BlockState.parse("minecraft:red_stained_glass"), + BlockState.parse("minecraft:chest[facing=south,type=single,waterlogged=false]"), + null ); } JigsawStudioGenerator( - Engine engine, - JigsawStudioActivation.Request request, + ToolPack pack, + JigsawStudioRequest request, JigsawStudioSession session, - PlatformBlockState lightFloor, - PlatformBlockState darkFloor, - PlatformBlockState frame, - PlatformBlockState topologyBase, - PlatformBlockState topologyPath, - PlatformBlockState connectorCap, - PlatformBlockState invalidMarker, - PlatformBlockState controlChest, + BlockState lightFloor, + BlockState darkFloor, + BlockState frame, + BlockState topologyBase, + BlockState topologyPath, + BlockState connectorCap, + BlockState invalidMarker, + BlockState controlChest, FinalStateRenderer finalStateRenderer ) { - super(engine); + this.pack = Objects.requireNonNull(pack, "Jigsaw Studio pack"); this.request = Objects.requireNonNull(request, "Jigsaw Studio request"); this.session = Objects.requireNonNull(session, "Jigsaw Studio session"); this.lightFloor = Objects.requireNonNull(lightFloor, "Jigsaw Studio light floor block"); @@ -110,9 +102,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { this.connectorCap = Objects.requireNonNull(connectorCap, "Jigsaw Studio connector cap block"); this.invalidMarker = Objects.requireNonNull(invalidMarker, "Jigsaw Studio invalid marker block"); this.controlChest = Objects.requireNonNull(controlChest, "Jigsaw Studio control chest block"); - this.finalStateRenderer = Objects.requireNonNull( - finalStateRenderer, - "Jigsaw Studio connector final-state renderer"); + this.finalStateRenderer = finalStateRenderer == null ? this::rotatedFinalState : finalStateRenderer; if (!request.requestId().equals(session.sessionId())) { throw new IllegalArgumentException("Jigsaw Studio request and session IDs do not match"); } @@ -121,7 +111,11 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { } } - public JigsawStudioActivation.Request getRequest() { + public ToolPack getPack() { + return pack; + } + + public JigsawStudioRequest getRequest() { return request; } @@ -176,29 +170,21 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { } @Override - public void generateChunk(Engine engine, TerrainChunk terrainChunk, int chunkX, int chunkZ) - throws WrongEngineBroException { - try (GenerationSessionLease lease = engine.acquireGenerationLease("bukkit_jigsaw_studio_stage"); - IrisContext.Scope ignored = IrisContext.open(engine, lease.sessionId(), null)) { - paintChunk(terrainChunk, chunkX, chunkZ); - ensureServiceRegistered(engine); - if (serviceRegistered.get()) { - JigsawStudioService.get().markChunkGenerated(engine, this, chunkX, chunkZ); - } - } + public void paint(int chunkX, int chunkZ, ChunkCanvas canvas) { + paintChunk(canvas, chunkX, chunkZ); } - public void paintChunk(TerrainChunk terrainChunk, int chunkX, int chunkZ) { - Objects.requireNonNull(terrainChunk, "Jigsaw Studio terrain chunk"); - int floorY = Math.max(terrainChunk.getMinHeight(), JigsawStudioLayout.FLOOR_Y); - if (floorY >= terrainChunk.getMaxHeight()) { + public void paintChunk(ChunkCanvas canvas, int chunkX, int chunkZ) { + Objects.requireNonNull(canvas, "Jigsaw Studio chunk canvas"); + int floorY = Math.max(canvas.minY(), JigsawStudioLayout.FLOOR_Y); + if (floorY >= canvas.maxY()) { return; } int chunkWorldX = chunkX << 4; int chunkWorldZ = chunkZ << 4; - paintFloor(terrainChunk, floorY, chunkWorldX, chunkWorldZ); - paintControlChest(terrainChunk, chunkWorldX, chunkWorldZ); + paintFloor(canvas, floorY, chunkWorldX, chunkWorldZ); + paintControlChest(canvas, chunkWorldX, chunkWorldZ); int chunkMaxX = chunkWorldX + 15; int chunkMaxZ = chunkWorldZ + 15; @@ -211,21 +197,21 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { chunkMaxZ + 1)) { continue; } - paintCage(terrainChunk, workcell, chunkWorldX, chunkWorldZ); + paintCage(canvas, workcell, chunkWorldX, chunkWorldZ); if (workcell.archetype().isPresent()) { - paintTopologyGlyph(terrainChunk, workcell, chunkWorldX, chunkWorldZ); + paintTopologyGlyph(canvas, workcell, chunkWorldX, chunkWorldZ); } RenderedBay renderedBay = renderBay(workcell); if (!renderedBay.valid()) { - paintInvalidBay(terrainChunk, workcell, chunkWorldX, chunkWorldZ); + paintInvalidBay(canvas, workcell, chunkWorldX, chunkWorldZ); continue; } - paintObject(terrainChunk, workcell, renderedBay, chunkWorldX, chunkWorldZ); + paintObject(canvas, workcell, renderedBay, chunkWorldX, chunkWorldZ); if (session.workcellSnapshot(workcell.stableId()).connectorsVisible()) { - paintConnectors(terrainChunk, workcell, renderedBay, chunkWorldX, chunkWorldZ); + paintConnectors(canvas, workcell, renderedBay, chunkWorldX, chunkWorldZ); } else { paintHiddenConnectorFinalStates( - terrainChunk, + canvas, workcell, renderedBay, chunkWorldX, @@ -234,48 +220,23 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { } } - private void ensureServiceRegistered(Engine engine) { - if (serviceRegistered.get()) { - return; - } - World world = BukkitWorldBinding.world(engine.getTarget().getWorld()); - if (world == null) { - return; - } - publishServiceRegistration(() -> JigsawStudioService.get().register(engine, this)); - } - - void publishServiceRegistration(Runnable registration) { - Objects.requireNonNull(registration, "Jigsaw Studio service registration"); - if (serviceRegistered.get()) { - return; - } - synchronized (serviceRegistered) { - if (serviceRegistered.get()) { - return; - } - registration.run(); - serviceRegistered.set(true); - } - } - - private void paintFloor(TerrainChunk terrainChunk, int floorY, int chunkWorldX, int chunkWorldZ) { - for (int localX = 0; localX < 16; localX++) { - for (int localZ = 0; localZ < 16; localZ++) { + private void paintFloor(ChunkCanvas canvas, int floorY, int chunkWorldX, int chunkWorldZ) { + for (int localX = 0; localX < CHUNK_SIZE; localX++) { + for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) { int worldX = chunkWorldX + localX; int worldZ = chunkWorldZ + localZ; int tileX = Math.floorDiv(worldX, CHECKER_SIZE); int tileZ = Math.floorDiv(worldZ, CHECKER_SIZE); - PlatformBlockState block = ((tileX + tileZ) & 1) == 0 ? lightFloor : darkFloor; - terrainChunk.setBlock(localX, floorY, localZ, block); + BlockState block = ((tileX + tileZ) & 1) == 0 ? lightFloor : darkFloor; + canvas.set(localX, floorY, localZ, block); } } } - private void paintControlChest(TerrainChunk terrainChunk, int chunkWorldX, int chunkWorldZ) { + private void paintControlChest(ChunkCanvas canvas, int chunkWorldX, int chunkWorldZ) { JigsawStudioControlPosition control = getLayout().controlPosition(); setWorldBlock( - terrainChunk, + canvas, control.worldX(), control.worldY(), control.worldZ(), @@ -285,7 +246,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { } private void paintCage( - TerrainChunk terrainChunk, + ChunkCanvas canvas, JigsawStudioBay workcell, int chunkWorldX, int chunkWorldZ @@ -299,7 +260,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { int topY = bounds.maxY() + 1; paintRectangle( - terrainChunk, + canvas, minimumX, maximumX, bottomY, @@ -308,7 +269,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { chunkWorldX, chunkWorldZ); paintRectangle( - terrainChunk, + canvas, minimumX, maximumX, topY, @@ -317,15 +278,15 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { chunkWorldX, chunkWorldZ); for (int y = bottomY + 1; y < topY; y++) { - setWorldBlock(terrainChunk, minimumX, y, minimumZ, frame, chunkWorldX, chunkWorldZ); - setWorldBlock(terrainChunk, maximumX, y, minimumZ, frame, chunkWorldX, chunkWorldZ); - setWorldBlock(terrainChunk, minimumX, y, maximumZ, frame, chunkWorldX, chunkWorldZ); - setWorldBlock(terrainChunk, maximumX, y, maximumZ, frame, chunkWorldX, chunkWorldZ); + setWorldBlock(canvas, minimumX, y, minimumZ, frame, chunkWorldX, chunkWorldZ); + setWorldBlock(canvas, maximumX, y, minimumZ, frame, chunkWorldX, chunkWorldZ); + setWorldBlock(canvas, minimumX, y, maximumZ, frame, chunkWorldX, chunkWorldZ); + setWorldBlock(canvas, maximumX, y, maximumZ, frame, chunkWorldX, chunkWorldZ); } } private void paintRectangle( - TerrainChunk terrainChunk, + ChunkCanvas canvas, int minimumX, int maximumX, int y, @@ -335,17 +296,17 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { int chunkWorldZ ) { for (int x = minimumX; x <= maximumX; x++) { - setWorldBlock(terrainChunk, x, y, minimumZ, frame, chunkWorldX, chunkWorldZ); - setWorldBlock(terrainChunk, x, y, maximumZ, frame, chunkWorldX, chunkWorldZ); + setWorldBlock(canvas, x, y, minimumZ, frame, chunkWorldX, chunkWorldZ); + setWorldBlock(canvas, x, y, maximumZ, frame, chunkWorldX, chunkWorldZ); } for (int z = minimumZ + 1; z < maximumZ; z++) { - setWorldBlock(terrainChunk, minimumX, y, z, frame, chunkWorldX, chunkWorldZ); - setWorldBlock(terrainChunk, maximumX, y, z, frame, chunkWorldX, chunkWorldZ); + setWorldBlock(canvas, minimumX, y, z, frame, chunkWorldX, chunkWorldZ); + setWorldBlock(canvas, maximumX, y, z, frame, chunkWorldX, chunkWorldZ); } } private void paintTopologyGlyph( - TerrainChunk terrainChunk, + ChunkCanvas canvas, JigsawStudioBay workcell, int chunkWorldX, int chunkWorldZ @@ -366,14 +327,14 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { int localX = worldX - bounds.originX(); for (int worldZ = minimumZ; worldZ <= maximumZ; worldZ++) { int localZ = worldZ - bounds.originZ(); - PlatformBlockState state = topologyGlyphState(topology, bounds.dimensions(), localX, localZ, + BlockState state = topologyGlyphState(topology, bounds.dimensions(), localX, localZ, centerX, centerZ); - setWorldBlock(terrainChunk, worldX, glyphY, worldZ, state, chunkWorldX, chunkWorldZ); + setWorldBlock(canvas, worldX, glyphY, worldZ, state, chunkWorldX, chunkWorldZ); } } } - private PlatformBlockState topologyGlyphState( + private BlockState topologyGlyphState( JigsawPlanarTopology topology, JigsawStudioCellDimensions dimensions, int localX, @@ -426,7 +387,8 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { } private RenderedBay buildRenderedBay(JigsawStudioBay workcell, JigsawStudioVariant variant) { - IrisJigsawPiece piece = StructureResources.piece(request.source().getPackResources(), variant.pieceKey()); + PackResources resources = pack.resources(); + IrisJigsawPiece piece = StructureResources.piece(resources, variant.pieceKey()); if (piece == null) { return RenderedBay.invalid( workcell.bounds().dimensions(), @@ -443,13 +405,13 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { "piece '" + variant.pieceKey() + "' changed its object from '" + variant.objectKey() + "' to '" + piece.getObject() + "'"); } - IrisObject object = request.source().getObjectLoader().load(variant.objectKey(), false); + PlaceableObject object = resources.objects().object(resources.idOf(variant.objectKey())).orElse(null); if (object == null) { return RenderedBay.invalid( workcell.bounds().dimensions(), "object '" + variant.objectKey() + "' is missing"); } - if (object.getW() < 1 || object.getH() < 1 || object.getD() < 1) { + if (object.width() < 1 || object.height() < 1 || object.depth() < 1) { return RenderedBay.invalid( workcell.bounds().dimensions(), "object '" + variant.objectKey() + "' has invalid dimensions"); @@ -463,15 +425,15 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { "object '" + variant.objectKey() + "' does not fit workcell '" + workcell.stableId() + "'"); } - ObjectTurn rotation = ObjectTurn.of(0, -90.0D * quarterTurns, 0); - List blocks = renderBlocks(object, dimensions, quarterTurns, rotation); + PieceTurn rotation = PieceTurn.aroundY(-90 * quarterTurns); + List blocks = renderBlocks(resources.blocks(), object, dimensions, quarterTurns, rotation); if (blocks == null) { return RenderedBay.invalid( dimensions, "object '" + variant.objectKey() + "' contains an invalid or out-of-bounds block"); } - ConnectorRenderResult connectors = renderConnectors(piece, object, dimensions, quarterTurns, rotation); + ConnectorRenderResult connectors = renderConnectors(variant.pieceKey(), piece, object, dimensions, quarterTurns, rotation); if (!connectors.failure().isEmpty()) { return RenderedBay.invalid(dimensions, connectors.failure()); } @@ -479,29 +441,28 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { } private List renderBlocks( - IrisObject object, + BlockRegistry registry, + PlaceableObject object, JigsawStudioCellDimensions dimensions, int quarterTurns, - ObjectTurn rotation + PieceTurn rotation ) { - VectorMap sourceBlocks = object.getBlocks(); - VectorMap sourceTiles = object.getStates(); - Vector3i center = object.getCenter(); + BlockPosition center = object.center(); + List sourceBlocks = object.geometry().blocks(); List blocks = new ArrayList<>(sourceBlocks.size()); - for (Map.Entry entry : sourceBlocks) { - IrisBlockVector signed = entry.getKey(); - int sourceX = signed.getBlockX() + center.getBlockX(); - int sourceY = signed.getBlockY() + center.getBlockY(); - int sourceZ = signed.getBlockZ() + center.getBlockZ(); - if (!inside(sourceX, sourceY, sourceZ, object.getW(), object.getH(), object.getD())) { + for (ObjectBlock source : sourceBlocks) { + int sourceX = source.position().x() + center.x(); + int sourceY = source.position().y() + center.y(); + int sourceZ = source.position().z() + center.z(); + if (!inside(sourceX, sourceY, sourceZ, object.width(), object.height(), object.depth())) { return null; } RotatedPosition position = rotatePosition( sourceX, sourceY, sourceZ, - object.getW(), - object.getD(), + object.width(), + object.depth(), quarterTurns); if (!inside( position.x(), @@ -512,33 +473,33 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { dimensions.depth())) { return null; } - PlatformBlockState blockState = quarterTurns == 0 - ? entry.getValue() - : BlockStateRotation.rotate(rotation, entry.getValue()); + BlockState blockState = quarterTurns == 0 + ? source.state() + : JigsawStudioBlocks.rotated(registry, source.state(), rotation); if (blockState == null) { return null; } - TileData tileData = sourceTiles.get(signed); blocks.add(new RenderedBlock( position.x(), position.y(), position.z(), blockState, - tileData == null ? null : tileData.clone())); + source.blockEntity().orElse(null))); } return List.copyOf(blocks); } private ConnectorRenderResult renderConnectors( + String pieceKey, IrisJigsawPiece piece, - IrisObject object, + PlaceableObject object, JigsawStudioCellDimensions dimensions, int quarterTurns, - ObjectTurn rotation + PieceTurn rotation ) { - KList sourceConnectors = piece.getConnectors(); + List sourceConnectors = piece.getConnectors(); if (sourceConnectors == null) { - return ConnectorRenderResult.invalid("piece '" + piece.getLoadKey() + "' has no connector list"); + return ConnectorRenderResult.invalid("piece '" + pieceKey + "' has no connector list"); } List connectors = new ArrayList<>(sourceConnectors.size()); for (int index = 0; index < sourceConnectors.size(); index++) { @@ -546,29 +507,29 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { if (!validConnectorMetadata(source)) { return ConnectorRenderResult.invalid("connector " + index + " has incomplete metadata"); } - IrisPosition sourcePosition = source.getPosition(); + BlockPosition sourcePosition = source.getPosition(); if (!inside( - sourcePosition.getX(), - sourcePosition.getY(), - sourcePosition.getZ(), - object.getW(), - object.getH(), - object.getD())) { + sourcePosition.x(), + sourcePosition.y(), + sourcePosition.z(), + object.width(), + object.height(), + object.depth())) { return ConnectorRenderResult.invalid("connector " + index + " is outside its object bounds"); } RotatedPosition position = rotatePosition( - sourcePosition.getX(), - sourcePosition.getY(), - sourcePosition.getZ(), - object.getW(), - object.getD(), + sourcePosition.x(), + sourcePosition.y(), + sourcePosition.z(), + object.width(), + object.depth(), quarterTurns); - IrisDirection front = quarterTurns == 0 + JigsawDirection front = quarterTurns == 0 ? source.getDirection() - : rotation.rotate(source.getDirection()); - IrisDirection top = quarterTurns == 0 + : source.getDirection().turnedBy(rotation.quarterTurns()); + JigsawDirection top = quarterTurns == 0 ? source.getTop() - : rotation.rotate(source.getTop()); + : source.getTop().turnedBy(rotation.quarterTurns()); String orientation; try { orientation = orientation(front, top); @@ -582,7 +543,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { + source.getFinalState() + "' cannot be parsed and rotated"); } IrisJigsawConnector connector = copyConnector(source) - .setPosition(new IrisPosition(position.x(), position.y(), position.z())) + .setPosition(new BlockPosition(position.x(), position.y(), position.z())) .setDirection(front) .setTop(top) .setFinalState(finalState); @@ -601,24 +562,21 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { return ConnectorRenderResult.valid(connectors); } - private static String rotatedFinalState( - String finalState, - ObjectTurn rotation, - int quarterTurns - ) { - PlatformBlockState state = B.getStateOrNull(finalState, false); + private String rotatedFinalState(String finalState, PieceTurn rotation, int quarterTurns) { + BlockRegistry registry = pack.resources().blocks(); + BlockState state = registry.find(finalState).orElse(null); if (state == null) { return null; } if (quarterTurns == 0) { return state.key(); } - PlatformBlockState rotated = BlockStateRotation.rotate(rotation, state); + BlockState rotated = JigsawStudioBlocks.rotated(registry, state, rotation); return rotated == null ? null : rotated.key(); } private void paintObject( - TerrainChunk terrainChunk, + ChunkCanvas canvas, JigsawStudioBay workcell, RenderedBay renderedBay, int chunkWorldX, @@ -627,7 +585,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { JigsawStudioBounds bounds = workcell.bounds(); for (RenderedBlock block : renderedBay.blocks()) { setWorldBlock( - terrainChunk, + canvas, bounds.originX() + block.x(), bounds.originY() + block.y(), bounds.originZ() + block.z(), @@ -638,7 +596,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { } private void paintConnectors( - TerrainChunk terrainChunk, + ChunkCanvas canvas, JigsawStudioBay workcell, RenderedBay renderedBay, int chunkWorldX, @@ -646,22 +604,24 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { ) { JigsawStudioBounds bounds = workcell.bounds(); for (RenderedConnector connector : renderedBay.connectors()) { - PlatformBlockState state = jigsawStates.computeIfAbsent( + BlockState state = jigsawStates.computeIfAbsent( connector.orientation(), - key -> B.getState("minecraft:jigsaw[orientation=" + key + "]")); + key -> pack.resources().blocks() + .find("minecraft:jigsaw[orientation=" + key + "]") + .orElse(invalidMarker)); setWorldBlock( - terrainChunk, + canvas, bounds.originX() + connector.x(), bounds.originY() + connector.y(), bounds.originZ() + connector.z(), - state == null ? invalidMarker : state, + state, chunkWorldX, chunkWorldZ); } } private void paintHiddenConnectorFinalStates( - TerrainChunk terrainChunk, + ChunkCanvas canvas, JigsawStudioBay workcell, RenderedBay renderedBay, int chunkWorldX, @@ -671,14 +631,15 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { for (RenderedBlock block : renderedBay.blocks()) { occupied.add(new RenderedPosition(block.x(), block.y(), block.z())); } + BlockRegistry registry = pack.resources().blocks(); JigsawStudioBounds bounds = workcell.bounds(); for (RenderedConnector connector : renderedBay.connectors()) { if (occupied.contains(new RenderedPosition(connector.x(), connector.y(), connector.z()))) { continue; } - PlatformBlockState finalState = B.getStateOrNull(connector.connector().getFinalState(), false); + BlockState finalState = registry.find(connector.connector().getFinalState()).orElse(null); setWorldBlock( - terrainChunk, + canvas, bounds.originX() + connector.x(), bounds.originY() + connector.y(), bounds.originZ() + connector.z(), @@ -689,7 +650,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { } private void paintInvalidBay( - TerrainChunk terrainChunk, + ChunkCanvas canvas, JigsawStudioBay workcell, int chunkWorldX, int chunkWorldZ @@ -699,7 +660,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { int length = Math.min(bounds.dimensions().width(), bounds.dimensions().depth()); for (int offset = 0; offset < length; offset++) { setWorldBlock( - terrainChunk, + canvas, bounds.originX() + offset, y, bounds.originZ() + offset, @@ -707,7 +668,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { chunkWorldX, chunkWorldZ); setWorldBlock( - terrainChunk, + canvas, bounds.maxX() - offset, y, bounds.originZ() + offset, @@ -751,25 +712,25 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { }; } - static String orientation(IrisDirection front, IrisDirection top) { - IrisDirection activeFront = Objects.requireNonNull(front, "Jigsaw connector front"); - IrisDirection activeTop = Objects.requireNonNull(top, "Jigsaw connector top"); - if (activeFront == IrisDirection.UP_POSITIVE_Y || activeFront == IrisDirection.DOWN_NEGATIVE_Y) { + static String orientation(JigsawDirection front, JigsawDirection top) { + JigsawDirection activeFront = Objects.requireNonNull(front, "Jigsaw connector front"); + JigsawDirection activeTop = Objects.requireNonNull(top, "Jigsaw connector top"); + if (activeFront == JigsawDirection.UP_POSITIVE_Y || activeFront == JigsawDirection.DOWN_NEGATIVE_Y) { if (activeTop.isVertical()) { throw new IllegalArgumentException("Vertical jigsaw fronts require a horizontal top direction"); } return directionName(activeFront) + "_" + directionName(activeTop); } - if (activeTop != IrisDirection.UP_POSITIVE_Y) { + if (activeTop != JigsawDirection.UP_POSITIVE_Y) { throw new IllegalArgumentException("Horizontal jigsaw fronts require an upward top direction"); } return directionName(activeFront) + "_up"; } - private static JigsawStudioCellDimensions rotatedDimensions(IrisObject object, int quarterTurns) { + private static JigsawStudioCellDimensions rotatedDimensions(PlaceableObject object, int quarterTurns) { return Math.floorMod(quarterTurns, 2) == 0 - ? new JigsawStudioCellDimensions(object.getW(), object.getH(), object.getD()) - : new JigsawStudioCellDimensions(object.getD(), object.getH(), object.getW()); + ? new JigsawStudioCellDimensions(object.width(), object.height(), object.depth()) + : new JigsawStudioCellDimensions(object.depth(), object.height(), object.width()); } private static boolean fits(JigsawStudioCellDimensions object, JigsawStudioCellDimensions bay) { @@ -802,10 +763,10 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { private static IrisJigsawConnector copyConnector(IrisJigsawConnector source) { return new IrisJigsawConnector() - .setPosition(new IrisPosition( - source.getPosition().getX(), - source.getPosition().getY(), - source.getPosition().getZ())) + .setPosition(new BlockPosition( + source.getPosition().x(), + source.getPosition().y(), + source.getPosition().z())) .setDirection(source.getDirection()) .setTop(source.getTop()) .setPool(source.getPool()) @@ -818,7 +779,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { .setPlacementPriority(source.getPlacementPriority()); } - private static String directionName(IrisDirection direction) { + private static String directionName(JigsawDirection direction) { return switch (direction) { case UP_POSITIVE_Y -> "up"; case DOWN_NEGATIVE_Y -> "down"; @@ -830,23 +791,23 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { } private void setWorldBlock( - TerrainChunk terrainChunk, + ChunkCanvas canvas, int worldX, int worldY, int worldZ, - PlatformBlockState block, + BlockState block, int chunkWorldX, int chunkWorldZ ) { int localX = worldX - chunkWorldX; int localZ = worldZ - chunkWorldZ; - if (localX < 0 || localX >= 16 || localZ < 0 || localZ >= 16) { + if (localX < 0 || localX >= CHUNK_SIZE || localZ < 0 || localZ >= CHUNK_SIZE) { return; } - if (worldY < terrainChunk.getMinHeight() || worldY >= terrainChunk.getMaxHeight()) { + if (worldY < canvas.minY() || worldY >= canvas.maxY()) { return; } - terrainChunk.setBlock(localX, worldY, localZ, block); + canvas.set(localX, worldY, localZ, block); } public record RenderedBay( @@ -883,7 +844,8 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { } } - public record RenderedBlock(int x, int y, int z, PlatformBlockState state, TileData tileData) { + /** A block of the object in the workcell, with the block entity it carries; the entity is null for a plain block. */ + public record RenderedBlock(int x, int y, int z, BlockState state, BlockEntityData blockEntity) { public RenderedBlock { state = Objects.requireNonNull(state, "Jigsaw Studio rendered block state"); } @@ -922,7 +884,7 @@ public final class JigsawStudioGenerator extends EnginedStudioGenerator { @FunctionalInterface interface FinalStateRenderer { - String render(String finalState, ObjectTurn rotation, int quarterTurns); + String render(String finalState, PieceTurn rotation, int quarterTurns); } record RotatedPosition(int x, int y, int z) { diff --git a/module/src/main/java/art/arcane/iris/modules/jigsaw/JigsawDatapackImport.java b/module/src/main/java/art/arcane/iris/modules/jigsaw/JigsawDatapackImport.java new file mode 100644 index 000000000..8d0102ed4 --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/jigsaw/JigsawDatapackImport.java @@ -0,0 +1,58 @@ +/* + * 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.modules.jigsaw; + +import art.arcane.iris.core.structure.BulkStructureImporter; +import art.arcane.iris.core.structure.StructureImporter; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.DatapackImportReport; +import com.volmit.tooling.DatapackStructureImport; +import com.volmit.tooling.PlatformStructures; +import com.volmit.tooling.Sender; +import com.volmit.tooling.ToolPack; + +import java.util.Collection; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; + +/** Imports a datapack's structures and templates as jigsaw structures, replacing what an earlier import of them made. */ +final class JigsawDatapackImport implements DatapackStructureImport { + @Override + public DatapackImportReport importAll(ToolPack pack, PlatformStructures platform, Sender sender, + Collection structures, Collection templates) { + BulkStructureImporter.Report report = BulkStructureImporter.importManagedDatapackStructures( + pack, platform, StructureImporter.Mode.OVERWRITE, sender, keysOf(structures), keysOf(templates)); + return new DatapackImportReport(report.total(), report.imported(), report.skipped(), report.failed(), + importedBundles(report), report.retryRequired()); + } + + private static Set keysOf(Collection ids) { + Set keys = new TreeSet<>(); + ids.forEach(id -> keys.add(id.toString())); + return keys; + } + + private static Map importedBundles(BulkStructureImporter.Report report) { + Map bundles = new TreeMap<>(); + report.successfulBundles().forEach((bundle, source) -> bundles.put(bundle, ResourceId.ofPlatformKey(source))); + return bundles; + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/jigsaw/JigsawModule.java b/module/src/main/java/art/arcane/iris/modules/jigsaw/JigsawModule.java new file mode 100644 index 000000000..586f1627d --- /dev/null +++ b/module/src/main/java/art/arcane/iris/modules/jigsaw/JigsawModule.java @@ -0,0 +1,58 @@ +/* + * 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.modules.jigsaw; + +import art.arcane.iris.core.structure.tooling.JigsawCommands; +import art.arcane.iris.core.structure.tooling.JigsawStudios; +import art.arcane.iris.engine.framework.structure.JigsawStructureAssembly; +import art.arcane.iris.engine.framework.structure.JigsawValidator; +import art.arcane.iris.engine.framework.structure.StructureResources; +import art.arcane.iris.engine.framework.structure.assembly.StructureAssembly; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; +import com.volmit.tooling.DatapackStructureImport; + +/** + * Module {@code iris:jigsaw}: what a structure is made of. It registers the pack's {@code structures}, {@code jigsaw-pools} + * and {@code jigsaw-pieces} resource kinds ({@link StructureResources}), checks them ({@link JigsawValidator}), and builds + * the pieces of the structures {@code iris:structure} places ({@link JigsawStructureAssembly}). + *

+ * It brings the tools that make them: the importers of the platform's structures and of a datapack's + * ({@link DatapackStructureImport}) and the {@code /iris module jigsaw} commands with the in-world Jigsaw Studio, which the + * first command that needs it creates. The studio closes with its tool world, which the host closes when it stops. + */ +public final class JigsawModule implements IrisModule { + private static final String VERSION = "built-in"; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:jigsaw", "Jigsaw", VERSION); + } + + @Override + public void setup(ModuleSetup setup) { + var registry = setup.registry(); + StructureResources.kinds().forEach(registry::registerResourceKind); + registry.registerValidator(new JigsawValidator()); + registry.registerService(StructureAssembly.class, new JigsawStructureAssembly(setup.log())); + registry.registerService(DatapackStructureImport.class, new JigsawDatapackImport()); + setup.tooling().registerCommand(JigsawCommands.root(new JigsawStudios())); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/objects/ForwardingTerrain.java b/module/src/main/java/art/arcane/iris/modules/objects/ForwardingTerrain.java index b3b5866ab..9ff2023ce 100644 --- a/module/src/main/java/art/arcane/iris/modules/objects/ForwardingTerrain.java +++ b/module/src/main/java/art/arcane/iris/modules/objects/ForwardingTerrain.java @@ -90,6 +90,16 @@ public abstract class ForwardingTerrain implements PlacementTerrain { delegate.recordPlacement(x, y, z, placement); } + @Override + public void clearBlock(int x, int y, int z) { + delegate.clearBlock(x, y, z); + } + + @Override + public void clearAttached(int x, int y, int z) { + delegate.clearAttached(x, y, z); + } + @Override public Optional placementAt(int x, int y, int z) { return delegate.placementAt(x, y, z);