Merge feat/structure-jigsaw-modules into port/v3-features

Structure placement and jigsaw now live in the built-in modules jar, on top of the port's weighted picking, studio tooling
and procedural object work.

api/CONTRACTS.md keeps both sides' rows: the weighted entries and the studio bake and scene creation types from the port,
and VanillaStructureContext.world, Argument.reading, PlatformStructures, tool worlds and the services lookup from the
structure move.

PackModuleResourceKindTest installs the built-in modules jar into its castle pack, as the structure move requires, and
writes the dimension and region lists as weighted entries, as the port requires.

StructurePlacing takes the structure move's version. Its int sentinel for a sampled height is replaced by an explicit
sampledHeight flag that calls ObjectRun.automatic, and explicit pieces pass their world Y minus the world's minimum, so an
explicit world Y below zero stays a height (e3dd61c17).

StructureOutputPinTest.everyScenarioPlacesThePinnedStructures is re-baselined for the underground scenario's writes hash
only (9176f55f60410c117cdd9d5e to 1025f82c04539d4881a0e92b): pieces at world Y -1 are now placed there instead of on the
surface. The start count, the piece hash and every other scenario are unchanged.
This commit is contained in:
piexel committed 2026-11-10 14:33:49 +01:00
commit 2889274291
514 files changed
+29979 -15110

No files matched your search

@@ -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()) {
@@ -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
@@ -54,13 +54,14 @@ public class VillageImporterListPoolElementRuntimeContractTest {
StructureTemplatePool.Projection.RIGID
);
VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(towers);
PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(towers);
Map<String, Object> 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<String, Object> 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",
@@ -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(
@@ -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());
}
/**
+4 -2
View File
@@ -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)
@@ -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();
@@ -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;
@@ -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 <https://www.gnu.org/licenses/>.
*/
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())));
}
}
@@ -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<SenderWorld> world;
private final Optional<ServedPack> 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<ToolPlayer> 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);
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<CapturedStructure> 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<CapturedStructure> capturedRef = new AtomicReference<>();
AtomicReference<Throwable> 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<TemplateBlock> 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<BlockEntityData> 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);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<ResourceId> templates() {
try {
return enumerateTemplateKeys();
} catch (Exception e) {
throw new StructureAccessException(ServerReflection.failureDetail(e), true, e);
}
}
@Override
public Optional<StructureTemplate> template(ResourceId id) {
return BukkitTemplateReader.read(Bukkit.getStructureManager().loadStructure(new NamespacedKey(id.namespace(), id.path())));
}
@Override
public List<ResourceId> structures() {
return idsOf(INMS.get().getStructureKeys());
}
@Override
public List<ResourceId> structureSets() {
return idsOf(INMS.get().getStructureSetKeys());
}
@Override
public Optional<JigsawStructureInfo> 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<TemplatePool> 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<ResourceId> fallback = Optional.empty();
Optional<String> 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<TemplatePool.Member> 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<CaptureArea> 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<ResourceId> idsOf(Iterable<String> keys) {
TreeSet<ResourceId> 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<ResourceId> 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<Object> endsWithNbt = location -> {
String path = identifierPath(location);
return path != null && path.endsWith(TEMPLATE_FILE_SUFFIX);
};
Object resultMap = listResources.invoke(resourceManager, STRUCTURE_TEMPLATE_FOLDER, endsWithNbt);
TreeSet<String> 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;
}
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<StructureTemplate> read(Structure structure) {
if (structure == null || structure.getPalettes().isEmpty()) {
return Optional.empty();
}
BlockVector size = structure.getSize();
Palette palette = structure.getPalettes().get(0);
List<TemplateBlock> 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<BlockEntityData> 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<String> 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();
}
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<ResourceId> 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<TemplatePool.Connector> 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<ResourceId> 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<String> 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
) {
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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;
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<BlockEntityData> 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<BlockFace> 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();
};
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<ToolItem> 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<ToolText> lore(ItemMeta meta) {
List<Component> 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));
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<UUID, OpenMenu> 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);
}
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<ToolWorld> 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<BlockPosition> 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<Boolean> 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<Boolean> 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<ToolText> 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<Particle> dust) {
List<Particle> 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<ToolItem> 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<Boolean> returnToOrigin() {
CompletableFuture<Boolean> 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();
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<TextColor, NamedTextColor> 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();
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<Void> 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<ToolPlayer> players() {
return bukkit().getPlayers().stream().<ToolPlayer>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 <T> CompletableFuture<T> call(BlockPosition at, Supplier<T> task) {
CompletableFuture<T> 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<BlockEntityData> blockEntity(BlockPosition at) {
return BukkitToolBlocks.blockEntityOf(ownedBlock(at));
}
@Override
public void setBlock(BlockPosition at, BlockState state, Optional<BlockEntityData> 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<Void> repaint(Collection<ChunkPos> chunks) {
if (isClosed()) {
return CompletableFuture.failedFuture(new IllegalStateException("Tool world " + name + " is closed"));
}
List<CompletableFuture<Void>> repaints = chunks.stream().distinct().map(this::repaintChunk).toList();
return CompletableFuture.allOf(repaints.toArray(CompletableFuture[]::new));
}
@Override
public CompletableFuture<Void> 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<String> closeRefusal() {
try {
return listener.closeRefusal();
} catch (Throwable failure) {
IrisLogging.reportError("The listener of tool world " + name + " failed.", failure);
return Optional.empty();
}
}
@Override
public CompletableFuture<Void> prepareReplacement(Optional<UUID> requestedBy) {
Optional<ToolPlayer> 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<ToolWorldListener, Boolean> 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<ToolWorldListener> 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<Void> sendPlayersBack() {
List<CompletableFuture<Boolean>> 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<Void> repaintChunk(ChunkPos position) {
World target = bukkit();
AtomicReference<Repainted> repainted = new AtomicReference<>();
CompletableFuture<Void> painting = J.afut(() -> repainted.set(paintAgain(target, position)));
CompletableFuture<Chunk> 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;
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<BukkitToolWorld> 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<BukkitToolWorld> 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);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<ToolWorld> open(ToolWorldSpec spec) {
Optional<String> 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<ToolWorld> 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<ToolWorld> 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;
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<String, BukkitToolWorld> byStorageName = new ConcurrentHashMap<>();
private final Map<UUID, BukkitToolWorld> byWorldId = new ConcurrentHashMap<>();
private final Map<String, BukkitToolWorld> 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<BukkitToolWorld> forWorld(World world) {
if (world == null) {
return Optional.empty();
}
BukkitToolWorld bound = byWorldId.get(world.getUID());
return bound != null ? Optional.of(bound) : forOpeningWorld(world);
}
Optional<BukkitToolWorld> forName(String packName, String name) {
return Optional.ofNullable(byPackAndName.get(packAndName(packName, name)));
}
List<BukkitToolWorld> all() {
return new ArrayList<>(byStorageName.values());
}
private Optional<BukkitToolWorld> 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;
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<Long, List<PaintedBlockEntity>> 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<PaintedBlockEntity> take(int chunkX, int chunkZ) {
List<PaintedBlockEntity> 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);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<UUID, BukkitToolPlayer> players = new ConcurrentHashMap<>();
private final Map<UUID, Location> origins = new ConcurrentHashMap<>();
private final Map<UUID, GameMode> 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<Location> 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;
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<BlockPosition> 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<BlockPosition> 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<Player> 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<Block> blocks, Optional<Player> player) {
for (Block block : blocks) {
Optional<ToolPlayer> 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<BukkitToolWorld> 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<BukkitToolWorld> 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<BukkitToolWorld> from = worlds.forWorld(event.getFrom().getWorld());
Optional<BukkitToolWorld> 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> player) {
allowOrCancel(event, cause, block.getWorld(), List.of(positionOf(block)), player, Optional.empty());
}
private void allowOrCancel(
Cancellable event,
Cause cause,
World world,
List<BlockPosition> positions,
Optional<Player> player,
Optional<BlockState> placed
) {
if (!isAllowed(cause, world, positions, player, placed)) {
event.setCancelled(true);
}
}
private void allowPistonOrCancel(Cancellable event, Block piston, List<Block> 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<Block> blocks = containerBlocks(inventory);
if (blocks.isEmpty()) {
return;
}
List<BlockPosition> 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<BlockPosition> positions,
Optional<Player> player,
Optional<BlockState> placed
) {
return isAllowed(cause, world, positions, positions, player, placed);
}
private boolean isAllowed(
Cause cause,
World world,
List<BlockPosition> positions,
List<BlockPosition> changed,
Optional<Player> player,
Optional<BlockState> placed
) {
Optional<BukkitToolWorld> 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<Block> 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<BlockPosition> pistonChecked(List<Block> moved, BlockFace direction) {
List<BlockPosition> 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<BlockPosition> pistonChanged(Block piston, List<Block> moved, BlockFace direction) {
List<BlockPosition> 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<Block> containerBlocks(Inventory inventory) {
if (inventory == null) {
return List.of();
}
List<Block> 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<Block> 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);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<UUID> 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);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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);
}
}
@@ -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<Void> 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) {
@@ -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/<key>.json", createKey.description());
assertEquals("key", openKey.name());
assertEquals(List.of("structure", "name"), List.of(openKey.aliases()));
assertEquals("Existing key loaded from structures/<key>.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<JigsawStudioWorkcellSpec> 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);
}
}
@@ -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);
@@ -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")); }
}
@@ -0,0 +1,33 @@
package art.arcane.iris.core.structure;
import org.junit.Test;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
public class BukkitCaptureAreaFailureTest {
@Test
public void captureFailurePreservesStructureChunkDetailAndCause() {
IllegalArgumentException cause = new IllegalArgumentException("placement broke");
IllegalStateException error = BukkitCaptureArea.captureFailure(
"minecraft:monument", 12, -8, "platform placement failed", cause);
assertSame(cause, error.getCause());
assertTrue(error.getMessage().contains("minecraft:monument"));
assertTrue(error.getMessage().contains("12,-8"));
assertTrue(error.getMessage().contains("platform placement failed"));
}
@Test
public void captureFailureSupportsInfrastructureFailuresWithoutACause() {
IllegalStateException error = BukkitCaptureArea.captureFailure(
"minecraft:stronghold", -3, 5, "region task was not accepted", null);
assertNull(error.getCause());
assertTrue(error.getMessage().contains("minecraft:stronghold"));
assertTrue(error.getMessage().contains("-3,5"));
assertTrue(error.getMessage().contains("region task was not accepted"));
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<Map<String, Object>> 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<String> getString(String key) {
return "final_state".equals(key) ? Optional.of(finalState) : Optional.empty();
}
}
private static final class FakeListPoolElement {
private final List<Object> elements;
private FakeListPoolElement(List<?> elements) {
this.elements = List.copyOf(elements);
}
public List<Object> 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;
}
}
}
@@ -0,0 +1,44 @@
package art.arcane.iris.core.structure;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* JigsawStructure.maxDistanceFromCenter is a plain int on some server builds and a
* JigsawStructure$MaxDistance record ({int horizontal, int vertical}) on others (e.g. Leaf
* 26.2-33). The reflective member reader must handle both — the wrapper shape previously threw
* IllegalArgumentException from Field.getInt, failing the jigsaw import of every datapack
* structure ("Failed to read jigsaw structure graph").
*/
public class ServerReflectionMaxDistanceReadTest {
private static final class IntShape {
private final int maxDistanceFromCenter = 80;
}
private record MaxDistance(int horizontal, int vertical) {
}
private static final class WrapperShape {
private final MaxDistance maxDistanceFromCenter = new MaxDistance(96, 48);
}
private static final class BoxedShape {
private final Integer maxDistanceFromCenter = 64;
}
@Test
public void readsPlainIntField() throws Exception {
assertEquals(80, ServerReflection.readIntMember(new IntShape(), "maxDistanceFromCenter"));
}
@Test
public void readsLargestIntComponentFromWrapperRecord() throws Exception {
assertEquals(96, ServerReflection.readIntMember(new WrapperShape(), "maxDistanceFromCenter"));
}
@Test
public void readsBoxedNumberField() throws Exception {
assertEquals(64, ServerReflection.readIntMember(new BoxedShape(), "maxDistanceFromCenter"));
}
}
@@ -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<ToolItem> 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());
}
}
@@ -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));
}
}
@@ -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;
}
}
@@ -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<BlockChange> changes = new ArrayList<>();
private final List<String> 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<ToolPlayer> 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<ToolPlayer> 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<BlockPosition> 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<BlockPosition> 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<Block> 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<String, EventHandler> byMethod = new HashMap<>();
for (Method method : ToolWorldEvents.class.getDeclaredMethods()) {
EventHandler handler = method.getAnnotation(EventHandler.class);
if (handler != null) {
byMethod.put(method.getName(), handler);
}
}
Set<String> 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<String, EventHandler> byMethod,
Set<String> 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());
}
}
@@ -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<ChunkAccess> 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<Level> 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<Biome> registry = region.registryAccess().lookupOrThrow(Registries.BIOME);
spawnTables.initializeVanillaSpawnBiomes(registry);
ChunkPos center = region.getCenter();
@@ -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<Level> key, String pack, String packDimensionKey, long seed) {
private static Handle inject(MinecraftServer server, ModdedServerAccess serverAccess, String dimensionId, ResourceKey<Level> key, String pack, String packDimensionKey, long seed,
ModdedToolPainting painting) {
RegistryAccess registryAccess = server.registryAccess();
Holder<DimensionType> dimensionType = resolveDimensionType(registryAccess, pack, packDimensionKey);
Holder<Biome> 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);
@@ -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);
@@ -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, "<root> <command...>", 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")
));
@@ -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));
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<CommandSourceStack> tree(String name) {
LiteralArgumentBuilder<CommandSourceStack> root = Commands.literal(name).requires(ModdedCommandTree.GATE);
root.executes((CommandContext<CommandSourceStack> 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<CommandSourceStack> message(String name, String text) {
return Commands.literal(name)
.executes((CommandContext<CommandSourceStack> context) -> {
IrisModdedCommands.fail(context.getSource(), text);
return 0;
})
.then(Commands.argument("args", StringArgumentType.greedyString())
.executes((CommandContext<CommandSourceStack> context) -> {
IrisModdedCommands.fail(context.getSource(), text);
return 0;
}));
}
}
@@ -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<String> 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<Void> 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<String> 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;
}
@@ -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<SenderWorld> 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<ToolPlayer> player() {
return Optional.ofNullable(source.getPlayer()).map(ModdedToolWorldService::toolPlayerOf);
}
@Override
public boolean isOperator() {
return ModdedCommandTree.GATE.test(source);
@@ -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 <https://www.gnu.org/licenses/>.
*/
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);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<InteractionResult> 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<InteractionResult> result) {
ToolWorldGuard.exit(context.getLevel());
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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();
}
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<InteractionResult> 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<InteractionResult> 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<Boolean> 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<Boolean> result) {
ToolWorldGuard.exit(level);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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();
}
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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();
}
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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();
}
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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();
}
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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();
}
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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());
}
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<Boolean> result) {
if (!ToolWorldGuard.setBlockAllowed((Level) (Object) this, position, state)) {
result.setReturnValue(false);
}
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<MobCategory> categories, CallbackInfo info) {
if (ToolWorldGuard.isToolWorld(level)) {
info.cancel();
}
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<Boolean> 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<Boolean> result) {
ToolWorldGuard.exit(level);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<Integer> result) {
ToolWorldGuard.enter(level, Cause.EXPLOSION, null, false);
}
@Inject(method = "explode", at = @At("RETURN"))
private void iris$endExplosion(CallbackInfoReturnable<Integer> result) {
ToolWorldGuard.exit(level);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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());
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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();
}
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<Boolean> 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<Boolean> 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<InteractionResult> 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<InteractionResult> 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<InteractionResult> 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<InteractionResult> 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);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<PlatformStructures.CaptureArea> open(MinecraftServer server, Sender sender) {
Optional<String> 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<String> 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<CapturedStructure> 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<TemplateBlock> 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> T onServerThread(MinecraftServer server, Supplier<T> task, long timeoutSeconds) {
CompletableFuture<T> 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);
}
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<ResourceId> templates() {
MinecraftServer server = server();
List<Identifier> 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<StructureTemplate> template(ResourceId id) {
return server().getStructureManager().get(identifierOf(id)).flatMap(TemplateReading::read);
}
@Override
public List<ResourceId> structures() {
return idsOf(registries().lookupOrThrow(Registries.STRUCTURE).keySet());
}
@Override
public List<ResourceId> structureSets() {
return idsOf(registries().lookupOrThrow(Registries.STRUCTURE_SET).keySet());
}
@Override
public Optional<JigsawStructureInfo> 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<TemplatePool> pool(ResourceId poolKey) {
MinecraftServer server = server();
Registry<StructureTemplatePool> registry = server.registryAccess().lookupOrThrow(Registries.TEMPLATE_POOL);
StructureTemplatePool pool = registry.getValue(identifierOf(poolKey));
if (pool == null) {
return Optional.empty();
}
Optional<ResourceId> fallback = Optional.empty();
Optional<String> 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<TemplatePool.Member> 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<Identifier> poolKeyOf(Registry<StructureTemplatePool> registry, Holder<StructureTemplatePool> holder) {
Optional<ResourceKey<StructureTemplatePool>> 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<CaptureArea> 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<ResourceId> idsOf(Collection<Identifier> keys) {
TreeSet<ResourceId> 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);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<StructurePoolElement, Integer> 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<ResourceId> 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<StructurePoolElement> 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<StructureTemplate.JigsawBlockInfo> 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<TemplatePool.Connector> 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<String> 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;
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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> T read(Object owner, String name, Class<T> 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);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<com.volmit.tooling.StructureTemplate> read(StructureTemplate template) {
List<?> palettes = PrivateFields.readList(template, PALETTES_FIELD);
if (palettes.isEmpty()) {
return Optional.empty();
}
Vec3i size = template.getSize();
List<TemplateBlock> 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<BlockEntityData> 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<String> finalStateOf(CompoundTag nbt) {
if (nbt == null) {
return Optional.empty();
}
return nbt.getString(FINAL_STATE_NBT_KEY).filter(finalState -> !finalState.isBlank());
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<Painted> 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<Painted> 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());
}
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<Heightmap.Types> 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);
}
}
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<ServerPlayer> 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<ToolWorld> 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<BlockPosition> 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<Boolean> 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<Boolean> arrived = new CompletableFuture<>();
server().execute(() -> {
Optional<ServerPlayer> 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<Boolean> arrived, Boolean success, Throwable failure,
ModdedToolWorld target, float yaw, float pitch) {
if (failure != null) {
arrived.completeExceptionally(failure);
return;
}
Optional<ServerPlayer> 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<SoundEvent> 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<ToolText> 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<Particle> dust) {
List<Particle> 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<ToolItem> 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<Boolean> returnToOrigin() {
CompletableFuture<Boolean> returned = new CompletableFuture<>();
server().execute(() -> {
Optional<ServerPlayer> 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;
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<Void> 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<ToolPlayer> players() {
return level().players().stream().<ToolPlayer>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 <T> CompletableFuture<T> call(BlockPosition at, Supplier<T> task) {
CompletableFuture<T> 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<BlockEntityData> blockEntity(BlockPosition at) {
requireOwned(at);
return ToolBlocks.blockEntityOf(level(), ToolBlocks.blockPosOf(at));
}
@Override
public void setBlock(BlockPosition at, BlockState state, Optional<BlockEntityData> 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<Void> repaint(Collection<ChunkPos> chunks) {
if (isClosed()) {
return CompletableFuture.failedFuture(new IllegalStateException("Tool world " + name + " is closed"));
}
List<ChunkPos> distinct = chunks.stream().distinct().toList();
CompletableFuture<Void> 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<Void> close() {
if (!closing.compareAndSet(false, true)) {
return closed;
}
server().execute(this::sendPlayersBackThenRemove);
return closed;
}
private void sendPlayersBackThenRemove() {
List<CompletableFuture<Boolean>> 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<String> closeRefusal() {
try {
return listener.closeRefusal();
} catch (Throwable failure) {
ModdedIrisLog.error("The listener of tool world {} failed.", name, failure);
return Optional.empty();
}
}
CompletableFuture<Void> prepareReplacement(Optional<ToolPlayer> 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<ToolWorldListener, Boolean> 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<ToolWorldListener> 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;
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<ModdedToolWorld> 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<ModdedToolWorld> 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<String> 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<Void> closeForStudioChange(Optional<ServerPlayer> by) {
Optional<ToolPlayer> requestedBy = by.map(PLAYERS::of);
List<ModdedToolWorld> 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)));
}
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<ToolWorld> open(ToolWorldSpec spec) {
MinecraftServer server = ModdedEngineBootstrap.currentServer();
if (server == null) {
return CompletableFuture.failedFuture(new IllegalStateException("No server is running"));
}
Optional<String> 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<ToolWorld> opened = new CompletableFuture<>();
server.execute(() -> create(server, world, opened));
return opened;
}
private void create(MinecraftServer server, ModdedToolWorld world, CompletableFuture<ToolWorld> 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<String> 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<ToolWorld> find(String name) {
return ToolWorldRegistry.INSTANCE.forName(packName, name).filter(ModdedToolWorld::isBound).map(world -> world);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<BlockFace> 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<BlockEntityData> 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());
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<ToolItem> 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<String> 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);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<MenuType<ChestMenu>> 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<UUID, Screen> 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<Integer, MenuButton> 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<Integer, MenuButton> 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);
}
}
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<Level> 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<UUID, ModdedToolPlayer> known = new ConcurrentHashMap<>();
private final Map<UUID, Origin> origins = new ConcurrentHashMap<>();
private final Map<UUID, GameType> modesBeforeCreative = new ConcurrentHashMap<>();
private final Map<UUID, Seen> 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<Boolean> 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<Boolean> 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<UUID> 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<ModdedToolWorld> 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();
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<UUID, Integer> 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<ToolText> 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);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<TextColor, ChatFormatting> 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;
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<Scope> CURRENT = new ThreadLocal<>();
private static final ThreadLocal<Integer> 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<BlockState> 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<ToolPlayer> player, List<BlockPosition> positions,
Optional<BlockState> placed) {
return allowed(level, cause, player, positions, positions, placed);
}
public static boolean allowed(Level level, Cause cause, Optional<ToolPlayer> player, List<BlockPosition> positions,
List<BlockPosition> changed, Optional<BlockState> placed) {
Optional<ModdedToolWorld> 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<ModdedToolWorld> 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<ToolPlayer> toolPlayerOf(Entity entity) {
return actorPlayer(entity);
}
static Optional<ModdedToolWorld> worldOf(Level level) {
if (!ToolWorldRegistry.INSTANCE.hasWorlds() || !(level instanceof ServerLevel serverLevel)) {
return Optional.empty();
}
return ToolWorldRegistry.INSTANCE.forLevel(serverLevel);
}
private static Optional<ToolPlayer> actorPlayer(Entity actor) {
if (actor instanceof ServerPlayer player) {
return Optional.of(ModdedToolWorldService.players().of(player));
}
return Optional.empty();
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<com.volmit.block.BlockState> 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<BlockPos> moved = new ArrayList<>(resolver.getToPush());
moved.addAll(resolver.getToDestroy());
List<BlockPosition> checked = new ArrayList<>();
List<BlockPosition> 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<BlockPosition> 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<ModdedToolWorld> world = ToolWorldGuard.worldOf(closer.level());
if (world.isEmpty() || !(closer instanceof ServerPlayer player)) {
return;
}
Optional<ToolPlayer> 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<BlockPosition> containerBlocks(AbstractContainerMenu menu) {
List<BlockPosition> blocks = new ArrayList<>(2);
for (Slot slot : menu.slots) {
addBlocksOf(blocks, slot.container);
}
return blocks;
}
private static void addBlocksOf(List<BlockPosition> 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<ModdedToolWorld> 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);
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<String, ModdedToolWorld> 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<ModdedToolWorld> forLevel(ServerLevel level) {
return Optional.ofNullable(byDimensionId.get(level.dimension().identifier().toString()));
}
Optional<ModdedToolWorld> forName(String packName, String name) {
return byDimensionId.values().stream()
.filter(world -> world.packName().equals(packName) && world.name().equals(name))
.findFirst();
}
List<ModdedToolWorld> all() {
return List.copyOf(byDimensionId.values());
}
void clear() {
byDimensionId.clear();
}
}
@@ -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": {
@@ -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<CommandSourceStack> node : iris.getChildren()) {
assertTrue(node.getName() + " must be a literal", node instanceof LiteralCommandNode);
}
for (CommandNode<CommandSourceStack> node : child(iris, "structure").getChildren()) {
assertTrue("structure " + node.getName() + " must be a literal", node instanceof LiteralCommandNode);
}
for (String branch : new String[]{"module", "m"}) {
CommandNode<CommandSourceStack> 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<CommandSourceStack> iris = irisNode();
for (String structure : new String[]{"structure", "struct", "str"}) {
assertNull(structure, iris.getChild(structure));
}
assertFalse(ModdedCommandHelp.sections().contains("structure"));
}
private static CommandNode<CommandSourceStack> child(
@@ -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 {
@@ -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 <https://www.gnu.org/licenses/>.
*/
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> T registered(ResourceKey<net.minecraft.core.Registry<T>> 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<StructurePoolElement, Integer> 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());
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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));
}
}
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<Component> 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<Component> 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());
}
}
@@ -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<BlockPos, BlockState> blocks = flatTerrain(area);
Map<BlockPos, BlockState> 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));