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 index f799313df..c0eff3214 100644 --- 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 @@ -20,8 +20,8 @@ package art.arcane.iris.core.toolworld; import com.volmit.resource.ResourceId; import com.volmit.tooling.world.ToolItem; +import com.volmit.tooling.world.ToolText; import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.format.TextDecoration; import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; import org.bukkit.Material; import org.bukkit.NamespacedKey; @@ -43,7 +43,11 @@ final class BukkitToolItems { private BukkitToolItems() { } - /** A new stack of {@code item}. */ + /** + * A new stack of {@code item}. The name and lore are set as legacy strings, the way a plugin sets text on an item + * with the platform's own calls, so the stack shows what such a stack always showed. + */ + @SuppressWarnings("deprecation") static ItemStack create(ToolItem item) { Material material = Material.matchMaterial(item.item().toString()); if (material == null || !material.isItem()) { @@ -55,10 +59,10 @@ final class BukkitToolItems { throw new IllegalStateException("The item " + item.item() + " cannot carry a name or a payload"); } if (!item.name().isEmpty()) { - meta.displayName(plain(item.name())); + meta.setDisplayName(BukkitToolText.legacy(item.name())); } if (!item.lore().isEmpty()) { - meta.lore(item.lore().stream().map(BukkitToolItems::plain).toList()); + meta.setLore(item.lore().stream().map(BukkitToolText::legacy).toList()); } if (item.glowing()) { meta.setEnchantmentGlintOverride(true); @@ -86,22 +90,18 @@ final class BukkitToolItems { } return Optional.of(new ToolItem( ResourceId.parse(stack.getType().getKey().toString()), - meta.hasDisplayName() ? plainText(meta.displayName()) : "", + meta.hasDisplayName() ? plainText(meta.displayName()) : ToolText.EMPTY, meta.hasLore() ? lore(meta) : List.of(), Boolean.TRUE.equals(meta.getEnchantmentGlintOverride()), payload)); } - private static List lore(ItemMeta meta) { + 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); + private static ToolText plainText(Component component) { + return component == null ? ToolText.EMPTY : ToolText.plain(PlainTextComponentSerializer.plainText().serialize(component)); } } diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolMenus.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolMenus.java index 9144e99e4..584637947 100644 --- 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 @@ -30,6 +30,7 @@ import com.volmit.tooling.world.MenuButton; import com.volmit.tooling.world.MenuClick; import com.volmit.tooling.world.ToolItem; import com.volmit.tooling.world.ToolMenu; +import com.volmit.tooling.world.ToolText; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -129,9 +130,9 @@ final class BukkitToolMenus { } UIElement element = new UIElement("slot-" + button.slot()) .setMaterial(new MaterialBlock(material)) - .setName(icon.name()) + .setName(BukkitToolText.legacy(icon.name())) .setEnchanted(icon.glowing()); - icon.lore().forEach(element::addLore); + icon.lore().forEach(line -> element.addLore(BukkitToolText.legacy(line))); element.onLeftClick(clicked -> click(viewer, button, false, false)); element.onRightClick(clicked -> click(viewer, button, true, false)); element.onShiftLeftClick(clicked -> click(viewer, button, false, true)); @@ -151,8 +152,14 @@ final class BukkitToolMenus { 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; + /** The title in the legacy codes the window takes, cut to what it can show without leaving half a code. */ + static String shortened(ToolText title) { + String legacy = BukkitToolText.legacy(title); + if (legacy.length() <= MAX_TITLE_LENGTH) { + return legacy; + } + String cut = legacy.substring(0, MAX_TITLE_LENGTH); + return cut.endsWith("§") ? cut.substring(0, MAX_TITLE_LENGTH - 1) : cut; } private static void runGuarded(Runnable task, String what) { 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 index 1b360bd84..d8768f284 100644 --- 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 @@ -23,6 +23,8 @@ import art.arcane.iris.core.service.BukkitToolingSender; import art.arcane.iris.platform.bukkit.BukkitPlatform; import art.arcane.iris.spi.IrisServices; import art.arcane.iris.util.common.scheduling.J; +import art.arcane.volmlib.util.plugin.ComponentMessenger; +import art.arcane.volmlib.util.plugin.ComponentText; import com.volmit.geometry.BlockPosition; import com.volmit.resource.ResourceId; import com.volmit.tooling.Sender; @@ -30,6 +32,7 @@ import com.volmit.tooling.world.Particle; import com.volmit.tooling.world.ToolItem; import com.volmit.tooling.world.ToolMenu; import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolText; import com.volmit.tooling.world.ToolWorld; import org.bukkit.Bukkit; import org.bukkit.Color; @@ -140,8 +143,13 @@ final class BukkitToolPlayer implements ToolPlayer { } @Override - public void actionBar(String text) { - J.runEntity(player, () -> player.sendActionBar(text)); + public void message(ToolText text) { + J.runEntity(player, () -> ComponentMessenger.send(player, ComponentText.component(BukkitToolText.component(text)))); + } + + @Override + public void actionBar(ToolText text) { + J.runEntity(player, () -> player.sendActionBar(BukkitToolText.component(text))); } @Override @@ -150,7 +158,7 @@ final class BukkitToolPlayer implements ToolPlayer { } @Override - public void sidebar(String title, List lines) { + public void sidebar(ToolText title, List lines) { BoardSVC board = IrisServices.getOrNull(BoardSVC.class); if (board == null) { return; @@ -174,11 +182,13 @@ final class BukkitToolPlayer implements ToolPlayer { } @Override - public void give(ToolItem item) { + public boolean give(ToolItem item) { ItemStack stack = BukkitToolItems.create(item); - J.runEntity(player, () -> player.getInventory().addItem(stack) - .values() - .forEach(leftover -> player.getWorld().dropItem(player.getLocation(), leftover))); + if (J.isOwnedByCurrentRegion(player)) { + return player.getInventory().addItem(stack).isEmpty(); + } + J.runEntity(player, () -> player.getInventory().addItem(stack)); + return true; } @Override diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolText.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolText.java new file mode 100644 index 000000000..c7a3dc4df --- /dev/null +++ b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolText.java @@ -0,0 +1,94 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.toolworld; + +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolText; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.TextDecoration; + +import java.util.EnumMap; +import java.util.Map; + +/** {@link ToolText} as the text Bukkit shows: an Adventure component, or the legacy string the platform's older calls take. */ +final class BukkitToolText { + private static final char SECTION = '§'; + private static final Map COLORS = new EnumMap<>(Map.ofEntries( + Map.entry(TextColor.BLACK, NamedTextColor.BLACK), + Map.entry(TextColor.DARK_BLUE, NamedTextColor.DARK_BLUE), + Map.entry(TextColor.DARK_GREEN, NamedTextColor.DARK_GREEN), + Map.entry(TextColor.DARK_AQUA, NamedTextColor.DARK_AQUA), + Map.entry(TextColor.DARK_RED, NamedTextColor.DARK_RED), + Map.entry(TextColor.DARK_PURPLE, NamedTextColor.DARK_PURPLE), + Map.entry(TextColor.GOLD, NamedTextColor.GOLD), + Map.entry(TextColor.GRAY, NamedTextColor.GRAY), + Map.entry(TextColor.DARK_GRAY, NamedTextColor.DARK_GRAY), + Map.entry(TextColor.BLUE, NamedTextColor.BLUE), + Map.entry(TextColor.GREEN, NamedTextColor.GREEN), + Map.entry(TextColor.AQUA, NamedTextColor.AQUA), + Map.entry(TextColor.RED, NamedTextColor.RED), + Map.entry(TextColor.LIGHT_PURPLE, NamedTextColor.LIGHT_PURPLE), + Map.entry(TextColor.YELLOW, NamedTextColor.YELLOW), + Map.entry(TextColor.WHITE, NamedTextColor.WHITE))); + + private BukkitToolText() { + } + + static Component component(ToolText text) { + TextComponent.Builder whole = Component.text(); + for (ToolText.Span span : text.spans()) { + Component piece = Component.text(span.text()); + if (span.color() != null) { + piece = piece.color(COLORS.get(span.color())); + } + piece = piece + .decoration(TextDecoration.BOLD, span.bold() ? TextDecoration.State.TRUE : TextDecoration.State.NOT_SET) + .decoration(TextDecoration.ITALIC, span.italic() ? TextDecoration.State.TRUE : TextDecoration.State.NOT_SET) + .decoration(TextDecoration.STRIKETHROUGH, + span.strikethrough() ? TextDecoration.State.TRUE : TextDecoration.State.NOT_SET); + whole.append(piece); + } + return whole.build(); + } + + /** The legacy string of {@code text}: formatting signs for the colour and style of each span, a reset between uncoloured ones. */ + static String legacy(ToolText text) { + StringBuilder legacy = new StringBuilder(); + for (ToolText.Span span : text.spans()) { + if (span.color() != null) { + legacy.append(SECTION).append(span.color().code()); + } else if (!legacy.isEmpty()) { + legacy.append(SECTION).append('r'); + } + if (span.bold()) { + legacy.append(SECTION).append('l'); + } + if (span.italic()) { + legacy.append(SECTION).append('o'); + } + if (span.strikethrough()) { + legacy.append(SECTION).append('m'); + } + legacy.append(span.text()); + } + return legacy.toString(); + } +} diff --git a/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorld.java b/adapters/bukkit/plugin/src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorld.java index 9823e1cb9..59e2f7246 100644 --- 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 @@ -19,6 +19,7 @@ package art.arcane.iris.core.toolworld; import art.arcane.iris.core.nms.INMS; +import art.arcane.iris.core.project.IrisProject; import art.arcane.iris.core.runtime.InPlaceChunkRegenerator; import art.arcane.iris.core.runtime.StudioOpenCoordinator; import art.arcane.iris.core.runtime.StudioPainterSlots; @@ -42,6 +43,7 @@ import org.bukkit.Chunk; import org.bukkit.World; import org.bukkit.block.Block; +import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -75,6 +77,7 @@ final class BukkitToolWorld implements ToolWorld, StudioSlotOccupant { private final AtomicBoolean closing = new AtomicBoolean(); private final AtomicBoolean gone = new AtomicBoolean(); private final CompletableFuture closed = new CompletableFuture<>(); + private final IrisProject project; private volatile World world; BukkitToolWorld( @@ -95,6 +98,18 @@ final class BukkitToolWorld implements ToolWorld, StudioSlotOccupant { this.pending = pending; this.registry = registry; this.players = players; + this.project = new IrisProject(new File(workspaceFolder(), packName)); + } + + /** The studio project this world is, as the studio service shows the open studio to its commands. */ + @Override + public IrisProject project() { + return project; + } + + private static File workspaceFolder() { + StudioSVC studios = IrisServices.getOrNull(StudioSVC.class); + return studios == null ? new File(".") : studios.getWorkspaceFolder(); } String packName() { @@ -199,6 +214,11 @@ final class BukkitToolWorld implements ToolWorld, StudioSlotOccupant { data.ifPresent(entity -> BukkitToolBlocks.applyBlockEntity(block, entity)); } + @Override + public boolean loaded(ChunkPos chunk) { + return bukkit().isChunkLoaded(chunk.x(), chunk.z()); + } + @Override public CompletableFuture repaint(Collection chunks) { if (isClosed()) { @@ -214,7 +234,7 @@ final class BukkitToolWorld implements ToolWorld, StudioSlotOccupant { return closed; } sendPlayersBack() - .thenCompose(ignored -> StudioOpenCoordinator.get().closeToolWorld(bukkit())) + .thenCompose(ignored -> StudioOpenCoordinator.get().closeToolWorld(bukkit(), project)) .whenComplete((result, failure) -> finishClose(result, failure)); return closed; } 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 index 4c20fd44f..90a93dff3 100644 --- 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 @@ -85,7 +85,7 @@ final class BukkitToolWorlds implements ToolWorlds { private StudioOpenCoordinator.StudioOpenRequest openRequest(String storageName, BukkitToolWorld toolWorld) { return new StudioOpenCoordinator.StudioOpenRequest( packName, - null, + toolWorld.project(), null, TOOL_WORLD_SEED, storageName, 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 index 4b9024dd0..1de093455 100644 --- 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 @@ -49,6 +49,7 @@ import org.bukkit.event.block.BlockPistonRetractEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.BlockRedstoneEvent; import org.bukkit.event.block.BlockSpreadEvent; +import org.bukkit.event.block.BrewingStartEvent; import org.bukkit.event.block.CrafterCraftEvent; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityChangeBlockEvent; @@ -56,6 +57,8 @@ import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.inventory.BrewEvent; import org.bukkit.event.inventory.BrewingStandFuelEvent; import org.bukkit.event.inventory.FurnaceBurnEvent; +import org.bukkit.event.inventory.FurnaceStartSmeltEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.FurnaceSmeltEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryDragEvent; @@ -184,14 +187,12 @@ public final class ToolWorldEvents implements Listener { @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()); + allowPistonOrCancel(event, event.getBlock(), event.getBlocks(), event.getDirection()); } @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()); + allowPistonOrCancel(event, event.getBlock(), event.getBlocks(), event.getDirection()); } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @@ -270,6 +271,33 @@ public final class ToolWorldEvents implements Listener { allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty()); } + // What changed inside containers and machines, told after the fact. + + @EventHandler(priority = EventPriority.MONITOR) + public void onInventoryClose(InventoryCloseEvent event) { + Player player = event.getPlayer() instanceof Player closer ? closer : null; + tellContainerChanged(containerBlocks(event.getView().getTopInventory()), Optional.ofNullable(player)); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onFurnaceStartSmelt(FurnaceStartSmeltEvent event) { + tellContainerChanged(List.of(event.getBlock()), Optional.empty()); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onBrewingStart(BrewingStartEvent event) { + tellContainerChanged(List.of(event.getBlock()), Optional.empty()); + } + + private void tellContainerChanged(List blocks, Optional player) { + for (Block block : blocks) { + Optional toolPlayer = player.map(players::of).map(ToolPlayer.class::cast); + BlockPosition at = positionOf(block); + worlds.forWorld(block.getWorld()).ifPresent(world -> + world.tell(listener -> listener.containerChanged(toolPlayer, at))); + } + } + // What players do. @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @@ -327,7 +355,8 @@ public final class ToolWorldEvents implements Listener { @EventHandler(priority = EventPriority.NORMAL) public void onJoin(PlayerJoinEvent event) { - worlds.forWorld(event.getPlayer().getWorld()).ifPresent(world -> enter(world, event.getPlayer())); + Player player = event.getPlayer(); + worlds.forWorld(player.getWorld()).ifPresent(world -> enter(world, player, player.getLocation())); } @EventHandler(priority = EventPriority.NORMAL) @@ -341,17 +370,20 @@ public final class ToolWorldEvents implements Listener { 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)); + worlds.forWorld(player.getWorld()).ifPresent(world -> enter(world, player, player.getLocation())); } + /** + * Every teleport of any player by anyone, portals included, is told to the tool worlds it touches at the time it + * happens, with the position it goes to: the world it leaves hears {@code left}, the one it enters {@code entered}, + * and the one it arrives in {@code teleported}. + */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onTeleport(PlayerTeleportEvent event) { Player player = event.getPlayer(); + Location destination = event.getTo(); Optional from = worlds.forWorld(event.getFrom().getWorld()); - Optional to = event.getTo() == null ? Optional.empty() : worlds.forWorld(event.getTo().getWorld()); - if (from.isPresent() && from.equals(to)) { - return; - } + Optional to = destination == null ? Optional.empty() : worlds.forWorld(destination.getWorld()); if (from.isEmpty() && to.isPresent()) { players.rememberOrigin(player, event.getFrom()); } @@ -359,13 +391,16 @@ public final class ToolWorldEvents implements Listener { players.restoreGameMode(player); players.takeOrigin(player); } - from.ifPresent(world -> leave(world, player)); - to.ifPresent(world -> enter(world, player)); + if (!from.equals(to)) { + from.ifPresent(world -> leave(world, player)); + } + to.ifPresent(world -> enter(world, player, destination)); } @EventHandler(priority = EventPriority.MONITOR) public void onRespawn(PlayerRespawnEvent event) { - worlds.forWorld(event.getRespawnLocation().getWorld()).ifPresent(world -> enter(world, event.getPlayer())); + Location respawn = event.getRespawnLocation(); + worlds.forWorld(respawn.getWorld()).ifPresent(world -> enter(world, event.getPlayer(), respawn)); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @@ -405,10 +440,13 @@ public final class ToolWorldEvents implements Listener { } } - private void enter(BukkitToolWorld world, Player player) { + /** The player is in the world at {@code at}: told as having entered on the first of their arrivals, and as having arrived on each. */ + private void enter(BukkitToolWorld world, Player player, Location at) { if (world.presence().enter(player.getUniqueId())) { world.tell(listener -> listener.entered(players.of(player))); } + BlockPosition arrival = BukkitToolBlocks.positionOf(at); + world.tell(listener -> listener.teleported(players.of(player), arrival)); } private void leave(BukkitToolWorld world, Player player) { @@ -434,6 +472,19 @@ public final class ToolWorldEvents implements Listener { } } + private void allowPistonOrCancel(Cancellable event, Block piston, List moved, BlockFace direction) { + boolean allowed = isAllowed( + Cause.PISTON, + piston.getWorld(), + pistonChecked(moved, direction), + pistonChanged(piston, moved, direction), + Optional.empty(), + Optional.empty()); + if (!allowed) { + event.setCancelled(true); + } + } + private void allowContainerOrCancel(Cancellable event, Inventory inventory, Player player) { List blocks = containerBlocks(inventory); if (blocks.isEmpty()) { @@ -450,12 +501,24 @@ public final class ToolWorldEvents implements Listener { List positions, Optional player, Optional placed + ) { + return isAllowed(cause, world, positions, positions, player, placed); + } + + private boolean isAllowed( + Cause cause, + World world, + List positions, + List changed, + Optional player, + Optional placed ) { Optional toolWorld = worlds.forWorld(world); if (toolWorld.isEmpty()) { return true; } - BlockChange change = new BlockChange(cause, positions, player.map(players::of).map(ToolPlayer.class::cast), placed); + BlockChange change = new BlockChange( + cause, positions, changed, player.map(players::of).map(ToolPlayer.class::cast), placed); return toolWorld.get().ask(listener -> listener.blockChanging(change), false); } @@ -466,10 +529,9 @@ public final class ToolWorldEvents implements Listener { 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) { + /** Each block a piston moves and the block each of them enters and leaves, which a protected area is checked against; not the piston. */ + static List pistonChecked(List moved, BlockFace direction) { List positions = new ArrayList<>(); - positions.add(positionOf(piston)); for (Block block : moved) { positions.add(positionOf(block)); positions.add(positionOf(block.getRelative(direction))); @@ -478,6 +540,18 @@ public final class ToolWorldEvents implements Listener { return positions.stream().distinct().toList(); } + /** The piston and the block ahead of it, then each block it moves and the block each enters: what a piston changes. */ + static List pistonChanged(Block piston, List moved, BlockFace direction) { + List positions = new ArrayList<>(); + positions.add(positionOf(piston)); + positions.add(positionOf(piston.getRelative(direction))); + for (Block block : moved) { + positions.add(positionOf(block)); + positions.add(positionOf(block.getRelative(direction))); + } + return positions.stream().distinct().toList(); + } + /** The blocks a container inventory is made of: none for a player's or a menu, two for a double chest. */ static List containerBlocks(Inventory inventory) { if (inventory == null) { 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 index afaf4d6a8..6c65cebc3 100644 --- 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 @@ -2,6 +2,7 @@ package art.arcane.iris.core.toolworld; import com.volmit.resource.ResourceId; import com.volmit.tooling.world.ToolItem; +import com.volmit.tooling.world.ToolText; import net.kyori.adventure.text.Component; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; @@ -41,8 +42,8 @@ public class BukkitToolItemsTest { 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); + assertEquals(Optional.of(new ToolItem(ResourceId.parse("minecraft:stick"), ToolText.plain("Select bay"), + List.of(ToolText.plain("Right-click to use")), true, "select:bay-1")), item); } @Test @@ -54,7 +55,7 @@ public class BukkitToolItemsTest { ToolItem tagged = BukkitToolItems.read(stackWith(empty, mock(ItemMeta.class))).orElseThrow(); assertEquals("", tagged.payload()); - assertEquals("", tagged.name()); + assertEquals(ToolText.EMPTY, tagged.name()); assertEquals(List.of(), tagged.lore()); assertTrue(BukkitToolItems.read(stackWith(missing, mock(ItemMeta.class))).isEmpty()); } diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/BukkitToolTextTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/BukkitToolTextTest.java new file mode 100644 index 000000000..f36cd29c3 --- /dev/null +++ b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/BukkitToolTextTest.java @@ -0,0 +1,61 @@ +package art.arcane.iris.core.toolworld; + +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolText; +import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.TextDecoration; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class BukkitToolTextTest { + private static final String SECTION = "§"; + + @Test + public void legacyTextHasTheColourCodeOfEachSpanAsTheOldMenusWroteThem() { + ToolText text = ToolText.builder().aqua("Structure").gray(": village").build(); + + assertEquals(SECTION + "bStructure" + SECTION + "7: village", BukkitToolText.legacy(text)); + } + + @Test + public void anUncolouredSpanAfterAnotherResets() { + ToolText text = ToolText.builder().yellow("Walk").append(" plain").build(); + + assertEquals(SECTION + "eWalk" + SECTION + "r plain", BukkitToolText.legacy(text)); + assertEquals("plain", BukkitToolText.legacy(ToolText.plain("plain"))); + assertEquals("", BukkitToolText.legacy(ToolText.EMPTY)); + } + + @Test + public void stylesFollowTheColour() { + ToolText text = ToolText.builder() + .append(new ToolText.Span("x", TextColor.GRAY, true, true, true)).build(); + + assertEquals(SECTION + "7" + SECTION + "l" + SECTION + "o" + SECTION + "mx", BukkitToolText.legacy(text)); + } + + @Test + public void aComponentCarriesTheColoursAndTheTextOfEverySpan() { + ToolText text = ToolText.builder().red("a").append("b").build(); + + Component component = BukkitToolText.component(text); + + assertEquals("ab", PlainTextComponentSerializer.plainText().serialize(component)); + assertEquals(NamedTextColor.RED, component.children().getFirst().color()); + assertEquals(null, component.children().getLast().color()); + assertEquals(TextDecoration.State.NOT_SET, component.children().getFirst().decoration(TextDecoration.ITALIC)); + } + + @Test + public void aTitleTooLongForTheWindowIsCutWithoutLeavingHalfACode() { + ToolText coloured = ToolText.colored(TextColor.GREEN, "x".repeat(40)); + + String cut = BukkitToolMenus.shortened(coloured); + + assertEquals(32, cut.length()); + assertEquals(SECTION + "a", cut.substring(0, 2)); + } +} diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/ToolWorldBookkeepingTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/core/toolworld/ToolWorldBookkeepingTest.java index 4dbeb0456..7b00478e9 100644 --- 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 @@ -4,6 +4,8 @@ import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedBlockEntity; import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedChunk; import com.volmit.object.BlockEntityData; import com.volmit.resource.ResourceId; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolText; import org.bukkit.World; import org.junit.Test; @@ -105,8 +107,9 @@ public class ToolWorldBookkeepingTest { @Test public void aMenuTitleIsShortenedToWhatTheWindowCanShow() { - assertEquals("short", BukkitToolMenus.shortened("short")); - assertEquals(32, BukkitToolMenus.shortened("x".repeat(50)).length()); + assertEquals("short", BukkitToolMenus.shortened(ToolText.plain("short"))); + assertEquals(32, BukkitToolMenus.shortened(ToolText.plain("x".repeat(50))).length()); + assertEquals("§a" + "x".repeat(30), BukkitToolMenus.shortened(ToolText.colored(TextColor.GREEN, "x".repeat(50)))); } private static BukkitToolWorld toolWorld(OpenToolWorlds worlds, String pack, String name, String storageName) { 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 index f8ef00e06..28db681a5 100644 --- 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 @@ -26,6 +26,7 @@ import org.bukkit.event.player.PlayerBucketEmptyEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.server.ServerCommandEvent; import org.bukkit.event.block.Action; @@ -80,6 +81,16 @@ public class ToolWorldEventsTest { heard.add("left " + player.name()); } + @Override + public void teleported(ToolPlayer player, BlockPosition to) { + heard.add("teleported " + player.name() + " " + to.x() + "," + to.y() + "," + to.z()); + } + + @Override + public void containerChanged(Optional player, BlockPosition at) { + heard.add("container " + player.map(ToolPlayer::name).orElse("nobody") + " " + at.x() + "," + at.y() + "," + at.z()); + } + @Override public boolean used(ToolPlayer player, ToolUse use) { heard.add("used " + use.action() + " " + use.hand()); @@ -202,21 +213,53 @@ public class ToolWorldEventsTest { } @Test - public void aPistonNamesItselfAndEveryBlockItMovesAndTheirNeighboursInTheDirectionOfTheMove() { + public void aPistonIsCheckedAgainstEveryBlockItMovesAndTheBlocksTheyLeaveAndEnterButNotItself() { Block piston = block(toolBukkitWorld, 0, 64, 0); Block moved = block(toolBukkitWorld, 1, 64, 0); Block ahead = block(toolBukkitWorld, 2, 64, 0); when(moved.getRelative(BlockFace.EAST)).thenReturn(ahead); when(moved.getRelative(BlockFace.WEST)).thenReturn(piston); - List positions = ToolWorldEvents.pistonPositions(piston, List.of(moved), BlockFace.EAST); + List positions = ToolWorldEvents.pistonChecked(List.of(moved), BlockFace.EAST); - assertEquals(List.of(new BlockPosition(0, 64, 0), new BlockPosition(1, 64, 0), new BlockPosition(2, 64, 0)), positions); + assertEquals(List.of(new BlockPosition(1, 64, 0), new BlockPosition(2, 64, 0), new BlockPosition(0, 64, 0)), positions); + } + + @Test + public void aPistonChangesItselfTheBlockAheadOfItAndEveryBlockItMovesAndWhereTheyGo() { + Block piston = block(toolBukkitWorld, 0, 64, 0); + Block moved = block(toolBukkitWorld, 1, 64, 0); + Block ahead = block(toolBukkitWorld, 2, 64, 0); + when(piston.getRelative(BlockFace.EAST)).thenReturn(moved); + when(moved.getRelative(BlockFace.EAST)).thenReturn(ahead); + + List changed = ToolWorldEvents.pistonChanged(piston, List.of(moved), BlockFace.EAST); + + assertEquals(List.of(new BlockPosition(0, 64, 0), new BlockPosition(1, 64, 0), new BlockPosition(2, 64, 0)), changed); + } + + @Test + public void aPistonThatMovesNothingStillChangesItsOwnBlocks() { + Block piston = block(toolBukkitWorld, 0, 64, 0); + Block ahead = block(toolBukkitWorld, 1, 64, 0); + when(piston.getRelative(BlockFace.EAST)).thenReturn(ahead); + BlockPistonExtendEvent event = mock(BlockPistonExtendEvent.class); + when(event.getBlock()).thenReturn(piston); + when(event.getBlocks()).thenReturn(List.of()); + when(event.getDirection()).thenReturn(BlockFace.EAST); + + events.onPistonExtend(event); + + BlockChange change = onlyChange(); + assertEquals(List.of(), change.positions()); + assertEquals(List.of(new BlockPosition(0, 64, 0), new BlockPosition(1, 64, 0)), change.changed()); } @Test public void aPistonExtendingInAToolWorldIsAPistonChange() { Block piston = block(toolBukkitWorld, 0, 64, 0); + Block ahead = block(toolBukkitWorld, 1, 64, 0); + when(piston.getRelative(BlockFace.EAST)).thenReturn(ahead); BlockPistonExtendEvent event = mock(BlockPistonExtendEvent.class); when(event.getBlock()).thenReturn(piston); when(event.getBlocks()).thenReturn(List.of()); @@ -351,7 +394,76 @@ public class ToolWorldEventsTest { events.onTeleport(teleport); events.onTeleport(teleport); - assertEquals(List.of("entered Tester"), heard); + assertEquals(List.of("entered Tester", "teleported Tester 0,64,0", "teleported Tester 0,64,0"), heard); + } + + @Test + public void aTeleportInsideAToolWorldIsToldAtOnceWithItsDestination() { + PlayerTeleportEvent teleport = mock(PlayerTeleportEvent.class); + when(teleport.getPlayer()).thenReturn(bukkitPlayer); + when(teleport.getFrom()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0)); + when(teleport.getTo()).thenReturn(new Location(toolBukkitWorld, 40, 70, -3)); + + events.onTeleport(teleport); + + assertEquals(List.of("entered Tester", "teleported Tester 40,70,-3"), heard); + } + + @Test + public void aTeleportOutOfAToolWorldIsToldAsLeaving() { + PlayerTeleportEvent in = mock(PlayerTeleportEvent.class); + when(in.getPlayer()).thenReturn(bukkitPlayer); + when(in.getFrom()).thenReturn(new Location(otherBukkitWorld, 0, 64, 0)); + when(in.getTo()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0)); + PlayerTeleportEvent out = mock(PlayerTeleportEvent.class); + when(out.getPlayer()).thenReturn(bukkitPlayer); + when(out.getFrom()).thenReturn(new Location(toolBukkitWorld, 0, 64, 0)); + when(out.getTo()).thenReturn(new Location(otherBukkitWorld, 5, 64, 5)); + + events.onTeleport(in); + events.onTeleport(out); + + assertEquals(List.of("entered Tester", "teleported Tester 0,64,0", "left Tester"), heard); + } + + @Test + public void respawningInAToolWorldIsAnArrivalAtTheRespawnPoint() { + PlayerRespawnEvent respawn = mock(PlayerRespawnEvent.class); + when(respawn.getPlayer()).thenReturn(bukkitPlayer); + when(respawn.getRespawnLocation()).thenReturn(new Location(toolBukkitWorld, 8, 66, 8)); + + events.onRespawn(respawn); + + assertEquals(List.of("entered Tester", "teleported Tester 8,66,8"), heard); + } + + @Test + public void closingAContainerInAToolWorldTellsTheToolWhichBlockChanged() { + Block chest = block(toolBukkitWorld, 4, 65, 4); + org.bukkit.inventory.Inventory inventory = mock(org.bukkit.inventory.Inventory.class); + org.bukkit.inventory.BlockInventoryHolder holder = mock(org.bukkit.inventory.BlockInventoryHolder.class); + when(holder.getBlock()).thenReturn(chest); + when(inventory.getHolder()).thenReturn(holder); + org.bukkit.inventory.InventoryView view = mock(org.bukkit.inventory.InventoryView.class); + when(view.getTopInventory()).thenReturn(inventory); + org.bukkit.event.inventory.InventoryCloseEvent close = mock(org.bukkit.event.inventory.InventoryCloseEvent.class); + when(close.getPlayer()).thenReturn(bukkitPlayer); + when(close.getView()).thenReturn(view); + + events.onInventoryClose(close); + + assertEquals(List.of("container Tester 4,65,4"), heard); + } + + @Test + public void aFurnaceStartingToSmeltTellsTheToolWithoutAPlayer() { + Block furnace = block(toolBukkitWorld, 2, 64, 2); + org.bukkit.event.inventory.FurnaceStartSmeltEvent smelt = mock(org.bukkit.event.inventory.FurnaceStartSmeltEvent.class); + when(smelt.getBlock()).thenReturn(furnace); + + events.onFurnaceStartSmelt(smelt); + + assertEquals(List.of("container nobody 2,64,2"), heard); } @Test @@ -367,7 +479,7 @@ public class ToolWorldEventsTest { events.onQuit(quit); events.onQuit(quit); - assertEquals(List.of("entered Tester", "left Tester"), heard); + assertEquals(List.of("entered Tester", "teleported Tester 0,64,0", "left Tester"), heard); } @Test @@ -413,6 +525,9 @@ public class ToolWorldEventsTest { assertPriority(byMethod, checked, "onTeleport", EventPriority.MONITOR, true); assertPriority(byMethod, checked, "onMove", EventPriority.MONITOR, true); assertPriority(byMethod, checked, "onRespawn", EventPriority.MONITOR, false); + for (String containerNews : List.of("onInventoryClose", "onFurnaceStartSmelt", "onBrewingStart")) { + assertPriority(byMethod, checked, containerNews, EventPriority.MONITOR, false); + } assertPriority(byMethod, checked, "onWorldUnload", EventPriority.MONITOR, true); assertEquals("every handler of the class was checked", byMethod.keySet(), checked); } diff --git a/api/CONTRACTS.md b/api/CONTRACTS.md index 77c0bfbe5..c01cf4b83 100644 --- a/api/CONTRACTS.md +++ b/api/CONTRACTS.md @@ -30,7 +30,7 @@ types that carry them and lists what the Iris adapter still owes. | Area a stage writes | `reach(blocks)`, `reach(PackReach)`, `writesMantle(...)` on stage definitions, `PackSettings` (with `resources()`, for a reach that depends on the size of the pack's objects), host `StageReach`, `ResolvedStage.reachBlocks`, `PipelineReach` | | Settings described for studio | `@Desc`, `@Required`, `@MinNumber`, `@MaxNumber`, `@MinItems`, `@Snippet`, `@Ref`/`Reference`, `@ResourceRef`, `FeatureRegistry.registerSettings`, host `LoadedPack.schema()` (`PackSchema`, `FeatureSchema`, `ObjectType`, `SchemaOption`, `ValueKind` with `HostKind`), `ModuleHost.describingHostTypesIn` | | Geometry and mantle registration | `FeatureRegistry`, host `ModuleRegistry`, `FeatureCatalog` | -| Block states and palettes | `BlockState`, `BlockRegistry` (`resolve(BlockSpec)`, `find(key)`, `blockEntity`, `hasTrait`, `oreFor`, `rotate(state, BlockTurn)`, `merge`, `withPropertyIfAccepted`, `matches`), `BlockTurn`, `BlockTrait` (with `STORAGE`), `BlockSpec`, `PaletteSpec` and `PaletteSampler` (`BlockRegistry.palette`) | +| Block states and palettes | `BlockState`, `BlockRegistry` (`resolve(BlockSpec)`, `find(key)`, `blockEntity`, `hasTrait`, `oreFor`, `rotate(state, BlockTurn)`, `tryRotate(state, BlockTurn)` (empty for a block that cannot face the turn, where `rotate` answers air), `merge`, `withPropertyIfAccepted`, `matches`), `BlockTurn`, `BlockTrait` (with `STORAGE`), `BlockSpec`, `PaletteSpec` and `PaletteSampler` (`BlockRegistry.palette`) | | A pack's objects | `PlaceableObject` (`name`, size, `center`, `geometry`), `PackObjects` (`object`, `sizeOf`, `scaled` with `ScaleMethod`, `smartBored`, `build`), `PackResources.objects()` | | Placing through the pack's placement graph | `Placements.place(PlacementRun)` (`PackWorld.placements()`), `PlacementRun` (request, name, settings JSON, area, terrain, input, seed), `PlacementTerrain` (`recordPlacement` / `placementAt` with a `PlacementRecord`), `StructureVolumes`, `PlacedMarker`, `PlacementOutcome`; stages read `PlacementContext.placementTerrain()` and `input(type)`; mantle stages get a terrain from `MantleGenerationContext.placementTerrain()`; `RunningWorld.placementAt` reads what a placement recorded; `FeatureRegistry.registerPlacementType` names the type packs write placements as (host `FeatureCatalog.placementType()`, `PackSchema.placementType()`) | | Noise from pack-described styles | `NoiseStyle`, `StyledRange`, `PackResources.noise()`, `NoiseFactory`, `NoiseSampler` | @@ -48,7 +48,7 @@ types that carry them and lists what the Iris adapter still owes. | 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` (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`, `closeRefusal`, `closing`, `closed`), `com.volmit.geometry.ChunkPos`; a tool world takes the pack's studio slot, so the host asks `closeRefusal` before it closes the world for another studio, the studio close command or a server stop, and waits for `closing` when another studio replaces it; every Y is the world's own; implemented by each platform adapter (Bukkit; modded adapters answer with a failed `open`) | +| Worlds a tool opens | `com.volmit.tooling.world`, exposed to pack modules by host `ExposedPackages`: `ToolWorlds` (`open`, `find`) with `ToolWorldSpec`, `ChunkPainter` and `ChunkCanvas`, `ToolWorld` (`players`, `owns`, `run`, `call`, `block`, `blockEntity`, `setBlock`, `loaded`, `repaint`, `close`), `ToolPlayer` (`teleport`, `creative`, `message`, `actionBar`, `sound`, `sidebar`, `particles`, `give` answering whether the item fitted, `held`, `openMenu`), `ToolText` with `TextColor` (styled text: item names and lore, menu titles, sidebar, chat and action bar; the host shows each span in its colour and style, an empty sidebar title keeps the platform's, and an item read back has plain text), `ToolItem`, `ToolMenu` with `MenuButton` and `MenuClick`, `Particle`, `ToolWorldListener` (`entered`, `left`, `teleported` for every arrival other than walking, at the time of the teleport, `moved`, `sneakToggled`, `used` with `ToolUse`, `blockChanging` with `BlockChange.Cause` and `BlockChange.changed`, `containerChanged` for a closed container inventory or a furnace or brewing stand that started, `command`, `chunkLoaded`, `closeRefusal`, `closing`, `closed`), `com.volmit.geometry.ChunkPos`; a tool world takes the pack's studio slot, so the host asks `closeRefusal` before it closes the world for another studio, the studio close command or a server stop, and waits for `closing` when another studio replaces it; every Y is the world's own; implemented by each platform adapter (Bukkit; 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 9872f9de5..045b803e8 100644 --- a/api/DESIGN.md +++ b/api/DESIGN.md @@ -1431,8 +1431,9 @@ It exists so the tool lives in a module and runs on every platform: a tool that 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. + its own widgets (VolmLib windows and scoreboards on Bukkit). Their text is `ToolText`: spans of a named colour + (`TextColor`) and a few styles, so no colour codes or components cross the api, and the host maps the spans onto + whatever its platform draws text with. - **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`. diff --git a/api/README.md b/api/README.md index a0214d280..fde99046f 100644 --- a/api/README.md +++ b/api/README.md @@ -620,8 +620,20 @@ worlds.open(new ToolWorldSpec("scratch", painter, new ToolWorldListener() { })) `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. + of `MenuButton`s), chat messages, an action bar, a sidebar, sounds and dust `Particle`s. `give` answers whether the item + fitted; one that did not is neither given nor dropped. `ToolWorld.close()` sends every player back to where they came + from and deletes the world. +- Styled text is `ToolText`, a list of spans with a `TextColor` (the sixteen named colours; none keeps the platform's + default) and bold, italic and strikethrough. Build it with `ToolText.builder().gray("Size: ").white("16x16x16").build()` + or `ToolText.plain`/`ToolText.colored`; `plainText()` drops the style. Item names and lore, menu titles, sidebar lines, + the action bar and `ToolPlayer.message` take it; an empty sidebar title keeps the platform's own. Text of a span is + shown as it is, so it needs no escaping. An item the host reads back carries its name and lore as plain text. +- `ToolWorldListener` also hears `teleported(player, to)` whenever a player arrives by other means than walking (join, + world change, respawn, a teleport or portal by anyone, inside the world too), at the time it happens, after `entered` + for a player coming in; `containerChanged(player, at)` when a container's inventory was closed or a furnace or brewing + stand started working, which no `blockChanging` announced; and `blockChanging` carries in `BlockChange.positions` what + a protected area is checked against and in `BlockChange.changed` the blocks whose content changes, which differ for a + piston. `ToolWorld.loaded(chunk)` asks the platform whether a chunk is loaded. ## Module jars diff --git a/api/api/src/main/java/com/volmit/block/BlockRegistry.java b/api/api/src/main/java/com/volmit/block/BlockRegistry.java index 16f8c9b77..eb7419acf 100644 --- a/api/api/src/main/java/com/volmit/block/BlockRegistry.java +++ b/api/api/src/main/java/com/volmit/block/BlockRegistry.java @@ -68,6 +68,17 @@ public interface BlockRegistry { */ BlockState rotate(BlockState state, BlockTurn turn); + /** + * Like {@link #rotate}, but says when the block cannot face the way it is turned instead of answering air, so a + * caller can tell a block that was dropped from air that stayed air. The default asks {@link #rotate} and takes air + * from a block that is not air for a block that was dropped. + */ + default Optional tryRotate(BlockState state, BlockTurn turn) { + BlockState turned = rotate(state, turn); + boolean dropped = hasTrait(turned, BlockTrait.AIR) && !hasTrait(state, BlockTrait.AIR); + return dropped ? Optional.empty() : Optional.of(turned); + } + /** {@code update} laid over {@code base}: the platform's merge of two states of one block, such as the sides of a * fence, wall or pane; {@code update} when the platform does not merge them. */ diff --git a/api/api/src/main/java/com/volmit/tooling/world/BlockChange.java b/api/api/src/main/java/com/volmit/tooling/world/BlockChange.java index 735d9b898..027fd2aa8 100644 --- a/api/api/src/main/java/com/volmit/tooling/world/BlockChange.java +++ b/api/api/src/main/java/com/volmit/tooling/world/BlockChange.java @@ -10,12 +10,21 @@ 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 positions the blocks a protected area is checked against: the block a player breaks or places, the blocks an + * explosion would destroy one at a time, the blocks a piston moves with the blocks they leave and + * enter. Empty only when {@code changed} is not, such as a piston that moves nothing. + * @param changed the blocks whose content changes, which a tool may want to save; the same as {@code positions} + * unless the cause touches other blocks than it is checked against, as a piston does with its own block * @param player the player behind it, when there is one * @param placed the state being placed, for {@link Cause#PLACE} and {@link Cause#BUCKET}; empty when it is not known */ -public record BlockChange(Cause cause, List positions, Optional player, Optional placed) { +public record BlockChange( + Cause cause, + List positions, + List changed, + Optional player, + Optional placed +) { /** What changes a block. */ public enum Cause { /** A player places a block. */ @@ -49,10 +58,16 @@ public record BlockChange(Cause cause, List positions, Optional positions, Optional player, Optional placed) { + this(cause, positions, positions, player, placed); + } } diff --git a/api/api/src/main/java/com/volmit/tooling/world/TextColor.java b/api/api/src/main/java/com/volmit/tooling/world/TextColor.java new file mode 100644 index 000000000..aa643f065 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/TextColor.java @@ -0,0 +1,35 @@ +package com.volmit.tooling.world; + +/** + * The sixteen named colours of Minecraft text, in the order of their formatting codes. Every platform shows them the same + * way, so a tool picks a colour by name and the host maps it. + */ +public enum TextColor { + BLACK('0'), + DARK_BLUE('1'), + DARK_GREEN('2'), + DARK_AQUA('3'), + DARK_RED('4'), + DARK_PURPLE('5'), + GOLD('6'), + GRAY('7'), + DARK_GRAY('8'), + BLUE('9'), + GREEN('a'), + AQUA('b'), + RED('c'), + LIGHT_PURPLE('d'), + YELLOW('e'), + WHITE('f'); + + private final char code; + + TextColor(char code) { + this.code = code; + } + + /** The character that follows the formatting sign in Minecraft's legacy codes, such as {@code 'a'} for green. */ + public char code() { + return code; + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/ToolItem.java b/api/api/src/main/java/com/volmit/tooling/world/ToolItem.java index d3a53cbb4..77117f7a9 100644 --- a/api/api/src/main/java/com/volmit/tooling/world/ToolItem.java +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolItem.java @@ -10,13 +10,16 @@ import java.util.Objects; * data on Bukkit and as custom data on modded platforms, and hands it back through {@link ToolPlayer#held()} and * {@link ToolUse#item()}. A tool tells its own items apart by their payload. * + *

The host shows the name and the lore the way the platform shows text a plugin sets on an item, in the colours of + * the {@link ToolText}. An item the host reads back from a player carries its name and lore as plain text. + * * @param item the platform's item, such as {@code minecraft:stick} - * @param name the display name as plain text; empty keeps the item's own name - * @param lore the lines under the name, plain text + * @param name the display name; empty keeps the item's own name + * @param lore the lines under the name * @param glowing whether the item shows the enchantment glint * @param payload what the tool keeps on the item; empty for nothing */ -public record ToolItem(ResourceId item, String name, List lore, boolean glowing, String payload) { +public record ToolItem(ResourceId item, ToolText name, List lore, boolean glowing, String payload) { public ToolItem { Objects.requireNonNull(item, "item"); Objects.requireNonNull(name, "name"); 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 index e5d8175ed..284a3342e 100644 --- a/api/api/src/main/java/com/volmit/tooling/world/ToolMenu.java +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolMenu.java @@ -8,14 +8,14 @@ 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 title the title; the host shortens it to what the window can show * @param rows the number of rows, 1 to {@value #MAX_ROWS} * @param buttons the slots that do something; the others show a filler. No slot is used twice and every slot is inside * the rows. * @param onClose called on the player's thread when the menu closes for any reason: the player closed it, the world * closed, or the tool closed or replaced it. Null stands for nothing to do. */ -public record ToolMenu(String title, int rows, List buttons, Runnable onClose) { +public record ToolMenu(ToolText title, int rows, List buttons, Runnable onClose) { public static final int MAX_ROWS = 6; public static final int SLOTS_PER_ROW = 9; 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 index 57db252a6..9ffae6411 100644 --- a/api/api/src/main/java/com/volmit/tooling/world/ToolPlayer.java +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolPlayer.java @@ -23,7 +23,7 @@ public interface ToolPlayer { /** 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. */ + /** The player as a command sender; its messages are plain text, delivered on the thread the platform needs. For styled text use {@link #message}. */ Sender sender(); /** The tool world the player stands in; empty when they stand in another world, even another pack's tool world. */ @@ -54,17 +54,20 @@ public interface ToolPlayer { */ void creative(boolean on); + /** Sends {@code text} to the player's chat, in its colours. */ + void message(ToolText text); + /** Shows {@code text} above the hotbar. */ - void actionBar(String text); + void actionBar(ToolText text); /** Plays {@code sound}, such as {@code minecraft:block.note_block.pling}, to this player only, where they stand. */ void sound(ResourceId sound, float volume, float pitch); /** * Shows a sidebar with {@code title} and {@code lines}, top to bottom, replacing the one this player has from a tool. - * Text is plain: the host removes formatting codes. The sidebar goes away when the player leaves the tool world. + * An empty title keeps the platform's own sidebar title. The sidebar goes away when the player leaves the tool world. */ - void sidebar(String title, List lines); + void sidebar(ToolText title, List lines); /** Removes the sidebar {@link #sidebar} showed. */ void hideSidebar(); @@ -72,8 +75,12 @@ public interface ToolPlayer { /** 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); + /** + * Puts {@code item} in the player's inventory, in the first free slot, and returns whether it fitted. An item that did + * not fit is not given and not dropped. Called off the player's own thread, the item is given later and the answer + * is true. + */ + boolean give(ToolItem item); /** The tool item in the player's main hand; empty when the held item is not one, which is when it carries no payload. */ Optional held(); diff --git a/api/api/src/main/java/com/volmit/tooling/world/ToolText.java b/api/api/src/main/java/com/volmit/tooling/world/ToolText.java new file mode 100644 index 000000000..942d865e3 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolText.java @@ -0,0 +1,188 @@ +package com.volmit.tooling.world; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * Styled text a tool shows a player: item names and lore, menu titles, sidebars, the action bar and chat. It is a list of + * spans, each a piece of text with its own colour and style, so the text carries no formatting codes and a platform shows + * it with its own text components. A value is immutable. + * + *

Build it with {@link #builder()}, or use {@link #plain(String)} and {@link #colored(TextColor, String)} for one span. + * Text of a span is shown as it is: a formatting sign in it is just a character. + * + * @param spans the pieces in order + */ +public record ToolText(List spans) { + /** Nothing at all. */ + public static final ToolText EMPTY = new ToolText(List.of()); + + public ToolText { + spans = List.copyOf(spans); + } + + /** + * A piece of text in one style. + * + * @param text what is shown, never empty + * @param color the colour; null leaves the platform's default colour for that kind of text + * @param bold whether the text is bold + * @param italic whether the text is italic + * @param strikethrough whether the text has a line through it + */ + public record Span(String text, TextColor color, boolean bold, boolean italic, boolean strikethrough) { + public Span { + Objects.requireNonNull(text, "text"); + if (text.isEmpty()) { + throw new IllegalArgumentException("A span has text"); + } + } + + /** A span in {@code color} and no other style. */ + public static Span of(TextColor color, String text) { + return new Span(text, color, false, false, false); + } + + boolean sameStyle(Span other) { + return color == other.color && bold == other.bold && italic == other.italic + && strikethrough == other.strikethrough; + } + } + + /** One span in the platform's default colour. */ + public static ToolText plain(String text) { + return builder().append(text).build(); + } + + /** One span in {@code color}. */ + public static ToolText colored(TextColor color, String text) { + return builder().append(color, text).build(); + } + + public static Builder builder() { + return new Builder(); + } + + /** The text without any style, as one string. */ + public String plainText() { + StringBuilder text = new StringBuilder(); + for (Span span : spans) { + text.append(span.text()); + } + return text.toString(); + } + + public boolean isEmpty() { + return spans.isEmpty(); + } + + /** Builds a {@link ToolText} span by span. Empty text is skipped, and neighbours of one style become one span. */ + @SuppressWarnings("UnusedReturnValue") + public static final class Builder { + private final List spans = new ArrayList<>(); + + private Builder() { + } + + /** Adds {@code text} in the platform's default colour; empty text adds nothing. */ + public Builder append(String text) { + Objects.requireNonNull(text, "text"); + return text.isEmpty() ? this : append(new Span(text, null, false, false, false)); + } + + /** Adds {@code text} in {@code color}; empty text adds nothing. */ + public Builder append(TextColor color, String text) { + Objects.requireNonNull(color, "color"); + Objects.requireNonNull(text, "text"); + return text.isEmpty() ? this : append(Span.of(color, text)); + } + + /** Adds {@code span}, joined to the span before it when they share a style. */ + public Builder append(Span span) { + Objects.requireNonNull(span, "span"); + if (!spans.isEmpty() && spans.getLast().sameStyle(span)) { + Span last = spans.removeLast(); + spans.add(new Span(last.text() + span.text(), last.color(), last.bold(), last.italic(), + last.strikethrough())); + return this; + } + spans.add(span); + return this; + } + + public Builder append(ToolText text) { + Objects.requireNonNull(text, "text"); + text.spans().forEach(this::append); + return this; + } + + public Builder black(String text) { + return append(TextColor.BLACK, text); + } + + public Builder darkBlue(String text) { + return append(TextColor.DARK_BLUE, text); + } + + public Builder darkGreen(String text) { + return append(TextColor.DARK_GREEN, text); + } + + public Builder darkAqua(String text) { + return append(TextColor.DARK_AQUA, text); + } + + public Builder darkRed(String text) { + return append(TextColor.DARK_RED, text); + } + + public Builder darkPurple(String text) { + return append(TextColor.DARK_PURPLE, text); + } + + public Builder gold(String text) { + return append(TextColor.GOLD, text); + } + + public Builder gray(String text) { + return append(TextColor.GRAY, text); + } + + public Builder darkGray(String text) { + return append(TextColor.DARK_GRAY, text); + } + + public Builder blue(String text) { + return append(TextColor.BLUE, text); + } + + public Builder green(String text) { + return append(TextColor.GREEN, text); + } + + public Builder aqua(String text) { + return append(TextColor.AQUA, text); + } + + public Builder red(String text) { + return append(TextColor.RED, text); + } + + public Builder lightPurple(String text) { + return append(TextColor.LIGHT_PURPLE, text); + } + + public Builder yellow(String text) { + return append(TextColor.YELLOW, text); + } + + public Builder white(String text) { + return append(TextColor.WHITE, text); + } + + public ToolText build() { + return new ToolText(spans); + } + } +} diff --git a/api/api/src/main/java/com/volmit/tooling/world/ToolWorld.java b/api/api/src/main/java/com/volmit/tooling/world/ToolWorld.java index de8a6a7fd..f8effaffe 100644 --- a/api/api/src/main/java/com/volmit/tooling/world/ToolWorld.java +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolWorld.java @@ -67,6 +67,9 @@ public interface ToolWorld { */ void setBlock(BlockPosition at, BlockState state, Optional data); + /** Whether the platform has {@code chunk} loaded right now. Safe from any thread; a tool treats it as a hint. */ + boolean loaded(ChunkPos chunk); + /** * Runs the painter again for {@code chunks}, writes the differences into the live chunks and sends them to the * players. Block entities the painter sets replace those of the chunk. The future completes on a host thread when 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 index 4451a5e24..2c325f65f 100644 --- a/api/api/src/main/java/com/volmit/tooling/world/ToolWorldListener.java +++ b/api/api/src/main/java/com/volmit/tooling/world/ToolWorldListener.java @@ -23,6 +23,17 @@ public interface ToolWorldListener { default void left(ToolPlayer player) { } + /** + * A player arrived at a position of the world by other means than walking: they joined the server in it, changed + * world into it, respawned in it, or were teleported into it or inside it by anyone, such as a command, another + * plugin or a portal. It is told at the time of the teleport, with the position they arrive at, and for a player + * coming in after {@link #entered}. A player teleported out only hears {@link #left}. The default treats it as + * {@link #moved}. + */ + default void teleported(ToolPlayer player, BlockPosition to) { + moved(player, to); + } + /** A player moved to another block of the world; not called for moves inside one block. */ default void moved(ToolPlayer player, BlockPosition to) { } @@ -49,6 +60,18 @@ public interface ToolWorldListener { return true; } + /** + * What is inside a container or a machine changed without a block changing: a player closed a container block's + * inventory, a furnace started smelting, a brewing stand started brewing. It is told after the fact and cannot be + * cancelled; {@link #blockChanging} with {@link BlockChange.Cause#CONTAINER} or {@link BlockChange.Cause#MACHINE} + * decides the changes that can be. + * + * @param player the player behind it, when there is one + * @param at the block of the container or machine + */ + default void containerChanged(Optional player, BlockPosition at) { + } + /** A chunk of the world finished loading, painted or read back. */ default void chunkLoaded(int chunkX, int chunkZ) { } 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 index 03e89cc3a..c4c85edec 100644 --- a/api/api/src/test/java/com/volmit/tooling/world/ToolWorldRecordsTest.java +++ b/api/api/src/test/java/com/volmit/tooling/world/ToolWorldRecordsTest.java @@ -14,7 +14,7 @@ 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, ""); + private static final ToolItem ICON = new ToolItem(STICK, ToolText.plain("Tool"), List.of(ToolText.plain("line")), false, ""); @Test void aChunkIsTheBlockCoordinatesDividedBySixteenRoundedDown() { @@ -48,34 +48,74 @@ class ToolWorldRecordsTest { @Test void aToolItemKeepsItsOwnCopyOfTheLore() { - var lore = new ArrayList<>(List.of("one")); - var item = new ToolItem(STICK, "Name", lore, true, "payload"); - lore.add("two"); + var lore = new ArrayList<>(List.of(ToolText.plain("one"))); + var item = new ToolItem(STICK, ToolText.plain("Name"), lore, true, "payload"); + lore.add(ToolText.plain("two")); - assertEquals(List.of("one"), item.lore()); - assertThrows(UnsupportedOperationException.class, () -> item.lore().add("three")); - assertThrows(NullPointerException.class, () -> new ToolItem(STICK, "Name", List.of(), false, null)); + assertEquals(List.of(ToolText.plain("one")), item.lore()); + assertThrows(UnsupportedOperationException.class, () -> item.lore().add(ToolText.plain("three"))); + assertThrows(NullPointerException.class, () -> new ToolItem(STICK, ToolText.plain("Name"), List.of(), false, null)); + } + + @Test + void textIsSpansOfColourAndStyleAndAdjoiningSpansOfOneStyleJoin() { + var text = ToolText.builder().gray("Capacity: ").gray("16x16x16").white(" now").append(" plain").build(); + + assertEquals(3, text.spans().size()); + assertEquals("Capacity: 16x16x16 now plain", text.plainText()); + assertEquals(new ToolText.Span("Capacity: 16x16x16", TextColor.GRAY, false, false, false), text.spans().getFirst()); + assertNull(text.spans().getLast().color()); + } + + @Test + void emptyTextAddsNoSpanAndPlainTextOfNothingIsEmpty() { + var text = ToolText.builder().red("").append("").build(); + + assertTrue(text.isEmpty()); + assertEquals("", text.plainText()); + assertEquals(ToolText.EMPTY, text); + assertThrows(IllegalArgumentException.class, () -> new ToolText.Span("", null, false, false, false)); + } + + @Test + void textKeepsItsOwnCopyOfTheSpans() { + var spans = new ArrayList<>(List.of(ToolText.Span.of(TextColor.RED, "a"))); + var text = new ToolText(spans); + spans.add(ToolText.Span.of(TextColor.RED, "b")); + + assertEquals("a", text.plainText()); + assertThrows(UnsupportedOperationException.class, () -> text.spans().add(ToolText.Span.of(TextColor.RED, "c"))); + } + + @Test + void theSixteenColoursHaveTheirFormattingCodes() { + var codes = new StringBuilder(); + for (TextColor color : TextColor.values()) { + codes.append(color.code()); + } + + assertEquals("0123456789abcdef", codes.toString()); } @Test void aMenuHasOneToSixRowsAndEveryButtonInsideThemOnItsOwnSlot() { var button = new MenuButton(17, ICON, click -> { }); - assertEquals(1, new ToolMenu("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"); + assertEquals(1, new ToolMenu(ToolText.plain("t"),1, List.of(new MenuButton(8, ICON, click -> { })), null).rows()); + assertEquals(2, new ToolMenu(ToolText.plain("t"),2, List.of(button), null).rows()); + assertThrows(IllegalArgumentException.class, () -> new ToolMenu(ToolText.plain("t"),0, List.of(), null)); + assertThrows(IllegalArgumentException.class, () -> new ToolMenu(ToolText.plain("t"),7, List.of(), null)); + assertThrows(IllegalArgumentException.class, () -> new ToolMenu(ToolText.plain("t"),1, List.of(button), null), "slot 17 is in the second row"); assertThrows(IllegalArgumentException.class, - () -> new ToolMenu("t", 2, List.of(button, new MenuButton(17, ICON, click -> { })), null)); + () -> new ToolMenu(ToolText.plain("t"),2, List.of(button, new MenuButton(17, ICON, click -> { })), null)); assertThrows(IllegalArgumentException.class, () -> new MenuButton(-1, ICON, click -> { })); } @Test void aMenuWithoutAnOnCloseHasOneThatDoesNothing() { var closed = new AtomicBoolean(); - var withHandler = new ToolMenu("t", 1, List.of(), () -> closed.set(true)); - var without = new ToolMenu("t", 1, List.of(), null); + var withHandler = new ToolMenu(ToolText.plain("t"),1, List.of(), () -> closed.set(true)); + var without = new ToolMenu(ToolText.plain("t"),1, List.of(), null); without.onClose().run(); assertFalse(closed.get()); @@ -94,6 +134,36 @@ class ToolWorldRecordsTest { () -> new BlockChange(BlockChange.Cause.BREAK, List.of(), Optional.empty(), Optional.empty())); } + @Test + void whatAChangeChangesIsWhatItIsCheckedAgainstUnlessSaidOtherwise() { + var position = new BlockPosition(1, 2, 3); + var aside = new BlockPosition(4, 5, 6); + + assertEquals(List.of(position), new BlockChange(BlockChange.Cause.PLACE, List.of(position), Optional.empty(), Optional.empty()).changed()); + var piston = new BlockChange(BlockChange.Cause.PISTON, List.of(), List.of(aside), Optional.empty(), Optional.empty()); + assertEquals(List.of(), piston.positions()); + assertEquals(List.of(aside), piston.changed()); + assertThrows(IllegalArgumentException.class, + () -> new BlockChange(BlockChange.Cause.PISTON, List.of(), List.of(), Optional.empty(), Optional.empty())); + } + + @Test + void aTeleportIsAMoveToAListenerThatDoesNotCareAndNothingToCareAboutInContainers() { + var moves = new ArrayList(); + var listener = new ToolWorldListener() { + @Override + public void moved(ToolPlayer player, BlockPosition to) { + moves.add(to); + } + }; + var to = new BlockPosition(7, 8, 9); + + listener.teleported(null, to); + listener.containerChanged(Optional.empty(), to); + + assertEquals(List.of(to), moves); + } + @Test void aListenerThatImplementsNothingFreezesTheWorldAndAllowsEverythingElse() { var listener = new ToolWorldListener() { }; diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisBlockRegistry.java b/core/src/main/java/art/arcane/iris/core/modules/IrisBlockRegistry.java index 348127eff..6821f3ccd 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisBlockRegistry.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisBlockRegistry.java @@ -148,8 +148,14 @@ final class IrisBlockRegistry implements BlockRegistry { /** A block that cannot face the way it is turned is dropped, as Iris drops it: it becomes air. */ @Override public BlockState rotate(BlockState state, BlockTurn turn) { + return tryRotate(state, turn).orElse(PlatformBlockStates.AIR); + } + + /** Empty exactly when the platform has no state for the turned block, which is when Iris drops it. */ + @Override + public Optional tryRotate(BlockState state, BlockTurn turn) { PlatformBlockState rotated = BlockStateRotation.rotate(turn, platformState(state)); - return rotated == null ? PlatformBlockStates.AIR : apiState(rotated); + return rotated == null ? Optional.empty() : Optional.of(apiState(rotated)); } @Override diff --git a/core/src/main/java/art/arcane/iris/core/runtime/StudioOpenCoordinator.java b/core/src/main/java/art/arcane/iris/core/runtime/StudioOpenCoordinator.java index 4d388afcb..90663c4a2 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 @@ -101,10 +101,10 @@ public final class StudioOpenCoordinator { * 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) { + public CompletableFuture closeToolWorld(World world, IrisProject project) { Objects.requireNonNull(world, "world"); PlatformChunkGenerator provider = IrisToolbelt.access(world); - return closeWorldCoordinated(provider, IrisWorldStorage.logicalName(world), world, true, null); + return closeWorldCoordinated(provider, IrisWorldStorage.logicalName(world), world, true, project); } public CompletableFuture teleportPlayerToProject( diff --git a/core/src/main/java/art/arcane/iris/core/runtime/StudioSlotOccupant.java b/core/src/main/java/art/arcane/iris/core/runtime/StudioSlotOccupant.java index 3287aecf2..fa2f4481f 100644 --- a/core/src/main/java/art/arcane/iris/core/runtime/StudioSlotOccupant.java +++ b/core/src/main/java/art/arcane/iris/core/runtime/StudioSlotOccupant.java @@ -18,6 +18,8 @@ package art.arcane.iris.core.runtime; +import art.arcane.iris.core.project.IrisProject; + import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -28,6 +30,12 @@ import java.util.concurrent.CompletableFuture; * the tool that owns the world. */ public interface StudioSlotOccupant { + /** + * The studio project the world is, which the studio service shows to every command that asks for the open studio: it + * is open while the world is and carries the world's generator, as the project of any other studio does. + */ + IrisProject project(); + /** A message that vetoes closing the world now; empty lets it close. */ Optional closeRefusal(); 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 b1dce9c55..88247c8a0 100644 --- a/core/src/main/java/art/arcane/iris/core/service/BoardSVC.java +++ b/core/src/main/java/art/arcane/iris/core/service/BoardSVC.java @@ -31,6 +31,7 @@ import art.arcane.volmlib.util.board.Board; import art.arcane.volmlib.util.board.BoardProvider; import art.arcane.volmlib.util.board.BoardSettings; import art.arcane.volmlib.util.board.ScoreDirection; +import com.volmit.tooling.world.ToolText; import art.arcane.volmlib.util.format.Form; import art.arcane.iris.util.common.plugin.IrisService; import art.arcane.iris.util.common.scheduling.J; @@ -176,8 +177,11 @@ public class BoardSVC implements IrisService, BoardProvider { } } - /** 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) { + /** + * What a tool shows a player in a tool world: a title and styled lines, top to bottom, for as long as the player + * stays in {@code worldId}. An empty title keeps the Iris board title. + */ + public record ToolSidebar(UUID worldId, ToolText title, List lines) { public ToolSidebar { Objects.requireNonNull(worldId, "worldId"); Objects.requireNonNull(title, "title"); @@ -256,7 +260,7 @@ public class BoardSVC implements IrisService, BoardProvider { @Override public String getTitle(Player player) { PlayerBoard board = boards.get(player); - if (board != null && board.view == BoardView.TOOL) { + if (board != null && board.view == BoardView.TOOL && !board.title.isEmpty()) { return board.title; } return IrisLanguage.text(BukkitUiMessages.SCOREBOARD_TITLE); @@ -324,7 +328,33 @@ public class BoardSVC implements IrisService, BoardProvider { } static List toolLines(ToolSidebar sidebar) { - return sidebar.lines().stream().map(BoardSVC::untrustedBoardValue).toList(); + return sidebar.lines().stream().map(BoardSVC::boardLine).toList(); + } + + /** + * {@code text} in the board's {@code &} codes: each span starts with its colour and styles, a span without a colour + * resets after another, and the text of a span cannot carry codes of its own. + */ + static String boardLine(ToolText text) { + StringBuilder line = new StringBuilder(); + for (ToolText.Span span : text.spans()) { + if (span.color() != null) { + line.append('&').append(span.color().code()); + } else if (!line.isEmpty()) { + line.append("&r"); + } + if (span.bold()) { + line.append("&l"); + } + if (span.italic()) { + line.append("&o"); + } + if (span.strikethrough()) { + line.append("&m"); + } + line.append(untrustedBoardValue(span.text())); + } + return line.toString(); } public class PlayerBoard { @@ -391,7 +421,7 @@ public class BoardSVC implements IrisService, BoardProvider { } view = BoardView.TOOL; toolSidebar = sidebar; - title = untrustedBoardValue(sidebar.title()); + title = boardLine(sidebar.title()); lines = toolLines(sidebar); board.update(); } diff --git a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioBlocks.java b/core/src/main/java/art/arcane/iris/core/service/JigsawStudioBlocks.java index e62e1026b..22ffd6101 100644 --- a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioBlocks.java +++ b/core/src/main/java/art/arcane/iris/core/service/JigsawStudioBlocks.java @@ -38,16 +38,11 @@ public final class JigsawStudioBlocks { return BlockState.parse(JIGSAW_BLOCK + "[" + ORIENTATION_PROPERTY + "=" + orientation + "]"); } - /** - * {@code state} turned like {@code rotation}; null when the block cannot face the way it is turned, which the - * registry reports as air. - */ + /** {@code state} turned like {@code rotation}; null when the registry cannot turn the block. */ public static BlockState rotated(BlockRegistry registry, BlockState state, ObjectTurn rotation) { if (!rotation.canRotate()) { return state; } - BlockState turned = registry.rotate(state, rotation.blockTurn()); - boolean dropped = turned.equals(AIR) && !state.equals(AIR); - return dropped ? null : turned; + return registry.tryRotate(state, rotation.blockTurn()).orElse(null); } } diff --git a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioBoardContext.java b/core/src/main/java/art/arcane/iris/core/service/JigsawStudioBoardContext.java index 3e6064cfb..f1c998233 100644 --- a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioBoardContext.java +++ b/core/src/main/java/art/arcane/iris/core/service/JigsawStudioBoardContext.java @@ -1,6 +1,8 @@ package art.arcane.iris.core.service; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolText; import java.util.ArrayList; import java.util.List; @@ -18,7 +20,6 @@ public record JigsawStudioBoardContext( JigsawStudioBoardState state, String controlHint ) { - private static final String SIDEBAR_TITLE = "Iris"; private static final String SEPARATOR = "-------------------"; private static final int SIDEBAR_LINE_CAPACITY = 11; @@ -41,40 +42,51 @@ public record JigsawStudioBoardContext( return !workcellName.isEmpty(); } - public String sidebarTitle() { - return SIDEBAR_TITLE; + /** Empty: the sidebar keeps the platform's own title. */ + public ToolText sidebarTitle() { + return ToolText.EMPTY; } - /** The sidebar lines for this context, top to bottom, as plain text. */ - public List sidebarLines() { - List lines = new ArrayList<>(SIDEBAR_LINE_CAPACITY); - lines.add(SEPARATOR); - lines.add("Jigsaw Studio"); - lines.add("Structure: " + structureKey); + /** The sidebar lines for this context, top to bottom. */ + public List sidebarLines() { + List lines = new ArrayList<>(SIDEBAR_LINE_CAPACITY); + lines.add(separator()); + lines.add(ToolText.colored(TextColor.LIGHT_PURPLE, "Jigsaw Studio")); + lines.add(labelled("Structure", structureKey)); if (!insideWorkcell()) { - lines.add("Mode: " + modeDisplayName()); - lines.add(SEPARATOR); - lines.add("Walk into a workcell"); + lines.add(labelled("Mode", modeDisplayName())); + lines.add(separator()); + lines.add(ToolText.colored(TextColor.YELLOW, "Walk into a workcell")); if (!controlHint.isEmpty()) { - lines.add(controlHint); + lines.add(ToolText.colored(TextColor.GRAY, controlHint)); } - lines.add(SEPARATOR); + lines.add(separator()); return List.copyOf(lines); } - lines.add("Workcell: " + workcellName); + lines.add(labelled("Workcell", workcellName)); if (!workcellRole.isEmpty() && !workcellRole.equals(workcellName)) { - lines.add("Role: " + workcellRole); + lines.add(labelled("Role", workcellRole)); } - lines.add("Variant: " + (variantName.isEmpty() ? "None" : variantName)); - lines.add("State: " + state.displayName()); - lines.add(SEPARATOR); + lines.add(labelled("Variant", variantName.isEmpty() ? "None" : variantName)); + lines.add(labelled("State", state.displayName())); + lines.add(separator()); if (!controlHint.isEmpty()) { - lines.add(controlHint); + lines.add(ToolText.colored(TextColor.YELLOW, controlHint)); } - lines.add(SEPARATOR); + lines.add(separator()); return List.copyOf(lines); } + private static ToolText separator() { + return ToolText.builder() + .append(new ToolText.Span(SEPARATOR, TextColor.GRAY, false, false, true)) + .build(); + } + + private static ToolText labelled(String label, String value) { + return ToolText.builder().aqua(label).gray(": " + value).build(); + } + public String modeDisplayName() { return switch (mode) { case PLANAR_JIGSAW -> "Planar"; diff --git a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuController.java b/core/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuController.java index da1098fbc..9faa40447 100644 --- a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuController.java +++ b/core/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuController.java @@ -6,7 +6,9 @@ import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioPieceRules; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolAction; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolPayload; +import com.volmit.tooling.world.TextColor; import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolText; import java.util.ArrayList; import java.util.List; @@ -268,18 +270,18 @@ public final class JigsawStudioMenuController { "duplicate-family", available ? JigsawStudioMenuIcon.PURPLE_DYE : JigsawStudioMenuIcon.GRAY_DYE, available - ? "Duplicate All Enabled Cells as Family" - : "Duplicate All Enabled Cells as Family"); - family.addLore("Copies each enabled cell's loaded variant into one coherent family."); - family.addLore("New family: " + safe(nextThemeKey)); + ? lightPurple("Duplicate All Enabled Cells as Family") + : gray("Duplicate All Enabled Cells as Family")); + family.addLore(gray("Copies each enabled cell's loaded variant into one coherent family.")); + family.addLore(gray("New family: " + safe(nextThemeKey))); if (available) { - family.addLore("Left-click to duplicate the complete family atomically"); + family.addLore(yellow("Left-click to duplicate the complete family atomically")); family.onLeftClick(clicked -> duplicateActiveFamily( window.getViewer(), state.requestId(), nextThemeKey)); } else if (!state.irisExtended()) { - family.addLore("Coherent families require Iris compatibility."); + family.addLore(gray("Coherent families require Iris compatibility.")); } else { - family.addLore("Load an owned variant in every enabled workcell first."); + family.addLore(gray("Load an owned variant in every enabled workcell first.")); } window.setElement(3, 0, family); } @@ -294,14 +296,14 @@ public final class JigsawStudioMenuController { state.irisExtended() ? state.requireCaps() ? JigsawStudioMenuIcon.IRON_BARS : JigsawStudioMenuIcon.TRIPWIRE_HOOK : JigsawStudioMenuIcon.BARRIER, - "Structure Rules"); - structure.addLore("Mandatory caps: " + yesNo(state.requireCaps())); - structure.addLore("Theme sets: " + state.themeSets().size()); - structure.addLore("Compatibility: " + compatibilityName(state.compatibilityTarget())); - structure.addLore("Left-click for themes and rules"); + lightPurple("Structure Rules")); + structure.addLore(gray("Mandatory caps: " + yesNo(state.requireCaps()))); + structure.addLore(gray("Theme sets: " + state.themeSets().size())); + structure.addLore(gray("Compatibility: " + compatibilityName(state.compatibilityTarget()))); + structure.addLore(yellow("Left-click for themes and rules")); structure.addLore(state.irisExtended() - ? "Right-click to toggle mandatory caps" - : "Mandatory caps and themes require Iris compatibility"); + ? yellow("Right-click to toggle mandatory caps") + : gray("Mandatory caps and themes require Iris compatibility")); structure.onLeftClick(clicked -> openStructureSettings( window.getViewer(), state.requestId(), selectedWorkcellId, 0)); if (state.irisExtended()) { @@ -320,26 +322,28 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement element = element( "workcell-" + index, workcellMaterial(workcell, selected), - safe(workcell.displayName())) + ToolText.colored( + selected ? TextColor.AQUA : workcell.enabled() ? TextColor.WHITE : TextColor.GRAY, + safe(workcell.displayName()))) .setEnchanted(selected); element.addLore(workcell.enabled() - ? "Enabled" - : "Disabled for assembly and export"); + ? green("Enabled") + : red("Disabled for assembly and export")); if (!workcell.canonicalName().equals(workcell.displayName())) { - element.addLore("Solver role: " + safe(workcell.canonicalName())); + element.addLore(gray("Solver role: " + safe(workcell.canonicalName()))); } - element.addLore("Capacity: " + dimensions(workcell.capacity())); - element.addLore("Variants: " + workcell.variants().size()); + element.addLore(gray("Capacity: " + dimensions(workcell.capacity()))); + element.addLore(gray("Variants: " + workcell.variants().size())); JigsawStudioMenuState.Variant active = workcell.activeVariant(); - element.addLore("Loaded: " - + (active == null ? "None" : safe(active.displayName()))); + element.addLore(gray("Loaded: " + + (active == null ? "None" : safe(active.displayName())))); element.addLore(workcellStatus(workcell)); - element.addLore("Connector blocks: " - + (workcell.connectorsVisible() ? "Visible" : "Hidden")); - element.addLore("Left-click to select and teleport"); - element.addLore("Right-click for workcell settings"); + element.addLore(gray("Connector blocks: " + + (workcell.connectorsVisible() ? "Visible" : "Hidden"))); + element.addLore(yellow("Left-click to select and teleport")); + element.addLore(yellow("Right-click for workcell settings")); if (workcell.dirty() && !workcell.saving()) { - element.addLore("Shift-left: Flush Autosave Now"); + element.addLore(gold("Shift-left: Flush Autosave Now")); element.onShiftLeftClick(clicked -> flushNow( window.getViewer(), state.requestId(), workcell.stableId())); } @@ -368,8 +372,8 @@ public final class JigsawStudioMenuController { List variants = page( workcell.variants(), page, VARIANTS_PER_PAGE); if (variants.isEmpty()) { - JigsawStudioMenuElement empty = element("no-variants", JigsawStudioMenuIcon.BARRIER, "No variants"); - empty.addLore("Create a variant to begin authoring this workcell."); + JigsawStudioMenuElement empty = element("no-variants", JigsawStudioMenuIcon.BARRIER, red("No variants")); + empty.addLore(gray("Create a variant to begin authoring this workcell.")); window.setElement(0, 2, empty); return; } @@ -381,24 +385,26 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement element = element( "variant-" + index, variantMaterial(variant), - safe(variant.displayName()) - + (variant.active() ? " [Loaded]" : "")) + ToolText.builder() + .append(variant.active() ? TextColor.GREEN : TextColor.WHITE, safe(variant.displayName())) + .aqua(variant.active() ? " [Loaded]" : "") + .build()) .setEnchanted(variant.active()); - element.addLore(safe(variant.pieceKey())); + element.addLore(darkGray(safe(variant.pieceKey()))); element.addLore(variant.owned() - ? "Owned" - : "Read-only"); - element.addLore("Rotation: " + (variant.rotatable() ? "Enabled" : "Disabled")); - element.addLore("Size: " + variant.dimensions() + ? green("Owned") + : gray("Read-only")); + element.addLore(gray("Rotation: " + (variant.rotatable() ? "Enabled" : "Disabled"))); + element.addLore(gray("Size: " + variant.dimensions() .map(JigsawStudioMenuController::dimensions) - .orElse("Object missing")); - element.addLore("Themes: " + themes(variant.themes())); - element.addLore("Pool entries: " + variant.memberships().size()); - element.addLore(variant.active() + .orElse("Object missing"))); + element.addLore(gray("Themes: " + themes(variant.themes()))); + element.addLore(gray("Pool entries: " + variant.memberships().size())); + element.addLore(yellow(variant.active() ? "Loaded; right-click for details" - : "Left-click to load"); + : "Left-click to load")); if (!variant.active()) { - element.addLore("Right-click for details or deletion"); + element.addLore(yellow("Right-click for details or deletion")); } element.onLeftClick(clicked -> switchVariant( window.getViewer(), @@ -425,8 +431,8 @@ public final class JigsawStudioMenuController { JigsawStudioMenuState.Workcell workcell, int page ) { - JigsawStudioMenuElement create = element("create", JigsawStudioMenuIcon.NETHER_STAR, "New Blank Variant"); - create.addLore("Create an empty owned variant with this cell's current size."); + JigsawStudioMenuElement create = element("create", JigsawStudioMenuIcon.NETHER_STAR, green("New Blank Variant")); + create.addLore(gray("Create an empty owned variant with this cell's current size.")); create.onLeftClick(clicked -> createVariant( window.getViewer(), state.requestId(), workcell.stableId(), false)); window.setElement(-4, 5, create); @@ -437,43 +443,41 @@ public final class JigsawStudioMenuController { "duplicate", duplicateAvailable ? JigsawStudioMenuIcon.PAPER : JigsawStudioMenuIcon.GRAY_DYE, duplicateAvailable - ? "Duplicate This Cell's Variant" - : active == null - ? "Duplicate This Cell's Variant" - : "Duplicate This Cell's Variant"); - duplicate.addLore(duplicateAvailable + ? aqua("Duplicate This Cell's Variant") + : gray("Duplicate This Cell's Variant")); + duplicate.addLore(gray(duplicateAvailable ? "Clone the loaded variant into an owned variant." : active == null ? "Load a variant before duplicating it." - : "Adopt the read-only graph before duplicating it."); + : "Adopt the read-only graph before duplicating it.")); if (duplicateAvailable) { duplicate.onLeftClick(clicked -> createVariant( window.getViewer(), state.requestId(), workcell.stableId(), true)); } window.setElement(-3, 5, duplicate); - JigsawStudioMenuElement settings = element("settings", JigsawStudioMenuIcon.CRAFTING_TABLE, "Workcell Settings"); - settings.addLore("Enabled: " + yesNo(workcell.enabled())); - settings.addLore("Capacity: " + dimensions(workcell.capacity())); + JigsawStudioMenuElement settings = element("settings", JigsawStudioMenuIcon.CRAFTING_TABLE, gold("Workcell Settings")); + settings.addLore(gray("Enabled: " + yesNo(workcell.enabled()))); + settings.addLore(gray("Capacity: " + dimensions(workcell.capacity()))); settings.onLeftClick(clicked -> openWorkcellSettings( window.getViewer(), state.requestId(), workcell.stableId())); window.setElement(-2, 5, settings); int pageCount = pageCount(workcell.variants().size(), VARIANTS_PER_PAGE); if (page > 0) { - JigsawStudioMenuElement previous = element("previous", JigsawStudioMenuIcon.ARROW, "Previous Page"); + JigsawStudioMenuElement previous = element("previous", JigsawStudioMenuIcon.ARROW, yellow("Previous Page")); previous.onLeftClick(clicked -> refreshMain( window.getViewer(), state.requestId(), workcell.stableId(), page - 1)); window.setElement(-1, 5, previous); } - JigsawStudioMenuElement pageIndicator = element("page", JigsawStudioMenuIcon.BOOK, "Page " - + (page + 1) + "/" + pageCount); - pageIndicator.addLore("" + workcell.variants().size() + " variants"); + JigsawStudioMenuElement pageIndicator = element("page", JigsawStudioMenuIcon.BOOK, white("Page " + + (page + 1) + "/" + pageCount)); + pageIndicator.addLore(gray("" + workcell.variants().size() + " variants")); window.setElement(0, 5, pageIndicator); if (page + 1 < pageCount) { - JigsawStudioMenuElement next = element("next", JigsawStudioMenuIcon.ARROW, "Next Page"); + JigsawStudioMenuElement next = element("next", JigsawStudioMenuIcon.ARROW, yellow("Next Page")); next.onLeftClick(clicked -> refreshMain( window.getViewer(), state.requestId(), workcell.stableId(), page + 1)); window.setElement(1, 5, next); @@ -481,13 +485,13 @@ public final class JigsawStudioMenuController { window.setElement(2, 5, evaluationElement(state.evaluation())); - JigsawStudioMenuElement preview = element("preview", JigsawStudioMenuIcon.ENDER_EYE, "Go to Preview"); - preview.addLore("Open the deterministic assembly preview."); + JigsawStudioMenuElement preview = element("preview", JigsawStudioMenuIcon.ENDER_EYE, lightPurple("Go to Preview")); + preview.addLore(gray("Open the deterministic assembly preview.")); preview.onLeftClick(clicked -> goToPreview(window.getViewer(), state.requestId())); window.setElement(3, 5, preview); - JigsawStudioMenuElement toolbox = element("toolbox", JigsawStudioMenuIcon.STICK, "Toolbox"); - toolbox.addLore("Take named sticks bound to this Studio session."); + JigsawStudioMenuElement toolbox = element("toolbox", JigsawStudioMenuIcon.STICK, aqua("Toolbox")); + toolbox.addLore(gray("Take named sticks bound to this Studio session.")); toolbox.onLeftClick(clicked -> openToolbox( window.getViewer(), state.requestId(), workcell.stableId(), 0)); window.setElement(4, 5, toolbox); @@ -508,7 +512,7 @@ public final class JigsawStudioMenuController { window.batch(() -> { window.clearElements(); - JigsawStudioMenuElement back = element("settings-back", JigsawStudioMenuIcon.ARROW, "Back to Variants"); + JigsawStudioMenuElement back = element("settings-back", JigsawStudioMenuIcon.ARROW, yellow("Back to Variants")); back.onLeftClick(clicked -> leaveWorkcellSettings( window.getViewer(), state.requestId(), renderedWorkcell.stableId())); window.setElement(-4, 0, back); @@ -516,23 +520,23 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement identity = element( "settings-identity", renderedWorkcell.enabled() ? JigsawStudioMenuIcon.LIME_WOOL : JigsawStudioMenuIcon.GRAY_WOOL, - safe(renderedWorkcell.displayName())); - identity.addLore(safe(renderedWorkcell.stableId())); + aqua(safe(renderedWorkcell.displayName()))); + identity.addLore(darkGray(safe(renderedWorkcell.stableId()))); identity.addLore(renderedWorkcell.enabled() - ? "Enabled" - : "Disabled for assembly and export"); + ? green("Enabled") + : red("Disabled for assembly and export")); if (!renderedWorkcell.canonicalName().equals(renderedWorkcell.displayName())) { - identity.addLore("Solver role: " + safe(renderedWorkcell.canonicalName())); + identity.addLore(gray("Solver role: " + safe(renderedWorkcell.canonicalName()))); } - identity.addLore("Capacity: " + dimensions(renderedWorkcell.capacity())); + identity.addLore(gray("Capacity: " + dimensions(renderedWorkcell.capacity()))); if (pendingResize != null) { identity.addLore(pendingResize.applying() - ? "Applying one live relayout" - : "Pending; apply when all dimensions are ready"); + ? yellow("Applying one live relayout") + : gold("Pending; apply when all dimensions are ready")); } - identity.addLore("Left-click for a rename stick"); - identity.addLore("Rename that stick in an anvil, then right-click it."); - identity.addLore("Sneak-right-click the stick to reset this label."); + identity.addLore(yellow("Left-click for a rename stick")); + identity.addLore(gray("Rename that stick in an anvil, then right-click it.")); + identity.addLore(gray("Sneak-right-click the stick to reset this label.")); identity.onLeftClick(clicked -> actions.giveTool( window.getViewer(), JigsawStudioToolPayload.workcell( @@ -547,11 +551,11 @@ public final class JigsawStudioMenuController { "settings-enabled", renderedWorkcell.enabled() ? JigsawStudioMenuIcon.LEVER : JigsawStudioMenuIcon.REDSTONE_TORCH, renderedWorkcell.enabled() - ? "Workcell Enabled" - : "Workcell Disabled"); - enabled.addLore("Disabled workcells remain editable and keep their size."); - enabled.addLore("Left-click to " - + (renderedWorkcell.enabled() ? "disable" : "enable")); + ? green("Workcell Enabled") + : red("Workcell Disabled")); + enabled.addLore(gray("Disabled workcells remain editable and keep their size.")); + enabled.addLore(yellow("Left-click to " + + (renderedWorkcell.enabled() ? "disable" : "enable"))); enabled.onLeftClick(clicked -> setWorkcellEnabled( window.getViewer(), state.requestId(), @@ -562,9 +566,9 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement spatial = element( "spatial-bounds", JigsawStudioMenuIcon.SCAFFOLDING, - "Spatial Workcell Bounds"); - spatial.addLore("Spatial project bounds are shared by the project."); - spatial.addLore("Changing them regenerates the Studio layout."); + aqua("Spatial Workcell Bounds")); + spatial.addLore(gray("Spatial project bounds are shared by the project.")); + spatial.addLore(gray("Changing them regenerates the Studio layout.")); window.setElement(0, 1, spatial); } @@ -572,11 +576,11 @@ public final class JigsawStudioMenuController { "settings-connectors", renderedWorkcell.connectorsVisible() ? JigsawStudioMenuIcon.JIGSAW : JigsawStudioMenuIcon.STRUCTURE_VOID, renderedWorkcell.connectorsVisible() - ? "Connector Blocks Visible" - : "Connector Blocks Hidden"); - connectors.addLore("Hidden connectors retain their metadata and final block state."); - connectors.addLore("Left-click to " - + (renderedWorkcell.connectorsVisible() ? "hide" : "show") + " connector blocks"); + ? green("Connector Blocks Visible") + : yellow("Connector Blocks Hidden")); + connectors.addLore(gray("Hidden connectors retain their metadata and final block state.")); + connectors.addLore(yellow("Left-click to " + + (renderedWorkcell.connectorsVisible() ? "hide" : "show") + " connector blocks")); connectors.onLeftClick(clicked -> toggleConnectorBlocks( window.getViewer(), state.requestId(), @@ -587,9 +591,9 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement resetConnectors = element( "settings-reset-connectors", JigsawStudioMenuIcon.RECOVERY_COMPASS, - "Reset Connector Blocks"); - resetConnectors.addLore("Restore every connector in this workcell from disk."); - resetConnectors.addLore("Other edited blocks are left unchanged."); + aqua("Reset Connector Blocks")); + resetConnectors.addLore(gray("Restore every connector in this workcell from disk.")); + resetConnectors.addLore(gray("Other edited blocks are left unchanged.")); resetConnectors.onLeftClick(clicked -> resetConnectorBlocks( window.getViewer(), state.requestId(), @@ -620,10 +624,10 @@ public final class JigsawStudioMenuController { "settings-apply-capacity", pendingResize.applying() ? JigsawStudioMenuIcon.CLOCK : JigsawStudioMenuIcon.EMERALD_BLOCK, pendingResize.applying() - ? "Applying Cell Size" - : "Apply Cell Size"); - apply.addLore(dimensions(pendingResize.dimensions())); - apply.addLore("Regenerates the layout once after all size edits."); + ? yellow("Applying Cell Size") + : green("Apply Cell Size")); + apply.addLore(white(dimensions(pendingResize.dimensions()))); + apply.addLore(gray("Regenerates the layout once after all size edits.")); if (!pendingResize.applying()) { apply.onLeftClick(clicked -> applyWorkcellResize( window.getViewer(), state.requestId(), renderedWorkcell.stableId())); @@ -634,14 +638,14 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement discard = element( "settings-discard-capacity", JigsawStudioMenuIcon.BARRIER, - "Discard Size Changes"); + red("Discard Size Changes")); discard.onLeftClick(clicked -> discardWorkcellResize( window.getViewer(), state.requestId(), renderedWorkcell.stableId())); window.setElement(2, 3, discard); } } - JigsawStudioMenuElement footerBack = element("settings-footer-back", JigsawStudioMenuIcon.ARROW, "Back"); + JigsawStudioMenuElement footerBack = element("settings-footer-back", JigsawStudioMenuIcon.ARROW, yellow("Back")); footerBack.onLeftClick(clicked -> leaveWorkcellSettings( window.getViewer(), state.requestId(), renderedWorkcell.stableId())); window.setElement(-4, 5, footerBack); @@ -649,9 +653,9 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement undo = element( "settings-undo", JigsawStudioMenuIcon.CLOCK, - "Undo Last Autosave"); - undo.addLore("Restore the previous owned graph iteration."); - undo.addLore("Up to five autosave iterations are retained on disk."); + lightPurple("Undo Last Autosave")); + undo.addLore(gray("Restore the previous owned graph iteration.")); + undo.addLore(gray("Up to five autosave iterations are retained on disk.")); undo.onLeftClick(clicked -> undoAutosave( window.getViewer(), state.requestId())); @@ -661,9 +665,9 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement saveNow = element( "save-now", JigsawStudioMenuIcon.EMERALD, - "Flush Autosave Now"); - saveNow.addLore("Autosave is automatic."); - saveNow.addLore("Use this only to flush pending work or recover immediately."); + gold("Flush Autosave Now")); + saveNow.addLore(gray("Autosave is automatic.")); + saveNow.addLore(gray("Use this only to flush pending work or recover immediately.")); saveNow.onLeftClick(clicked -> flushNow( window.getViewer(), state.requestId(), renderedWorkcell.stableId())); window.setElement(2, 5, saveNow); @@ -672,11 +676,11 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement preview = element( "settings-preview", JigsawStudioMenuIcon.ENDER_EYE, - "Go to Preview"); + lightPurple("Go to Preview")); preview.onLeftClick(clicked -> goToPreview(window.getViewer(), state.requestId())); window.setElement(3, 5, preview); - JigsawStudioMenuElement toolbox = element("settings-toolbox", JigsawStudioMenuIcon.STICK, "Toolbox"); + JigsawStudioMenuElement toolbox = element("settings-toolbox", JigsawStudioMenuIcon.STICK, aqua("Toolbox")); toolbox.onLeftClick(clicked -> openToolbox( window.getViewer(), state.requestId(), renderedWorkcell.stableId(), 0)); window.setElement(4, 5, toolbox); @@ -693,7 +697,7 @@ public final class JigsawStudioMenuController { window.batch(() -> { window.clearElements(); - JigsawStudioMenuElement back = element("variant-size-back", JigsawStudioMenuIcon.ARROW, "Back to Details"); + JigsawStudioMenuElement back = element("variant-size-back", JigsawStudioMenuIcon.ARROW, yellow("Back to Details")); back.onLeftClick(clicked -> openDetails( window.getViewer(), state.requestId(), workcell.stableId(), variant.pieceKey(), 0)); window.setElement(-4, 0, back); @@ -701,11 +705,11 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement identity = element( "variant-size-identity", JigsawStudioMenuIcon.SCAFFOLDING, - safe(variant.displayName()) + " Size"); - identity.addLore(safe(variant.pieceKey())); - identity.addLore("Current: " + dimensions(current)); - identity.addLore("Workcell capacity: " + dimensions(workcell.capacity())); - identity.addLore("Only this variant object and its edge connectors change."); + aqua(safe(variant.displayName()) + " Size")); + identity.addLore(darkGray(safe(variant.pieceKey()))); + identity.addLore(white("Current: " + dimensions(current))); + identity.addLore(gray("Workcell capacity: " + dimensions(workcell.capacity()))); + identity.addLore(gray("Only this variant object and its edge connectors change.")); window.setElement(0, 0, identity); window.setElement(4, 0, evaluationElement(state.evaluation())); @@ -720,11 +724,11 @@ public final class JigsawStudioMenuController { "variant-size-capacity", variant.resizableToCapacity() ? JigsawStudioMenuIcon.NETHER_STAR : JigsawStudioMenuIcon.GRAY_DYE, variant.resizableToCapacity() - ? "Resize This Variant to Capacity" - : "Variant Already Matches Capacity"); - capacity.addLore(dimensions(workcell.capacity())); + ? green("Resize This Variant to Capacity") + : gray("Variant Already Matches Capacity")); + capacity.addLore(gray(dimensions(workcell.capacity()))); if (variant.resizableToCapacity()) { - capacity.addLore("Left-click to resize only this variant"); + capacity.addLore(yellow("Left-click to resize only this variant")); capacity.onLeftClick(clicked -> resizeVariant( window.getViewer(), state.requestId(), @@ -734,7 +738,7 @@ public final class JigsawStudioMenuController { } window.setElement(0, 3, capacity); - JigsawStudioMenuElement footerBack = element("variant-size-footer-back", JigsawStudioMenuIcon.ARROW, "Back"); + JigsawStudioMenuElement footerBack = element("variant-size-footer-back", JigsawStudioMenuIcon.ARROW, yellow("Back")); footerBack.onLeftClick(clicked -> openDetails( window.getViewer(), state.requestId(), workcell.stableId(), variant.pieceKey(), 0)); window.setElement(-4, 5, footerBack); @@ -753,12 +757,12 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement element = element( "variant-axis-" + axis.name().toLowerCase(Locale.ROOT), material, - axis.displayName() + ": " + axis.value(current)); - element.addLore("Left-click: +1"); - element.addLore("Right-click: -1"); - element.addLore("Shift-left: +8"); - element.addLore("Shift-right: -8"); - element.addLore("Maximum: " + axis.value(workcell.capacity())); + aqua(axis.displayName() + ": " + axis.value(current))); + element.addLore(green("Left-click: +1")); + element.addLore(yellow("Right-click: -1")); + element.addLore(green("Shift-left: +8")); + element.addLore(yellow("Shift-right: -8")); + element.addLore(gray("Maximum: " + axis.value(workcell.capacity()))); element.onLeftClick(clicked -> resizeVariantAxis( window.getViewer(), state.requestId(), workcell.stableId(), variant.pieceKey(), axis, 1)); element.onRightClick(clicked -> resizeVariantAxis( @@ -781,7 +785,7 @@ public final class JigsawStudioMenuController { window.batch(() -> { window.clearElements(); - JigsawStudioMenuElement back = element("structure-back", JigsawStudioMenuIcon.ARROW, "Back to Variants"); + JigsawStudioMenuElement back = element("structure-back", JigsawStudioMenuIcon.ARROW, yellow("Back to Variants")); back.onLeftClick(clicked -> refreshMain( window.getViewer(), state.requestId(), selectedWorkcellId, 0)); window.setElement(-4, 0, back); @@ -789,11 +793,11 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement identity = element( "structure-identity", JigsawStudioMenuIcon.JIGSAW, - "Structure Themes & Caps"); - identity.addLore(safe(state.structureKey())); - identity.addLore("Compatibility: " + compatibilityName(state.compatibilityTarget())); - identity.addLore("Theme sets select one coherent variant family per assembly."); - identity.addLore("Empty piece themes remain available to every family."); + lightPurple("Structure Themes & Caps")); + identity.addLore(darkGray(safe(state.structureKey()))); + identity.addLore(gray("Compatibility: " + compatibilityName(state.compatibilityTarget()))); + identity.addLore(gray("Theme sets select one coherent variant family per assembly.")); + identity.addLore(gray("Empty piece themes remain available to every family.")); window.setElement(0, 0, identity); window.setElement(4, 0, evaluationElement(state.evaluation())); @@ -803,17 +807,17 @@ public final class JigsawStudioMenuController { ? state.requireCaps() ? JigsawStudioMenuIcon.IRON_BARS : JigsawStudioMenuIcon.TRIPWIRE_HOOK : JigsawStudioMenuIcon.BARRIER, !state.irisExtended() - ? "Mandatory Caps Require Iris Compatibility" + ? gray("Mandatory Caps Require Iris Compatibility") : state.requireCaps() - ? "Mandatory Caps Enabled" - : "Mandatory Caps Disabled"); - requireCaps.addLore(!state.irisExtended() + ? green("Mandatory Caps Enabled") + : yellow("Mandatory Caps Disabled")); + requireCaps.addLore(gray(!state.irisExtended() ? "Vanilla-portable export rejects Iris mandatory-cap metadata." : state.requireCaps() ? "Every open connector must close with a terminal piece." - : "Assembly may leave an open connector when no cap can fit."); + : "Assembly may leave an open connector when no cap can fit.")); if (state.irisExtended()) { - requireCaps.addLore("Left-click to toggle"); + requireCaps.addLore(yellow("Left-click to toggle")); requireCaps.onLeftClick(clicked -> setRequireCaps( window.getViewer(), state.requestId(), !state.requireCaps())); } @@ -825,17 +829,17 @@ public final class JigsawStudioMenuController { "new-theme-set", themeEditingAvailable ? JigsawStudioMenuIcon.NETHER_STAR : JigsawStudioMenuIcon.BARRIER, themeEditingAvailable - ? "Duplicate All Enabled Cells as Family: " + safe(nextThemeKey) - : "Theme Sets Require Iris Compatibility"); + ? green("Duplicate All Enabled Cells as Family: " + safe(nextThemeKey)) + : gray("Theme Sets Require Iris Compatibility")); if (themeEditingAvailable) { - createTheme.addLore("Creates one new owned variant for every enabled workcell."); - createTheme.addLore("All created variants join " + safe(nextThemeKey) + "."); - createTheme.addLore("One family is selected for the complete assembly."); - createTheme.addLore("Left-click to create the complete set"); + createTheme.addLore(gray("Creates one new owned variant for every enabled workcell.")); + createTheme.addLore(gray("All created variants join " + safe(nextThemeKey) + ".")); + createTheme.addLore(gray("One family is selected for the complete assembly.")); + createTheme.addLore(yellow("Left-click to create the complete set")); createTheme.onLeftClick(clicked -> duplicateActiveFamily( window.getViewer(), state.requestId(), nextThemeKey)); } else { - createTheme.addLore("Vanilla jigsaw resources cannot encode Iris theme metadata."); + createTheme.addLore(gray("Vanilla jigsaw resources cannot encode Iris theme metadata.")); } window.setElement(0, 1, createTheme); @@ -845,19 +849,19 @@ public final class JigsawStudioMenuController { "delete-project", deleteConfirmed ? JigsawStudioMenuIcon.REDSTONE : JigsawStudioMenuIcon.LAVA_BUCKET, deleteConfirmed - ? "Confirm Delete Jigsaw" - : "Delete Jigsaw") + ? red("Confirm Delete Jigsaw") + : red("Delete Jigsaw")) .setEnchanted(deleteConfirmed); - deleteProject.addLore(deleteConfirmed + deleteProject.addLore(red(deleteConfirmed ? "Click again to delete this entire managed project." - : "Click twice within 10 seconds to confirm."); + : "Click twice within 10 seconds to confirm.")); deleteProject.onLeftClick(clicked -> confirmOrDeleteProject( window.getViewer(), state.requestId(), selectedWorkcellId, page)); window.setElement(3, 1, deleteProject); addThemeSets(window, state, page); - JigsawStudioMenuElement footerBack = element("structure-footer-back", JigsawStudioMenuIcon.ARROW, "Back"); + JigsawStudioMenuElement footerBack = element("structure-footer-back", JigsawStudioMenuIcon.ARROW, yellow("Back")); footerBack.onLeftClick(clicked -> refreshMain( window.getViewer(), state.requestId(), selectedWorkcellId, 0)); window.setElement(-4, 5, footerBack); @@ -867,7 +871,7 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement previous = element( "theme-previous", JigsawStudioMenuIcon.ARROW, - "Previous Page"); + yellow("Previous Page")); previous.onLeftClick(clicked -> refreshStructureSettings( window.getViewer(), state.requestId(), selectedWorkcellId, page - 1)); window.setElement(-1, 5, previous); @@ -875,11 +879,11 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement indicator = element( "theme-page", JigsawStudioMenuIcon.BOOK, - "Page " + (page + 1) + "/" + pageCount); - indicator.addLore("" + state.themeSets().size() + " theme sets"); + white("Page " + (page + 1) + "/" + pageCount)); + indicator.addLore(gray("" + state.themeSets().size() + " theme sets")); window.setElement(0, 5, indicator); if (page + 1 < pageCount) { - JigsawStudioMenuElement next = element("theme-next", JigsawStudioMenuIcon.ARROW, "Next Page"); + JigsawStudioMenuElement next = element("theme-next", JigsawStudioMenuIcon.ARROW, yellow("Next Page")); next.onLeftClick(clicked -> refreshStructureSettings( window.getViewer(), state.requestId(), selectedWorkcellId, page + 1)); window.setElement(1, 5, next); @@ -899,8 +903,8 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement empty = element( "no-theme-sets", JigsawStudioMenuIcon.GRAY_DYE, - "Implicit Unthemed Assembly"); - empty.addLore("Create variant-1 to begin coherent theme selection."); + gray("Implicit Unthemed Assembly")); + empty.addLore(gray("Create variant-1 to begin coherent theme selection.")); window.setElement(0, 3, empty); return; } @@ -911,15 +915,17 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement element = element( "theme-set-" + index, state.irisExtended() ? JigsawStudioMenuIcon.PURPLE_DYE : JigsawStudioMenuIcon.GRAY_DYE, - safe(themeSet.key())); - element.addLore("Selection weight: " + themeSet.weight()); - element.addLore("Whole-assembly chance: " - + themeSelectionPercent(state.themeSets(), themeSet)); + ToolText.colored( + state.irisExtended() ? TextColor.LIGHT_PURPLE : TextColor.GRAY, + safe(themeSet.key()))); + element.addLore(white("Selection weight: " + themeSet.weight())); + element.addLore(white("Whole-assembly chance: " + + themeSelectionPercent(state.themeSets(), themeSet))); if (state.irisExtended()) { - element.addLore("Left-click: weight +1"); - element.addLore("Right-click: weight -1"); - element.addLore("Shift-left: weight +8"); - element.addLore("Shift-right: weight -8"); + element.addLore(green("Left-click: weight +1")); + element.addLore(yellow("Right-click: weight -1")); + element.addLore(green("Shift-left: weight +8")); + element.addLore(yellow("Shift-right: weight -8")); element.onLeftClick(clicked -> adjustThemeSetWeight( window.getViewer(), state.requestId(), themeSet, 1)); element.onRightClick(clicked -> adjustThemeSetWeight( @@ -929,7 +935,7 @@ public final class JigsawStudioMenuController { element.onShiftRightClick(clicked -> adjustThemeSetWeight( window.getViewer(), state.requestId(), themeSet, -8)); } else { - element.addLore("Theme metadata is unavailable for vanilla-portable graphs."); + element.addLore(gray("Theme metadata is unavailable for vanilla-portable graphs.")); } window.setElement(position, row, element); } @@ -945,12 +951,12 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement element = element( "axis-" + axis.name().toLowerCase(Locale.ROOT), material, - axis.displayName() + " Capacity: " + axis.value(workcell.capacity())); - element.addLore("Left-click: +1"); - element.addLore("Right-click: -1"); - element.addLore("Shift-left: +8"); - element.addLore("Shift-right: -8"); - element.addLore("Changes stay in this menu until Apply Cell Size."); + aqua(axis.displayName() + " Capacity: " + axis.value(workcell.capacity()))); + element.addLore(green("Left-click: +1")); + element.addLore(yellow("Right-click: -1")); + element.addLore(green("Shift-left: +8")); + element.addLore(yellow("Shift-right: -8")); + element.addLore(gray("Changes stay in this menu until Apply Cell Size.")); element.onLeftClick(clicked -> resizeWorkcell( window.getViewer(), state.requestId(), workcell.stableId(), axis, 1)); element.onRightClick(clicked -> resizeWorkcell( @@ -986,33 +992,33 @@ public final class JigsawStudioMenuController { JigsawStudioMenuState.Variant variant, int page ) { - JigsawStudioMenuElement back = element("back", JigsawStudioMenuIcon.ARROW, "Back to Variants"); + JigsawStudioMenuElement back = element("back", JigsawStudioMenuIcon.ARROW, yellow("Back to Variants")); back.onLeftClick(clicked -> refreshMain( window.getViewer(), state.requestId(), workcell.stableId(), 0)); window.setElement(-4, 0, back); - JigsawStudioMenuElement identity = element("identity", JigsawStudioMenuIcon.NAME_TAG, safe(variant.displayName())); - identity.addLore(safe(variant.pieceKey())); + JigsawStudioMenuElement identity = element("identity", JigsawStudioMenuIcon.NAME_TAG, aqua(safe(variant.displayName()))); + identity.addLore(darkGray(safe(variant.pieceKey()))); identity.addLore(variant.owned() - ? "Owned variant" - : "Read-only variant"); + ? green("Owned variant") + : gray("Read-only variant")); identity.addLore(variant.active() - ? "Loaded in this workcell" - : "Not currently loaded"); - identity.addLore("Size: " + variant.dimensions() + ? green("Loaded in this workcell") + : gray("Not currently loaded")); + identity.addLore(gray("Size: " + variant.dimensions() .map(JigsawStudioMenuController::dimensions) - .orElse("Object missing")); - identity.addLore("Themes: " + themes(variant.themes())); - identity.addLore("Depth: " + variant.rules().minimumDepth() - + "-" + variant.rules().maximumDepth()); - identity.addLore("Placements: " + variant.rules().minimumPlacements() - + "-" + maximumPlacements(variant.rules().maximumPlacements())); - identity.addLore("Terminal: " + yesNo(variant.rules().terminal())); - identity.addLore("Pool entries: " + variant.memberships().size()); + .orElse("Object missing"))); + identity.addLore(gray("Themes: " + themes(variant.themes()))); + identity.addLore(gray("Depth: " + variant.rules().minimumDepth() + + "-" + variant.rules().maximumDepth())); + identity.addLore(gray("Placements: " + variant.rules().minimumPlacements() + + "-" + maximumPlacements(variant.rules().maximumPlacements()))); + identity.addLore(gray("Terminal: " + yesNo(variant.rules().terminal()))); + identity.addLore(gray("Pool entries: " + variant.memberships().size())); if (variant.owned()) { - identity.addLore("Left-click for a rename stick"); - identity.addLore("Rename that stick in an anvil, then right-click it."); - identity.addLore("Sneak-right-click the stick to reset this label."); + identity.addLore(yellow("Left-click for a rename stick")); + identity.addLore(gray("Rename that stick in an anvil, then right-click it.")); + identity.addLore(gray("Sneak-right-click the stick to reset this label.")); identity.onLeftClick(clicked -> actions.giveTool( window.getViewer(), JigsawStudioToolPayload.variant( @@ -1029,15 +1035,15 @@ public final class JigsawStudioMenuController { "variant-settings", irisRuleEditing ? JigsawStudioMenuIcon.COMPARATOR : JigsawStudioMenuIcon.GRAY_DYE, irisRuleEditing - ? "Themes & Piece Rules" - : "Themes & Rules Unavailable"); - settings.addLore(irisRuleEditing + ? gold("Themes & Piece Rules") + : gray("Themes & Rules Unavailable")); + settings.addLore(gray(irisRuleEditing ? "Edit this loaded variant's theme membership and placement rules." : state.irisExtended() ? "Load an owned variant before editing its rules." - : "Vanilla-portable pieces cannot encode Iris theme or rule metadata."); + : "Vanilla-portable pieces cannot encode Iris theme or rule metadata.")); if (irisRuleEditing) { - settings.addLore("Left-click to edit"); + settings.addLore(yellow("Left-click to edit")); settings.onLeftClick(clicked -> openVariantSettings( window.getViewer(), state.requestId(), workcell.stableId(), variant.pieceKey(), 0)); } @@ -1048,17 +1054,17 @@ public final class JigsawStudioMenuController { "rotation", rotationEditable ? JigsawStudioMenuIcon.REPEATER : JigsawStudioMenuIcon.BARRIER, rotationEditable - ? "Toggle Rotation" - : "Rotation is Read-only"); - rotation.addLore("Currently: " + (variant.rotatable() ? "Enabled" : "Disabled")); + ? lightPurple("Toggle Rotation") + : gray("Rotation is Read-only")); + rotation.addLore(gray("Currently: " + (variant.rotatable() ? "Enabled" : "Disabled"))); if (rotationEditable) { - rotation.addLore("Left-click to toggle"); + rotation.addLore(yellow("Left-click to toggle")); rotation.onLeftClick(clicked -> toggleRotation( window.getViewer(), state.requestId(), workcell.stableId())); } else if (!variant.active()) { - rotation.addLore("Load this variant before editing rotation."); + rotation.addLore(gray("Load this variant before editing rotation.")); } else if (variant.owned() && variant.rotatable()) { - rotation.addLore("Vanilla-portable variants must remain rotatable."); + rotation.addLore(gray("Vanilla-portable variants must remain rotatable.")); } window.setElement(3, 0, rotation); @@ -1067,18 +1073,18 @@ public final class JigsawStudioMenuController { "variant-size", sizeEditable ? JigsawStudioMenuIcon.SCAFFOLDING : JigsawStudioMenuIcon.BARRIER, sizeEditable - ? "Edit This Variant's Size" - : "Variant Size is Read-only"); - size.addLore("Current: " + variant.dimensions() + ? green("Edit This Variant's Size") + : gray("Variant Size is Read-only")); + size.addLore(gray("Current: " + variant.dimensions() .map(JigsawStudioMenuController::dimensions) - .orElse("Object missing")); - size.addLore("Workcell capacity: " + dimensions(workcell.capacity())); + .orElse("Object missing"))); + size.addLore(gray("Workcell capacity: " + dimensions(workcell.capacity()))); if (sizeEditable) { - size.addLore("Left-click for width, height, and depth controls"); + size.addLore(yellow("Left-click for width, height, and depth controls")); size.onLeftClick(clicked -> openVariantSizeSettings( window.getViewer(), state.requestId(), workcell.stableId(), variant.pieceKey())); if (variant.resizableToCapacity()) { - size.addLore("Shift-left: resize this variant to capacity"); + size.addLore(yellow("Shift-left: resize this variant to capacity")); size.onShiftLeftClick(clicked -> resizeVariant( window.getViewer(), state.requestId(), @@ -1100,17 +1106,17 @@ public final class JigsawStudioMenuController { "delete-variant", deletionAvailable ? confirmed ? JigsawStudioMenuIcon.REDSTONE : JigsawStudioMenuIcon.LAVA_BUCKET : JigsawStudioMenuIcon.BARRIER, deletionAvailable - ? confirmed ? "Confirm Delete Variant" : "Delete Variant" + ? confirmed ? red("Confirm Delete Variant") : red("Delete Variant") : variant.active() - ? "Loaded Variant Cannot Be Deleted" + ? gray("Loaded Variant Cannot Be Deleted") : lastVariant - ? "Last Variant Cannot Be Deleted" - : "Deletion is Read-only") + ? gray("Last Variant Cannot Be Deleted") + : gray("Deletion is Read-only")) .setEnchanted(confirmed); if (deletionAvailable) { - delete.addLore(confirmed + delete.addLore(red(confirmed ? "Click again to permanently delete this owned variant." - : "Click twice within 10 seconds to confirm."); + : "Click twice within 10 seconds to confirm.")); delete.onLeftClick(clicked -> confirmOrDeleteVariant( window.getViewer(), state.requestId(), @@ -1118,9 +1124,9 @@ public final class JigsawStudioMenuController { variant.pieceKey(), page)); } else if (variant.active()) { - delete.addLore("Load another variant in this workcell first."); + delete.addLore(gray("Load another variant in this workcell first.")); } else if (lastVariant) { - delete.addLore("Create another variant before deleting this one."); + delete.addLore(gray("Create another variant before deleting this one.")); } window.setElement(4, 0, delete); } @@ -1135,8 +1141,8 @@ public final class JigsawStudioMenuController { List memberships = page( variant.memberships(), page, MEMBERSHIPS_PER_PAGE); if (memberships.isEmpty()) { - JigsawStudioMenuElement empty = element("no-memberships", JigsawStudioMenuIcon.BARRIER, "No Pool Entries"); - empty.addLore("This variant is not linked from an owned pool."); + JigsawStudioMenuElement empty = element("no-memberships", JigsawStudioMenuIcon.BARRIER, red("No Pool Entries")); + empty.addLore(gray("This variant is not linked from an owned pool.")); window.setElement(0, 2, empty); return; } @@ -1154,28 +1160,32 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement element = element( "membership-" + index, confirmed ? JigsawStudioMenuIcon.REDSTONE : JigsawStudioMenuIcon.GOLD_NUGGET, - safe(displayKey(membership.poolKey())) - + " [" + membership.entryIndex() + "]") + ToolText.colored( + confirmed ? TextColor.RED : TextColor.GOLD, + safe(displayKey(membership.poolKey())) + + " [" + membership.entryIndex() + "]")) .setEnchanted(confirmed); - element.addLore(safe(membership.poolKey())); - element.addLore("Exact entry: " + membership.entryIndex()); - element.addLore("Weight: " + membership.weight()); - element.addLore("Chance: " + chance(membership.chance()) - + (state.irisExtended() ? "" : " (Iris only)")); + element.addLore(darkGray(safe(membership.poolKey()))); + element.addLore(gray("Exact entry: " + membership.entryIndex())); + element.addLore(white("Weight: " + membership.weight())); + element.addLore(ToolText.colored( + state.irisExtended() ? TextColor.WHITE : TextColor.GRAY, + "Chance: " + chance(membership.chance()) + + (state.irisExtended() ? "" : " (Iris only)"))); if (variant.active() && variant.owned()) { - element.addLore("Left-click: weight +1"); - element.addLore("Right-click: weight -1"); + element.addLore(green("Left-click: weight +1")); + element.addLore(yellow("Right-click: weight -1")); if (state.irisExtended()) { - element.addLore("Shift-left: chance +" - + CHANCE_STEP_PERCENTAGE_POINTS + "%"); - element.addLore("Shift-right: chance -" - + CHANCE_STEP_PERCENTAGE_POINTS + "%"); + element.addLore(green("Shift-left: chance +" + + CHANCE_STEP_PERCENTAGE_POINTS + "%")); + element.addLore(yellow("Shift-right: chance -" + + CHANCE_STEP_PERCENTAGE_POINTS + "%")); } else { - element.addLore("Vanilla-portable pool entries always have 100% chance."); + element.addLore(gray("Vanilla-portable pool entries always have 100% chance.")); } - element.addLore(confirmed + element.addLore(red(confirmed ? "Middle-click again to unlink" - : "Middle-click twice to unlink"); + : "Middle-click twice to unlink")); element.onLeftClick(clicked -> adjustMembershipWeight( window.getViewer(), state.requestId(), workcell.stableId(), membership, 1)); element.onRightClick(clicked -> adjustMembershipWeight( @@ -1197,9 +1207,9 @@ public final class JigsawStudioMenuController { element.onMiddleClick(clicked -> confirmOrUnlink( window.getViewer(), state.requestId(), workcell.stableId(), membership, page)); } else { - element.addLore(variant.active() + element.addLore(gray(variant.active() ? "Read-only pool entry" - : "Load this variant to edit its pool entry"); + : "Load this variant to edit its pool entry")); } window.setElement(position, row, element); } @@ -1212,14 +1222,14 @@ public final class JigsawStudioMenuController { JigsawStudioMenuState.Variant variant, int page ) { - JigsawStudioMenuElement back = element("footer-back", JigsawStudioMenuIcon.ARROW, "Back"); + JigsawStudioMenuElement back = element("footer-back", JigsawStudioMenuIcon.ARROW, yellow("Back")); back.onLeftClick(clicked -> refreshMain( window.getViewer(), state.requestId(), workcell.stableId(), 0)); window.setElement(-4, 5, back); int pageCount = pageCount(variant.memberships().size(), MEMBERSHIPS_PER_PAGE); if (page > 0) { - JigsawStudioMenuElement previous = element("membership-previous", JigsawStudioMenuIcon.ARROW, "Previous Page"); + JigsawStudioMenuElement previous = element("membership-previous", JigsawStudioMenuIcon.ARROW, yellow("Previous Page")); previous.onLeftClick(clicked -> refreshDetails( window.getViewer(), state.requestId(), @@ -1228,12 +1238,12 @@ public final class JigsawStudioMenuController { page - 1)); window.setElement(-1, 5, previous); } - JigsawStudioMenuElement indicator = element("membership-page", JigsawStudioMenuIcon.BOOK, "Page " - + (page + 1) + "/" + pageCount); - indicator.addLore("" + variant.memberships().size() + " exact pool entries"); + JigsawStudioMenuElement indicator = element("membership-page", JigsawStudioMenuIcon.BOOK, white("Page " + + (page + 1) + "/" + pageCount)); + indicator.addLore(gray("" + variant.memberships().size() + " exact pool entries")); window.setElement(0, 5, indicator); if (page + 1 < pageCount) { - JigsawStudioMenuElement next = element("membership-next", JigsawStudioMenuIcon.ARROW, "Next Page"); + JigsawStudioMenuElement next = element("membership-next", JigsawStudioMenuIcon.ARROW, yellow("Next Page")); next.onLeftClick(clicked -> refreshDetails( window.getViewer(), state.requestId(), @@ -1244,7 +1254,7 @@ public final class JigsawStudioMenuController { } window.setElement(2, 5, evaluationElement(state.evaluation())); - JigsawStudioMenuElement toolbox = element("details-toolbox", JigsawStudioMenuIcon.STICK, "Toolbox"); + JigsawStudioMenuElement toolbox = element("details-toolbox", JigsawStudioMenuIcon.STICK, aqua("Toolbox")); toolbox.onLeftClick(clicked -> openToolbox( window.getViewer(), state.requestId(), workcell.stableId(), 0)); window.setElement(4, 5, toolbox); @@ -1261,7 +1271,7 @@ public final class JigsawStudioMenuController { window.batch(() -> { window.clearElements(); - JigsawStudioMenuElement back = element("variant-settings-back", JigsawStudioMenuIcon.ARROW, "Back to Details"); + JigsawStudioMenuElement back = element("variant-settings-back", JigsawStudioMenuIcon.ARROW, yellow("Back to Details")); back.onLeftClick(clicked -> openDetails( window.getViewer(), state.requestId(), workcell.stableId(), variant.pieceKey(), 0)); window.setElement(-4, 0, back); @@ -1269,10 +1279,10 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement identity = element( "variant-settings-identity", JigsawStudioMenuIcon.COMPARATOR, - safe(variant.displayName()) + " Rules"); - identity.addLore(safe(variant.pieceKey())); - identity.addLore("Theme memberships: " + themes(variant.themes())); - identity.addLore("Use Duplicate All Enabled Cells as Family for coherent sets."); + gold(safe(variant.displayName()) + " Rules")); + identity.addLore(darkGray(safe(variant.pieceKey()))); + identity.addLore(gray("Theme memberships: " + themes(variant.themes()))); + identity.addLore(gray("Use Duplicate All Enabled Cells as Family for coherent sets.")); window.setElement(0, 0, identity); window.setElement(4, 0, evaluationElement(state.evaluation())); @@ -1281,11 +1291,11 @@ public final class JigsawStudioMenuController { "variant-settings-unavailable", JigsawStudioMenuIcon.BARRIER, state.irisExtended() - ? "Load an Owned Variant First" - : "Iris Metadata Unavailable"); - unavailable.addLore(state.irisExtended() + ? red("Load an Owned Variant First") + : gray("Iris Metadata Unavailable")); + unavailable.addLore(gray(state.irisExtended() ? "Rules and themes can only change for the loaded owned variant." - : "Vanilla-portable pieces use vanilla placement behavior."); + : "Vanilla-portable pieces use vanilla placement behavior.")); window.setElement(0, 2, unavailable); } else { window.setElement(-4, 1, ruleElement( @@ -1301,10 +1311,10 @@ public final class JigsawStudioMenuController { "rule-terminal", variant.rules().terminal() ? JigsawStudioMenuIcon.REDSTONE_TORCH : JigsawStudioMenuIcon.LEVER, variant.rules().terminal() - ? "Terminal Piece: Yes" - : "Terminal Piece: No"); - terminal.addLore("Terminal pieces consume a connector without expanding."); - terminal.addLore("Left-click to toggle"); + ? green("Terminal Piece: Yes") + : yellow("Terminal Piece: No")); + terminal.addLore(gray("Terminal pieces consume a connector without expanding.")); + terminal.addLore(yellow("Left-click to toggle")); terminal.onLeftClick(clicked -> updateVariantRules( window.getViewer(), state.requestId(), @@ -1316,7 +1326,7 @@ public final class JigsawStudioMenuController { addVariantThemeMemberships(window, state, workcell, variant, page); } - JigsawStudioMenuElement footerBack = element("variant-rules-footer-back", JigsawStudioMenuIcon.ARROW, "Back"); + JigsawStudioMenuElement footerBack = element("variant-rules-footer-back", JigsawStudioMenuIcon.ARROW, yellow("Back")); footerBack.onLeftClick(clicked -> openDetails( window.getViewer(), state.requestId(), workcell.stableId(), variant.pieceKey(), 0)); window.setElement(-4, 5, footerBack); @@ -1326,7 +1336,7 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement previous = element( "variant-theme-previous", JigsawStudioMenuIcon.ARROW, - "Previous Page"); + yellow("Previous Page")); previous.onLeftClick(clicked -> refreshVariantSettings( window.getViewer(), state.requestId(), @@ -1338,14 +1348,14 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement indicator = element( "variant-theme-page", JigsawStudioMenuIcon.BOOK, - "Theme Page " + (page + 1) + "/" + pageCount); - indicator.addLore("" + state.themeSets().size() + " declared themes"); + white("Theme Page " + (page + 1) + "/" + pageCount)); + indicator.addLore(gray("" + state.themeSets().size() + " declared themes")); window.setElement(0, 5, indicator); if (page + 1 < pageCount) { JigsawStudioMenuElement next = element( "variant-theme-next", JigsawStudioMenuIcon.ARROW, - "Next Page"); + yellow("Next Page")); next.onLeftClick(clicked -> refreshVariantSettings( window.getViewer(), state.requestId(), @@ -1369,24 +1379,24 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement element = element( "rule-" + field.name().toLowerCase(Locale.ROOT), field.material(), - field.displayName() + ": " + field.displayValue(value)); + aqua(field.displayName() + ": " + field.displayValue(value))); boolean unlimitedMaximum = field == RuleField.MAXIMUM_PLACEMENTS && value == 0; if (unlimitedMaximum) { - element.addLore("Increase is already unlimited."); + element.addLore(gray("Increase is already unlimited.")); } else { - element.addLore("Left-click: +1"); - element.addLore("Shift-left: +" + field.shiftStep()); + element.addLore(green("Left-click: +1")); + element.addLore(green("Shift-left: +" + field.shiftStep())); element.onLeftClick(clicked -> adjustVariantRule( window.getViewer(), state.requestId(), workcell, variant, field, 1)); element.onShiftLeftClick(clicked -> adjustVariantRule( window.getViewer(), state.requestId(), workcell, variant, field, field.shiftStep())); } - element.addLore(unlimitedMaximum + element.addLore(yellow(unlimitedMaximum ? "Right-click: set 512" - : "Right-click: -1"); - element.addLore(unlimitedMaximum + : "Right-click: -1")); + element.addLore(yellow(unlimitedMaximum ? "Shift-right: set 497" - : "Shift-right: -" + field.shiftStep()); + : "Shift-right: -" + field.shiftStep())); element.onRightClick(clicked -> adjustVariantRule( window.getViewer(), state.requestId(), workcell, variant, field, -1)); element.onShiftRightClick(clicked -> adjustVariantRule( @@ -1407,8 +1417,8 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement empty = element( "variant-no-themes", JigsawStudioMenuIcon.GRAY_DYE, - "Available to Every Theme"); - empty.addLore("Create a coherent theme set from Structure Rules first."); + gray("Available to Every Theme")); + empty.addLore(gray("Create a coherent theme set from Structure Rules first.")); window.setElement(0, 3, empty); return; } @@ -1420,13 +1430,13 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement element = element( "variant-theme-" + index, member ? JigsawStudioMenuIcon.LIME_DYE : JigsawStudioMenuIcon.GRAY_DYE, - safe(themeSet.key())) + ToolText.colored(member ? TextColor.GREEN : TextColor.GRAY, safe(themeSet.key()))) .setEnchanted(member); element.addLore(member - ? "This variant belongs to the theme." - : "This variant does not belong to the theme."); - element.addLore("Only variants in the selected family are eligible."); - element.addLore("Left-click to toggle membership"); + ? green("This variant belongs to the theme.") + : gray("This variant does not belong to the theme.")); + element.addLore(gray("Only variants in the selected family are eligible.")); + element.addLore(yellow("Left-click to toggle membership")); element.onLeftClick(clicked -> toggleVariantTheme( window.getViewer(), state.requestId(), workcell, variant, themeSet.key())); window.setElement(position, row, element); @@ -1445,14 +1455,14 @@ public final class JigsawStudioMenuController { window.batch(() -> { window.clearElements(); - JigsawStudioMenuElement back = element("toolbox-back", JigsawStudioMenuIcon.ARROW, "Back to Variants"); + JigsawStudioMenuElement back = element("toolbox-back", JigsawStudioMenuIcon.ARROW, yellow("Back to Variants")); back.onLeftClick(clicked -> refreshMain( window.getViewer(), state.requestId(), workcell.stableId(), 0)); window.setElement(-4, 0, back); - JigsawStudioMenuElement heading = element("toolbox-heading", JigsawStudioMenuIcon.CHEST, "Bound Tool Sticks"); - heading.addLore("Every stick is bound to request " + state.requestId()); - heading.addLore("Stale sticks stop working when this Studio closes."); + JigsawStudioMenuElement heading = element("toolbox-heading", JigsawStudioMenuIcon.CHEST, aqua("Bound Tool Sticks")); + heading.addLore(gray("Every stick is bound to request " + state.requestId())); + heading.addLore(gray("Stale sticks stop working when this Studio closes.")); window.setElement(0, 0, heading); window.setElement(4, 0, evaluationElement(state.evaluation())); @@ -1463,35 +1473,35 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement element = element( "tool-" + index, JigsawStudioMenuIcon.STICK, - safe(tool.displayName())); - element.addLore("Action: " + tool.payload().action().displayName()); + aqua(safe(tool.displayName()))); + element.addLore(gray("Action: " + tool.payload().action().displayName())); addToolBindingLore(element, tool.payload()); element.addLore(tool.payload().action().destructive() - ? "Bound tools require confirmation when used." - : "Left-click to receive this named stick."); + ? red("Bound tools require confirmation when used.") + : yellow("Left-click to receive this named stick.")); element.onLeftClick(clicked -> giveTool( window.getViewer(), state.requestId(), tool.payload())); window.setElement(position, row, element); } - JigsawStudioMenuElement footerBack = element("toolbox-footer-back", JigsawStudioMenuIcon.ARROW, "Back"); + JigsawStudioMenuElement footerBack = element("toolbox-footer-back", JigsawStudioMenuIcon.ARROW, yellow("Back")); footerBack.onLeftClick(clicked -> refreshMain( window.getViewer(), state.requestId(), workcell.stableId(), 0)); window.setElement(-4, 5, footerBack); int pageCount = pageCount(allTools.size(), TOOLS_PER_PAGE); if (page > 0) { - JigsawStudioMenuElement previous = element("toolbox-previous", JigsawStudioMenuIcon.ARROW, "Previous Page"); + JigsawStudioMenuElement previous = element("toolbox-previous", JigsawStudioMenuIcon.ARROW, yellow("Previous Page")); previous.onLeftClick(clicked -> refreshToolbox( window.getViewer(), state.requestId(), workcell.stableId(), page - 1)); window.setElement(-1, 5, previous); } - JigsawStudioMenuElement indicator = element("toolbox-page", JigsawStudioMenuIcon.BOOK, "Page " - + (page + 1) + "/" + pageCount); - indicator.addLore("" + allTools.size() + " bound tools"); + JigsawStudioMenuElement indicator = element("toolbox-page", JigsawStudioMenuIcon.BOOK, white("Page " + + (page + 1) + "/" + pageCount)); + indicator.addLore(gray("" + allTools.size() + " bound tools")); window.setElement(0, 5, indicator); if (page + 1 < pageCount) { - JigsawStudioMenuElement next = element("toolbox-next", JigsawStudioMenuIcon.ARROW, "Next Page"); + JigsawStudioMenuElement next = element("toolbox-next", JigsawStudioMenuIcon.ARROW, yellow("Next Page")); next.onLeftClick(clicked -> refreshToolbox( window.getViewer(), state.requestId(), workcell.stableId(), page + 1)); window.setElement(1, 5, next); @@ -2441,11 +2451,11 @@ public final class JigsawStudioMenuController { } private static void send(ToolPlayer player, String message) { - player.sender().info(message); + player.message(yellow(message)); } private static void sendError(ToolPlayer player, String message) { - player.sender().error(message); + player.message(red(message)); } private void closeAfterAction(ToolPlayer player) { @@ -2984,17 +2994,17 @@ public final class JigsawStudioMenuController { private static void addToolBindingLore(JigsawStudioMenuElement element, JigsawStudioToolPayload payload) { if (!payload.workcellId().isEmpty()) { - element.addLore("Workcell: " + safe(payload.workcellId())); + element.addLore(gray("Workcell: " + safe(payload.workcellId()))); } if (!payload.pieceKey().isEmpty()) { - element.addLore("Variant: " + safe(payload.pieceKey())); + element.addLore(gray("Variant: " + safe(payload.pieceKey()))); } if (!payload.poolKey().isEmpty()) { - element.addLore("Pool: " + safe(payload.poolKey()) - + (payload.entryIndex() < 0 ? "" : " [" + payload.entryIndex() + "]")); + element.addLore(gray("Pool: " + safe(payload.poolKey()) + + (payload.entryIndex() < 0 ? "" : " [" + payload.entryIndex() + "]"))); } if (payload.amount() != 0) { - element.addLore("Amount: " + payload.amount()); + element.addLore(gray("Amount: " + payload.amount())); } } @@ -3022,22 +3032,32 @@ public final class JigsawStudioMenuController { JigsawStudioMenuElement element = element( "evaluation", evaluationMaterial(evaluation.state()), - evaluationName(evaluation.state())); - element.addLore("Evaluation updates automatically."); - element.addLore("Seed: " + evaluation.seed()); + ToolText.colored(evaluationColor(evaluation.state()), evaluationName(evaluation.state()))); + element.addLore(gray("Evaluation updates automatically.")); + element.addLore(gray("Seed: " + evaluation.seed())); if (evaluation.generation() > 0L) { - element.addLore("Generation: " + evaluation.generation()); + element.addLore(gray("Generation: " + evaluation.generation())); } if (!evaluation.selectedTheme().isEmpty()) { - element.addLore("Theme: " + safe(evaluation.selectedTheme())); + element.addLore(gray("Theme: " + safe(evaluation.selectedTheme()))); } - element.addLore("Pieces: " + evaluation.pieceCount()); + element.addLore(gray("Pieces: " + evaluation.pieceCount())); if (!evaluation.detail().isEmpty()) { - element.addLore(safe(evaluation.detail())); + element.addLore(gray(safe(evaluation.detail()))); } return element; } + private static TextColor evaluationColor(JigsawStudioEvaluationState state) { + return switch (state) { + case PENDING -> TextColor.AQUA; + case VALID -> TextColor.GREEN; + case WARNING -> TextColor.YELLOW; + case INVALID -> TextColor.RED; + case STALE -> TextColor.GRAY; + }; + } + static JigsawStudioMenuIcon evaluationMaterial(JigsawStudioEvaluationState state) { return switch (state) { case PENDING -> JigsawStudioMenuIcon.CLOCK; @@ -3078,17 +3098,17 @@ public final class JigsawStudioMenuController { return variant.owned() ? JigsawStudioMenuIcon.PAPER : JigsawStudioMenuIcon.GRAY_DYE; } - static String workcellStatus(JigsawStudioMenuState.Workcell workcell) { + static ToolText workcellStatus(JigsawStudioMenuState.Workcell workcell) { if (workcell.loading()) { - return "Loading variant"; + return yellow("Loading variant"); } if (workcell.saving()) { - return "Autosave in progress"; + return yellow("Autosave in progress"); } if (workcell.dirty()) { - return "Autosave pending"; + return gold("Autosave pending"); } - return "Autosaved"; + return green("Autosaved"); } private static String dimensions(JigsawStudioCellDimensions dimensions) { @@ -3118,12 +3138,48 @@ public final class JigsawStudioMenuController { }; } - private static JigsawStudioMenuElement element(String id, JigsawStudioMenuIcon material, String name) { + private static JigsawStudioMenuElement element(String id, JigsawStudioMenuIcon material, ToolText name) { return new JigsawStudioMenuElement(id) .setIcon(material) .setName(name); } + private static ToolText gray(String text) { + return ToolText.colored(TextColor.GRAY, text); + } + + private static ToolText yellow(String text) { + return ToolText.colored(TextColor.YELLOW, text); + } + + private static ToolText green(String text) { + return ToolText.colored(TextColor.GREEN, text); + } + + private static ToolText red(String text) { + return ToolText.colored(TextColor.RED, text); + } + + private static ToolText aqua(String text) { + return ToolText.colored(TextColor.AQUA, text); + } + + private static ToolText white(String text) { + return ToolText.colored(TextColor.WHITE, text); + } + + private static ToolText gold(String text) { + return ToolText.colored(TextColor.GOLD, text); + } + + private static ToolText lightPurple(String text) { + return ToolText.colored(TextColor.LIGHT_PURPLE, text); + } + + private static ToolText darkGray(String text) { + return ToolText.colored(TextColor.DARK_GRAY, text); + } + private static String title(String structureKey) { String value = "Iris Jigsaw: " + safe(displayKey(structureKey)); return value.length() > 32 ? value.substring(0, 32) : value; diff --git a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuElement.java b/core/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuElement.java index 77dea190a..2cf0182cb 100644 --- a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuElement.java +++ b/core/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuElement.java @@ -3,6 +3,7 @@ package art.arcane.iris.core.service; import com.volmit.tooling.world.MenuButton; import com.volmit.tooling.world.MenuClick; import com.volmit.tooling.world.ToolItem; +import com.volmit.tooling.world.ToolText; import java.util.ArrayList; import java.util.List; @@ -12,9 +13,9 @@ import java.util.function.Consumer; /** One slot of a studio menu: an icon with a name and lore, and what each kind of click on it does. */ final class JigsawStudioMenuElement { private final String id; - private final List lore = new ArrayList<>(); + private final List lore = new ArrayList<>(); private JigsawStudioMenuIcon icon = JigsawStudioMenuIcon.BARRIER; - private String name = ""; + private ToolText name = ToolText.EMPTY; private boolean enchanted; private Consumer onLeftClick; private Consumer onRightClick; @@ -35,7 +36,7 @@ final class JigsawStudioMenuElement { return this; } - JigsawStudioMenuElement setName(String name) { + JigsawStudioMenuElement setName(ToolText name) { this.name = Objects.requireNonNull(name, "Jigsaw Studio menu name"); return this; } @@ -45,7 +46,7 @@ final class JigsawStudioMenuElement { return this; } - JigsawStudioMenuElement addLore(String line) { + JigsawStudioMenuElement addLore(ToolText line) { lore.add(Objects.requireNonNull(line, "Jigsaw Studio menu lore")); return this; } diff --git a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuWindow.java b/core/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuWindow.java index 6c253fb81..49c0fc192 100644 --- a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuWindow.java +++ b/core/src/main/java/art/arcane/iris/core/service/JigsawStudioMenuWindow.java @@ -3,6 +3,7 @@ package art.arcane.iris.core.service; import com.volmit.tooling.world.MenuButton; import com.volmit.tooling.world.ToolMenu; import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolText; import java.util.ArrayList; import java.util.List; @@ -23,7 +24,7 @@ final class JigsawStudioMenuWindow { private final ToolPlayer viewer; private final Map elements = new TreeMap<>(); - private String title = ""; + private ToolText title = ToolText.EMPTY; private int viewportRows = ToolMenu.MAX_ROWS; private Runnable onClosed = () -> { }; private int batchDepth; @@ -43,11 +44,15 @@ final class JigsawStudioMenuWindow { return this; } - JigsawStudioMenuWindow setTitle(String title) { + JigsawStudioMenuWindow setTitle(ToolText title) { this.title = Objects.requireNonNull(title, "Jigsaw Studio menu title"); return this; } + JigsawStudioMenuWindow setTitle(String title) { + return setTitle(ToolText.plain(Objects.requireNonNull(title, "Jigsaw Studio menu title"))); + } + JigsawStudioMenuWindow onClosed(Runnable onClosed) { this.onClosed = Objects.requireNonNull(onClosed, "Jigsaw Studio menu close handler"); return this; diff --git a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioService.java b/core/src/main/java/art/arcane/iris/core/service/JigsawStudioService.java index b51f93730..97afb2660 100644 --- a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioService.java +++ b/core/src/main/java/art/arcane/iris/core/service/JigsawStudioService.java @@ -65,6 +65,7 @@ import com.volmit.tooling.world.BlockChange; import com.volmit.tooling.world.Particle; import com.volmit.tooling.world.ToolItem; import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolText; import com.volmit.tooling.world.ToolUse; import com.volmit.tooling.world.ToolWorld; import com.volmit.tooling.world.ToolWorldListener; @@ -291,7 +292,6 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act generator, new ConcurrentHashMap<>(), ConcurrentHashMap.newKeySet(), - ConcurrentHashMap.newKeySet(), new AtomicLong()); synchronized (saveLifecycleLock) { if (!enabled || disableStarted.get()) { @@ -337,7 +337,6 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act } private void markChunkAvailable(ActiveStudio studio, int chunkX, int chunkZ) { - studio.loadedChunks().add(chunkKey(chunkX, chunkZ)); long chunkKey = chunkKey(chunkX, chunkZ); boolean relevant = false; for (JigsawStudioBay bay : studio.generator().getLayout().bays()) { @@ -2871,7 +2870,10 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act message(player, "This tool belongs to a different or closed Jigsaw Studio session."); return false; } - player.give(toolCodec.create(payload)); + if (!player.give(toolCodec.create(payload))) { + message(player, "Your inventory is full; no Jigsaw Studio tool was added."); + return false; + } message(player, "Added " + payload.action().displayName() + " tool."); return true; } @@ -3068,7 +3070,7 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act if (resetLabel) { return Optional.of(""); } - String normalized = tool == null ? "" : tool.name().trim(); + String normalized = tool == null ? "" : tool.name().plainText().trim(); String defaultName = JigsawStudioToolCodec.NAME_PREFIX + payload.action().displayName(); if (normalized.isEmpty() || normalized.equals(defaultName)) { message(player, "Rename this bound stick in an anvil to the desired label, then right-click it. " @@ -3779,7 +3781,17 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act assemblyPreviews.remove(player.id()); playerWorkcells.remove(player.id()); ensureVisualizationLoop(player); - reconcilePlayerContext(player, player.position()); + } + + /** A player arrived by other means than walking; the host tells it at the time of the teleport, after the arrival it belongs to. */ + void playerTeleported(ToolPlayer player, BlockPosition to) { + finalizeJigsawTileWatchesForPlayer(player.id()); + reconcilePlayerContext(player, to); + } + + /** The contents of a container or machine changed without a block change: the container's workcell has unsaved work. */ + void containerChanged(UUID worldId, BlockPosition at) { + markDirty(studios.get(worldId), at); } void playerLeft(ToolPlayer player) { @@ -3947,6 +3959,7 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act switch (change.cause()) { case FLUID -> markDirty(studio, positions.getLast()); case PHYSICS -> markDirty(studio, positions.getFirst()); + case PISTON -> change.changed().forEach(position -> markDirty(studio, position)); default -> positions.forEach(position -> markDirty(studio, position)); } } @@ -4500,18 +4513,11 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act } /** - * Whether the block in the world is the one that was written: a state the platform completes with the properties it - * defaults, so each property the written state names has to agree, and air stands for every kind of air. + * Whether the block in the world is the one that was written: the same block with every property equal. The states + * written are the platform's own complete states, so a block the platform changed on its own does not pass. */ - private static boolean sameBlock(BlockState actual, BlockState written) { - if (JigsawStudioBlocks.isAir(actual) && JigsawStudioBlocks.isAir(written)) { - return true; - } - if (!actual.material().equals(written.material())) { - return false; - } - return written.properties().entrySet().stream() - .allMatch(property -> property.getValue().equals(actual.properties().get(property.getKey()))); + static boolean sameBlock(BlockState actual, BlockState written) { + return actual.equals(written); } private static BlockRegistry registryOf(ActiveStudio studio) { @@ -7269,7 +7275,7 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act private static void message(ToolPlayer player, String text) { if (player != null) { - player.sender().info(MESSAGE_PREFIX + text); + player.message(ToolText.plain(MESSAGE_PREFIX + text)); } } @@ -7304,7 +7310,6 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act JigsawStudioGenerator generator, ConcurrentHashMap populations, Set hydrationsInProgress, - Set loadedChunks, AtomicLong evaluationGeneration ) { ActiveStudio { @@ -7313,13 +7318,12 @@ public final class JigsawStudioService implements JigsawStudioMenuController.Act Objects.requireNonNull(generator, "Jigsaw Studio generator"); Objects.requireNonNull(populations, "Jigsaw Studio bay populations"); Objects.requireNonNull(hydrationsInProgress, "Jigsaw Studio hydrations"); - Objects.requireNonNull(loadedChunks, "Jigsaw Studio loaded chunks"); Objects.requireNonNull(evaluationGeneration, "Jigsaw Studio evaluation generation"); } - /** Whether the world has loaded the chunk since the studio opened; the host tells the studio of each load. */ + /** Whether the platform has the chunk loaded now. */ boolean isChunkLoaded(int chunkX, int chunkZ) { - return loadedChunks.contains(chunkKey(chunkX, chunkZ)); + return world.loaded(new ChunkPos(chunkX, chunkZ)); } BayPopulation population(JigsawStudioBay bay) { diff --git a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioToolCodec.java b/core/src/main/java/art/arcane/iris/core/service/JigsawStudioToolCodec.java index 2d9373628..0fcc55f90 100644 --- a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioToolCodec.java +++ b/core/src/main/java/art/arcane/iris/core/service/JigsawStudioToolCodec.java @@ -6,7 +6,9 @@ import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.volmit.resource.ResourceId; +import com.volmit.tooling.world.TextColor; import com.volmit.tooling.world.ToolItem; +import com.volmit.tooling.world.ToolText; import java.util.ArrayList; import java.util.List; @@ -33,7 +35,7 @@ public final class JigsawStudioToolCodec { JigsawStudioToolPayload binding = requireCurrentSchema(payload); return new ToolItem( TOOL_ITEM, - NAME_PREFIX + binding.action().displayName(), + ToolText.colored(TextColor.AQUA, NAME_PREFIX + binding.action().displayName()), lore(binding), false, encode(binding)); @@ -107,24 +109,24 @@ public final class JigsawStudioToolCodec { return json.has(field) ? json.get(field).getAsString() : ""; } - private static List lore(JigsawStudioToolPayload payload) { - List lore = new ArrayList<>(); + private static List lore(JigsawStudioToolPayload payload) { + List lore = new ArrayList<>(); if (!payload.workcellId().isEmpty()) { - lore.add("Workcell: " + payload.workcellId()); + lore.add(ToolText.colored(TextColor.GRAY, "Workcell: " + payload.workcellId())); } if (!payload.pieceKey().isEmpty()) { - lore.add("Variant: " + payload.pieceKey()); + lore.add(ToolText.colored(TextColor.GRAY, "Variant: " + payload.pieceKey())); } if (!payload.poolKey().isEmpty()) { - lore.add("Pool: " + payload.poolKey() - + (payload.entryIndex() < 0 ? "" : " [" + payload.entryIndex() + "]")); + lore.add(ToolText.colored(TextColor.GRAY, "Pool: " + payload.poolKey() + + (payload.entryIndex() < 0 ? "" : " [" + payload.entryIndex() + "]"))); } if (payload.amount() != 0) { - lore.add("Amount: " + payload.amount()); + lore.add(ToolText.colored(TextColor.GRAY, "Amount: " + payload.amount())); } lore.add(payload.action().destructive() - ? "Right-click twice to confirm" - : "Right-click to use"); + ? ToolText.colored(TextColor.RED, "Right-click twice to confirm") + : ToolText.colored(TextColor.YELLOW, "Right-click to use")); return List.copyOf(lore); } } diff --git a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioWorldListener.java b/core/src/main/java/art/arcane/iris/core/service/JigsawStudioWorldListener.java index fbec63367..f174c243c 100644 --- a/core/src/main/java/art/arcane/iris/core/service/JigsawStudioWorldListener.java +++ b/core/src/main/java/art/arcane/iris/core/service/JigsawStudioWorldListener.java @@ -39,6 +39,16 @@ final class JigsawStudioWorldListener implements ToolWorldListener { service.playerMoved(player, to); } + @Override + public void teleported(ToolPlayer player, BlockPosition to) { + service.playerTeleported(player, to); + } + + @Override + public void containerChanged(Optional player, BlockPosition at) { + service.containerChanged(studioId, at); + } + @Override public void sneakToggled(ToolPlayer player, boolean sneaking) { service.sneakToggled(player, sneaking); diff --git a/core/src/main/java/art/arcane/iris/core/service/StudioSVC.java b/core/src/main/java/art/arcane/iris/core/service/StudioSVC.java index a8188ffe0..61c6a83e1 100644 --- a/core/src/main/java/art/arcane/iris/core/service/StudioSVC.java +++ b/core/src/main/java/art/arcane/iris/core/service/StudioSVC.java @@ -126,8 +126,9 @@ public class StudioSVC implements IrisService { boolean stopping = IrisToolbelt.isServerStopping(); LinkedHashSet worldNamesToDelete = new LinkedHashSet<>(TransientWorldCleanupSupport.collectTransientStudioWorldNames(IrisWorldStorage.levelRoot())); - if (activeProject != null) { - PlatformChunkGenerator activeProvider = activeProject.getActiveProvider(); + IrisProject openProject = currentProject(); + if (openProject != null) { + PlatformChunkGenerator activeProvider = openProject.getActiveProvider(); if (activeProvider != null) { String activeWorldName = IrisWorldStorage.logicalName( WorldIdentity.parse(activeProvider.getTarget().getWorld().identity())); @@ -476,13 +477,20 @@ public class StudioSVC implements IrisService { } public boolean isProjectOpen() { - return activeProject != null && activeProject.isOpen(); + IrisProject project = currentProject(); + return project != null && project.isOpen(); + } + + /** The studio project in the slot: the project of the open tool world, or the one opened as a project. */ + private IrisProject currentProject() { + StudioSlotOccupant toolWorld = activeToolWorld; + return toolWorld == null ? activeProject : toolWorld.project(); } public CompletableFuture teleportToActiveProject(Player player) { Player target = Objects.requireNonNull(player, "Studio teleport player"); return studioTransitions.submit(() -> { - IrisProject project = activeProject; + IrisProject project = currentProject(); if (project == null || !project.isOpen()) { return CompletableFuture.failedFuture(new IllegalStateException( "No active Studio project is available for teleport.")); @@ -1493,12 +1501,12 @@ public class StudioSVC implements IrisService { } public IrisProject getActiveProject() { - return activeProject; + return currentProject(); } public void updateWorkspace() { if (isProjectOpen()) { - new IrisCodeWorkspace(activeProject).updateWorkspace(); + new IrisCodeWorkspace(currentProject()).updateWorkspace(); } } } diff --git a/core/src/test/java/art/arcane/iris/core/runtime/StudioOpenCoordinatorOpenKindTest.java b/core/src/test/java/art/arcane/iris/core/runtime/StudioOpenCoordinatorOpenKindTest.java index 229e9f9f7..d5a7ab7a8 100644 --- a/core/src/test/java/art/arcane/iris/core/runtime/StudioOpenCoordinatorOpenKindTest.java +++ b/core/src/test/java/art/arcane/iris/core/runtime/StudioOpenCoordinatorOpenKindTest.java @@ -119,7 +119,7 @@ public class StudioOpenCoordinatorOpenKindTest { int serviceEnd = service.indexOf("public void open(VolmitSender", serviceStart); String serviceMethod = service.substring(serviceStart, serviceEnd); int transitionAdmission = serviceMethod.indexOf("studioTransitions.submit(() ->"); - int projectCapture = serviceMethod.indexOf("IrisProject project = activeProject"); + int projectCapture = serviceMethod.indexOf("IrisProject project = currentProject()"); int nativeDelegation = coordinatorMethod.indexOf( "WorldRuntimeControlService.get().teleportInMode(player, entry, GameMode.SPECTATOR)"); diff --git a/core/src/test/java/art/arcane/iris/core/service/BoardSVCToolSidebarTest.java b/core/src/test/java/art/arcane/iris/core/service/BoardSVCToolSidebarTest.java index 97fa7bbea..f455ae43d 100644 --- a/core/src/test/java/art/arcane/iris/core/service/BoardSVCToolSidebarTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/BoardSVCToolSidebarTest.java @@ -1,5 +1,7 @@ package art.arcane.iris.core.service; +import com.volmit.tooling.world.TextColor; +import com.volmit.tooling.world.ToolText; import org.junit.Test; import java.util.ArrayList; @@ -14,22 +16,34 @@ public class BoardSVCToolSidebarTest { @Test public void aToolSidebarKeepsItsOwnCopyOfTheLines() { - List lines = new ArrayList<>(List.of("one")); - BoardSVC.ToolSidebar sidebar = new BoardSVC.ToolSidebar(WORLD, "Title", lines); - lines.add("two"); + List lines = new ArrayList<>(List.of(ToolText.plain("one"))); + BoardSVC.ToolSidebar sidebar = new BoardSVC.ToolSidebar(WORLD, ToolText.plain("Title"), lines); + lines.add(ToolText.plain("two")); - assertEquals(List.of("one"), sidebar.lines()); - assertThrows(NullPointerException.class, () -> new BoardSVC.ToolSidebar(null, "Title", List.of())); + assertEquals(List.of(ToolText.plain("one")), sidebar.lines()); + assertThrows(NullPointerException.class, () -> new BoardSVC.ToolSidebar(null, ToolText.plain("Title"), List.of())); assertThrows(NullPointerException.class, () -> new BoardSVC.ToolSidebar(WORLD, null, List.of())); } @Test - public void toolLinesAreShownAsPlainTextWithoutColourOrMarkup() { - BoardSVC.ToolSidebar sidebar = new BoardSVC.ToolSidebar(WORLD, "Title", - List.of("&cStructure§a", "line\nbreak", "plain")); + public void textOfASpanCannotCarryCodesOrMarkup() { + BoardSVC.ToolSidebar sidebar = new BoardSVC.ToolSidebar(WORLD, ToolText.EMPTY, + List.of(ToolText.plain("&cStructure§a"), ToolText.plain("line\nbreak"))); - assertEquals(List.of(BoardSVC.untrustedBoardValue("&cStructure§a"), "line break", "plain"), - BoardSVC.toolLines(sidebar)); - assertEquals("&cStructure‹red›", BoardSVC.toolLines(sidebar).get(0)); + assertEquals(List.of("&cStructure‹red›", "line break"), BoardSVC.toolLines(sidebar)); + } + + @Test + public void spansBecomeTheBoardsCodesTheWayTheJigsawLinesWereWritten() { + ToolText separator = ToolText.builder() + .append(new ToolText.Span("-------------------", TextColor.GRAY, false, false, true)) + .build(); + ToolText value = ToolText.builder().aqua("Structure").gray(": village").build(); + ToolText mixed = ToolText.builder().yellow("Walk").append(" plain").build(); + + assertEquals("&7&m-------------------", BoardSVC.boardLine(separator)); + assertEquals("&bStructure&7: village", BoardSVC.boardLine(value)); + assertEquals("&eWalk&r plain", BoardSVC.boardLine(mixed)); + assertEquals("", BoardSVC.boardLine(ToolText.EMPTY)); } } diff --git a/core/src/test/java/art/arcane/iris/core/service/FakeBlockRegistry.java b/core/src/test/java/art/arcane/iris/core/service/FakeBlockRegistry.java index 0a8dfebff..b2248cb7b 100644 --- a/core/src/test/java/art/arcane/iris/core/service/FakeBlockRegistry.java +++ b/core/src/test/java/art/arcane/iris/core/service/FakeBlockRegistry.java @@ -30,6 +30,8 @@ final class FakeBlockRegistry { Optional.of(BlockState.parse(invocation.getArgument(0)))); when(registry.rotate(any(), any())).thenAnswer(invocation -> rotated(invocation.getArgument(0), invocation.getArgument(1))); + when(registry.tryRotate(any(), any())).thenAnswer(invocation -> + Optional.of(rotated(invocation.getArgument(0), invocation.getArgument(1)))); return registry; } diff --git a/core/src/test/java/art/arcane/iris/core/service/FakeToolPlayer.java b/core/src/test/java/art/arcane/iris/core/service/FakeToolPlayer.java index db9d2a564..30c94f32e 100644 --- a/core/src/test/java/art/arcane/iris/core/service/FakeToolPlayer.java +++ b/core/src/test/java/art/arcane/iris/core/service/FakeToolPlayer.java @@ -7,6 +7,7 @@ import com.volmit.tooling.world.Particle; import com.volmit.tooling.world.ToolItem; import com.volmit.tooling.world.ToolMenu; import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolText; import com.volmit.tooling.world.ToolWorld; import java.util.ArrayList; @@ -19,7 +20,8 @@ import java.util.concurrent.CompletableFuture; final class FakeToolPlayer implements ToolPlayer { final List messages = new ArrayList<>(); final List given = new ArrayList<>(); - final List> sidebars = new ArrayList<>(); + final List texts = new ArrayList<>(); + final List> sidebars = new ArrayList<>(); final List menus = new ArrayList<>(); final List particles = new ArrayList<>(); final List sounds = new ArrayList<>(); @@ -28,6 +30,7 @@ final class FakeToolPlayer implements ToolPlayer { BlockPosition position = new BlockPosition(0, 64, 0); boolean sneaking; boolean ownedElsewhere; + boolean inventoryFull; int sidebarsHidden; int menusClosed; private final UUID id; @@ -138,7 +141,13 @@ final class FakeToolPlayer implements ToolPlayer { } @Override - public void actionBar(String text) { + public void message(ToolText text) { + texts.add(text); + messages.add(text.plainText()); + } + + @Override + public void actionBar(ToolText text) { } @Override @@ -150,7 +159,7 @@ final class FakeToolPlayer implements ToolPlayer { } @Override - public void sidebar(String title, List lines) { + public void sidebar(ToolText title, List lines) { sidebars.add(lines); } @@ -165,8 +174,12 @@ final class FakeToolPlayer implements ToolPlayer { } @Override - public void give(ToolItem item) { + public boolean give(ToolItem item) { + if (inventoryFull) { + return false; + } given.add(item); + return true; } @Override diff --git a/core/src/test/java/art/arcane/iris/core/service/FakeToolWorld.java b/core/src/test/java/art/arcane/iris/core/service/FakeToolWorld.java index f94fb87c1..1a991f610 100644 --- a/core/src/test/java/art/arcane/iris/core/service/FakeToolWorld.java +++ b/core/src/test/java/art/arcane/iris/core/service/FakeToolWorld.java @@ -26,6 +26,8 @@ final class FakeToolWorld implements ToolWorld { final List players = new ArrayList<>(); final List repainted = new ArrayList<>(); final List held = Collections.synchronizedList(new ArrayList<>()); + /** Every chunk is loaded except these. */ + final List unloadedChunks = Collections.synchronizedList(new ArrayList<>()); volatile boolean schedulingFails; volatile boolean holdTasks; private final String name; @@ -107,6 +109,11 @@ final class FakeToolWorld implements ToolWorld { data.ifPresentOrElse(entity -> entities.put(at, entity), () -> entities.remove(at)); } + @Override + public boolean loaded(ChunkPos chunk) { + return unloadedChunks.stream().noneMatch(chunk::equals); + } + @Override public CompletableFuture repaint(Collection chunks) { repainted.addAll(chunks); diff --git a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioBlocksTest.java b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioBlocksTest.java new file mode 100644 index 000000000..6f6a0de5b --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioBlocksTest.java @@ -0,0 +1,68 @@ +package art.arcane.iris.core.service; + +import art.arcane.iris.engine.object.prefab.ObjectTurn; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import org.junit.Test; + +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +public class JigsawStudioBlocksTest { + private static final ObjectTurn QUARTER_TURN = ObjectTurn.of(0, 90.0D, 0); + + @Test + public void aBlockTheRegistryCannotTurnComesBackAsNothingNotAsAir() { + BlockRegistry registry = mock(BlockRegistry.class); + BlockState sign = BlockState.parse("minecraft:oak_sign"); + when(registry.tryRotate(any(), any())).thenReturn(Optional.empty()); + + assertNull(JigsawStudioBlocks.rotated(registry, sign, QUARTER_TURN)); + } + + @Test + public void airThatStaysAirIsNotABlockThatWasDropped() { + BlockRegistry registry = mock(BlockRegistry.class); + BlockState caveAir = BlockState.parse("minecraft:cave_air"); + when(registry.tryRotate(any(), any())).thenReturn(Optional.of(caveAir)); + + assertSame(caveAir, JigsawStudioBlocks.rotated(registry, caveAir, QUARTER_TURN)); + } + + @Test + public void aTurnThatTurnsNothingNeverAsksTheRegistry() { + BlockRegistry registry = mock(BlockRegistry.class); + BlockState stairs = BlockState.parse("minecraft:oak_stairs[facing=east]"); + + assertSame(stairs, JigsawStudioBlocks.rotated(registry, stairs, ObjectTurn.of(0, 0, 0))); + verifyNoInteractions(registry); + } + + @Test + public void aWrittenBlockMatchesOnlyTheSameBlockWithEveryPropertyEqual() { + BlockState written = BlockState.parse("minecraft:chest[facing=east,type=single,waterlogged=false]"); + + assertTrue(JigsawStudioService.sameBlock( + BlockState.parse("minecraft:chest[facing=east,type=single,waterlogged=false]"), written)); + assertFalse(JigsawStudioService.sameBlock( + BlockState.parse("minecraft:chest[facing=east,type=single,waterlogged=true]"), written)); + assertFalse(JigsawStudioService.sameBlock(BlockState.parse("minecraft:chest"), written)); + assertFalse(JigsawStudioService.sameBlock(BlockState.parse("minecraft:trapped_chest"), written)); + } + + @Test + public void everyKindOfAirIsItsOwnBlockWhenMaterializationIsChecked() { + assertFalse(JigsawStudioService.sameBlock( + BlockState.parse("minecraft:cave_air"), BlockState.parse("minecraft:air"))); + assertEquals(BlockState.parse("minecraft:air"), JigsawStudioBlocks.AIR); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioBoardContextTest.java b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioBoardContextTest.java index 7162f9850..4f71d3530 100644 --- a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioBoardContextTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioBoardContextTest.java @@ -1,6 +1,7 @@ package art.arcane.iris.core.service; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; +import com.volmit.tooling.world.ToolText; import org.junit.Test; import java.util.List; @@ -23,8 +24,19 @@ public class JigsawStudioBoardContextTest { "Right-click the chest for variants" ); - List lines = context.sidebarLines(); + List lines = plain(context.sidebarLines()); + assertEquals(List.of( + "&7&m-------------------", + "&dJigsaw Studio", + "&bStructure&7: village", + "&bWorkcell&7: Corner", + "&bVariant&7: mossy", + "&bState&7: Unsaved", + "&7&m-------------------", + "&eRight-click the chest for variants", + "&7&m-------------------" + ), context.sidebarLines().stream().map(BoardSVC::boardLine).toList()); assertEquals(List.of( "-------------------", "Jigsaw Studio", @@ -65,7 +77,17 @@ public class JigsawStudioBoardContextTest { "Walk into a workcell", "Use the workcell chest to choose a variant", "-------------------" - ), context.sidebarLines()); + ), plain(context.sidebarLines())); + assertEquals(List.of( + "&7&m-------------------", + "&dJigsaw Studio", + "&bStructure&7: village", + "&bMode&7: Spatial", + "&7&m-------------------", + "&eWalk into a workcell", + "&7Use the workcell chest to choose a variant", + "&7&m-------------------" + ), context.sidebarLines().stream().map(BoardSVC::boardLine).toList()); } @Test @@ -81,7 +103,7 @@ public class JigsawStudioBoardContextTest { JigsawStudioBoardState.SAVED, "Triple-sneak for controls"); - List lines = context.sidebarLines(); + List lines = plain(context.sidebarLines()); assertTrue(lines.contains("Workcell: Village Entrances")); assertTrue(lines.contains("Role: End Cap")); @@ -155,6 +177,16 @@ public class JigsawStudioBoardContextTest { )); } + private static List plain(List lines) { + return lines.stream().map(ToolText::plainText).toList(); + } + + @Test + public void theSidebarKeepsThePlatformTitle() { + assertTrue(context(JigsawStudioMode.PLANAR_JIGSAW, "", "", JigsawStudioBoardState.SAVED, "") + .sidebarTitle().isEmpty()); + } + private JigsawStudioBoardContext context( JigsawStudioMode mode, String workcell, diff --git a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioLifecycleTest.java b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioLifecycleTest.java index c9c85225c..7e305abf3 100644 --- a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioLifecycleTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioLifecycleTest.java @@ -168,7 +168,6 @@ public class JigsawStudioLifecycleTest { mock(JigsawStudioGenerator.class), new ConcurrentHashMap<>(), ConcurrentHashMap.newKeySet(), - ConcurrentHashMap.newKeySet(), new AtomicLong()); Class watchType = Class.forName(JigsawStudioService.class.getName() + "$JigsawTileWatch"); Constructor watchConstructor = watchType.getDeclaredConstructor( diff --git a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioMenuControllerTest.java b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioMenuControllerTest.java index 89e7244d2..749c3af74 100644 --- a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioMenuControllerTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioMenuControllerTest.java @@ -7,7 +7,9 @@ import art.arcane.iris.core.runtime.jigsaw.JigsawStudioPieceRules; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolAction; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolPayload; import com.volmit.ModuleLog; +import com.volmit.tooling.world.TextColor; import com.volmit.tooling.world.ToolPlayer; +import com.volmit.tooling.world.ToolText; import org.junit.After; import org.junit.Test; @@ -77,7 +79,7 @@ public class JigsawStudioMenuControllerTest { false, List.of(active)); - assertEquals("Autosaved", JigsawStudioMenuController.workcellStatus(fresh)); + assertEquals(ToolText.colored(TextColor.GREEN, "Autosaved"), JigsawStudioMenuController.workcellStatus(fresh)); } @Test diff --git a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioMenuWindowTest.java b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioMenuWindowTest.java index bfbb456ad..1938cb718 100644 --- a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioMenuWindowTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioMenuWindowTest.java @@ -3,7 +3,9 @@ package art.arcane.iris.core.service; import com.volmit.resource.ResourceId; import com.volmit.tooling.world.MenuButton; import com.volmit.tooling.world.MenuClick; +import com.volmit.tooling.world.TextColor; import com.volmit.tooling.world.ToolMenu; +import com.volmit.tooling.world.ToolText; import org.junit.Test; import java.util.ArrayList; @@ -30,7 +32,7 @@ public class JigsawStudioMenuWindowTest { window.open(); ToolMenu menu = viewer.menus.getLast(); - assertEquals("Jigsaw: village", menu.title()); + assertEquals(ToolText.plain("Jigsaw: village"), menu.title()); assertEquals(List.of(0, 4, 17, 18, 35), slotsOf(menu)); } @@ -39,16 +41,16 @@ public class JigsawStudioMenuWindowTest { JigsawStudioMenuWindow window = new JigsawStudioMenuWindow(viewer); window.setElement(0, 0, new JigsawStudioMenuElement("details") .setIcon(JigsawStudioMenuIcon.EMERALD) - .setName("Ready to Assemble") - .addLore("Seed 1337 assembled 19 pieces") + .setName(ToolText.colored(TextColor.GREEN, "Ready to Assemble")) + .addLore(ToolText.colored(TextColor.GRAY, "Seed 1337 assembled 19 pieces")) .setEnchanted(true)); window.open(); MenuButton button = viewer.menus.getLast().buttons().getFirst(); assertEquals(ResourceId.parse("minecraft:emerald"), button.icon().item()); - assertEquals("Ready to Assemble", button.icon().name()); - assertEquals(List.of("Seed 1337 assembled 19 pieces"), button.icon().lore()); + assertEquals(ToolText.colored(TextColor.GREEN, "Ready to Assemble"), button.icon().name()); + assertEquals(List.of(ToolText.colored(TextColor.GRAY, "Seed 1337 assembled 19 pieces")), button.icon().lore()); assertTrue(button.icon().glowing()); } @@ -169,7 +171,7 @@ public class JigsawStudioMenuWindowTest { } private static JigsawStudioMenuElement element(String id) { - return new JigsawStudioMenuElement(id).setName(id); + return new JigsawStudioMenuElement(id).setName(ToolText.plain(id)); } private static List slotsOf(ToolMenu menu) { diff --git a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioServiceCaptureTest.java b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioServiceCaptureTest.java index a6793af44..2279ff2ae 100644 --- a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioServiceCaptureTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioServiceCaptureTest.java @@ -1211,7 +1211,6 @@ public class JigsawStudioServiceCaptureTest { generator, populations, ConcurrentHashMap.newKeySet(), - ConcurrentHashMap.newKeySet(), new AtomicLong()); try { Field studiosField = JigsawStudioService.class.getDeclaredField("studios"); diff --git a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioToolCodecTest.java b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioToolCodecTest.java index fa78a9fe7..1e5a3771a 100644 --- a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioToolCodecTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioToolCodecTest.java @@ -3,7 +3,9 @@ package art.arcane.iris.core.service; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolAction; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolPayload; import com.volmit.resource.ResourceId; +import com.volmit.tooling.world.TextColor; import com.volmit.tooling.world.ToolItem; +import com.volmit.tooling.world.ToolText; import org.junit.Test; import java.util.List; @@ -34,16 +36,25 @@ public class JigsawStudioToolCodecTest { ToolItem tool = codec.create(payload); assertEquals(STICK, tool.item()); - assertEquals("Jigsaw Studio: Adjust Variant Weight", tool.name()); + assertEquals(ToolText.colored(TextColor.AQUA, "Jigsaw Studio: Adjust Variant Weight"), tool.name()); assertEquals(List.of( - "Workcell: workcell/corner", - "Variant: village/corner_mossy", - "Pool: village/start [3]", - "Amount: -1", - "Right-click to use"), tool.lore()); + ToolText.colored(TextColor.GRAY, "Workcell: workcell/corner"), + ToolText.colored(TextColor.GRAY, "Variant: village/corner_mossy"), + ToolText.colored(TextColor.GRAY, "Pool: village/start [3]"), + ToolText.colored(TextColor.GRAY, "Amount: -1"), + ToolText.colored(TextColor.YELLOW, "Right-click to use")), tool.lore()); assertFalse(tool.glowing()); } + @Test + public void aDestructiveToolAsksForConfirmationInRed() { + JigsawStudioToolCodec codec = new JigsawStudioToolCodec(); + + ToolItem tool = codec.create(JigsawStudioToolPayload.request(JigsawStudioToolAction.DELETE_PROJECT, REQUEST)); + + assertEquals(ToolText.colored(TextColor.RED, "Right-click twice to confirm"), tool.lore().getLast()); + } + @Test public void everyPayloadRoundTripsThroughTheItem() { JigsawStudioToolCodec codec = new JigsawStudioToolCodec(); @@ -106,7 +117,7 @@ public class JigsawStudioToolCodecTest { JigsawStudioToolPayload payload = JigsawStudioToolPayload.request(JigsawStudioToolAction.PREVIEW_GRAPH, REQUEST); ToolItem tool = codec.create(payload); ToolItem stone = new ToolItem(ResourceId.parse("minecraft:stone"), tool.name(), tool.lore(), false, tool.payload()); - ToolItem plainStick = new ToolItem(STICK, "Stick", List.of(), false, ""); + ToolItem plainStick = new ToolItem(STICK, ToolText.plain("Stick"), List.of(), false, ""); assertTrue(codec.isTool(tool)); assertFalse(codec.isTool(stone)); diff --git a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioWorldListenerTest.java b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioWorldListenerTest.java index e6aa2dac3..e2942ac63 100644 --- a/core/src/test/java/art/arcane/iris/core/service/JigsawStudioWorldListenerTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/JigsawStudioWorldListenerTest.java @@ -15,7 +15,11 @@ import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariantCatalog; import art.arcane.iris.engine.platform.studio.generators.JigsawStudioGenerator; import com.volmit.ModuleLog; import com.volmit.block.BlockState; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolAction; +import art.arcane.iris.core.runtime.jigsaw.JigsawStudioToolPayload; import com.volmit.geometry.BlockPosition; +import com.volmit.geometry.ChunkPos; +import com.volmit.tooling.world.ToolText; import com.volmit.tooling.world.BlockChange; import com.volmit.tooling.world.BlockChange.Cause; import com.volmit.tooling.world.ToolWorldListener; @@ -57,6 +61,8 @@ public class JigsawStudioWorldListenerTest { private final FakeToolPlayer other = new FakeToolPlayer(OTHER, "other", world); private JigsawStudioLayout layout; private JigsawStudioSession session; + private JigsawStudioService.ActiveStudio studio; + private UUID requestId; private ToolWorldListener listener; @Before @@ -94,7 +100,6 @@ public class JigsawStudioWorldListenerTest { generator, new ConcurrentHashMap<>(), ConcurrentHashMap.newKeySet(), - ConcurrentHashMap.newKeySet(), new AtomicLong()); Field studiosField = JigsawStudioService.class.getDeclaredField("studios"); studiosField.setAccessible(true); @@ -102,6 +107,8 @@ public class JigsawStudioWorldListenerTest { Map studios = (Map) studiosField.get(service); studios.put(request.requestId(), studio); + this.studio = studio; + this.requestId = request.requestId(); listener = new JigsawStudioWorldListener(service, request.requestId()); } @@ -191,6 +198,104 @@ public class JigsawStudioWorldListenerTest { assertFalse(listener.blockChanging(change(Cause.CONTAINER, owner, chest))); } + @Test + public void aPistonIsCheckedAgainstItsPositionsAndMarksTheBlocksItChanged() { + BlockPosition end = inside(EDITABLE_BAY); + BlockPosition straight = inside(SECOND_EDITABLE_BAY); + BlockChange change = new BlockChange( + Cause.PISTON, List.of(end), List.of(straight), Optional.empty(), Optional.empty()); + + assertTrue(listener.blockChanging(change)); + + assertFalse(dirty(EDITABLE_BAY)); + assertTrue(dirty(SECOND_EDITABLE_BAY)); + } + + @Test + public void aPistonThatMovesNothingIsAllowedAndMarksItsOwnBlocks() { + BlockChange change = new BlockChange( + Cause.PISTON, List.of(), List.of(inside(EDITABLE_BAY)), Optional.empty(), Optional.empty()); + + assertTrue(listener.blockChanging(change)); + + assertTrue(dirty(EDITABLE_BAY)); + } + + @Test + public void aPistonCheckedAgainstAnUneditableBayIsRefusedWhateverItChanged() { + BlockChange change = new BlockChange( + Cause.PISTON, List.of(inside(EMPTY_BAY)), List.of(inside(EDITABLE_BAY)), Optional.empty(), Optional.empty()); + + assertFalse(listener.blockChanging(change)); + + assertFalse(dirty(EDITABLE_BAY)); + } + + @Test + public void aContainerThatChangedMarksItsBayDirtyAndOneOutsideAnyBayDoesNot() { + listener.containerChanged(Optional.of(owner), inside(EDITABLE_BAY)); + listener.containerChanged(Optional.empty(), new BlockPosition(100_000, 64, 100_000)); + listener.containerChanged(Optional.empty(), inside(EMPTY_BAY)); + + assertTrue(dirty(EDITABLE_BAY)); + assertFalse(dirty(SECOND_EDITABLE_BAY)); + assertFalse(dirty(EMPTY_BAY)); + } + + @Test + public void aTeleportMakesTheStudioReconcileTheArrivalAtOnceAndEnteringAloneDoesNot() { + listener.entered(owner); + assertTrue(owner.sidebars.isEmpty()); + + listener.teleported(owner, inside(EDITABLE_BAY)); + + assertFalse(owner.sidebars.isEmpty()); + assertTrue(owner.sidebars.getLast().stream() + .map(ToolText::plainText).anyMatch(line -> line.startsWith("Workcell: "))); + } + + @Test + public void aChunkIsLoadedWhenThePlatformSaysSo() { + world.unloadedChunks.add(new ChunkPos(3, 4)); + + assertTrue(studio.isChunkLoaded(0, 0)); + assertFalse(studio.isChunkLoaded(3, 4)); + } + + @Test + public void aToolIsNotGivenWhenTheInventoryIsFullAndThePlayerIsToldSo() { + JigsawStudioToolPayload payload = JigsawStudioToolPayload.request(JigsawStudioToolAction.PREVIEW_GRAPH, requestId); + owner.inventoryFull = true; + + assertFalse(service.giveTool(owner, payload)); + + assertTrue(owner.given.isEmpty()); + assertEquals( + List.of("[Iris Jigsaw Studio] Your inventory is full; no Jigsaw Studio tool was added."), + owner.messages); + } + + @Test + public void aToolThatFitsIsGivenAndAnnounced() { + JigsawStudioToolPayload payload = JigsawStudioToolPayload.request(JigsawStudioToolAction.PREVIEW_GRAPH, requestId); + + assertTrue(service.giveTool(owner, payload)); + + assertEquals(1, owner.given.size()); + assertEquals( + List.of("[Iris Jigsaw Studio] Added " + JigsawStudioToolAction.PREVIEW_GRAPH.displayName() + " tool."), + owner.messages); + } + + @Test + public void studioMessagesAreWhiteTextWithTheStudioPrefix() { + assertFalse(listener.blockChanging(change(Cause.PLACE, owner, inside(EMPTY_BAY)))); + + assertEquals( + List.of(ToolText.plain("[Iris Jigsaw Studio] This empty Jigsaw Studio workcell has no loaded editable variant. Load one before editing it.")), + owner.texts); + } + @Test public void aMultiBlockChangeMarksTheBaysItTouchesByItsCause() { BlockPosition end = inside(EDITABLE_BAY); diff --git a/core/src/test/java/art/arcane/iris/core/service/StudioSVCJigsawProtectionTest.java b/core/src/test/java/art/arcane/iris/core/service/StudioSVCJigsawProtectionTest.java index fdb2dacc1..a7bcf6c44 100644 --- a/core/src/test/java/art/arcane/iris/core/service/StudioSVCJigsawProtectionTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/StudioSVCJigsawProtectionTest.java @@ -9,6 +9,7 @@ import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCompatibilityTarget; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode; import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariantCatalog; +import art.arcane.iris.engine.platform.PlatformChunkGenerator; import art.arcane.iris.util.common.plugin.VolmitSender; import com.volmit.ModuleLog; import org.bukkit.entity.Player; @@ -16,6 +17,7 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.io.File; import java.lang.reflect.Field; import java.util.Optional; import java.util.UUID; @@ -26,6 +28,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; @@ -85,6 +88,26 @@ public class StudioSVCJigsawProtectionTest { verify(project).close(); } + @Test + public void anOpenJigsawStudioIsTheOpenStudioProjectToEveryoneWhoAsks() { + JigsawStudioRequest request = activateOwnedStudio(); + AtomicBoolean closed = new AtomicBoolean(); + StudioSVC studio = new StudioSVC(); + StudioSlotOccupant occupant = occupantOf(request, closed); + studio.occupyStudioSlot(occupant, () -> CompletableFuture.completedFuture(null)).join(); + + assertFalse(studio.isProjectOpen()); + occupant.project().setActiveProvider(mock(PlatformChunkGenerator.class)); + assertTrue(studio.isProjectOpen()); + assertSame(occupant.project(), studio.getActiveProject()); + + jigsawService.tryBeginClose(request.requestId(), OWNER, false); + studio.close().join(); + occupant.project().setActiveProvider(null); + assertFalse(studio.isProjectOpen()); + assertNull(studio.getActiveProject()); + } + @Test public void ownerCanReplaceJigsawStudioThroughOrdinaryStudioOpen() { JigsawStudioRequest request = activateOwnedStudio(); @@ -118,7 +141,13 @@ public class StudioSVCJigsawProtectionTest { /** The occupant the Bukkit host makes of a tool world: it asks the studio and closes the world. */ private StudioSlotOccupant occupantOf(JigsawStudioRequest request, AtomicBoolean closed) { + IrisProject project = new IrisProject(new File("overworld")); return new StudioSlotOccupant() { + @Override + public IrisProject project() { + return project; + } + @Override public Optional closeRefusal() { return jigsawService.closeRefusal(request.requestId()); diff --git a/core/src/test/java/art/arcane/iris/engine/platform/studio/generators/JigsawStudioGeneratorTest.java b/core/src/test/java/art/arcane/iris/engine/platform/studio/generators/JigsawStudioGeneratorTest.java index ba6b40ea4..4ff06736f 100644 --- a/core/src/test/java/art/arcane/iris/engine/platform/studio/generators/JigsawStudioGeneratorTest.java +++ b/core/src/test/java/art/arcane/iris/engine/platform/studio/generators/JigsawStudioGeneratorTest.java @@ -543,6 +543,7 @@ public class JigsawStudioGeneratorTest { when(blocks.find(anyString())).thenAnswer(invocation -> Optional.of(BlockState.parse(invocation.getArgument(0)))); when(blocks.rotate(any(), any())).thenAnswer(invocation -> invocation.getArgument(0)); + when(blocks.tryRotate(any(), any())).thenAnswer(invocation -> Optional.of(invocation.getArgument(0))); } void piece(String key, IrisJigsawPiece piece) {