From a9e3cbaa936528f7852a066b9baa731ad48c65a3 Mon Sep 17 00:00:00 2001 From: piexel Date: Wed, 28 Oct 2026 04:02:32 +0100 Subject: [PATCH] Close the object-placement couplings of the tooling audit PlacementRun carries the placement's display name and its JSON, from which the host reads the settings other modules declare at the placement level. FeatureRegistry.registerPlacementType lets the module that owns placements declare the type and its JSON names for the placement level. RunningWorld and PlacementTerrain keep a typed PlacementRecord (object id, placement id, optional structure id) instead of a text. Loot gives the seed a container is shuffled with, the ProtectedFloor service says whether the lowest layer belongs to the terrain module, and EntitySpec holds the spawn reason, rising out of the ground, panda genes and applying to a provided mob. --- CONTRACTS.md | 13 +++- DESIGN.md | 28 ++++++--- README.md | 27 ++++++--- .../main/java/com/volmit/FeatureRegistry.java | 10 ++++ .../java/com/volmit/entity/EntitySpec.java | 32 +++++++--- .../com/volmit/placement/PlacementRecord.java | 34 +++++++++++ .../com/volmit/placement/PlacementRun.java | 28 ++++++--- .../volmit/placement/PlacementTerrain.java | 8 +-- .../main/java/com/volmit/service/Loot.java | 11 ++++ .../com/volmit/service/ProtectedFloor.java | 18 ++++++ .../java/com/volmit/world/RunningWorld.java | 3 +- .../com/volmit/ItemAndEntityValuesTest.java | 49 ++++++++++++++- .../java/com/volmit/host/FeatureCatalog.java | 10 +++- .../java/com/volmit/host/ModuleRegistry.java | 47 ++++++++++++++- .../com/volmit/host/PackSchemaBuilder.java | 2 +- .../host/PlacementTypeRegistration.java | 18 ++++++ .../com/volmit/host/schema/PackSchema.java | 7 ++- .../com/volmit/host/ModuleRegistryTest.java | 60 +++++++++++++++++++ 18 files changed, 355 insertions(+), 50 deletions(-) create mode 100644 api/src/main/java/com/volmit/placement/PlacementRecord.java create mode 100644 api/src/main/java/com/volmit/service/ProtectedFloor.java create mode 100644 host/src/main/java/com/volmit/host/PlacementTypeRegistration.java diff --git a/CONTRACTS.md b/CONTRACTS.md index 3832c1358..e816519c9 100644 --- a/CONTRACTS.md +++ b/CONTRACTS.md @@ -30,7 +30,7 @@ types that carry them and lists what the Iris adapter still owes. | 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`, `withProperty`, `matches`), `BlockTurn`, `BlockTrait` (with `STORAGE`), `BlockPalette`, `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, area, terrain, input, seed), `PlacementTerrain`, `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 | +| Placing through the pack's placement graph | `Placements.place(PlacementRun)` (`PackWorld.placements()`), `PlacementRun` (request, name, settings JSON, area, terrain, input, seed), `PlacementTerrain` (`recordPlacement` / `placementAt` with a `PlacementRecord`), `StructureVolumes`, `PlacedMarker`, `PlacementOutcome`; stages read `PlacementContext.placementTerrain()` and `input(type)`; mantle stages get a terrain from `MantleGenerationContext.placementTerrain()`; `RunningWorld.placementAt` reads what a placement recorded; `FeatureRegistry.registerPlacementType` names the type packs write placements as (host `FeatureCatalog.placementType()`, `PackSchema.placementType()`) | | Noise from pack-described styles | `NoiseStyle`, `StyledRange`, `PackResources.noise()`, `NoiseFactory`, `NoiseSampler` | | 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)` | @@ -39,7 +39,7 @@ types that carry them and lists what the Iris adapter still owes. | Module-owned pack checks | `Validator`, `ValidationContext`, `Problem`, `Severity`, `Subject`, `FeatureRegistry.registerValidator`, host `FeatureCatalog.validators()` | | Per-world module state | `PackWorld` (`state`), `InvocationContext.world()`, host `WorldStates` | | Module lifecycle across loads, hotloads and reloads | `ModuleLifecycle`, `PackContext`, `FeatureRegistry.registerLifecycle`, host `FeatureCatalog.lifecycles()`, `LifecycleRunner` | -| Host questions answered by modules | `@Service`, `Providers`, `FeatureRegistry.registerService`, host `FeatureCatalog.services(type)` / `service(type)`; services `ObjectsAt`, `StructureLocator` (`LocateResult`, `startedStructures`, `locatableStarts`, `locateStart`, `ChunkFilter`), `SaplingGrowth`, `Loot`, `BlockDrops`, `EntitySpawns`, `CaveBiomes`, `AmbientEffects`, `VanillaFeatures` (`DecorationStep`); values `ItemDrop`, `EntitySpec`, `ItemRegistry` (`PackResources.items()`) | +| 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()`) | | Terrain and settings sampling | `TerrainSampler`, `BiomeSample`, `TerrainSample`, `FeatureSettings` | | Dense chunk output | `Hunk`, `GenerationContext.blocks`, reference `ArrayHunk` | | Positions, boxes and faces | `com.volmit.geometry`: `BlockPosition`, `BlockBox`, `BlockFace` | @@ -237,7 +237,14 @@ running Iris is the pack publisher's responsibility. - Create what `ItemDrop` and `EntitySpec` describe on the platform, skip what the platform lacks (an unknown enchantment, attribute or item flag) with a warning, route a `ContentKey.Provided` (and a `Registered` id of a namespace another plugin owns) to that plugin, apply the `EntitySpec.extensions()` of the host's own types and ignore the rest, and run the checks that come with an `EntitySpawns.Attempt` (light, surface, - free space) before spawning. Report how many entities appeared with `EntitySpawns.spawned`. + free space) before spawning. Report how many entities appeared with `EntitySpawns.spawned`. Apply `Arrival.reason` + (the platform's own name for the spawn reason, natural when it is empty or unknown), `Arrival.risesFromGround`, a + panda's `Appearance` genes, and `adjustsProvidedMob` (a `ContentKey.Provided` mob is otherwise left as its provider set it up). +- Shuffle a filled container's slots with `Loot.shuffleSeed` (the first seed in module order; leave the order alone when + no module gives one), and discard the blocks written at height 0 when a `ProtectedFloor` provider says the floor is + protected (ask once per world). +- Keep a `PlacementRecord` beside the block a placement recorded it at and return it from `placementAt` (the host chooses + the form it stores); read the settings of `PlacementRun.settings` from the JSON at `Level.PLACEMENT`. - `AmbientEffects.due`: ask for the player's last sampled position (not every tick's), carry out an `Effect` in the order sound, particles, commands, potion, skip a part the platform lacks, and give no potion to a player who already has the same one with a higher amplifier. diff --git a/DESIGN.md b/DESIGN.md index 768babef9..57f81f6aa 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -440,8 +440,14 @@ are ordered only by the tie-break, so they are where two modules can silently co A module places an object through the pack's placement graph with `PackWorld.placements().place(PlacementRun)`; the host runs `PlacementRunner` over an edit that buffers into the run's `PlacementTerrain`, and returns the API -`PlacementOutcome`. One service, one request and one outcome: the run carries the object, the area, the terrain, the -placing module's own input and the seed, and nothing names a host. The terrain is an interface so a module can hold +`PlacementOutcome`. One service, one request and one outcome: the run carries the object, its display name, the +placement as the pack wrote it (JSON, from which the host reads the settings other modules declare at `Level.PLACEMENT`), +the area, the terrain, the placing module's own input and the seed, and nothing names a host. The module that owns the +placement type declares it with `registerPlacementType(type, jsonFields)`: its option names are reserved at the placement +level, as the host's own fields are at the others, and studio adds the placement-level settings to the type's schema. The +host decodes the placement JSON once per text. A placed object is remembered by a `PlacementRecord` (object id, the +module's placement number, optional structure id) that the terrain keeps beside the blocks and `RunningWorld.placementAt` +reads back; the host stores it in its own form. The terrain is an interface so a module can hold writes (an island that only accepts blocks over itself, a cave that keeps an object inside it) and commit or drop them as one; the host's terrain for a mantle invocation is `MantleGenerationContext.placementTerrain()`. Objects come from `PackResources.objects()` (`PackObjects`), which loads, scales and builds them per pack snapshot. @@ -1172,7 +1178,8 @@ from a sapling, which drops a block has. A module answers such questions through - **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 - table gives, so the host and plugins can change the tables in between. `BlockDrops`, `EntitySpawns` and `SaplingGrowth` + table gives, so the host and plugins can change the tables in between; a third answer is the seed to shuffle the + container's slots with, so the host does not know how the module seeds its loot. `BlockDrops`, `EntitySpawns` and `SaplingGrowth` return values the host carries out: `ItemDrop` and `EntitySpec` carry every decision the module made (the module draws from its streams in the order the feature always did, which is why `ItemRegistry` answers whether an item can be damaged), and the host reads what only the platform knows (light, the surface below, free space, the blocks around a @@ -1188,9 +1195,11 @@ from a sapling, which drops a block has. A module answers such questions through Choices with a fixed set of answers are enums (`ItemAttribute.Operation`, `DyeColor`), colours are RGB ints. - **Groups and extensions.** `ItemDrop` and `EntitySpec` group their components by what a host does with them (`Look`, `Wear`, `PlatformExtras`; `Appearance`, `Behaviour`, `Company`, `Drops`, `Arrival`), each with a named - default, so a reader sees a dozen meaningful parts instead of seventeen positional ones. What only one host can apply - (Iris's spawn reason, panda genes, rising out of the ground) is not an API field: the module puts a value of the host's - own type in `EntitySpec.extensions()`, the host finds it with `extension(type)`, and other hosts ignore it. + default, so a reader sees a dozen meaningful parts instead of seventeen positional ones. What platforms commonly have + (a spawn reason by the platform's name, a panda's genes, rising out of the ground, whether the spec applies to a + provider's mob) is a field of the spec, optional where a platform may lack it. What only one host can apply is not: the + module puts a value of the host's own type in `EntitySpec.extensions()`, the host finds it with `extension(type)`, and + other hosts ignore it. `AmbientEffects` follows the same rule: the module decides which effects are due (interval and chance, kept in the world's state) and every random value they carry, the host only plays them. - **Services now.** `ObjectsAt` (`ALL`): the ids of pack objects a module would place in a chunk, predicted without @@ -1282,9 +1291,10 @@ API now: `world.running()`, `world.seed(purpose)`, `TerrainSampler`, `FeatureSet goes when a world format change lets object placing draw from stage streams and API noise. - **`objects.ObjectRun`** (the input of a placement run, `PlacementRun.input`). The object and the module's own `objects.ObjectPlacement` settings that Iris's built-in placement stages read, and what they report back (the anchor - height, which written blocks are the object's). Iris reads it in two places: for the placement-level module settings of - the run, and when Iris places an object itself (its studio and commands, the jigsaw placer). It goes when those settings - are part of the run the API describes and Iris no longer places objects itself. + height, which written blocks are the object's). The placement-level module settings no longer need it: the run carries + 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 diff --git a/README.md b/README.md index 19d024dc9..167ccc88a 100644 --- a/README.md +++ b/README.md @@ -276,7 +276,8 @@ PlaceableObject tower = objects.object(world.resources().idOf("towers/north")).o PlaceableObject large = objects.scaled(tower, 2, ScaleMethod.TRILINEAR); // kept per pack snapshot PlacementTerrain terrain = context.placementTerrain(); // in a mantle stage -PlacementRun run = new PlacementRun(new PlacementRequest(large.geometry(), anchor), area, terrain, mySettings, seed); +PlacementRun run = new PlacementRun(new PlacementRequest(large.geometry(), anchor), "towers/north", + Optional.of(placementJson), area, terrain, mySettings, seed); PlacementOutcome outcome = world.placements().place(run); if (!outcome.isPlaced()) { context.log().debug("tower rejected: " + outcome.rejection().orElseThrow()); @@ -287,8 +288,15 @@ if (!outcome.isPlaced()) { smart-bored copy, and objects a module builds block by block (`build`). The host keeps them per pack snapshot. - `PlacementTerrain` is the world the placement reads and the host writes into once it commits: heights, blocks, carved space, fluid, the structures nearby and the placement recorded at a block (`recordPlacement`, `placementAt`; - `RunningWorld.placementAt` reads it back later, such as for the loot of a placed object). A module may wrap it to hold - or filter writes; a mantle stage gets one for its invocation from `MantleGenerationContext.placementTerrain()`. + `RunningWorld.placementAt` reads it back later, such as for the loot of a placed object). A recorded placement is a + `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()`. +- `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 + options, so no settings key can take one: `registry.registerPlacementType(MyPlacement.class, names)`. Studio then adds + the placement-level settings to that type's schema. - `input` is what the module hands its own placement stages (`PlacementContext.input(type)`); other modules' stages do not know its type. The area bounds what the placement may write, widened by the reach of the pack's placement stages. - A placement commits whole or not at all: blocks, then markers, and only when no stage rejected and none threw. @@ -441,10 +449,11 @@ final class RuinsObjects implements ObjectsAt { | `ObjectsAt` | `ALL` | The pack objects a module would place in a chunk, predicted without generating it, and the biomes and regions of the layout that place a given object (`PlacedBy`), so the host can narrow an object search to the areas it can appear in. | | `StructureLocator` | `FIRST` | Every structure the module knows (the structure index), the ones a world places and can locate (commands complete them), every id under which it finds what a world places (`placed`: its own structures and the platform structures it starts or stands in for), and the nearest start of one, as a `LocateResult`: `Found(position)`, `NotFound` or `SearchLimitReached`. Ids are lower case, so a host matching typed keys matches without regard to case. | | `SaplingGrowth` | `ALL` | The tree a growing sapling becomes, as a `Growth` of placed blocks (the first module with one wins; none leaves the growth to the platform), and the objects the module places as trees (`TreeObjects`). The host passes `Surroundings` to read the world around the sapling and places the blocks itself. | -| `Loot` | `ALL` | The loot tables a container draws from at a `Site` (`Table` of the pack, `PlatformTable` with the seed to draw it with), in the order their items are added, and the `ItemDrop`s one table gives there. The host puts them together, tells listeners, creates the stacks and shuffles the container. | +| `Loot` | `ALL` | The loot tables a container draws from at a `Site` (`Table` of the pack, `PlatformTable` with the seed to draw it with), in the order their items are added, the `ItemDrop`s one table gives there, and the seed to shuffle the container's slots with (`shuffleSeed`, the first one given wins). The host puts them together, tells listeners, creates the stacks and shuffles the container. | | `BlockDrops` | `ALL` | What a module drops for a broken block: `ItemDrop`s, and whether the platform's own drops of the block are replaced. | | `EntitySpawns` | `ALL` | A `Plan` of entities to spawn in a chunk or at a marker, each `Attempt` an `EntitySpec` with the block, light range and surface it needs; how many appeared (`spawned`); what a marker means (`MarkerRule`); one entity of the pack on request. The host checks light, surface and free space, spawns, and applies the spec. | | `CaveBiomes` | `ONE` | The pack biome a module puts at a position whatever the regions say (a band of the deep dark), and how far below the surface a biome's caves begin. The host places the cave biome of a position itself and asks this where a module overrides it. | +| `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). | | `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. | @@ -625,10 +634,12 @@ another namespace to the plugin that owns it. `ItemDrop` is one stack: the item, the amount, its `Look` (name, lore, custom model, leather colour as RGB, `DyeColor`), enchantments (`ItemEnchantment`), attribute modifiers (`ItemAttribute` with an `Operation`), its `Wear` (unbreakable, damage as a fraction of the item's durability), `PlatformExtras` (item flags and custom NBT, which only some platforms -apply) and, for debugging, its `Source`. `EntitySpec` is one entity: its type, `Appearance`, `Behaviour`, equipment -(`ItemDrop`s), attribute modifiers, `Company` (passengers, leash holder), `Drops` (loot table ids and their shuffle seed), -`Arrival` (spawn effect and console commands) and host extensions, which `extension(type)` finds: what only one host -knows how to apply travels as a value of that host's type and is ignored by the others. Modules ask the platform about +apply) and, for debugging, its `Source`. `EntitySpec` is one entity: its type, `Appearance` (name, glow, baby and a +panda's genes), `Behaviour`, equipment (`ItemDrop`s), attribute modifiers, `Company` (passengers, leash holder), `Drops` +(loot table ids and their shuffle seed), `Arrival` (spawn effect, console commands, the platform's name for the spawn +reason and whether the entity climbs out of the ground), whether the spec also applies to a mob of a content provider +(`adjustsProvidedMob`) and host extensions, which `extension(type)` finds: what only one host knows how to apply travels +as a value of that host's type and is ignored by the others. Modules ask the platform about items through `resources.items()` (`ItemRegistry.maxDurability(item)`, empty for an item the platform lacks): whether an item can be damaged decides whether a loot entry draws a damage roll, so a module needs it to keep its random stream. diff --git a/api/src/main/java/com/volmit/FeatureRegistry.java b/api/src/main/java/com/volmit/FeatureRegistry.java index 894cb8683..b53546a22 100644 --- a/api/src/main/java/com/volmit/FeatureRegistry.java +++ b/api/src/main/java/com/volmit/FeatureRegistry.java @@ -8,6 +8,7 @@ import com.volmit.resource.ResourceKind; import com.volmit.service.Service; import com.volmit.stage.StageGraph; import com.volmit.validation.Validator; +import java.util.Set; /** Host implementation collects non-stage registrations before loading pack configuration. * Feature IDs must be unique. JSON keys must be unique per {@link com.volmit.config.Level}, including the @@ -41,6 +42,15 @@ public interface FeatureRegistry { */ void registerResourceKind(ResourceKind kind); + /** + * Declares the type packs write their object placements as, the JSON object that holds + * {@link com.volmit.config.Level#PLACEMENT}: settings other modules declare on a placement are keys of that same + * object, next to the type's own fields. So no settings key at that level may be one of {@code jsonFields}, the + * names the type's JSON uses, and studio describes {@code type} with those settings added. A pack has one placement + * type; a second declaration, from this module or another, fails the pack load naming both. + */ + void registerPlacementType(Class type, Set jsonFields); + /** Adds a check the host runs over the whole pack wherever it validates packs. */ void registerValidator(Validator validator); diff --git a/api/src/main/java/com/volmit/entity/EntitySpec.java b/api/src/main/java/com/volmit/entity/EntitySpec.java index 2de97d3f3..1313d5d07 100644 --- a/api/src/main/java/com/volmit/entity/EntitySpec.java +++ b/api/src/main/java/com/volmit/entity/EntitySpec.java @@ -21,10 +21,13 @@ import java.util.Optional; * @param company the entities that come with it * @param drops what it drops when it dies * @param arrival what happens where it appears + * @param adjustsProvidedMob whether the rest of the spec also applies to a {@link ContentKey.Provided} mob, which is + * otherwise left as its provider set it up * @param extensions values for a particular host, which other hosts ignore; see {@link #extension} */ public record EntitySpec(ContentKey type, Appearance appearance, Behaviour behaviour, Equipment equipment, - List attributes, Company company, Drops drops, Arrival arrival, List extensions) { + List attributes, Company company, Drops drops, Arrival arrival, + boolean adjustsProvidedMob, List extensions) { public EntitySpec { Objects.requireNonNull(type, "type"); Objects.requireNonNull(appearance, "appearance"); @@ -45,14 +48,20 @@ public record EntitySpec(ContentKey type, Appearance appearance, Behaviour behav /** * How the entity looks. * - * @param customName the name shown above the entity, as authored in the pack with {@code &} colour codes; empty for none - * @param nameVisible whether the name shows even when nobody looks at the entity + * @param customName the name shown above the entity, as authored in the pack with {@code &} colour codes; empty for none + * @param nameVisible whether the name shows even when nobody looks at the entity + * @param pandaMainGene for a panda, its main gene by the platform's name for it; empty to leave it to the platform + * @param pandaHiddenGene for a panda, its hidden gene by the platform's name for it; empty to leave it to the platform */ - public record Appearance(Optional customName, boolean nameVisible, boolean glowing, boolean baby) { - public static final Appearance PLAIN = new Appearance(Optional.empty(), false, false, false); + public record Appearance(Optional customName, boolean nameVisible, boolean glowing, boolean baby, + Optional pandaMainGene, Optional pandaHiddenGene) { + public static final Appearance PLAIN = new Appearance(Optional.empty(), false, false, false, Optional.empty(), + Optional.empty()); public Appearance { Objects.requireNonNull(customName, "customName"); + Objects.requireNonNull(pandaMainGene, "pandaMainGene"); + Objects.requireNonNull(pandaHiddenGene, "pandaHiddenGene"); } } @@ -117,15 +126,20 @@ public record EntitySpec(ContentKey type, Appearance appearance, Behaviour behav /** * What happens where the entity appears. * - * @param effect an effect to show; empty for none - * @param commands console commands to run + * @param effect an effect to show; empty for none + * @param commands console commands to run + * @param reason why the entity appears, by the platform's name for the reason, such as {@code COMMAND}; empty + * for a natural spawn + * @param risesFromGround whether the entity slowly climbs out of the ground when players are near */ - public record Arrival(Optional effect, List commands) { - public static final Arrival QUIET = new Arrival(Optional.empty(), List.of()); + public record Arrival(Optional effect, List commands, Optional reason, + boolean risesFromGround) { + public static final Arrival QUIET = new Arrival(Optional.empty(), List.of(), Optional.empty(), false); public Arrival { Objects.requireNonNull(effect, "effect"); commands = List.copyOf(commands); + Objects.requireNonNull(reason, "reason"); } } diff --git a/api/src/main/java/com/volmit/placement/PlacementRecord.java b/api/src/main/java/com/volmit/placement/PlacementRecord.java new file mode 100644 index 000000000..4fbe0b758 --- /dev/null +++ b/api/src/main/java/com/volmit/placement/PlacementRecord.java @@ -0,0 +1,34 @@ +package com.volmit.placement; + +import com.volmit.resource.ResourceId; + +import java.util.Objects; +import java.util.Optional; + +/** + * What a module recorded beside a block when it placed an object there ({@link PlacementTerrain#recordPlacement}), and + * what later placements and services read back ({@link PlacementTerrain#placementAt}, + * {@link com.volmit.world.RunningWorld#placementAt}): which object stands there, which placement of it that was and, for a + * piece of a structure, which structure. + * + * @param object the pack object, or the name the module gave an object it made itself, as an id + * @param placementId the number the placing module gave this placement, which tells it apart from other placements of the + * same object; the module picks it, the host keeps it as it is + * @param structure the structure the object is a piece of; empty for an object placed on its own + */ +public record PlacementRecord(ResourceId object, int placementId, Optional structure) { + public PlacementRecord { + Objects.requireNonNull(object, "object"); + Objects.requireNonNull(structure, "structure"); + } + + /** An object placed on its own. */ + public static PlacementRecord of(ResourceId object, int placementId) { + return new PlacementRecord(object, placementId, Optional.empty()); + } + + /** A piece of {@code structure}. */ + public static PlacementRecord ofPiece(ResourceId object, int placementId, ResourceId structure) { + return new PlacementRecord(object, placementId, Optional.of(structure)); + } +} diff --git a/api/src/main/java/com/volmit/placement/PlacementRun.java b/api/src/main/java/com/volmit/placement/PlacementRun.java index db3722168..52085a789 100644 --- a/api/src/main/java/com/volmit/placement/PlacementRun.java +++ b/api/src/main/java/com/volmit/placement/PlacementRun.java @@ -3,22 +3,32 @@ package com.volmit.placement; import com.volmit.geometry.BlockBox; import java.util.Objects; +import java.util.Optional; /** * One object a module asks the host to place through the pack's placement stages ({@link Placements#place}). * - * @param request the object and where it goes - * @param area the blocks the object may reach around its anchor in any way it is placed; the host widens it by the - * reach the pack's placement stages declare, and the result bounds the placement's {@link PlacementAccess}. - * Reaching outside fails the placement - * @param terrain the world the placement reads, and where the host writes the blocks when the placement commits - * @param input what the placing module hands its own stages, such as its placement settings; stages read it with - * {@link PlacementContext#input}, and stages of other modules do not know its type - * @param seed the seed the stages' random streams derive from; the same seed, stages and inputs give the same placement + * @param request the object and where it goes + * @param name the placement's display name, such as the object's key: it labels the placement in the host's logs and + * names the source of the settings the pack declares on it + * @param settings the placement as the pack wrote it, a JSON object, from which the host reads the settings that pack + * modules declare at {@link com.volmit.config.Level#PLACEMENT} so that stages see them like any other + * level's; the placement type's own fields ({@link com.volmit.FeatureRegistry#registerPlacementType}) are + * not settings and are ignored. Empty for a placement the pack did not write. Equal text is read once + * @param area the blocks the object may reach around its anchor in any way it is placed; the host widens it by the + * reach the pack's placement stages declare, and the result bounds the placement's {@link PlacementAccess}. + * Reaching outside fails the placement + * @param terrain the world the placement reads, and where the host writes the blocks when the placement commits + * @param input what the placing module hands its own stages, such as its placement settings; stages read it with + * {@link PlacementContext#input}, and stages of other modules do not know its type + * @param seed the seed the stages' random streams derive from; the same seed, stages and inputs give the same placement */ -public record PlacementRun(PlacementRequest request, BlockBox area, PlacementTerrain terrain, Object input, long seed) { +public record PlacementRun(PlacementRequest request, String name, Optional settings, BlockBox area, + PlacementTerrain terrain, Object input, long seed) { public PlacementRun { Objects.requireNonNull(request, "request"); + Objects.requireNonNull(name, "name"); + Objects.requireNonNull(settings, "settings"); Objects.requireNonNull(area, "area"); Objects.requireNonNull(terrain, "terrain"); Objects.requireNonNull(input, "input"); diff --git a/api/src/main/java/com/volmit/placement/PlacementTerrain.java b/api/src/main/java/com/volmit/placement/PlacementTerrain.java index c0722d783..826886ca9 100644 --- a/api/src/main/java/com/volmit/placement/PlacementTerrain.java +++ b/api/src/main/java/com/volmit/placement/PlacementTerrain.java @@ -43,13 +43,13 @@ public interface PlacementTerrain { boolean preventsDecay(); /** - * Records that the block belongs to {@code placement}, the name the placing module gives one placed object, so a - * later placement can tell what is already there ({@link #placementAt}). The host keeps the name as it is. + * Records that the block belongs to {@code placement}, one placed object, so a later placement can tell what is + * already there ({@link #placementAt}). The host keeps the record beside the block in its generation storage. */ - void recordPlacement(int x, int y, int z, String placement); + void recordPlacement(int x, int y, int z, PlacementRecord placement); /** The placement recorded at the block ({@link #recordPlacement}); empty when none is. */ - Optional placementAt(int x, int y, int z); + Optional placementAt(int x, int y, int z); /** The bounds of the platform's structure pieces planned around the columns, for placements that keep out of them. */ StructureVolumes structureVolumes(int minX, int minZ, int maxX, int maxZ); diff --git a/api/src/main/java/com/volmit/service/Loot.java b/api/src/main/java/com/volmit/service/Loot.java index 79c16728e..fd3056976 100644 --- a/api/src/main/java/com/volmit/service/Loot.java +++ b/api/src/main/java/com/volmit/service/Loot.java @@ -8,6 +8,7 @@ import com.volmit.world.PackWorld; import java.util.List; import java.util.Objects; import java.util.Optional; +import java.util.OptionalLong; /** * The loot a module gives containers and mobs. The host asks in two steps so that it, and plugins listening to it, can @@ -27,6 +28,16 @@ public interface Loot { /** The items the pack's table {@code table} gives at {@code site}; empty for a table this module does not know. */ List items(PackWorld world, Site site, ResourceId table); + /** + * The seed the host shuffles the slots of the container at {@code site} with after it filled it, so that the same + * container always ends up with its items in the same slots. Empty to leave the order to the host's other providers; + * the host uses the first seed it gets, in module id order, and keeps the items in the order of the tables when no + * provider gives one. + */ + default OptionalLong shuffleSeed(PackWorld world, Site site) { + return OptionalLong.empty(); + } + /** * Where loot is given. * diff --git a/api/src/main/java/com/volmit/service/ProtectedFloor.java b/api/src/main/java/com/volmit/service/ProtectedFloor.java new file mode 100644 index 000000000..949ad96c8 --- /dev/null +++ b/api/src/main/java/com/volmit/service/ProtectedFloor.java @@ -0,0 +1,18 @@ +package com.volmit.service; + +import com.volmit.world.PackWorld; + +/** + * Whether the lowest layer of the world, the blocks at height 0, belongs to the module that shapes the terrain, such as + * a bedrock floor it writes itself. When it does, the host discards the blocks that placements and other stages write + * there, so that nothing replaces the floor. A pack has one provider, since two modules could not both own the floor. + * Without a provider the host protects nothing. + */ +@Service(Providers.ONE) +public interface ProtectedFloor { + /** + * Whether the host discards blocks written at height 0 of {@code world}. The answer depends on the world and its + * settings only: the host asks once when it starts the world and keeps it while the world runs. + */ + boolean protectsFloor(PackWorld world); +} diff --git a/api/src/main/java/com/volmit/world/RunningWorld.java b/api/src/main/java/com/volmit/world/RunningWorld.java index b221279c0..a92db8f6c 100644 --- a/api/src/main/java/com/volmit/world/RunningWorld.java +++ b/api/src/main/java/com/volmit/world/RunningWorld.java @@ -2,6 +2,7 @@ package com.volmit.world; import com.volmit.config.FeatureSettings; import com.volmit.geometry.BlockPosition; +import com.volmit.placement.PlacementRecord; import com.volmit.resource.ResourceId; import java.util.List; import java.util.Optional; @@ -39,7 +40,7 @@ public interface RunningWorld { * ({@link com.volmit.placement.PlacementTerrain#recordPlacement}); empty when none was, or when the block's chunk * keeps no generation data any more. Y is the height above the dimension's bottom. */ - Optional placementAt(int worldX, int y, int worldZ); + Optional placementAt(int worldX, int y, int worldZ); /** The time and weather of the world; empty while the platform has not loaded the world. */ Optional sky(); diff --git a/api/src/test/java/com/volmit/ItemAndEntityValuesTest.java b/api/src/test/java/com/volmit/ItemAndEntityValuesTest.java index 03712b3af..cb6985190 100644 --- a/api/src/test/java/com/volmit/ItemAndEntityValuesTest.java +++ b/api/src/test/java/com/volmit/ItemAndEntityValuesTest.java @@ -4,12 +4,15 @@ import com.volmit.entity.EntitySpec; import com.volmit.geometry.BlockPosition; import com.volmit.item.ItemDrop; import com.volmit.item.ItemEnchantment; +import com.volmit.placement.PlacementRecord; import com.volmit.resource.ContentKey; import com.volmit.resource.ResourceId; import com.volmit.service.AmbientEffects; import com.volmit.service.BlockDrops; import com.volmit.service.EntitySpawns; +import com.volmit.service.Loot; import com.volmit.service.SaplingGrowth; +import com.volmit.world.PackWorld; import org.junit.jupiter.api.Test; import java.util.ArrayList; @@ -75,6 +78,50 @@ class ItemAndEntityValuesTest { assertEquals(Optional.empty(), zombie.extension(Integer.class)); } + @Test + void anEntityCarriesWhatOnlyAPlatformHasANameForInsteadOfAnExtension() { + EntitySpec.Appearance panda = new EntitySpec.Appearance(Optional.empty(), false, false, false, Optional.of("PLAYFUL"), + Optional.of("WEAK")); + EntitySpec.Arrival command = new EntitySpec.Arrival(Optional.empty(), List.of(), Optional.of("COMMAND"), true); + + assertEquals(Optional.of("PLAYFUL"), panda.pandaMainGene()); + assertEquals(Optional.of("COMMAND"), command.reason()); + assertTrue(command.risesFromGround()); + assertTrue(EntitySpec.Appearance.PLAIN.pandaHiddenGene().isEmpty()); + assertTrue(EntitySpec.Arrival.QUIET.reason().isEmpty()); + assertFalse(EntitySpec.Arrival.QUIET.risesFromGround()); + assertThrows(NullPointerException.class, () -> new EntitySpec.Arrival(Optional.empty(), List.of(), null, false)); + } + + @Test + void aPlacementRecordNamesItsObjectAndAnOptionalStructure() { + ResourceId oak = ResourceId.parse("overworld:trees/oak"); + ResourceId village = ResourceId.parse("overworld:village"); + + assertEquals(Optional.empty(), PlacementRecord.of(oak, 7).structure()); + assertEquals(Optional.of(village), PlacementRecord.ofPiece(oak, 7, village).structure()); + assertEquals(PlacementRecord.of(oak, 7), new PlacementRecord(oak, 7, Optional.empty())); + assertThrows(NullPointerException.class, () -> new PlacementRecord(null, 7, Optional.empty())); + } + + @Test + void aLootProviderGivesNoShuffleSeedUnlessItSaysSo() { + Loot loot = new Loot() { + @Override + public List tables(PackWorld world, Site site) { + return List.of(); + } + + @Override + public List items(PackWorld world, Site site, ResourceId table) { + return List.of(); + } + }; + Loot.Site site = new Loot.Site(new BlockPosition(1, 2, 3), Optional.empty(), false, false); + + assertTrue(loot.shuffleSeed(null, site).isEmpty()); + } + @Test void anAttemptSaysWhetherLightMatters() { BlockPosition at = new BlockPosition(1, 2, 3); @@ -109,6 +156,6 @@ class ItemAndEntityValuesTest { private static EntitySpec entity(List extensions) { return new EntitySpec(new ContentKey.Registered(ResourceId.parse("minecraft:zombie")), EntitySpec.Appearance.PLAIN, EntitySpec.Behaviour.NATURAL, EntitySpec.Equipment.NONE, List.of(), EntitySpec.Company.NONE, - EntitySpec.Drops.PLATFORM, EntitySpec.Arrival.QUIET, extensions); + EntitySpec.Drops.PLATFORM, EntitySpec.Arrival.QUIET, false, extensions); } } diff --git a/host/src/main/java/com/volmit/host/FeatureCatalog.java b/host/src/main/java/com/volmit/host/FeatureCatalog.java index b62a513c9..7434599e2 100644 --- a/host/src/main/java/com/volmit/host/FeatureCatalog.java +++ b/host/src/main/java/com/volmit/host/FeatureCatalog.java @@ -40,6 +40,7 @@ public final class FeatureCatalog { private final List lifecycles; private final Map, List> registrationsByService; private final Map, List> providersByService; + private final Optional placementType; FeatureCatalog( Map, FeatureDescriptor> settings, @@ -48,7 +49,9 @@ public final class FeatureCatalog { Collection resourceKinds, List validators, List lifecycles, - List services) { + List services, + PlacementTypeRegistration placementType) { + this.placementType = Optional.ofNullable(placementType); this.settings = Map.copyOf(settings); this.objects = Map.copyOf(objects); this.mantle = Map.copyOf(mantle); @@ -72,6 +75,11 @@ public final class FeatureCatalog { return sorted(mantle.values(), registration -> registration.key().id()); } + /** The type packs write their object placements as, if a module declared it ({@code FeatureRegistry.registerPlacementType}). */ + public Optional placementType() { + return placementType; + } + /** The pack resource kinds modules read, by kind id. */ public List resourceKinds() { return resourceKinds; diff --git a/host/src/main/java/com/volmit/host/ModuleRegistry.java b/host/src/main/java/com/volmit/host/ModuleRegistry.java index a4bce3c32..d0ba59a87 100644 --- a/host/src/main/java/com/volmit/host/ModuleRegistry.java +++ b/host/src/main/java/com/volmit/host/ModuleRegistry.java @@ -47,6 +47,7 @@ public final class ModuleRegistry implements FeatureRegistry { private final List services = new ArrayList<>(); private final Set reservedFolders; private final List registered = new ArrayList<>(); + private PlacementTypeRegistration placementType; private FeatureCatalog catalog; private DiscoveredModule registering; @@ -128,6 +129,36 @@ public final class ModuleRegistry implements FeatureRegistry { resourceKinds.put(kind.id(), registration); } + @Override + public void registerPlacementType(Class type, Set jsonFields) { + checkOpen(); + Objects.requireNonNull(type, "type"); + Objects.requireNonNull(jsonFields, "jsonFields"); + requireRegistering("Placement type " + type.getName()); + var added = new PlacementTypeRegistration(type, jsonFields, registering); + if (placementType != null) { + throw new IllegalArgumentException("A pack has one placement type: " + placementType + " declared it already, and " + + added + " declares it too; remove one of them"); + } + added.jsonFields().forEach(FeatureDescriptor::requireFieldName); + for (var field : added.jsonFields().stream().sorted().toList()) { + requireUnclaimedPlacementField(field, added); + } + added.jsonFields().forEach(field -> keyClaimants.put(new KeyAtTarget(Level.PLACEMENT, field), KeyClaimant.of(added))); + placementType = added; + } + + /** A field of the placement type is a JSON key of the placement, which a setting cannot also be. */ + private void requireUnclaimedPlacementField(String field, PlacementTypeRegistration added) { + var earlier = keyClaimants.get(new KeyAtTarget(Level.PLACEMENT, field)); + if (earlier == null) return; + var later = KeyClaimant.of(added); + var first = earlier.compareTo(later) <= 0 ? earlier : later; + var second = first == earlier ? later : earlier; + throw new IllegalArgumentException(targetName(Level.PLACEMENT) + " key \"" + field + "\" is claimed by " + first + + " and " + second + "; give the setting another key in its @Feature"); + } + @Override public void registerValidator(Validator validator) { checkOpen(); @@ -184,7 +215,8 @@ public final class ModuleRegistry implements FeatureRegistry { public FeatureCatalog freeze() { if (catalog == null) { - catalog = new FeatureCatalog(settings, objects, mantle, resourceKinds.values(), validators, lifecycles, services); + catalog = new FeatureCatalog(settings, objects, mantle, resourceKinds.values(), validators, lifecycles, services, + placementType); } return catalog; } @@ -308,8 +340,17 @@ public final class ModuleRegistry implements FeatureRegistry { } static KeyClaimant of(FeatureDescriptor descriptor, DiscoveredModule owner) { - var source = owner.source() == DiscoveredModule.Source.HOST ? Source.BUILT_IN : Source.PACK; - return new KeyClaimant(source, descriptor.id().toString(), descriptor.id() + " (" + owner.origin() + ")"); + return new KeyClaimant(sourceOf(owner), descriptor.id().toString(), descriptor.id() + " (" + owner.origin() + ")"); + } + + static KeyClaimant of(PlacementTypeRegistration placementType) { + var owner = placementType.module(); + return new KeyClaimant(sourceOf(owner), placementType.type().getName(), + "the fields of " + placementType.type().getName() + " (" + owner.origin() + ")"); + } + + private static Source sourceOf(DiscoveredModule owner) { + return owner.source() == DiscoveredModule.Source.HOST ? Source.BUILT_IN : Source.PACK; } @Override diff --git a/host/src/main/java/com/volmit/host/PackSchemaBuilder.java b/host/src/main/java/com/volmit/host/PackSchemaBuilder.java index 7e2c97ee0..ee3af8285 100644 --- a/host/src/main/java/com/volmit/host/PackSchemaBuilder.java +++ b/host/src/main/java/com/volmit/host/PackSchemaBuilder.java @@ -51,7 +51,7 @@ final class PackSchemaBuilder { requireUniqueSnippets(); var types = completeTypes(); return new PackSchema(features.stream().map(feature -> feature.complete(types)).toList(), resources, - List.copyOf(types.values())); + List.copyOf(types.values()), catalog.placementType().map(placement -> placement.type().getName())); } private static Optional resourceKindOf(FeatureCatalog catalog, Class type) { diff --git a/host/src/main/java/com/volmit/host/PlacementTypeRegistration.java b/host/src/main/java/com/volmit/host/PlacementTypeRegistration.java new file mode 100644 index 000000000..b9c17fe5b --- /dev/null +++ b/host/src/main/java/com/volmit/host/PlacementTypeRegistration.java @@ -0,0 +1,18 @@ +package com.volmit.host; + +import java.util.Objects; +import java.util.Set; + +/** The type a pack's object placements are written as, its JSON field names and the module that declared it. */ +public record PlacementTypeRegistration(Class type, Set jsonFields, DiscoveredModule module) { + public PlacementTypeRegistration { + Objects.requireNonNull(type, "type"); + jsonFields = Set.copyOf(jsonFields); + Objects.requireNonNull(module, "module"); + } + + @Override + public String toString() { + return "placement type " + type.getName() + " from module " + module; + } +} diff --git a/host/src/main/java/com/volmit/host/schema/PackSchema.java b/host/src/main/java/com/volmit/host/schema/PackSchema.java index c995312fa..b807f5c6d 100644 --- a/host/src/main/java/com/volmit/host/schema/PackSchema.java +++ b/host/src/main/java/com/volmit/host/schema/PackSchema.java @@ -6,6 +6,7 @@ import java.util.Comparator; import java.util.List; import java.util.NoSuchElementException; import java.util.Objects; +import java.util.Optional; /** What the modules of a loaded pack add to the pack's JSON, for the host to render as JSON Schema and * studio completion. It holds module-provided entries only: the host describes its own fields. @@ -17,12 +18,16 @@ import java.util.Objects; * @param features every catalogued settings type of the pack's modules, built-in ones included * @param resources every resource kind of the pack's modules, built-in ones included * @param types every class reachable from those settings and resource kinds, each once + * @param placementType the name of the class packs write their object placements as, the JSON holder of + * {@link Level#PLACEMENT}, if a module declared it ({@code FeatureRegistry.registerPlacementType}) */ -public record PackSchema(List features, List resources, List types) { +public record PackSchema(List features, List resources, List types, + Optional placementType) { public PackSchema { features = features.stream().sorted(Comparator.comparing(FeatureSchema::id)).toList(); resources = resources.stream().sorted(Comparator.comparing(ResourceKindSchema::id)).toList(); types = types.stream().sorted(Comparator.comparing(ObjectType::name)).toList(); + Objects.requireNonNull(placementType, "placementType"); } /** The resource kind {@code id}, such as the one a {@link ValueKind.ResourceReferenceKind} names. */ diff --git a/host/src/test/java/com/volmit/host/ModuleRegistryTest.java b/host/src/test/java/com/volmit/host/ModuleRegistryTest.java index 12f9aa2d2..d4dadf0ed 100644 --- a/host/src/test/java/com/volmit/host/ModuleRegistryTest.java +++ b/host/src/test/java/com/volmit/host/ModuleRegistryTest.java @@ -36,6 +36,10 @@ class ModuleRegistryTest { static class Veins implements IrisFeature {} @Feature(id = "test:named", name = "Named", key = "name", targets = Level.BIOME) static class Named implements IrisFeature {} + @Feature(id = "test:seams", name = "Seams", key = "deposits", targets = Level.PLACEMENT) + static class Seams implements IrisFeature {} + static class Placement {} + static class OtherPlacement {} static class MissingAnnotation implements IrisFeature {} @Feature(id = "test:core/abstract", name = "Abstract", key = "coreAbstract", targets = Level.BIOME) abstract static class AbstractFeature implements IrisFeature {} @@ -224,6 +228,62 @@ class ModuleRegistryTest { assertTrue(stage.getMessage().startsWith("region key \"deposits\" is claimed by test:minerals (host classpath) and test:ores"), stage.getMessage()); } + @Test + void aPlacementTypeIsKeptWithItsFieldsAndReservesThemAsKeysOfThePlacementLevel() { + var registry = new ModuleRegistry(); + registerAs(registry, "test:objects", placements -> placements.registerPlacementType(Placement.class, Set.of("place", "chance"))); + + var declared = registry.freeze().placementType().orElseThrow(); + + assertEquals(Placement.class, declared.type()); + assertEquals(Set.of("place", "chance"), declared.jsonFields()); + assertTrue(new ModuleRegistry().freeze().placementType().isEmpty()); + } + + @Test + void theSchemaNamesThePlacementTypeForStudio() { + var objects = new IrisModule() { + public ModuleInfo info() { return ModuleInfo.of("test:objects", "Objects", "1"); } + public void setup(ModuleSetup setup) { setup.registry().registerPlacementType(Placement.class, Set.of("place")); } + }; + + var loaded = LoadedModules.load(discovered(objects), Map.of(), Set.of(), Set.of()); + + assertEquals(Optional.of(Placement.class.getName()), loaded.schema().placementType()); + assertTrue(LoadedModules.load(discovered(), Map.of(), Set.of(), Set.of()).schema().placementType().isEmpty()); + } + + @Test + void aSettingsKeyThatIsAFieldOfThePlacementTypeIsRefusedInEitherOrder() { + var placementFirst = new ModuleRegistry(); + registerAs(placementFirst, "test:objects", placements -> placements.registerPlacementType(Placement.class, Set.of("deposits"))); + var late = assertThrows(IllegalArgumentException.class, + () -> registerAs(placementFirst, "test:seams", settings -> settings.registerSettings(Seams.class))); + assertEquals("placement key \"deposits\" is claimed by the fields of " + Placement.class.getName() + + " (host classpath) and test:seams (host classpath); give one of the settings another key in its @Feature", late.getMessage()); + + var settingsFirst = new ModuleRegistry(); + registerAs(settingsFirst, "test:seams", settings -> settings.registerSettings(Seams.class)); + var early = assertThrows(IllegalArgumentException.class, + () -> registerAs(settingsFirst, "test:objects", placements -> placements.registerPlacementType(Placement.class, Set.of("deposits")))); + assertEquals("placement key \"deposits\" is claimed by the fields of " + Placement.class.getName() + + " (host classpath) and test:seams (host classpath); give the setting another key in its @Feature", early.getMessage()); + assertTrue(settingsFirst.freeze().placementType().isEmpty(), "a refused placement type is not kept"); + } + + @Test + void aPackHasOnePlacementType() { + var registry = new ModuleRegistry(); + registerAs(registry, "test:objects", placements -> placements.registerPlacementType(Placement.class, Set.of("place"))); + + var second = assertThrows(IllegalArgumentException.class, + () -> registerAs(registry, "test:other", placements -> placements.registerPlacementType(OtherPlacement.class, Set.of("kind")))); + + assertTrue(second.getMessage().startsWith("A pack has one placement type: placement type " + Placement.class.getName() + + " from module test:objects from host classpath declared it already"), second.getMessage()); + assertEquals(Placement.class, registry.freeze().placementType().orElseThrow().type()); + } + @Test void aRefusedKeyLeavesNothingClaimedByTheFailedFeature() { var registry = new ModuleRegistry(Map.of(Level.REGION, Set.of("deposits")), Set.of());