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

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

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

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

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

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

No files matched your search

+8 -6
View File
@@ -30,24 +30,25 @@ 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()`) |
| 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`; `clearBlock` / `clearAttached` take a block, or its block entity, record and markers, back), `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` |
| Values in settings | `BlockSpec`, `PaletteSpec`, `NoiseStyle`, `StyledRange`, `Range`, `BlockPosition`, `JigsawOverrides`, `Object` as `ValueKind.AnyKind` |
| Decisions over and fit of the platform's own structures | service `VanillaStructures` (`rule`, `starts`, `shift`, `reach`, `beforePieces`, `afterPieces`, `setup`), `VanillaStructureRule`, `VanillaStructureContext`, `VanillaStructureStart`, `VanillaStructureStartContext`, `VanillaStructureSetup`, `PlatformStart`, `StartMemo`, `StartReach`, `StructureFit` (`Start`, `Piece`, `ColumnVisitor`), `DecorationStep`, `TerrainAdaptation`, `PieceKind`, `TemplateCells`, `world.BlockAccess`, host `FeatureCatalog.registrations(service)` |
| Decisions over and fit of the platform's own structures | service `VanillaStructures` (`rule`, `starts`, `shift`, `reach`, `beforePieces`, `afterPieces`, `setup`), `VanillaStructureRule`, `VanillaStructureContext` (`world()`, empty when the host asks before any world exists), `VanillaStructureStart`, `VanillaStructureStartContext`, `VanillaStructureSetup`, `PlatformStart`, `StartMemo`, `StartReach`, `StructureFit` (`Start`, `Piece`, `ColumnVisitor`), `DecorationStep`, `TerrainAdaptation`, `PieceKind`, `TemplateCells`, `world.BlockAccess`, host `FeatureCatalog.registrations(service)` |
| Pack-scoped resolution | `ResourceId` (`ofPackKey`, `ofPlatformKey`), `ContentKey`, `PackResources` (`find(kind, id)`, `require`, `ids(kind)`, `idOf`; kinds `BIOMES`, `REGIONS`, `OBJECTS`, `EXPRESSIONS`, `IMAGE_MAPS`), `PackBiome`, `PackRegion` (their children and biome lists are `Weighted` entries; `Weighted.pick` walks them the way the host does), `PackExpression`, `PackImageMap` |
| Module-owned pack resources | `ResourceKind`, `FeatureRegistry.registerResourceKind`, `@ResourceRef`, host `ModuleHost.reservingFolders`, `FeatureCatalog.resourceKinds()`, `ResourceKindSchema`, `ValueKind.ResourceReferenceKind` |
| 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)` and `PackResources.services(type)` (empty by default; host `ModuleWorld` forwards to the host's world); services `DatapackStructureImport` (`importAll`, `DatapackImportReport`), `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`, `BakeRun` (`Stage`), `BlockParts`, `PatternView` with `PatternEntry`, `PatternArea`, `BlockPattern`), `EditableSceneView` (`SceneFile`, `SceneCreation`, `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`, `reading` with `Argument.Reader`, `orElse`, `suggesting`), `CommandAction`, `CommandContext` (`get`, `sender`, `pack`, `world`, `platform`, `platformStructures`), plain-text `Sender` (with `player()`), `PlatformStructures` (`templates`, `template` answering `StructureTemplate`, `structures`, `structureSets`, `jigsaw` answering `JigsawStructureInfo`, `pool` answering `TemplatePool` with `Member`, `Element`, `ConnectorSource`, `Connectors` and `JigsawConnector`, `supportsCapture`, `openCaptureArea` answering a closable `CaptureArea` whose `capture` answers `CapturedStructure`; `TemplateBlock`; readers throw `StructureAccessException`), `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`, `loaded`, `repaint`, `close`), `ToolPlayer` (`targetBlock`, `teleport`, `creative`, `message`, `actionBar`, `sound`, `sidebar`, `particles`, `give` answering whether the item fitted, `held`, `openMenu`), `ToolWorldDenied` (what `open` completes with when the host refuses for a reason the user can fix; a tool reports the message and logs no stack trace), `ToolText` with `TextColor` (styled text, spans in a colour with bold, italic and strikethrough: 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, and the modded adapters on the server thread) |
| Buffered placement writes | `PlacementRequest`, `PlacementAccess`, host-owned `PlacementEdit` |
| Typed generation and persistent storage | `mantle` package |
@@ -239,7 +240,8 @@ running Iris is the pack publisher's responsibility.
- Answer `PackWorld.running()` for a world the host runs, empty for a tool's world. Its `layout()` covers every column of
the world (not one chunk), with the same values chunk stages read; its `settings()` are the settings at a column and a
biome's declarations as chunk stages see them; `highest` is the platform's highest block now; `caveFloors` are
the cave floor markers of a chunk, in heights above the bottom; `sky()` is empty until the platform has the world.
the cave floor markers of a chunk, in heights above the bottom; `carvedAt` is the void the cave carver planned at a
block, empty where none was or when the host cannot read it; `sky()` is empty until the platform has the world.
- Call the hooks with `LifecycleRunner`: `packLoaded` once per pack snapshot before its first world starts,
`worldStarted` before the world generates anything, `warmUp` after it (on a thread of your choice, and wait for it before
the world's first generation; report a failure naming the module and carry on), `worldStopped` when it stops. On a hotload, and when the pack's
+61 -9
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
@@ -1136,7 +1137,7 @@ each world a state store and tells modules when worlds start and stop.
seeds its existing worlds were generated with, and every other id by the specification.
- **The running world.** `PackWorld.running()` is the world as it runs now, for services and lifecycle hooks, which have
no chunk to ask: the layout over every column as a `TerrainSampler`, the settings at a column and of a biome as
`FeatureSettings`, the highest block now, the cave floors the mantle marked, the sky (time and weather), the platform's
`FeatureSettings`, the highest block now, the cave floors the mantle marked, the void the cave carver planned at a block (`carvedAt`), the sky (time and weather), the platform's
loot tables and whether it is a debug world. It reuses the chunk vocabulary instead of a second one: Iris's built-ins
read the same through a facade (`LiveWorld`, with its own `Level`, `BiomeKind` and `Sky`), now deleted. Empty for a
tool's world, which nothing runs. Which biome a block "is in" (cave below the surface, else surface) stays a module
@@ -1236,6 +1237,12 @@ 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. `PackResources.services(type)` is the same for code that holds only the resources (a
locator listing structures asks the modules that own the kinds), and is empty where the host cannot ask.
- **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
@@ -1310,11 +1317,11 @@ A module jar sees three things besides the JDK and its own pack's jars, and noth
question, and none hands out an engine.
**The extension point.** A built-in reaches its facade through one door: `PackWorld.extension(type)` for what belongs to
a world (Iris's structure host), `InvocationContext.extension(type)` for what belongs to one invocation (the
a world, `InvocationContext.extension(type)` for what belongs to one invocation (the
platform chunk Iris generates), and `PackSettings.extension(type)` for what is worked out
from a pack's settings before any world exists (how far a feature reaches). Each returns an `Optional`, empty by default,
so a host offers what it has and a module states what it requires:
`world.extension(StructureHost.class).orElseThrow()`. Why one door:
`world.extension(Facade.class).orElseThrow()`. Why one door:
- **No thread-locals.** Facades used to be bound to the current thread (`IrisChunk.current()`, `ObjectPlacement.current()`),
which only worked while the host's own code had bound them and broke silently on another thread. The context a stage
@@ -1337,7 +1344,7 @@ Iris's own built-ins hold to this at compile time: IrisModule is a build of its
`com.volmit:iris-api`, VolmLib, Gson and the JDK, never `iris-host` or Iris, and its jar passes `ModuleJarCheck`
before Iris bundles it. Iris depends on IrisModule, not the reverse. What the built-ins cannot do through the API they
ask through the facades of item 3, which Iris implements; the classes that need Iris itself (the layout model, the
structure placer behind `StructureHost`) are Iris's and live there.
placement service) are Iris's and live there.
### Iris extensions, with the reason each is not api yet
@@ -1352,10 +1359,6 @@ API now: `world.running()`, `world.seed(purpose)`, `TerrainSampler`, `FeatureSet
the placement's JSON. Iris still reads it when it places an object itself with the pack's rules: the jigsaw placer, the
structure place commands and its tests (`ModuleObjectPlacement`). Pasting an object is not one of them: a paste writes
the object's blocks turned by a fixed angle (`IrisObject.paste`). It goes when the structures move into their module.
- **`StructureHost`** (world). Iris's structure assembler, locator and placer, and the loot tables of a structure for the
loot of its pieces. The structure model (structures, pools, pieces) is `iris:structure`'s own resource kinds, which Iris
registers with its own modules because its jigsaw studio reads them. Its surface is already API vocabulary; it goes when
the placer can write through the API.
- **Random parameters (`RNG`) in these facades and `loot.LootResolver`**. They are the legacy streams existing worlds were
generated from. They go when a world format change lets them be stage streams.
@@ -1406,6 +1409,55 @@ 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). 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.
- **The platform's structures are one capability.** Registries, resource managers and structure managers differ by
platform and version, and some are reached only by reflection. `PlatformStructures` is the one door for the tools that
import them, and answers in api types (`BlockState`, `BlockEntityData`, `ResourceId`), so an importer holds only
model-building logic. Capturing a structure needs a scratch area that has to be removed, so it is a `CaptureArea` the
tool closes, and not a call that leaves the area to the platform. A platform without the capability gives
`CommandContext.platformStructures()` empty and the tool says so.
- **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`.
- **A refusal is not a fault.** `ToolWorldDenied` is how a host says no for a reason the user can fix (a pack with
blocking errors); a tool prints its message and logs nothing, so a mistake of the pack's author does not look like a bug
of the tool.
- **Answers a tool needs back.** `ToolPlayer.give` says whether the item fitted, because a menu that hands out a tool the
player never got would look like it worked; `targetBlock` exists because only the platform can ray-trace against the
blocks the player sees. `teleported` and `containerChanged` report what no `blockChanging` announces, so a tool that
protects an area hears every way in and every inventory that changed.
- **Importing a datapack is a service.** `DatapackStructureImport` (`FIRST`) lets the host, which installs datapacks and
knows nothing about jigsaw, hand the structures it found to whichever module turns them into pack resources. A pack
without a provider leaves them pending, like a retryable failure, and `DatapackImportReport.retryRequired` tells the
host which kind of failure it saw.
- **Reading a command word.** `Argument.reading` exists for a value that only the command's module can check, such as a
resource of a kind a neighbouring module registered; the built-in argument types cover what the host can check itself.
## Not implemented
- Host wiring, which lives in Iris: JSON decoding and validation, rendering `PackSchema` into Iris's schema and
+91 -3
View File
@@ -259,6 +259,9 @@ PackBiome dunes = resources.require(PackResources.BIOMES, resources.idOf("desert
list, set or array of them, and studio completes the kind's keys. Packs write the key either way; a `ResourceId`
field holds the pack's id of it. Built-in kinds may read into a class the host describes
itself, as built-in settings may hold one.
- `PackResources.services(type)` gives the providers of a service that the pack's modules registered, for code that holds
only the resources, such as a locator listing structures. It asks the modules that own a kind what the kind means, as
`PackWorld.services` does; it is empty where the host cannot ask, and the list does not change for the snapshot.
```
Resource kind example:castle/keep of module example:castle from modules/castle.jar reads folder 'biomes', which the host reads itself; give the kind a folder of its own
@@ -294,6 +297,9 @@ if (!outcome.isPlaced()) {
`PlacementRecord`: the object's id, the module's number for this placement of it and, for a piece of a structure, the
structure's id. A module may wrap the terrain to hold or filter writes; a mantle stage gets one for its invocation from
`MantleGenerationContext.placementTerrain()`.
- `clearBlock(x, y, z)` takes a block a placement wrote back, so the terrain shows through; the block entity, placement
record and markers kept beside it stay until `clearAttached(x, y, z)` takes them back, whether or not a block is still
written there. A terrain that cannot take them back throws `UnsupportedOperationException`.
- `name` labels the placement (the object's key). `settings` is the placement as the pack wrote it, a JSON object: the
host reads from it the settings other modules declare at `Level.PLACEMENT`, so their stages see them like those of any
other level. The module that owns the placement type declares it once in `setup`, with the JSON names of its own
@@ -464,13 +470,19 @@ final class RuinsObjects implements ObjectsAt {
values in what they return are `Optional`s.
- A service that answers about the world as it runs, outside any chunk, reads `world.running()`: the layout over every
column (`layout()`, a `TerrainSampler`), the settings at a column and what a biome declares (`settings()`), the
highest block now, the cave floors the mantle marked, the time and weather (`sky()`, empty until the platform has
highest block now, the cave floors the mantle marked, the void the cave carver planned at a block (`carvedAt`, in
heights above the bottom; empty where none was, when the chunk keeps no generation data any more and on a platform
that cannot read it), the time and weather (`sky()`, empty until the platform has
the world), the platform's loot tables and whether the world is a debug (studio) world. It is empty for a tool's
world, which nothing runs.
- Each service says how several providers combine, with `@Service(Providers.X)`: `ALL` (the host asks every provider
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 |
| --- | --- | --- |
@@ -484,6 +496,7 @@ final class RuinsObjects implements ObjectsAt {
| `ProtectedFloor` | `ONE` | Whether the lowest layer of the world (height 0) belongs to the module that shapes the terrain, such as a bedrock floor it writes itself. The host then discards the blocks other placements and stages write there. Asked once per world; no provider protects nothing. |
| `AmbientEffects` | `ALL` | The effects due for a player standing at a position: a `Sound`, `Particles`, `Command`s and a `Potion` per `Effect`, every random choice already made (offsets, scatter, duration). The host asks now and then, carries out the parts the platform has, and keeps a stronger potion effect the player already has. |
| `VanillaStructures` | `ALL` | Rules, starts, shifts and reaches for the platform's own structures, fitting the terrain to the starts in one chunk through the `BlockAccess` the host hands over, and finding the starts a module makes of them (see Vanilla structures). |
| `DatapackStructureImport` | `FIRST` | Turns the structures and templates a datapack brought into editable resources of the pack once the host installed it (`importAll`, answering a `DatapackImportReport` of imported, skipped and failed sources, the bundles that landed and whether a failure may pass on a retry). Re-importing a source replaces what an earlier import made of it; with no provider the host leaves the datapack's structures pending. |
| `VanillaFeatures` | `ALL` | Whether the platform runs its own placed features (ores, trees, plants, springs) over a world's terrain, and which decoration steps (`DecorationStep`) and features it skips there. Off unless a module turns it on; any module may refuse a step or a feature. Asked once per world, step and feature. |
```
@@ -567,6 +580,9 @@ private void info(CommandContext context) {
constant written in lower case with `-`), `resource` (an id of a `ResourceKind` in the pack) and `registered` (an id in
one of the platform's registries, by `Reference`). `orElse` makes an argument optional; an optional argument may not
come before a required one. `suggesting` adds completions. Read a value with `context.get(argument)`.
`Argument.reading(name, reader)` takes one word and turns it into any value with a `Reader`, which throws
`IllegalArgumentException` saying why it cannot, for a value only the command's module can check, such as a resource of
a kind its neighbour registers; it completes nothing until `suggesting` gives it candidates.
- The host resolves the pack before it parses the line: `pack=<name>` taken out of the arguments, else the pack of the
sender's world, else the pack of the sender's open studio, else it fails with `Name a pack: pack=<name>`. A command
exists only for packs whose jars contain its module. `context.pack()` is that pack, `context.world()` the sender's
@@ -582,6 +598,76 @@ 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.
- `CommandContext.platformStructures()` is the platform's structures for the tools that turn them into pack resources,
empty on a platform that has none. `PlatformStructures` lists the registered structures and structure sets and the
loadable templates (`templates`, `template`, `structures`, `structureSets`), reads a registered jigsaw structure and a
template pool (`jigsaw` answering `JigsawStructureInfo`, `pool` answering `TemplatePool` with its members, fallback and
the connectors of each element), and generates structures that have no template in a throwaway area
(`supportsCapture`, `openCaptureArea`: a closable `CaptureArea` places one structure after another in a scratch area
and `capture(structure, seed, maxSpan)` reads each back, empty when the box is wider or taller than `maxSpan`, and
`close` removes the area). A template or a captured structure is a list of `TemplateBlock` with
`BlockState` and `BlockEntityData`. A reader throws `StructureAccessException` when the platform's registries cannot be
read, and says whether asking again may help.
## 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.
A host that refuses to open a world for a reason the user or the pack's author can fix, such as a pack with blocking
errors, completes `open` with `ToolWorldDenied`; its message is for the user, so a tool reports it and logs no stack trace.
```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.
- A tool world takes the pack's studio slot: opening another studio, the studio close command and a server stop go
through the world. `closeRefusal()` lets the tool veto such a close with a message (an unsaved edit, a running
save), and `closing(by)` lets it finish its work before another studio replaces it; the host closes the world when
that future completes.
- 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), 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. `targetBlock(maxDistance)` is the block the player looks at,
fluids not counting. `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
@@ -686,8 +772,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
@@ -880,6 +966,8 @@ Every method has a default that changes nothing, so a provider implements only w
structure, `JigsawOverrides` for jigsaw structures and a `StartMemo`.
The context gives the world (`PackWorld`) and a `TerrainSampler` over the chunk. Answer from the world and chunk
only: the host asks again when it locates structures and when it checks starts it finds in the world.
`VanillaStructureContext.world()` is the world a rule decides for, empty when the host asks before any world exists,
such as for the setup of a dimension; a rule that needs the world answers its default then.
- `shift(start, context)`: how many blocks one of the platform's own starts moves up or down before the host
publishes it. A `PlatformStart` gives its bounds, whether the platform generates it underground, whether the host
aligns it itself (ocean monuments to the sea, desert and jungle temples to the terrain; a shift then applies on top),
@@ -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<BlockState> 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.
*/
@@ -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);
}
}
@@ -48,6 +48,26 @@ public interface PlacementTerrain {
*/
void recordPlacement(int x, int y, int z, PlacementRecord placement);
/**
* Takes back the block written at the position, so the terrain shows through there. The block entity, placement
* record and markers kept beside it stay ({@link #clearAttached}).
*
* @throws UnsupportedOperationException when this terrain cannot take blocks back
*/
default void clearBlock(int x, int y, int z) {
throw new UnsupportedOperationException("This terrain cannot take blocks back");
}
/**
* Takes back the block entity, placement record and markers the host kept beside the block, whether or not a block
* is still written there.
*
* @throws UnsupportedOperationException when this terrain cannot take them back
*/
default void clearAttached(int x, int y, int z) {
throw new UnsupportedOperationException("This terrain cannot take what is kept beside a block back");
}
/** The placement recorded at the block ({@link #recordPlacement}); empty when none is. */
Optional<PlacementRecord> placementAt(int x, int y, int z);
@@ -69,6 +69,13 @@ public interface PackResources {
return ResourceId.ofPackKey(packId().namespace(), key);
}
/** The providers of {@code service} that the pack's modules registered, in module id order, so a module that holds only the
* resources, such as a locator listing structures, can ask the modules that own the kinds. Empty by default.
*/
default <S> List<S> services(Class<S> service) {
return List.of();
}
/** {@link #find} for a resource that must exist: a missing one throws NoSuchElementException naming kind and id. */
default <T> T require(ResourceKind<T> kind, ResourceId id) {
return find(kind, id).orElseThrow(() -> new NoSuchElementException("Missing " + kind.id() + " resource: " + id));
@@ -117,6 +117,15 @@ public final class Argument<T> {
});
}
/** One word that {@code reader} turns into the value, for a value only the command's module can check, such as a resource
* of a kind its module's neighbour registers. {@code reader} fails with an IllegalArgumentException that says why; the
* argument completes nothing until {@link #suggesting} gives it candidates.
*/
public static <T> Argument<T> reading(String name, Reader<T> reader) {
Objects.requireNonNull(reader, "reader");
return of(name, false, reader::read, (partial, context) -> List.of());
}
/** An id registered in the platform's {@code registry}, such as {@link Reference#STRUCTURE}; completes
* {@link PlatformRegistries#ids}. Written as the platform writes it, {@code minecraft:village_plains}, or without the
* {@code minecraft:} namespace.
@@ -244,6 +253,12 @@ public final class Argument<T> {
return registry.name().toLowerCase(Locale.ROOT).replace('_', ' ');
}
/** Turns the word a sender typed into the argument's value. */
@FunctionalInterface
public interface Reader<T> {
T read(String text, CommandContext context);
}
private interface Parser<T> {
T parse(String text, CommandContext context);
}
@@ -0,0 +1,18 @@
package com.volmit.tooling;
import com.volmit.geometry.BlockPosition;
import java.util.List;
import java.util.Objects;
/**
* A structure the platform generated in a scratch area and read back.
*
* @param size the width, height and depth of the box the structure filled
* @param blocks every block in that box that is not plain air, with positions from the box's corner
*/
public record CapturedStructure(BlockPosition size, List<TemplateBlock> blocks) {
public CapturedStructure {
Objects.requireNonNull(size, "size");
blocks = List.copyOf(blocks);
}
}
@@ -30,4 +30,7 @@ public interface CommandContext {
/** The platform's registries; empty when the host runs without a platform. */
Optional<PlatformRegistries> platform();
/** The structures the platform registers and the templates it loads; empty on a platform that does not offer them. */
Optional<PlatformStructures> platformStructures();
}
@@ -0,0 +1,23 @@
package com.volmit.tooling;
import com.volmit.resource.ResourceId;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
/** What {@link DatapackStructureImport#importAll} did.
*
* @param total the sources it tried
* @param imported the sources it imported
* @param skipped the sources it left as they were
* @param failed the sources it could not import
* @param importedBundles the bundle each fully imported source ended up as, by bundle name
* @param retryRequired whether a failure may pass when the import runs again, as opposed to the source being invalid
*/
public record DatapackImportReport(int total, int imported, int skipped, int failed, Map<String, ResourceId> importedBundles,
boolean retryRequired) {
public DatapackImportReport {
Objects.requireNonNull(importedBundles, "importedBundles");
importedBundles = java.util.Collections.unmodifiableMap(new TreeMap<>(importedBundles));
}
}
@@ -0,0 +1,19 @@
package com.volmit.tooling;
import com.volmit.resource.ResourceId;
import com.volmit.service.Providers;
import com.volmit.service.Service;
import java.util.Collection;
/** Turns the structures and templates a datapack brought into editable resources of the pack, once the host installed the
* datapack. A module that owns a kind of structure provides it; the host asks the pack's first provider and, when the pack has
* none, leaves the datapack's structures pending. Re-importing a source replaces what an earlier import made of it.
*/
@Service(Providers.FIRST)
public interface DatapackStructureImport {
/** Imports {@code structures} (ids of the platform's registered structures) and {@code templates} (ids of its structure
* templates) into {@code pack}, reporting progress to {@code sender}. A source that fails does not stop the others.
*/
DatapackImportReport importAll(ToolPack pack, PlatformStructures platform, Sender sender,
Collection<ResourceId> structures, Collection<ResourceId> templates);
}
@@ -0,0 +1,23 @@
package com.volmit.tooling;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/**
* What a registered jigsaw structure says about itself.
*
* @param startPool the template pool the structure starts from
* @param maxDepth how many pieces deep the structure grows
* @param maxDistance how far from its centre the structure may reach, in blocks; the horizontal reach when the platform
* keeps a horizontal and a vertical one
* @param gameVersion the platform's own version string, which tools record as where the structure came from
* @param shuffleSeed what the platform seeds its shuffle of the connectors of this structure's pool elements with, so
* that reading the same structure twice lists them in the same order
*/
public record JigsawStructureInfo(ResourceId startPool, int maxDepth, int maxDistance, String gameVersion,
long shuffleSeed) {
public JigsawStructureInfo {
Objects.requireNonNull(startPool, "startPool");
Objects.requireNonNull(gameVersion, "gameVersion");
}
}
@@ -0,0 +1,63 @@
package com.volmit.tooling;
import com.volmit.resource.ResourceId;
import java.util.List;
import java.util.Optional;
/**
* The structures a platform registers and the templates it loads, for the tools that turn them into pack resources.
* A command reaches it as {@link CommandContext#platformStructures()}, which is empty on a platform without it. Every
* method may take a while and reads the running server, so a tool calls them from its worker thread and never
* from the platform's main or region thread.
*
* <p>Each reader that cannot answer because the platform's registries cannot be read throws a
* {@link StructureAccessException}; a reader that answers empty means the platform has no such thing.
*/
public interface PlatformStructures {
/** The ids of the structure templates the platform can load, such as {@code minecraft:village/plains/houses/plains_small_house_1}, in id order. */
List<ResourceId> templates();
/** The template {@code id}; empty when the platform has none or it holds no palette. */
Optional<StructureTemplate> template(ResourceId id);
/** The ids of the structures the platform registers, in id order. */
List<ResourceId> structures();
/** The ids of the structure sets the platform registers, in id order. */
List<ResourceId> structureSets();
/** What {@code structure} says about itself; empty when it is no jigsaw structure or is not registered. */
Optional<JigsawStructureInfo> jigsaw(ResourceId structure);
/** The template pool {@code pool}; empty when it is not registered. */
Optional<TemplatePool> pool(ResourceId pool);
/** Whether the platform can generate a structure in a scratch area and read it back, which {@link #openCaptureArea} needs. */
boolean supportsCapture();
/**
* Opens a throwaway area to generate structures in, for the structures that have no template. Close it when the
* captures are done; it is removed then.
*
* @param sender where the platform reports what it does while it opens and removes the area
* @return the area; empty when it could not be opened, which the platform has told the sender
*/
Optional<CaptureArea> openCaptureArea(Sender sender);
/** A throwaway area structures are generated in, one after another. */
interface CaptureArea extends AutoCloseable {
/**
* Generates {@code structure} in the next free spot of the area and reads it back.
*
* @param seed what the platform generates the structure with
* @param maxSpan the widest and tallest box, in blocks, the platform reads back
* @return the structure; empty when it placed nothing capturable here, such as one wider than {@code maxSpan}
* @throws IllegalStateException when the platform could not place it, with the reason
*/
Optional<CapturedStructure> capture(ResourceId structure, long seed, int maxSpan);
/** Removes the area. */
@Override
void close();
}
}
@@ -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();
}
@@ -0,0 +1,28 @@
package com.volmit.tooling;
/**
* What a {@link PlatformStructures} reader throws when the platform cannot answer, such as a server version whose
* registries it cannot read. The message is written for the sender who ran the tool, so a tool shows it as it is.
*/
public final class StructureAccessException extends RuntimeException {
private final boolean retryable;
/**
* @param message what went wrong, as the sender should read it
* @param retryable whether asking again later may succeed, as for a registry that was not ready yet
*/
public StructureAccessException(String message, boolean retryable) {
super(message);
this.retryable = retryable;
}
public StructureAccessException(String message, boolean retryable, Throwable cause) {
super(message, cause);
this.retryable = retryable;
}
/** Whether asking again later may succeed. */
public boolean retryable() {
return retryable;
}
}
@@ -0,0 +1,20 @@
package com.volmit.tooling;
import com.volmit.geometry.BlockPosition;
import java.util.List;
import java.util.Objects;
/**
* A structure template the platform loads, such as a vanilla {@code .nbt}: its size and the blocks of its first palette.
*
* @param size the template's width, height and depth in blocks
* @param paletteCount how many palettes the template has; only the first is in {@code blocks}
* @param entityCount how many entities the template holds, which tools do not read
* @param blocks the blocks of the first palette, with positions from the template's corner
*/
public record StructureTemplate(BlockPosition size, int paletteCount, int entityCount, List<TemplateBlock> blocks) {
public StructureTemplate {
Objects.requireNonNull(size, "size");
blocks = List.copyOf(blocks);
}
}
@@ -0,0 +1,33 @@
package com.volmit.tooling;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockPosition;
import com.volmit.object.BlockEntityData;
import java.util.Objects;
import java.util.Optional;
/**
* One block of a {@link StructureTemplate} or {@link CapturedStructure}.
*
* @param position where the block is, from the template's corner
* @param state the block as the platform stores it; a jigsaw block is the jigsaw block itself
* @param blockEntity the block entity data of a block that has some; empty for a jigsaw block, which tools resolve
* through {@code jigsawFinalState}
* @param jigsawFinalState what a jigsaw block turns into when its piece is placed: the {@code final_state} the block
* names, as the platform writes it; empty for any other block and for a jigsaw block that names
* none
*/
public record TemplateBlock(BlockPosition position, BlockState state, Optional<BlockEntityData> blockEntity,
Optional<String> jigsawFinalState) {
public TemplateBlock {
Objects.requireNonNull(position, "position");
Objects.requireNonNull(state, "state");
Objects.requireNonNull(blockEntity, "blockEntity");
Objects.requireNonNull(jigsawFinalState, "jigsawFinalState");
}
/** A block with no jigsaw final state. */
public static TemplateBlock of(BlockPosition position, BlockState state, Optional<BlockEntityData> blockEntity) {
return new TemplateBlock(position, state, blockEntity, Optional.empty());
}
}
@@ -0,0 +1,154 @@
package com.volmit.tooling;
import com.volmit.geometry.BlockFace;
import com.volmit.geometry.BlockPosition;
import com.volmit.resource.ResourceId;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.LongSupplier;
/**
* A jigsaw template pool the platform registers: what its entries are and where it falls back to.
*
* @param members the entries in the order the platform lists them, every one of them, so the count is the
* pool's own size
* @param fallback the pool used when none of the entries fits; empty when it has none
* @param fallbackFailure why the fallback could not be read, when it could not; the fallback is then empty
*/
public record TemplatePool(List<Member> members, Optional<ResourceId> fallback, Optional<String> fallbackFailure) {
public TemplatePool {
members = List.copyOf(members);
Objects.requireNonNull(fallback, "fallback");
Objects.requireNonNull(fallbackFailure, "fallbackFailure");
}
/** One entry of a pool. */
public sealed interface Member permits Absent, Unreadable, Element {
}
/** An entry that holds no element. */
public record Absent() implements Member {
}
/** Which part of an entry could not be read. */
public enum Part {
/** The element and its weight. */
ENTRY,
/** Where the element's template is. */
TEMPLATE_LOCATION
}
/**
* An entry the platform could not read.
*
* @param part what could not be read
* @param detail why, as the platform reports it
*/
public record Unreadable(Part part, String detail) implements Member {
public Unreadable {
Objects.requireNonNull(part, "part");
Objects.requireNonNull(detail, "detail");
}
}
/**
* One element of a pool with its weight.
*
* @param weight how likely the element is among the entries; at least 1
* @param type the platform's name for the kind of element, such as {@code SinglePoolElement}, which tells an
* empty element from one a tool cannot convert when {@code template} is empty
* @param template the template the element places; when the platform wraps several elements in a list, the
* first one that places a template; empty for an element that places none
* @param listLevels how many list elements wrap the one {@code template} came from
* @param omittedElements how many elements those lists held besides the one {@code template} came from
* @param connectors reads the jigsaw connectors of the element
*/
public record Element(int weight, String type, Optional<ResourceId> template, int listLevels, int omittedElements,
ConnectorSource connectors) implements Member {
public Element {
Objects.requireNonNull(type, "type");
Objects.requireNonNull(template, "template");
Objects.requireNonNull(connectors, "connectors");
}
}
/** Reads the jigsaw connectors of one pool element. */
@FunctionalInterface
public interface ConnectorSource {
/**
* The connectors of the element, in the order the platform shuffles them with a seed.
*
* @param shuffleSeeds gives the seed to shuffle with; the platform asks only when it shuffles, so the caller's
* random sequence advances once for each element that has connectors to shuffle
* @throws StructureAccessException when the platform cannot read the connectors at all
*/
Connectors read(LongSupplier shuffleSeeds);
}
/** Whether the platform could list an element's connectors. */
public enum Availability {
READ,
/** The platform's version has no way to list them. */
UNAVAILABLE,
/** The platform answered with no list. */
NO_COLLECTION
}
/**
* The connectors of an element.
*
* @param availability whether {@code connectors} were listed
* @param connectors one entry for each jigsaw block, in the platform's shuffled order
*/
public record Connectors(Availability availability, List<Connector> connectors) {
public Connectors {
Objects.requireNonNull(availability, "availability");
connectors = List.copyOf(connectors);
}
}
/** One jigsaw block of an element. */
public sealed interface Connector permits JigsawConnector, UnreadableConnector {
}
/**
* A jigsaw block the platform could not convert.
*
* @param detail why, as the platform reports it
*/
public record UnreadableConnector(String detail) implements Connector {
public UnreadableConnector {
Objects.requireNonNull(detail, "detail");
}
}
/**
* A jigsaw block.
*
* @param position where it is, from the element's corner
* @param front the side it connects through
* @param top the side its top faces, which fixes the roll of a rollable joint
* @param pool the pool it pulls its next piece from; empty when it names none
* @param name the name other blocks target
* @param target the name of the blocks it connects to
* @param aligned whether the joint keeps the pieces aligned rather than letting them roll
* @param finalState the block it turns into once it connects, as the platform writes block states; empty when
* the block names none
* @param selectionPriority which block is tried first
* @param placementPriority which connected piece is expanded first
*/
public record JigsawConnector(BlockPosition position, BlockFace front, BlockFace top, Optional<ResourceId> pool,
String name, String target, boolean aligned, Optional<String> finalState,
int selectionPriority, int placementPriority) implements Connector {
public JigsawConnector {
Objects.requireNonNull(position, "position");
Objects.requireNonNull(front, "front");
Objects.requireNonNull(top, "top");
Objects.requireNonNull(pool, "pool");
Objects.requireNonNull(name, "name");
Objects.requireNonNull(target, "target");
Objects.requireNonNull(finalState, "finalState");
}
}
}
@@ -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,73 @@
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 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<BlockPosition> positions,
List<BlockPosition> changed,
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);
changed = List.copyOf(changed);
if (positions.isEmpty() && changed.isEmpty()) {
throw new IllegalArgumentException("A block change names at least one block");
}
Objects.requireNonNull(player, "player");
Objects.requireNonNull(placed, "placed");
}
/** A change that is checked against the blocks it changes. */
public BlockChange(Cause cause, List<BlockPosition> positions, Optional<ToolPlayer> player, Optional<BlockState> placed) {
this(cause, positions, positions, player, 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,20 @@
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}; the middle
* mouse button is {@code middle}, with {@code right} and {@code shift} false.
*
* @param player the player who clicked
*/
public record MenuClick(ToolPlayer player, boolean right, boolean shift, boolean middle) {
public MenuClick {
Objects.requireNonNull(player, "player");
}
/** A left or right click, with or without shift. */
public MenuClick(ToolPlayer player, boolean right, boolean shift) {
this(player, right, shift, false);
}
}
@@ -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,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;
}
}
@@ -0,0 +1,29 @@
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.
*
* <p>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; 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, ToolText name, List<ToolText> 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; 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(ToolText 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,99 @@
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. 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. */
Optional<ToolWorld> world();
BlockPosition position();
/** The direction the player faces, in degrees, as the platform counts them. */
float yaw();
float pitch();
boolean sneaking();
/**
* The block the player looks at within {@code maxDistance} blocks, fluids not counting; empty when they look at none.
* Like the other readers, valid only on the thread that owns the player.
*/
Optional<BlockPosition> targetBlock(int maxDistance);
/** 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);
/** Sends {@code text} to the player's chat, in its colours. */
void message(ToolText text);
/** Shows {@code text} above the hotbar. */
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.
* An empty title keeps the platform's own sidebar title. The sidebar goes away when the player leaves the tool world.
*/
void sidebar(ToolText title, List<ToolText> 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, 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<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,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.
*
* <p>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<Span> 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<Span> 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);
}
}
}
@@ -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,87 @@
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);
/** 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
* 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,13 @@
package com.volmit.tooling.world;
/** A host refused to open a tool world for a reason its message tells the user and the pack's author can fix, such as a pack
* with blocking errors. {@link ToolWorlds#open} completes with it; it is not a fault, so a tool reports the message and logs no
* stack trace.
*/
public final class ToolWorldDenied extends RuntimeException {
private static final long serialVersionUID = 1L;
public ToolWorldDenied(String message) {
super(message);
}
}
@@ -0,0 +1,102 @@
package com.volmit.tooling.world;
import com.volmit.geometry.BlockPosition;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
/**
* 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 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) {
}
/** 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;
}
/**
* 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<ToolPlayer> player, BlockPosition at) {
}
/** A chunk of the world finished loading, painted or read back. */
default void chunkLoaded(int chunkX, int chunkZ) {
}
/**
* Whether the host may close the world now, asked before the host closes it for any reason other than the tool's own
* {@link ToolWorld#close()}: another studio opening, the studio close command, the server stopping. A tool world takes
* the pack's studio slot, so those paths go through the world. Return a message for the user to veto the close, such
* as "autosave is still running"; empty lets it happen. Asked on any thread, and must return quickly.
*/
default Optional<String> closeRefusal() {
return Optional.empty();
}
/**
* Another studio wants this world's slot. Get the world ready to close, such as finishing a save, and complete the
* future when it is ready; the host then closes the world. Complete it exceptionally to refuse, with a message for the
* user. {@code by} is the player who asked, empty when the console did. Called on any thread; the future may complete
* on any thread.
*/
default CompletableFuture<Void> closing(Optional<ToolPlayer> by) {
return CompletableFuture.completedFuture(null);
}
/** 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,28 @@
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, with {@link ToolWorldDenied} when the host refuses the pack a world (its message says why), 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: it hears {@link ToolWorldListener#closing}
* of each and waits for it before {@link ToolWorldListener#closed}.
*
* <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);
}
@@ -2,6 +2,9 @@ package com.volmit.vanilla;
import com.volmit.config.PackSettings;
import com.volmit.resource.PackResources;
import com.volmit.world.PackWorld;
import java.util.Optional;
/** The world a {@link com.volmit.service.VanillaStructures} provider decides for. Valid only while the provider runs. */
public interface VanillaStructureContext {
@@ -10,4 +13,9 @@ public interface VanillaStructureContext {
/** The module settings the world's dimension declares: its own, and every region and biome it can reach. */
PackSettings settings();
/** The world the provider decides for; empty when it decides before any world exists, such as for the setup of a dimension. */
default Optional<PackWorld> world() {
return Optional.empty();
}
}
@@ -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);
}
@@ -3,6 +3,7 @@ package com.volmit.world;
import com.volmit.config.FeatureSettings;
import com.volmit.data.SavedKey;
import com.volmit.geometry.BlockPosition;
import com.volmit.mantle.CarvedVoid;
import com.volmit.placement.PlacementRecord;
import com.volmit.resource.ResourceId;
import java.util.List;
@@ -43,6 +44,15 @@ public interface RunningWorld {
*/
Optional<PlacementRecord> placementAt(int worldX, int y, int worldZ);
/**
* The void the cave carver planned at the block, as the world holds it now; empty where none was, or when the block's
* chunk keeps no generation data any more, and on a platform that cannot read it. Y is the height above the
* dimension's bottom.
*/
default Optional<CarvedVoid> carvedAt(int worldX, int y, int worldZ) {
return Optional.empty();
}
/**
* The value the module keeps with this world across restarts under {@code key}: the host's one instance of it for
* the world, read from the world's storage the first time anyone asks (or {@code key.initial()} when none was
@@ -0,0 +1,48 @@
package com.volmit.tooling;
import com.volmit.block.BlockState;
import com.volmit.geometry.BlockFace;
import com.volmit.geometry.BlockPosition;
import com.volmit.resource.ResourceId;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PlatformStructuresTest {
@Test
void aTemplateKeepsItsOwnCopyOfItsBlocks() {
var blocks = new ArrayList<>(List.of(TemplateBlock.of(
new BlockPosition(0, 0, 0), BlockState.parse("minecraft:stone"), Optional.empty())));
var template = new StructureTemplate(new BlockPosition(1, 1, 1), 1, 0, blocks);
blocks.clear();
assertEquals(1, template.blocks().size());
assertThrows(UnsupportedOperationException.class, () -> template.blocks().clear());
}
@Test
void aPoolListsEveryMemberWhetherTheToolCanReadItOrNot() {
var unreadable = new TemplatePool.Unreadable(TemplatePool.Part.ENTRY, "no weight");
var element = new TemplatePool.Element(3, "SinglePoolElement",
Optional.of(ResourceId.parse("minecraft:village/house")), 0, 0,
seeds -> new TemplatePool.Connectors(TemplatePool.Availability.READ, List.of(
new TemplatePool.JigsawConnector(new BlockPosition(1, 2, 3), BlockFace.NORTH, BlockFace.UP,
Optional.empty(), "minecraft:door", "minecraft:door", false, Optional.empty(), 0, 0))));
var pool = new TemplatePool(List.of(new TemplatePool.Absent(), unreadable, element), Optional.empty(), Optional.empty());
assertEquals(3, pool.members().size());
assertEquals(1, element.connectors().read(() -> 7L).connectors().size());
}
@Test
void anAccessFailureSaysWhetherAskingAgainMayHelp() {
assertTrue(new StructureAccessException("registry not ready", true).retryable());
assertEquals("no such member", new StructureAccessException("no such member", false).getMessage());
}
}
@@ -0,0 +1,184 @@
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, ToolText.plain("Tool"), List.of(ToolText.plain("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 aListenerThatSaysNothingAboutClosingLetsTheWorldCloseAtOnce() {
var listener = new ToolWorldListener() { };
assertEquals(java.util.Optional.empty(), listener.closeRefusal());
assertEquals(true, listener.closing(java.util.Optional.empty()).isDone());
assertEquals(false, listener.closing(java.util.Optional.empty()).isCompletedExceptionally());
}
@Test
void aToolItemKeepsItsOwnCopyOfTheLore() {
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(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(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(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(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());
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 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<BlockPosition>();
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() { };
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. */
@@ -4,8 +4,10 @@ import com.volmit.ModuleLog;
import com.volmit.config.PackSettings;
import com.volmit.placement.Placements;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
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;
@@ -36,6 +38,11 @@ final class ModuleWorld implements PackWorld {
return world.seed();
}
@Override
public long seed(ResourceId purpose) {
return world.seed(purpose);
}
@Override
public PackResources resources() {
return world.resources();
@@ -72,6 +79,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"));
}
@@ -12,6 +12,7 @@ import com.volmit.hunk.Hunk;
import com.volmit.mantle.Mantle;
import com.volmit.placement.Placements;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.stage.Pipeline;
import com.volmit.stage.Stage;
import com.volmit.support.TestContexts;
@@ -73,6 +74,18 @@ class ExtensionsTest {
assertEquals(Optional.of(new WorldOffer("iris")), view.extension(WorldOffer.class));
}
@Test
void aModulesViewOfAWorldAnswersTheSeedPurposesTheHostAnswers() {
var world = new OfferingWorld(new WorldOffer("iris"));
PackWorld view = ModuleWorld.of(world, ModuleLogs.discarding());
assertEquals(HOST_SEED, view.seed(HOST_SEED_PURPOSE), "the host decides the seed of a purpose it knows");
assertEquals(world.seed(ResourceId.parse("test:other")), view.seed(ResourceId.parse("test:other")));
}
private static final ResourceId HOST_SEED_PURPOSE = ResourceId.parse("test:host-seed");
private static final long HOST_SEED = 31337L;
private static final class OfferingWorld implements PackWorld {
private final WorldStates states = new WorldStates();
private final WorldOffer offer;
@@ -82,12 +95,14 @@ class ExtensionsTest {
}
public long seed() { return TestContexts.SEED; }
@Override public long seed(ResourceId purpose) { return purpose.equals(HOST_SEED_PURPOSE) ? HOST_SEED : PackWorld.super.seed(purpose); }
public PackResources resources() { throw new AssertionError("Unused resources"); }
public PackSettings settings() { throw new AssertionError("Unused settings"); }
public int minWorldY() { return 0; }
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;