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

+3 -2
View File
@@ -41,13 +41,14 @@ types that carry them and lists what the Iris adapter still owes.
| Module-owned pack checks | `Validator`, `ValidationContext`, `Problem`, `Severity`, `Subject`, `FeatureRegistry.registerValidator`, host `FeatureCatalog.validators()` |
| Per-world module state | `PackWorld` (`state`), `InvocationContext.world()`, host `WorldStates` |
| Module lifecycle across loads, hotloads and reloads | `ModuleLifecycle`, `PackContext`, `FeatureRegistry.registerLifecycle`, host `FeatureCatalog.lifecycles()`, `LifecycleRunner` |
| Host questions answered by modules | `@Service`, `Providers`, `FeatureRegistry.registerService`, host `FeatureCatalog.services(type)` / `service(type)`; services `ObjectsAt`, `StructureLocator` (`LocateResult`, `startedStructures`, `locatableStarts`, `locateStart`, `ChunkFilter`), `SaplingGrowth`, `Loot` (with `shuffleSeed`), `BlockDrops`, `EntitySpawns`, `CaveBiomes`, `ProtectedFloor`, `AmbientEffects`, `VanillaFeatures` (`DecorationStep`); values `ItemDrop`, `EntitySpec`, `ItemRegistry` (`PackResources.items()`) |
| Host questions answered by modules | `@Service`, `Providers`, `FeatureRegistry.registerService`, host `FeatureCatalog.services(type)` / `service(type)`; modules ask each other with `PackWorld.services(type)`, `ValidationContext.services(type)` and `ToolPack.services(type)` (host `ModuleWorld` forwards to the host's world); services `ObjectsAt`, `StructureLocator` (`LocateResult`, `startedStructures`, `locatableStarts`, `locateStart`, `ChunkFilter`), `SaplingGrowth`, `Loot` (with `shuffleSeed`), `BlockDrops`, `EntitySpawns`, `CaveBiomes`, `ProtectedFloor`, `AmbientEffects`, `VanillaFeatures` (`DecorationStep`); values `ItemDrop`, `EntitySpec`, `ItemRegistry` (`PackResources.items()`) |
| Terrain and settings sampling | `TerrainSampler`, `BiomeSample`, `TerrainSample`, `FeatureSettings` |
| Dense chunk output | `Hunk<T>`, `GenerationContext.blocks`, reference `ArrayHunk<T>` |
| Positions, boxes and faces | `com.volmit.geometry`: `BlockPosition`, `BlockBox`, `BlockFace` |
| Sparse geometry | `GeneratedObject` |
| Studio views of what a module builds | `com.volmit.tooling`: `ModuleSetup.tooling()` (`ToolingRegistry.registerView`), sealed `StudioView` (`SceneView` with `SceneEntry`, `PatternView` with `PatternEntry`, `PatternArea`, `BlockPattern`), `EditableSceneView` (`SceneFile`, `NodeGraph`, `GraphNode` with `Link`, `NodeSettings`, `Edits`, `Addition`), `JsonText`, `JsonPath` (`Key`, `Index`), host `StudioViewRegistration` |
| Commands of a module | `com.volmit.tooling`: `ToolingRegistry.registerCommand`, immutable `Command` (`named`, `alias`, `describe`, `child`, `argument`, `runs`, `openToEveryone`), typed `Argument` (`word`, `text`, `integer`, `decimal`, `flag`, `choice`, `resource`, `registered`, `orElse`, `suggesting`), `CommandAction`, `CommandContext` (`get`, `sender`, `pack`, `world`, `platform`), plain-text `Sender`, `ToolPack` (`edit` with `PackEdit`, `outputFolder`, `objects` with `ObjectCodec`), host `CommandRegistration` in `FeatureCatalog.commands()` |
| Commands of a module | `com.volmit.tooling`: `ToolingRegistry.registerCommand`, immutable `Command` (`named`, `alias`, `describe`, `child`, `argument`, `runs`, `openToEveryone`), typed `Argument` (`word`, `text`, `integer`, `decimal`, `flag`, `choice`, `resource`, `registered`, `orElse`, `suggesting`), `CommandAction`, `CommandContext` (`get`, `sender`, `pack`, `world`, `platform`), plain-text `Sender` (with `player()`), `ToolPack` (`edit` with `PackEdit`, `outputFolder`, `objects` with `ObjectCodec`, `worlds`, `services`), host `CommandRegistration` in `FeatureCatalog.commands()` |
| Worlds a tool opens | `com.volmit.tooling.world`, exposed to pack modules by host `ExposedPackages`: `ToolWorlds` (`open`, `find`) with `ToolWorldSpec`, `ChunkPainter` and `ChunkCanvas`, `ToolWorld` (`players`, `owns`, `run`, `call`, `block`, `blockEntity`, `setBlock`, `repaint`, `close`), `ToolPlayer` (`teleport`, `creative`, `actionBar`, `sound`, `sidebar`, `particles`, `give`, `held`, `openMenu`), `ToolItem`, `ToolMenu` with `MenuButton` and `MenuClick`, `Particle`, `ToolWorldListener` (`entered`, `left`, `moved`, `sneakToggled`, `used` with `ToolUse`, `blockChanging` with `BlockChange.Cause`, `command`, `chunkLoaded`, `closed`), `com.volmit.geometry.ChunkPos`; every Y is the world's own; implemented by each platform adapter (Bukkit; modded adapters answer with a failed `open`) |
| Buffered placement writes | `PlacementRequest`, `PlacementAccess`, host-owned `PlacementEdit` |
| Typed generation and persistent storage | `mantle` package |
+36 -1
View File
@@ -326,7 +326,8 @@ the part then gets the same `Class` objects the modules registered, where a sibl
defines into a `ClassCastException`. The caller opens and closes it; closing it never closes the pack's loader.
`ExposedPackages` carves out every `com.volmit.tooling.<platform>` package like `com.volmit.host`: only a part sees a
platform's tooling api. `com.volmit.tooling` itself, the neutral api, stays exposed. Enabling parts lazily, mounting their
platform's tooling api. `com.volmit.tooling` itself, the neutral api, stays exposed, and so does
`com.volmit.tooling.world`, the one neutral subpackage (Tool worlds). Enabling parts lazily, mounting their
commands and listeners, and disabling them belongs to the platform adapter, not to the host.
### Namespaces
@@ -1236,6 +1237,11 @@ from a sapling, which drops a block has. A module answers such questions through
- **Lookup.** The host asks the pack's catalog: `services(type)` for every provider, `service(type)` for the one
provider of a `ONE` service. Looking up a type that is not marked fails, and so does `service` for a service that may
have several providers.
- **Modules ask each other.** `PackWorld`, `ValidationContext` and `ToolPack` carry the same `services(type)`, so a
module reaches another module's service without a host extension. It returns the providers only, unscoped: the caller
passes the world it holds, and the provider's log is the host's concern when the host calls it, not the caller's.
`service(type)` for a `ONE` service is not repeated there, since `services(type).stream().findFirst()` says the same
and the api keeps one lookup.
- **Threading.** The host may call a provider from any thread, several at once. A provider that searches long
(`StructureLocator.locate`) is called off the server's main thread.
- **Loot, drops, entities, trees.** `Loot` (`ALL`) asks in two steps, which tables a container draws from and what a
@@ -1402,6 +1408,35 @@ the typed arguments; parsing, completion, permission and threads are the host's.
required one, and anything after a rest-of-line argument when the tree is built. Two modules claiming one root name or
alias fail the pack load, naming both.
## Tool worlds
`com.volmit.tooling.world` is what an in-world tool, the jigsaw studio first, needs from a platform and nothing more.
It exists so the tool lives in a module and runs on every platform: a tool that imported Bukkit could not.
- **The world is a studio world with a painter.** The host opens a studio world of the tool's pack and swaps its
generation for a `ChunkPainter`. That keeps one way to create, load, unload and delete worlds per platform, and the
platform's own height range, instead of a second kind of world. The cost is that heights are the pack dimension's.
- **Platform Y.** A tool world is not a `PackWorld`: it is the platform's world as players see it, so positions use the
world's own Y, and `minY()`/`maxY()` say its range. Converting to the height above the bottom would make every
position a tool shows a player disagree with the coordinates on their screen.
- **Painters are pure, listeners are threaded.** A painter is called from generation threads, so it reads shared state
only. A listener is called on the thread that owns the player or the position, so a module never needs a lock for
platform state, and `owns`/`run`/`call` exist for the rest. Splitting a world by region is the platform's right
(Folia); the api makes it visible instead of pretending to one thread.
- **Cancel by return value.** `blockChanging`, `used` and `command` return whether to allow. The host maps every platform
event onto `BlockChange.Cause` and cancels on `false`, so a tool freezes a bay or lets edits through without knowing which
event it was. The default for blocks is frozen: a world that forgets to answer cannot be damaged.
- **The host keeps the boring guarantees.** No natural spawning, weather, daylight, portals, vanilla structures or
features; players go back where they came from on close; the world is deleted on close and what is left is deleted at
the next start; an item's payload survives. A tool that had to do these itself would do them differently on every
platform.
- **Items, menus, sidebars are values.** `ToolItem`, `ToolMenu` and the sidebar lines are plain data the host draws with
its own widgets (VolmLib windows and scoreboards on Bukkit). No colour codes or components cross the api, for the
reason `Sender` has none.
- **A platform may not have it.** `ToolWorlds.open` then returns a failed future and `Sender.player()` is empty, so a tool
tells its user instead of failing at class loading. The package is exposed to pack modules, unlike the platform
packages below `com.volmit.tooling`.
## Not implemented
- Host wiring, which lives in Iris: JSON decoding and validation, rendering `PackSchema` into Iris's schema and
+47 -2
View File
@@ -471,6 +471,10 @@ final class RuinsObjects implements ObjectsAt {
and combines the answers), `FIRST` (the host asks in order until one answers) or `ONE` (at most one provider per
pack; a second fails the pack load, naming both modules). Providers are in module id order, each module's in
registration order.
- A module asks another module's service with `services(type)`, on the `PackWorld` a stage or service gets, on the
`ValidationContext` a validator gets and on the `ToolPack` a command gets. It returns the pack's providers in that
order, empty when no module provides the service, and fails with `IllegalArgumentException` for an interface that is
not a `@Service`. Pass the world you hold to the provider's methods.
| Service | Providers | What the host asks |
| --- | --- | --- |
@@ -573,6 +577,47 @@ private void info(CommandContext context) {
and writes pack objects in the host's object format (`ObjectCodec`).
- A root command's name and each alias are root names. One that another module of the pack took fails the pack load,
naming both modules. A host without commands, such as a build check, accepts the registration and ignores it.
- `Sender.player()` is the sender as a `ToolPlayer` (see Tool worlds), empty for the console and on a platform without
tool worlds.
## Tool worlds
A tool that shows or edits what it builds in a world, such as a jigsaw studio, opens a tool world through
`ToolPack.worlds()`, in `com.volmit.tooling.world`. The package is neutral, so the same tool runs on every platform that
implements it; a platform without tool worlds answers with a failed future.
```java
ToolWorlds worlds = context.pack().worlds();
ChunkPainter painter = (chunkX, chunkZ, canvas) -> {
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
canvas.set(x, canvas.minY() + 1, z, BlockState.parse("minecraft:smooth_stone"));
}
}
};
worlds.open(new ToolWorldSpec("scratch", painter, new ToolWorldListener() { }))
.thenAccept(world -> context.sender().player().ifPresent(player ->
player.teleport(world, 8, world.minY() + 2, 8, 0, 0)));
```
- The world's chunks come only from the `ChunkPainter`, which the host calls from its generation threads, several at once,
and again for `ToolWorld.repaint`. A painter keeps no per-call state and does not keep the `ChunkCanvas`. Block entities
go through `canvas.set(..., BlockEntityData)` and are applied once the chunk is live.
- It is a studio world of the tool's pack with generation swapped for the painter, so its height range is the pack
dimension's (`minY()`, `maxY()`). Every Y in this package is the world's own Y, not the height above the bottom that
`PackWorld` counts. There is no natural mob spawning, weather, daylight cycle, portal, vanilla structure or feature.
- `ToolWorldListener` is how the tool hears about the world: players entering, leaving and moving to another block,
sneaking, using their hand (`ToolUse`), commands, loaded chunks, and every change to blocks (`BlockChange` with a
`Cause`). Each method returns `true` to allow or `false` to cancel where it decides, and `blockChanging` freezes the
world unless the tool overrides it. Calls come on the thread that owns the player or the position, and must return
quickly.
- On a platform that splits a world across threads (Folia), `ToolWorld.owns(at)` says whether the calling thread may
touch the block, `run`/`call` get a task there, and `block`, `blockEntity` and `setBlock` fail with
`IllegalStateException` elsewhere. `ToolPlayer` readers are valid on the player's own thread (`ToolPlayer.run`); its
changing methods are safe from any thread.
- `ToolPlayer` also gives items (`ToolItem`, whose payload the host keeps on the item), a chest-style menu (`ToolMenu`
of `MenuButton`s), an action bar, a sidebar, sounds and dust `Particle`s. `ToolWorld.close()` sends every player back
to where they came from and deletes the world.
## Module jars
@@ -677,8 +722,8 @@ The host loads a part through its own class loader, `ToolingPartLoader`, a child
classes from the same jar copy, hands the platform's api packages to the platform's loader and everything else to the
pack's loader, so a part gets the same `Class` objects the modules registered. The adapter opens it
(`LoadedPack.openToolingPart`) and closes it before the pack; closing it leaves the pack's loader open. The generation
loader never sees `com.volmit.tooling.<platform>`, the platform parts of the tooling api; `com.volmit.tooling` itself stays
visible.
loader never sees `com.volmit.tooling.<platform>`, the platform parts of the tooling api; `com.volmit.tooling` itself and
the neutral `com.volmit.tooling.world` stay visible.
## Settings for studio
@@ -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));
}
}
@@ -13,7 +13,8 @@ import java.util.TreeSet;
* {@code com.volmitx}. The host side of IrisApi, {@code com.volmit.host}, lies inside the API's
* root package but is never exposed: it loads and runs modules, and no module may reach it. The
* platform packages of the tooling api, {@code com.volmit.tooling.<platform>}, are never exposed either:
* only a tooling part may use them. The neutral {@code com.volmit.tooling} stays exposed.
* only a tooling part may use them. The neutral {@code com.volmit.tooling} stays exposed, and so does the world api for
* tools, {@code com.volmit.tooling.world}, which every platform implements.
*/
final class ExposedPackages {
/** The root package of the Iris API. Module classes must not use it. */
@@ -22,6 +23,9 @@ final class ExposedPackages {
static final String HOST_PACKAGE = ExposedPackages.class.getPackageName();
/** The neutral tooling api. Each platform's own api is a subpackage of it, such as {@code com.volmit.tooling.bukkit}. */
static final String TOOLING_PACKAGE = API_PACKAGE + ".tooling";
/** The world api for tools, which every platform implements; it is neutral, so modules see it. */
static final String TOOL_WORLD_PACKAGE = TOOLING_PACKAGE + ".world";
private static final PackageName TOOL_WORLD = new PackageName(TOOL_WORLD_PACKAGE);
private static final PackageName API = new PackageName(API_PACKAGE);
private static final PackageName HOST = new PackageName(HOST_PACKAGE);
private static final PackageName TOOLING = new PackageName(TOOLING_PACKAGE);
@@ -77,9 +81,12 @@ final class ExposedPackages {
return !HOST.contains(dottedName) && packages.stream().anyMatch(name -> name.contains(dottedName));
}
/** Whether the package lies below {@code com.volmit.tooling}, where each platform's api has its package. */
/** Whether the package lies below {@code com.volmit.tooling}, where each platform's api has its package. The
* platform-neutral world api for tools, {@code com.volmit.tooling.world}, lies there too but is not a platform's.
*/
private static boolean isToolingPlatformPackage(String packageName) {
return TOOLING.contains(packageName);
boolean isToolWorldApi = packageName.equals(TOOL_WORLD_PACKAGE) || TOOL_WORLD.contains(packageName);
return TOOLING.contains(packageName) && !isToolWorldApi;
}
/** What precedes the last separator: the package of a class name, or the directory of a resource path. */
@@ -6,6 +6,7 @@ import com.volmit.placement.Placements;
import com.volmit.resource.PackResources;
import com.volmit.world.PackWorld;
import com.volmit.world.RunningWorld;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
@@ -72,6 +73,11 @@ final class ModuleWorld implements PackWorld {
return world.extension(type);
}
@Override
public <S> List<S> services(Class<S> service) {
return world.services(service);
}
@Override
public ModuleLog log() {
return log;
@@ -42,6 +42,8 @@ class ExposedPackagesTest {
assertTrue(exposed.exposes("com.volmit.tooling.Command$Builder"));
assertFalse(exposed.exposes("com.volmit.tooling.bukkit.BukkitToolPart"));
assertFalse(exposed.exposes("com.volmit.tooling.modded.deep.ModdedToolPart"));
assertTrue(exposed.exposes("com.volmit.tooling.world.ToolWorld"), "the world api for tools is neutral");
assertFalse(exposed.exposes("com.volmit.tooling.worldly.BukkitToolPart"));
assertTrue(exposed.exposes("com.volmit.toolingx.Other"));
assertTrue(exposed.exposes("com.volmit.tool.bukkit.Other"));
}
@@ -88,6 +88,7 @@ class ExtensionsTest {
public Optional<RunningWorld> running() { return Optional.empty(); }
public Placements placements() { throw new AssertionError("Unused placements"); }
public <T> T state(Class<T> type, Function<? super PackWorld, ? extends T> create) { return states.state(type, () -> create.apply(this)); }
public <S> List<S> services(Class<S> service) { return List.of(); }
public ModuleLog log() { return ModuleLogs.discarding(); }
@Override
@@ -0,0 +1,81 @@
package com.volmit.host;
import com.volmit.IrisModule;
import com.volmit.FeatureRegistry;
import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
import com.volmit.service.Providers;
import com.volmit.service.Service;
import com.volmit.support.TestWorld;
import com.volmit.world.PackWorld;
import java.util.List;
import java.util.function.Consumer;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** A module asks another module's service through the world: {@code PackWorld.services}, which the validation context and
* the tool pack answer the same way.
*/
class PackWorldServicesTest {
@Service(Providers.ALL)
interface Greeting { String greet(); }
@Service(Providers.ONE)
interface Clock { long now(); }
interface NotAService { void run(); }
private static void registerAs(ModuleRegistry registry, String moduleId, Consumer<FeatureRegistry> registrations) {
ModuleSetups.run(DiscoveredModule.builtIn(new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of(moduleId, "Test module " + moduleId, "1"); }
public void setup(ModuleSetup setup) { registrations.accept(setup.registry()); }
}), new StageGraphBuilder(), registry);
}
private static FeatureCatalog catalogOf(Greeting zeta, Greeting alphaFirst, Greeting alphaSecond) {
var registry = new ModuleRegistry();
registerAs(registry, "test:zeta", services -> services.registerService(Greeting.class, zeta));
registerAs(registry, "test:alpha", services -> {
services.registerService(Greeting.class, alphaFirst);
services.registerService(Greeting.class, alphaSecond);
});
return registry.freeze();
}
@Test
void aWorldAnswersWithTheProvidersOfItsPacksModulesInModuleIdOrder() {
Greeting zeta = () -> "zeta";
Greeting alphaFirst = () -> "alpha 1";
Greeting alphaSecond = () -> "alpha 2";
try (var world = new TestWorld(catalogOf(zeta, alphaFirst, alphaSecond))) {
assertEquals(List.of(alphaFirst, alphaSecond, zeta), world.services(Greeting.class));
}
}
@Test
void aServiceNobodyProvidesHasNoProviders() {
try (var world = new TestWorld(catalogOf(() -> "zeta", () -> "alpha 1", () -> "alpha 2"))) {
assertEquals(List.of(), world.services(Clock.class));
}
}
@Test
void anInterfaceThatIsNotAServiceIsRefused() {
try (var world = new TestWorld(catalogOf(() -> "zeta", () -> "alpha 1", () -> "alpha 2"))) {
assertThrows(IllegalArgumentException.class, () -> world.services(NotAService.class));
}
}
@Test
void theViewAModuleGetsOfAWorldAnswersLikeTheWorld() {
Greeting zeta = () -> "zeta";
Greeting alphaFirst = () -> "alpha 1";
Greeting alphaSecond = () -> "alpha 2";
var catalog = catalogOf(zeta, alphaFirst, alphaSecond);
try (var world = new TestWorld(catalog)) {
PackWorld view = catalog.registrations(Greeting.class).getFirst().scope(world);
assertNotSame(world, view);
assertEquals(world.services(Greeting.class), view.services(Greeting.class));
assertEquals(List.of(alphaFirst, alphaSecond, zeta), view.services(Greeting.class));
}
}
}
@@ -4,27 +4,38 @@ import com.volmit.IrisFeature;
import com.volmit.ModuleLog;
import com.volmit.config.PackSettings;
import com.volmit.config.SettingsStack;
import com.volmit.host.FeatureCatalog;
import com.volmit.host.ModuleLogs;
import com.volmit.host.WorldStates;
import com.volmit.placement.Placements;
import com.volmit.resource.PackResources;
import com.volmit.world.PackWorld;
import com.volmit.world.RunningWorld;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
/** A world for tests: the test seed, no resources, no declared settings, and a real state store. */
/** A world for tests: the test seed, no resources, no declared settings, a real state store, and the service providers of
* a catalog when it is given one.
*/
public final class TestWorld implements PackWorld, AutoCloseable {
private final WorldStates states;
private final ModuleLog log;
private final FeatureCatalog catalog;
public TestWorld() {
this(new WorldStates(), ModuleLogs.discarding());
this(null);
}
private TestWorld(WorldStates states, ModuleLog log) {
/** A world whose services are those {@code catalog} holds. */
public TestWorld(FeatureCatalog catalog) {
this(new WorldStates(), ModuleLogs.discarding(), catalog);
}
private TestWorld(WorldStates states, ModuleLog log, FeatureCatalog catalog) {
this.states = states;
this.log = log;
this.catalog = catalog;
}
@Override
@@ -70,6 +81,11 @@ public final class TestWorld implements PackWorld, AutoCloseable {
return states.state(type, () -> create.apply(this));
}
@Override
public <S> List<S> services(Class<S> service) {
return catalog == null ? List.of() : catalog.services(service);
}
@Override
public ModuleLog log() {
return log;