Give tools a platform-neutral world api and let modules ask each other's services

PackWorld, ValidationContext and ToolPack answer services(type) with the pack's providers.
com.volmit.tooling.world lets a tool open a painter-backed world and drive its players,
menus, items and block changes; ToolPack.worlds() and Sender.player() reach it. The Bukkit
adapter implements it over the studio world creation with a painter slot keyed by world,
one protection listener, VolmLib menus, persistent-data items and BoardSVC sidebars. Other
platforms answer that tool worlds are not supported yet.
This commit is contained in:
piexel committed 2026-11-08 15:30:39 +01:00
1 parent a81a3abb9f
commit 3691611c6c
76 files changed
+4533 -23

No files matched your search

@@ -0,0 +1,14 @@
package com.volmit.geometry;
import java.util.Objects;
/** A chunk column, by chunk coordinates: block X and Z divided by 16, rounded down. */
public record ChunkPos(int x, int z) {
private static final int CHUNK_SHIFT = 4;
/** The chunk that contains {@code block}. */
public static ChunkPos containing(BlockPosition block) {
Objects.requireNonNull(block, "block");
return new ChunkPos(block.x() >> CHUNK_SHIFT, block.z() >> CHUNK_SHIFT);
}
}
@@ -1,5 +1,6 @@
package com.volmit.tooling;
import com.volmit.tooling.world.ToolPlayer;
import java.util.Optional;
/**
@@ -21,4 +22,7 @@ public interface Sender {
/** The platform's own sender as {@code type}, such as a Bukkit {@code Player}; empty when it is not one. For platform parts. */
<T> Optional<T> extension(Class<T> type);
/** The sender as a player of the platform; empty for the console, a command block, or a platform without tool worlds. */
Optional<ToolPlayer> player();
}
@@ -3,8 +3,10 @@ package com.volmit.tooling;
import com.volmit.ModuleLog;
import com.volmit.config.PackSettings;
import com.volmit.resource.PackResources;
import com.volmit.tooling.world.ToolWorlds;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
/**
* A pack as tools see it: its current resources, its folder, and the one way to change files in it. Tools are file tools,
@@ -32,4 +34,17 @@ public interface ToolPack {
/** The log of the module that asked. */
ModuleLog log();
/** The worlds this pack's tools open on the platform. */
ToolWorlds worlds();
/**
* The providers of {@code service} that the pack's modules registered, in module id order and each module's in the
* order it registered them; empty when no module provides it. This is how a module asks another module's service,
* such as a structure tool asking who knows a structure.
*
* @param service an interface marked {@link com.volmit.service.Service}
* @throws IllegalArgumentException when {@code service} is not such an interface
*/
<S> List<S> services(Class<S> service);
}
@@ -0,0 +1,58 @@
package com.volmit.tooling.world;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockPosition;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* Something that is about to change blocks in a tool world, handed to {@link ToolWorldListener#blockChanging}.
*
* @param cause what is changing them
* @param positions the blocks that change, at least one: the block a player breaks or places, the blocks an explosion
* would destroy one at a time, all the blocks a piston would move together
* @param player the player behind it, when there is one
* @param placed the state being placed, for {@link Cause#PLACE} and {@link Cause#BUCKET}; empty when it is not known
*/
public record BlockChange(Cause cause, List<BlockPosition> positions, Optional<ToolPlayer> player, Optional<BlockState> placed) {
/** What changes a block. */
public enum Cause {
/** A player places a block. */
PLACE,
/** A player breaks a block. */
BREAK,
/** A player fills or empties a bucket. */
BUCKET,
/** A block forms, fades or spreads by itself, such as ice, snow, grass or coral. */
PHYSICS,
/** Water or lava flows. */
FLUID,
/** A plant or a sapling grows. */
GROWTH,
/** A block burns. */
FIRE,
/** Redstone power changes; cancelling keeps the old power. */
REDSTONE,
/** A piston pushes or pulls blocks. */
PISTON,
/** An explosion destroys blocks. */
EXPLOSION,
/** A mob or a falling block changes a block. */
ENTITY,
/** A player or a hopper changes what a container block holds. */
CONTAINER,
/** A furnace, a brewing stand, a crafter or a dispenser works. */
MACHINE
}
public BlockChange {
Objects.requireNonNull(cause, "cause");
positions = List.copyOf(positions);
if (positions.isEmpty()) {
throw new IllegalArgumentException("A block change names at least one block");
}
Objects.requireNonNull(player, "player");
Objects.requireNonNull(placed, "placed");
}
}
@@ -0,0 +1,30 @@
package com.volmit.tooling.world;
import com.volmit.block.BlockState;
import com.volmit.object.BlockEntityData;
/**
* The chunk a {@link ChunkPainter} paints: blocks only, with the host's own block-entity handling behind it. A canvas
* starts empty (air) and is valid only while {@link ChunkPainter#paint} runs; the host never lets a painter keep it.
*
* <p>X and Z are local to the chunk, 0 to 15. Y is the world's own Y, from {@link #minY()} up to but not including
* {@link #maxY()}, as {@link ToolWorld#minY()} and {@link ToolWorld#maxY()} report it. A coordinate outside these
* ranges throws {@link IllegalArgumentException}.
*/
public interface ChunkCanvas {
/** The lowest Y a block can have in this world. */
int minY();
/** The first Y above the world; the highest block has Y {@code maxY() - 1}. */
int maxY();
/** Puts {@code state} at the position, replacing what the painter put there before. */
void set(int x, int y, int z, BlockState state);
/**
* Puts {@code state} at the position with {@code data} as its block entity, such as the contents of a chest or the
* lines of a sign. The host applies the entity once the chunk is live; a state that has no block entity on the
* platform ignores the data. Data in a format the host does not read fails with {@link IllegalArgumentException}.
*/
void set(int x, int y, int z, BlockState state, BlockEntityData data);
}
@@ -0,0 +1,16 @@
package com.volmit.tooling.world;
/**
* Where the chunks of a tool world come from: the host asks it for every chunk it generates, and for the ones
* {@link ToolWorld#repaint} names. Nothing else shapes a tool world's terrain.
*
* <p>The host calls {@code paint} from its generation threads, several at once, and again for a chunk whenever it
* repaints it, so a painter holds no per-call state and reads what it paints from state that is safe to read from any
* thread. It must return quickly and must not call back into the {@link ToolWorld} that is waiting for it. A painter
* that throws leaves its chunk empty and the failure in the host's log.
*/
@FunctionalInterface
public interface ChunkPainter {
/** Paints chunk {@code chunkX}, {@code chunkZ} onto {@code canvas}. */
void paint(int chunkX, int chunkZ, ChunkCanvas canvas);
}
@@ -0,0 +1,21 @@
package com.volmit.tooling.world;
import java.util.Objects;
import java.util.function.Consumer;
/**
* One slot of a {@link ToolMenu}.
*
* @param slot the slot counted along the rows from the top left, 0 to 8 in the first row, 9 to 17 in the second
* @param icon what the slot shows
* @param action called on the player's thread for every click on the slot; it must return quickly
*/
public record MenuButton(int slot, ToolItem icon, Consumer<MenuClick> action) {
public MenuButton {
if (slot < 0) {
throw new IllegalArgumentException("A menu slot is not negative: " + slot);
}
Objects.requireNonNull(icon, "icon");
Objects.requireNonNull(action, "action");
}
}
@@ -0,0 +1,14 @@
package com.volmit.tooling.world;
import java.util.Objects;
/**
* A click on a {@link MenuButton}. A left click has {@code right} false; holding shift is {@code shift}.
*
* @param player the player who clicked
*/
public record MenuClick(ToolPlayer player, boolean right, boolean shift) {
public MenuClick {
Objects.requireNonNull(player, "player");
}
}
@@ -0,0 +1,21 @@
package com.volmit.tooling.world;
/**
* One dust particle at a position of a tool world, for {@link ToolPlayer#particles}. The position is in world
* coordinates with the world's own Y.
*
* @param rgb the colour as {@code 0xRRGGBB}
* @param size the size of the speck, above zero
*/
public record Particle(double x, double y, double z, int rgb, float size) {
private static final int MAX_RGB = 0xFFFFFF;
public Particle {
if (rgb < 0 || rgb > MAX_RGB) {
throw new IllegalArgumentException("A particle colour is 0xRRGGBB: " + Integer.toHexString(rgb));
}
if (!(size > 0)) {
throw new IllegalArgumentException("A particle size is above zero: " + size);
}
}
}
@@ -0,0 +1,26 @@
package com.volmit.tooling.world;
import com.volmit.resource.ResourceId;
import java.util.List;
import java.util.Objects;
/**
* An item a tool hands to a player, or a menu shows as an icon: the platform's item, a name and lore, and a payload the
* host keeps on the item. The host guarantees the payload survives on the item, as a string in the item's persistent
* data on Bukkit and as custom data on modded platforms, and hands it back through {@link ToolPlayer#held()} and
* {@link ToolUse#item()}. A tool tells its own items apart by their payload.
*
* @param item the platform's item, such as {@code minecraft:stick}
* @param name the display name as plain text; empty keeps the item's own name
* @param lore the lines under the name, plain text
* @param glowing whether the item shows the enchantment glint
* @param payload what the tool keeps on the item; empty for nothing
*/
public record ToolItem(ResourceId item, String name, List<String> lore, boolean glowing, String payload) {
public ToolItem {
Objects.requireNonNull(item, "item");
Objects.requireNonNull(name, "name");
Objects.requireNonNull(payload, "payload");
lore = List.copyOf(lore);
}
}
@@ -0,0 +1,41 @@
package com.volmit.tooling.world;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
/**
* A chest-style menu a tool opens for a player with {@link ToolPlayer#openMenu}. Menus are the host's own inventory
* windows, so they work the same on every platform; a tool that wants another page opens a new menu from a click.
*
* @param title the title as plain text; the host shortens it to what the window can show
* @param rows the number of rows, 1 to {@value #MAX_ROWS}
* @param buttons the slots that do something; the others show a filler. No slot is used twice and every slot is inside
* the rows.
* @param onClose called on the player's thread when the menu closes for any reason: the player closed it, the world
* closed, or the tool closed or replaced it. Null stands for nothing to do.
*/
public record ToolMenu(String title, int rows, List<MenuButton> buttons, Runnable onClose) {
public static final int MAX_ROWS = 6;
public static final int SLOTS_PER_ROW = 9;
public ToolMenu {
Objects.requireNonNull(title, "title");
if (rows < 1 || rows > MAX_ROWS) {
throw new IllegalArgumentException("A menu has 1 to " + MAX_ROWS + " rows: " + rows);
}
buttons = List.copyOf(buttons);
var used = new HashSet<Integer>();
for (var button : buttons) {
if (button.slot() >= rows * SLOTS_PER_ROW) {
throw new IllegalArgumentException("Slot " + button.slot() + " is outside a menu of " + rows + " rows");
}
if (!used.add(button.slot())) {
throw new IllegalArgumentException("Slot " + button.slot() + " is used twice");
}
}
if (onClose == null) {
onClose = () -> { };
}
}
}
@@ -0,0 +1,86 @@
package com.volmit.tooling.world;
import com.volmit.geometry.BlockPosition;
import com.volmit.resource.ResourceId;
import com.volmit.tooling.Sender;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
/**
* A player as a tool sees them. Positions are block positions of the world the player stands in, with that world's own Y.
*
* <p>Threads. The readers ({@link #world}, {@link #position}, {@link #yaw}, {@link #pitch}, {@link #sneaking},
* {@link #held}) are valid only on the thread that owns the player, which is where every {@link ToolWorldListener} call
* about them and every {@link #run} task runs. The methods that change the player ({@link #teleport} and the ones
* below it) are safe from any thread: the host moves the change onto the owning thread. A player stays one object for
* as long as they are online, though {@link #id()} is the safer key for a map.
*/
public interface ToolPlayer {
UUID id();
/** The player's name as the platform shows it. */
String name();
/** The player as a command sender; its messages are plain text, delivered on the thread the platform needs. */
Sender sender();
/** The tool world the player stands in; empty when they stand in another world, even another pack's tool world. */
Optional<ToolWorld> world();
BlockPosition position();
/** The direction the player faces, in degrees, as the platform counts them. */
float yaw();
float pitch();
boolean sneaking();
/** Runs {@code task} on the thread that owns the player: at once when the caller is that thread, else later. */
void run(Runnable task);
/**
* Moves the player to the position in {@code world} and completes with whether they arrived. The host remembers
* where a player came from when they enter a tool world from outside one, and {@link ToolWorld#close()} sends them
* back there.
*/
CompletableFuture<Boolean> teleport(ToolWorld world, double x, double y, double z, float yaw, float pitch);
/**
* Puts the player in creative mode when {@code on}, remembering the mode they had; turns it off by restoring that
* mode. The host also restores it when it sends the player out of a tool world.
*/
void creative(boolean on);
/** Shows {@code text} above the hotbar. */
void actionBar(String text);
/** Plays {@code sound}, such as {@code minecraft:block.note_block.pling}, to this player only, where they stand. */
void sound(ResourceId sound, float volume, float pitch);
/**
* Shows a sidebar with {@code title} and {@code lines}, top to bottom, replacing the one this player has from a tool.
* Text is plain: the host removes formatting codes. The sidebar goes away when the player leaves the tool world.
*/
void sidebar(String title, List<String> lines);
/** Removes the sidebar {@link #sidebar} showed. */
void hideSidebar();
/** Shows dust particles to this player only. Positions are in the world the player stands in. */
void particles(List<Particle> dust);
/** Puts {@code item} in the player's inventory, in the first free slot. */
void give(ToolItem item);
/** The tool item in the player's main hand; empty when the held item is not one, which is when it carries no payload. */
Optional<ToolItem> held();
/** Opens {@code menu} for the player, closing the menu they had open. */
void openMenu(ToolMenu menu);
/** Closes the menu a tool opened for the player; does nothing when none is open. */
void closeMenu();
}
@@ -0,0 +1,36 @@
package com.volmit.tooling.world;
import com.volmit.geometry.BlockFace;
import com.volmit.geometry.BlockPosition;
import java.util.Objects;
import java.util.Optional;
/**
* A player using their hand in a tool world, handed to {@link ToolWorldListener#used}.
*
* @param hand the hand that was used
* @param action what the player did
* @param item the tool item in that hand; empty when the item is not one
* @param block the block clicked; empty for a click in the air
* @param face the face of the block clicked; empty for a click in the air
*/
public record ToolUse(Hand hand, Action action, Optional<ToolItem> item, Optional<BlockPosition> block, Optional<BlockFace> face) {
public enum Hand { MAIN, OFF }
public enum Action {
LEFT_CLICK_AIR,
LEFT_CLICK_BLOCK,
RIGHT_CLICK_AIR,
RIGHT_CLICK_BLOCK,
/** Stepping on a pressure plate, trampling farmland, touching a tripwire. */
PHYSICAL
}
public ToolUse {
Objects.requireNonNull(hand, "hand");
Objects.requireNonNull(action, "action");
Objects.requireNonNull(item, "item");
Objects.requireNonNull(block, "block");
Objects.requireNonNull(face, "face");
}
}
@@ -0,0 +1,84 @@
package com.volmit.tooling.world;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockPosition;
import com.volmit.geometry.ChunkPos;
import com.volmit.object.BlockEntityData;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
/**
* One open tool world. Every position here is a block of the world itself: X and Z are world coordinates and Y is the
* world's own Y, from {@link #minY()} up to but not including {@link #maxY()}. That is not the height above the
* dimension's bottom that {@link com.volmit.world.PackWorld} uses.
*
* <p>Threads. A host may split a world across threads, one for each region of it, as Folia does. {@link #owns} tells
* whether the calling thread owns a position; reading and writing blocks is allowed only there, and {@link #run} and
* {@link #call} get a task onto the owning thread from any other. Everything else here is safe from any thread.
*/
public interface ToolWorld {
/** The name the tool gave in {@link ToolWorldSpec#name()}. Still answers after the world closed. */
String name();
/** The lowest Y of the world. */
int minY();
/** The first Y above the world. */
int maxY();
/** The players standing in this world now, a snapshot. */
List<ToolPlayer> players();
/** Whether the calling thread owns the block at {@code at}, so that it may read and write it. */
boolean owns(BlockPosition at);
/**
* Runs {@code task} on the thread that owns {@code at}: at once when the caller is that thread, else later. A
* task that throws is logged by the host.
*/
void run(BlockPosition at, Runnable task);
/** Runs {@code task} like {@link #run} and completes with its result, or fails with what it threw. */
<T> CompletableFuture<T> call(BlockPosition at, Supplier<T> task);
/**
* The block at {@code at}. The state is complete, with every property.
*
* @throws IllegalStateException when the calling thread does not own {@code at}, or the world closed
*/
BlockState block(BlockPosition at);
/**
* The block entity at {@code at}; empty when the block has none.
*
* @throws IllegalStateException when the calling thread does not own {@code at}, or the world closed
*/
Optional<BlockEntityData> blockEntity(BlockPosition at);
/**
* Replaces the block at {@code at} with {@code state} and {@code data} as its block entity, without block updates
* or {@link ToolWorldListener#blockChanging} calls, since the tool is the one changing it. Empty data leaves the
* new block with the platform's default entity, if its state has one.
*
* @throws IllegalStateException when the calling thread does not own {@code at}, or the world closed
*/
void setBlock(BlockPosition at, BlockState state, Optional<BlockEntityData> data);
/**
* Runs the painter again for {@code chunks}, writes the differences into the live chunks and sends them to the
* players. Block entities the painter sets replace those of the chunk. The future completes on a host thread when
* every chunk is written, and fails if one could not be; chunks written before the failure stay written.
*/
CompletableFuture<Void> repaint(Collection<ChunkPos> chunks);
/**
* Closes the world: sends every player back to where they were before they entered a tool world, restoring their
* game mode, then unloads the world and deletes its files. {@link ToolWorldListener#closed()} is called once it
* is unloaded. Closing a closed world completes at once. The future fails when the world could not be unloaded or
* deleted; the host then deletes what is left when it starts next.
*/
CompletableFuture<Void> close();
}
@@ -0,0 +1,58 @@
package com.volmit.tooling.world;
import com.volmit.geometry.BlockPosition;
import java.util.Optional;
/**
* What a tool hears about its world. Every method has a default that does nothing, so a tool implements only the ones
* it needs.
*
* <p>Threads. A call runs on the thread that owns the player or the position it is about, and the host waits for it:
* return quickly, and hand slow work to another thread. The host calls only for the tool's own world. A listener that
* throws is logged by the host and counts as having answered with the method's default.
*
* <p>The methods that return a boolean decide whether the host lets the thing happen: {@code false} cancels it.
*/
public interface ToolWorldListener {
/** A player came into the world: joined the server in it, teleported or changed world into it, or respawned in it. Once for each stay. */
default void entered(ToolPlayer player) {
}
/** A player left the world: quit, teleported or changed world out of it. Once for each stay. */
default void left(ToolPlayer player) {
}
/** A player moved to another block of the world; not called for moves inside one block. */
default void moved(ToolPlayer player, BlockPosition to) {
}
/** A player started or stopped sneaking. */
default void sneakToggled(ToolPlayer player, boolean sneaking) {
}
/** A player used their hand. Return {@code false} to cancel what the platform would do with it, such as opening a container or placing a block. */
default boolean used(ToolPlayer player, ToolUse use) {
return true;
}
/** Something is about to change blocks. Return {@code false} to cancel it. The default freezes the world. */
default boolean blockChanging(BlockChange change) {
return false;
}
/**
* A command is about to run: {@code line} is what was typed without the leading slash. {@code sender} is empty for the
* console, which is asked on behalf of every tool world that is open. Return {@code false} to cancel it.
*/
default boolean command(Optional<ToolPlayer> sender, String line) {
return true;
}
/** A chunk of the world finished loading, painted or read back. */
default void chunkLoaded(int chunkX, int chunkZ) {
}
/** The world was unloaded and is gone; nothing can be done with it any more. */
default void closed() {
}
}
@@ -0,0 +1,29 @@
package com.volmit.tooling.world;
import java.util.Objects;
import java.util.regex.Pattern;
/**
* What a tool asks {@link ToolWorlds#open} for: a world of the tool's pack whose chunks come only from {@code painter},
* and who hears about it.
*
* <p>The host opens it as a studio world of the tool's pack with its generation swapped for the painter, so its height
* range is the pack dimension's; {@link ToolWorld#minY()} and {@link ToolWorld#maxY()} report it.
*
* @param name the tool's name for the world, unique among the open tool worlds of the pack: lower case letters,
* digits, {@code _} and {@code -}, starting with a letter or a digit. It is not the platform's world name.
* @param painter the only source of the world's chunks
* @param listener told about the players, blocks and commands of the world
*/
public record ToolWorldSpec(String name, ChunkPainter painter, ToolWorldListener listener) {
private static final Pattern NAME = Pattern.compile("[a-z0-9][a-z0-9_-]*");
public ToolWorldSpec {
Objects.requireNonNull(name, "name");
Objects.requireNonNull(painter, "painter");
Objects.requireNonNull(listener, "listener");
if (!NAME.matcher(name).matches()) {
throw new IllegalArgumentException("A tool world name is lower case letters, digits, '_' and '-': " + name);
}
}
}
@@ -0,0 +1,26 @@
package com.volmit.tooling.world;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
/**
* The tool worlds of one pack: worlds a tool opens to show or edit what it builds, such as a jigsaw studio. Reached
* through {@link com.volmit.tooling.ToolPack#worlds()}. A platform without tool worlds still answers: {@link #open}
* then returns a failed future and {@link #find} an empty result.
*
* <p>Safe to call from any thread, the server's main thread included.
*/
public interface ToolWorlds {
/**
* Opens a world whose chunks come only from {@code spec.painter()}. The future completes, on a host thread, when
* players can enter the world. It fails with {@link IllegalStateException} when a tool world of that name is open
* already, and with the cause when the platform cannot create the world; a failed open leaves no world behind.
* The host closes every tool world it still has open when it shuts down.
*
* <p>A tool world has no natural mob spawning, weather, daylight cycle, portals, vanilla structures or features.
*/
CompletableFuture<ToolWorld> open(ToolWorldSpec spec);
/** The open tool world of this pack called {@code name}; empty when none is open or it closed. */
Optional<ToolWorld> find(String name);
}
@@ -4,6 +4,7 @@ import com.volmit.config.PackSettings;
import com.volmit.resource.PackResources;
import com.volmit.resource.PlatformRegistries;
import java.util.List;
import java.util.Optional;
/** The pack one {@link Validator} checks, as the host would load it, and where it reports what it finds. Valid
@@ -25,6 +26,16 @@ public interface ValidationContext {
*/
Optional<PlatformRegistries> platform();
/**
* The providers of {@code service} that the pack's modules registered, in module id order and each module's in the
* order it registered them; empty when no module provides it. This is how a validator asks another module, such as
* whether a module knows a structure the pack names.
*
* @param service an interface marked {@link com.volmit.service.Service}
* @throws IllegalArgumentException when {@code service} is not such an interface
*/
<S> List<S> services(Class<S> service);
/** Records {@code problem}. An {@link Severity#ERROR} stops the pack from loading once every validator has run. */
void report(Problem problem);
}
@@ -6,6 +6,7 @@ import com.volmit.placement.Placements;
import com.volmit.random.WorldRandom;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
@@ -87,4 +88,15 @@ public interface PackWorld {
default <T> Optional<T> extension(Class<T> type) {
return Optional.empty();
}
/**
* The providers of {@code service} that the pack's modules registered, in module id order and each module's in the
* order it registered them; empty when no module provides it. This is how a module asks another module's service,
* such as a placement asking who builds a structure. A provider takes the world as the first argument of its
* methods, so pass this one. The list does not change while the world runs.
*
* @param service an interface marked {@link com.volmit.service.Service}
* @throws IllegalArgumentException when {@code service} is not such an interface
*/
<S> List<S> services(Class<S> service);
}
@@ -0,0 +1,105 @@
package com.volmit.tooling.world;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockPosition;
import com.volmit.geometry.ChunkPos;
import com.volmit.resource.ResourceId;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ToolWorldRecordsTest {
private static final ResourceId STICK = ResourceId.parse("minecraft:stick");
private static final ToolItem ICON = new ToolItem(STICK, "Tool", List.of("line"), false, "");
@Test
void aChunkIsTheBlockCoordinatesDividedBySixteenRoundedDown() {
assertEquals(new ChunkPos(0, 0), ChunkPos.containing(new BlockPosition(15, 70, 0)));
assertEquals(new ChunkPos(1, -1), ChunkPos.containing(new BlockPosition(16, 0, -1)));
assertEquals(new ChunkPos(-2, -1), ChunkPos.containing(new BlockPosition(-17, 0, -16)));
}
@Test
void aToolWorldNameIsLowerCaseWordsOfLettersDigitsUnderscoresAndDashes() {
ChunkPainter painter = (x, z, canvas) -> { };
var listener = new ToolWorldListener() { };
assertEquals("jigsaw-1_a", new ToolWorldSpec("jigsaw-1_a", painter, listener).name());
assertThrows(IllegalArgumentException.class, () -> new ToolWorldSpec("Jigsaw", painter, listener));
assertThrows(IllegalArgumentException.class, () -> new ToolWorldSpec("two words", painter, listener));
assertThrows(IllegalArgumentException.class, () -> new ToolWorldSpec("", painter, listener));
assertThrows(IllegalArgumentException.class, () -> new ToolWorldSpec("-dash", painter, listener));
assertThrows(NullPointerException.class, () -> new ToolWorldSpec("name", null, listener));
assertThrows(NullPointerException.class, () -> new ToolWorldSpec("name", painter, null));
}
@Test
void aToolItemKeepsItsOwnCopyOfTheLore() {
var lore = new ArrayList<>(List.of("one"));
var item = new ToolItem(STICK, "Name", lore, true, "payload");
lore.add("two");
assertEquals(List.of("one"), item.lore());
assertThrows(UnsupportedOperationException.class, () -> item.lore().add("three"));
assertThrows(NullPointerException.class, () -> new ToolItem(STICK, "Name", List.of(), false, null));
}
@Test
void aMenuHasOneToSixRowsAndEveryButtonInsideThemOnItsOwnSlot() {
var button = new MenuButton(17, ICON, click -> { });
assertEquals(1, new ToolMenu("t", 1, List.of(new MenuButton(8, ICON, click -> { })), null).rows());
assertEquals(2, new ToolMenu("t", 2, List.of(button), null).rows());
assertThrows(IllegalArgumentException.class, () -> new ToolMenu("t", 0, List.of(), null));
assertThrows(IllegalArgumentException.class, () -> new ToolMenu("t", 7, List.of(), null));
assertThrows(IllegalArgumentException.class, () -> new ToolMenu("t", 1, List.of(button), null), "slot 17 is in the second row");
assertThrows(IllegalArgumentException.class,
() -> new ToolMenu("t", 2, List.of(button, new MenuButton(17, ICON, click -> { })), null));
assertThrows(IllegalArgumentException.class, () -> new MenuButton(-1, ICON, click -> { }));
}
@Test
void aMenuWithoutAnOnCloseHasOneThatDoesNothing() {
var closed = new AtomicBoolean();
var withHandler = new ToolMenu("t", 1, List.of(), () -> closed.set(true));
var without = new ToolMenu("t", 1, List.of(), null);
without.onClose().run();
assertFalse(closed.get());
withHandler.onClose().run();
assertTrue(closed.get());
}
@Test
void aBlockChangeNamesAtLeastOneBlock() {
var position = new BlockPosition(1, 2, 3);
var change = new BlockChange(BlockChange.Cause.PLACE, List.of(position), Optional.empty(),
Optional.of(BlockState.parse("minecraft:stone")));
assertEquals(List.of(position), change.positions());
assertThrows(IllegalArgumentException.class,
() -> new BlockChange(BlockChange.Cause.BREAK, List.of(), Optional.empty(), Optional.empty()));
}
@Test
void aListenerThatImplementsNothingFreezesTheWorldAndAllowsEverythingElse() {
var listener = new ToolWorldListener() { };
var change = new BlockChange(BlockChange.Cause.PISTON, List.of(new BlockPosition(0, 0, 0)), Optional.empty(), Optional.empty());
assertFalse(listener.blockChanging(change));
assertTrue(listener.command(Optional.empty(), "gamemode creative"));
}
@Test
void aParticleHasAnRgbColourAndAPositiveSize() {
assertEquals(0xFF00FF, new Particle(0, 0, 0, 0xFF00FF, 1.5F).rgb());
assertThrows(IllegalArgumentException.class, () -> new Particle(0, 0, 0, 0x1000000, 1F));
assertThrows(IllegalArgumentException.class, () -> new Particle(0, 0, 0, -1, 1F));
assertThrows(IllegalArgumentException.class, () -> new Particle(0, 0, 0, 0, 0F));
assertThrows(IllegalArgumentException.class, () -> new Particle(0, 0, 0, 0, Float.NaN));
}
}