Batch 3 of the API review: extension point, resources by kind

- PackWorld, InvocationContext and PackSettings get extension(type),
  an Optional empty by default: the one door a host's own modules use
  to reach its facades. The runners forward the inputs' extensions;
  the world a module sees (ModuleWorld, built by the host) forwards
  the world's. PackWorld.withLog is gone.
- A chunk stage writes registered mantle layers inside its own chunk
  and reads the rest (ChunkMantle); ReadOnlyMantle and its host() are
  gone.
- PackResources.find(kind, id), require(kind, id), ids(kind) and the
  host kinds BIOMES, REGIONS, OBJECTS replace ResourceKey and
  ResourceKind.key. Services and LinkedBiomes name pack resources by
  ResourceId. @Ref(PACK_*) and @ResourceRef fit ResourceId fields.
- BlockAccess extends BlockView.
- Absent values in ItemDrop, EntitySpec and AmbientEffects.Effect are
  Optionals; StructureFit.Start.key() returns a StartKey.
- Mantle.caverns() becomes isCarved(x, y, z).
- OptionsMetadata and DeclaredFieldOrder move to com.volmit.host.
- README, DESIGN and CONTRACTS updated; ExtensionsTest added.
This commit is contained in:
piexel committed 2026-10-24 00:17:10 +02:00
1 parent 7143908d4b
commit 3a307b5b8e
54 files changed
+821 -398

No files matched your search

+12 -7
View File
@@ -22,8 +22,9 @@ types that carry them and lists what the Iris adapter still owes.
| Per-block work with single-pass cost | `BlockStage`, fused block passes | | Per-block work with single-pass cost | `BlockStage`, fused block passes |
| Pack-load validation and diagnostics | host `StageGraphBuilder`, `ResolvedGraph`, `LoadedModules` | | Pack-load validation and diagnostics | host `StageGraphBuilder`, `ResolvedGraph`, `LoadedModules` |
| Reference execution | host `PlacementRunner`, `ChunkRunner`, `MantleRunner`, each timed through host `StageTimings` | | Reference execution | host `PlacementRunner`, `ChunkRunner`, `MantleRunner`, each timed through host `StageTimings` |
| Work across chunks and mantle writes | `Stage.mantle`, `MantleStage`, `MantleStageContext`, `MantleGenerationContext`; chunk stages read the mantle only | | Work across chunks and mantle writes | `Stage.mantle`, `MantleStage`, `MantleStageContext`, `MantleGenerationContext`; chunk stages write registered layers in their own chunk only and read the neighbors |
| Annotated settings | `IrisFeature`, `@Feature` (id, short JSON `key`, optional `root`), config annotations, `OptionsMetadata`, `LinkedBiomes` (`treeBiomes`, `usedBiomes`: pack biomes the settings bring into the layout) | | Annotated settings | `IrisFeature`, `@Feature` (id, short JSON `key`, optional `root`), config annotations, host `OptionsMetadata`, `LinkedBiomes` (`treeBiomes`, `usedBiomes`: pack biomes the settings bring into the layout) |
| Host facades for the host's own modules | `PackWorld.extension(type)`, `InvocationContext.extension(type)`, `PackSettings.extension(type)` (each an `Optional`, empty by default) |
| Area a stage writes | `reach(blocks)`, `reach(PackReach)`, `writesMantle(...)` on stage definitions, `PackSettings`, host `StageReach`, `ResolvedStage.reachBlocks`, `PipelineReach` | | Area a stage writes | `reach(blocks)`, `reach(PackReach)`, `writesMantle(...)` on stage definitions, `PackSettings`, host `StageReach`, `ResolvedStage.reachBlocks`, `PipelineReach` |
| Settings described for studio | `@Desc`, `@Required`, `@MinNumber`, `@MaxNumber`, `@MinItems`, `@Snippet`, `@Ref`/`Reference`, `FeatureRegistry.registerSettings`, `FeatureRegistry.registerHeldType`, host `FeatureCatalog.heldTypes()`, host `LoadedPack.schema()` (`PackSchema`, `FeatureSchema`, `ObjectType`, `SchemaOption`, `ValueKind` with `HostKind`), `ModuleHost.describingHostTypesIn` | | Settings described for studio | `@Desc`, `@Required`, `@MinNumber`, `@MaxNumber`, `@MinItems`, `@Snippet`, `@Ref`/`Reference`, `FeatureRegistry.registerSettings`, `FeatureRegistry.registerHeldType`, host `FeatureCatalog.heldTypes()`, host `LoadedPack.schema()` (`PackSchema`, `FeatureSchema`, `ObjectType`, `SchemaOption`, `ValueKind` with `HostKind`), `ModuleHost.describingHostTypesIn` |
| Geometry and mantle registration | `FeatureRegistry`, host `ModuleRegistry`, `FeatureCatalog` | | Geometry and mantle registration | `FeatureRegistry`, host `ModuleRegistry`, `FeatureCatalog` |
@@ -31,7 +32,7 @@ types that carry them and lists what the Iris adapter still owes.
| Noise from pack-described styles | `NoiseStyle`, `StyledRange`, `PackResources.noise()`, `NoiseFactory`, `NoiseSampler` | | 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` | | 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`, `startedStructures`, `locatableStarts`, `locateStart`, `ChunkFilter`), `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`, `startedStructures`, `locatableStarts`, `locateStart`, `ChunkFilter`), `VanillaStructureRule`, `VanillaStructureContext`, `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`), `ResourceKey<T>`, `PackResources` (`find`, `ids`, `idOf`), `PackBiome`, `PackRegion` | | Pack-scoped resolution | `ResourceId` (`ofPackKey`), `PackResources` (`find(kind, id)`, `require`, `ids(kind)`, `idOf`; kinds `BIOMES`, `REGIONS`, `OBJECTS`), `PackBiome`, `PackRegion` |
| Module-owned pack resources | `ResourceKind`, `FeatureRegistry.registerResourceKind`, `@ResourceRef`, host `ModuleHost.reservingFolders`, `FeatureCatalog.resourceKinds()`, `ResourceKindSchema`, `ValueKind.ResourceReferenceKind` | | 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()` | | Module-owned pack checks | `Validator`, `ValidationContext`, `Problem`, `Severity`, `Subject`, `FeatureRegistry.registerValidator`, host `FeatureCatalog.validators()` |
| Per-world module state | `PackWorld` (`state`), `InvocationContext.world()`, host `WorldStates` | | Per-world module state | `PackWorld` (`state`), `InvocationContext.world()`, host `WorldStates` |
@@ -109,8 +110,10 @@ running Iris is the pack publisher's responsibility.
decode them as Iris does, and render each `HostKind` with Iris's own description of the class. decode them as Iris does, and render each `HostKind` with Iris's own description of the class.
- Back each module's log with the host's own: `ModuleHost.loggingTo(logger)` where `logger` writes `DEBUG` only when the - Back each module's log with the host's own: `ModuleHost.loggingTo(logger)` where `logger` writes `DEBUG` only when the
host's debug setting is on and writes an `ERROR` with a cause as the host reports its own failures. Implement host's debug setting is on and writes an `ERROR` with a cause as the host reports its own failures. Implement
`PackWorld.log()` and `withLog(log)` (a view of the world sharing everything else) and hand services a world scoped to the `PackWorld.log()` (the host's own log) and hand services a world scoped to the provider's module
provider's module (`ServiceRegistration.scope`); the runners do it for stages and hooks. (`ServiceRegistration.scope`); the runners do it for stages and hooks.
- Offer the facades of the host's own modules through `extension(type)` on the world, the invocation inputs and the pack
settings, and nowhere else: no thread-bound state and no interfaces for modules to cast to.
- Hand modules heights above the dimension's bottom (0 = bottom block, whatever the platform's minimum - Hand modules heights above the dimension's bottom (0 = bottom block, whatever the platform's minimum
height is) in every value that carries Y: samples, bounds, block views, placement edits, the mantle, height is) in every value that carries Y: samples, bounds, block views, placement edits, the mantle,
hunks. X and Z stay world coordinates. Convert in one place at the boundary. hunks. X and Z stay world coordinates. Convert in one place at the boundary.
@@ -130,13 +133,15 @@ running Iris is the pack publisher's responsibility.
- Run each mantle stage (`MantleRunner.generate(stage, ...)`) as its own pass, in resolved order: for - Run each mantle stage (`MantleRunner.generate(stage, ...)`) as its own pass, in resolved order: for
every chunk within that stage's reach plus the reach of every later stage of a chunk, each chunk once, every chunk within that stage's reach plus the reach of every later stage of a chunk, each chunk once,
before the next stage and before that chunk generates, with the mantle widened by the stage's reach. before the next stage and before that chunk generates, with the mantle widened by the stage's reach.
Give chunk stages that chunk's mantle; `ChunkRunner` makes it read-only. Give chunk stages a `TerrainSampler` over the Give chunk stages that chunk's mantle; `ChunkRunner` limits writes to the chunk's own columns. Give chunk stages a `TerrainSampler` over the
chunk and the 16 blocks around it, and mantle stages one over the chunk and the larger of their reach and 16 blocks. chunk and the 16 blocks around it, and mantle stages one over the chunk and the larger of their reach and 16 blocks.
- Serve `Mantle.blocks()` in every invocation: the blocks placements wrote into the mantle, read-only, none where the - Serve `Mantle.blocks()` in every invocation: the blocks placements wrote into the mantle, read-only, none where the
dimension keeps no mantle or the chunk generates without it. A block a stage reads and writes back unchanged keeps dimension keeps no mantle or the chunk generates without it. A block a stage reads and writes back unchanged keeps
the host's own identity of it (a custom block of a content plugin stays one). the host's own identity of it (a custom block of a content plugin stays one).
- Serve `Mantle.caverns()` in every invocation (read-only, none where the dimension keeps no mantle) and cover the chunk and the 16 blocks - Answer `Mantle.isCarved(x, y, z)` in every invocation (false where the dimension keeps no mantle) and cover the chunk and the 16 blocks
around it in a chunk stage's mantle, as the sampler does. around it in a chunk stage's mantle, as the sampler does.
- Name pack resources to services by `ResourceId` and convert to the host's keys at the host's edge; read a `ResourceId`
setting written as a bare pack key as the pack's id of that key.
- Answer `TerrainSampler.surfaceBiome(x, z)` (the id `biome(x, y, z).surfaceBiome()` gives), `surfaceKind`, `minWorldY()`, `surfaceBlock` (empty - Answer `TerrainSampler.surfaceBiome(x, z)` (the id `biome(x, y, z).surfaceBiome()` gives), `surfaceKind`, `minWorldY()`, `surfaceBlock` (empty
where no image map gives one) and `upperDimension()` (empty when nothing sits above); `FeatureSettings.declaredBy(biome, type)` answers the where no image map gives one) and `upperDimension()` (empty when nothing sits above); `FeatureSettings.declaredBy(biome, type)` answers the
settings the biome declares itself (empty when it declares none or is unknown); `BlockRegistry.oreFor` answers from the platform. settings the biome declares itself (empty when it declares none or is unknown); `BlockRegistry.oreFor` answers from the platform.
+52 -28
View File
@@ -538,8 +538,11 @@ map gives the ground, `minWorldY` the world Y of the dimension's bottom (setting
`upperDimension()` the dimension stacked above, whose own settings (`UpperDimension.settings()`), resources and image-map blocks decide what its ground is `upperDimension()` the dimension stacked above, whose own settings (`UpperDimension.settings()`), resources and image-map blocks decide what its ground is
made of. A biome that is no column's surface biome, such as the cave biome of a `BiomeSample`, has its settings through `FeatureSettings.declaredBy`. made of. A biome that is no column's surface biome, such as the cave biome of a `BiomeSample`, has its settings through `FeatureSettings.declaredBy`.
The chunk stage's mantle covers the chunk and the 16 blocks around it like the sampler, so a decoration that attaches to a neighbor sees the blocks The chunk stage's mantle covers the chunk and the 16 blocks around it like the sampler, so a decoration that attaches to a neighbor sees the blocks
placements planned there; `Mantle.caverns()` is the host's read-only layer of carved voids, as `blocks()` is of planned blocks: a void the planner placements planned there. It writes registered layers inside the chunk's own 16 by 16 columns only: the mantle pipeline has finished around the
marked need not show in the chunk (under a dimension above, the cave stage leaves it solid), and a stage that places something solid asks it. chunk, and a neighbor may already be generated, so its mantle stays as the pipeline left it (a write outside throws, naming `Stage.mantle`).
`Mantle.isCarved(x, y, z)` is the host's answer whether the cave planner carved a block, as `blocks()` is its read-only layer of planned blocks: a
void the planner marked need not show in the chunk (under a dimension above, the cave stage leaves it solid), and a stage that places something
solid asks it. A yes-or-no question rather than a layer, because no module writes it and none needs to visit it.
`BlockRegistry.oreFor(rock, ore)` is the platform's answer to which variant of an ore belongs in a rock. `BlockRegistry.oreFor(rock, ore)` is the platform's answer to which variant of an ore belongs in a rock.
## Mantle invocations ## Mantle invocations
@@ -733,8 +736,6 @@ instead:
layer: the host would need a format for each. `Object` is the exception: it means any JSON value layer: the host would need a format for each. `Object` is the exception: it means any JSON value
(`AnyKind`), decoded as maps, lists, `Double`s, strings and booleans, for data whose shape belongs to (`AnyKind`), decoded as maps, lists, `Double`s, strings and booleans, for data whose shape belongs to
someone else, such as a block entity's data in a `BlockSpec`; someone else, such as a block entity's data in a `BlockSpec`;
- `ResourceKey<T>`: its type argument is the Java class a resource loads as, which tells studio
nothing it could list; `ResourceId` with `@Ref` says what a value names;
- interfaces and abstract classes: their fields depend on the subclass a pack would pick; - interfaces and abstract classes: their fields depend on the subclass a pack would pick;
- inner (non-static), local and anonymous classes, which cannot be created on their own; - inner (non-static), local and anonymous classes, which cannot be created on their own;
- raw `List`, `Set` and `Map`, concrete collections such as `ArrayList`, wildcards and type - raw `List`, `Set` and `Map`, concrete collections such as `ArrayList`, wildcards and type
@@ -753,9 +754,10 @@ biomes, regions, objects, expressions and image maps of the pack, the resource f
refer to most. More kinds come when a refer to most. More kinds come when a
module needs one and the host can serve it. `@Ref` fits `String` and `ResourceId` and lists, sets and module needs one and the host can serve it. `@Ref` fits `String` and `ResourceId` and lists, sets and
arrays of them, where it applies to the elements. On any other field, a map included, it fails the arrays of them, where it applies to the elements. On any other field, a map included, it fails the
load. The pack kinds (`PACK_BIOME`, `PACK_REGION`, `PACK_OBJECT`, `PACK_EXPRESSION`, `PACK_IMAGE_MAP`, `PACK_STRUCTURE`) fit `String` only: packs name their load. The pack kinds (`PACK_BIOME`, `PACK_REGION`, `PACK_OBJECT`, `PACK_EXPRESSION`, `PACK_IMAGE_MAP`, `PACK_STRUCTURE`) are
biomes, regions and objects by path without a namespace, such as `desert/dunes`, which a `ResourceId` plain text in the JSON either way: packs name their biomes, regions and objects by path without a namespace, such as
cannot hold. `BlockState` always names a block, so its fields are block references without `@Ref`; `desert/dunes`. On a `ResourceId` field the host reads that path as the pack's id of it (`PackResources.idOf`), and a
value with a namespace as written, so a module can hand the value straight to `PackResources.find`. `BlockState` always names a block, so its fields are block references without `@Ref`;
`@Ref(BLOCK)` there is accepted, any other kind fails. `@Ref(BLOCK)` there is accepted, any other kind fails.
### Defaults ### Defaults
@@ -846,9 +848,10 @@ Why these lines:
have to know that rule, so the resources say it; a default method (namespace and key) serves a host without such characters. have to know that rule, so the resources say it; a default method (namespace and key) serves a host without such characters.
- **`TerrainSampler.caveBiome(x, y, z)`** is `biome(...).caveBiome()` without the region and the surface biome: a cave wall asks for the - **`TerrainSampler.caveBiome(x, y, z)`** is `biome(...).caveBiome()` without the region and the surface biome: a cave wall asks for the
cave biome around it five times per block, and the other two lookups were most of the cost. A default method keeps every sampler valid. cave biome around it five times per block, and the other two lookups were most of the cost. A default method keeps every sampler valid.
- **`ReadOnlyMantle.host()`** hands a host's own extension back the mantle behind a chunk stage's read-only view. A chunk stage may not - **A chunk stage writes its own chunk's mantle.** Iris's cave stage stamps markers into the matter the platform reads, in the chunk it
write the mantle, but Iris's cave stage stamps markers into the matter that the platform reads, through a built-in facade, so the generates. Earlier the chunk's mantle was read-only and a built-in facade reached past the view to the host's mantle; now the view lets
facade has to reach past the view. Not for pack modules: writing through it breaks the promise the view makes. any chunk stage write registered layers inside its own columns and reads the neighbors only, so no stage, built-in or not, needs a way
around it.
- **`PackWorld.minHeight()`**: all heights are above the dimension's bottom, but packs write some settings as absolute - **`PackWorld.minHeight()`**: all heights are above the dimension's bottom, but packs write some settings as absolute
world Y (cave biome bands, floating island altitudes, structure bands). Those are converted by the module with the world Y (cave biome bands, floating island altitudes, structure bands). Those are converted by the module with the
platform's Y of the bottom, a default method (0) so a fixture without negative Y needs nothing. platform's Y of the bottom, a default method (0) so a fixture without negative Y needs nothing.
@@ -944,9 +947,11 @@ the resources it serves itself.
sit inside another's, whose files the host would then read twice. One folder holds one kind. The host's own sit inside another's, whose files the host would then read twice. One folder holds one kind. The host's own
folders are reserved with `ModuleHost.reservingFolders`. Either conflict fails the pack load in `ModuleRegistry`, folders are reserved with `ModuleHost.reservingFolders`. Either conflict fails the pack load in `ModuleRegistry`,
naming both owners; the host is named as "the host". naming both owners; the host is named as "the host".
- **Type.** `PackResources` selects a kind by the requested type, so one class backs at most one kind and - **Lookup.** `PackResources.find(KEEPS, id)` and `ids(KEEPS)` take the kind itself, the constant the module registered, and
`find(new ResourceKey<>(id, Keep.class))` needs no kind id. The class must be concrete; like settings it needs a return its type. The host's own kinds are constants of `PackResources` (`BIOMES`, `REGIONS`, `OBJECTS`), so one call
no-argument constructor, checked when the pack's description is built. shape serves both, and no second key type (it used to be `ResourceKey`, a pair of id and class). One class still backs
at most one kind, because `@ResourceRef` names the kind by its class. The class must be concrete; like settings it
needs a no-argument constructor, checked when the pack's description is built.
- **Reading.** The host creates the instance with that constructor and reads the JSON into it, exactly as it - **Reading.** The host creates the instance with that constructor and reads the JSON into it, exactly as it
decodes settings, so a missing field keeps its default and studio's defaults are what packs get. decodes settings, so a missing field keeps its default and studio's defaults are what packs get.
- **Lifetime.** A resource is read once per pack snapshot and every caller gets the same instance, so resources - **Lifetime.** A resource is read once per pack snapshot and every caller gets the same instance, so resources
@@ -958,10 +963,10 @@ the resources it serves itself.
- **Studio.** `PackSchema.resources()` lists each kind with its folder and the files' type, an `ObjectKind` - **Studio.** `PackSchema.resources()` lists each kind with its folder and the files' type, an `ObjectKind`
described in `types()` or a `HostKind`. The host writes a schema per kind for the files below its folder. An described in `types()` or a `HostKind`. The host writes a schema per kind for the files below its folder. An
option that names a resource of a kind carries `@ResourceRef(Keep.class)`: a class, not a kind id, so the option that names a resource of a kind carries `@ResourceRef(Keep.class)`: a class, not a kind id, so the
reference is checked by the compiler and matches how `PackResources` selects kinds. It becomes reference is checked by the compiler (an annotation cannot hold the kind constant). It becomes
`ResourceReferenceKind(kindId)`, and studio completes the kind's keys. Keys are pack paths without a `ResourceReferenceKind(kindId)`, and studio completes the kind's keys. Keys are pack paths without a
namespace, so only `String` fits, like the pack references of `@Ref`. A class that backs no kind of the pack namespace in the JSON, like the pack references of `@Ref`; the field may be a `String` or a `ResourceId`, which the
fails the load. host reads as the pack's id of the key. A class that backs no kind of the pack fails the load.
## Validators ## Validators
@@ -1044,9 +1049,10 @@ gives each module a `ModuleLog` instead.
keys it only debugs, which keeps a key space nobody bounded from growing. keys it only debugs, which keeps a key space nobody bounded from growing.
- **Where a module reaches it.** `InvocationContext.log()` for stage bodies and generators, `PackWorld.log()` for services - **Where a module reaches it.** `InvocationContext.log()` for stage bodies and generators, `PackWorld.log()` for services
and lifecycle hooks, `PackContext.log()` in `packLoaded`, `ModuleSetup.log()` during `setup`. The world and the context and lifecycle hooks, `PackContext.log()` in `packLoaded`, `ModuleSetup.log()` during `setup`. The world and the context
agree: the runners hand a stage a view of the world whose log is its module's (`PackWorld.withLog`, a host method; the agree: the runners hand a stage a view of the world whose log is its module's (built by the reference host around the
view shares the state store, and the graph keeps the last view per module, so a run of invocations of one world builds host's world, so a host implements no method for it; the view shares the state store and the extensions, and the graph
it once; several worlds sharing one graph only rebuild it when they alternate), and keeps the last view per module, so a run of invocations of one world builds it once; several worlds sharing one graph
only rebuild it when they alternate), and
`LifecycleRunner` and `ServiceRegistration.scope` do the same for hooks and providers. A host that calls a provider itself `LifecycleRunner` and `ServiceRegistration.scope` do the same for hooks and providers. A host that calls a provider itself
must scope the world, or the provider's lines carry the host's label. must scope the world, or the provider's lines carry the host's label.
- **Why not `System.Logger` for modules.** A module that logs through the JDK works where the host installed a logger - **Why not `System.Logger` for modules.** A module that logs through the JDK works where the host installed a logger
@@ -1083,12 +1089,14 @@ from a sapling, which drops a block has. A module answers such questions through
second method for it (`EntitySpawns.spawned`, which keeps a spawner's rate limits). second method for it (`EntitySpawns.spawned`, which keeps a spawner's rate limits).
`AmbientEffects` follows the same rule: the module decides which effects are due (interval and chance, kept in the world's `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. state) and every random value they carry, the host only plays them.
- **Services now.** `ObjectsAt` (`ALL`): pack object keys a module would place in a chunk, predicted without - **Services now.** `ObjectsAt` (`ALL`): the ids of pack objects a module would place in a chunk, predicted without
generating it, and the biomes and regions whose settings place a given object (`PlacedBy`, named by pack keys; the generating it, and the biomes and regions whose settings place a given object (`PlacedBy`, by id; the
host builds its search area from them through the biome tree it owns). `StructureLocator` (`FIRST`): every structure key a module knows, the ones a world places (`locatable`; `placed` adds the host builds its search area from them through the biome tree it owns). `StructureLocator` (`FIRST`): every structure a module knows, the ones a world places (`locatable`; `placed` adds the
platform structures the module starts or stands in for, and keys it places but cannot search for), and the platform structures the module starts or stands in for, and structures it places but cannot search for), and the
nearest start of one as a `LocateResult` (`Found`, `NotFound`, `SearchLimitReached`; a sealed interface, so callers nearest start of one as a `LocateResult` (`Found`, `NotFound`, `SearchLimitReached`; a sealed interface, so callers
switch over every outcome). Keys are pack keys as packs write them and match without regard to case. switch over every outcome). Services name pack resources by `ResourceId`, like `PackResources`; the host turns ids into
the keys its commands and files use at its own edge. Ids are lower case, so a host matching a typed key matches without
regard to case.
`CaveBiomes` (`ONE`): the pack biome a module puts at a position whatever the regions say (a band of the deep dark, `CaveBiomes` (`ONE`): the pack biome a module puts at a position whatever the regions say (a band of the deep dark,
`overriddenBiome`, the height counted above the dimension's bottom) and how deep below the surface a biome's caves begin `overriddenBiome`, the height counted above the dimension's bottom) and how deep below the surface a biome's caves begin
(`minDepthBelowSurface`, asked once per biome and kept while the world runs). The host owns the 3D biome of a position (its regions, terrain height and the cave biome stream) (`minDepthBelowSurface`, asked once per biome and kept while the world runs). The host owns the 3D biome of a position (its regions, terrain height and the cave biome stream)
@@ -1119,10 +1127,26 @@ A module jar sees three things besides the JDK and its own pack's jars, and noth
Whatever a second module could want goes here, host-neutral and tested without Iris. Whatever a second module could want goes here, host-neutral and tested without Iris.
2. **Packages the host exposes**: libraries it shares (VolmLib, Gson) and the public face of its built-in modules 2. **Packages the host exposes**: libraries it shares (VolmLib, Gson) and the public face of its built-in modules
(`art.arcane.iris.builtin`: stage constants, settings and output types packs may read). (`art.arcane.iris.builtin`: stage constants, settings and output types packs may read).
3. **Narrow facades for the host's own built-ins**, in that same exposed package: interfaces the host's worlds 3. **Narrow facades for the host's own built-ins**, in that same exposed package, for what only the host's own
implement, for what only the host's own features need from its internals, such as Iris's per-feature world seeds features need from its internals, such as Iris's per-feature world seeds (`IrisSeeds`), which existing worlds depend
(`IrisSeed`), which existing worlds depend on. A pack module never needs one. Every such type is a promise the host on. A pack module never needs one. Every such type is a promise the host keeps, so there are few, each answers one
keeps, so there are few, each answers one question, and none hands out an engine. 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 (seeds, the world at a block), `InvocationContext.extension(type)` for what belongs to one invocation (the
platform chunk Iris generates, the placement being attempted), 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(IrisSeeds.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
receives already says which invocation it is, so it carries the facade.
- **No casts.** Facades used to be interfaces the host's world implemented (`IrisSeed.Source`) and modules cast to. A view of
the world (the one with a module's log) then had to implement every such interface too. The view forwards `extension`,
and that is all.
- **Built-ins only, by convention.** The method is public API, and a pack module can call it; it gets only what the host
offers, typed by classes in the host's exposed package. Every type offered is a promise, as above.
A module never reaches the host's engine, its data loader or its layout classes; it reads the layout through the API's A module never reaches the host's engine, its data loader or its layout classes; it reads the layout through the API's
values and its settings through `FeatureSettings`. Iris's mapping from its internals to this surface, with the values and its settings through `FeatureSettings`. Iris's mapping from its internals to this surface, with the
+35 -22
View File
@@ -157,8 +157,9 @@ shore); `surfaceBlock(x, z)` is the block an image map gives the ground there, `
`upperDimension()` the dimension stacked above (`UpperDimension`: its own settings, resources and image-map blocks), for a stage that fills in its ground. `upperDimension()` the dimension stacked above (`UpperDimension`: its own settings, resources and image-map blocks), for a stage that fills in its ground.
`ctx.settings().declaredBy(biomeId, Type.class)` reads what a biome declares itself, such as a cave biome of a `BiomeSample`, which is no level of `ctx.settings().declaredBy(biomeId, Type.class)` reads what a biome declares itself, such as a cave biome of a `BiomeSample`, which is no level of
`at(...)`. A mantle stage's `ctx.terrain()` covers the chunk and the larger of its reach and 16 blocks around it; a chunk stage's `ctx.mantle()` covers the same area as its terrain. `ctx.mantle().blocks()` holds the blocks placements wrote into the mantle for the chunks to `at(...)`. A mantle stage's `ctx.terrain()` covers the chunk and the larger of its reach and 16 blocks around it; a chunk stage's `ctx.mantle()` covers the same area as its terrain. `ctx.mantle().blocks()` holds the blocks placements wrote into the mantle for the chunks to
take over, such as objects and structures; a chunk stage copies them in (Iris's `iris:matter`). `ctx.mantle().caverns()` holds `true` where the cave planner take over, such as objects and structures; a chunk stage copies them in (Iris's `iris:matter`). `ctx.mantle().isCarved(x, y, z)` says whether the cave planner
carved a void, whatever the chunk's blocks show there. Stages only read both. `blocks().oreFor(rock, ore)` gives the ore variant that suits the rock carved a void there, whatever the chunk's blocks show. Stages only read both. A chunk stage may write the layers its module registered, inside
its own chunk's columns; around it, the mantle stays as the mantle stages left it. `blocks().oreFor(rock, ore)` gives the ore variant that suits the rock
(deepslate ores in deepslate), which the platform decides, and `PackBiome.vanillaBiome()` the biome vanilla's rules see a pack biome as. (deepslate ores in deepslate), which the platform decides, and `PackBiome.vanillaBiome()` the biome vanilla's rules see a pack biome as.
```java ```java
@@ -211,8 +212,9 @@ public void setup(ModuleSetup setup) {
} }
// anywhere the pack's resources are at hand, such as a stage or a validator // anywhere the pack's resources are at hand, such as a stage or a validator
Keep keep = resources.require(KEEPS.key(resources.idOf("towers/north"))); Keep keep = resources.require(KEEPS, resources.idOf("towers/north"));
List<ResourceId> all = resources.ids(Keep.class); // every keep of the pack, in id order List<ResourceId> all = resources.ids(KEEPS); // every keep of the pack, in id order
PackBiome dunes = resources.require(PackResources.BIOMES, resources.idOf("desert/dunes")); // the host's kinds alike
``` ```
- A file's key is its path below the folder without `.json` (`towers/north`), and its id is - A file's key is its path below the folder without `.json` (`towers/north`), and its id is
@@ -221,15 +223,16 @@ List<ResourceId> all = resources.ids(Keep.class); // every keep of the pack, in
field names. field names.
- The kind's id follows the module id. The folder is one folder name directly below the pack root; the module - The kind's id follows the module id. The folder is one folder name directly below the pack root; the module
chooses it, so a kind that replaces one of Iris's own keeps the folder and file format packs already have. chooses it, so a kind that replaces one of Iris's own keeps the folder and file format packs already have.
- One folder holds one kind and one class backs one kind: `PackResources` finds resources by type. Two kinds - One folder holds one kind and one class backs one kind, which `@ResourceRef` names by its class. Two kinds
claiming one folder, or a folder the host reads itself (`ModuleHost.reservingFolders`), fail the pack load, claiming one folder, or a folder the host reads itself (`ModuleHost.reservingFolders`), fail the pack load,
naming both owners. naming both owners.
- The host creates each resource with the class's no-argument constructor and reads the JSON into it, as it does - The host creates each resource with the class's no-argument constructor and reads the JSON into it, as it does
settings, so an omitted field keeps its default. It reads a resource once per pack load and hands every caller settings, so an omitted field keeps its default. It reads a resource once per pack load and hands every caller
the same instance, so resources are values nobody may change. A reload (studio hotload) reads them again. the same instance, so resources are values nobody may change. A reload (studio hotload) reads them again.
- Studio describes the files from the class like settings: `@Desc`, `@MinNumber`, `@Required` and the rest. An - Studio describes the files from the class like settings: `@Desc`, `@MinNumber`, `@Required` and the rest. An
option that names a resource of a kind carries `@ResourceRef(Keep.class)` on a `String`, or a list, set or option that names a resource of a kind carries `@ResourceRef(Keep.class)` on a `String` or `ResourceId`, or a
array of them, and studio completes the kind's keys. Built-in kinds may read into a class the host describes 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. itself, as built-in settings may hold one.
``` ```
@@ -244,8 +247,8 @@ problems with its own.
```java ```java
registry.registerValidator(pack -> { registry.registerValidator(pack -> {
for (ResourceId id : pack.resources().ids(Keep.class)) { for (ResourceId id : pack.resources().ids(KEEPS)) {
Keep keep = pack.resources().require(KEEPS.key(id)); Keep keep = pack.resources().require(KEEPS, id);
if (keep.towers() > 8) { if (keep.towers() > 8) {
pack.report(Problem.error(Subject.file("keeps/" + id.path() + ".json"), "Keep has " + keep.towers() + " towers; at most 8 fit.")); pack.report(Problem.error(Subject.file("keeps/" + id.path() + ".json"), "Keep has " + keep.towers() + " towers; at most 8 fit."));
} }
@@ -348,11 +351,11 @@ public void setup(ModuleSetup setup) {
} }
final class RuinsObjects implements ObjectsAt { final class RuinsObjects implements ObjectsAt {
public Set<String> objectsAt(PackWorld world, int chunkX, int chunkZ) { public Set<ResourceId> objectsAt(PackWorld world, int chunkX, int chunkZ) {
return planted(world).contains(chunkX, chunkZ) ? Set.of("ruins/arch") : Set.of(); return planted(world).contains(chunkX, chunkZ) ? Set.of(world.resources().idOf("ruins/arch")) : Set.of();
} }
public PlacedBy placedBy(PackWorld world, String objectKey) { public PlacedBy placedBy(PackWorld world, ResourceId object) {
return PlacedBy.NOTHING; return PlacedBy.NOTHING;
} }
} }
@@ -362,6 +365,8 @@ final class RuinsObjects implements ObjectsAt {
Service methods take the world, and the provider keeps what it needs in the world's state store. Service methods take the world, and the provider keeps what it needs in the world's state store.
- Services compute; they never act on the platform. What should happen in the world comes back as a value the host - Services compute; they never act on the platform. What should happen in the world comes back as a value the host
carries out on the right thread. carries out on the right thread.
- Services name pack resources by `ResourceId` (`world.resources().idOf(key)` for a key the pack wrote), and absent
values in what they return are `Optional`s.
- Each service says how several providers combine, with `@Service(Providers.X)`: `ALL` (the host asks every provider - 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 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 pack; a second fails the pack load, naming both modules). Providers are in module id order, each module's in
@@ -370,7 +375,7 @@ final class RuinsObjects implements ObjectsAt {
| Service | Providers | What the host asks | | Service | Providers | What the host asks |
| --- | --- | --- | | --- | --- | --- |
| `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. | | `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 key the module knows (the structure index), the ones a world places and can locate (commands complete them), every key 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`. Keys match without regard to case. | | `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. | | `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, and the `ItemDrop`s one table gives there. 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. | | `BlockDrops` | `ALL` | What a module drops for a broken block: `ItemDrop`s, and whether the platform's own drops of the block are replaced. |
@@ -489,7 +494,7 @@ public final class FloraSettings implements IrisFeature {
which are described the same way, IrisApi's value types among them (see Values in settings). `@Snippet("example/flora/patch")` on a class lets packs write it as a file under which are described the same way, IrisApi's value types among them (see Values in settings). `@Snippet("example/flora/patch")` on a class lets packs write it as a file under
`snippet/example/flora/patch/`. A pack module's snippet names start with its module id as a folder `snippet/example/flora/patch/`. A pack module's snippet names start with its module id as a folder
path (`example/flora` for `example:flora`). path (`example/flora` for `example:flora`).
Anything else fails the pack load: `char`, other JDK classes such as `UUID` or `Optional`, `ResourceKey`, Anything else fails the pack load: `char`, other JDK classes such as `UUID` or `Optional`,
interfaces and abstract classes, inner (non-static) classes, collections without type arguments, interfaces and abstract classes, inner (non-static) classes, collections without type arguments,
concrete collections such as `ArrayList`, and maps with other keys. concrete collections such as `ArrayList`, and maps with other keys.
- `@Ref(Reference.X)` says what a `String` or `ResourceId` names, also on lists, sets and arrays of - `@Ref(Reference.X)` says what a `String` or `ResourceId` names, also on lists, sets and arrays of
@@ -497,9 +502,10 @@ public final class FloraSettings implements IrisFeature {
(a structure or a family prefix such as `minecraft:village`), `STRUCTURE_SET`, `TEMPLATE_POOL` (a jigsaw template pool), (a structure or a family prefix such as `minecraft:village`), `STRUCTURE_SET`, `TEMPLATE_POOL` (a jigsaw template pool),
`POTION_EFFECT`, `ENCHANTMENT`, `LOOT_TABLE` or `SPECIAL_ENTITY` (a mob of another plugin) from the server's registries, `NOISE_STYLE` from the host's noise `POTION_EFFECT`, `ENCHANTMENT`, `LOOT_TABLE` or `SPECIAL_ENTITY` (a mob of another plugin) from the server's registries, `NOISE_STYLE` from the host's noise
styles, or `PACK_BIOME`, `PACK_REGION`, `PACK_OBJECT`, `PACK_EXPRESSION`, `PACK_IMAGE_MAP` or `PACK_STRUCTURE` (a jigsaw structure) of the pack. styles, or `PACK_BIOME`, `PACK_REGION`, `PACK_OBJECT`, `PACK_EXPRESSION`, `PACK_IMAGE_MAP` or `PACK_STRUCTURE` (a jigsaw structure) of the pack.
The pack kinds fit `String` only, in the form packs use (`desert/dunes`), never `ResourceId`. `BlockState` fields name blocks without it. `@Ref` on any other field fails Packs write the pack kinds in the form they always have (`desert/dunes`); on a `ResourceId` field the host reads that
as the pack's id (`resources.idOf(...)`), so the value goes straight to `PackResources.find`. `BlockState` fields name blocks without it. `@Ref` on any other field fails
the load. the load.
- `@ResourceRef(Keep.class)` says that a `String`, or a list, set or array of them, names a resource of the - `@ResourceRef(Keep.class)` says that a `String` or `ResourceId`, or a list, set or array of them, names a resource of the
module resource kind read into that class, by its key (see Pack resources of a module). The class must back a module resource kind read into that class, by its key (see Pack resources of a module). The class must back a
kind of the pack; anywhere else, or together with `@Ref`, it fails the load. kind of the pack; anywhere else, or together with `@Ref`, it fails the load.
- Packs write settings under the short `key` the feature declares, which is required: a plain JSON field name - Packs write settings under the short `key` the feature declares, which is required: a plain JSON field name
@@ -855,11 +861,17 @@ Optional<Clock> clock = pack.catalog().service(Clock.class); // a Pro
## Values that stay ## Values that stay
- `ResourceId` requires a namespace. `ResourceKey<T>` pairs it with a public type. - `ResourceId` requires a namespace. Services and values name pack resources by it; a host converts to its own keys
at its edge.
- `PackResources` serves one immutable pack snapshot; caches must not survive a reload. - `PackResources` serves one immutable pack snapshot; caches must not survive a reload.
It serves pack objects (`GeneratedObject`), biomes (`PackBiome`), regions (`PackRegion`) and every module It serves pack objects (`OBJECTS`, `GeneratedObject`), biomes (`BIOMES`, `PackBiome`), regions (`REGIONS`,
resource kind; the requested type selects the kind, so `BiomeSample` ids look up directly. `ids(type)` lists `PackRegion`) and every module resource kind: `find(kind, id)` (empty when absent), `require(kind, id)` and
a kind. `ids(kind)`, so `BiomeSample` ids look up directly.
- Value records say "absent" with `Optional`, `OptionalInt` or `OptionalDouble` components, never with `null` or an
empty string (`ItemDrop`, `EntitySpec`, `AmbientEffects.Effect`). `StructureFit.Start.key()` is a `StartKey`, an
identity the host makes once per platform start.
- A host reaches its own built-ins' facades through `extension(type)` on `PackWorld`, `InvocationContext` and
`PackSettings`; see DESIGN, "How a module reaches the host".
- `BlockState` has value equality and sorted properties; `BlockRegistry` checks it against the - `BlockState` has value equality and sorted properties; `BlockRegistry` checks it against the
platform and resolves `BlockSpec`s. It answers a state's traits (`AIR`, `SOLID`, `FLUID`, `FOLIAGE`, `DECORATION`, platform and resolves `BlockSpec`s. It answers a state's traits (`AIR`, `SOLID`, `FLUID`, `FOLIAGE`, `DECORATION`,
`VINE`, ...), tags, whether it attaches to a face (`canAttach`) and whether it can stand on a block (`canPlaceOn`, the `VINE`, ...), tags, whether it attaches to a face (`canAttach`) and whether it can stand on a block (`canPlaceOn`, the
@@ -870,7 +882,8 @@ Optional<Clock> clock = pack.catalog().service(Clock.class); // a Pro
- `Hunk<T>` is a dense local volume; `ArrayHunk<T>` is the bounds-checked reference. - `Hunk<T>` is a dense local volume; `ArrayHunk<T>` is the bounds-checked reference.
- The `mantle` package keeps namespaced typed layers, codecs, lifetimes and buffered edits. - The `mantle` package keeps namespaced typed layers, codecs, lifetimes and buffered edits.
- `IrisFeature`, `@Feature`, the config annotations (`@Desc`, `@Required`, `@MinNumber`, - `IrisFeature`, `@Feature`, the config annotations (`@Desc`, `@Required`, `@MinNumber`,
`@MaxNumber`, `@MinItems`, `@Snippet`, `@Ref`) and `OptionsMetadata` describe settings. `@MaxNumber`, `@MinItems`, `@Snippet`, `@Ref`) describe settings; the host reads them with `OptionsMetadata`
(`com.volmit.host`).
Invocation views and random streams expire when the invocation ends. Stage bodies are shared by Invocation views and random streams expire when the invocation ends. Stage bodies are shared by
concurrent invocations and must not keep views, streams or mutable state; what a module keeps per world lives in the concurrent invocations and must not keep views, streams or mutable state; what a module keeps per world lives in the
@@ -937,5 +950,5 @@ loads and that other internal packages are still reported. `PackModulesSummaryTe
ports in `src/test/java/com/volmit/example` rebuild preparation, anchoring, block writes, stilt and ports in `src/test/java/com/volmit/example` rebuild preparation, anchoring, block writes, stilt and
snow as separate modules, add a third-party moss module, and add a two-module chunk pipeline whose snow as separate modules, add a third-party moss module, and add a two-module chunk pipeline whose
`ChunkPipelineTest` checks any-column activation, per-column reads, stacked levels, a mantle stage `ChunkPipelineTest` checks any-column activation, per-column reads, stacked levels, a mantle stage
whose reach follows the pack's longest vein writing into the next chunk that a chunk stage then reads, and the read-only mantle of chunk stages. There whose reach follows the pack's longest vein writing into the next chunk that a chunk stage then reads, and that a chunk stage writes the mantle of its own chunk only. There
is no Minecraft integration or production storage in these tests. is no Minecraft integration or production storage in these tests.
@@ -1,6 +1,8 @@
package com.volmit.config; package com.volmit.config;
import com.volmit.IrisFeature; import com.volmit.IrisFeature;
import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import java.util.Collection; import java.util.Collection;
import java.util.Set; import java.util.Set;
@@ -9,15 +11,17 @@ import java.util.Set;
* Implemented by settings that make pack biomes part of a pack's layout besides the ones its regions list: the biome * Implemented by settings that make pack biomes part of a pack's layout besides the ones its regions list: the biome
* that a cave band puts underground, or the target of a floating island. The host asks the settings of every dimension * that a cave band puts underground, or the target of a floating island. The host asks the settings of every dimension
* and biome it reaches, without knowing the module behind them, so such a biome is loaded, registered and given its own * and biome it reaches, without knowing the module behind them, so such a biome is loaded, registered and given its own
* settings like any other. Keys are pack biome keys as packs write them; blank keys and keys naming no biome are * settings like any other. Biomes are named by their ids, {@link PackResources#idOf} of the keys the settings hold; ids
* ignored. * naming no biome of the pack are ignored.
*/ */
public interface LinkedBiomes { public interface LinkedBiomes {
/** /**
* Biomes that join the biome tree of every region the owner is part of, like the owner's children: the host registers * Biomes that join the biome tree of every region the owner is part of, like the owner's children: the host registers
* them with the region, so their terrain generators take part in the region's terrain. * them with the region, so their terrain generators take part in the region's terrain.
*
* @param pack the pack the settings belong to, which turns their keys into ids
*/ */
default Set<String> treeBiomes() { default Set<ResourceId> treeBiomes(PackResources pack) {
return Set.of(); return Set.of();
} }
@@ -25,10 +29,11 @@ public interface LinkedBiomes {
* Biomes the settings use besides, which a dimension reaches (their objects, decorators and settings take part in * Biomes the settings use besides, which a dimension reaches (their objects, decorators and settings take part in
* generation) without joining the region's biome tree. * generation) without joining the region's biome tree.
* *
* @param pack the pack the settings belong to, which turns their keys into ids
* @param dimension the settings the owner's dimension declares, for settings that name something the dimension * @param dimension the settings the owner's dimension declares, for settings that name something the dimension
* declares, such as a band of its caves * declares, such as a band of its caves
*/ */
default Set<String> usedBiomes(Collection<IrisFeature> dimension) { default Set<ResourceId> usedBiomes(PackResources pack, Collection<IrisFeature> dimension) {
return Set.of(); return Set.of();
} }
} }
@@ -1,6 +1,7 @@
package com.volmit.config; package com.volmit.config;
import com.volmit.IrisFeature; import com.volmit.IrisFeature;
import java.util.Optional;
/** Every settings declaration of the pack the host is loading, for what depends on the whole pack rather /** Every settings declaration of the pack the host is loading, for what depends on the whole pack rather
* than one column, such as how far a mantle stage reaches ({@link com.volmit.stage.PackReach}). * than one column, such as how far a mantle stage reaches ({@link com.volmit.stage.PackReach}).
@@ -14,4 +15,14 @@ public interface PackSettings {
* empty when nothing declares it. * empty when nothing declares it.
*/ */
<F extends IrisFeature> SettingsStack<F> declared(Class<F> featureType); <F extends IrisFeature> SettingsStack<F> declared(Class<F> featureType);
/**
* What the host offers for the pack it is loading beyond the API, as an object of {@code type}: empty when it offers
* no such thing. The same door as {@link com.volmit.world.PackWorld#extension}, for what is worked out from the
* settings before any world generates, such as a {@link com.volmit.stage.PackReach} that needs the size of the pack's
* objects from the host.
*/
default <T> Optional<T> extension(Class<T> type) {
return Optional.empty();
}
} }
+44 -20
View File
@@ -2,51 +2,58 @@ package com.volmit.entity;
import com.volmit.item.ItemAttribute; import com.volmit.item.ItemAttribute;
import com.volmit.item.ItemDrop; import com.volmit.item.ItemDrop;
import com.volmit.resource.ResourceId;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* An entity a module decided to spawn, with every random choice made: the host creates it on the platform and applies * An entity a module decided to spawn, with every random choice made: the host creates it on the platform and applies
* what is set. Names are as authored in the pack, with {@code &} colour codes. * what is set. Names are as authored in the pack, with {@code &} colour codes.
* *
* @param type the entity type's key, such as {@code minecraft:zombie}; ignored when {@code specialType} is set * @param type the entity type's key, such as {@code minecraft:zombie}; ignored when {@code specialType} is set
* @param specialType a mob of another plugin, written {@code PluginName:MobName}, or empty * @param specialType a mob of another plugin, written {@code PluginName:MobName}; empty for an entity of the platform
* @param reason the platform's spawn reason by name, or null for a natural spawn * @param reason the platform's spawn reason by name; empty for a natural spawn
* @param customName the name shown above the entity, empty for none * @param customName the name shown above the entity; empty for none
* @param flags the settings that every entity kind understands * @param flags the settings that every entity kind understands
* @param equipment what the entity wears and holds * @param equipment what the entity wears and holds
* @param passengers entities that ride this one * @param passengers entities that ride this one
* @param attributes attribute modifiers to apply * @param attributes attribute modifiers to apply
* @param lootTables keys of loot tables the entity drops, instead of the platform's drops, when it dies * @param lootTables the pack's loot tables the entity drops, instead of the platform's drops, when it dies
* @param lootShuffleSeed seeds how the drops of {@code lootTables} are shuffled * @param lootShuffleSeed seeds how the drops of {@code lootTables} are shuffled
* @param leashHolder the entity that holds this one on a leash, or null * @param leashHolder the entity that holds this one on a leash; empty for none
* @param spawnEffect an effect to show when the entity appears, or null * @param spawnEffect an effect to show when the entity appears; empty for none
* @param riseOutOfGround whether the entity slowly climbs out of the ground when players are near * @param riseOutOfGround whether the entity slowly climbs out of the ground when players are near
* @param pandaMainGene for pandas the main gene by name, or null * @param pandaMainGene for pandas the main gene by name; empty to leave it to the platform
* @param pandaHiddenGene for pandas the hidden gene by name, or null * @param pandaHiddenGene for pandas the hidden gene by name; empty to leave it to the platform
* @param applySettingsToSpecial whether the settings also apply to a mob of another plugin * @param applySettingsToSpecial whether the settings also apply to a mob of another plugin
* @param commands console commands to run where the entity appears * @param commands console commands to run where the entity appears
*/ */
public record EntitySpec(String type, String specialType, String reason, String customName, Flags flags, Equipment equipment, public record EntitySpec(Optional<String> type, Optional<String> specialType, Optional<String> reason, Optional<String> customName,
List<EntitySpec> passengers, List<ItemAttribute> attributes, List<String> lootTables, Flags flags, Equipment equipment, List<EntitySpec> passengers, List<ItemAttribute> attributes,
long lootShuffleSeed, EntitySpec leashHolder, SpawnEffect spawnEffect, boolean riseOutOfGround, List<ResourceId> lootTables, long lootShuffleSeed, Optional<EntitySpec> leashHolder,
String pandaMainGene, String pandaHiddenGene, boolean applySettingsToSpecial, Optional<SpawnEffect> spawnEffect, boolean riseOutOfGround, Optional<String> pandaMainGene,
List<Command> commands) { Optional<String> pandaHiddenGene, boolean applySettingsToSpecial, List<Command> commands) {
public EntitySpec { public EntitySpec {
Objects.requireNonNull(type, "type"); Objects.requireNonNull(type, "type");
Objects.requireNonNull(specialType, "specialType"); Objects.requireNonNull(specialType, "specialType");
Objects.requireNonNull(reason, "reason");
Objects.requireNonNull(customName, "customName"); Objects.requireNonNull(customName, "customName");
Objects.requireNonNull(flags, "flags"); Objects.requireNonNull(flags, "flags");
Objects.requireNonNull(equipment, "equipment"); Objects.requireNonNull(equipment, "equipment");
passengers = List.copyOf(passengers); passengers = List.copyOf(passengers);
attributes = List.copyOf(attributes); attributes = List.copyOf(attributes);
lootTables = List.copyOf(lootTables); lootTables = List.copyOf(lootTables);
Objects.requireNonNull(leashHolder, "leashHolder");
Objects.requireNonNull(spawnEffect, "spawnEffect");
Objects.requireNonNull(pandaMainGene, "pandaMainGene");
Objects.requireNonNull(pandaHiddenGene, "pandaHiddenGene");
commands = List.copyOf(commands); commands = List.copyOf(commands);
} }
/** Whether the entity is a mob of another plugin. */ /** Whether the entity is a mob of another plugin. */
public boolean isSpecial() { public boolean isSpecial() {
return !specialType.isEmpty(); return specialType.isPresent();
} }
/** What an entity can be set to be, whatever its kind; the host applies the ones its kind has. */ /** What an entity can be set to be, whatever its kind; the host applies the ones its kind has. */
@@ -55,19 +62,36 @@ public record EntitySpec(String type, String specialType, String reason, String
boolean keepEntity, boolean baby) { boolean keepEntity, boolean baby) {
} }
/** The items an entity wears and holds; null for an empty slot. */ /** The items an entity wears and holds; empty for an empty slot. */
public record Equipment(ItemDrop helmet, ItemDrop chestplate, ItemDrop leggings, ItemDrop boots, ItemDrop mainHand, public record Equipment(Optional<ItemDrop> helmet, Optional<ItemDrop> chestplate, Optional<ItemDrop> leggings,
ItemDrop offHand) { Optional<ItemDrop> boots, Optional<ItemDrop> mainHand, Optional<ItemDrop> offHand) {
public static final Equipment NONE = new Equipment(null, null, null, null, null, null); public static final Equipment NONE = new Equipment(Optional.empty(), Optional.empty(), Optional.empty(),
Optional.empty(), Optional.empty(), Optional.empty());
public Equipment {
Objects.requireNonNull(helmet, "helmet");
Objects.requireNonNull(chestplate, "chestplate");
Objects.requireNonNull(leggings, "leggings");
Objects.requireNonNull(boots, "boots");
Objects.requireNonNull(mainHand, "mainHand");
Objects.requireNonNull(offHand, "offHand");
}
} }
/** /**
* Sound and particles shown around an entity that appears. Offsets and the randomness of the particle motion are * Sound and particles shown around an entity that appears. Offsets and the randomness of the particle motion are
* as in an effect of the pack; the host makes the random choices. * as in an effect of the pack; the host makes the random choices.
*
* @param sound the platform's sound key; empty for no sound
* @param particle the platform's particle key; empty for no particles
*/ */
public record SpawnEffect(String sound, int soundDistance, double minPitch, double maxPitch, double volume, public record SpawnEffect(Optional<String> sound, int soundDistance, double minPitch, double maxPitch, double volume,
String particle, int particleOffset, int particleCount, double altX, double altY, Optional<String> particle, int particleOffset, int particleCount, double altX, double altY,
double altZ, boolean randomAltX, boolean randomAltY, boolean randomAltZ, double extra) { double altZ, boolean randomAltX, boolean randomAltY, boolean randomAltZ, double extra) {
public SpawnEffect {
Objects.requireNonNull(sound, "sound");
Objects.requireNonNull(particle, "particle");
}
} }
/** /**
@@ -21,10 +21,12 @@ public interface GenerationContext extends ChunkContext {
@Override @Override
TerrainSampler terrain(); TerrainSampler terrain();
/** Non-null mantle access scoped to this invocation; the host owns its lifetime. Chunk stages read it /** Non-null mantle access scoped to this invocation; the host owns its lifetime. Like {@link #terrain()} it covers
* only: the mantle pipeline has finished around the chunk, and writes throw. Like {@link #terrain()} it covers the * the chunk and the 16 blocks around it, so a stage that places something against a neighbor can see what the mantle
* chunk and the 16 blocks around it, so a stage that places something against a neighbor can see what the mantle * holds there. A chunk stage writes module layers inside its own chunk's columns only, such as markers it derives
* holds there. * from the chunk's finished blocks: the mantle pipeline has finished around the chunk, and a neighbor may already
* be generated, so writes outside the chunk throw UnsupportedOperationException, as do writes to
* {@link Mantle#blocks()} and {@link Mantle#edit()}.
*/ */
Mantle mantle(); Mantle mantle();
@@ -2,6 +2,7 @@ package com.volmit.generation;
import com.volmit.ModuleLog; import com.volmit.ModuleLog;
import com.volmit.world.PackWorld; import com.volmit.world.PackWorld;
import java.util.Optional;
/** Host-owned invocation inputs. Views must not be retained or used by detached tasks. /** Host-owned invocation inputs. Views must not be retained or used by detached tasks.
* *
@@ -19,4 +20,14 @@ public interface InvocationContext {
default ModuleLog log() { default ModuleLog log() {
return world().log(); return world().log();
} }
/**
* What the host offers for this one invocation beyond the API, as an object of {@code type}: empty when the host
* offers no such thing. The per invocation counterpart of {@link PackWorld#extension}: a host hands its own modules
* inputs that belong to one placement or one chunk this way, such as what Iris knows about the placement that is
* running. The host fills it for each invocation; like every input it must not be kept after the invocation.
*/
default <T> Optional<T> extension(Class<T> type) {
return Optional.empty();
}
} }
@@ -12,8 +12,9 @@ import com.volmit.stage.ChunkStageContext;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.world.TerrainSampler; import com.volmit.world.TerrainSampler;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** The context every stage of one chunk invocation receives. The mantle is read-only. */ /** The context every stage of one chunk invocation receives. The mantle is writable in the chunk's own columns only. */
final class ChunkInvocation implements ChunkStageContext { final class ChunkInvocation implements ChunkStageContext {
private final StageInvocation stages; private final StageInvocation stages;
private final GenerationContext inputs; private final GenerationContext inputs;
@@ -59,7 +60,7 @@ final class ChunkInvocation implements ChunkStageContext {
@Override @Override
public Mantle mantle() { public Mantle mantle() {
return new ReadOnlyMantle(inputs.mantle()); return new ChunkMantle(inputs.mantle(), inputs.originX(), inputs.originZ());
} }
@Override @Override
@@ -72,6 +73,11 @@ final class ChunkInvocation implements ChunkStageContext {
return stages.world(inputs.world()); return stages.world(inputs.world());
} }
@Override
public <T> Optional<T> extension(Class<T> type) {
return inputs.extension(type);
}
@Override @Override
public WorldRandom random() { public WorldRandom random() {
return stages.random(); return stages.random();
@@ -0,0 +1,130 @@
package com.volmit.host;
import com.volmit.block.BlockState;
import com.volmit.generation.ChunkContext;
import com.volmit.mantle.BlockBox;
import com.volmit.mantle.Mantle;
import com.volmit.mantle.MantleEdit;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLayer;
import com.volmit.mantle.MantleVisitor;
/** The mantle as chunk stages see it: reads pass through everywhere the host's mantle reaches, writes to module layers
* only inside the chunk's own 16 by 16 columns. The mantle pipeline has finished around the chunk by then, and its
* neighbours may already be generated, so their mantle stays as the pipeline left it. The host's blocks are read-only.
*/
final class ChunkMantle implements Mantle {
private static final String NEIGHBOUR_WRITE = "A chunk stage writes the mantle of its own chunk only;"
+ " write around it from a mantle stage (Stage.mantle), which runs before the chunks it reaches";
private static final String HOST_BLOCKS = "The mantle's blocks are written by placements, not by stages";
private final Mantle mantle;
private final BlockBox ownChunk;
ChunkMantle(Mantle mantle, int originX, int originZ) {
this.mantle = mantle;
BlockBox bounds = mantle.bounds();
this.ownChunk = new BlockBox(originX, bounds.minY(), originZ, originX + ChunkContext.CHUNK_WIDTH, bounds.maxY(),
originZ + ChunkContext.CHUNK_WIDTH);
}
@Override
public BlockBox bounds() {
return mantle.bounds();
}
@Override
public <T> MantleLayer<T> layer(MantleKey<T> key) {
return new OwnChunkLayer<>(mantle.layer(key));
}
@Override
public MantleLayer<BlockState> blocks() {
return new ReadOnlyLayer<>(mantle.blocks());
}
@Override
public boolean isCarved(int x, int y, int z) {
return mantle.isCarved(x, y, z);
}
@Override
public MantleEdit edit() {
throw new UnsupportedOperationException("Chunk stages write mantle layers directly, without an edit");
}
private void requireOwnChunk(int x, int y, int z) {
if (!ownChunk.contains(x, y, z)) {
throw new UnsupportedOperationException(NEIGHBOUR_WRITE + "; " + x + "," + y + "," + z + " is outside " + ownChunk);
}
}
private void requireOwnChunk(BlockBox area) {
if (!ownChunk.contains(area)) {
throw new UnsupportedOperationException(NEIGHBOUR_WRITE + "; " + area + " reaches outside " + ownChunk);
}
}
private final class OwnChunkLayer<T> implements MantleLayer<T> {
private final MantleLayer<T> layer;
OwnChunkLayer(MantleLayer<T> layer) {
this.layer = layer;
}
@Override
public T get(int x, int y, int z) {
return layer.get(x, y, z);
}
@Override
public void set(int x, int y, int z, T value) {
requireOwnChunk(x, y, z);
layer.set(x, y, z, value);
}
@Override
public void remove(int x, int y, int z) {
requireOwnChunk(x, y, z);
layer.remove(x, y, z);
}
@Override
public void visit(BlockBox area, MantleVisitor<T> visitor) {
layer.visit(area, visitor);
}
@Override
public void clear(BlockBox area) {
requireOwnChunk(area);
layer.clear(area);
}
}
private record ReadOnlyLayer<T>(MantleLayer<T> layer) implements MantleLayer<T> {
@Override
public T get(int x, int y, int z) {
return layer.get(x, y, z);
}
@Override
public void set(int x, int y, int z, T value) {
throw new UnsupportedOperationException(HOST_BLOCKS);
}
@Override
public void remove(int x, int y, int z) {
throw new UnsupportedOperationException(HOST_BLOCKS);
}
@Override
public void visit(BlockBox area, MantleVisitor<T> visitor) {
layer.visit(area, visitor);
}
@Override
public void clear(BlockBox area) {
throw new UnsupportedOperationException(HOST_BLOCKS);
}
}
}
@@ -6,7 +6,7 @@ import java.util.Objects;
/** Reference executor of a resolved chunk graph: active stages run once, in resolved order. /** Reference executor of a resolved chunk graph: active stages run once, in resolved order.
* It does not schedule neighbors or roll back hunks; a failed invocation must prevent the host * It does not schedule neighbors or roll back hunks; a failed invocation must prevent the host
* from publishing the chunk. Stages see the mantle read-only. * from publishing the chunk. Stages write the mantle in the chunk's own columns only.
*/ */
public final class ChunkRunner { public final class ChunkRunner {
private final ResolvedGraph graph; private final ResolvedGraph graph;
@@ -1,4 +1,4 @@
package com.volmit.config; package com.volmit.host;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@@ -3,7 +3,6 @@ package com.volmit.host;
import com.volmit.IrisFeature; import com.volmit.IrisFeature;
import com.volmit.config.Feature; import com.volmit.config.Feature;
import com.volmit.config.Level; import com.volmit.config.Level;
import com.volmit.config.OptionsMetadata;
import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceId;
import java.lang.annotation.IncompleteAnnotationException; import java.lang.annotation.IncompleteAnnotationException;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
@@ -19,7 +19,7 @@ public record LifecycleRegistration(ModuleLifecycle lifecycle, DiscoveredModule
* module's own. * module's own.
*/ */
PackWorld scope(PackWorld world) { PackWorld scope(PackWorld world) {
return world.withLog(module.log()); return ModuleWorld.of(world, module.log());
} }
/** The pack snapshot as this hook's module sees it, whose {@link PackContext#log} is the module's own. */ /** The pack snapshot as this hook's module sees it, whose {@link PackContext#log} is the module's own. */
@@ -11,6 +11,7 @@ import com.volmit.stage.MantleStageContext;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.world.TerrainSampler; import com.volmit.world.TerrainSampler;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** The context every stage of one mantle invocation receives. */ /** The context every stage of one mantle invocation receives. */
final class MantleInvocation implements MantleStageContext { final class MantleInvocation implements MantleStageContext {
@@ -66,6 +67,11 @@ final class MantleInvocation implements MantleStageContext {
return stages.world(inputs.world()); return stages.world(inputs.world());
} }
@Override
public <T> Optional<T> extension(Class<T> type) {
return inputs.extension(type);
}
@Override @Override
public WorldRandom random() { public WorldRandom random() {
return stages.random(); return stages.random();
@@ -0,0 +1,72 @@
package com.volmit.host;
import com.volmit.ModuleLog;
import com.volmit.config.PackSettings;
import com.volmit.resource.PackResources;
import com.volmit.world.PackWorld;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
/** A world as one module sees it: everything is the host's world, state and extensions included, except the log, which
* is the module's own. The host hands such a view to every stage body, service call and lifecycle hook, so a line is
* labelled with the module that wrote it. A state created through the view is created with the view.
*/
final class ModuleWorld implements PackWorld {
private final PackWorld world;
private final ModuleLog log;
private ModuleWorld(PackWorld world, ModuleLog log) {
this.world = world;
this.log = log;
}
/** {@code world} as the module whose log is {@code log} sees it; a view of a view wraps the host's world itself. */
static PackWorld of(PackWorld world, ModuleLog log) {
Objects.requireNonNull(world, "world");
Objects.requireNonNull(log, "log");
PackWorld hostWorld = world instanceof ModuleWorld view ? view.world : world;
return new ModuleWorld(hostWorld, log);
}
@Override
public long seed() {
return world.seed();
}
@Override
public PackResources resources() {
return world.resources();
}
@Override
public PackSettings settings() {
return world.settings();
}
@Override
public int minHeight() {
return world.minHeight();
}
@Override
public <T> T state(Class<T> type, Function<? super PackWorld, ? extends T> create) {
Objects.requireNonNull(create, "create");
return world.state(type, ignored -> create.apply(this));
}
@Override
public <T> Optional<T> extension(Class<T> type) {
return world.extension(type);
}
@Override
public ModuleLog log() {
return log;
}
@Override
public String toString() {
return world + " as " + log;
}
}
@@ -1,5 +1,14 @@
package com.volmit.config; package com.volmit.host;
import com.volmit.config.Desc;
import com.volmit.config.MaxNumber;
import com.volmit.config.MinItems;
import com.volmit.config.MinNumber;
import com.volmit.config.Ref;
import com.volmit.config.Reference;
import com.volmit.config.Required;
import com.volmit.config.ResourceRef;
import com.volmit.config.Snippet;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.lang.reflect.Type; import java.lang.reflect.Type;
@@ -7,7 +16,9 @@ import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
/** Annotation metadata, independent of JSON libraries. Does not decode or validate values. */ /** For the host: the options a settings class declares with their annotations, independent of JSON libraries, as
* studio descriptions and settings decoders read them. Does not decode or validate values.
*/
public record OptionsMetadata(String description, String snippet, List<Option> options) { public record OptionsMetadata(String description, String snippet, List<Option> options) {
public OptionsMetadata { public OptionsMetadata {
options = List.copyOf(options); options = List.copyOf(options);
@@ -15,6 +15,7 @@ import com.volmit.stage.Stage;
import com.volmit.world.BlockView; import com.volmit.world.BlockView;
import com.volmit.world.TerrainSampler; import com.volmit.world.TerrainSampler;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** The context every stage of one placement attempt receives. Block accessors work only while /** The context every stage of one placement attempt receives. Block accessors work only while
* a block pass is running. * a block pass is running.
@@ -118,6 +119,11 @@ final class PlacementInvocation implements BlockStageContext {
return stages.world(inputs.world()); return stages.world(inputs.world());
} }
@Override
public <T> Optional<T> extension(Class<T> type) {
return inputs.extension(type);
}
@Override @Override
public WorldRandom random() { public WorldRandom random() {
return stages.random(); return stages.random();
@@ -113,9 +113,9 @@ final class PlacementViews {
} }
@Override @Override
public MantleLayer<Boolean> caverns() { public boolean isCarved(int x, int y, int z) {
bounds(); checkPosition(bounds(), x, y, z);
return new RestrictedMantleLayer<>(this, parent.caverns()); return parent.isCarved(x, y, z);
} }
} }
@@ -1,82 +0,0 @@
package com.volmit.host;
import com.volmit.block.BlockState;
import com.volmit.mantle.BlockBox;
import com.volmit.mantle.Mantle;
import com.volmit.mantle.MantleEdit;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLayer;
import com.volmit.mantle.MantleVisitor;
/** The mantle as chunk stages see it: reads pass through, every write throws. The mantle pipeline has
* finished around the chunk by then, and its neighbors may already be generated.
*/
public final class ReadOnlyMantle implements Mantle {
private static final String READ_ONLY = "Chunk stages read the mantle but do not write it;"
+ " write it from a mantle stage (Stage.mantle), which runs before the chunks it reaches";
private final Mantle mantle;
ReadOnlyMantle(Mantle mantle) {
this.mantle = mantle;
}
/** The host's mantle behind this view: for a host's own extensions of {@link Mantle}, such as a built-in facade that
* reaches the platform's storage. A module that writes through it breaks the promise this view makes to chunk stages.
*/
public Mantle host() {
return mantle;
}
@Override
public BlockBox bounds() {
return mantle.bounds();
}
@Override
public <T> MantleLayer<T> layer(MantleKey<T> key) {
return new ReadOnlyLayer<>(mantle.layer(key));
}
@Override
public MantleLayer<BlockState> blocks() {
return new ReadOnlyLayer<>(mantle.blocks());
}
@Override
public MantleLayer<Boolean> caverns() {
return new ReadOnlyLayer<>(mantle.caverns());
}
@Override
public MantleEdit edit() {
throw new UnsupportedOperationException(READ_ONLY);
}
private record ReadOnlyLayer<T>(MantleLayer<T> layer) implements MantleLayer<T> {
@Override
public T get(int x, int y, int z) {
return layer.get(x, y, z);
}
@Override
public void set(int x, int y, int z, T value) {
throw new UnsupportedOperationException(READ_ONLY);
}
@Override
public void remove(int x, int y, int z) {
throw new UnsupportedOperationException(READ_ONLY);
}
@Override
public void visit(BlockBox area, MantleVisitor<T> visitor) {
layer.visit(area, visitor);
}
@Override
public void clear(BlockBox area) {
throw new UnsupportedOperationException(READ_ONLY);
}
}
}
@@ -4,7 +4,7 @@ import com.volmit.ModuleLog;
import com.volmit.world.PackWorld; import com.volmit.world.PackWorld;
import java.util.Objects; import java.util.Objects;
/** The views of worlds one module's stages get, whose log is the module's own ({@link PackWorld#withLog}). It keeps /** The views of worlds one module's stages get, whose log is the module's own ({@link ModuleWorld}). It keeps
* the view of the world it was last asked for, so the stages of a host that generates one world per resolved graph * the view of the world it was last asked for, so the stages of a host that generates one world per resolved graph
* get it without a new view per invocation; a host that alternates worlds on one graph asks the world each time. * get it without a new view per invocation; a host that alternates worlds on one graph asks the world each time.
* The kept world is released when the next one is asked for or the graph is dropped. Safe for concurrent use. * The kept world is released when the next one is asked for or the graph is dropped. Safe for concurrent use.
@@ -22,7 +22,7 @@ final class ScopedWorlds {
if (scoped != null && scoped.world() == world) { if (scoped != null && scoped.world() == world) {
return scoped.view(); return scoped.view();
} }
var view = world.withLog(log); var view = ModuleWorld.of(world, log);
last = new Scoped(world, view); last = new Scoped(world, view);
return view; return view;
} }
@@ -15,7 +15,7 @@ public record ServiceRegistration(Class<?> service, Object provider, DiscoveredM
* {@link PackWorld#log} is the module's own. * {@link PackWorld#log} is the module's own.
*/ */
public PackWorld scope(PackWorld world) { public PackWorld scope(PackWorld world) {
return world.withLog(module.log()); return ModuleWorld.of(world, module.log());
} }
@Override @Override
@@ -1,6 +1,5 @@
package com.volmit.host; package com.volmit.host;
import com.volmit.config.OptionsMetadata;
import com.volmit.host.schema.ValueKind; import com.volmit.host.schema.ValueKind;
import com.volmit.host.schema.ValueKind.ObjectKind; import com.volmit.host.schema.ValueKind.ObjectKind;
import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceId;
+7 -25
View File
@@ -2,7 +2,6 @@ package com.volmit.host;
import com.volmit.block.BlockState; import com.volmit.block.BlockState;
import com.volmit.config.Desc; import com.volmit.config.Desc;
import com.volmit.config.OptionsMetadata;
import com.volmit.config.Reference; import com.volmit.config.Reference;
import com.volmit.host.schema.TextFormat; import com.volmit.host.schema.TextFormat;
import com.volmit.host.schema.ValueKind; import com.volmit.host.schema.ValueKind;
@@ -20,7 +19,6 @@ import com.volmit.host.schema.ValueKind.ReferenceKind;
import com.volmit.host.schema.ValueKind.ResourceReferenceKind; import com.volmit.host.schema.ValueKind.ResourceReferenceKind;
import com.volmit.host.schema.ValueKind.TextKind; import com.volmit.host.schema.ValueKind.TextKind;
import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKey;
import java.lang.reflect.GenericArrayType; import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType; import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type; import java.lang.reflect.Type;
@@ -95,7 +93,6 @@ final class ValueKinds {
if (type == BlockState.class) return blockState(naming); if (type == BlockState.class) return blockState(naming);
if (type.isArray()) return new ListKind(kind(type.getComponentType(), naming), false); if (type.isArray()) return new ListKind(kind(type.getComponentType(), naming), false);
if (isCollection(type)) throw unsupported(type, " without type arguments; " + DECLARE_COLLECTION); if (isCollection(type)) throw unsupported(type, " without type arguments; " + DECLARE_COLLECTION);
if (type == ResourceKey.class) throw resourceKey(type);
requireNoNaming(type, naming); requireNoNaming(type, naming);
if (BOOLEANS.contains(type)) return new BooleanKind(); if (BOOLEANS.contains(type)) return new BooleanKind();
if (INTEGERS.contains(type)) return new IntegerKind(); if (INTEGERS.contains(type)) return new IntegerKind();
@@ -112,7 +109,6 @@ final class ValueKinds {
if (raw == List.class || raw == Set.class) return new ListKind(kind(arguments[0], naming), raw == Set.class); if (raw == List.class || raw == Set.class) return new ListKind(kind(arguments[0], naming), raw == Set.class);
if (raw == Map.class) return mapKind(generic, arguments, naming); if (raw == Map.class) return mapKind(generic, arguments, naming);
if (isCollection(raw)) throw unsupported(generic, "; " + DECLARE_COLLECTION); if (isCollection(raw)) throw unsupported(generic, "; " + DECLARE_COLLECTION);
if (raw == ResourceKey.class) throw resourceKey(generic);
throw unsupported(generic, "; only List, Set and Map may have type arguments"); throw unsupported(generic, "; only List, Set and Map may have type arguments");
} }
@@ -130,35 +126,27 @@ final class ValueKinds {
} }
private ValueKind text(TextFormat format, Naming naming) { private ValueKind text(TextFormat format, Naming naming) {
if (naming.resource() != null) return resourceReference(format, naming); if (naming.resource() != null) return resourceReference(naming);
var reference = naming.reference(); var reference = naming.reference();
if (reference == null) return new TextKind(format); if (reference == null) return new TextKind(format);
if (format == TextFormat.RESOURCE_ID && PACK_REFERENCES.contains(reference)) throw packReferenceOnResourceId(reference); if (PACK_REFERENCES.contains(reference)) return new ReferenceKind(reference, TextFormat.PLAIN);
return new ReferenceKind(reference, format); return new ReferenceKind(reference, format);
} }
/** Packs name a kind's resources by key without a namespace, as they name their biomes, so only plain text holds one. */ /** Packs name a kind's resources by key without a namespace, as they name their biomes, so the JSON holds a key
private ValueKind resourceReference(TextFormat format, Naming naming) { * whether the field is a String or a ResourceId (which the host reads as the pack's id of that key).
*/
private ValueKind resourceReference(Naming naming) {
var resource = naming.resource(); var resource = naming.resource();
if (naming.reference() != null) { if (naming.reference() != null) {
throw new SettingsTypeProblem("has both @Ref(" + naming.reference() + ") and @ResourceRef(" + resource.getName() throw new SettingsTypeProblem("has both @Ref(" + naming.reference() + ") and @ResourceRef(" + resource.getName()
+ "); an option names one kind of thing, so keep one"); + "); an option names one kind of thing, so keep one");
} }
if (format != TextFormat.PLAIN) {
throw new SettingsTypeProblem("has @ResourceRef(" + resource.getName() + ") on ResourceId, but packs name a kind's"
+ " resources by key without a namespace, such as castle/start; use String");
}
return resourceKinds.apply(resource).map(ResourceReferenceKind::new).orElseThrow(() -> new SettingsTypeProblem( return resourceKinds.apply(resource).map(ResourceReferenceKind::new).orElseThrow(() -> new SettingsTypeProblem(
"has @ResourceRef(" + resource.getName() + "), but no module of the pack registers a resource kind read into" "has @ResourceRef(" + resource.getName() + "), but no module of the pack registers a resource kind read into"
+ " that class; name the class of a kind registered with FeatureRegistry.registerResourceKind")); + " that class; name the class of a kind registered with FeatureRegistry.registerResourceKind"));
} }
/** Packs name their biomes, regions and objects by path without a namespace, so a ResourceId could not hold one. */
private static SettingsTypeProblem packReferenceOnResourceId(Reference reference) {
return new SettingsTypeProblem("has @Ref(" + reference + ") on ResourceId, but packs name their biomes,"
+ " regions and objects by path without a namespace, such as desert/dunes; use String");
}
private static ValueKind blockState(Naming naming) { private static ValueKind blockState(Naming naming) {
var reference = naming.reference(); var reference = naming.reference();
if (naming.resource() == null && (reference == null || reference == Reference.BLOCK)) { if (naming.resource() == null && (reference == null || reference == Reference.BLOCK)) {
@@ -196,13 +184,7 @@ final class ValueKinds {
+ ", but @Ref fits only String and ResourceId and lists, sets and arrays of them"); + ", but @Ref fits only String and ResourceId and lists, sets and arrays of them");
} }
throw new SettingsTypeProblem("has @ResourceRef(" + naming.resource().getName() + ") on " + type.getTypeName() throw new SettingsTypeProblem("has @ResourceRef(" + naming.resource().getName() + ") on " + type.getTypeName()
+ ", but @ResourceRef fits only String and lists, sets and arrays of it"); + ", but @ResourceRef fits only String and ResourceId and lists, sets and arrays of them");
}
/** ResourceKey's type argument is the Java class a resource loads as, which tells studio nothing to list. */
private static SettingsTypeProblem resourceKey(Type type) {
return unsupported(type, ", which names a Java type, not something studio can list; use ResourceId,"
+ " with @Ref when it names a block, biome or other listed entry");
} }
private static boolean isCollection(Class<?> type) { private static boolean isCollection(Class<?> type) {
+28 -15
View File
@@ -5,6 +5,9 @@ import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
/** /**
* One stack of items a module decided to give: what a loot entry, a block's drops or an entity's equipment turned into * One stack of items a module decided to give: what a loot entry, a block's drops or an entity's equipment turned into
@@ -13,45 +16,55 @@ import java.util.Objects;
* *
* @param item the item's key as the pack wrote it, see {@link ItemRegistry} * @param item the item's key as the pack wrote it, see {@link ItemRegistry}
* @param amount how many, at least 1 * @param amount how many, at least 1
* @param displayName the item's name, or null to keep the platform's * @param displayName the item's name; empty keeps the platform's
* @param lore lines of text under the name * @param lore lines of text under the name
* @param enchantments applied in order * @param enchantments applied in order
* @param attributes attribute modifiers applied in order * @param attributes attribute modifiers applied in order
* @param unbreakable whether the item never breaks * @param unbreakable whether the item never breaks
* @param flags platform item flags to set, by name; names the platform lacks are ignored * @param flags platform item flags to set, by name; names the platform lacks are ignored
* @param customModel custom model number, or null * @param customModel custom model number; empty for none
* @param damage the fraction of the item's durability already used, 0 to 1, or null to leave it undamaged * @param damage the fraction of the item's durability already used, 0 to 1; empty leaves it undamaged
* @param leatherColor colour of leather armour as {@code #rrggbb}, or null * @param leatherColor colour of leather armour as {@code #rrggbb}; empty for none
* @param dyeColor dye colour name, or null * @param dyeColor dye colour name; empty for none
* @param customNbt custom data the platform stores on the item, or empty * @param customNbt custom data the platform stores on the item, or an empty map
* @param source where the item came from, set only when the host asked for it to be shown (debug loot) * @param source where the item came from, present only when the host asked for it to be shown (debug loot)
*/ */
public record ItemDrop(String item, int amount, String displayName, List<String> lore, List<ItemEnchantment> enchantments, public record ItemDrop(String item, int amount, Optional<String> displayName, List<String> lore, List<ItemEnchantment> enchantments,
List<ItemAttribute> attributes, boolean unbreakable, List<String> flags, Integer customModel, List<ItemAttribute> attributes, boolean unbreakable, List<String> flags, OptionalInt customModel,
Double damage, String leatherColor, String dyeColor, Map<String, Object> customNbt, Source source) { OptionalDouble damage, Optional<String> leatherColor, Optional<String> dyeColor, Map<String, Object> customNbt,
Optional<Source> source) {
public ItemDrop { public ItemDrop {
Objects.requireNonNull(item, "item"); Objects.requireNonNull(item, "item");
if (amount < 1) throw new IllegalArgumentException("Item amount must be at least 1: " + amount); if (amount < 1) throw new IllegalArgumentException("Item amount must be at least 1: " + amount);
Objects.requireNonNull(displayName, "displayName");
lore = List.copyOf(lore); lore = List.copyOf(lore);
enchantments = List.copyOf(enchantments); enchantments = List.copyOf(enchantments);
attributes = List.copyOf(attributes); attributes = List.copyOf(attributes);
flags = List.copyOf(flags); flags = List.copyOf(flags);
customNbt = customNbt == null ? Map.of() : Collections.unmodifiableMap(new LinkedHashMap<>(customNbt)); Objects.requireNonNull(customModel, "customModel");
Objects.requireNonNull(damage, "damage");
Objects.requireNonNull(leatherColor, "leatherColor");
Objects.requireNonNull(dyeColor, "dyeColor");
customNbt = Collections.unmodifiableMap(new LinkedHashMap<>(customNbt));
Objects.requireNonNull(source, "source");
} }
/** {@code amount} items of kind {@code item} and nothing else. */ /** {@code amount} items of kind {@code item} and nothing else. */
public static ItemDrop of(String item, int amount) { public static ItemDrop of(String item, int amount) {
return new ItemDrop(item, amount, null, List.of(), List.of(), List.of(), false, List.of(), null, null, null, null, return new ItemDrop(item, amount, Optional.empty(), List.of(), List.of(), List.of(), false, List.of(), OptionalInt.empty(),
Map.of(), null); OptionalDouble.empty(), Optional.empty(), Optional.empty(), Map.of(), Optional.empty());
} }
/** /**
* Where a shown item came from: the loot table, when it came from one, and the 1-in-N chances it passed. * Where a shown item came from: the loot table, when it came from one, and the 1-in-N chances it passed.
* *
* @param table the table's name, or null for an item that came from no table * @param table the table's name; empty for an item that came from no table
* @param tableRarity the table's rarity, 1 in this many * @param tableRarity the table's rarity, 1 in this many
* @param entryRarity the entry's rarity within the table * @param entryRarity the entry's rarity within the table
*/ */
public record Source(String table, int tableRarity, int entryRarity) { public record Source(Optional<String> table, int tableRarity, int entryRarity) {
public Source {
Objects.requireNonNull(table, "table");
}
} }
} }
+4 -5
View File
@@ -32,12 +32,11 @@ public interface Mantle {
*/ */
MantleLayer<BlockState> blocks(); MantleLayer<BlockState> blocks();
/** Where the mantle holds a carved void for the chunk to take over: a cave's air or fluid, planned before the chunks /** Whether the mantle holds a carved void at the position for the chunk to take over: a cave's air or fluid, planned
* were generated. Present ({@code true}) at carved positions, absent elsewhere, also where the chunk's own blocks * before the chunks were generated. Also true where the chunk's own blocks show no void, such as under a dimension
* show no void, such as under a dimension stacked above. The host owns this layer, so it needs no registration. * stacked above. The host owns the carving; stages only ask. A dimension that keeps no mantle carves nothing.
* Stages read it only, and writes throw UnsupportedOperationException. A dimension that keeps no mantle holds none.
*/ */
MantleLayer<Boolean> caverns(); boolean isCarved(int x, int y, int z);
/** Only one edit may be active per view. Parent reads remain allowed, but parent /** Only one edit may be active per view. Parent reads remain allowed, but parent
* mutations are prohibited until the edit ends (IllegalStateException). * mutations are prohibited until the edit ends (IllegalStateException).
@@ -3,6 +3,9 @@ package com.volmit.resource;
import com.volmit.block.BlockRegistry; import com.volmit.block.BlockRegistry;
import com.volmit.item.ItemRegistry; import com.volmit.item.ItemRegistry;
import com.volmit.noise.NoiseFactory; import com.volmit.noise.NoiseFactory;
import com.volmit.object.GeneratedObject;
import com.volmit.world.PackBiome;
import com.volmit.world.PackRegion;
import java.util.List; import java.util.List;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Optional; import java.util.Optional;
@@ -10,14 +13,22 @@ import java.util.UUID;
/** Immutable view of one loaded pack snapshot, safe for concurrent reads. /** Immutable view of one loaded pack snapshot, safe for concurrent reads.
* Reload produces a different snapshotId, even for the same pack. Resources must be immutable * Reload produces a different snapshotId, even for the same pack. Resources must be immutable
* or explicitly thread-safe. The requested type selects the kind of resource, so one ID can name * or explicitly thread-safe. A resource is named by its kind and its id, so one id can name
* both a biome and a region. Hosts serve {@code GeneratedObject} (pack objects), * both a biome and a region. Hosts serve the kinds {@link #BIOMES}, {@link #REGIONS} and {@link #OBJECTS}
* {@code PackBiome}, {@code PackRegion} and the type of every {@link ResourceKind} the pack's modules * and every {@link ResourceKind} the pack's modules register; an id the pack lacks for that kind returns empty,
* register; an ID the pack lacks for that kind returns empty, and a type the host does not serve throws * and a kind the host does not serve throws IllegalArgumentException. Broken resources fail loading rather than
* IllegalArgumentException. Broken resources fail loading rather than appearing absent. * appearing absent. The host owns resolution, imports, native handles and caches; no filesystem paths escape.
* The host owns resolution, imports, native handles and caches; no filesystem paths escape.
*/ */
public interface PackResources { public interface PackResources {
/** The pack's biomes, as the host reads them from its own folder. */
ResourceKind<PackBiome> BIOMES = ResourceKind.of("host:biome", "biomes", PackBiome.class);
/** The pack's regions, as the host reads them from its own folder. */
ResourceKind<PackRegion> REGIONS = ResourceKind.of("host:region", "regions", PackRegion.class);
/** The pack's objects as geometry, as the host reads them from its own folder. */
ResourceKind<GeneratedObject> OBJECTS = ResourceKind.of("host:object", "objects", GeneratedObject.class);
ResourceId packId(); ResourceId packId();
UUID snapshotId(); UUID snapshotId();
BlockRegistry blocks(); BlockRegistry blocks();
@@ -28,12 +39,13 @@ public interface PackResources {
/** Builds the noise of the {@link com.volmit.noise.NoiseStyle}s the pack's settings describe. */ /** Builds the noise of the {@link com.volmit.noise.NoiseStyle}s the pack's settings describe. */
NoiseFactory noise(); NoiseFactory noise();
<T> Optional<T> find(ResourceKey<T> key); /** The resource of {@code kind} the pack has under {@code id}; empty when it has none. */
<T> Optional<T> find(ResourceKind<T> kind, ResourceId id);
/** The ids of every resource of the kind {@code type} selects, in id order. A type the host does not serve /** The ids of every resource of {@code kind}, in id order. A kind the host does not serve throws
* throws IllegalArgumentException, as in {@link #find}. * IllegalArgumentException, as in {@link #find}.
*/ */
List<ResourceId> ids(Class<?> type); List<ResourceId> ids(ResourceKind<?> kind);
/** The id of the resource the pack's files name by {@code key} (the file path inside the kind's folder, without /** The id of the resource the pack's files name by {@code key} (the file path inside the kind's folder, without
* {@code .json}), such as {@code overworld:dungeon/chest} for {@code dungeon/chest}; see * {@code .json}), such as {@code overworld:dungeon/chest} for {@code dungeon/chest}; see
@@ -45,7 +57,8 @@ public interface PackResources {
return ResourceId.ofPackKey(packId().namespace(), key); return ResourceId.ofPackKey(packId().namespace(), key);
} }
default <T> T require(ResourceKey<T> key) { /** {@link #find} for a resource that must exist: a missing one throws NoSuchElementException naming kind and id. */
return find(key).orElseThrow(() -> new NoSuchElementException("Missing resource: " + key.id())); default <T> T require(ResourceKind<T> kind, ResourceId id) {
return find(kind, id).orElseThrow(() -> new NoSuchElementException("Missing " + kind.id() + " resource: " + id));
} }
} }
@@ -1,14 +0,0 @@
package com.volmit.resource;
import java.util.Objects;
/** A resource ID paired with its public value type; the host owns loading and caching. */
public record ResourceKey<T>(ResourceId id, Class<T> type) {
public ResourceKey {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(type, "type");
if (type.isPrimitive()) throw new IllegalArgumentException("Resources require a reference type");
}
public ResourceKey(String id, Class<T> type) { this(ResourceId.parse(id), type); }
}
@@ -4,11 +4,12 @@ import java.lang.reflect.Modifier;
import java.util.Objects; import java.util.Objects;
import java.util.regex.Pattern; import java.util.regex.Pattern;
/** A kind of resource a module reads from the pack: every JSON file below {@code <pack>/<folder>/}, each read /** A kind of resource read from the pack: every JSON file below {@code <pack>/<folder>/}, each read
* into a new instance of {@code type}. A file's key is its path below the folder without {@code .json}, such as * into a new instance of {@code type}. A file's key is its path below the folder without {@code .json}, such as
* {@code castle/keep}, and its id is {@code <pack namespace>:<key>}, the form {@link PackResources} uses for * {@code castle/keep}, and its id is {@code <pack namespace>:<key>}, the form {@link PackResources} uses for
* every pack resource. The host serves resources of the kind through {@link PackResources#find} by * every pack resource. A resource is found by its kind and its id, {@link PackResources#find}{@code (kind, id)};
* {@code type}, so each kind has a class of its own. * the host tells kinds apart by {@code type}, so each kind has a class of its own. The host's own kinds are the
* constants of {@link PackResources}.
* *
* <p>Modules register kinds with {@link com.volmit.FeatureRegistry#registerResourceKind}. The id names the kind * <p>Modules register kinds with {@link com.volmit.FeatureRegistry#registerResourceKind}. The id names the kind
* in errors and studio and follows the module id like every other id the module owns: {@code iris:structure} * in errors and studio and follows the module id like every other id the module owns: {@code iris:structure}
@@ -39,11 +40,6 @@ public record ResourceKind<T>(ResourceId id, String folder, Class<T> type) {
return FOLDER.matcher(name).matches() && !name.equals(".") && !name.equals(".."); return FOLDER.matcher(name).matches() && !name.equals(".") && !name.equals("..");
} }
/** The key {@link PackResources#find} takes for the resource {@code resource} of this kind. */
public ResourceKey<T> key(ResourceId resource) {
return new ResourceKey<>(resource, type);
}
private static void requireFolderName(ResourceId id, String folder) { private static void requireFolderName(ResourceId id, String folder) {
if (isFolderName(folder)) return; if (isFolderName(folder)) return;
throw new IllegalArgumentException("Folder '" + folder + "' of resource kind " + id + " is not a folder name;" throw new IllegalArgumentException("Folder '" + folder + "' of resource kind " + id + " is not a folder name;"
@@ -5,6 +5,7 @@ import com.volmit.world.BlockPosition;
import com.volmit.world.PackWorld; import com.volmit.world.PackWorld;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* The ambient effects of an area: sounds, particles, potion effects and commands that play around the players who stay * The ambient effects of an area: sounds, particles, potion effects and commands that play around the players who stay
@@ -26,14 +27,17 @@ public interface AmbientEffects {
* One effect that plays now. The host carries out the parts it has, in the order sound, particles, commands, potion. * One effect that plays now. The host carries out the parts it has, in the order sound, particles, commands, potion.
* A part the platform lacks, such as an unknown sound, is skipped. * A part the platform lacks, such as an unknown sound, is skipped.
* *
* @param sound a sound to play, or null * @param sound a sound to play; empty for none
* @param particles particles to show, or null * @param particles particles to show; empty for none
* @param commands console commands to run, none when the effect has no commands that may run now * @param commands console commands to run, none when the effect has no commands that may run now
* @param potion a potion effect to give, or null * @param potion a potion effect to give; empty for none
*/ */
record Effect(Sound sound, Particles particles, List<Command> commands, Potion potion) { record Effect(Optional<Sound> sound, Optional<Particles> particles, List<Command> commands, Optional<Potion> potion) {
public Effect { public Effect {
Objects.requireNonNull(sound, "sound");
Objects.requireNonNull(particles, "particles");
commands = List.copyOf(commands); commands = List.copyOf(commands);
Objects.requireNonNull(potion, "potion");
} }
} }
@@ -1,5 +1,6 @@
package com.volmit.service; package com.volmit.service;
import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld; import com.volmit.world.PackWorld;
import java.util.Optional; import java.util.Optional;
@@ -15,14 +16,14 @@ public interface CaveBiomes {
* overrides nothing. * overrides nothing.
* *
* @param y the height above the dimension's bottom * @param y the height above the dimension's bottom
* @return the biome key as packs write it * @return the biome's pack id
*/ */
Optional<String> overriddenBiome(PackWorld world, int x, int y, int z); Optional<ResourceId> overriddenBiome(PackWorld world, int x, int y, int z);
/** /**
* How many blocks below the surface a position must lie for the pack biome {@code biomeKey} to be the cave biome there; * How many blocks below the surface a position must lie for the pack biome {@code biome} to be the cave biome there;
* nearer the surface the surface's biome is. 0 for a biome that has no such limit. The answer depends on the world and the * nearer the surface the surface's biome is. 0 for a biome that has no such limit. The answer depends on the world and the
* biome only: the host asks once per biome and keeps it while the world runs. * biome only: the host asks once per biome and keeps it while the world runs.
*/ */
int minDepthBelowSurface(PackWorld world, String biomeKey); int minDepthBelowSurface(PackWorld world, ResourceId biome);
} }
@@ -1,6 +1,7 @@
package com.volmit.service; package com.volmit.service;
import com.volmit.entity.EntitySpec; import com.volmit.entity.EntitySpec;
import com.volmit.resource.ResourceId;
import com.volmit.world.BlockPosition; import com.volmit.world.BlockPosition;
import com.volmit.world.PackWorld; import com.volmit.world.PackWorld;
import java.util.List; import java.util.List;
@@ -21,8 +22,8 @@ public interface EntitySpawns {
/** Called with the number of entities of {@code plan} that appeared, so the spawner's rate limits count them. */ /** Called with the number of entities of {@code plan} that appeared, so the spawner's rate limits count them. */
void spawned(PackWorld world, Plan plan, int count); void spawned(PackWorld world, Plan plan, int count);
/** The entity of the pack named {@code key} as this module would spawn it, for tools that spawn one on request; empty for an unknown key. */ /** The pack's entity {@code entity} as this module would spawn it, for tools that spawn one on request; empty for an unknown one. */
Optional<EntitySpec> entity(PackWorld world, String key); Optional<EntitySpec> entity(PackWorld world, ResourceId entity);
/** What a marker in the world means for spawning; empty for a marker this module does not know. */ /** What a marker in the world means for spawning; empty for a marker this module does not know. */
Optional<MarkerRule> marker(PackWorld world, String tag); Optional<MarkerRule> marker(PackWorld world, String tag);
@@ -46,10 +47,10 @@ public interface EntitySpawns {
* *
* @param position the marker's block: world X and Z, Y the height above the dimension's bottom * @param position the marker's block: world X and Z, Y the height above the dimension's bottom
* @param marker the marker's tag * @param marker the marker's tag
* @param spawner the key of the spawner chosen among the marker's * @param spawner the pack's spawner chosen among the marker's
* @param initial whether the spawner's initial spawns are used rather than its ordinary ones * @param initial whether the spawner's initial spawns are used rather than its ordinary ones
*/ */
record Marker(BlockPosition position, String marker, String spawner, boolean initial) implements Site { record Marker(BlockPosition position, String marker, ResourceId spawner, boolean initial) implements Site {
public Marker { public Marker {
Objects.requireNonNull(position, "position"); Objects.requireNonNull(position, "position");
Objects.requireNonNull(marker, "marker"); Objects.requireNonNull(marker, "marker");
@@ -60,11 +61,11 @@ public interface EntitySpawns {
/** /**
* What a marker does. * What a marker does.
* *
* @param spawners keys of the spawners at the marker * @param spawners the pack's spawners at the marker
* @param emptyAbove whether it only counts with free space above it * @param emptyAbove whether it only counts with free space above it
* @param removeOnChange whether it goes away when its block changes * @param removeOnChange whether it goes away when its block changes
*/ */
record MarkerRule(List<String> spawners, boolean emptyAbove, boolean removeOnChange) { record MarkerRule(List<ResourceId> spawners, boolean emptyAbove, boolean removeOnChange) {
public MarkerRule { public MarkerRule {
spawners = List.copyOf(spawners); spawners = List.copyOf(spawners);
} }
@@ -73,12 +74,12 @@ public interface EntitySpawns {
/** /**
* Entities to spawn, tried one after the other. * Entities to spawn, tried one after the other.
* *
* @param spawner the key of the spawner that planned them * @param spawner the pack's spawner that planned them
* @param chunkX the chunk they spawn in, where the spawner's per-chunk limit counts them * @param chunkX the chunk they spawn in, where the spawner's per-chunk limit counts them
* @param exhaustsMarker whether the marker that led here is used up and should be removed * @param exhaustsMarker whether the marker that led here is used up and should be removed
* @param attempts the spawns to try * @param attempts the spawns to try
*/ */
record Plan(String spawner, int chunkX, int chunkZ, boolean exhaustsMarker, List<Attempt> attempts) { record Plan(ResourceId spawner, int chunkX, int chunkZ, boolean exhaustsMarker, List<Attempt> attempts) {
public Plan { public Plan {
Objects.requireNonNull(spawner, "spawner"); Objects.requireNonNull(spawner, "spawner");
attempts = List.copyOf(attempts); attempts = List.copyOf(attempts);
+10 -7
View File
@@ -2,10 +2,12 @@ package com.volmit.service;
import com.volmit.block.BlockState; import com.volmit.block.BlockState;
import com.volmit.item.ItemDrop; import com.volmit.item.ItemDrop;
import com.volmit.resource.ResourceId;
import com.volmit.world.BlockPosition; import com.volmit.world.BlockPosition;
import com.volmit.world.PackWorld; import com.volmit.world.PackWorld;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* The loot a module gives containers and mobs. The host asks in two steps so that it, and plugins listening to it, can * The loot a module gives containers and mobs. The host asks in two steps so that it, and plugins listening to it, can
@@ -22,8 +24,8 @@ public interface Loot {
*/ */
List<Source> tables(PackWorld world, Site site); List<Source> tables(PackWorld world, Site site);
/** The items table {@code key} gives at {@code site}; empty for a table this module does not know. */ /** The items the pack's table {@code table} gives at {@code site}; empty for a table this module does not know. */
List<ItemDrop> items(PackWorld world, Site site, String key); List<ItemDrop> items(PackWorld world, Site site, ResourceId table);
/** /**
* Where loot is given. * Where loot is given.
@@ -31,13 +33,14 @@ public interface Loot {
* @param position the container, or the mob's spawn spot: world X and Z, Y the height above the dimension's * @param position the container, or the mob's spawn spot: world X and Z, Y the height above the dimension's
* bottom * bottom
* @param container the container's block when it is a storage chest the module may give the loot of the object * @param container the container's block when it is a storage chest the module may give the loot of the object
* placed there, null for any other spot * placed there; empty for any other spot
* @param nativeLootDefined whether the platform already gave the container a loot table of its own * @param nativeLootDefined whether the platform already gave the container a loot table of its own
* @param debug whether items should say where they came from ({@link ItemDrop#source()}) * @param debug whether items should say where they came from ({@link ItemDrop#source()})
*/ */
record Site(BlockPosition position, BlockState container, boolean nativeLootDefined, boolean debug) { record Site(BlockPosition position, Optional<BlockState> container, boolean nativeLootDefined, boolean debug) {
public Site { public Site {
Objects.requireNonNull(position, "position"); Objects.requireNonNull(position, "position");
Objects.requireNonNull(container, "container");
} }
} }
@@ -45,10 +48,10 @@ public interface Loot {
sealed interface Source permits Table, PlatformTable { sealed interface Source permits Table, PlatformTable {
} }
/** A loot table of the pack, named by its key as packs write it ({@code dungeon/chest}). */ /** A loot table of the pack, by the id {@link com.volmit.resource.PackResources#idOf} gives its key. */
record Table(String key) implements Source { record Table(ResourceId id) implements Source {
public Table { public Table {
Objects.requireNonNull(key, "key"); Objects.requireNonNull(id, "id");
} }
} }
@@ -1,5 +1,6 @@
package com.volmit.service; package com.volmit.service;
import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld; import com.volmit.world.PackWorld;
import java.util.Objects; import java.util.Objects;
import java.util.Set; import java.util.Set;
@@ -10,23 +11,23 @@ import java.util.Set;
@Service(Providers.ALL) @Service(Providers.ALL)
public interface ObjectsAt { public interface ObjectsAt {
/** /**
* The keys of the pack objects this module would place in the chunk at {@code chunkX}, {@code chunkZ} (chunk * The ids of the pack objects this module would place in the chunk at {@code chunkX}, {@code chunkZ} (chunk
* coordinates, world X and Z divided by 16), in the form packs write them ({@code trees/oak}). It is a prediction: * coordinates, world X and Z divided by 16), as {@link com.volmit.resource.PackResources#idOf} gives them. It is a
* it may name an object whose placement the chunk's generation later rejects. Empty when the module places nothing * prediction: it may name an object whose placement the chunk's generation later rejects. Empty when the module
* there. * places nothing there.
*/ */
Set<String> objectsAt(PackWorld world, int chunkX, int chunkZ); Set<ResourceId> objectsAt(PackWorld world, int chunkX, int chunkZ);
/** /**
* The biomes and regions of {@code world}'s layout whose own settings make this module place the object * The biomes and regions of {@code world}'s layout whose own settings make this module place the object
* {@code objectKey}. The host finds the areas where the object can appear from these: a biome counts for the areas * {@code object}. The host finds the areas where the object can appear from these: a biome counts for the areas
* it generates in and, through its children, for the areas of the biomes inside it, so a provider names only the * it generates in and, through its children, for the areas of the biomes inside it, so a provider names only the
* layout entries that place the object themselves. Only biomes and regions the dimension can reach are named. * layout entries that place the object themselves. Only biomes and regions the dimension can reach are named.
*/ */
PlacedBy placedBy(PackWorld world, String objectKey); PlacedBy placedBy(PackWorld world, ResourceId object);
/** Layout entries that place an object, named by the keys packs write ({@code land/plains}, {@code temperate}). */ /** Layout entries that place an object, by their pack ids. */
record PlacedBy(Set<String> biomes, Set<String> regions) { record PlacedBy(Set<ResourceId> biomes, Set<ResourceId> regions) {
public static final PlacedBy NOTHING = new PlacedBy(Set.of(), Set.of()); public static final PlacedBy NOTHING = new PlacedBy(Set.of(), Set.of());
public PlacedBy { public PlacedBy {
@@ -2,6 +2,7 @@ package com.volmit.service;
import com.volmit.block.BlockState; import com.volmit.block.BlockState;
import com.volmit.placement.PlacedBlock; import com.volmit.placement.PlacedBlock;
import com.volmit.resource.ResourceId;
import com.volmit.world.BlockPosition; import com.volmit.world.BlockPosition;
import com.volmit.world.PackWorld; import com.volmit.world.PackWorld;
import java.util.List; import java.util.List;
@@ -53,10 +54,11 @@ public interface SaplingGrowth {
/** /**
* The tree to place. * The tree to place.
* *
* @param object the pack object key the tree comes from, in the form packs write it * @param object the id of the object the tree comes from, as {@link com.volmit.resource.PackResources#idOf} gives it
* for the object's key
* @param blocks the blocks to place, in order, later ones over earlier ones * @param blocks the blocks to place, in order, later ones over earlier ones
*/ */
record Growth(String object, List<PlacedBlock> blocks) { record Growth(ResourceId object, List<PlacedBlock> blocks) {
public Growth { public Growth {
Objects.requireNonNull(object, "object"); Objects.requireNonNull(object, "object");
blocks = List.copyOf(blocks); blocks = List.copyOf(blocks);
@@ -64,12 +66,12 @@ public interface SaplingGrowth {
} }
/** /**
* Object keys a module places as trees. * Objects a module places as trees, by the ids {@link com.volmit.resource.PackResources#idOf} gives their keys.
* *
* @param objects pack objects its placements mark as trees * @param objects pack objects its placements mark as trees
* @param procedural the keys of the objects its procedural trees generate, one per variant * @param procedural the objects its procedural trees generate, one per variant
*/ */
record TreeObjects(Set<String> objects, Set<String> procedural) { record TreeObjects(Set<ResourceId> objects, Set<ResourceId> procedural) {
public static final TreeObjects NONE = new TreeObjects(Set.of(), Set.of()); public static final TreeObjects NONE = new TreeObjects(Set.of(), Set.of());
public TreeObjects { public TreeObjects {
@@ -1,39 +1,40 @@
package com.volmit.service; package com.volmit.service;
import com.volmit.resource.PackResources; import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld; import com.volmit.world.PackWorld;
import java.util.Set; import java.util.Set;
/** Finds the structures a module places, for the host's structure commands and index. Structures are named by their /** Finds the structures a module places, for the host's structure commands and index. Structures are named by their
* keys, in the form packs write them ({@code castle}, {@code villages/plains}). The host asks the providers in order and * ids: a pack's own structure by the id {@link PackResources#idOf} gives its key ({@code overworld:villages/plains}),
* sends a key to the first that places it in the world ({@link #placed}). * a platform structure by the platform's id ({@code minecraft:ancient_city}). The host asks the providers in order and
* sends an id to the first that places it in the world ({@link #placed}).
*/ */
@Service(Providers.FIRST) @Service(Providers.FIRST)
public interface StructureLocator { public interface StructureLocator {
/** Every structure key of the pack this module knows, placed in a world or not, such as one per structure file. The /** Every structure of the pack this module knows, placed in a world or not, such as one per structure file. The
* host lists them in its index of the structures a pack has. * host lists them in its index of the structures a pack has.
*/ */
Set<String> structures(PackResources pack); Set<ResourceId> structures(PackResources pack);
/** The keys of the structures this module places in {@code world} and can find with {@link #locate}: commands offer /** The structures this module places in {@code world} and can find with {@link #locate}: commands offer them and
* them and send a search for one of them here. A structure no placement of the world uses is not among them. * send a search for one of them here. A structure no placement of the world uses is not among them.
*/ */
Set<String> locatable(PackWorld world); Set<ResourceId> locatable(PackWorld world);
/** The keys under which {@link #locate} finds the structures this module places in {@code world}, locatable or not: its /** The structures {@link #locate} finds among those this module places in {@code world}, locatable or not: its own
* own structures, the platform structures it starts itself and the platform structures its own stand in for (namespaced, * structures, the platform structures it starts itself and the platform structures its own stand in for. Commands
* such as {@code minecraft:ancient_city}). Commands report them and send a search for one of them here. By default the * report them and send a search for one of them here. By default the {@link #locatable} ones.
* {@link #locatable} ones.
*/ */
default Set<String> placed(PackWorld world) { default Set<ResourceId> placed(PackWorld world) {
return locatable(world); return locatable(world);
} }
/** /**
* The start of structure {@code key} nearest to the column {@code fromX}, {@code fromZ} (world coordinates), searched * The start of {@code structure} nearest to the column {@code fromX}, {@code fromZ} (world coordinates), searched
* up to {@code maxRadiusChunks} chunks away from it. The position is the structure's origin: world X and Z, and Y the * up to {@code maxRadiusChunks} chunks away from it. The position is the structure's origin: world X and Z, and Y the
* height above the dimension's bottom of its base. Called with a key from {@link #placed}. May take long; the * height above the dimension's bottom of its base. Called with an id from {@link #placed}. May take long; the
* host calls it off the server's main thread. * host calls it off the server's main thread.
*/ */
LocateResult locate(PackWorld world, String key, int fromX, int fromZ, int maxRadiusChunks); LocateResult locate(PackWorld world, ResourceId structure, int fromX, int fromZ, int maxRadiusChunks);
} }
@@ -2,9 +2,9 @@ package com.volmit.stage;
import com.volmit.IrisFeature; import com.volmit.IrisFeature;
/** Declares one chunk stage. A chunk stage writes only its own chunk and reads the mantle, so it declares neither a /** Declares one chunk stage. A chunk stage writes only its own chunk, its blocks and its columns of the mantle, and
* reach nor mantle layers: work that writes the mantle or reaches beyond its chunk is a {@link MantleStage}. Edges * reads the mantle around it, so it declares neither a reach nor mantle layers: work that writes the mantle beyond its
* work as on {@link PlacementStageDefinition}. * chunk is a {@link MantleStage}. Edges work as on {@link PlacementStageDefinition}.
*/ */
public interface ChunkStageDefinition<O> { public interface ChunkStageDefinition<O> {
ChunkStageDefinition<O> requires(Stage<?>... stages); ChunkStageDefinition<O> requires(Stage<?>... stages);
@@ -0,0 +1,21 @@
package com.volmit.vanilla;
/** Names one platform start for as long as the platform keeps it, across chunks: {@link StructureFit.Start#key()}.
* Two keys are equal only when they are the same object, and the host hands out the same key for the same start, so a
* module may keep what it worked out about a start in a cache keyed weakly by it; the key holds nothing of the start,
* so the cache does not keep the start alive. Only the host creates keys.
*/
public final class StartKey {
/** For the host: a key for a start it has not named yet. */
public static StartKey create() {
return new StartKey();
}
private StartKey() {
}
@Override
public String toString() {
return "StartKey@" + Integer.toHexString(System.identityHashCode(this));
}
}
@@ -80,10 +80,10 @@ public interface StructureFit {
/** Every piece of the start, in the platform's order: also the pieces outside the chunk. */ /** Every piece of the start, in the platform's order: also the pieces outside the chunk. */
List<Piece> pieces(); List<Piece> pieces();
/** An object that stays the same for this start for as long as the platform keeps it, across chunks: a key for /** The key that stays the same for this start for as long as the platform keeps it, across chunks: for caches
* caches about the start, held weakly so the start can be forgotten. * about the start, held weakly so the start can be forgotten.
*/ */
Object key(); StartKey key();
} }
/** A piece of a start. */ /** A piece of a start. */
@@ -3,7 +3,6 @@ package com.volmit.world;
import com.volmit.block.BlockFace; import com.volmit.block.BlockFace;
import com.volmit.block.BlockState; import com.volmit.block.BlockState;
import com.volmit.block.BlockTrait; import com.volmit.block.BlockTrait;
import com.volmit.mantle.BlockBox;
import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceId;
/** The live blocks of an area of the platform's world, for code that reads and changes them in place while the /** The live blocks of an area of the platform's world, for code that reads and changes them in place while the
@@ -18,11 +17,7 @@ import com.volmit.resource.ResourceId;
* *
* <p>Not thread-safe, and valid only while the call that handed it out runs. * <p>Not thread-safe, and valid only while the call that handed it out runs.
*/ */
public interface BlockAccess { public interface BlockAccess extends BlockView {
BlockBox bounds();
BlockState get(int x, int y, int z);
/** Reads {@code into.length} blocks of a column upward: {@code into[i]} is the block at height {@code fromY + i}. */ /** Reads {@code into.length} blocks of a column upward: {@code into[i]} is the block at height {@code fromY + i}. */
void column(int x, int z, int fromY, BlockState[] into); void column(int x, int z, int fromY, BlockState[] into);
@@ -3,10 +3,11 @@ package com.volmit.world;
import com.volmit.block.BlockState; import com.volmit.block.BlockState;
import com.volmit.mantle.BlockBox; import com.volmit.mantle.BlockBox;
/** Read-only prepared generation blocks, not the live server world. X and Z are world coordinates; /** Blocks of an area to read: a placement's prepared generation blocks ({@link com.volmit.placement.PlacementContext#blocks()}),
* or, through {@link BlockAccess}, the live blocks of the platform's world. X and Z are world coordinates;
* Y is the height above the dimension's bottom (0 = bottom), also in {@link #bounds()}. * Y is the height above the dimension's bottom (0 = bottom), also in {@link #bounds()}.
* Empty space is a non-null air state. Out-of-area access throws IndexOutOfBoundsException. * Empty space is a non-null air state. Out-of-area access throws IndexOutOfBoundsException.
* Views expire with the owning invocation; access afterwards throws IllegalStateException. * Views expire with the call or invocation that handed them out; access afterwards throws IllegalStateException.
*/ */
public interface BlockView { public interface BlockView {
BlockBox bounds(); BlockBox bounds();
+11 -3
View File
@@ -3,6 +3,7 @@ package com.volmit.world;
import com.volmit.ModuleLog; import com.volmit.ModuleLog;
import com.volmit.config.PackSettings; import com.volmit.config.PackSettings;
import com.volmit.resource.PackResources; import com.volmit.resource.PackResources;
import java.util.Optional;
import java.util.function.Function; import java.util.function.Function;
/** One world the host generates with a pack, for as long as the pack stays loaded: the world's seed, the pack's /** One world the host generates with a pack, for as long as the pack stays loaded: the world's seed, the pack's
@@ -57,8 +58,15 @@ public interface PackWorld {
*/ */
ModuleLog log(); ModuleLog log();
/** For the host: this world as {@code log}'s module sees it, sharing everything else, state included. The host calls it /**
* once per module it hands a world to; a module has no reason to. * What the host offers for this world beyond the API, as an object of {@code type}: empty when the host offers no
* such thing. A host extends the API this way for its own modules, such as Iris's built-in modules, which reach Iris's
* object placing or its derived seeds through interfaces of their own exposed package. The host fills it when it
* builds the world; a module that asks for a type the host does not know gets empty and decides itself whether that
* is an error. Pack modules written for any host use the API only. Per invocation inputs are
* {@link com.volmit.generation.InvocationContext#extension}.
*/ */
PackWorld withLog(ModuleLog log); default <T> Optional<T> extension(Class<T> type) {
return Optional.empty();
}
} }
@@ -38,7 +38,6 @@ class ApiValuesTest {
assertEquals("y", state.properties().get("axis")); assertEquals("y", state.properties().get("axis"));
assertEquals("x", state.withProperty("axis", "x").properties().get("axis")); assertEquals("x", state.withProperty("axis", "x").properties().get("axis"));
assertThrows(UnsupportedOperationException.class, () -> state.properties().clear()); assertThrows(UnsupportedOperationException.class, () -> state.properties().clear());
assertThrows(IllegalArgumentException.class, () -> new ResourceKey<>("test:value", int.class));
} }
@Test @Test
@@ -187,10 +186,6 @@ class ApiValuesTest {
@Test @Test
void resourceKindsReadOneFolderIntoAConcreteClass() { void resourceKindsReadOneFolderIntoAConcreteClass() {
var kind = ResourceKind.of("test:castle/keep", "keeps", Keep.class);
var id = ResourceId.parse("overworld:castle/main");
assertEquals(new ResourceKey<>(id, Keep.class), kind.key(id));
assertTrue(ResourceKind.isFolderName("jigsaw-pools")); assertTrue(ResourceKind.isFolderName("jigsaw-pools"));
for (String folder : List.of("", ".", "..", "a/b", "Keeps", "a b")) { for (String folder : List.of("", ".", "..", "a/b", "Keeps", "a b")) {
var failure = assertThrows(IllegalArgumentException.class, () -> ResourceKind.of("test:castle/keep", folder, Keep.class)); var failure = assertThrows(IllegalArgumentException.class, () -> ResourceKind.of("test:castle/keep", folder, Keep.class));
@@ -2,6 +2,7 @@ package com.volmit;
import com.volmit.config.*; import com.volmit.config.*;
import com.volmit.host.FeatureDescriptor; import com.volmit.host.FeatureDescriptor;
import com.volmit.host.OptionsMetadata;
import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceId;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@@ -13,6 +13,9 @@ import org.junit.jupiter.api.Test;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
@@ -23,8 +26,8 @@ class ItemAndEntityValuesTest {
assertThrows(IllegalArgumentException.class, () -> ItemDrop.of("stick", 0)); assertThrows(IllegalArgumentException.class, () -> ItemDrop.of("stick", 0));
List<ItemEnchantment> enchantments = new ArrayList<>(List.of(new ItemEnchantment("sharpness", 3))); List<ItemEnchantment> enchantments = new ArrayList<>(List.of(new ItemEnchantment("sharpness", 3)));
ItemDrop drop = new ItemDrop("diamond_sword", 1, null, List.of(), enchantments, List.of(), false, List.of(), null, ItemDrop drop = new ItemDrop("diamond_sword", 1, Optional.empty(), List.of(), enchantments, List.of(), false, List.of(),
0.25, null, null, Map.of(), null); OptionalInt.empty(), OptionalDouble.of(0.25), Optional.empty(), Optional.empty(), Map.of(), Optional.empty());
enchantments.clear(); enchantments.clear();
assertEquals(1, drop.enchantments().size()); assertEquals(1, drop.enchantments().size());
@@ -32,10 +35,23 @@ class ItemAndEntityValuesTest {
assertThrows(IllegalArgumentException.class, () -> new ItemEnchantment("sharpness", 0)); assertThrows(IllegalArgumentException.class, () -> new ItemEnchantment("sharpness", 0));
} }
@Test
void absentValuesAreEmptyNeverNull() {
ItemDrop stick = ItemDrop.of("stick", 1);
assertTrue(stick.displayName().isEmpty());
assertTrue(stick.damage().isEmpty());
assertTrue(stick.source().isEmpty());
assertThrows(NullPointerException.class, () -> new ItemDrop("stick", 1, null, List.of(), List.of(), List.of(), false,
List.of(), OptionalInt.empty(), OptionalDouble.empty(), Optional.empty(), Optional.empty(), Map.of(), Optional.empty()));
assertThrows(NullPointerException.class, () -> new AmbientEffects.Effect(null, Optional.empty(), List.of(), Optional.empty()));
assertThrows(NullPointerException.class, () -> new EntitySpawns.MarkerRule(null, false, false));
}
@Test @Test
void anEntityKnowsWhetherItIsAnotherPluginsMob() { void anEntityKnowsWhetherItIsAnotherPluginsMob() {
EntitySpec zombie = entity("minecraft:zombie", ""); EntitySpec zombie = entity(Optional.of("minecraft:zombie"), Optional.empty());
EntitySpec special = entity("", "mythic:dragon"); EntitySpec special = entity(Optional.empty(), Optional.of("mythic:dragon"));
assertFalse(zombie.isSpecial()); assertFalse(zombie.isSpecial());
assertTrue(special.isSpecial()); assertTrue(special.isSpecial());
@@ -44,7 +60,7 @@ class ItemAndEntityValuesTest {
@Test @Test
void anAttemptSaysWhetherLightMatters() { void anAttemptSaysWhetherLightMatters() {
BlockPosition at = new BlockPosition(1, 2, 3); BlockPosition at = new BlockPosition(1, 2, 3);
EntitySpec zombie = entity("minecraft:zombie", ""); EntitySpec zombie = entity(Optional.of("minecraft:zombie"), Optional.empty());
assertFalse(new EntitySpawns.Attempt(at, zombie, EntitySpawns.Surface.LAND, 0, 15, true).restrictsLight()); assertFalse(new EntitySpawns.Attempt(at, zombie, EntitySpawns.Surface.LAND, 0, 15, true).restrictsLight());
assertTrue(new EntitySpawns.Attempt(at, zombie, EntitySpawns.Surface.LAND, 0, 7, true).restrictsLight()); assertTrue(new EntitySpawns.Attempt(at, zombie, EntitySpawns.Surface.LAND, 0, 7, true).restrictsLight());
@@ -62,7 +78,8 @@ class ItemAndEntityValuesTest {
void anAmbientEffectKeepsItsCommandsApartAndRefusesPartsWithoutKeys() { void anAmbientEffectKeepsItsCommandsApartAndRefusesPartsWithoutKeys() {
List<AmbientEffects.Command> commands = new ArrayList<>(List.of( List<AmbientEffects.Command> commands = new ArrayList<>(List.of(
new AmbientEffects.Command(new EntitySpec.Command(List.of("say hi"), 0, false, 100), 1, 0, -1))); new AmbientEffects.Command(new EntitySpec.Command(List.of("say hi"), 0, false, 100), 1, 0, -1)));
AmbientEffects.Effect effect = new AmbientEffects.Effect(null, null, commands, new AmbientEffects.Potion("luck", 0, 100)); AmbientEffects.Effect effect = new AmbientEffects.Effect(Optional.empty(), Optional.empty(), commands,
Optional.of(new AmbientEffects.Potion("luck", 0, 100)));
commands.clear(); commands.clear();
assertEquals(1, effect.commands().size()); assertEquals(1, effect.commands().size());
@@ -71,9 +88,9 @@ class ItemAndEntityValuesTest {
assertThrows(NullPointerException.class, () -> new AmbientEffects.Command(null, 0, 0, 0)); assertThrows(NullPointerException.class, () -> new AmbientEffects.Command(null, 0, 0, 0));
} }
private static EntitySpec entity(String type, String specialType) { private static EntitySpec entity(Optional<String> type, Optional<String> specialType) {
return new EntitySpec(type, specialType, null, "", new EntitySpec.Flags(false, true, true, false, true, false, false, return new EntitySpec(type, specialType, Optional.empty(), Optional.empty(), new EntitySpec.Flags(false, true, true, false,
false, false, false, false), EntitySpec.Equipment.NONE, List.of(), List.of(), List.of(), 0L, null, null, false, true, false, false, false, false, false, false), EntitySpec.Equipment.NONE, List.of(), List.of(), List.of(), 0L,
null, null, false, List.of()); Optional.empty(), Optional.empty(), false, Optional.empty(), Optional.empty(), false, List.of());
} }
} }
@@ -2,7 +2,7 @@ package com.volmit;
import com.volmit.block.BlockSpec; import com.volmit.block.BlockSpec;
import com.volmit.block.PaletteSpec; import com.volmit.block.PaletteSpec;
import com.volmit.config.OptionsMetadata; import com.volmit.host.OptionsMetadata;
import com.volmit.config.Range; import com.volmit.config.Range;
import com.volmit.noise.NoiseFactory; import com.volmit.noise.NoiseFactory;
import com.volmit.noise.NoiseSampler; import com.volmit.noise.NoiseSampler;
@@ -1,7 +1,7 @@
package com.volmit; package com.volmit;
import com.volmit.block.BlockState; import com.volmit.block.BlockState;
import com.volmit.config.OptionsMetadata; import com.volmit.host.OptionsMetadata;
import com.volmit.resource.PackResources; import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceId;
import com.volmit.service.LocateResult; import com.volmit.service.LocateResult;
@@ -30,6 +30,7 @@ import static org.junit.jupiter.api.Assertions.*;
class VanillaStructureValuesTest { class VanillaStructureValuesTest {
private static final ResourceId VILLAGES = ResourceId.parse("minecraft:villages"); private static final ResourceId VILLAGES = ResourceId.parse("minecraft:villages");
private static final ResourceId CITY = ResourceId.parse("minecraft:ancient_city"); private static final ResourceId CITY = ResourceId.parse("minecraft:ancient_city");
private static final ResourceId CASTLE = ResourceId.parse("test:castle");
@Test @Test
void jigsawOverridesKeepThePacksJsonNamesAndDefaults() { void jigsawOverridesKeepThePacksJsonNamesAndDefaults() {
@@ -137,22 +138,22 @@ class VanillaStructureValuesTest {
public void aLocatorPlacesWhatItCanLocateUnlessItSaysMore() { public void aLocatorPlacesWhatItCanLocateUnlessItSaysMore() {
StructureLocator locator = new StructureLocator() { StructureLocator locator = new StructureLocator() {
@Override @Override
public Set<String> structures(PackResources pack) { public Set<ResourceId> structures(PackResources pack) {
return Set.of("castle", "tower"); return Set.of(CASTLE, ResourceId.parse("test:tower"));
} }
@Override @Override
public Set<String> locatable(PackWorld world) { public Set<ResourceId> locatable(PackWorld world) {
return Set.of("castle"); return Set.of(CASTLE);
} }
@Override @Override
public LocateResult locate(PackWorld world, String key, int fromX, int fromZ, int maxRadiusChunks) { public LocateResult locate(PackWorld world, ResourceId structure, int fromX, int fromZ, int maxRadiusChunks) {
return LocateResult.NOT_FOUND; return LocateResult.NOT_FOUND;
} }
}; };
assertEquals(Set.of("castle"), locator.placed(null)); assertEquals(Set.of(CASTLE), locator.placed(null));
} }
@Test @Test
@@ -21,7 +21,9 @@ import com.volmit.host.MantleRunner;
import com.volmit.host.StageTimings; import com.volmit.host.StageTimings;
import com.volmit.hunk.Hunk; import com.volmit.hunk.Hunk;
import com.volmit.mantle.BlockBox; import com.volmit.mantle.BlockBox;
import com.volmit.mantle.MantleLayer;
import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceId;
import com.volmit.stage.ChunkStageContext;
import com.volmit.stage.Pipeline; import com.volmit.stage.Pipeline;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.support.ColumnSettings; import com.volmit.support.ColumnSettings;
@@ -30,9 +32,11 @@ import com.volmit.support.MemoryMantle;
import com.volmit.support.TestContexts; import com.volmit.support.TestContexts;
import com.volmit.support.TestSetups; import com.volmit.support.TestSetups;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.function.BiConsumer;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
@@ -193,9 +197,8 @@ class ChunkPipelineTest {
public ModuleInfo info() { return ModuleInfo.of("test:caves", "Caves", "1"); } public ModuleInfo info() { return ModuleInfo.of("test:caves", "Caves", "1"); }
public void setup(ModuleSetup setup) { public void setup(ModuleSetup setup) {
setup.stages().define(probe).run(context -> { setup.stages().define(probe).run(context -> {
var caverns = context.mantle().caverns(); carved.add(String.valueOf(context.mantle().isCarved(6, 9, 2)));
carved.add(String.valueOf(caverns.get(6, 9, 2))); carved.add(String.valueOf(context.mantle().isCarved(6, 10, 2)));
carved.add(String.valueOf(caverns.get(6, 10, 2)));
}); });
} }
}; };
@@ -205,8 +208,7 @@ class ChunkPipelineTest {
TestContexts.generation(Map.of(BlockState.class, blocks), ColumnSettings.NONE, mantle.within(chunkArea)), TestContexts.SEED, TestContexts.generation(Map.of(BlockState.class, blocks), ColumnSettings.NONE, mantle.within(chunkArea)), TestContexts.SEED,
StageTimings.NONE); StageTimings.NONE);
assertEquals(List.of("true", "null"), carved); assertEquals(List.of("true", "false"), carved);
assertThrows(UnsupportedOperationException.class, () -> mantle.within(chunkArea).caverns().set(0, 0, 0, true));
} }
@Test @Test
@@ -221,22 +223,44 @@ class ChunkPipelineTest {
} }
@Test @Test
void chunkStagesReadTheMantleButCannotWriteIt() { void chunkStagesWriteTheMantleOfTheirOwnChunkOnly() {
var stage = Stage.chunk("test:writer/work");
var mantle = new MemoryMantle(); var mantle = new MemoryMantle();
IrisModule module = new IrisModule() { var aroundTheChunk = new BlockBox(-CHUNK, BOTTOM, -CHUNK, 2 * CHUNK, TOP, 2 * CHUNK);
public ModuleInfo info() { return ModuleInfo.of("test:writer", "Writer", "1"); } var graph = TestSetups.stages(oreWriter((context, layer) -> layer.set(15, 3, 0, 1))).resolve(Pipeline.CHUNK);
public void setup(ModuleSetup setup) {
setup.stages().define(stage).run(context -> context.mantle().layer(VeinModule.ORE).set(0, 0, 0, 1)); new ChunkRunner(graph).generate(TestContexts.generation(Map.of(), ColumnSettings.NONE, mantle.within(aroundTheChunk)),
} TestContexts.SEED, StageTimings.NONE);
};
var graph = TestSetups.stages(module).resolve(Pipeline.CHUNK); assertEquals(1, mantle.get(VeinModule.ORE, 15, 3, 0));
var inputs = TestContexts.generation(Map.of(), ColumnSettings.NONE, mantle.within(new BlockBox(0, BOTTOM, 0, CHUNK, TOP, CHUNK))); }
@Test
void chunkStagesReadTheirNeighboursMantleButCannotWriteIt() {
var mantle = new MemoryMantle();
var aroundTheChunk = new BlockBox(-CHUNK, BOTTOM, -CHUNK, 2 * CHUNK, TOP, 2 * CHUNK);
var read = new ArrayList<Integer>();
var graph = TestSetups.stages(oreWriter((context, layer) -> {
read.add(layer.get(CHUNK, 0, 0));
layer.set(CHUNK, 0, 0, 1);
})).resolve(Pipeline.CHUNK);
var inputs = TestContexts.generation(Map.of(), ColumnSettings.NONE, mantle.within(aroundTheChunk));
var failure = assertThrows(UnsupportedOperationException.class, var failure = assertThrows(UnsupportedOperationException.class,
() -> new ChunkRunner(graph).generate(inputs, TestContexts.SEED, StageTimings.NONE)); () -> new ChunkRunner(graph).generate(inputs, TestContexts.SEED, StageTimings.NONE));
assertEquals("Chunk stages read the mantle but do not write it; write it from a mantle stage (Stage.mantle)," assertEquals("A chunk stage writes the mantle of its own chunk only; write around it from a mantle stage"
+ " which runs before the chunks it reaches", failure.getMessage()); + " (Stage.mantle), which runs before the chunks it reaches; 16,0,0 is outside BlockBox[minX=0, minY=0,"
assertNull(mantle.get(VeinModule.ORE, 0, 0, 0)); + " minZ=0, maxX=16, maxY=384, maxZ=16]", failure.getMessage());
assertEquals(Collections.singletonList(null), read, "the neighbour is read before the write fails");
assertNull(mantle.get(VeinModule.ORE, CHUNK, 0, 0));
}
private static IrisModule oreWriter(BiConsumer<ChunkStageContext, MantleLayer<Integer>> body) {
var stage = Stage.chunk("test:writer/work");
return new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of("test:writer", "Writer", "1"); }
public void setup(ModuleSetup setup) {
setup.stages().define(stage).run(context -> body.accept(context, context.mantle().layer(VeinModule.ORE)));
}
};
} }
} }
@@ -9,6 +9,7 @@ import com.volmit.host.DiscoveredModule;
import com.volmit.host.LifecycleRunner; import com.volmit.host.LifecycleRunner;
import com.volmit.host.LoadedModules; import com.volmit.host.LoadedModules;
import com.volmit.host.StageTimings; import com.volmit.host.StageTimings;
import com.volmit.resource.ResourceId;
import com.volmit.service.ObjectsAt; import com.volmit.service.ObjectsAt;
import com.volmit.stage.ChunkStage; import com.volmit.stage.ChunkStage;
import com.volmit.stage.ChunkStageContext; import com.volmit.stage.ChunkStageContext;
@@ -30,6 +31,7 @@ import static org.junit.jupiter.api.Assertions.*;
class WorldStateExampleTest { class WorldStateExampleTest {
static final class RuinsModule implements IrisModule, ModuleLifecycle { static final class RuinsModule implements IrisModule, ModuleLifecycle {
static final ChunkStage<Void> PLANT = Stage.chunk("example:ruins/plant"); static final ChunkStage<Void> PLANT = Stage.chunk("example:ruins/plant");
static final ResourceId ARCH = new ResourceId("test", "ruins/arch");
/** What ruins keeps per world. A field of the module would be shared by every world. */ /** What ruins keeps per world. A field of the module would be shared by every world. */
static final class PlantedChunks { static final class PlantedChunks {
@@ -49,12 +51,12 @@ class WorldStateExampleTest {
registry.registerLifecycle(this); registry.registerLifecycle(this);
registry.registerService(ObjectsAt.class, new ObjectsAt() { registry.registerService(ObjectsAt.class, new ObjectsAt() {
@Override @Override
public Set<String> objectsAt(PackWorld world, int chunkX, int chunkZ) { public Set<ResourceId> objectsAt(PackWorld world, int chunkX, int chunkZ) {
return RuinsModule.objectsAt(world, chunkX, chunkZ); return RuinsModule.objectsAt(world, chunkX, chunkZ);
} }
@Override @Override
public PlacedBy placedBy(PackWorld world, String objectKey) { public PlacedBy placedBy(PackWorld world, ResourceId object) {
return PlacedBy.NOTHING; return PlacedBy.NOTHING;
} }
}); });
@@ -73,8 +75,8 @@ class WorldStateExampleTest {
planted(context.world()).chunks.add(key(context.chunkX(), context.chunkZ())); planted(context.world()).chunks.add(key(context.chunkX(), context.chunkZ()));
} }
private static Set<String> objectsAt(PackWorld world, int chunkX, int chunkZ) { private static Set<ResourceId> objectsAt(PackWorld world, int chunkX, int chunkZ) {
return planted(world).chunks.contains(key(chunkX, chunkZ)) ? Set.of("ruins/arch") : Set.of(); return planted(world).chunks.contains(key(chunkX, chunkZ)) ? Set.of(ARCH) : Set.of();
} }
private static long key(int chunkX, int chunkZ) { private static long key(int chunkX, int chunkZ) {
@@ -97,7 +99,7 @@ class WorldStateExampleTest {
StageTimings.NONE); StageTimings.NONE);
assertSame(startedWith, RuinsModule.planted(world), "the stage used the state the hook built"); assertSame(startedWith, RuinsModule.planted(world), "the stage used the state the hook built");
assertEquals(Set.of("ruins/arch"), objects.objectsAt(world, 0, 0)); assertEquals(Set.of(RuinsModule.ARCH), objects.objectsAt(world, 0, 0));
assertEquals(Set.of(), objects.objectsAt(world, 1, 0)); assertEquals(Set.of(), objects.objectsAt(world, 1, 0));
lifecycles.worldStopped(world); lifecycles.worldStopped(world);
} }
@@ -0,0 +1,107 @@
package com.volmit.host;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.ModuleLog;
import com.volmit.ModuleSetup;
import com.volmit.config.FeatureSettings;
import com.volmit.config.PackSettings;
import com.volmit.generation.GenerationContext;
import com.volmit.hunk.Hunk;
import com.volmit.mantle.Mantle;
import com.volmit.resource.PackResources;
import com.volmit.stage.Pipeline;
import com.volmit.stage.Stage;
import com.volmit.support.TestContexts;
import com.volmit.support.TestSetups;
import com.volmit.world.PackWorld;
import com.volmit.world.TerrainSampler;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** What a host offers its own modules beyond the API reaches the stages through the world and the invocation. */
class ExtensionsTest {
/** Something a host offers for a whole world. */
record WorldOffer(String name) {}
/** Something a host offers for one invocation. */
record ChunkOffer(int chunkX) {}
@Test
void aStageReachesWhatTheHostOffersForItsWorldAndItsInvocation() {
var seen = new ArrayList<Object>();
var stage = Stage.chunk("test:offers/read");
IrisModule module = new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of("test:offers", "Offers", "1"); }
public void setup(ModuleSetup setup) {
setup.stages().define(stage).run(context -> {
seen.add(context.world().extension(WorldOffer.class));
seen.add(context.extension(ChunkOffer.class));
seen.add(context.world().extension(ChunkOffer.class));
seen.add(context.extension(WorldOffer.class));
seen.add(context.world().log() == ModuleLogs.discarding() ? "host's log" : "module's log");
});
}
};
var world = new OfferingWorld(new WorldOffer("iris"));
var inputs = new OfferingChunk(TestContexts.generation(Map.of(), null, null, world), new ChunkOffer(0));
new ChunkRunner(TestSetups.stages(module).resolve(Pipeline.CHUNK)).generate(inputs, TestContexts.SEED, StageTimings.NONE);
assertEquals(List.of(Optional.of(new WorldOffer("iris")), Optional.of(new ChunkOffer(0)), Optional.empty(), Optional.empty(),
"module's log"), seen, "the module's view of the world keeps the host's offers, with the module's own log");
}
@Test
void aModulesViewOfAWorldCreatesStateWithThatView() {
var world = new OfferingWorld(new WorldOffer("iris"));
var log = ModuleLogs.discarding();
PackWorld view = ModuleWorld.of(ModuleWorld.of(world, ModuleLogs.discarding()), log);
PackWorld createdWith = view.state(PackWorld.class, Function.identity());
assertSame(view, createdWith);
assertSame(createdWith, world.state(PackWorld.class, ignored -> null), "the state lives in the host's world");
assertEquals(Optional.of(new WorldOffer("iris")), view.extension(WorldOffer.class));
}
private static final class OfferingWorld implements PackWorld {
private final WorldStates states = new WorldStates();
private final WorldOffer offer;
OfferingWorld(WorldOffer offer) {
this.offer = offer;
}
public long seed() { return TestContexts.SEED; }
public PackResources resources() { throw new AssertionError("Unused resources"); }
public PackSettings settings() { throw new AssertionError("Unused settings"); }
public <T> T state(Class<T> type, Function<? super PackWorld, ? extends T> create) { return states.state(type, () -> create.apply(this)); }
public ModuleLog log() { return ModuleLogs.discarding(); }
@Override
public <T> Optional<T> extension(Class<T> type) {
return type.isInstance(offer) ? Optional.of(type.cast(offer)) : Optional.empty();
}
}
private record OfferingChunk(GenerationContext inputs, ChunkOffer offer) implements GenerationContext {
public int originX() { return inputs.originX(); }
public int originZ() { return inputs.originZ(); }
public TerrainSampler terrain() { return inputs.terrain(); }
public FeatureSettings settings() { return inputs.settings(); }
public Mantle mantle() { return inputs.mantle(); }
public <T> Hunk<T> hunk(Class<T> type) { return inputs.hunk(type); }
public PackWorld world() { return inputs.world(); }
@Override
public <T> Optional<T> extension(Class<T> type) {
return type.isInstance(offer) ? Optional.of(type.cast(offer)) : Optional.empty();
}
}
}
@@ -595,9 +595,6 @@ class PackSchemaTest {
+ " map keys must be String", "private Map<Integer, String> weights;"); + " map keys must be String", "private Map<Integer, String> weights;");
assertLoadFails("Field pack.flora.FloraSettings.letter of " + FLORA_SOURCE + " uses char, which settings cannot use; " assertLoadFails("Field pack.flora.FloraSettings.letter of " + FLORA_SOURCE + " uses char, which settings cannot use; "
+ ValueKinds.SUPPORTED_TYPES, "private char letter;"); + ValueKinds.SUPPORTED_TYPES, "private char letter;");
assertLoadFails("Field pack.flora.FloraSettings.palette of " + FLORA_SOURCE + " uses com.volmit.resource.ResourceKey<java.lang.String>, which names"
+ " a Java type, not something studio can list; use ResourceId, with @Ref when it names a block, biome or other listed entry",
"private ResourceKey<String> palette;");
assertLoadFails("Field pack.flora.FloraSettings.names of " + FLORA_SOURCE + " uses ? extends java.lang.String, which is not a" assertLoadFails("Field pack.flora.FloraSettings.names of " + FLORA_SOURCE + " uses ? extends java.lang.String, which is not a"
+ " concrete type; name the type, such as List<String>", "private List<? extends String> names;"); + " concrete type; name the type, such as List<String>", "private List<? extends String> names;");
} }
@@ -673,12 +670,29 @@ class PackSchemaTest {
} }
@Test @Test
void packReferencesFitOnlyPlainText() { void packReferencesOnResourceIdsAreWrittenAsKeys() {
assertLoadFails("Field pack.flora.FloraSettings.home of " + FLORA_SOURCE + " has @Ref(PACK_BIOME) on ResourceId, but packs name" var pack = pack("pack-ids");
+ " their biomes, regions and objects by path without a namespace, such as desert/dunes; use String", module("pack.flora.FloraModule", FLORA, NO_MEMBERS, "registry.registerSettings(FloraSettings.class);")
"@Ref(Reference.PACK_BIOME) private ResourceId home;"); .source("pack.flora.FloraSettings", """
assertTrue(loadFailure("@Ref(Reference.PACK_OBJECT) private List<ResourceId> objects;").getMessage() package pack.flora;
.contains("has @Ref(PACK_OBJECT) on ResourceId"));
import com.volmit.IrisFeature;
import com.volmit.config.*;
import com.volmit.resource.ResourceId;
import java.util.*;
@Feature(id = "example:flora", name = "Flora", key = "flora", targets = Level.BIOME)
public final class FloraSettings implements IrisFeature {
@Ref(Reference.PACK_BIOME) private ResourceId home;
@Ref(Reference.PACK_OBJECT) private List<ResourceId> objects = List.of();
}
""")
.writeInto(pack, "flora.jar");
var settings = schemaOf(pack, NO_BUILT_INS).type("pack.flora.FloraSettings");
assertEquals(new ReferenceKind(Reference.PACK_BIOME, TextFormat.PLAIN), option(settings, "home").kind());
assertEquals(new ListKind(new ReferenceKind(Reference.PACK_OBJECT, TextFormat.PLAIN), false), option(settings, "objects").kind());
} }
@Test @Test
@@ -807,10 +821,8 @@ class PackSchemaTest {
+ " module of the pack registers a resource kind read into that class; name the class of a kind registered with" + " module of the pack registers a resource kind read into that class; name the class of a kind registered with"
+ " FeatureRegistry.registerResourceKind", "@ResourceRef(Integer.class) private String keep;"); + " FeatureRegistry.registerResourceKind", "@ResourceRef(Integer.class) private String keep;");
assertLoadFails("Field pack.flora.FloraSettings.count of " + FLORA_SOURCE + " has @ResourceRef(java.lang.Integer) on int," assertLoadFails("Field pack.flora.FloraSettings.count of " + FLORA_SOURCE + " has @ResourceRef(java.lang.Integer) on int,"
+ " but @ResourceRef fits only String and lists, sets and arrays of it", "@ResourceRef(Integer.class) private int count;"); + " but @ResourceRef fits only String and ResourceId and lists, sets and arrays of them",
assertLoadFails("Field pack.flora.FloraSettings.keep of " + FLORA_SOURCE + " has @ResourceRef(java.lang.Integer) on" "@ResourceRef(Integer.class) private int count;");
+ " ResourceId, but packs name a kind's resources by key without a namespace, such as castle/start; use String",
"@ResourceRef(Integer.class) private ResourceId keep;");
assertLoadFails("Field pack.flora.FloraSettings.keep of " + FLORA_SOURCE + " has both @Ref(BLOCK) and" assertLoadFails("Field pack.flora.FloraSettings.keep of " + FLORA_SOURCE + " has both @Ref(BLOCK) and"
+ " @ResourceRef(java.lang.Integer); an option names one kind of thing, so keep one", + " @ResourceRef(java.lang.Integer); an option names one kind of thing, so keep one",
"@Ref(Reference.BLOCK) @ResourceRef(Integer.class) private String keep;"); "@Ref(Reference.BLOCK) @ResourceRef(Integer.class) private String keep;");
@@ -5,7 +5,7 @@ import com.volmit.item.ItemRegistry;
import com.volmit.noise.NoiseFactory; import com.volmit.noise.NoiseFactory;
import com.volmit.resource.PackResources; import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKey; import com.volmit.resource.ResourceKind;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
@@ -40,12 +40,12 @@ public final class EmptyResources implements PackResources {
} }
@Override @Override
public <T> Optional<T> find(ResourceKey<T> key) { public <T> Optional<T> find(ResourceKind<T> kind, ResourceId id) {
return Optional.empty(); return Optional.empty();
} }
@Override @Override
public List<ResourceId> ids(Class<?> type) { public List<ResourceId> ids(ResourceKind<?> kind) {
return List.of(); return List.of();
} }
} }
@@ -32,7 +32,7 @@ public final class MemoryMantle {
public BlockBox bounds() { return bounds; } public BlockBox bounds() { return bounds; }
public <T> MantleLayer<T> layer(MantleKey<T> key) { return new Layer<>(key, bounds, true); } public <T> MantleLayer<T> layer(MantleKey<T> key) { return new Layer<>(key, bounds, true); }
public MantleLayer<BlockState> blocks() { return new Layer<>(PLANNED_BLOCKS, bounds, false); } public MantleLayer<BlockState> blocks() { return new Layer<>(PLANNED_BLOCKS, bounds, false); }
public MantleLayer<Boolean> caverns() { return new Layer<>(CAVERNS, bounds, false); } public boolean isCarved(int x, int y, int z) { return new Layer<>(CAVERNS, bounds, false).get(x, y, z) != null; }
public MantleEdit edit() { throw new UnsupportedOperationException("Edits are not used in these tests"); } public MantleEdit edit() { throw new UnsupportedOperationException("Edits are not used in these tests"); }
}; };
} }
@@ -53,11 +53,6 @@ public final class TestWorld implements PackWorld, AutoCloseable {
return log; return log;
} }
@Override
public PackWorld withLog(ModuleLog log) {
return new TestWorld(states, log);
}
@Override @Override
public void close() { public void close() {
states.close(); states.close();