From 3691611c6cd33ce4da1bfed36c1e25d3851c8561 Mon Sep 17 00:00:00 2001 From: piexel Date: Sun, 8 Nov 2026 15:30:39 +0100 Subject: [PATCH] Give tools a platform-neutral world api and let modules ask each other's services PackWorld, ValidationContext and ToolPack answer services(type) with the pack's providers. com.volmit.tooling.world lets a tool open a painter-backed world and drive its players, menus, items and block changes; ToolPack.worlds() and Sender.player() reach it. The Bukkit adapter implements it over the studio world creation with a painter slot keyed by world, one protection listener, VolmLib menus, persistent-data items and BoardSVC sidebars. Other platforms answer that tool worlds are not supported yet. --- .../src/main/java/art/arcane/iris/Iris.java | 4 + .../core/service/BukkitToolingSender.java | 15 +- .../iris/core/toolworld/BukkitToolBlocks.java | 99 ++++ .../iris/core/toolworld/BukkitToolItems.java | 107 ++++ .../iris/core/toolworld/BukkitToolMenus.java | 119 ++++ .../iris/core/toolworld/BukkitToolPlayer.java | 238 ++++++++ .../iris/core/toolworld/BukkitToolWorld.java | 355 ++++++++++++ .../toolworld/BukkitToolWorldService.java | 60 ++ .../iris/core/toolworld/BukkitToolWorlds.java | 107 ++++ .../iris/core/toolworld/OpenToolWorlds.java | 95 ++++ .../core/toolworld/PendingBlockEntities.java | 51 ++ .../iris/core/toolworld/ToolPlayers.java | 84 +++ .../iris/core/toolworld/ToolWorldEvents.java | 519 ++++++++++++++++++ .../core/toolworld/ToolWorldPresence.java | 46 ++ .../iris/core/toolworld/ToolWorldRules.java | 43 ++ .../core/toolworld/BukkitToolItemsTest.java | 79 +++ .../toolworld/ToolWorldBookkeepingTest.java | 122 ++++ .../core/toolworld/ToolWorldEventsTest.java | 433 +++++++++++++++ .../modded/command/ModdedToolingSender.java | 9 +- api/CONTRACTS.md | 5 +- api/DESIGN.md | 37 +- api/README.md | 49 +- .../java/com/volmit/geometry/ChunkPos.java | 14 + .../main/java/com/volmit/tooling/Sender.java | 4 + .../java/com/volmit/tooling/ToolPack.java | 15 + .../com/volmit/tooling/world/BlockChange.java | 58 ++ .../com/volmit/tooling/world/ChunkCanvas.java | 30 + .../volmit/tooling/world/ChunkPainter.java | 16 + .../com/volmit/tooling/world/MenuButton.java | 21 + .../com/volmit/tooling/world/MenuClick.java | 14 + .../com/volmit/tooling/world/Particle.java | 21 + .../com/volmit/tooling/world/ToolItem.java | 26 + .../com/volmit/tooling/world/ToolMenu.java | 41 ++ .../com/volmit/tooling/world/ToolPlayer.java | 86 +++ .../com/volmit/tooling/world/ToolUse.java | 36 ++ .../com/volmit/tooling/world/ToolWorld.java | 84 +++ .../tooling/world/ToolWorldListener.java | 58 ++ .../volmit/tooling/world/ToolWorldSpec.java | 29 + .../com/volmit/tooling/world/ToolWorlds.java | 26 + .../volmit/validation/ValidationContext.java | 11 + .../main/java/com/volmit/world/PackWorld.java | 12 + .../tooling/world/ToolWorldRecordsTest.java | 105 ++++ .../java/com/volmit/host/ExposedPackages.java | 13 +- .../java/com/volmit/host/ModuleWorld.java | 6 + .../com/volmit/host/ExposedPackagesTest.java | 2 + .../java/com/volmit/host/ExtensionsTest.java | 1 + .../volmit/host/PackWorldServicesTest.java | 81 +++ .../java/com/volmit/support/TestWorld.java | 22 +- .../iris/core/modules/IrisPackWorld.java | 6 + .../core/modules/IrisValidationContext.java | 5 + .../core/modules/ModuleObjectPlacement.java | 2 +- .../iris/core/modules/PackServices.java | 49 ++ .../arcane/iris/core/modules/ToolWorld.java | 13 +- .../core/runtime/StudioOpenCoordinator.java | 18 +- .../iris/core/runtime/StudioPainterSlots.java | 96 ++++ .../arcane/iris/core/service/BoardSVC.java | 94 +++- .../iris/core/tooling/IrisToolPack.java | 15 + .../iris/core/tooling/ToolWorldsHost.java | 30 + .../core/tooling/UnsupportedToolWorlds.java | 47 ++ .../engine/platform/BukkitChunkGenerator.java | 37 +- .../platform/studio/TerrainChunkCanvas.java | 102 ++++ .../generators/PainterStudioGenerator.java | 76 +++ .../iris/core/modules/CarveTestWorld.java | 5 + .../iris/core/modules/ToolWorldTest.java | 23 +- .../StudioOpenCoordinatorOpenKindTest.java | 12 + .../core/runtime/StudioPainterSlotsTest.java | 67 +++ .../core/service/BoardSVCToolSidebarTest.java | 35 ++ .../iris/core/tooling/IrisToolPackTest.java | 47 ++ .../iris/core/tooling/RecordingSender.java | 7 + .../tooling/UnsupportedToolWorldsTest.java | 31 ++ .../iris/engine/loot/LootValidatorTest.java | 5 + .../arcane/iris/engine/modifier/ApiChunk.java | 5 + .../studio/TerrainChunkCanvasTest.java | 125 +++++ .../PainterStudioGeneratorTest.java | 85 +++ .../iris/engine/terrain/TestLayerBlocks.java | 6 + .../iris/engine/terrain/TestPackWorld.java | 5 + 76 files changed, 4533 insertions(+), 23 deletions(-) create mode 100644 adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolBlocks.java create mode 100644 adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolItems.java create mode 100644 adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolMenus.java create mode 100644 adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolPlayer.java create mode 100644 adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorld.java create mode 100644 adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorldService.java create mode 100644 adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorlds.java create mode 100644 adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/OpenToolWorlds.java create mode 100644 adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/PendingBlockEntities.java create mode 100644 adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolPlayers.java create mode 100644 adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolWorldEvents.java create mode 100644 adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolWorldPresence.java create mode 100644 adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolWorldRules.java create mode 100644 adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/BukkitToolItemsTest.java create mode 100644 adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/ToolWorldBookkeepingTest.java create mode 100644 adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/ToolWorldEventsTest.java create mode 100644 api/api/src/main/java/com/volmit/geometry/ChunkPos.java create mode 100644 api/api/src/main/java/com/volmit/tooling/world/BlockChange.java create mode 100644 api/api/src/main/java/com/volmit/tooling/world/ChunkCanvas.java create mode 100644 api/api/src/main/java/com/volmit/tooling/world/ChunkPainter.java create mode 100644 api/api/src/main/java/com/volmit/tooling/world/MenuButton.java create mode 100644 api/api/src/main/java/com/volmit/tooling/world/MenuClick.java create mode 100644 api/api/src/main/java/com/volmit/tooling/world/Particle.java create mode 100644 api/api/src/main/java/com/volmit/tooling/world/ToolItem.java create mode 100644 api/api/src/main/java/com/volmit/tooling/world/ToolMenu.java create mode 100644 api/api/src/main/java/com/volmit/tooling/world/ToolPlayer.java create mode 100644 api/api/src/main/java/com/volmit/tooling/world/ToolUse.java create mode 100644 api/api/src/main/java/com/volmit/tooling/world/ToolWorld.java create mode 100644 api/api/src/main/java/com/volmit/tooling/world/ToolWorldListener.java create mode 100644 api/api/src/main/java/com/volmit/tooling/world/ToolWorldSpec.java create mode 100644 api/api/src/main/java/com/volmit/tooling/world/ToolWorlds.java create mode 100644 api/api/src/test/java/com/volmit/tooling/world/ToolWorldRecordsTest.java create mode 100644 api/host/src/test/java/com/volmit/host/PackWorldServicesTest.java create mode 100644 core/src/main/java/art/arcane/iris/core/modules/PackServices.java create mode 100644 core/src/main/java/art/arcane/iris/core/runtime/StudioPainterSlots.java create mode 100644 core/src/main/java/art/arcane/iris/core/tooling/ToolWorldsHost.java create mode 100644 core/src/main/java/art/arcane/iris/core/tooling/UnsupportedToolWorlds.java create mode 100644 core/src/main/java/art/arcane/iris/engine/platform/studio/TerrainChunkCanvas.java create mode 100644 core/src/main/java/art/arcane/iris/engine/platform/studio/generators/PainterStudioGenerator.java create mode 100644 core/src/test/java/art/arcane/iris/core/runtime/StudioPainterSlotsTest.java create mode 100644 core/src/test/java/art/arcane/iris/core/service/BoardSVCToolSidebarTest.java create mode 100644 core/src/test/java/art/arcane/iris/core/tooling/UnsupportedToolWorldsTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/platform/studio/TerrainChunkCanvasTest.java create mode 100644 core/src/test/java/art/arcane/iris/engine/platform/studio/generators/PainterStudioGeneratorTest.java diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/Iris.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/Iris.java index 34bb5769f..7e4e0f25a 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/Iris.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/Iris.java @@ -46,6 +46,8 @@ 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.tooling.ToolWorldsHost; import art.arcane.iris.api.terrain.IrisTerrainService; import art.arcane.iris.core.link.IrisPapiInstaller; import art.arcane.iris.core.link.IrisPapiListener; @@ -629,6 +631,7 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware { new EntityRiseSVC(), new WandSVC(), new BoardSVC(), + new BukkitToolWorldService(), new IrisIntegrationService(), new MultiverseSVC(), new IrisProtocolService(), @@ -640,6 +643,7 @@ 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(BlockEditAccess.class, services.get(EditSVC.class)); IrisServices.register(PreservationRegistry.class, services.get(PreservationSVC.class)); compat = IrisCompat.configured(getDataFile("compat.json")); diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/service/BukkitToolingSender.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/service/BukkitToolingSender.java index 52c0dbaa2..a41650b08 100644 --- a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/service/BukkitToolingSender.java +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/service/BukkitToolingSender.java @@ -19,6 +19,7 @@ package art.arcane.iris.core.service; import art.arcane.iris.core.project.IrisProject; +import art.arcane.iris.core.toolworld.BukkitToolWorldService; import art.arcane.iris.core.tooling.IrisServedPack; import art.arcane.iris.core.tooling.SenderWorld; import art.arcane.iris.core.tooling.ServedPack; @@ -30,6 +31,7 @@ import art.arcane.iris.spi.IrisServices; import art.arcane.iris.util.common.format.C; import art.arcane.iris.util.common.plugin.VolmitSender; import art.arcane.iris.util.common.scheduling.J; +import com.volmit.tooling.world.ToolPlayer; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -39,13 +41,13 @@ import java.util.Optional; * A Bukkit sender of a tooling command. It reads the world the sender stands in and the open studio when it is built, which * the adapter does on the thread that received the command, and delivers messages on the sender's own thread. */ -final class BukkitToolingSender implements ToolingSender { +public final class BukkitToolingSender implements ToolingSender { private final CommandSender sender; private final VolmitSender messages; private final Optional world; private final Optional openStudioPack; - BukkitToolingSender(CommandSender sender) { + public BukkitToolingSender(CommandSender sender) { this.sender = sender; this.messages = new VolmitSender(sender); this.world = standingWorld(sender); @@ -77,6 +79,15 @@ final class BukkitToolingSender implements ToolingSender { return type.isInstance(sender) ? Optional.of(type.cast(sender)) : Optional.empty(); } + @Override + public Optional player() { + BukkitToolWorldService toolWorlds = IrisServices.getOrNull(BukkitToolWorldService.class); + if (!(sender instanceof Player player) || toolWorlds == null) { + return Optional.empty(); + } + return Optional.of(toolWorlds.playerOf(player)); + } + @Override public boolean isOperator() { return sender.hasPermission(CommandSVC.ROOT_PERMISSION); diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolBlocks.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolBlocks.java new file mode 100644 index 000000000..9bae0e4a4 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolBlocks.java @@ -0,0 +1,99 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.toolworld; + +import art.arcane.iris.core.modules.BlockEntities; +import art.arcane.iris.engine.object.prefab.TileData; +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockFace; +import com.volmit.geometry.BlockPosition; +import com.volmit.object.BlockEntityData; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.data.BlockData; + +import java.util.Optional; + +/** Blocks, positions and block entities between the tool world api and Bukkit. */ +final class BukkitToolBlocks { + private BukkitToolBlocks() { + } + + static BlockPosition positionOf(Block block) { + return new BlockPosition(block.getX(), block.getY(), block.getZ()); + } + + static BlockPosition positionOf(Location location) { + return new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + } + + static Block blockAt(World world, BlockPosition at) { + return world.getBlockAt(at.x(), at.y(), at.z()); + } + + /** The complete state of {@code data}, with every property. */ + static BlockState stateOf(BlockData data) { + return BlockState.parse(data.getAsString()); + } + + /** + * The platform's data for {@code state}. + * + * @throws IllegalArgumentException when the platform has no such block or property + */ + static BlockData dataOf(BlockState state) { + return Bukkit.createBlockData(state.key()); + } + + /** The block entity of {@code block}; empty for a block without one. */ + static Optional blockEntityOf(Block block) { + return Optional.ofNullable(TileData.getTileState(block, false)).map(BlockEntities::of); + } + + /** + * Writes {@code data} into the block entity of {@code block}, which must already be the block it was made for. + * + * @throws IllegalArgumentException when the block cannot take it, or the data is not in the format Iris stores + */ + static void applyBlockEntity(Block block, BlockEntityData data) { + TileData tile = BlockEntities.tileOf(data); + if (!TileData.setTileState(block, tile)) { + throw new IllegalArgumentException("The block " + block.getType() + " at " + block.getX() + ", " + block.getY() + + ", " + block.getZ() + " cannot take block entity data of " + tile.getMaterialKey()); + } + } + + /** The api face for a Bukkit face; empty for the diagonals and for {@code SELF}. */ + static Optional faceOf(org.bukkit.block.BlockFace face) { + if (face == null) { + return Optional.empty(); + } + return switch (face) { + case UP -> Optional.of(BlockFace.UP); + case DOWN -> Optional.of(BlockFace.DOWN); + case NORTH -> Optional.of(BlockFace.NORTH); + case SOUTH -> Optional.of(BlockFace.SOUTH); + case EAST -> Optional.of(BlockFace.EAST); + case WEST -> Optional.of(BlockFace.WEST); + default -> Optional.empty(); + }; + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolItems.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolItems.java new file mode 100644 index 000000000..f799313df --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolItems.java @@ -0,0 +1,107 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.toolworld; + +import com.volmit.resource.ResourceId; +import com.volmit.tooling.world.ToolItem; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.TextDecoration; +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}. */ + 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.displayName(plain(item.name())); + } + if (!item.lore().isEmpty()) { + meta.lore(item.lore().stream().map(BukkitToolItems::plain).toList()); + } + if (item.glowing()) { + meta.setEnchantmentGlintOverride(true); + } + meta.getPersistentDataContainer().set(PAYLOAD_KEY, PersistentDataType.STRING, item.payload()); + if (!stack.setItemMeta(meta)) { + throw new IllegalStateException("The metadata of tool item " + item.item() + " was rejected"); + } + return stack; + } + + /** The tool item {@code stack} is; empty for nothing, air or a stack without the tool payload. */ + static Optional read(ItemStack stack) { + if (stack == null || stack.getType() == Material.AIR || !stack.hasItemMeta()) { + return Optional.empty(); + } + ItemMeta meta = stack.getItemMeta(); + if (meta == null) { + return Optional.empty(); + } + PersistentDataContainer data = meta.getPersistentDataContainer(); + String payload = data.get(PAYLOAD_KEY, PersistentDataType.STRING); + if (payload == null) { + return Optional.empty(); + } + return Optional.of(new ToolItem( + ResourceId.parse(stack.getType().getKey().toString()), + meta.hasDisplayName() ? plainText(meta.displayName()) : "", + meta.hasLore() ? lore(meta) : List.of(), + Boolean.TRUE.equals(meta.getEnchantmentGlintOverride()), + payload)); + } + + private static List lore(ItemMeta meta) { + List lines = meta.lore(); + return lines == null ? List.of() : lines.stream().map(BukkitToolItems::plainText).toList(); + } + + private static Component plain(String text) { + return Component.text(text).decoration(TextDecoration.ITALIC, false); + } + + private static String plainText(Component component) { + return component == null ? "" : PlainTextComponentSerializer.plainText().serialize(component); + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolMenus.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolMenus.java new file mode 100644 index 000000000..5dc0a0c4f --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolMenus.java @@ -0,0 +1,119 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.toolworld; + +import art.arcane.iris.platform.bukkit.BukkitPlatform; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.util.common.scheduling.J; +import art.arcane.volmlib.util.data.MaterialBlock; +import art.arcane.volmlib.util.inventorygui.UIElement; +import art.arcane.volmlib.util.inventorygui.UIPaneDecorator; +import art.arcane.volmlib.util.inventorygui.UIWindow; +import art.arcane.volmlib.util.inventorygui.WindowResolution; +import com.volmit.tooling.world.MenuButton; +import com.volmit.tooling.world.MenuClick; +import com.volmit.tooling.world.ToolItem; +import com.volmit.tooling.world.ToolMenu; +import org.bukkit.Material; +import org.bukkit.entity.Player; + +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** The chest menus tools open for players, as VolmLib inventory windows. */ +final class BukkitToolMenus { + private static final int MAX_TITLE_LENGTH = 32; + private static final int SLOTS_PER_ROW = ToolMenu.SLOTS_PER_ROW; + private static final int CENTER_SLOT_OFFSET = SLOTS_PER_ROW / 2; + + private final Map windows = new ConcurrentHashMap<>(); + + /** Opens {@code menu} for {@code viewer}, closing the one they had. Runs on the viewer's thread. */ + void open(BukkitToolPlayer viewer, ToolMenu menu) { + Player player = viewer.bukkit(); + close(player); + UUID playerId = player.getUniqueId(); + UIWindow window = new UIWindow(BukkitPlatform.volmitPlugin(), player); + window.setResolution(WindowResolution.W9_H6); + window.setViewportHeight(menu.rows()); + window.setDecorator(new UIPaneDecorator(Material.BLACK_STAINED_GLASS_PANE)); + window.setTitle(shortened(menu.title())); + window.onClosed(closed -> { + windows.remove(playerId, window); + runGuarded(menu.onClose(), "menu close handler of " + player.getName()); + }); + for (MenuButton button : menu.buttons()) { + window.setElement(positionOf(button.slot()), button.slot() / SLOTS_PER_ROW, element(viewer, button)); + } + windows.put(playerId, window); + window.open(); + } + + /** Closes the player's menu; does nothing when none is open. Runs on the player's thread. */ + void close(Player player) { + UIWindow window = windows.remove(player.getUniqueId()); + if (window != null) { + 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(icon.name()) + .setEnchanted(icon.glowing()); + icon.lore().forEach(element::addLore); + 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)); + 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; + } + + static String shortened(String title) { + return title.length() > MAX_TITLE_LENGTH ? title.substring(0, MAX_TITLE_LENGTH) : title; + } + + private static void runGuarded(Runnable task, String what) { + try { + task.run(); + } catch (RuntimeException failure) { + IrisLogging.reportError("A tool failed in the " + what + ".", failure); + } + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolPlayer.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolPlayer.java new file mode 100644 index 000000000..1b360bd84 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolPlayer.java @@ -0,0 +1,238 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.toolworld; + +import art.arcane.iris.core.service.BoardSVC; +import art.arcane.iris.core.service.BukkitToolingSender; +import art.arcane.iris.platform.bukkit.BukkitPlatform; +import art.arcane.iris.spi.IrisServices; +import art.arcane.iris.util.common.scheduling.J; +import 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.ToolWorld; +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +/** A Bukkit player as a tool sees them. Readers must run on the player's thread; changes hop there by themselves. */ +final class BukkitToolPlayer implements ToolPlayer { + private final Player player; + private final OpenToolWorlds worlds; + private final ToolPlayers players; + private final BukkitToolMenus menus; + + BukkitToolPlayer(Player player, OpenToolWorlds worlds, ToolPlayers players, BukkitToolMenus menus) { + this.player = player; + this.worlds = worlds; + this.players = players; + this.menus = menus; + } + + Player bukkit() { + return player; + } + + @Override + public UUID id() { + return player.getUniqueId(); + } + + @Override + public String name() { + return player.getName(); + } + + @Override + public Sender sender() { + return new BukkitToolingSender(player); + } + + @Override + public Optional world() { + return worlds.forWorld(player.getWorld()).map(world -> world); + } + + @Override + public BlockPosition position() { + return BukkitToolBlocks.positionOf(player.getLocation()); + } + + @Override + public float yaw() { + return player.getLocation().getYaw(); + } + + @Override + public float pitch() { + return player.getLocation().getPitch(); + } + + @Override + public boolean sneaking() { + return player.isSneaking(); + } + + @Override + public void run(Runnable task) { + J.runEntity(player, task); + } + + @Override + public CompletableFuture teleport(ToolWorld world, double x, double y, double z, float yaw, float pitch) { + if (!(world instanceof BukkitToolWorld target)) { + return CompletableFuture.failedFuture(new IllegalArgumentException("Not a tool world of this platform: " + world)); + } + CompletableFuture arrived = new CompletableFuture<>(); + boolean scheduled = J.runEntity(player, () -> BukkitPlatform + .teleportAsync(player, new Location(target.bukkit(), x, y, z, yaw, pitch)) + .whenComplete((success, failure) -> { + if (failure != null) { + arrived.completeExceptionally(failure); + } else { + arrived.complete(Boolean.TRUE.equals(success)); + } + })); + if (!scheduled) { + arrived.complete(false); + } + return arrived; + } + + @Override + public void creative(boolean on) { + J.runEntity(player, () -> { + if (on) { + players.rememberModeBeforeCreative(player); + player.setGameMode(GameMode.CREATIVE); + return; + } + players.restoreGameMode(player); + }); + } + + @Override + public void actionBar(String text) { + J.runEntity(player, () -> player.sendActionBar(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(String title, List lines) { + BoardSVC board = IrisServices.getOrNull(BoardSVC.class); + if (board == null) { + return; + } + J.runEntity(player, () -> board.applyToolSidebar(player, + new BoardSVC.ToolSidebar(player.getWorld().getUID(), title, lines))); + } + + @Override + public void hideSidebar() { + BoardSVC board = IrisServices.getOrNull(BoardSVC.class); + if (board != null) { + board.clearToolSidebar(player); + } + } + + @Override + public void particles(List dust) { + List specks = List.copyOf(dust); + J.runEntity(player, () -> specks.forEach(this::showDust)); + } + + @Override + public void give(ToolItem item) { + ItemStack stack = BukkitToolItems.create(item); + J.runEntity(player, () -> player.getInventory().addItem(stack) + .values() + .forEach(leftover -> player.getWorld().dropItem(player.getLocation(), leftover))); + } + + @Override + public Optional held() { + return BukkitToolItems.read(player.getInventory().getItemInMainHand()); + } + + @Override + public void openMenu(ToolMenu menu) { + J.runEntity(player, () -> menus.open(this, menu)); + } + + @Override + public void closeMenu() { + J.runEntity(player, () -> menus.close(player)); + } + + /** + * Sends the player to where they were before they entered a tool world, or to the spawn of the main world when that + * is not known any more, and gives back the game mode they had. Completes with whether they arrived. + */ + CompletableFuture returnToOrigin() { + CompletableFuture returned = new CompletableFuture<>(); + boolean scheduled = J.runEntity(player, () -> { + menus.close(player); + players.restoreGameMode(player); + Location destination = players.takeOrigin(player) + .filter(this::isOutsideToolWorlds) + .orElseGet(() -> Bukkit.getWorlds().getFirst().getSpawnLocation()); + BukkitPlatform.teleportAsync(player, destination).whenComplete((success, failure) -> { + if (failure != null) { + returned.completeExceptionally(failure); + } else { + returned.complete(Boolean.TRUE.equals(success)); + } + }); + }); + if (!scheduled) { + returned.complete(false); + } + return returned; + } + + private boolean isOutsideToolWorlds(Location location) { + return location.getWorld() != null && worlds.forWorld(location.getWorld()).isEmpty(); + } + + private void showDust(Particle speck) { + org.bukkit.Particle.DustOptions options = new org.bukkit.Particle.DustOptions(Color.fromRGB(speck.rgb()), speck.size()); + player.spawnParticle(org.bukkit.Particle.DUST, speck.x(), speck.y(), speck.z(), 1, 0.0D, 0.0D, 0.0D, 0.0D, options); + } + + @Override + public String toString() { + return "tool player " + player.getName(); + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorld.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorld.java new file mode 100644 index 000000000..0148791b9 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorld.java @@ -0,0 +1,355 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.toolworld; + +import art.arcane.iris.core.nms.INMS; +import art.arcane.iris.core.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.engine.data.chunk.TerrainChunk; +import art.arcane.iris.engine.platform.studio.TerrainChunkCanvas; +import art.arcane.iris.spi.IrisLogging; +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.Chunk; +import org.bukkit.World; +import org.bukkit.block.Block; + +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 { + private static final int CHUNK_SHIFT = 4; + + private final String packName; + private final String name; + private final String storageName; + private final ToolWorldListener listener; + private final StudioPainterSlots.Slot slot; + private final PendingBlockEntities pending; + private final ToolWorldPresence presence = new ToolWorldPresence(); + private final OpenToolWorlds registry; + private final ToolPlayers players; + private final AtomicBoolean closing = new AtomicBoolean(); + private final AtomicBoolean gone = new AtomicBoolean(); + private final CompletableFuture closed = new CompletableFuture<>(); + private 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; + } + + String packName() { + return packName; + } + + /** The logical name of the world's storage, which the generator finds its painter by. */ + String storageName() { + return storageName; + } + + /** Gives the world its Bukkit world, once Bukkit has created it. */ + void bind(World created) { + world = Objects.requireNonNull(created, "created"); + registry.bound(this); + } + + boolean isBound() { + return world != null; + } + + UUID worldId() { + return bukkit().getUID(); + } + + World bukkit() { + World bound = world; + if (bound == null) { + throw new IllegalStateException("The tool world " + name + " is not created yet"); + } + return bound; + } + + ToolWorldPresence presence() { + return presence; + } + + @Override + public String name() { + return name; + } + + @Override + public int minY() { + return bukkit().getMinHeight(); + } + + @Override + public int maxY() { + return bukkit().getMaxHeight(); + } + + @Override + public List players() { + return bukkit().getPlayers().stream().map(players::of).toList(); + } + + @Override + public boolean owns(BlockPosition at) { + return J.isOwnedByCurrentRegion(bukkit(), at.x() >> CHUNK_SHIFT, at.z() >> CHUNK_SHIFT); + } + + @Override + public void run(BlockPosition at, Runnable task) { + World target = bukkit(); + Runnable guarded = () -> runGuarded(task, "task at " + at); + if (!J.runRegion(target, at.x() >> CHUNK_SHIFT, at.z() >> CHUNK_SHIFT, guarded)) { + IrisLogging.warn("Tool world %s could not schedule a task at %s.", name, at); + } + } + + @Override + public CompletableFuture call(BlockPosition at, Supplier task) { + CompletableFuture result = new CompletableFuture<>(); + boolean scheduled = J.runRegion(bukkit(), at.x() >> CHUNK_SHIFT, at.z() >> CHUNK_SHIFT, () -> { + try { + result.complete(task.get()); + } catch (Throwable failure) { + result.completeExceptionally(failure); + } + }); + if (!scheduled) { + result.completeExceptionally(new IllegalStateException("Tool world " + name + " could not schedule a task at " + at)); + } + return result; + } + + @Override + public BlockState block(BlockPosition at) { + return BukkitToolBlocks.stateOf(ownedBlock(at).getBlockData()); + } + + @Override + public Optional blockEntity(BlockPosition at) { + return BukkitToolBlocks.blockEntityOf(ownedBlock(at)); + } + + @Override + public void setBlock(BlockPosition at, BlockState state, Optional data) { + Block block = ownedBlock(at); + block.setBlockData(BukkitToolBlocks.dataOf(state), false); + data.ifPresent(entity -> BukkitToolBlocks.applyBlockEntity(block, entity)); + } + + @Override + public CompletableFuture repaint(Collection chunks) { + if (isClosed()) { + return CompletableFuture.failedFuture(new IllegalStateException("Tool world " + name + " is closed")); + } + List> repaints = chunks.stream().distinct().map(this::repaintChunk).toList(); + return CompletableFuture.allOf(repaints.toArray(CompletableFuture[]::new)); + } + + @Override + public CompletableFuture close() { + if (!closing.compareAndSet(false, true)) { + return closed; + } + sendPlayersBack() + .thenCompose(ignored -> StudioOpenCoordinator.get().closeToolWorld(bukkit())) + .whenComplete((result, failure) -> finishClose(result, failure)); + return closed; + } + + /** The tool's listener asked, with {@code fallback} as the answer when it throws. Runs on the caller's thread. */ + boolean ask(Function question, boolean fallback) { + try { + return question.apply(listener); + } catch (Throwable failure) { + IrisLogging.reportError("The listener of tool world " + name + " failed.", failure); + return fallback; + } + } + + /** Tells the listener something. Runs on the caller's thread. */ + void tell(Consumer news) { + ask(listener -> { + news.accept(listener); + return true; + }, true); + } + + /** A chunk of the world loaded: writes the block entities its paint asked for, then tells the tool. */ + void chunkLoaded(Chunk chunk) { + for (PaintedBlockEntity entity : pending.take(chunk.getX(), chunk.getZ())) { + applyPainted(chunk, entity); + } + tell(toolListener -> toolListener.chunkLoaded(chunk.getX(), chunk.getZ())); + } + + /** Bukkit unloaded the world, whoever asked: it is gone for the tool and for the host. */ + void unloaded() { + if (!gone.compareAndSet(false, true)) { + return; + } + StudioPainterSlots.remove(storageName); + registry.unregister(this); + tell(ToolWorldListener::closed); + } + + /** Called by the opener when creating the world failed: nothing of it is left to unload. */ + void abandon() { + StudioPainterSlots.remove(storageName); + registry.unregister(this); + } + + private void finishClose(StudioOpenCoordinator.StudioCloseResult result, Throwable failure) { + unloaded(); + Throwable cause = failure != null ? unwrap(failure) : result == null ? null : result.failureCause(); + if (cause == null) { + closed.complete(null); + return; + } + closed.completeExceptionally(cause); + } + + private CompletableFuture sendPlayersBack() { + List> departures = bukkit().getPlayers().stream() + .map(player -> players.of(player).returnToOrigin()) + .toList(); + return CompletableFuture.allOf(departures.toArray(CompletableFuture[]::new)); + } + + private record Repainted(TerrainChunk terrain, TerrainChunkCanvas canvas) { + } + + private CompletableFuture repaintChunk(ChunkPos position) { + World target = bukkit(); + AtomicReference repainted = new AtomicReference<>(); + CompletableFuture painting = J.afut(() -> repainted.set(paintAgain(target, position))); + CompletableFuture loading = target.getChunkAtAsync(position.x(), position.z()); + return painting.thenCombine(loading, (ignored, chunk) -> chunk) + .thenCompose(chunk -> J.runRegionFuture(target, position.x(), position.z(), + () -> writeRepainted(target, chunk, repainted.get()))); + } + + private Repainted paintAgain(World target, ChunkPos position) { + TerrainChunk terrain = TerrainChunk.create(target); + TerrainChunkCanvas canvas = TerrainChunkCanvas.onPlatform(terrain); + slot.painter().paint(position.x(), position.z(), canvas); + return new Repainted(terrain, canvas); + } + + private void writeRepainted(World target, Chunk chunk, Repainted repainted) { + if (!INMS.get().applyChunkBlocks(chunk, repainted.terrain())) { + InPlaceChunkRegenerator.applyBlockDiffs(chunk, repainted.terrain().getChunkData(), + target.getMinHeight(), target.getMaxHeight()); + } + repainted.canvas().blockEntities().forEach(entity -> applyPainted(chunk, entity)); + target.refreshChunk(chunk.getX(), chunk.getZ()); + } + + private void applyPainted(Chunk chunk, PaintedBlockEntity entity) { + Block block = chunk.getBlock(entity.x(), entity.y(), entity.z()); + try { + BukkitToolBlocks.applyBlockEntity(block, entity.data()); + } catch (RuntimeException failure) { + IrisLogging.reportError("Tool world " + name + " could not write a block entity at " + + block.getX() + ", " + block.getY() + ", " + block.getZ() + ".", failure); + } + } + + private Block ownedBlock(BlockPosition at) { + requireOpen(); + if (!owns(at)) { + throw new IllegalStateException("The calling thread does not own " + at + " in tool world " + name); + } + return BukkitToolBlocks.blockAt(bukkit(), at); + } + + private void requireOpen() { + if (isClosed()) { + throw new IllegalStateException("Tool world " + name + " is closed"); + } + bukkit(); + } + + private boolean isClosed() { + return closing.get() || gone.get(); + } + + private void runGuarded(Runnable task, String what) { + try { + task.run(); + } catch (Throwable failure) { + IrisLogging.reportError("A task of tool world " + name + " failed: " + what + ".", failure); + } + } + + private static Throwable unwrap(Throwable failure) { + Throwable cursor = failure; + while (cursor instanceof CompletionException && cursor.getCause() != null) { + cursor = cursor.getCause(); + } + return cursor; + } + + @Override + public String toString() { + return "tool world " + name; + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorldService.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorldService.java new file mode 100644 index 000000000..1955b4630 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorldService.java @@ -0,0 +1,60 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.toolworld; + +import art.arcane.iris.core.tooling.ToolWorldsHost; +import art.arcane.iris.platform.bukkit.BukkitPlatform; +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; + +/** + * 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 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); + worlds.all().forEach(BukkitToolWorld::unloaded); + } + + @Override + public ToolWorlds worldsOf(String packName) { + return new BukkitToolWorlds(packName, worlds, players); + } + + /** The tool player for {@code player}, the same object for as long as the player is online. */ + public ToolPlayer playerOf(Player player) { + return players.of(player); + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorlds.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorlds.java new file mode 100644 index 000000000..b8d02e20a --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorlds.java @@ -0,0 +1,107 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.toolworld; + +import art.arcane.iris.core.runtime.StudioOpenCoordinator; +import art.arcane.iris.core.runtime.StudioPainterSlots; +import com.volmit.tooling.world.ToolWorld; +import com.volmit.tooling.world.ToolWorldSpec; +import com.volmit.tooling.world.ToolWorlds; +import org.bukkit.World; + +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; + +/** + * The tool worlds of one pack on Bukkit. A tool world is created through the studio's own world creation, with the + * tool's painter installed first so that even the first chunk is the tool's. + */ +final class BukkitToolWorlds implements ToolWorlds { + private static final String STORAGE_NAME_PREFIX = "iris-"; + private static final long TOOL_WORLD_SEED = 1337L; + + private final String packName; + private final OpenToolWorlds registry; + private final ToolPlayers players; + + BukkitToolWorlds(String packName, OpenToolWorlds registry, ToolPlayers players) { + this.packName = packName; + this.registry = registry; + this.players = players; + } + + @Override + public CompletableFuture open(ToolWorldSpec spec) { + PendingBlockEntities pending = new PendingBlockEntities(); + StudioPainterSlots.Slot slot = new StudioPainterSlots.Slot(spec.painter(), pending::add); + String storageName = STORAGE_NAME_PREFIX + UUID.randomUUID(); + BukkitToolWorld toolWorld = new BukkitToolWorld(packName, spec.name(), storageName, spec.listener(), slot, pending, + registry, players); + if (!registry.register(toolWorld)) { + return CompletableFuture.failedFuture(new IllegalStateException( + "A tool world called " + spec.name() + " is open already in pack " + packName)); + } + StudioPainterSlots.install(storageName, slot); + CompletableFuture opened = new CompletableFuture<>(); + StudioOpenCoordinator.get().open(openRequest(storageName, toolWorld)).whenComplete((result, failure) -> { + if (failure != null) { + toolWorld.abandon(); + opened.completeExceptionally(unwrap(failure)); + return; + } + opened.complete(toolWorld); + }); + return opened; + } + + @Override + public Optional find(String name) { + return registry.forName(packName, name).filter(BukkitToolWorld::isBound).map(world -> world); + } + + private StudioOpenCoordinator.StudioOpenRequest openRequest(String storageName, BukkitToolWorld toolWorld) { + return new StudioOpenCoordinator.StudioOpenRequest( + packName, + null, + null, + TOOL_WORLD_SEED, + storageName, + null, + StudioOpenCoordinator.StudioOpenKind.TOOL, + false, + null, + world -> prepare(toolWorld, world), + System.nanoTime()); + } + + private static void prepare(BukkitToolWorld toolWorld, World created) { + toolWorld.bind(created); + ToolWorldRules.apply(created); + } + + private static Throwable unwrap(Throwable failure) { + Throwable cursor = failure; + while (cursor instanceof CompletionException && cursor.getCause() != null) { + cursor = cursor.getCause(); + } + return cursor; + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/OpenToolWorlds.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/OpenToolWorlds.java new file mode 100644 index 000000000..9078d2d9e --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/OpenToolWorlds.java @@ -0,0 +1,95 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.toolworld; + +import art.arcane.iris.core.IrisWorldStorage; +import org.bukkit.World; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * The tool worlds that are open or opening: found by the Bukkit world they live in, and by the tool's name for them + * within a pack. A world is registered before Bukkit has created it, since chunks load while it is created; until it + * is bound to its Bukkit world it is found by the logical name of its storage, which the creator fixes beforehand. + */ +final class OpenToolWorlds { + private final Map byStorageName = new ConcurrentHashMap<>(); + private final Map byWorldId = new ConcurrentHashMap<>(); + private final Map byPackAndName = new ConcurrentHashMap<>(); + + /** + * Registers {@code world} under its storage name and the name its tool gave it. + * + * @return whether the tool's name was free; when it is not, nothing is registered + */ + boolean register(BukkitToolWorld world) { + if (byPackAndName.putIfAbsent(packAndName(world.packName(), world.name()), world) != null) { + return false; + } + byStorageName.put(world.storageName(), world); + return true; + } + + /** Records the Bukkit world of {@code world}, which is bound already. */ + void bound(BukkitToolWorld world) { + byWorldId.put(world.worldId(), world); + } + + void unregister(BukkitToolWorld world) { + byStorageName.remove(world.storageName(), world); + byPackAndName.remove(packAndName(world.packName(), world.name()), world); + if (world.isBound()) { + byWorldId.remove(world.worldId(), world); + } + } + + /** The tool world that {@code world} is; empty for every other world. */ + Optional forWorld(World world) { + if (world == null) { + return Optional.empty(); + } + BukkitToolWorld bound = byWorldId.get(world.getUID()); + return bound != null ? Optional.of(bound) : forOpeningWorld(world); + } + + Optional forName(String packName, String name) { + return Optional.ofNullable(byPackAndName.get(packAndName(packName, name))); + } + + List all() { + return new ArrayList<>(byStorageName.values()); + } + + private Optional forOpeningWorld(World world) { + boolean anyOpening = byStorageName.values().stream().anyMatch(candidate -> !candidate.isBound()); + if (!anyOpening) { + return Optional.empty(); + } + return Optional.ofNullable(byStorageName.get(IrisWorldStorage.logicalName(world))); + } + + private static String packAndName(String packName, String name) { + return packName + "/" + name; + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/PendingBlockEntities.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/PendingBlockEntities.java new file mode 100644 index 000000000..d94377caf --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/PendingBlockEntities.java @@ -0,0 +1,51 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.toolworld; + +import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedBlockEntity; +import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedChunk; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * The block entities a painter asked for in chunks that are generated but not loaded yet. A chunk is painted on a + * generation thread and its block entities can only be written once it is live, so they wait here for its load. + */ +final class PendingBlockEntities { + private static final int INT_BITS = 32; + + private final Map> byChunk = new ConcurrentHashMap<>(); + + /** Keeps what a paint of a chunk asked for; a later paint of the same chunk replaces it. */ + void add(PaintedChunk painted) { + byChunk.put(chunkKey(painted.chunkX(), painted.chunkZ()), painted.blockEntities()); + } + + /** Hands over what waits for the chunk, once; empty when nothing does. */ + List take(int chunkX, int chunkZ) { + List waiting = byChunk.remove(chunkKey(chunkX, chunkZ)); + return waiting == null ? List.of() : waiting; + } + + private static long chunkKey(int chunkX, int chunkZ) { + return ((long) chunkX << INT_BITS) | (chunkZ & 0xFFFFFFFFL); + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolPlayers.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolPlayers.java new file mode 100644 index 000000000..d54e7bb0b --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolPlayers.java @@ -0,0 +1,84 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.toolworld; + +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * The tool players: one {@link BukkitToolPlayer} for each online player, and what the host remembers about them while + * they are in tool worlds, which is where they came from and the game mode they had before a tool made them creative. + */ +final class ToolPlayers { + private final OpenToolWorlds worlds; + private final BukkitToolMenus menus = new BukkitToolMenus(); + private final Map players = new ConcurrentHashMap<>(); + private final Map origins = new ConcurrentHashMap<>(); + private final Map modesBeforeCreative = new ConcurrentHashMap<>(); + + ToolPlayers(OpenToolWorlds worlds) { + this.worlds = worlds; + } + + BukkitToolPlayer of(Player player) { + return players.computeIfAbsent(player.getUniqueId(), id -> new BukkitToolPlayer(player, worlds, this, menus)); + } + + /** Forgets everything about a player who left the server. */ + void forget(Player player) { + UUID id = player.getUniqueId(); + players.remove(id); + origins.remove(id); + modesBeforeCreative.remove(id); + menus.forget(id); + } + + /** Remembers where a player was before their first step into a tool world; later steps keep the first. */ + void rememberOrigin(Player player, Location origin) { + origins.putIfAbsent(player.getUniqueId(), origin.clone()); + } + + /** Hands over where the player came from, once. */ + Optional takeOrigin(Player player) { + return Optional.ofNullable(origins.remove(player.getUniqueId())); + } + + /** Remembers the game mode of a player a tool makes creative; the first mode is kept while they stay creative. */ + void rememberModeBeforeCreative(Player player) { + modesBeforeCreative.putIfAbsent(player.getUniqueId(), player.getGameMode()); + } + + /** Gives a player the game mode they had before a tool made them creative; does nothing when none did. */ + void restoreGameMode(Player player) { + GameMode previous = modesBeforeCreative.remove(player.getUniqueId()); + if (previous != null) { + player.setGameMode(previous); + } + } + + BukkitToolMenus menus() { + return menus; + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolWorldEvents.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolWorldEvents.java new file mode 100644 index 000000000..4b9024dd0 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolWorldEvents.java @@ -0,0 +1,519 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.toolworld; + +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.tooling.world.BlockChange; +import com.volmit.tooling.world.BlockChange.Cause; +import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolUse; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.DoubleChest; +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockBurnEvent; +import org.bukkit.event.block.BlockCookEvent; +import org.bukkit.event.block.BlockDispenseEvent; +import org.bukkit.event.block.BlockExplodeEvent; +import org.bukkit.event.block.BlockFadeEvent; +import org.bukkit.event.block.BlockFormEvent; +import org.bukkit.event.block.BlockFromToEvent; +import org.bukkit.event.block.BlockGrowEvent; +import org.bukkit.event.block.BlockMultiPlaceEvent; +import org.bukkit.event.block.BlockPistonExtendEvent; +import org.bukkit.event.block.BlockPistonRetractEvent; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.event.block.BlockRedstoneEvent; +import org.bukkit.event.block.BlockSpreadEvent; +import org.bukkit.event.block.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.FurnaceSmeltEvent; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryDragEvent; +import org.bukkit.event.inventory.InventoryMoveItemEvent; +import org.bukkit.event.inventory.InventoryPickupItemEvent; +import org.bukkit.event.player.PlayerBucketEmptyEvent; +import org.bukkit.event.player.PlayerBucketFillEvent; +import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerPortalEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerRespawnEvent; +import org.bukkit.event.player.PlayerTeleportEvent; +import org.bukkit.event.player.PlayerToggleSneakEvent; +import org.bukkit.event.server.ServerCommandEvent; +import org.bukkit.event.world.ChunkLoadEvent; +import org.bukkit.event.world.StructureGrowEvent; +import org.bukkit.event.world.WorldUnloadEvent; +import org.bukkit.inventory.BlockInventoryHolder; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * The one listener that maps Bukkit's events onto {@link com.volmit.tooling.world.ToolWorldListener}, for tool worlds + * only. Every handler first asks whether the event happens in a tool world and does nothing when it does not. The + * priorities and {@code ignoreCancelled} flags are those of the jigsaw studio's own handlers: decisions at HIGHEST so + * that other plugins have had their say, observations at MONITOR. + */ +public final class ToolWorldEvents implements Listener { + private static final String COMMAND_PREFIX = "/"; + + private final OpenToolWorlds worlds; + private final ToolPlayers players; + + ToolWorldEvents(OpenToolWorlds worlds, ToolPlayers players) { + this.worlds = worlds; + this.players = players; + } + + // Block changes: the tool decides, `false` cancels. + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockPlace(BlockPlaceEvent event) { + Block placed = event.getBlockPlaced(); + allowOrCancel(event, Cause.PLACE, placed.getWorld(), List.of(positionOf(placed)), Optional.of(event.getPlayer()), + Optional.of(BukkitToolBlocks.stateOf(placed.getBlockData()))); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockMultiPlace(BlockMultiPlaceEvent event) { + List replaced = event.getReplacedBlockStates().stream() + .map(state -> positionOf(state.getBlock())).toList(); + allowOrCancel(event, Cause.PLACE, event.getBlock().getWorld(), replaced, Optional.of(event.getPlayer()), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockBreak(BlockBreakEvent event) { + allowOrCancel(event, Cause.BREAK, event.getBlock(), Optional.of(event.getPlayer())); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBucketEmpty(PlayerBucketEmptyEvent event) { + allowOrCancel(event, Cause.BUCKET, event.getBlockClicked().getRelative(event.getBlockFace()), Optional.of(event.getPlayer())); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBucketFill(PlayerBucketFillEvent event) { + allowOrCancel(event, Cause.BUCKET, event.getBlockClicked(), Optional.of(event.getPlayer())); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockForm(BlockFormEvent event) { + allowOrCancel(event, Cause.PHYSICS, event.getBlock(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockFade(BlockFadeEvent event) { + allowOrCancel(event, Cause.PHYSICS, event.getBlock(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockSpread(BlockSpreadEvent event) { + allowOrCancel(event, Cause.PHYSICS, event.getBlock().getWorld(), + List.of(positionOf(event.getBlock()), positionOf(event.getSource())), Optional.empty(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockFromTo(BlockFromToEvent event) { + allowOrCancel(event, Cause.FLUID, event.getBlock().getWorld(), + List.of(positionOf(event.getBlock()), positionOf(event.getToBlock())), Optional.empty(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockGrow(BlockGrowEvent event) { + allowOrCancel(event, Cause.GROWTH, event.getBlock(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onStructureGrow(StructureGrowEvent event) { + World world = event.getLocation().getWorld(); + List grown = event.getBlocks().stream().map(state -> positionOf(state.getBlock())).toList(); + if (!grown.isEmpty()) { + allowOrCancel(event, Cause.GROWTH, world, grown, Optional.ofNullable(event.getPlayer()), Optional.empty()); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockBurn(BlockBurnEvent event) { + allowOrCancel(event, Cause.FIRE, event.getBlock(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onBlockRedstone(BlockRedstoneEvent event) { + Block block = event.getBlock(); + if (!isAllowed(Cause.REDSTONE, block.getWorld(), List.of(positionOf(block)), Optional.empty(), Optional.empty())) { + event.setNewCurrent(event.getOldCurrent()); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPistonExtend(BlockPistonExtendEvent event) { + allowOrCancel(event, Cause.PISTON, event.getBlock().getWorld(), + pistonPositions(event.getBlock(), event.getBlocks(), event.getDirection()), Optional.empty(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPistonRetract(BlockPistonRetractEvent event) { + allowOrCancel(event, Cause.PISTON, event.getBlock().getWorld(), + pistonPositions(event.getBlock(), event.getBlocks(), event.getDirection()), Optional.empty(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockExplode(BlockExplodeEvent event) { + keepAllowedBlocks(event.getBlock().getWorld(), event.blockList()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onEntityExplode(EntityExplodeEvent event) { + keepAllowedBlocks(event.getEntity().getWorld(), event.blockList()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onEntityChangeBlock(EntityChangeBlockEvent event) { + Optional actor = event.getEntity() instanceof Player player ? Optional.of(player) : Optional.empty(); + allowOrCancel(event, Cause.ENTITY, event.getBlock(), actor); + } + + // Containers and machines. + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onInventoryClick(InventoryClickEvent event) { + allowContainerOrCancel(event, event.getView().getTopInventory(), event.getWhoClicked() instanceof Player player ? player : null); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onInventoryDrag(InventoryDragEvent event) { + allowContainerOrCancel(event, event.getView().getTopInventory(), event.getWhoClicked() instanceof Player player ? player : null); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onInventoryMove(InventoryMoveItemEvent event) { + allowContainerOrCancel(event, event.getSource(), null); + if (!event.isCancelled()) { + allowContainerOrCancel(event, event.getDestination(), null); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onInventoryPickup(InventoryPickupItemEvent event) { + allowContainerOrCancel(event, event.getInventory(), null); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockCook(BlockCookEvent event) { + allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onFurnaceBurn(FurnaceBurnEvent event) { + allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onFurnaceSmelt(FurnaceSmeltEvent event) { + allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBrew(BrewEvent event) { + allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBrewingStandFuel(BrewingStandFuelEvent event) { + allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockDispense(BlockDispenseEvent event) { + allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty()); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onCrafterCraft(CrafterCraftEvent event) { + allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty()); + } + + // What players do. + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onInteract(PlayerInteractEvent event) { + Player player = event.getPlayer(); + Optional toolWorld = worlds.forWorld(player.getWorld()); + if (toolWorld.isEmpty()) { + return; + } + ToolUse use = new ToolUse( + event.getHand() == org.bukkit.inventory.EquipmentSlot.OFF_HAND ? ToolUse.Hand.OFF : ToolUse.Hand.MAIN, + ToolUse.Action.valueOf(event.getAction().name()), + BukkitToolItems.read(event.getItem()), + Optional.ofNullable(event.getClickedBlock()).map(ToolWorldEvents::positionOf), + BukkitToolBlocks.faceOf(event.getBlockFace())); + ToolPlayer toolPlayer = players.of(player); + if (!toolWorld.get().ask(listener -> listener.used(toolPlayer, use), false)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onToggleSneak(PlayerToggleSneakEvent event) { + Player player = event.getPlayer(); + worlds.forWorld(player.getWorld()).ifPresent(world -> + world.tell(listener -> listener.sneakToggled(players.of(player), event.isSneaking()))); + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPlayerCommand(PlayerCommandPreprocessEvent event) { + Player player = event.getPlayer(); + Optional toolWorld = worlds.forWorld(player.getWorld()); + if (toolWorld.isEmpty()) { + return; + } + String line = lineOf(event.getMessage()); + ToolPlayer toolPlayer = players.of(player); + if (!toolWorld.get().ask(listener -> listener.command(Optional.of(toolPlayer), line), true)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onServerCommand(ServerCommandEvent event) { + String line = lineOf(event.getCommand()); + for (BukkitToolWorld toolWorld : worlds.all()) { + if (!toolWorld.ask(listener -> listener.command(Optional.empty(), line), true)) { + event.setCancelled(true); + return; + } + } + } + + // Arriving, leaving and moving. + + @EventHandler(priority = EventPriority.NORMAL) + public void onJoin(PlayerJoinEvent event) { + worlds.forWorld(event.getPlayer().getWorld()).ifPresent(world -> enter(world, event.getPlayer())); + } + + @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)); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onTeleport(PlayerTeleportEvent event) { + Player player = event.getPlayer(); + Optional from = worlds.forWorld(event.getFrom().getWorld()); + Optional to = event.getTo() == null ? Optional.empty() : worlds.forWorld(event.getTo().getWorld()); + if (from.isPresent() && from.equals(to)) { + return; + } + if (from.isEmpty() && to.isPresent()) { + players.rememberOrigin(player, event.getFrom()); + } + if (from.isPresent() && to.isEmpty()) { + players.restoreGameMode(player); + players.takeOrigin(player); + } + from.ifPresent(world -> leave(world, player)); + to.ifPresent(world -> enter(world, player)); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onRespawn(PlayerRespawnEvent event) { + worlds.forWorld(event.getRespawnLocation().getWorld()).ifPresent(world -> enter(world, event.getPlayer())); + } + + @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); + } + } + + private void enter(BukkitToolWorld world, Player player) { + if (world.presence().enter(player.getUniqueId())) { + world.tell(listener -> listener.entered(players.of(player))); + } + } + + private void leave(BukkitToolWorld world, Player player) { + if (world.presence().leave(player.getUniqueId())) { + world.tell(listener -> listener.left(players.of(player))); + } + } + + private void allowOrCancel(Cancellable event, Cause cause, Block block, Optional player) { + allowOrCancel(event, cause, block.getWorld(), List.of(positionOf(block)), player, Optional.empty()); + } + + private void allowOrCancel( + Cancellable event, + Cause cause, + World world, + List positions, + Optional player, + Optional placed + ) { + if (!isAllowed(cause, world, positions, player, placed)) { + event.setCancelled(true); + } + } + + private void allowContainerOrCancel(Cancellable event, Inventory inventory, Player player) { + List blocks = containerBlocks(inventory); + if (blocks.isEmpty()) { + return; + } + List positions = blocks.stream().map(ToolWorldEvents::positionOf).toList(); + allowOrCancel(event, Cause.CONTAINER, blocks.getFirst().getWorld(), positions, Optional.ofNullable(player), Optional.empty()); + } + + /** Whether the tool lets the change happen; changes outside tool worlds are none of the host's business. */ + private boolean isAllowed( + Cause cause, + World world, + List positions, + Optional player, + Optional placed + ) { + Optional toolWorld = worlds.forWorld(world); + if (toolWorld.isEmpty()) { + return true; + } + BlockChange change = new BlockChange(cause, positions, player.map(players::of).map(ToolPlayer.class::cast), placed); + return toolWorld.get().ask(listener -> listener.blockChanging(change), false); + } + + private void keepAllowedBlocks(World world, List exploded) { + if (worlds.forWorld(world).isEmpty()) { + return; + } + exploded.removeIf(block -> !isAllowed(Cause.EXPLOSION, world, List.of(positionOf(block)), Optional.empty(), Optional.empty())); + } + + /** The piston, each block it moves, and the block each of them leaves and enters, as a protected area is checked. */ + static List pistonPositions(Block piston, List moved, BlockFace direction) { + List positions = new ArrayList<>(); + positions.add(positionOf(piston)); + 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 blocks a container inventory is made of: none for a player's or a menu, two for a double chest. */ + static List containerBlocks(Inventory inventory) { + if (inventory == null) { + return List.of(); + } + List blocks = new ArrayList<>(2); + InventoryHolder holder = inventory.getHolder(); + if (holder instanceof BlockInventoryHolder blockHolder) { + blocks.add(blockHolder.getBlock()); + } else if (holder instanceof DoubleChest doubleChest) { + addBlockOf(blocks, doubleChest.getLeftSide()); + addBlockOf(blocks, doubleChest.getRightSide()); + } + return blocks; + } + + private static void addBlockOf(List blocks, InventoryHolder holder) { + if (holder instanceof BlockInventoryHolder blockHolder && !blocks.contains(blockHolder.getBlock())) { + blocks.add(blockHolder.getBlock()); + } + } + + /** Whether two locations are in one block of one world. */ + static boolean sameBlock(Location from, Location to) { + return from.getWorld() == to.getWorld() + && from.getBlockX() == to.getBlockX() + && from.getBlockY() == to.getBlockY() + && from.getBlockZ() == to.getBlockZ(); + } + + /** What a command line is for the tool: without the slash a player types before it. */ + static String lineOf(String typed) { + return typed.startsWith(COMMAND_PREFIX) ? typed.substring(COMMAND_PREFIX.length()) : typed; + } + + private static BlockPosition positionOf(Block block) { + return BukkitToolBlocks.positionOf(block); + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolWorldPresence.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolWorldPresence.java new file mode 100644 index 000000000..30119e940 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolWorldPresence.java @@ -0,0 +1,46 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.toolworld; + +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Who stands in one tool world, so that the platform's several ways of arriving and leaving (join, teleport, world + * change, respawn, quit) tell the tool once for each stay: {@code entered} on the first of them, {@code left} on the + * first of them after. + */ +final class ToolWorldPresence { + private final Set present = ConcurrentHashMap.newKeySet(); + + /** Whether the player was not here before, which is when the tool hears {@code entered}. */ + boolean enter(UUID player) { + return present.add(player); + } + + /** Whether the player was here, which is when the tool hears {@code left}. */ + boolean leave(UUID player) { + return present.remove(player); + } + + boolean isPresent(UUID player) { + return present.contains(player); + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolWorldRules.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolWorldRules.java new file mode 100644 index 000000000..e5e5b8663 --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/ToolWorldRules.java @@ -0,0 +1,43 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.toolworld; + +import art.arcane.iris.core.runtime.WorldRuntimeControlService; +import org.bukkit.GameRules; +import org.bukkit.World; + +/** + * What every tool world is made to be, whatever the server's studio settings say: no natural mobs, no weather, no + * daylight cycle, no portals, on top of the rules the object and jigsaw studios already use. + */ +final class ToolWorldRules { + private ToolWorldRules() { + } + + /** Applies the rules; runs on the thread that may change the world's rules (the main or global thread). */ + static void apply(World world) { + WorldRuntimeControlService.get().applyObjectStudioWorldRules(world); + world.setGameRule(GameRules.SPAWN_MOBS, false); + world.setGameRule(GameRules.ADVANCE_WEATHER, false); + world.setGameRule(GameRules.ADVANCE_TIME, false); + world.setGameRule(GameRules.ALLOW_ENTERING_NETHER_USING_PORTALS, false); + world.setStorm(false); + world.setThundering(false); + } +} diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/BukkitToolItemsTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/BukkitToolItemsTest.java new file mode 100644 index 000000000..afaf4d6a8 --- /dev/null +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/BukkitToolItemsTest.java @@ -0,0 +1,79 @@ +package art.arcane.iris.core.toolworld; + +import com.volmit.resource.ResourceId; +import com.volmit.tooling.world.ToolItem; +import net.kyori.adventure.text.Component; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.persistence.PersistentDataContainer; +import org.bukkit.persistence.PersistentDataType; +import org.junit.Test; + +import java.util.List; +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class BukkitToolItemsTest { + private ItemStack stackWith(PersistentDataContainer data, ItemMeta meta) { + ItemStack stack = mock(ItemStack.class); + when(stack.getType()).thenReturn(Material.STICK); + when(stack.hasItemMeta()).thenReturn(true); + when(stack.getItemMeta()).thenReturn(meta); + when(meta.getPersistentDataContainer()).thenReturn(data); + return stack; + } + + @Test + public void aStackWithThePayloadReadsBackAsTheToolItemItWasMadeFrom() { + PersistentDataContainer data = mock(PersistentDataContainer.class); + ItemMeta meta = mock(ItemMeta.class); + when(data.get(BukkitToolItems.PAYLOAD_KEY, PersistentDataType.STRING)).thenReturn("select:bay-1"); + when(meta.hasDisplayName()).thenReturn(true); + when(meta.displayName()).thenReturn(Component.text("Select bay")); + when(meta.hasLore()).thenReturn(true); + when(meta.lore()).thenReturn(List.of(Component.text("Right-click to use"))); + when(meta.getEnchantmentGlintOverride()).thenReturn(true); + + Optional item = BukkitToolItems.read(stackWith(data, meta)); + + assertEquals(Optional.of(new ToolItem(ResourceId.parse("minecraft:stick"), "Select bay", + List.of("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("", tagged.name()); + assertEquals(List.of(), tagged.lore()); + assertTrue(BukkitToolItems.read(stackWith(missing, mock(ItemMeta.class))).isEmpty()); + } + + @Test + public void nothingAirOrAStackWithoutMetadataIsNotAToolItem() { + ItemStack air = mock(ItemStack.class); + when(air.getType()).thenReturn(Material.AIR); + ItemStack plain = mock(ItemStack.class); + when(plain.getType()).thenReturn(Material.STICK); + when(plain.hasItemMeta()).thenReturn(false); + + assertTrue(BukkitToolItems.read(null).isEmpty()); + assertTrue(BukkitToolItems.read(air).isEmpty()); + assertTrue(BukkitToolItems.read(plain).isEmpty()); + } + + @Test + public void thePayloadLivesUnderTheIrisToolPayloadKey() { + assertEquals("iris:tool_payload", BukkitToolItems.PAYLOAD_KEY.toString()); + } +} diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/ToolWorldBookkeepingTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/ToolWorldBookkeepingTest.java new file mode 100644 index 000000000..4dbeb0456 --- /dev/null +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/ToolWorldBookkeepingTest.java @@ -0,0 +1,122 @@ +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 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("short")); + assertEquals(32, BukkitToolMenus.shortened("x".repeat(50)).length()); + } + + private static BukkitToolWorld toolWorld(OpenToolWorlds worlds, String pack, String name, String storageName) { + return new BukkitToolWorld(pack, name, storageName, new com.volmit.tooling.world.ToolWorldListener() { }, null, + new PendingBlockEntities(), worlds, new ToolPlayers(worlds)); + } + + private static World world(UUID id) { + World world = mock(World.class); + when(world.getUID()).thenReturn(id); + return world; + } +} diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/ToolWorldEventsTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/ToolWorldEventsTest.java new file mode 100644 index 000000000..f8ef00e06 --- /dev/null +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/ToolWorldEventsTest.java @@ -0,0 +1,433 @@ +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.PlayerTeleportEvent; +import org.bukkit.event.server.ServerCommandEvent; +import org.bukkit.event.block.Action; +import org.bukkit.inventory.EquipmentSlot; +import org.junit.Before; +import org.junit.Test; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** The events of a tool world reach its listener as the api says, and the events of other worlds reach nobody. */ +public class ToolWorldEventsTest { + private static final UUID TOOL_WORLD_ID = UUID.fromString("00000000-0000-0000-0000-0000000000a1"); + private static final UUID OTHER_WORLD_ID = UUID.fromString("00000000-0000-0000-0000-0000000000b2"); + private static final UUID PLAYER_ID = UUID.fromString("00000000-0000-0000-0000-0000000000c3"); + + private final List changes = new ArrayList<>(); + private final List heard = new ArrayList<>(); + private boolean allowChanges; + private boolean allowUses = true; + private boolean allowCommands = true; + private World toolBukkitWorld; + private World otherBukkitWorld; + private Player bukkitPlayer; + private ToolWorldEvents events; + + @Before + public void aToolWorldAndAnotherWorld() { + ToolWorldListener listener = new ToolWorldListener() { + @Override + public void entered(ToolPlayer player) { + heard.add("entered " + player.name()); + } + + @Override + public void left(ToolPlayer player) { + heard.add("left " + player.name()); + } + + @Override + public boolean used(ToolPlayer player, ToolUse use) { + heard.add("used " + use.action() + " " + use.hand()); + return allowUses; + } + + @Override + public boolean blockChanging(BlockChange change) { + changes.add(change); + return allowChanges; + } + + @Override + public boolean command(Optional sender, String line) { + heard.add("command " + sender.map(ToolPlayer::name).orElse("console") + " " + line); + return allowCommands; + } + }; + OpenToolWorlds worlds = new OpenToolWorlds(); + ToolPlayers players = new ToolPlayers(worlds); + BukkitToolWorld toolWorld = new BukkitToolWorld("pack", "scratch", "iris-test", listener, null, + new PendingBlockEntities(), worlds, players); + toolBukkitWorld = world(TOOL_WORLD_ID); + otherBukkitWorld = world(OTHER_WORLD_ID); + assertTrue(worlds.register(toolWorld)); + toolWorld.bind(toolBukkitWorld); + bukkitPlayer = mock(Player.class); + when(bukkitPlayer.getUniqueId()).thenReturn(PLAYER_ID); + when(bukkitPlayer.getName()).thenReturn("Tester"); + when(bukkitPlayer.getWorld()).thenReturn(toolBukkitWorld); + events = new ToolWorldEvents(worlds, players); + } + + private static World world(UUID id) { + World world = mock(World.class); + when(world.getUID()).thenReturn(id); + return world; + } + + private static Block block(World world, int x, int y, int z) { + Block block = mock(Block.class); + when(block.getWorld()).thenReturn(world); + when(block.getX()).thenReturn(x); + when(block.getY()).thenReturn(y); + when(block.getZ()).thenReturn(z); + BlockData data = mock(BlockData.class); + when(data.getAsString()).thenReturn("minecraft:stone"); + when(block.getBlockData()).thenReturn(data); + return block; + } + + private BlockChange onlyChange() { + assertEquals(1, changes.size()); + return changes.getFirst(); + } + + @Test + public void aPlacedBlockIsAPlaceChangeWithThePlacedStateAndThePlayer() { + Block placed = block(toolBukkitWorld, 3, 70, -4); + BlockPlaceEvent event = mock(BlockPlaceEvent.class); + when(event.getBlockPlaced()).thenReturn(placed); + when(event.getPlayer()).thenReturn(bukkitPlayer); + + events.onBlockPlace(event); + + BlockChange change = onlyChange(); + assertEquals(Cause.PLACE, change.cause()); + assertEquals(List.of(new BlockPosition(3, 70, -4)), change.positions()); + assertEquals("minecraft:stone", change.placed().orElseThrow().key()); + assertEquals("Tester", change.player().orElseThrow().name()); + verify(event).setCancelled(true); + } + + @Test + public void aListenerThatAllowsTheChangeLeavesTheEventAlone() { + allowChanges = true; + Block broken = block(toolBukkitWorld, 1, 2, 3); + BlockBreakEvent event = mock(BlockBreakEvent.class); + when(event.getBlock()).thenReturn(broken); + when(event.getPlayer()).thenReturn(bukkitPlayer); + + events.onBlockBreak(event); + + assertEquals(Cause.BREAK, onlyChange().cause()); + verify(event, never()).setCancelled(true); + } + + @Test + public void aBucketEmptiesIntoTheBlockNextToTheOneClicked() { + Block clicked = block(toolBukkitWorld, 0, 64, 0); + Block target = block(toolBukkitWorld, 0, 65, 0); + when(clicked.getRelative(BlockFace.UP)).thenReturn(target); + PlayerBucketEmptyEvent event = mock(PlayerBucketEmptyEvent.class); + when(event.getBlockClicked()).thenReturn(clicked); + when(event.getBlockFace()).thenReturn(BlockFace.UP); + when(event.getPlayer()).thenReturn(bukkitPlayer); + + events.onBucketEmpty(event); + + BlockChange change = onlyChange(); + assertEquals(Cause.BUCKET, change.cause()); + assertEquals(List.of(new BlockPosition(0, 65, 0)), change.positions()); + } + + @Test + public void flowingFluidNamesTheSourceAndTheTargetBlock() { + Block source = block(toolBukkitWorld, 0, 64, 0); + Block target = block(toolBukkitWorld, 1, 64, 0); + BlockFromToEvent event = mock(BlockFromToEvent.class); + when(event.getBlock()).thenReturn(source); + when(event.getToBlock()).thenReturn(target); + + events.onBlockFromTo(event); + + BlockChange change = onlyChange(); + assertEquals(Cause.FLUID, change.cause()); + assertEquals(List.of(new BlockPosition(0, 64, 0), new BlockPosition(1, 64, 0)), change.positions()); + assertTrue(change.player().isEmpty()); + verify(event).setCancelled(true); + } + + @Test + public void aPistonNamesItselfAndEveryBlockItMovesAndTheirNeighboursInTheDirectionOfTheMove() { + Block piston = block(toolBukkitWorld, 0, 64, 0); + Block moved = block(toolBukkitWorld, 1, 64, 0); + Block ahead = block(toolBukkitWorld, 2, 64, 0); + when(moved.getRelative(BlockFace.EAST)).thenReturn(ahead); + when(moved.getRelative(BlockFace.WEST)).thenReturn(piston); + + List positions = ToolWorldEvents.pistonPositions(piston, List.of(moved), BlockFace.EAST); + + assertEquals(List.of(new BlockPosition(0, 64, 0), new BlockPosition(1, 64, 0), new BlockPosition(2, 64, 0)), positions); + } + + @Test + public void aPistonExtendingInAToolWorldIsAPistonChange() { + Block piston = block(toolBukkitWorld, 0, 64, 0); + BlockPistonExtendEvent event = mock(BlockPistonExtendEvent.class); + when(event.getBlock()).thenReturn(piston); + when(event.getBlocks()).thenReturn(List.of()); + when(event.getDirection()).thenReturn(BlockFace.EAST); + + events.onPistonExtend(event); + + assertEquals(Cause.PISTON, onlyChange().cause()); + verify(event).setCancelled(true); + } + + @Test + public void anExplosionAsksForEachBlockAndKeepsOnlyTheOnesTheToolAllows() { + allowChanges = false; + Block first = block(toolBukkitWorld, 0, 64, 0); + Block second = block(toolBukkitWorld, 5, 64, 5); + List blockList = new ArrayList<>(List.of(first, second)); + Block source = block(toolBukkitWorld, 0, 70, 0); + BlockExplodeEvent event = mock(BlockExplodeEvent.class); + when(event.getBlock()).thenReturn(source); + when(event.blockList()).thenReturn(blockList); + + events.onBlockExplode(event); + + assertEquals(2, changes.size()); + assertEquals(Cause.EXPLOSION, changes.getFirst().cause()); + assertTrue("nothing was allowed to blow up", blockList.isEmpty()); + } + + @Test + public void refusedRedstoneKeepsTheOldCurrent() { + Block wire = block(toolBukkitWorld, 0, 64, 0); + BlockRedstoneEvent event = mock(BlockRedstoneEvent.class); + when(event.getBlock()).thenReturn(wire); + when(event.getOldCurrent()).thenReturn(7); + + events.onBlockRedstone(event); + + assertEquals(Cause.REDSTONE, onlyChange().cause()); + verify(event).setNewCurrent(7); + } + + @Test + public void aCrafterIsAMachine() { + Block crafter = block(toolBukkitWorld, 0, 64, 0); + CrafterCraftEvent event = mock(CrafterCraftEvent.class); + when(event.getBlock()).thenReturn(crafter); + + events.onCrafterCraft(event); + + assertEquals(Cause.MACHINE, onlyChange().cause()); + } + + @Test + public void nothingThatHappensInAnotherWorldReachesTheToolOrIsCancelled() { + Block brokenElsewhere = block(otherBukkitWorld, 1, 2, 3); + Block wireElsewhere = block(otherBukkitWorld, 1, 2, 3); + BlockBreakEvent breaking = mock(BlockBreakEvent.class); + when(breaking.getBlock()).thenReturn(brokenElsewhere); + when(breaking.getPlayer()).thenReturn(bukkitPlayer); + BlockRedstoneEvent redstone = mock(BlockRedstoneEvent.class); + when(redstone.getBlock()).thenReturn(wireElsewhere); + + events.onBlockBreak(breaking); + events.onBlockRedstone(redstone); + + assertTrue(changes.isEmpty()); + verify(breaking, never()).setCancelled(true); + verify(redstone, never()).setNewCurrent(0); + } + + @Test + public void usingTheHandIsAUseWithTheHandAndActionAndAFalseCancelsIt() { + allowUses = false; + PlayerInteractEvent event = mock(PlayerInteractEvent.class); + when(event.getPlayer()).thenReturn(bukkitPlayer); + when(event.getHand()).thenReturn(EquipmentSlot.OFF_HAND); + when(event.getAction()).thenReturn(Action.RIGHT_CLICK_AIR); + when(event.getBlockFace()).thenReturn(BlockFace.SELF); + + events.onInteract(event); + + assertEquals(List.of("used RIGHT_CLICK_AIR OFF"), heard); + verify(event).setCancelled(true); + } + + @Test + public void aCommandReachesTheToolWithoutItsSlashAndTheConsoleHasNoPlayer() { + allowCommands = false; + PlayerCommandPreprocessEvent typed = mock(PlayerCommandPreprocessEvent.class); + when(typed.getPlayer()).thenReturn(bukkitPlayer); + when(typed.getMessage()).thenReturn("/gamemode survival"); + ServerCommandEvent console = mock(ServerCommandEvent.class); + when(console.getCommand()).thenReturn("stop"); + + events.onPlayerCommand(typed); + events.onServerCommand(console); + + assertEquals(List.of("command Tester gamemode survival", "command console stop"), heard); + verify(typed).setCancelled(true); + verify(console).setCancelled(true); + } + + @Test + public void naturalSpawnsInAToolWorldAreCancelledButOtherSpawnsAreNot() { + CreatureSpawnEvent natural = mock(CreatureSpawnEvent.class); + when(natural.getSpawnReason()).thenReturn(CreatureSpawnEvent.SpawnReason.NATURAL); + when(natural.getLocation()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0)); + CreatureSpawnEvent egg = mock(CreatureSpawnEvent.class); + when(egg.getSpawnReason()).thenReturn(CreatureSpawnEvent.SpawnReason.SPAWNER_EGG); + when(egg.getLocation()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0)); + CreatureSpawnEvent elsewhere = mock(CreatureSpawnEvent.class); + when(elsewhere.getSpawnReason()).thenReturn(CreatureSpawnEvent.SpawnReason.NATURAL); + when(elsewhere.getLocation()).thenReturn(new Location(otherBukkitWorld, 0, 64, 0)); + + events.onNaturalSpawn(natural); + events.onNaturalSpawn(egg); + events.onNaturalSpawn(elsewhere); + + verify(natural).setCancelled(true); + verify(egg, never()).setCancelled(true); + verify(elsewhere, never()).setCancelled(true); + } + + @Test + public void enteringIsToldOnceHoweverManyEventsAnnounceTheArrival() { + PlayerTeleportEvent teleport = mock(PlayerTeleportEvent.class); + when(teleport.getPlayer()).thenReturn(bukkitPlayer); + when(teleport.getFrom()).thenReturn(new Location(otherBukkitWorld, 0, 64, 0)); + when(teleport.getTo()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0)); + + events.onTeleport(teleport); + events.onTeleport(teleport); + + assertEquals(List.of("entered Tester"), 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", "left Tester"), heard); + } + + @Test + public void movingInsideOneBlockIsNotAMove() { + Location from = new Location(toolBukkitWorld, 1.1, 64.0, 2.2); + + assertTrue(ToolWorldEvents.sameBlock(from, new Location(toolBukkitWorld, 1.9, 64.5, 2.9))); + assertFalse(ToolWorldEvents.sameBlock(from, new Location(toolBukkitWorld, 2.1, 64.0, 2.2))); + assertFalse(ToolWorldEvents.sameBlock(from, new Location(otherBukkitWorld, 1.1, 64.0, 2.2))); + } + + @Test + public void aCommandLineHasNoLeadingSlash() { + assertEquals("tp a b", ToolWorldEvents.lineOf("/tp a b")); + assertEquals("tp a b", ToolWorldEvents.lineOf("tp a b")); + } + + @Test + public void everyHandlerKeepsThePriorityAndCancelFlagOfTheJigsawStudioHandlerItReplaces() { + Map byMethod = new HashMap<>(); + for (Method method : ToolWorldEvents.class.getDeclaredMethods()) { + EventHandler handler = method.getAnnotation(EventHandler.class); + if (handler != null) { + byMethod.put(method.getName(), handler); + } + } + Set checked = new HashSet<>(); + + for (String decision : List.of("onBlockPlace", "onBlockMultiPlace", "onBlockBreak", "onBucketEmpty", "onBucketFill", + "onBlockForm", "onBlockFade", "onBlockSpread", "onBlockFromTo", "onBlockGrow", "onStructureGrow", "onBlockBurn", + "onPistonExtend", "onPistonRetract", "onBlockExplode", "onEntityExplode", "onEntityChangeBlock", + "onInventoryClick", "onInventoryDrag", "onInventoryMove", "onInventoryPickup", "onBlockCook", "onFurnaceBurn", + "onFurnaceSmelt", "onBrew", "onBrewingStandFuel", "onBlockDispense", "onCrafterCraft", "onPlayerCommand", + "onServerCommand", "onNaturalSpawn", "onPortal")) { + assertPriority(byMethod, checked, decision, EventPriority.HIGHEST, true); + } + assertPriority(byMethod, checked, "onBlockRedstone", EventPriority.HIGHEST, false); + assertPriority(byMethod, checked, "onInteract", EventPriority.LOWEST, true); + assertPriority(byMethod, checked, "onToggleSneak", EventPriority.NORMAL, false); + for (String arrival : List.of("onJoin", "onQuit", "onChangedWorld", "onChunkLoad")) { + assertPriority(byMethod, checked, arrival, EventPriority.NORMAL, false); + } + assertPriority(byMethod, checked, "onTeleport", EventPriority.MONITOR, true); + assertPriority(byMethod, checked, "onMove", EventPriority.MONITOR, true); + assertPriority(byMethod, checked, "onRespawn", EventPriority.MONITOR, false); + assertPriority(byMethod, checked, "onWorldUnload", EventPriority.MONITOR, true); + assertEquals("every handler of the class was checked", byMethod.keySet(), checked); + } + + private static void assertPriority( + Map byMethod, + Set checked, + String method, + EventPriority priority, + boolean ignoreCancelled + ) { + checked.add(method); + EventHandler handler = byMethod.get(method); + assertTrue(method + " is a handler", handler != null); + assertEquals(method + " priority", priority, handler.priority()); + assertEquals(method + " ignoreCancelled", ignoreCancelled, handler.ignoreCancelled()); + } +} diff --git a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedToolingSender.java b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedToolingSender.java index b7ee7ca70..07d7cb3ae 100644 --- a/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedToolingSender.java +++ b/adapters/modded-common/src/main/java/art/arcane/iris/modded/command/ModdedToolingSender.java @@ -22,6 +22,7 @@ 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 com.volmit.tooling.world.ToolPlayer; import net.minecraft.commands.CommandSourceStack; import net.minecraft.network.chat.Component; @@ -29,7 +30,8 @@ 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 modded platform has no studio and no tool + * players yet: tool worlds are not supported there, so {@link #player()} is empty. */ final class ModdedToolingSender implements ToolingSender { private final CommandSourceStack source; @@ -70,6 +72,11 @@ final class ModdedToolingSender implements ToolingSender { return Optional.ofNullable(source.getEntity()).filter(type::isInstance).map(type::cast); } + @Override + public Optional player() { + return Optional.empty(); + } + @Override public boolean isOperator() { return ModdedCommandTree.GATE.test(source); diff --git a/api/CONTRACTS.md b/api/CONTRACTS.md index 9b36ee862..9d5b186d4 100644 --- a/api/CONTRACTS.md +++ b/api/CONTRACTS.md @@ -41,13 +41,14 @@ types that carry them and lists what the Iris adapter still owes. | Module-owned pack checks | `Validator`, `ValidationContext`, `Problem`, `Severity`, `Subject`, `FeatureRegistry.registerValidator`, host `FeatureCatalog.validators()` | | Per-world module state | `PackWorld` (`state`), `InvocationContext.world()`, host `WorldStates` | | Module lifecycle across loads, hotloads and reloads | `ModuleLifecycle`, `PackContext`, `FeatureRegistry.registerLifecycle`, host `FeatureCatalog.lifecycles()`, `LifecycleRunner` | -| Host questions answered by modules | `@Service`, `Providers`, `FeatureRegistry.registerService`, host `FeatureCatalog.services(type)` / `service(type)`; services `ObjectsAt`, `StructureLocator` (`LocateResult`, `startedStructures`, `locatableStarts`, `locateStart`, `ChunkFilter`), `SaplingGrowth`, `Loot` (with `shuffleSeed`), `BlockDrops`, `EntitySpawns`, `CaveBiomes`, `ProtectedFloor`, `AmbientEffects`, `VanillaFeatures` (`DecorationStep`); values `ItemDrop`, `EntitySpec`, `ItemRegistry` (`PackResources.items()`) | +| Host questions answered by modules | `@Service`, `Providers`, `FeatureRegistry.registerService`, host `FeatureCatalog.services(type)` / `service(type)`; modules ask each other with `PackWorld.services(type)`, `ValidationContext.services(type)` and `ToolPack.services(type)` (host `ModuleWorld` forwards to the host's world); services `ObjectsAt`, `StructureLocator` (`LocateResult`, `startedStructures`, `locatableStarts`, `locateStart`, `ChunkFilter`), `SaplingGrowth`, `Loot` (with `shuffleSeed`), `BlockDrops`, `EntitySpawns`, `CaveBiomes`, `ProtectedFloor`, `AmbientEffects`, `VanillaFeatures` (`DecorationStep`); values `ItemDrop`, `EntitySpec`, `ItemRegistry` (`PackResources.items()`) | | Terrain and settings sampling | `TerrainSampler`, `BiomeSample`, `TerrainSample`, `FeatureSettings` | | Dense chunk output | `Hunk`, `GenerationContext.blocks`, reference `ArrayHunk` | | Positions, boxes and faces | `com.volmit.geometry`: `BlockPosition`, `BlockBox`, `BlockFace` | | Sparse geometry | `GeneratedObject` | | Studio views of what a module builds | `com.volmit.tooling`: `ModuleSetup.tooling()` (`ToolingRegistry.registerView`), sealed `StudioView` (`SceneView` with `SceneEntry`, `PatternView` with `PatternEntry`, `PatternArea`, `BlockPattern`), `EditableSceneView` (`SceneFile`, `NodeGraph`, `GraphNode` with `Link`, `NodeSettings`, `Edits`, `Addition`), `JsonText`, `JsonPath` (`Key`, `Index`), host `StudioViewRegistration` | -| Commands of a module | `com.volmit.tooling`: `ToolingRegistry.registerCommand`, immutable `Command` (`named`, `alias`, `describe`, `child`, `argument`, `runs`, `openToEveryone`), typed `Argument` (`word`, `text`, `integer`, `decimal`, `flag`, `choice`, `resource`, `registered`, `orElse`, `suggesting`), `CommandAction`, `CommandContext` (`get`, `sender`, `pack`, `world`, `platform`), plain-text `Sender`, `ToolPack` (`edit` with `PackEdit`, `outputFolder`, `objects` with `ObjectCodec`), host `CommandRegistration` in `FeatureCatalog.commands()` | +| Commands of a module | `com.volmit.tooling`: `ToolingRegistry.registerCommand`, immutable `Command` (`named`, `alias`, `describe`, `child`, `argument`, `runs`, `openToEveryone`), typed `Argument` (`word`, `text`, `integer`, `decimal`, `flag`, `choice`, `resource`, `registered`, `orElse`, `suggesting`), `CommandAction`, `CommandContext` (`get`, `sender`, `pack`, `world`, `platform`), plain-text `Sender` (with `player()`), `ToolPack` (`edit` with `PackEdit`, `outputFolder`, `objects` with `ObjectCodec`, `worlds`, `services`), host `CommandRegistration` in `FeatureCatalog.commands()` | +| Worlds a tool opens | `com.volmit.tooling.world`, exposed to pack modules by host `ExposedPackages`: `ToolWorlds` (`open`, `find`) with `ToolWorldSpec`, `ChunkPainter` and `ChunkCanvas`, `ToolWorld` (`players`, `owns`, `run`, `call`, `block`, `blockEntity`, `setBlock`, `repaint`, `close`), `ToolPlayer` (`teleport`, `creative`, `actionBar`, `sound`, `sidebar`, `particles`, `give`, `held`, `openMenu`), `ToolItem`, `ToolMenu` with `MenuButton` and `MenuClick`, `Particle`, `ToolWorldListener` (`entered`, `left`, `moved`, `sneakToggled`, `used` with `ToolUse`, `blockChanging` with `BlockChange.Cause`, `command`, `chunkLoaded`, `closed`), `com.volmit.geometry.ChunkPos`; every Y is the world's own; implemented by each platform adapter (Bukkit; modded adapters answer with a failed `open`) | | Buffered placement writes | `PlacementRequest`, `PlacementAccess`, host-owned `PlacementEdit` | | Typed generation and persistent storage | `mantle` package | diff --git a/api/DESIGN.md b/api/DESIGN.md index 761218c22..9872f9de5 100644 --- a/api/DESIGN.md +++ b/api/DESIGN.md @@ -326,7 +326,8 @@ the part then gets the same `Class` objects the modules registered, where a sibl defines into a `ClassCastException`. The caller opens and closes it; closing it never closes the pack's loader. `ExposedPackages` carves out every `com.volmit.tooling.` package like `com.volmit.host`: only a part sees a -platform's tooling api. `com.volmit.tooling` itself, the neutral api, stays exposed. Enabling parts lazily, mounting their +platform's tooling api. `com.volmit.tooling` itself, the neutral api, stays exposed, and so does +`com.volmit.tooling.world`, the one neutral subpackage (Tool worlds). Enabling parts lazily, mounting their commands and listeners, and disabling them belongs to the platform adapter, not to the host. ### Namespaces @@ -1236,6 +1237,11 @@ from a sapling, which drops a block has. A module answers such questions through - **Lookup.** The host asks the pack's catalog: `services(type)` for every provider, `service(type)` for the one provider of a `ONE` service. Looking up a type that is not marked fails, and so does `service` for a service that may have several providers. +- **Modules ask each other.** `PackWorld`, `ValidationContext` and `ToolPack` carry the same `services(type)`, so a + module reaches another module's service without a host extension. It returns the providers only, unscoped: the caller + passes the world it holds, and the provider's log is the host's concern when the host calls it, not the caller's. + `service(type)` for a `ONE` service is not repeated there, since `services(type).stream().findFirst()` says the same + and the api keeps one lookup. - **Threading.** The host may call a provider from any thread, several at once. A provider that searches long (`StructureLocator.locate`) is called off the server's main thread. - **Loot, drops, entities, trees.** `Loot` (`ALL`) asks in two steps, which tables a container draws from and what a @@ -1402,6 +1408,35 @@ the typed arguments; parsing, completion, permission and threads are the host's. required one, and anything after a rest-of-line argument when the tree is built. Two modules claiming one root name or alias fail the pack load, naming both. +## Tool worlds + +`com.volmit.tooling.world` is what an in-world tool, the jigsaw studio first, needs from a platform and nothing more. +It exists so the tool lives in a module and runs on every platform: a tool that imported Bukkit could not. + +- **The world is a studio world with a painter.** The host opens a studio world of the tool's pack and swaps its + generation for a `ChunkPainter`. That keeps one way to create, load, unload and delete worlds per platform, and the + platform's own height range, instead of a second kind of world. The cost is that heights are the pack dimension's. +- **Platform Y.** A tool world is not a `PackWorld`: it is the platform's world as players see it, so positions use the + world's own Y, and `minY()`/`maxY()` say its range. Converting to the height above the bottom would make every + position a tool shows a player disagree with the coordinates on their screen. +- **Painters are pure, listeners are threaded.** A painter is called from generation threads, so it reads shared state + only. A listener is called on the thread that owns the player or the position, so a module never needs a lock for + platform state, and `owns`/`run`/`call` exist for the rest. Splitting a world by region is the platform's right + (Folia); the api makes it visible instead of pretending to one thread. +- **Cancel by return value.** `blockChanging`, `used` and `command` return whether to allow. The host maps every platform + event onto `BlockChange.Cause` and cancels on `false`, so a tool freezes a bay or lets edits through without knowing which + event it was. The default for blocks is frozen: a world that forgets to answer cannot be damaged. +- **The host keeps the boring guarantees.** No natural spawning, weather, daylight, portals, vanilla structures or + features; players go back where they came from on close; the world is deleted on close and what is left is deleted at + the next start; an item's payload survives. A tool that had to do these itself would do them differently on every + platform. +- **Items, menus, sidebars are values.** `ToolItem`, `ToolMenu` and the sidebar lines are plain data the host draws with + its own widgets (VolmLib windows and scoreboards on Bukkit). No colour codes or components cross the api, for the + reason `Sender` has none. +- **A platform may not have it.** `ToolWorlds.open` then returns a failed future and `Sender.player()` is empty, so a tool + tells its user instead of failing at class loading. The package is exposed to pack modules, unlike the platform + packages below `com.volmit.tooling`. + ## Not implemented - Host wiring, which lives in Iris: JSON decoding and validation, rendering `PackSchema` into Iris's schema and diff --git a/api/README.md b/api/README.md index f8b95b127..28aeb354d 100644 --- a/api/README.md +++ b/api/README.md @@ -471,6 +471,10 @@ final class RuinsObjects implements ObjectsAt { and combines the answers), `FIRST` (the host asks in order until one answers) or `ONE` (at most one provider per pack; a second fails the pack load, naming both modules). Providers are in module id order, each module's in registration order. +- A module asks another module's service with `services(type)`, on the `PackWorld` a stage or service gets, on the + `ValidationContext` a validator gets and on the `ToolPack` a command gets. It returns the pack's providers in that + order, empty when no module provides the service, and fails with `IllegalArgumentException` for an interface that is + not a `@Service`. Pass the world you hold to the provider's methods. | Service | Providers | What the host asks | | --- | --- | --- | @@ -573,6 +577,47 @@ private void info(CommandContext context) { and writes pack objects in the host's object format (`ObjectCodec`). - A root command's name and each alias are root names. One that another module of the pack took fails the pack load, naming both modules. A host without commands, such as a build check, accepts the registration and ignores it. +- `Sender.player()` is the sender as a `ToolPlayer` (see Tool worlds), empty for the console and on a platform without + tool worlds. + +## Tool worlds + +A tool that shows or edits what it builds in a world, such as a jigsaw studio, opens a tool world through +`ToolPack.worlds()`, in `com.volmit.tooling.world`. The package is neutral, so the same tool runs on every platform that +implements it; a platform without tool worlds answers with a failed future. + +```java +ToolWorlds worlds = context.pack().worlds(); +ChunkPainter painter = (chunkX, chunkZ, canvas) -> { + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + canvas.set(x, canvas.minY() + 1, z, BlockState.parse("minecraft:smooth_stone")); + } + } +}; +worlds.open(new ToolWorldSpec("scratch", painter, new ToolWorldListener() { })) + .thenAccept(world -> context.sender().player().ifPresent(player -> + player.teleport(world, 8, world.minY() + 2, 8, 0, 0))); +``` + +- The world's chunks come only from the `ChunkPainter`, which the host calls from its generation threads, several at once, + and again for `ToolWorld.repaint`. A painter keeps no per-call state and does not keep the `ChunkCanvas`. Block entities + go through `canvas.set(..., BlockEntityData)` and are applied once the chunk is live. +- It is a studio world of the tool's pack with generation swapped for the painter, so its height range is the pack + dimension's (`minY()`, `maxY()`). Every Y in this package is the world's own Y, not the height above the bottom that + `PackWorld` counts. There is no natural mob spawning, weather, daylight cycle, portal, vanilla structure or feature. +- `ToolWorldListener` is how the tool hears about the world: players entering, leaving and moving to another block, + sneaking, using their hand (`ToolUse`), commands, loaded chunks, and every change to blocks (`BlockChange` with a + `Cause`). Each method returns `true` to allow or `false` to cancel where it decides, and `blockChanging` freezes the + world unless the tool overrides it. Calls come on the thread that owns the player or the position, and must return + quickly. +- On a platform that splits a world across threads (Folia), `ToolWorld.owns(at)` says whether the calling thread may + touch the block, `run`/`call` get a task there, and `block`, `blockEntity` and `setBlock` fail with + `IllegalStateException` elsewhere. `ToolPlayer` readers are valid on the player's own thread (`ToolPlayer.run`); its + changing methods are safe from any thread. +- `ToolPlayer` also gives items (`ToolItem`, whose payload the host keeps on the item), a chest-style menu (`ToolMenu` + of `MenuButton`s), an action bar, a sidebar, sounds and dust `Particle`s. `ToolWorld.close()` sends every player back + to where they came from and deletes the world. ## Module jars @@ -677,8 +722,8 @@ The host loads a part through its own class loader, `ToolingPartLoader`, a child classes from the same jar copy, hands the platform's api packages to the platform's loader and everything else to the pack's loader, so a part gets the same `Class` objects the modules registered. The adapter opens it (`LoadedPack.openToolingPart`) and closes it before the pack; closing it leaves the pack's loader open. The generation -loader never sees `com.volmit.tooling.`, the platform parts of the tooling api; `com.volmit.tooling` itself stays -visible. +loader never sees `com.volmit.tooling.`, the platform parts of the tooling api; `com.volmit.tooling` itself and +the neutral `com.volmit.tooling.world` stay visible. ## Settings for studio diff --git a/api/api/src/main/java/com/volmit/geometry/ChunkPos.java b/api/api/src/main/java/com/volmit/geometry/ChunkPos.java new file mode 100644 index 000000000..fe2329c08 --- /dev/null +++ b/api/api/src/main/java/com/volmit/geometry/ChunkPos.java @@ -0,0 +1,14 @@ +package com.volmit.geometry; + +import java.util.Objects; + +/** A chunk column, by chunk coordinates: block X and Z divided by 16, rounded down. */ +public record ChunkPos(int x, int z) { + private static final int CHUNK_SHIFT = 4; + + /** The chunk that contains {@code block}. */ + public static ChunkPos containing(BlockPosition block) { + Objects.requireNonNull(block, "block"); + return new ChunkPos(block.x() >> CHUNK_SHIFT, block.z() >> CHUNK_SHIFT); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/Sender.java b/api/api/src/main/java/com/volmit/tooling/Sender.java index d387eec39..b77b8d731 100644 --- a/api/api/src/main/java/com/volmit/tooling/Sender.java +++ b/api/api/src/main/java/com/volmit/tooling/Sender.java @@ -1,5 +1,6 @@ package com.volmit.tooling; +import com.volmit.tooling.world.ToolPlayer; import java.util.Optional; /** @@ -21,4 +22,7 @@ public interface Sender { /** The platform's own sender as {@code type}, such as a Bukkit {@code Player}; empty when it is not one. For platform parts. */ Optional extension(Class type); + + /** The sender as a player of the platform; empty for the console, a command block, or a platform without tool worlds. */ + Optional player(); } diff --git a/api/api/src/main/java/com/volmit/tooling/ToolPack.java b/api/api/src/main/java/com/volmit/tooling/ToolPack.java index 073e2d8c0..794f51863 100644 --- a/api/api/src/main/java/com/volmit/tooling/ToolPack.java +++ b/api/api/src/main/java/com/volmit/tooling/ToolPack.java @@ -3,8 +3,10 @@ package com.volmit.tooling; import com.volmit.ModuleLog; import com.volmit.config.PackSettings; import com.volmit.resource.PackResources; +import com.volmit.tooling.world.ToolWorlds; import java.io.IOException; import java.nio.file.Path; +import java.util.List; /** * A pack as tools see it: its current resources, its folder, and the one way to change files in it. Tools are file tools, @@ -32,4 +34,17 @@ public interface ToolPack { /** The log of the module that asked. */ ModuleLog log(); + + /** The worlds this pack's tools open on the platform. */ + ToolWorlds worlds(); + + /** + * The providers of {@code service} that the pack's modules registered, in module id order and each module's in the + * order it registered them; empty when no module provides it. This is how a module asks another module's service, + * such as a structure tool asking who knows a structure. + * + * @param service an interface marked {@link com.volmit.service.Service} + * @throws IllegalArgumentException when {@code service} is not such an interface + */ + List services(Class service); } diff --git a/api/api/src/main/java/com/volmit/tooling/world/BlockChange.java b/api/api/src/main/java/com/volmit/tooling/world/BlockChange.java new file mode 100644 index 000000000..735d9b898 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/BlockChange.java @@ -0,0 +1,58 @@ +package com.volmit.tooling.world; + +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +/** + * Something that is about to change blocks in a tool world, handed to {@link ToolWorldListener#blockChanging}. + * + * @param cause what is changing them + * @param positions the blocks that change, at least one: the block a player breaks or places, the blocks an explosion + * would destroy one at a time, all the blocks a piston would move together + * @param player the player behind it, when there is one + * @param placed the state being placed, for {@link Cause#PLACE} and {@link Cause#BUCKET}; empty when it is not known + */ +public record BlockChange(Cause cause, List positions, Optional player, Optional placed) { + /** What changes a block. */ + public enum Cause { + /** A player places a block. */ + PLACE, + /** A player breaks a block. */ + BREAK, + /** A player fills or empties a bucket. */ + BUCKET, + /** A block forms, fades or spreads by itself, such as ice, snow, grass or coral. */ + PHYSICS, + /** Water or lava flows. */ + FLUID, + /** A plant or a sapling grows. */ + GROWTH, + /** A block burns. */ + FIRE, + /** Redstone power changes; cancelling keeps the old power. */ + REDSTONE, + /** A piston pushes or pulls blocks. */ + PISTON, + /** An explosion destroys blocks. */ + EXPLOSION, + /** A mob or a falling block changes a block. */ + ENTITY, + /** A player or a hopper changes what a container block holds. */ + CONTAINER, + /** A furnace, a brewing stand, a crafter or a dispenser works. */ + MACHINE + } + + public BlockChange { + Objects.requireNonNull(cause, "cause"); + positions = List.copyOf(positions); + if (positions.isEmpty()) { + throw new IllegalArgumentException("A block change names at least one block"); + } + Objects.requireNonNull(player, "player"); + Objects.requireNonNull(placed, "placed"); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/ChunkCanvas.java b/api/api/src/main/java/com/volmit/tooling/world/ChunkCanvas.java new file mode 100644 index 000000000..7b97bb5b1 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/ChunkCanvas.java @@ -0,0 +1,30 @@ +package com.volmit.tooling.world; + +import com.volmit.block.BlockState; +import com.volmit.object.BlockEntityData; + +/** + * The chunk a {@link ChunkPainter} paints: blocks only, with the host's own block-entity handling behind it. A canvas + * starts empty (air) and is valid only while {@link ChunkPainter#paint} runs; the host never lets a painter keep it. + * + *

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

The host calls {@code paint} from its generation threads, several at once, and again for a chunk whenever it + * repaints it, so a painter holds no per-call state and reads what it paints from state that is safe to read from any + * thread. It must return quickly and must not call back into the {@link ToolWorld} that is waiting for it. A painter + * that throws leaves its chunk empty and the failure in the host's log. + */ +@FunctionalInterface +public interface ChunkPainter { + /** Paints chunk {@code chunkX}, {@code chunkZ} onto {@code canvas}. */ + void paint(int chunkX, int chunkZ, ChunkCanvas canvas); +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/MenuButton.java b/api/api/src/main/java/com/volmit/tooling/world/MenuButton.java new file mode 100644 index 000000000..2f8f97a22 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/MenuButton.java @@ -0,0 +1,21 @@ +package com.volmit.tooling.world; + +import java.util.Objects; +import java.util.function.Consumer; + +/** + * One slot of a {@link ToolMenu}. + * + * @param slot the slot counted along the rows from the top left, 0 to 8 in the first row, 9 to 17 in the second + * @param icon what the slot shows + * @param action called on the player's thread for every click on the slot; it must return quickly + */ +public record MenuButton(int slot, ToolItem icon, Consumer action) { + public MenuButton { + if (slot < 0) { + throw new IllegalArgumentException("A menu slot is not negative: " + slot); + } + Objects.requireNonNull(icon, "icon"); + Objects.requireNonNull(action, "action"); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/MenuClick.java b/api/api/src/main/java/com/volmit/tooling/world/MenuClick.java new file mode 100644 index 000000000..e106a0761 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/MenuClick.java @@ -0,0 +1,14 @@ +package com.volmit.tooling.world; + +import java.util.Objects; + +/** + * A click on a {@link MenuButton}. A left click has {@code right} false; holding shift is {@code shift}. + * + * @param player the player who clicked + */ +public record MenuClick(ToolPlayer player, boolean right, boolean shift) { + public MenuClick { + Objects.requireNonNull(player, "player"); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/Particle.java b/api/api/src/main/java/com/volmit/tooling/world/Particle.java new file mode 100644 index 000000000..0faa57655 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/Particle.java @@ -0,0 +1,21 @@ +package com.volmit.tooling.world; + +/** + * One dust particle at a position of a tool world, for {@link ToolPlayer#particles}. The position is in world + * coordinates with the world's own Y. + * + * @param rgb the colour as {@code 0xRRGGBB} + * @param size the size of the speck, above zero + */ +public record Particle(double x, double y, double z, int rgb, float size) { + private static final int MAX_RGB = 0xFFFFFF; + + public Particle { + if (rgb < 0 || rgb > MAX_RGB) { + throw new IllegalArgumentException("A particle colour is 0xRRGGBB: " + Integer.toHexString(rgb)); + } + if (!(size > 0)) { + throw new IllegalArgumentException("A particle size is above zero: " + size); + } + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/ToolItem.java b/api/api/src/main/java/com/volmit/tooling/world/ToolItem.java new file mode 100644 index 000000000..d3a53cbb4 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolItem.java @@ -0,0 +1,26 @@ +package com.volmit.tooling.world; + +import com.volmit.resource.ResourceId; +import java.util.List; +import java.util.Objects; + +/** + * An item a tool hands to a player, or a menu shows as an icon: the platform's item, a name and lore, and a payload the + * host keeps on the item. The host guarantees the payload survives on the item, as a string in the item's persistent + * data on Bukkit and as custom data on modded platforms, and hands it back through {@link ToolPlayer#held()} and + * {@link ToolUse#item()}. A tool tells its own items apart by their payload. + * + * @param item the platform's item, such as {@code minecraft:stick} + * @param name the display name as plain text; empty keeps the item's own name + * @param lore the lines under the name, plain text + * @param glowing whether the item shows the enchantment glint + * @param payload what the tool keeps on the item; empty for nothing + */ +public record ToolItem(ResourceId item, String name, List lore, boolean glowing, String payload) { + public ToolItem { + Objects.requireNonNull(item, "item"); + Objects.requireNonNull(name, "name"); + Objects.requireNonNull(payload, "payload"); + lore = List.copyOf(lore); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/ToolMenu.java b/api/api/src/main/java/com/volmit/tooling/world/ToolMenu.java new file mode 100644 index 000000000..e5d8175ed --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolMenu.java @@ -0,0 +1,41 @@ +package com.volmit.tooling.world; + +import java.util.HashSet; +import java.util.List; +import java.util.Objects; + +/** + * A chest-style menu a tool opens for a player with {@link ToolPlayer#openMenu}. Menus are the host's own inventory + * windows, so they work the same on every platform; a tool that wants another page opens a new menu from a click. + * + * @param title the title as plain text; the host shortens it to what the window can show + * @param rows the number of rows, 1 to {@value #MAX_ROWS} + * @param buttons the slots that do something; the others show a filler. No slot is used twice and every slot is inside + * the rows. + * @param onClose called on the player's thread when the menu closes for any reason: the player closed it, the world + * closed, or the tool closed or replaced it. Null stands for nothing to do. + */ +public record ToolMenu(String title, int rows, List buttons, Runnable onClose) { + public static final int MAX_ROWS = 6; + public static final int SLOTS_PER_ROW = 9; + + public ToolMenu { + Objects.requireNonNull(title, "title"); + if (rows < 1 || rows > MAX_ROWS) { + throw new IllegalArgumentException("A menu has 1 to " + MAX_ROWS + " rows: " + rows); + } + buttons = List.copyOf(buttons); + var used = new HashSet(); + for (var button : buttons) { + if (button.slot() >= rows * SLOTS_PER_ROW) { + throw new IllegalArgumentException("Slot " + button.slot() + " is outside a menu of " + rows + " rows"); + } + if (!used.add(button.slot())) { + throw new IllegalArgumentException("Slot " + button.slot() + " is used twice"); + } + } + if (onClose == null) { + onClose = () -> { }; + } + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/ToolPlayer.java b/api/api/src/main/java/com/volmit/tooling/world/ToolPlayer.java new file mode 100644 index 000000000..57db252a6 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolPlayer.java @@ -0,0 +1,86 @@ +package com.volmit.tooling.world; + +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.Sender; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +/** + * A player as a tool sees them. Positions are block positions of the world the player stands in, with that world's own Y. + * + *

Threads. The readers ({@link #world}, {@link #position}, {@link #yaw}, {@link #pitch}, {@link #sneaking}, + * {@link #held}) are valid only on the thread that owns the player, which is where every {@link ToolWorldListener} call + * about them and every {@link #run} task runs. The methods that change the player ({@link #teleport} and the ones + * below it) are safe from any thread: the host moves the change onto the owning thread. A player stays one object for + * as long as they are online, though {@link #id()} is the safer key for a map. + */ +public interface ToolPlayer { + UUID id(); + + /** The player's name as the platform shows it. */ + String name(); + + /** The player as a command sender; its messages are plain text, delivered on the thread the platform needs. */ + Sender sender(); + + /** The tool world the player stands in; empty when they stand in another world, even another pack's tool world. */ + Optional world(); + + BlockPosition position(); + + /** The direction the player faces, in degrees, as the platform counts them. */ + float yaw(); + + float pitch(); + + boolean sneaking(); + + /** Runs {@code task} on the thread that owns the player: at once when the caller is that thread, else later. */ + void run(Runnable task); + + /** + * Moves the player to the position in {@code world} and completes with whether they arrived. The host remembers + * where a player came from when they enter a tool world from outside one, and {@link ToolWorld#close()} sends them + * back there. + */ + CompletableFuture teleport(ToolWorld world, double x, double y, double z, float yaw, float pitch); + + /** + * Puts the player in creative mode when {@code on}, remembering the mode they had; turns it off by restoring that + * mode. The host also restores it when it sends the player out of a tool world. + */ + void creative(boolean on); + + /** Shows {@code text} above the hotbar. */ + void actionBar(String text); + + /** Plays {@code sound}, such as {@code minecraft:block.note_block.pling}, to this player only, where they stand. */ + void sound(ResourceId sound, float volume, float pitch); + + /** + * Shows a sidebar with {@code title} and {@code lines}, top to bottom, replacing the one this player has from a tool. + * Text is plain: the host removes formatting codes. The sidebar goes away when the player leaves the tool world. + */ + void sidebar(String title, List lines); + + /** Removes the sidebar {@link #sidebar} showed. */ + void hideSidebar(); + + /** Shows dust particles to this player only. Positions are in the world the player stands in. */ + void particles(List dust); + + /** Puts {@code item} in the player's inventory, in the first free slot. */ + void give(ToolItem item); + + /** The tool item in the player's main hand; empty when the held item is not one, which is when it carries no payload. */ + Optional held(); + + /** Opens {@code menu} for the player, closing the menu they had open. */ + void openMenu(ToolMenu menu); + + /** Closes the menu a tool opened for the player; does nothing when none is open. */ + void closeMenu(); +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/ToolUse.java b/api/api/src/main/java/com/volmit/tooling/world/ToolUse.java new file mode 100644 index 000000000..26e2352b1 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolUse.java @@ -0,0 +1,36 @@ +package com.volmit.tooling.world; + +import com.volmit.geometry.BlockFace; +import com.volmit.geometry.BlockPosition; +import java.util.Objects; +import java.util.Optional; + +/** + * A player using their hand in a tool world, handed to {@link ToolWorldListener#used}. + * + * @param hand the hand that was used + * @param action what the player did + * @param item the tool item in that hand; empty when the item is not one + * @param block the block clicked; empty for a click in the air + * @param face the face of the block clicked; empty for a click in the air + */ +public record ToolUse(Hand hand, Action action, Optional item, Optional block, Optional face) { + public enum Hand { MAIN, OFF } + + public enum Action { + LEFT_CLICK_AIR, + LEFT_CLICK_BLOCK, + RIGHT_CLICK_AIR, + RIGHT_CLICK_BLOCK, + /** Stepping on a pressure plate, trampling farmland, touching a tripwire. */ + PHYSICAL + } + + public ToolUse { + Objects.requireNonNull(hand, "hand"); + Objects.requireNonNull(action, "action"); + Objects.requireNonNull(item, "item"); + Objects.requireNonNull(block, "block"); + Objects.requireNonNull(face, "face"); + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/ToolWorld.java b/api/api/src/main/java/com/volmit/tooling/world/ToolWorld.java new file mode 100644 index 000000000..de8a6a7fd --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolWorld.java @@ -0,0 +1,84 @@ +package com.volmit.tooling.world; + +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.geometry.ChunkPos; +import com.volmit.object.BlockEntityData; +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.function.Supplier; + +/** + * One open tool world. Every position here is a block of the world itself: X and Z are world coordinates and Y is the + * world's own Y, from {@link #minY()} up to but not including {@link #maxY()}. That is not the height above the + * dimension's bottom that {@link com.volmit.world.PackWorld} uses. + * + *

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

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

The methods that return a boolean decide whether the host lets the thing happen: {@code false} cancels it. + */ +public interface ToolWorldListener { + /** A player came into the world: joined the server in it, teleported or changed world into it, or respawned in it. Once for each stay. */ + default void entered(ToolPlayer player) { + } + + /** A player left the world: quit, teleported or changed world out of it. Once for each stay. */ + default void left(ToolPlayer player) { + } + + /** A player moved to another block of the world; not called for moves inside one block. */ + default void moved(ToolPlayer player, BlockPosition to) { + } + + /** A player started or stopped sneaking. */ + default void sneakToggled(ToolPlayer player, boolean sneaking) { + } + + /** A player used their hand. Return {@code false} to cancel what the platform would do with it, such as opening a container or placing a block. */ + default boolean used(ToolPlayer player, ToolUse use) { + return true; + } + + /** Something is about to change blocks. Return {@code false} to cancel it. The default freezes the world. */ + default boolean blockChanging(BlockChange change) { + return false; + } + + /** + * A command is about to run: {@code line} is what was typed without the leading slash. {@code sender} is empty for the + * console, which is asked on behalf of every tool world that is open. Return {@code false} to cancel it. + */ + default boolean command(Optional sender, String line) { + return true; + } + + /** A chunk of the world finished loading, painted or read back. */ + default void chunkLoaded(int chunkX, int chunkZ) { + } + + /** The world was unloaded and is gone; nothing can be done with it any more. */ + default void closed() { + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/ToolWorldSpec.java b/api/api/src/main/java/com/volmit/tooling/world/ToolWorldSpec.java new file mode 100644 index 000000000..096e5268e --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolWorldSpec.java @@ -0,0 +1,29 @@ +package com.volmit.tooling.world; + +import java.util.Objects; +import java.util.regex.Pattern; + +/** + * What a tool asks {@link ToolWorlds#open} for: a world of the tool's pack whose chunks come only from {@code painter}, + * and who hears about it. + * + *

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

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

A tool world has no natural mob spawning, weather, daylight cycle, portals, vanilla structures or features. + */ + CompletableFuture open(ToolWorldSpec spec); + + /** The open tool world of this pack called {@code name}; empty when none is open or it closed. */ + Optional find(String name); +} diff --git a/api/api/src/main/java/com/volmit/validation/ValidationContext.java b/api/api/src/main/java/com/volmit/validation/ValidationContext.java index 0f6231898..d7b73ea2d 100644 --- a/api/api/src/main/java/com/volmit/validation/ValidationContext.java +++ b/api/api/src/main/java/com/volmit/validation/ValidationContext.java @@ -4,6 +4,7 @@ import com.volmit.config.PackSettings; import com.volmit.resource.PackResources; import com.volmit.resource.PlatformRegistries; +import java.util.List; import java.util.Optional; /** The pack one {@link Validator} checks, as the host would load it, and where it reports what it finds. Valid @@ -25,6 +26,16 @@ public interface ValidationContext { */ Optional platform(); + /** + * The providers of {@code service} that the pack's modules registered, in module id order and each module's in the + * order it registered them; empty when no module provides it. This is how a validator asks another module, such as + * whether a module knows a structure the pack names. + * + * @param service an interface marked {@link com.volmit.service.Service} + * @throws IllegalArgumentException when {@code service} is not such an interface + */ + List services(Class service); + /** Records {@code problem}. An {@link Severity#ERROR} stops the pack from loading once every validator has run. */ void report(Problem problem); } diff --git a/api/api/src/main/java/com/volmit/world/PackWorld.java b/api/api/src/main/java/com/volmit/world/PackWorld.java index 9d583db44..7eb92dc4d 100644 --- a/api/api/src/main/java/com/volmit/world/PackWorld.java +++ b/api/api/src/main/java/com/volmit/world/PackWorld.java @@ -6,6 +6,7 @@ import com.volmit.placement.Placements; import com.volmit.random.WorldRandom; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; +import java.util.List; import java.util.Optional; import java.util.function.Function; @@ -87,4 +88,15 @@ public interface PackWorld { default Optional extension(Class type) { return Optional.empty(); } + + /** + * The providers of {@code service} that the pack's modules registered, in module id order and each module's in the + * order it registered them; empty when no module provides it. This is how a module asks another module's service, + * such as a placement asking who builds a structure. A provider takes the world as the first argument of its + * methods, so pass this one. The list does not change while the world runs. + * + * @param service an interface marked {@link com.volmit.service.Service} + * @throws IllegalArgumentException when {@code service} is not such an interface + */ + List services(Class service); } diff --git a/api/api/src/test/java/com/volmit/tooling/world/ToolWorldRecordsTest.java b/api/api/src/test/java/com/volmit/tooling/world/ToolWorldRecordsTest.java new file mode 100644 index 000000000..083d4e2a8 --- /dev/null +++ b/api/api/src/test/java/com/volmit/tooling/world/ToolWorldRecordsTest.java @@ -0,0 +1,105 @@ +package com.volmit.tooling.world; + +import com.volmit.block.BlockState; +import com.volmit.geometry.BlockPosition; +import com.volmit.geometry.ChunkPos; +import com.volmit.resource.ResourceId; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class ToolWorldRecordsTest { + private static final ResourceId STICK = ResourceId.parse("minecraft:stick"); + private static final ToolItem ICON = new ToolItem(STICK, "Tool", List.of("line"), false, ""); + + @Test + void aChunkIsTheBlockCoordinatesDividedBySixteenRoundedDown() { + assertEquals(new ChunkPos(0, 0), ChunkPos.containing(new BlockPosition(15, 70, 0))); + assertEquals(new ChunkPos(1, -1), ChunkPos.containing(new BlockPosition(16, 0, -1))); + assertEquals(new ChunkPos(-2, -1), ChunkPos.containing(new BlockPosition(-17, 0, -16))); + } + + @Test + void aToolWorldNameIsLowerCaseWordsOfLettersDigitsUnderscoresAndDashes() { + ChunkPainter painter = (x, z, canvas) -> { }; + var listener = new ToolWorldListener() { }; + + assertEquals("jigsaw-1_a", new ToolWorldSpec("jigsaw-1_a", painter, listener).name()); + assertThrows(IllegalArgumentException.class, () -> new ToolWorldSpec("Jigsaw", painter, listener)); + assertThrows(IllegalArgumentException.class, () -> new ToolWorldSpec("two words", painter, listener)); + assertThrows(IllegalArgumentException.class, () -> new ToolWorldSpec("", painter, listener)); + assertThrows(IllegalArgumentException.class, () -> new ToolWorldSpec("-dash", painter, listener)); + assertThrows(NullPointerException.class, () -> new ToolWorldSpec("name", null, listener)); + assertThrows(NullPointerException.class, () -> new ToolWorldSpec("name", painter, null)); + } + + @Test + void aToolItemKeepsItsOwnCopyOfTheLore() { + var lore = new ArrayList<>(List.of("one")); + var item = new ToolItem(STICK, "Name", lore, true, "payload"); + lore.add("two"); + + assertEquals(List.of("one"), item.lore()); + assertThrows(UnsupportedOperationException.class, () -> item.lore().add("three")); + assertThrows(NullPointerException.class, () -> new ToolItem(STICK, "Name", List.of(), false, null)); + } + + @Test + void aMenuHasOneToSixRowsAndEveryButtonInsideThemOnItsOwnSlot() { + var button = new MenuButton(17, ICON, click -> { }); + + assertEquals(1, new ToolMenu("t", 1, List.of(new MenuButton(8, ICON, click -> { })), null).rows()); + assertEquals(2, new ToolMenu("t", 2, List.of(button), null).rows()); + assertThrows(IllegalArgumentException.class, () -> new ToolMenu("t", 0, List.of(), null)); + assertThrows(IllegalArgumentException.class, () -> new ToolMenu("t", 7, List.of(), null)); + assertThrows(IllegalArgumentException.class, () -> new ToolMenu("t", 1, List.of(button), null), "slot 17 is in the second row"); + assertThrows(IllegalArgumentException.class, + () -> new ToolMenu("t", 2, List.of(button, new MenuButton(17, ICON, click -> { })), null)); + assertThrows(IllegalArgumentException.class, () -> new MenuButton(-1, ICON, click -> { })); + } + + @Test + void aMenuWithoutAnOnCloseHasOneThatDoesNothing() { + var closed = new AtomicBoolean(); + var withHandler = new ToolMenu("t", 1, List.of(), () -> closed.set(true)); + var without = new ToolMenu("t", 1, List.of(), null); + + without.onClose().run(); + assertFalse(closed.get()); + withHandler.onClose().run(); + assertTrue(closed.get()); + } + + @Test + void aBlockChangeNamesAtLeastOneBlock() { + var position = new BlockPosition(1, 2, 3); + var change = new BlockChange(BlockChange.Cause.PLACE, List.of(position), Optional.empty(), + Optional.of(BlockState.parse("minecraft:stone"))); + + assertEquals(List.of(position), change.positions()); + assertThrows(IllegalArgumentException.class, + () -> new BlockChange(BlockChange.Cause.BREAK, List.of(), Optional.empty(), Optional.empty())); + } + + @Test + void aListenerThatImplementsNothingFreezesTheWorldAndAllowsEverythingElse() { + var listener = new ToolWorldListener() { }; + var change = new BlockChange(BlockChange.Cause.PISTON, List.of(new BlockPosition(0, 0, 0)), Optional.empty(), Optional.empty()); + + assertFalse(listener.blockChanging(change)); + assertTrue(listener.command(Optional.empty(), "gamemode creative")); + } + + @Test + void aParticleHasAnRgbColourAndAPositiveSize() { + assertEquals(0xFF00FF, new Particle(0, 0, 0, 0xFF00FF, 1.5F).rgb()); + assertThrows(IllegalArgumentException.class, () -> new Particle(0, 0, 0, 0x1000000, 1F)); + assertThrows(IllegalArgumentException.class, () -> new Particle(0, 0, 0, -1, 1F)); + assertThrows(IllegalArgumentException.class, () -> new Particle(0, 0, 0, 0, 0F)); + assertThrows(IllegalArgumentException.class, () -> new Particle(0, 0, 0, 0, Float.NaN)); + } +} diff --git a/api/host/src/main/java/com/volmit/host/ExposedPackages.java b/api/host/src/main/java/com/volmit/host/ExposedPackages.java index f26fbad4b..7cc7d39df 100644 --- a/api/host/src/main/java/com/volmit/host/ExposedPackages.java +++ b/api/host/src/main/java/com/volmit/host/ExposedPackages.java @@ -13,7 +13,8 @@ import java.util.TreeSet; * {@code com.volmitx}. The host side of IrisApi, {@code com.volmit.host}, lies inside the API's * root package but is never exposed: it loads and runs modules, and no module may reach it. The * platform packages of the tooling api, {@code com.volmit.tooling.}, are never exposed either: - * only a tooling part may use them. The neutral {@code com.volmit.tooling} stays exposed. + * only a tooling part may use them. The neutral {@code com.volmit.tooling} stays exposed, and so does the world api for + * tools, {@code com.volmit.tooling.world}, which every platform implements. */ final class ExposedPackages { /** The root package of the Iris API. Module classes must not use it. */ @@ -22,6 +23,9 @@ final class ExposedPackages { static final String HOST_PACKAGE = ExposedPackages.class.getPackageName(); /** The neutral tooling api. Each platform's own api is a subpackage of it, such as {@code com.volmit.tooling.bukkit}. */ static final String TOOLING_PACKAGE = API_PACKAGE + ".tooling"; + /** The world api for tools, which every platform implements; it is neutral, so modules see it. */ + static final String TOOL_WORLD_PACKAGE = TOOLING_PACKAGE + ".world"; + private static final PackageName TOOL_WORLD = new PackageName(TOOL_WORLD_PACKAGE); private static final PackageName API = new PackageName(API_PACKAGE); private static final PackageName HOST = new PackageName(HOST_PACKAGE); private static final PackageName TOOLING = new PackageName(TOOLING_PACKAGE); @@ -77,9 +81,12 @@ final class ExposedPackages { return !HOST.contains(dottedName) && packages.stream().anyMatch(name -> name.contains(dottedName)); } - /** Whether the package lies below {@code com.volmit.tooling}, where each platform's api has its package. */ + /** Whether the package lies below {@code com.volmit.tooling}, where each platform's api has its package. The + * platform-neutral world api for tools, {@code com.volmit.tooling.world}, lies there too but is not a platform's. + */ private static boolean isToolingPlatformPackage(String packageName) { - return TOOLING.contains(packageName); + boolean isToolWorldApi = packageName.equals(TOOL_WORLD_PACKAGE) || TOOL_WORLD.contains(packageName); + return TOOLING.contains(packageName) && !isToolWorldApi; } /** What precedes the last separator: the package of a class name, or the directory of a resource path. */ diff --git a/api/host/src/main/java/com/volmit/host/ModuleWorld.java b/api/host/src/main/java/com/volmit/host/ModuleWorld.java index 4a8b0fc56..30ee2db0f 100644 --- a/api/host/src/main/java/com/volmit/host/ModuleWorld.java +++ b/api/host/src/main/java/com/volmit/host/ModuleWorld.java @@ -6,6 +6,7 @@ import com.volmit.placement.Placements; import com.volmit.resource.PackResources; import com.volmit.world.PackWorld; import com.volmit.world.RunningWorld; +import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Function; @@ -72,6 +73,11 @@ final class ModuleWorld implements PackWorld { return world.extension(type); } + @Override + public List services(Class service) { + return world.services(service); + } + @Override public ModuleLog log() { return log; diff --git a/api/host/src/test/java/com/volmit/host/ExposedPackagesTest.java b/api/host/src/test/java/com/volmit/host/ExposedPackagesTest.java index 7113e7a65..3e14a2c3d 100644 --- a/api/host/src/test/java/com/volmit/host/ExposedPackagesTest.java +++ b/api/host/src/test/java/com/volmit/host/ExposedPackagesTest.java @@ -42,6 +42,8 @@ class ExposedPackagesTest { assertTrue(exposed.exposes("com.volmit.tooling.Command$Builder")); assertFalse(exposed.exposes("com.volmit.tooling.bukkit.BukkitToolPart")); assertFalse(exposed.exposes("com.volmit.tooling.modded.deep.ModdedToolPart")); + assertTrue(exposed.exposes("com.volmit.tooling.world.ToolWorld"), "the world api for tools is neutral"); + assertFalse(exposed.exposes("com.volmit.tooling.worldly.BukkitToolPart")); assertTrue(exposed.exposes("com.volmit.toolingx.Other")); assertTrue(exposed.exposes("com.volmit.tool.bukkit.Other")); } diff --git a/api/host/src/test/java/com/volmit/host/ExtensionsTest.java b/api/host/src/test/java/com/volmit/host/ExtensionsTest.java index e9b0a50ec..29b76af9c 100644 --- a/api/host/src/test/java/com/volmit/host/ExtensionsTest.java +++ b/api/host/src/test/java/com/volmit/host/ExtensionsTest.java @@ -88,6 +88,7 @@ class ExtensionsTest { public Optional running() { return Optional.empty(); } public Placements placements() { throw new AssertionError("Unused placements"); } public T state(Class type, Function create) { return states.state(type, () -> create.apply(this)); } + public List services(Class service) { return List.of(); } public ModuleLog log() { return ModuleLogs.discarding(); } @Override diff --git a/api/host/src/test/java/com/volmit/host/PackWorldServicesTest.java b/api/host/src/test/java/com/volmit/host/PackWorldServicesTest.java new file mode 100644 index 000000000..e67e229f6 --- /dev/null +++ b/api/host/src/test/java/com/volmit/host/PackWorldServicesTest.java @@ -0,0 +1,81 @@ +package com.volmit.host; + +import com.volmit.IrisModule; +import com.volmit.FeatureRegistry; +import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; +import com.volmit.service.Providers; +import com.volmit.service.Service; +import com.volmit.support.TestWorld; +import com.volmit.world.PackWorld; +import java.util.List; +import java.util.function.Consumer; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +/** A module asks another module's service through the world: {@code PackWorld.services}, which the validation context and + * the tool pack answer the same way. + */ +class PackWorldServicesTest { + @Service(Providers.ALL) + interface Greeting { String greet(); } + @Service(Providers.ONE) + interface Clock { long now(); } + interface NotAService { void run(); } + + private static void registerAs(ModuleRegistry registry, String moduleId, Consumer registrations) { + ModuleSetups.run(DiscoveredModule.builtIn(new IrisModule() { + public ModuleInfo info() { return ModuleInfo.of(moduleId, "Test module " + moduleId, "1"); } + public void setup(ModuleSetup setup) { registrations.accept(setup.registry()); } + }), new StageGraphBuilder(), registry); + } + + private static FeatureCatalog catalogOf(Greeting zeta, Greeting alphaFirst, Greeting alphaSecond) { + var registry = new ModuleRegistry(); + registerAs(registry, "test:zeta", services -> services.registerService(Greeting.class, zeta)); + registerAs(registry, "test:alpha", services -> { + services.registerService(Greeting.class, alphaFirst); + services.registerService(Greeting.class, alphaSecond); + }); + return registry.freeze(); + } + + @Test + void aWorldAnswersWithTheProvidersOfItsPacksModulesInModuleIdOrder() { + Greeting zeta = () -> "zeta"; + Greeting alphaFirst = () -> "alpha 1"; + Greeting alphaSecond = () -> "alpha 2"; + try (var world = new TestWorld(catalogOf(zeta, alphaFirst, alphaSecond))) { + assertEquals(List.of(alphaFirst, alphaSecond, zeta), world.services(Greeting.class)); + } + } + + @Test + void aServiceNobodyProvidesHasNoProviders() { + try (var world = new TestWorld(catalogOf(() -> "zeta", () -> "alpha 1", () -> "alpha 2"))) { + assertEquals(List.of(), world.services(Clock.class)); + } + } + + @Test + void anInterfaceThatIsNotAServiceIsRefused() { + try (var world = new TestWorld(catalogOf(() -> "zeta", () -> "alpha 1", () -> "alpha 2"))) { + assertThrows(IllegalArgumentException.class, () -> world.services(NotAService.class)); + } + } + + @Test + void theViewAModuleGetsOfAWorldAnswersLikeTheWorld() { + Greeting zeta = () -> "zeta"; + Greeting alphaFirst = () -> "alpha 1"; + Greeting alphaSecond = () -> "alpha 2"; + var catalog = catalogOf(zeta, alphaFirst, alphaSecond); + try (var world = new TestWorld(catalog)) { + PackWorld view = catalog.registrations(Greeting.class).getFirst().scope(world); + + assertNotSame(world, view); + assertEquals(world.services(Greeting.class), view.services(Greeting.class)); + assertEquals(List.of(alphaFirst, alphaSecond, zeta), view.services(Greeting.class)); + } + } +} diff --git a/api/host/src/test/java/com/volmit/support/TestWorld.java b/api/host/src/test/java/com/volmit/support/TestWorld.java index 4b33fde34..15cd5aa14 100644 --- a/api/host/src/test/java/com/volmit/support/TestWorld.java +++ b/api/host/src/test/java/com/volmit/support/TestWorld.java @@ -4,27 +4,38 @@ import com.volmit.IrisFeature; import com.volmit.ModuleLog; import com.volmit.config.PackSettings; import com.volmit.config.SettingsStack; +import com.volmit.host.FeatureCatalog; import com.volmit.host.ModuleLogs; import com.volmit.host.WorldStates; import com.volmit.placement.Placements; import com.volmit.resource.PackResources; import com.volmit.world.PackWorld; import com.volmit.world.RunningWorld; +import java.util.List; import java.util.Optional; import java.util.function.Function; -/** A world for tests: the test seed, no resources, no declared settings, and a real state store. */ +/** A world for tests: the test seed, no resources, no declared settings, a real state store, and the service providers of + * a catalog when it is given one. + */ public final class TestWorld implements PackWorld, AutoCloseable { private final WorldStates states; private final ModuleLog log; + private final FeatureCatalog catalog; public TestWorld() { - this(new WorldStates(), ModuleLogs.discarding()); + this(null); } - private TestWorld(WorldStates states, ModuleLog log) { + /** A world whose services are those {@code catalog} holds. */ + public TestWorld(FeatureCatalog catalog) { + this(new WorldStates(), ModuleLogs.discarding(), catalog); + } + + private TestWorld(WorldStates states, ModuleLog log, FeatureCatalog catalog) { this.states = states; this.log = log; + this.catalog = catalog; } @Override @@ -70,6 +81,11 @@ public final class TestWorld implements PackWorld, AutoCloseable { return states.state(type, () -> create.apply(this)); } + @Override + public List services(Class service) { + return catalog == null ? List.of() : catalog.services(service); + } + @Override public ModuleLog log() { return log; diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java b/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java index 154055c67..47f01651c 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java @@ -26,6 +26,7 @@ import com.volmit.host.WorldStates; import com.volmit.placement.Placements; import com.volmit.world.PackWorld; import com.volmit.world.RunningWorld; +import java.util.List; import java.util.Optional; import java.util.function.Function; @@ -100,6 +101,11 @@ public final class IrisPackWorld implements PackWorld { return states.state(type, () -> create.apply(this)); } + @Override + public List services(Class service) { + return PackServices.of(engine.getData()).providers(service); + } + @Override public ModuleLog log() { return log; diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisValidationContext.java b/core/src/main/java/art/arcane/iris/core/modules/IrisValidationContext.java index 455064e89..130a921fb 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisValidationContext.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisValidationContext.java @@ -90,6 +90,11 @@ public final class IrisValidationContext implements ValidationContext { return platform; } + @Override + public List services(Class service) { + return PackServices.of(data).providers(service); + } + @Override public void report(Problem problem) { problems.add(Objects.requireNonNull(problem, "problem")); diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleObjectPlacement.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleObjectPlacement.java index 1b84f34d3..64efb74fd 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleObjectPlacement.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleObjectPlacement.java @@ -77,7 +77,7 @@ public final class ModuleObjectPlacement { } long worldSeed = rng.nextLong(); try (ToolWorld toolWorld = new ToolWorld(worldSeed, data.getPackResources(), new PackDeclaredSettings(data), - world -> new IrisPlacements(data, null, () -> world))) { + PackServices.of(data), world -> new IrisPlacements(data, null, () -> world))) { return run.placeIn(toolWorld, terrain); } } diff --git a/core/src/main/java/art/arcane/iris/core/modules/PackServices.java b/core/src/main/java/art/arcane/iris/core/modules/PackServices.java new file mode 100644 index 000000000..cb0f252f5 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/PackServices.java @@ -0,0 +1,49 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.modules; + +import art.arcane.iris.core.loader.IrisData; + +import java.util.List; +import java.util.Objects; + +/** + * The service providers of one pack's modules, as {@code PackWorld.services}, {@code ValidationContext.services} and + * {@code ToolPack.services} answer them. Asking a pack whose modules fail to load throws its {@link PackModulesException}. + */ +@FunctionalInterface +public interface PackServices { + /** + * Every provider of {@code service}, in module id order; empty when no module provides it. + * + * @throws IllegalArgumentException when {@code service} is not an interface marked as a service + */ + List providers(Class service); + + /** The providers of the modules of the pack {@code data} holds, looked up whenever they are asked for. */ + static PackServices of(IrisData data) { + Objects.requireNonNull(data, "data"); + return new PackServices() { + @Override + public List providers(Class service) { + return data.getModules().pack().catalog().services(service); + } + }; + } +} diff --git a/core/src/main/java/art/arcane/iris/core/modules/ToolWorld.java b/core/src/main/java/art/arcane/iris/core/modules/ToolWorld.java index 5188401ae..a00e15775 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ToolWorld.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ToolWorld.java @@ -27,6 +27,7 @@ import com.volmit.resource.PackResources; import com.volmit.world.PackWorld; import com.volmit.world.RunningWorld; +import java.util.List; import java.util.Optional; import java.util.function.Function; @@ -42,12 +43,15 @@ final class ToolWorld implements PackWorld, AutoCloseable { private final WorldStates states; private final ModuleLog log; private final Placements placements; + private final PackServices services; - /** {@code placements} makes the placements of the new world. */ - ToolWorld(long seed, PackResources resources, PackSettings settings, Function placements) { + /** {@code placements} makes the placements of the new world; {@code services} are those of the pack's modules. */ + ToolWorld(long seed, PackResources resources, PackSettings settings, PackServices services, + Function placements) { this.seeds = new SeedManager(seed); this.resources = resources; this.settings = settings; + this.services = services; this.states = new WorldStates(); this.log = IrisApiLogger.hostLog(); this.placements = placements.apply(this); @@ -91,6 +95,11 @@ final class ToolWorld implements PackWorld, AutoCloseable { return states.state(type, () -> create.apply(this)); } + @Override + public List services(Class service) { + return services.providers(service); + } + @Override public ModuleLog log() { return log; diff --git a/core/src/main/java/art/arcane/iris/core/runtime/StudioOpenCoordinator.java b/core/src/main/java/art/arcane/iris/core/runtime/StudioOpenCoordinator.java index 129be2571..c8f6f22a6 100644 --- a/core/src/main/java/art/arcane/iris/core/runtime/StudioOpenCoordinator.java +++ b/core/src/main/java/art/arcane/iris/core/runtime/StudioOpenCoordinator.java @@ -97,6 +97,16 @@ public final class StudioOpenCoordinator { return closeWorldCoordinated(provider, worldName, world, true, project); } + /** + * Unloads a tool world and deletes its files, reserving the world mutation lock like a studio close. Players must be + * gone from it already; any that remain are sent to the spawn of another world. + */ + public CompletableFuture closeToolWorld(World world) { + Objects.requireNonNull(world, "world"); + PlatformChunkGenerator provider = IrisToolbelt.access(world); + return closeWorldCoordinated(provider, IrisWorldStorage.logicalName(world), world, true, null); + } + public CompletableFuture teleportPlayerToProject( IrisProject project, Player player @@ -772,7 +782,7 @@ public final class StudioOpenCoordinator { } String transientName = TransientWorldCleanupSupport.transientStudioBaseWorldName( child.getFileName().toString()); - if (transientName != null) { + if (transientName != null && !StudioPainterSlots.isInstalled(transientName)) { worldNames.add(transientName); } } @@ -923,6 +933,10 @@ public final class StudioOpenCoordinator { true, IrisCreator.DatapackPreparation.REUSE_LOADED_RUNTIME_IF_READY), JIGSAW( + false, + false, + IrisCreator.DatapackPreparation.REUSE_LOADED_RUNTIME_IF_READY), + TOOL( false, false, IrisCreator.DatapackPreparation.REUSE_LOADED_RUNTIME_IF_READY); @@ -952,7 +966,7 @@ public final class StudioOpenCoordinator { } public boolean prepareGeneratorState() { - return this != JIGSAW; + return this != JIGSAW && this != TOOL; } public IrisCreator.DatapackPreparation datapackPreparation() { diff --git a/core/src/main/java/art/arcane/iris/core/runtime/StudioPainterSlots.java b/core/src/main/java/art/arcane/iris/core/runtime/StudioPainterSlots.java new file mode 100644 index 000000000..3d019e9c3 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/runtime/StudioPainterSlots.java @@ -0,0 +1,96 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.runtime; + +import com.volmit.object.BlockEntityData; +import com.volmit.tooling.world.ChunkPainter; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Consumer; + +/** + * Which studio worlds are painted by a tool instead of generated from their pack, keyed by the logical name of the + * world. A tool world installs its slot before the world is created, so the first chunk the world generates is already + * the tool's, and removes it when the world closes. The world's generator reads the slot on every chunk, so a slot that + * is installed or removed takes effect at the next chunk. + */ +public final class StudioPainterSlots { + private static final Map SLOTS = new ConcurrentHashMap<>(); + + private StudioPainterSlots() { + } + + /** + * A tool's claim on one world: the painter, and where the block entities it painted go. They go to + * {@code blockEntities} because they can only be applied once the chunk is live, which is later than the paint. + */ + public record Slot(ChunkPainter painter, Consumer blockEntities) { + public Slot { + Objects.requireNonNull(painter, "painter"); + Objects.requireNonNull(blockEntities, "blockEntities"); + } + } + + /** The block entities one paint of chunk {@code chunkX}, {@code chunkZ} asked for; never empty. */ + public record PaintedChunk(int chunkX, int chunkZ, List blockEntities) { + public PaintedChunk { + blockEntities = List.copyOf(blockEntities); + } + } + + /** A block entity at chunk-local {@code x} and {@code z} and world {@code y}. */ + public record PaintedBlockEntity(int x, int y, int z, BlockEntityData data) { + public PaintedBlockEntity { + Objects.requireNonNull(data, "data"); + } + } + + /** + * Makes the world called {@code worldName} a painted one. + * + * @throws IllegalStateException when a tool painted that world already + */ + public static void install(String worldName, Slot slot) { + Objects.requireNonNull(worldName, "worldName"); + Objects.requireNonNull(slot, "slot"); + if (SLOTS.putIfAbsent(worldName, slot) != null) { + throw new IllegalStateException("The world " + worldName + " is painted by a tool already"); + } + } + + /** The slot of the world called {@code worldName}; empty for a world generated from its pack. */ + public static Optional slotOf(String worldName) { + return worldName == null ? Optional.empty() : Optional.ofNullable(SLOTS.get(worldName)); + } + + public static boolean isInstalled(String worldName) { + return slotOf(worldName).isPresent(); + } + + /** Gives the world back to its pack. Does nothing for a world nobody painted. */ + public static void remove(String worldName) { + if (worldName != null) { + SLOTS.remove(worldName); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/service/BoardSVC.java b/core/src/main/java/art/arcane/iris/core/service/BoardSVC.java index fe177d1aa..dbf390b68 100644 --- a/core/src/main/java/art/arcane/iris/core/service/BoardSVC.java +++ b/core/src/main/java/art/arcane/iris/core/service/BoardSVC.java @@ -65,6 +65,7 @@ public class BoardSVC implements IrisService, BoardProvider { private final Map boards = new ConcurrentHashMap<>(); private final Map jigsawContexts = new ConcurrentHashMap<>(); + private final Map toolSidebars = new ConcurrentHashMap<>(); private final Map yieldedWorlds = new ConcurrentHashMap<>(); private final Set hiddenPlayers = ConcurrentHashMap.newKeySet(); private volatile BoardSettings settings; @@ -118,6 +119,7 @@ public class BoardSVC implements IrisService, BoardProvider { } boards.clear(); jigsawContexts.clear(); + toolSidebars.clear(); yieldedWorlds.clear(); hiddenPlayers.clear(); settings = null; @@ -137,6 +139,7 @@ public class BoardSVC implements IrisService, BoardProvider { public void on(PlayerQuitEvent e) { remove(e.getPlayer()); jigsawContexts.remove(e.getPlayer().getUniqueId()); + toolSidebars.remove(e.getPlayer().getUniqueId()); yieldedWorlds.remove(e.getPlayer().getUniqueId()); clearPlayerPreference(e.getPlayer().getUniqueId()); } @@ -164,19 +167,58 @@ public class BoardSVC implements IrisService, BoardProvider { if (!isEligibleWorld(p)) { jigsawContexts.remove(playerId); + toolSidebars.remove(playerId); remove(p); return; } PlayerBoard playerBoard = boards.computeIfAbsent(p, PlayerBoard::new); + ToolSidebar toolSidebar = currentToolSidebar(p); JigsawStudioBoardContext jigsawContext = currentJigsawContext(p); - if (jigsawContext != null) { + if (toolSidebar != null) { + playerBoard.showTool(toolSidebar); + } else if (jigsawContext != null) { playerBoard.showJigsaw(jigsawContext); } else { playerBoard.showOrdinary(); } } + /** What a tool shows a player in a tool world: a title and plain lines, top to bottom, for as long as the player stays in {@code worldId}. */ + public record ToolSidebar(UUID worldId, String title, List lines) { + public ToolSidebar { + Objects.requireNonNull(worldId, "worldId"); + Objects.requireNonNull(title, "title"); + lines = List.copyOf(lines); + } + } + + public void applyToolSidebar(Player player, ToolSidebar sidebar) { + Objects.requireNonNull(player, "Tool sidebar player"); + Objects.requireNonNull(sidebar, "Tool sidebar"); + if (!J.isOwnedByCurrentRegion(player)) { + J.runEntity(player, () -> applyToolSidebar(player, sidebar)); + return; + } + if (!player.isOnline()) { + return; + } + toolSidebars.put(player.getUniqueId(), sidebar); + if (sidebar.worldId().equals(player.getWorld().getUID())) { + updatePlayer(player); + } + } + + public void clearToolSidebar(Player player) { + Objects.requireNonNull(player, "Tool sidebar player"); + if (!J.isOwnedByCurrentRegion(player)) { + J.runEntity(player, () -> clearToolSidebar(player)); + return; + } + toolSidebars.remove(player.getUniqueId()); + updatePlayer(player); + } + public void applyJigsawContext(Player player, JigsawStudioBoardContext context) { Objects.requireNonNull(player, "Jigsaw Studio board player"); Objects.requireNonNull(context, "Jigsaw Studio board context"); @@ -212,6 +254,7 @@ public class BoardSVC implements IrisService, BoardProvider { PlayerBoard previousBoard = boards.get(player); boolean alreadyOrdinary = previousBoard != null && previousBoard.isOrdinary(); jigsawContexts.remove(player.getUniqueId()); + toolSidebars.remove(player.getUniqueId()); updatePlayer(player); PlayerBoard playerBoard = boards.get(player); if (alreadyOrdinary && playerBoard == previousBoard) { @@ -247,6 +290,10 @@ public class BoardSVC implements IrisService, BoardProvider { @Override public String getTitle(Player player) { + PlayerBoard board = boards.get(player); + if (board != null && board.view == BoardView.TOOL) { + return board.title; + } return IrisLanguage.text(BukkitUiMessages.SCOREBOARD_TITLE); } @@ -342,6 +389,18 @@ public class BoardSVC implements IrisService, BoardProvider { } } + private ToolSidebar currentToolSidebar(Player player) { + ToolSidebar sidebar = toolSidebars.get(player.getUniqueId()); + if (sidebar == null || !sidebar.worldId().equals(player.getWorld().getUID())) { + return null; + } + return sidebar; + } + + static List toolLines(ToolSidebar sidebar) { + return sidebar.lines().stream().map(BoardSVC::untrustedBoardValue).toList(); + } + private JigsawStudioBoardContext currentJigsawContext(Player player) { JigsawStudioBoardContext context = jigsawContexts.get(player.getUniqueId()); if (context == null || !context.worldId().equals(player.getWorld().getUID())) { @@ -355,6 +414,8 @@ public class BoardSVC implements IrisService, BoardProvider { private final Board board; private volatile List lines; private volatile JigsawStudioBoardContext jigsawContext; + private volatile ToolSidebar toolSidebar; + private volatile String title; private volatile BoardView view; private volatile boolean cancelled; private volatile boolean ordinaryTickScheduled; @@ -364,6 +425,8 @@ public class BoardSVC implements IrisService, BoardProvider { this.board = new Board(player, settings); this.lines = List.of(); this.jigsawContext = null; + this.toolSidebar = null; + this.title = ""; this.view = BoardView.NONE; this.cancelled = false; this.ordinaryTickScheduled = false; @@ -380,6 +443,7 @@ public class BoardSVC implements IrisService, BoardProvider { boolean switched = view != BoardView.ORDINARY; view = BoardView.ORDINARY; jigsawContext = null; + toolSidebar = null; if (switched) { updateOrdinary(); board.update(); @@ -412,10 +476,30 @@ public class BoardSVC implements IrisService, BoardProvider { } view = BoardView.JIGSAW; jigsawContext = context; + toolSidebar = null; lines = jigsawLines(context); board.update(); } + private void showTool(ToolSidebar sidebar) { + if (cancelled) { + return; + } + if (!board.ownsScoreboardAssignment()) { + yieldBoard(player, this); + return; + } + if (view == BoardView.TOOL && sidebar.equals(toolSidebar)) { + return; + } + view = BoardView.TOOL; + toolSidebar = sidebar; + jigsawContext = null; + title = untrustedBoardValue(sidebar.title()); + lines = toolLines(sidebar); + board.update(); + } + private void scheduleOrdinaryTick() { if (ordinaryTickScheduled || cancelled || view != BoardView.ORDINARY || !boardEnabled || !player.isOnline()) { @@ -444,6 +528,11 @@ public class BoardSVC implements IrisService, BoardProvider { cancel(); return; } + ToolSidebar sidebar = currentToolSidebar(player); + if (sidebar != null) { + showTool(sidebar); + return; + } JigsawStudioBoardContext context = currentJigsawContext(player); if (context != null) { showJigsaw(context); @@ -534,6 +623,7 @@ public class BoardSVC implements IrisService, BoardProvider { private enum BoardView { NONE, ORDINARY, - JIGSAW + JIGSAW, + TOOL } } diff --git a/core/src/main/java/art/arcane/iris/core/tooling/IrisToolPack.java b/core/src/main/java/art/arcane/iris/core/tooling/IrisToolPack.java index 921cbb796..4cbb36704 100644 --- a/core/src/main/java/art/arcane/iris/core/tooling/IrisToolPack.java +++ b/core/src/main/java/art/arcane/iris/core/tooling/IrisToolPack.java @@ -20,19 +20,23 @@ package art.arcane.iris.core.tooling; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.modules.IrisValidationContext; +import art.arcane.iris.core.modules.PackServices; import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.IrisServices; import com.volmit.ModuleLog; import com.volmit.config.PackSettings; import com.volmit.resource.PackResources; import com.volmit.tooling.ObjectCodec; import com.volmit.tooling.PackEdit; import com.volmit.tooling.ToolPack; +import com.volmit.tooling.world.ToolWorlds; import java.io.File; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.List; import java.util.Objects; /** @@ -101,6 +105,17 @@ public final class IrisToolPack implements ToolPack { return log; } + @Override + public ToolWorlds worlds() { + ToolWorldsHost host = IrisServices.getOrNull(ToolWorldsHost.class); + return host == null ? UnsupportedToolWorlds.INSTANCE : host.worldsOf(data.getDataFolder().getName()); + } + + @Override + public List services(Class service) { + return PackServices.of(data).providers(service); + } + @Override public String toString() { return "pack " + data.getDataFolder().getName(); diff --git a/core/src/main/java/art/arcane/iris/core/tooling/ToolWorldsHost.java b/core/src/main/java/art/arcane/iris/core/tooling/ToolWorldsHost.java new file mode 100644 index 000000000..9f723f5dc --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/tooling/ToolWorldsHost.java @@ -0,0 +1,30 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.tooling; + +import com.volmit.tooling.world.ToolWorlds; + +/** + * The tool worlds a platform adapter offers, bound with {@code IrisServices} by an adapter that has them. A platform + * that binds none answers {@link UnsupportedToolWorlds}. + */ +public interface ToolWorldsHost { + /** The tool worlds of the pack in the folder {@code packName}, which tools reach through {@code ToolPack.worlds()}. */ + ToolWorlds worldsOf(String packName); +} diff --git a/core/src/main/java/art/arcane/iris/core/tooling/UnsupportedToolWorlds.java b/core/src/main/java/art/arcane/iris/core/tooling/UnsupportedToolWorlds.java new file mode 100644 index 000000000..cb4114aed --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/tooling/UnsupportedToolWorlds.java @@ -0,0 +1,47 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.tooling; + +import com.volmit.tooling.world.ToolWorld; +import com.volmit.tooling.world.ToolWorldSpec; +import com.volmit.tooling.world.ToolWorlds; + +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +/** The tool worlds of a platform that has none: nothing opens and nothing is found. */ +public final class UnsupportedToolWorlds implements ToolWorlds { + public static final String MESSAGE = "Tool worlds are not supported on this platform yet"; + public static final UnsupportedToolWorlds INSTANCE = new UnsupportedToolWorlds(); + + private UnsupportedToolWorlds() { + } + + @Override + public CompletableFuture open(ToolWorldSpec spec) { + Objects.requireNonNull(spec, "spec"); + return CompletableFuture.failedFuture(new UnsupportedOperationException(MESSAGE)); + } + + @Override + public Optional find(String name) { + return Optional.empty(); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/platform/BukkitChunkGenerator.java b/core/src/main/java/art/arcane/iris/engine/platform/BukkitChunkGenerator.java index 243572e22..00e4de5ba 100644 --- a/core/src/main/java/art/arcane/iris/engine/platform/BukkitChunkGenerator.java +++ b/core/src/main/java/art/arcane/iris/engine/platform/BukkitChunkGenerator.java @@ -28,11 +28,13 @@ import java.util.concurrent.Semaphore; import art.arcane.iris.spi.IrisServices; import art.arcane.iris.platform.bukkit.BukkitPlatform; import art.arcane.iris.core.IrisSettings; +import art.arcane.iris.core.IrisWorldStorage; import art.arcane.iris.core.IrisWorlds; import art.arcane.iris.core.gui.PregeneratorJob; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.core.nms.INMS; import art.arcane.iris.core.runtime.ObjectStudioActivation; +import art.arcane.iris.core.runtime.StudioPainterSlots; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioActivation; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioSession; import art.arcane.iris.core.service.StudioSVC; @@ -52,6 +54,7 @@ import art.arcane.iris.engine.object.world.IrisWorld; import art.arcane.iris.engine.object.runtime.StudioMode; import art.arcane.iris.engine.platform.studio.StudioGenerator; import art.arcane.iris.engine.platform.studio.generators.JigsawStudioGenerator; +import art.arcane.iris.engine.platform.studio.generators.PainterStudioGenerator; import art.arcane.iris.platform.bukkit.BukkitWorldBinding; import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisPlatforms; @@ -90,6 +93,7 @@ import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Objects; +import java.util.Optional; import java.util.Random; import java.util.UUID; import java.util.concurrent.TimeUnit; @@ -128,6 +132,7 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun private volatile Looper hotloader; private volatile StudioMode lastMode; private volatile UUID lastJigsawStudioRequestId; + private volatile StudioPainterSlots.Slot lastPainterSlot; private volatile boolean jigsawStudioActive; private volatile DummyBiomeProvider dummyBiomeProvider; private volatile Throwable initializationFailure; @@ -343,6 +348,7 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun private void setupEngine() { lastMode = StudioMode.NORMAL; lastJigsawStudioRequestId = null; + lastPainterSlot = null; EngineTarget engineTarget = getTarget(); String packKey = engineTarget.getDimension().getLoadKey(); JigsawStudioActivation.Request request = studio @@ -351,9 +357,10 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun JigsawStudioSession session = request == null ? null : JigsawStudioActivation.getGeneratorSession(packKey); - jigsawStudioActive = request != null + boolean jigsawRequestActive = request != null && session != null && session.sessionId().equals(request.requestId()); + jigsawStudioActive = jigsawRequestActive || paintedStudioSlot().isPresent(); IrisEngine createdEngine = new IrisEngine( engineTarget, selectInitializationMode(studio, jigsawStudioActive)); @@ -965,6 +972,9 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun lastJigsawStudioRequestId = null; lastMode = null; } + if (installPaintedStudioGenerator()) { + return; + } // Gson nulls unknown enum names, so a pack carrying a removed or typo'd studioMode must not NPE the generator. // Pack-declared studio modes are studio-only: a shipped pack that forgot to reset // studioMode must never replace production terrain with a debug generator. @@ -980,6 +990,31 @@ public class BukkitChunkGenerator extends ChunkGenerator implements PlatformChun } } + private Optional paintedStudioSlot() { + if (!studio || world.identity() == null) { + return Optional.empty(); + } + return StudioPainterSlots.slotOf(IrisWorldStorage.logicalName(WorldIdentity.parse(world.identity()))); + } + + /** Makes the generator the tool's painter while a slot is installed for this world; false when none is. */ + private boolean installPaintedStudioGenerator() { + Optional slot = paintedStudioSlot(); + if (slot.isEmpty()) { + if (lastPainterSlot != null) { + lastPainterSlot = null; + lastMode = null; + } + return false; + } + if (slot.get() != lastPainterSlot) { + setStudioGenerator(new PainterStudioGenerator(slot.get())); + lastPainterSlot = slot.get(); + lastMode = null; + } + return true; + } + @NotNull @Override public List getDefaultPopulators(@NotNull World world) { diff --git a/core/src/main/java/art/arcane/iris/engine/platform/studio/TerrainChunkCanvas.java b/core/src/main/java/art/arcane/iris/engine/platform/studio/TerrainChunkCanvas.java new file mode 100644 index 000000000..524d62b65 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/platform/studio/TerrainChunkCanvas.java @@ -0,0 +1,102 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.platform.studio; + +import art.arcane.iris.core.modules.PlatformBlockStates; +import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedBlockEntity; +import art.arcane.iris.engine.data.chunk.TerrainChunk; +import art.arcane.iris.spi.PlatformBlockState; +import art.arcane.iris.util.common.data.B; +import com.volmit.block.BlockState; +import com.volmit.object.BlockEntityData; +import com.volmit.tooling.world.ChunkCanvas; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.function.Function; + +/** + * The canvas of one paint of a tool world: block states go into a {@link TerrainChunk}, and the block entities the + * painter asks for are kept to be applied once the chunk is live. One canvas serves one paint on one thread. + */ +public final class TerrainChunkCanvas implements ChunkCanvas { + private static final int CHUNK_SIZE = 16; + + private final TerrainChunk chunk; + private final PlatformBlockStates states; + private final List blockEntities = new ArrayList<>(); + + /** {@code platformStates} turns a block state key into the platform's state; it fails for a key the platform lacks. */ + public TerrainChunkCanvas(TerrainChunk chunk, Function platformStates) { + this.chunk = Objects.requireNonNull(chunk, "chunk"); + this.states = new PlatformBlockStates(Objects.requireNonNull(platformStates, "platformStates")); + } + + /** A canvas over {@code chunk} that resolves block states through the platform Iris is bound to. */ + public static TerrainChunkCanvas onPlatform(TerrainChunk chunk) { + return new TerrainChunkCanvas(chunk, TerrainChunkCanvas::platformState); + } + + private static PlatformBlockState platformState(String key) { + PlatformBlockState state = B.getStateOrNull(key, false); + if (state == null) { + throw new IllegalArgumentException("The platform has no block state " + key); + } + return state; + } + + @Override + public int minY() { + return chunk.getMinHeight(); + } + + @Override + public int maxY() { + return chunk.getMaxHeight(); + } + + @Override + public void set(int x, int y, int z, BlockState state) { + requireInside(x, y, z); + chunk.setBlock(x, y, z, states.toPlatform(Objects.requireNonNull(state, "state"))); + blockEntities.removeIf(painted -> painted.x() == x && painted.y() == y && painted.z() == z); + } + + @Override + public void set(int x, int y, int z, BlockState state, BlockEntityData data) { + Objects.requireNonNull(data, "data"); + set(x, y, z, state); + blockEntities.add(new PaintedBlockEntity(x, y, z, data)); + } + + /** The block entities painted so far, one for each position that still holds the block it was painted with. */ + public List blockEntities() { + return List.copyOf(blockEntities); + } + + private void requireInside(int x, int y, int z) { + if (x < 0 || x >= CHUNK_SIZE || z < 0 || z >= CHUNK_SIZE) { + throw new IllegalArgumentException("Chunk-local x and z are 0 to 15: " + x + ", " + z); + } + if (y < minY() || y >= maxY()) { + throw new IllegalArgumentException("Y " + y + " is outside the world, " + minY() + " up to " + maxY()); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/platform/studio/generators/PainterStudioGenerator.java b/core/src/main/java/art/arcane/iris/engine/platform/studio/generators/PainterStudioGenerator.java new file mode 100644 index 000000000..324632e8b --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/platform/studio/generators/PainterStudioGenerator.java @@ -0,0 +1,76 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.engine.platform.studio.generators; + +import art.arcane.iris.core.runtime.StudioPainterSlots; +import art.arcane.iris.engine.data.chunk.TerrainChunk; +import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.GenerationSessionLease; +import art.arcane.iris.engine.framework.WrongEngineBroException; +import art.arcane.iris.engine.platform.studio.StudioGenerator; +import art.arcane.iris.engine.platform.studio.TerrainChunkCanvas; +import art.arcane.iris.spi.IrisLogging; +import art.arcane.iris.util.project.context.IrisContext; + +import java.util.Objects; +import java.util.function.Function; + +/** Generates the chunks of a tool world: whatever the world's {@link StudioPainterSlots.Slot} paints, and nothing else. */ +public final class PainterStudioGenerator implements StudioGenerator { + private static final String LEASE_OPERATION = "bukkit_tool_world_paint"; + + private final StudioPainterSlots.Slot slot; + private final Function canvases; + + public PainterStudioGenerator(StudioPainterSlots.Slot slot) { + this(slot, TerrainChunkCanvas::onPlatform); + } + + PainterStudioGenerator(StudioPainterSlots.Slot slot, Function canvases) { + this.slot = Objects.requireNonNull(slot, "slot"); + this.canvases = Objects.requireNonNull(canvases, "canvases"); + } + + /** The slot this generator paints for; a world whose slot changed needs a new generator. */ + public StudioPainterSlots.Slot slot() { + return slot; + } + + @Override + public void generateChunk(Engine engine, TerrainChunk terrainChunk, int chunkX, int chunkZ) + throws WrongEngineBroException { + try (GenerationSessionLease lease = engine.acquireGenerationLease(LEASE_OPERATION); + IrisContext.Scope ignored = IrisContext.open(engine, lease.sessionId(), null)) { + paint(terrainChunk, chunkX, chunkZ); + } + } + + /** Paints the chunk into {@code terrainChunk}; a painter that throws leaves the chunk as far as it got. */ + void paint(TerrainChunk terrainChunk, int chunkX, int chunkZ) { + TerrainChunkCanvas canvas = canvases.apply(terrainChunk); + try { + slot.painter().paint(chunkX, chunkZ, canvas); + } catch (RuntimeException failure) { + IrisLogging.reportError("A tool world painter failed at chunk " + chunkX + "," + chunkZ + ".", failure); + } + if (!canvas.blockEntities().isEmpty()) { + slot.blockEntities().accept(new StudioPainterSlots.PaintedChunk(chunkX, chunkZ, canvas.blockEntities())); + } + } +} diff --git a/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java b/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java index 1c2f8c2e9..f09f07f76 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java +++ b/core/src/test/java/art/arcane/iris/core/modules/CarveTestWorld.java @@ -153,6 +153,11 @@ public final class CarveTestWorld implements PackWorld { return type.cast(known); } + @Override + public List services(Class service) { + return List.of(); + } + @Override public ModuleLog log() { return ModuleLogs.discarding(); diff --git a/core/src/test/java/art/arcane/iris/core/modules/ToolWorldTest.java b/core/src/test/java/art/arcane/iris/core/modules/ToolWorldTest.java index 83b34c3dd..99864a709 100644 --- a/core/src/test/java/art/arcane/iris/core/modules/ToolWorldTest.java +++ b/core/src/test/java/art/arcane/iris/core/modules/ToolWorldTest.java @@ -25,6 +25,8 @@ import com.volmit.resource.PackResources; import com.volmit.world.PackWorld; import org.junit.Test; +import java.util.List; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; @@ -48,7 +50,8 @@ public class ToolWorldTest { public void theWorldKeepsItsStateUntilItIsClosed() { PackResources resources = mock(PackResources.class); Tracked tracked; - try (ToolWorld world = new ToolWorld(SEED, resources, mock(PackSettings.class), ignored -> mock(Placements.class))) { + try (ToolWorld world = new ToolWorld(SEED, resources, mock(PackSettings.class), mock(PackServices.class), + ignored -> mock(Placements.class))) { tracked = world.state(Tracked.class, ignored -> new Tracked()); assertSame(tracked, world.state(Tracked.class, ignored -> new Tracked())); @@ -60,4 +63,22 @@ public class ToolWorldTest { assertTrue(tracked.closed); } + + @Test + public void theWorldAnswersServicesWithTheProvidersOfThePacksModules() { + Runnable provider = () -> { }; + PackServices services = new PackServices() { + @Override + @SuppressWarnings("unchecked") + public List providers(Class service) { + return service == Runnable.class ? (List) List.of(provider) : List.of(); + } + }; + + try (ToolWorld world = new ToolWorld(SEED, mock(PackResources.class), mock(PackSettings.class), services, + ignored -> mock(Placements.class))) { + assertEquals(List.of(provider), world.services(Runnable.class)); + assertEquals(List.of(), world.services(Comparable.class)); + } + } } diff --git a/core/src/test/java/art/arcane/iris/core/runtime/StudioOpenCoordinatorOpenKindTest.java b/core/src/test/java/art/arcane/iris/core/runtime/StudioOpenCoordinatorOpenKindTest.java index 3e8b9389f..b2dbfdd10 100644 --- a/core/src/test/java/art/arcane/iris/core/runtime/StudioOpenCoordinatorOpenKindTest.java +++ b/core/src/test/java/art/arcane/iris/core/runtime/StudioOpenCoordinatorOpenKindTest.java @@ -71,6 +71,18 @@ public class StudioOpenCoordinatorOpenKindTest { kind.datapackPreparation()); } + @Test + public void toolWorldsOpenLikeAJigsawStudioWithTheirOwnDestinationTeleport() { + StudioOpenCoordinator.StudioOpenKind kind = StudioOpenCoordinator.StudioOpenKind.TOOL; + + assertFalse(kind.openWorkspace()); + assertFalse(kind.teleportThroughStandardEntry()); + assertFalse(kind.prepareGeneratorState()); + assertEquals( + IrisCreator.DatapackPreparation.REUSE_LOADED_RUNTIME_IF_READY, + kind.datapackPreparation()); + } + @Test public void studioRequestRetainsExplicitOpenKind() { IrisProject project = new IrisProject(new File("overworld")); diff --git a/core/src/test/java/art/arcane/iris/core/runtime/StudioPainterSlotsTest.java b/core/src/test/java/art/arcane/iris/core/runtime/StudioPainterSlotsTest.java new file mode 100644 index 000000000..cb4b3a9aa --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/runtime/StudioPainterSlotsTest.java @@ -0,0 +1,67 @@ +package art.arcane.iris.core.runtime; + +import com.volmit.tooling.world.ChunkPainter; +import org.junit.After; +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +public class StudioPainterSlotsTest { + private static final String WORLD = "iris-00000000-0000-0000-0000-000000000001"; + private static final String OTHER_WORLD = "iris-00000000-0000-0000-0000-000000000002"; + + private final ChunkPainter painter = (chunkX, chunkZ, canvas) -> { }; + + @After + public void removeSlots() { + StudioPainterSlots.remove(WORLD); + StudioPainterSlots.remove(OTHER_WORLD); + } + + @Test + public void aWorldIsPaintedFromTheMomentItsSlotIsInstalledUntilItIsRemoved() { + StudioPainterSlots.Slot slot = new StudioPainterSlots.Slot(painter, painted -> { }); + assertFalse(StudioPainterSlots.isInstalled(WORLD)); + + StudioPainterSlots.install(WORLD, slot); + + assertTrue(StudioPainterSlots.isInstalled(WORLD)); + assertSame(slot, StudioPainterSlots.slotOf(WORLD).orElseThrow()); + assertFalse("other worlds keep their pack", StudioPainterSlots.isInstalled(OTHER_WORLD)); + + StudioPainterSlots.remove(WORLD); + + assertFalse(StudioPainterSlots.isInstalled(WORLD)); + } + + @Test + public void aWorldHasOneSlotAtATime() { + StudioPainterSlots.install(WORLD, new StudioPainterSlots.Slot(painter, painted -> { })); + + assertThrows(IllegalStateException.class, + () -> StudioPainterSlots.install(WORLD, new StudioPainterSlots.Slot(painter, painted -> { }))); + } + + @Test + public void removingASlotThatIsNotThereOrAskingForANullNameIsHarmless() { + StudioPainterSlots.remove(WORLD); + StudioPainterSlots.remove(null); + + assertTrue(StudioPainterSlots.slotOf(null).isEmpty()); + assertTrue(StudioPainterSlots.slotOf(WORLD).isEmpty()); + } + + @Test + public void aPaintedChunkKeepsItsOwnCopyOfTheBlockEntities() { + List entities = new java.util.ArrayList<>(); + StudioPainterSlots.PaintedChunk chunk = new StudioPainterSlots.PaintedChunk(1, 2, entities); + entities.add(null); + + assertTrue(chunk.blockEntities().isEmpty()); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/service/BoardSVCToolSidebarTest.java b/core/src/test/java/art/arcane/iris/core/service/BoardSVCToolSidebarTest.java new file mode 100644 index 000000000..97fa7bbea --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/service/BoardSVCToolSidebarTest.java @@ -0,0 +1,35 @@ +package art.arcane.iris.core.service; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; + +public class BoardSVCToolSidebarTest { + private static final UUID WORLD = UUID.fromString("11111111-1111-1111-1111-111111111111"); + + @Test + public void aToolSidebarKeepsItsOwnCopyOfTheLines() { + List lines = new ArrayList<>(List.of("one")); + BoardSVC.ToolSidebar sidebar = new BoardSVC.ToolSidebar(WORLD, "Title", lines); + lines.add("two"); + + assertEquals(List.of("one"), sidebar.lines()); + assertThrows(NullPointerException.class, () -> new BoardSVC.ToolSidebar(null, "Title", List.of())); + assertThrows(NullPointerException.class, () -> new BoardSVC.ToolSidebar(WORLD, null, List.of())); + } + + @Test + public void toolLinesAreShownAsPlainTextWithoutColourOrMarkup() { + BoardSVC.ToolSidebar sidebar = new BoardSVC.ToolSidebar(WORLD, "Title", + List.of("&cStructure§a", "line\nbreak", "plain")); + + assertEquals(List.of(BoardSVC.untrustedBoardValue("&cStructure§a"), "line break", "plain"), + BoardSVC.toolLines(sidebar)); + assertEquals("&cStructure‹red›", BoardSVC.toolLines(sidebar).get(0)); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/tooling/IrisToolPackTest.java b/core/src/test/java/art/arcane/iris/core/tooling/IrisToolPackTest.java index 58fab7978..2ab65db6c 100644 --- a/core/src/test/java/art/arcane/iris/core/tooling/IrisToolPackTest.java +++ b/core/src/test/java/art/arcane/iris/core/tooling/IrisToolPackTest.java @@ -1,9 +1,16 @@ package art.arcane.iris.core.tooling; import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.PackModuleSet; import art.arcane.iris.spi.IrisPlatform; import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.IrisServices; import com.volmit.ModuleLog; +import com.volmit.host.FeatureCatalog; +import com.volmit.host.LoadedPack; +import com.volmit.service.Providers; +import com.volmit.service.Service; +import com.volmit.tooling.world.ToolWorlds; import org.junit.After; import org.junit.Before; import org.junit.Rule; @@ -14,6 +21,7 @@ import java.io.File; import java.io.IOException; import java.io.InterruptedIOException; import java.nio.file.Path; +import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -138,6 +146,45 @@ public class IrisToolPackTest { assertFalse(output.startsWith(packFolder.toPath())); } + @Test + public void aPlatformWithoutToolWorldsAnswersThatTheyAreNotSupported() { + IrisServices.remove(ToolWorldsHost.class); + + ToolWorlds worlds = pack.worlds(); + + assertSame(UnsupportedToolWorlds.INSTANCE, worlds); + assertTrue(worlds.find("any").isEmpty()); + } + + @Test + public void aPlatformWithToolWorldsAnswersWithThoseOfThePacksFolder() { + ToolWorlds overworldWorlds = mock(ToolWorlds.class); + IrisServices.register(ToolWorldsHost.class, (ToolWorldsHost) packName -> "overworld".equals(packName) ? overworldWorlds : null); + try { + assertSame(overworldWorlds, pack.worlds()); + } finally { + IrisServices.remove(ToolWorldsHost.class); + } + } + + @Test + public void servicesAreTheProvidersOfThePacksModules() { + Probe probe = new Probe() { }; + FeatureCatalog catalog = mock(FeatureCatalog.class); + LoadedPack loaded = mock(LoadedPack.class); + PackModuleSet modules = mock(PackModuleSet.class); + when(catalog.services(Probe.class)).thenReturn(List.of(probe)); + when(loaded.catalog()).thenReturn(catalog); + when(modules.pack()).thenReturn(loaded); + when(data.getModules()).thenReturn(modules); + + assertEquals(List.of(probe), pack.services(Probe.class)); + } + + @Service(Providers.ALL) + interface Probe { + } + @Test public void theObjectCodecReadsAndWritesIobFiles() { assertEquals(".iob", pack.objects().extension()); diff --git a/core/src/test/java/art/arcane/iris/core/tooling/RecordingSender.java b/core/src/test/java/art/arcane/iris/core/tooling/RecordingSender.java index 98dc3f25d..26d6dafae 100644 --- a/core/src/test/java/art/arcane/iris/core/tooling/RecordingSender.java +++ b/core/src/test/java/art/arcane/iris/core/tooling/RecordingSender.java @@ -1,5 +1,7 @@ package art.arcane.iris.core.tooling; +import com.volmit.tooling.world.ToolPlayer; + import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -39,6 +41,11 @@ final class RecordingSender implements ToolingSender { return Optional.empty(); } + @Override + public Optional player() { + return Optional.empty(); + } + @Override public boolean isOperator() { return operator; diff --git a/core/src/test/java/art/arcane/iris/core/tooling/UnsupportedToolWorldsTest.java b/core/src/test/java/art/arcane/iris/core/tooling/UnsupportedToolWorldsTest.java new file mode 100644 index 000000000..028eddb9a --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/tooling/UnsupportedToolWorldsTest.java @@ -0,0 +1,31 @@ +package art.arcane.iris.core.tooling; + +import com.volmit.tooling.world.ToolWorld; +import com.volmit.tooling.world.ToolWorldListener; +import com.volmit.tooling.world.ToolWorldSpec; +import org.junit.Test; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +public class UnsupportedToolWorldsTest { + @Test + public void openingFailsAndSaysThatToolWorldsAreNotSupportedYet() { + ToolWorldSpec spec = new ToolWorldSpec("scratch", (chunkX, chunkZ, canvas) -> { }, new ToolWorldListener() { }); + + CompletableFuture opened = UnsupportedToolWorlds.INSTANCE.open(spec); + + ExecutionException failure = assertThrows(ExecutionException.class, opened::get); + assertTrue(failure.getCause() instanceof UnsupportedOperationException); + assertEquals("Tool worlds are not supported on this platform yet", failure.getCause().getMessage()); + } + + @Test + public void nothingIsFound() { + assertTrue(UnsupportedToolWorlds.INSTANCE.find("scratch").isEmpty()); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/loot/LootValidatorTest.java b/core/src/test/java/art/arcane/iris/engine/loot/LootValidatorTest.java index d6b2e4dba..1615a07d8 100644 --- a/core/src/test/java/art/arcane/iris/engine/loot/LootValidatorTest.java +++ b/core/src/test/java/art/arcane/iris/engine/loot/LootValidatorTest.java @@ -226,6 +226,11 @@ public class LootValidatorTest { return Optional.empty(); } + @Override + public List services(Class service) { + return List.of(); + } + @Override public void report(Problem problem) { problems.add(problem); diff --git a/core/src/test/java/art/arcane/iris/engine/modifier/ApiChunk.java b/core/src/test/java/art/arcane/iris/engine/modifier/ApiChunk.java index 7c172c926..f3ed98456 100644 --- a/core/src/test/java/art/arcane/iris/engine/modifier/ApiChunk.java +++ b/core/src/test/java/art/arcane/iris/engine/modifier/ApiChunk.java @@ -690,6 +690,11 @@ public final class ApiChunk implements GenerationContext { return type.cast(known); } + @Override + public List services(Class service) { + return List.of(); + } + @Override public ModuleLog log() { return ModuleLogs.discarding(); diff --git a/core/src/test/java/art/arcane/iris/engine/platform/studio/TerrainChunkCanvasTest.java b/core/src/test/java/art/arcane/iris/engine/platform/studio/TerrainChunkCanvasTest.java new file mode 100644 index 000000000..d3fc4530d --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/platform/studio/TerrainChunkCanvasTest.java @@ -0,0 +1,125 @@ +package art.arcane.iris.engine.platform.studio; + +import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedBlockEntity; +import art.arcane.iris.engine.data.chunk.TerrainChunk; +import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.block.BlockState; +import com.volmit.object.BlockEntityData; +import com.volmit.resource.ResourceId; +import org.junit.Before; +import org.junit.Test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class TerrainChunkCanvasTest { + private static final int MIN_Y = -64; + private static final int MAX_Y = 320; + private static final BlockEntityData CHEST_DATA = + new BlockEntityData(ResourceId.parse("iris:tile"), 1, new byte[] {1, 2, 3}); + private static final BlockEntityData SIGN_DATA = + new BlockEntityData(ResourceId.parse("iris:tile"), 1, new byte[] {9}); + + private TerrainChunk chunk; + private final Map platformStates = new HashMap<>(); + private TerrainChunkCanvas canvas; + + @Before + public void anEmptyChunk() { + chunk = mock(TerrainChunk.class); + when(chunk.getMinHeight()).thenReturn(MIN_Y); + when(chunk.getMaxHeight()).thenReturn(MAX_Y); + canvas = new TerrainChunkCanvas(chunk, key -> platformStates.computeIfAbsent(key, ignored -> mock(PlatformBlockState.class))); + } + + @Test + public void theCanvasReportsTheHeightRangeOfTheChunk() { + assertEquals(MIN_Y, canvas.minY()); + assertEquals(MAX_Y, canvas.maxY()); + } + + @Test + public void aBlockGoesIntoTheChunkAsThePlatformsStateOfItsKey() { + canvas.set(3, 70, 12, BlockState.parse("minecraft:oak_log[axis=y]")); + + PlatformBlockState written = platformStates.get("minecraft:oak_log[axis=y]"); + verify(chunk).setBlock(3, 70, 12, written); + } + + @Test + public void thePlatformIsAskedOnceForAKeyAndItsAnswerIsReused() { + canvas.set(0, 0, 0, BlockState.parse("minecraft:stone")); + canvas.set(1, 0, 0, BlockState.parse("minecraft:stone")); + + PlatformBlockState stone = platformStates.get("minecraft:stone"); + verify(chunk).setBlock(0, 0, 0, stone); + verify(chunk).setBlock(1, 0, 0, stone); + assertEquals(1, platformStates.size()); + } + + @Test + public void positionsOutsideTheChunkOrTheWorldAreRefusedAndNothingIsWritten() { + BlockState stone = BlockState.parse("minecraft:stone"); + + assertThrows(IllegalArgumentException.class, () -> canvas.set(16, 0, 0, stone)); + assertThrows(IllegalArgumentException.class, () -> canvas.set(-1, 0, 0, stone)); + assertThrows(IllegalArgumentException.class, () -> canvas.set(0, 0, 16, stone)); + assertThrows(IllegalArgumentException.class, () -> canvas.set(0, MIN_Y - 1, 0, stone)); + assertThrows(IllegalArgumentException.class, () -> canvas.set(0, MAX_Y, 0, stone)); + verify(chunk, never()).setBlock(anyInt(), anyInt(), anyInt(), any()); + } + + @Test + public void theLowestAndHighestBlocksOfTheWorldAreInside() { + canvas.set(0, MIN_Y, 0, BlockState.parse("minecraft:bedrock")); + canvas.set(15, MAX_Y - 1, 15, BlockState.parse("minecraft:glass")); + + verify(chunk).setBlock(0, MIN_Y, 0, platformStates.get("minecraft:bedrock")); + verify(chunk).setBlock(15, MAX_Y - 1, 15, platformStates.get("minecraft:glass")); + } + + @Test + public void blockEntitiesAreKeptInPaintOrderWithTheirPositions() { + canvas.set(1, 64, 2, BlockState.parse("minecraft:chest"), CHEST_DATA); + canvas.set(4, 65, 5, BlockState.parse("minecraft:oak_sign"), SIGN_DATA); + + assertEquals(List.of(new PaintedBlockEntity(1, 64, 2, CHEST_DATA), new PaintedBlockEntity(4, 65, 5, SIGN_DATA)), + canvas.blockEntities()); + } + + @Test + public void paintingAnotherBlockOverABlockEntityDropsTheEntity() { + canvas.set(1, 64, 2, BlockState.parse("minecraft:chest"), CHEST_DATA); + canvas.set(1, 64, 2, BlockState.parse("minecraft:stone")); + + assertTrue(canvas.blockEntities().isEmpty()); + } + + @Test + public void paintingTwoEntitiesAtOnePositionKeepsTheLaterOne() { + canvas.set(1, 64, 2, BlockState.parse("minecraft:chest"), CHEST_DATA); + canvas.set(1, 64, 2, BlockState.parse("minecraft:chest"), SIGN_DATA); + + assertEquals(List.of(new PaintedBlockEntity(1, 64, 2, SIGN_DATA)), canvas.blockEntities()); + } + + @Test + public void aStateThePlatformLacksFailsThePaint() { + TerrainChunkCanvas strict = new TerrainChunkCanvas(chunk, key -> { + throw new IllegalArgumentException("no " + key); + }); + + assertThrows(IllegalArgumentException.class, () -> strict.set(0, 0, 0, BlockState.parse("example:nothing"))); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/platform/studio/generators/PainterStudioGeneratorTest.java b/core/src/test/java/art/arcane/iris/engine/platform/studio/generators/PainterStudioGeneratorTest.java new file mode 100644 index 000000000..120469ee3 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/platform/studio/generators/PainterStudioGeneratorTest.java @@ -0,0 +1,85 @@ +package art.arcane.iris.engine.platform.studio.generators; + +import art.arcane.iris.core.runtime.StudioPainterSlots; +import art.arcane.iris.engine.data.chunk.TerrainChunk; +import art.arcane.iris.engine.platform.studio.TerrainChunkCanvas; +import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.block.BlockState; +import com.volmit.object.BlockEntityData; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.world.ChunkPainter; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class PainterStudioGeneratorTest { + private static final BlockEntityData CHEST_DATA = + new BlockEntityData(ResourceId.parse("iris:tile"), 1, new byte[] {1}); + + private TerrainChunk chunk; + private final List sunk = new ArrayList<>(); + + @Before + public void anEmptyChunk() { + chunk = mock(TerrainChunk.class); + when(chunk.getMinHeight()).thenReturn(0); + when(chunk.getMaxHeight()).thenReturn(256); + } + + private PainterStudioGenerator generatorPainting(ChunkPainter painter) { + StudioPainterSlots.Slot slot = new StudioPainterSlots.Slot(painter, sunk::add); + return new PainterStudioGenerator(slot, terrain -> new TerrainChunkCanvas(terrain, key -> mock(PlatformBlockState.class))); + } + + @Test + public void theChunkIsWhatThePainterPaintsForThatChunkPosition() { + List asked = new ArrayList<>(); + PainterStudioGenerator generator = generatorPainting((chunkX, chunkZ, canvas) -> { + asked.add(new int[] {chunkX, chunkZ}); + canvas.set(0, 5, 0, BlockState.parse("minecraft:stone")); + }); + + generator.paint(chunk, 3, -4); + + assertEquals(1, asked.size()); + assertEquals(3, asked.get(0)[0]); + assertEquals(-4, asked.get(0)[1]); + verify(chunk).setBlock(eq(0), eq(5), eq(0), any()); + assertTrue("no block entities were painted", sunk.isEmpty()); + } + + @Test + public void blockEntitiesGoToTheSlotWithTheChunkTheyBelongTo() { + PainterStudioGenerator generator = generatorPainting((chunkX, chunkZ, canvas) -> + canvas.set(1, 64, 2, BlockState.parse("minecraft:chest"), CHEST_DATA)); + + generator.paint(chunk, 7, 8); + + assertEquals(1, sunk.size()); + assertEquals(7, sunk.get(0).chunkX()); + assertEquals(8, sunk.get(0).chunkZ()); + assertEquals(List.of(new StudioPainterSlots.PaintedBlockEntity(1, 64, 2, CHEST_DATA)), sunk.get(0).blockEntities()); + } + + @Test + public void aPainterThatThrowsLeavesTheChunkAsFarAsItGotAndDoesNotFailTheGeneration() { + PainterStudioGenerator generator = generatorPainting((chunkX, chunkZ, canvas) -> { + canvas.set(0, 5, 0, BlockState.parse("minecraft:stone")); + throw new IllegalStateException("painter bug"); + }); + + generator.paint(chunk, 0, 0); + + verify(chunk).setBlock(eq(0), eq(5), eq(0), any()); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/terrain/TestLayerBlocks.java b/core/src/test/java/art/arcane/iris/engine/terrain/TestLayerBlocks.java index d5a45d98f..0023ccca8 100644 --- a/core/src/test/java/art/arcane/iris/engine/terrain/TestLayerBlocks.java +++ b/core/src/test/java/art/arcane/iris/engine/terrain/TestLayerBlocks.java @@ -30,6 +30,7 @@ import com.volmit.world.PackWorld; import com.volmit.world.RunningWorld; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; @@ -85,6 +86,11 @@ public final class TestLayerBlocks { return type.cast(states.computeIfAbsent(type, ignored -> create.apply(this))); } + @Override + public List services(Class service) { + return List.of(); + } + @Override public ModuleLog log() { return ModuleLogs.discarding(); diff --git a/core/src/test/java/art/arcane/iris/engine/terrain/TestPackWorld.java b/core/src/test/java/art/arcane/iris/engine/terrain/TestPackWorld.java index 44a0bc106..29ac31a9b 100644 --- a/core/src/test/java/art/arcane/iris/engine/terrain/TestPackWorld.java +++ b/core/src/test/java/art/arcane/iris/engine/terrain/TestPackWorld.java @@ -114,6 +114,11 @@ public final class TestPackWorld implements PackWorld { return type.cast(states.computeIfAbsent(type, ignored -> create.apply(this))); } + @Override + public List services(Class service) { + return List.of(); + } + @Override public ModuleLog log() { return ModuleLogs.discarding();