diff --git a/CONTRACTS.md b/CONTRACTS.md index ffb5bf56b..541c3af80 100644 --- a/CONTRACTS.md +++ b/CONTRACTS.md @@ -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 | | Pack-load validation and diagnostics | host `StageGraphBuilder`, `ResolvedGraph`, `LoadedModules` | | 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 | -| Annotated settings | `IrisFeature`, `@Feature` (id, short JSON `key`, optional `root`), config annotations, `OptionsMetadata`, `LinkedBiomes` (`treeBiomes`, `usedBiomes`: pack biomes the settings bring into the layout) | +| 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, 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` | | 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` | @@ -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` | | 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)` | -| Pack-scoped resolution | `ResourceId` (`ofPackKey`), `ResourceKey`, `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 checks | `Validator`, `ValidationContext`, `Problem`, `Severity`, `Subject`, `FeatureRegistry.registerValidator`, host `FeatureCatalog.validators()` | | 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. - 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 - `PackWorld.log()` and `withLog(log)` (a view of the world sharing everything else) and hand services a world scoped to the - provider's module (`ServiceRegistration.scope`); the runners do it for stages and hooks. + `PackWorld.log()` (the host's own log) and hand services a world scoped to the provider's module + (`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 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. @@ -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 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. - 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. - 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 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. +- 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 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. diff --git a/DESIGN.md b/DESIGN.md index 4d8228421..472f6559e 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -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 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 -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 -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. +placements planned there. It writes registered layers inside the chunk's own 16 by 16 columns only: the mantle pipeline has finished around the +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. ## 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 (`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`; -- `ResourceKey`: 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; - 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 @@ -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 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 -load. The pack kinds (`PACK_BIOME`, `PACK_REGION`, `PACK_OBJECT`, `PACK_EXPRESSION`, `PACK_IMAGE_MAP`, `PACK_STRUCTURE`) fit `String` only: packs name their -biomes, regions and objects by path without a namespace, such as `desert/dunes`, which a `ResourceId` -cannot hold. `BlockState` always names a block, so its fields are block references without `@Ref`; +load. The pack kinds (`PACK_BIOME`, `PACK_REGION`, `PACK_OBJECT`, `PACK_EXPRESSION`, `PACK_IMAGE_MAP`, `PACK_STRUCTURE`) are +plain text in the JSON either way: packs name their biomes, regions and objects by path without a namespace, such as +`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. ### 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. - **`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. -- **`ReadOnlyMantle.host()`** hands a host's own extension back the mantle behind a chunk stage's read-only view. A chunk stage may not - write the mantle, but Iris's cave stage stamps markers into the matter that the platform reads, through a built-in facade, so the - facade has to reach past the view. Not for pack modules: writing through it breaks the promise the view makes. +- **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 + 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 + 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 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. @@ -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 folders are reserved with `ModuleHost.reservingFolders`. Either conflict fails the pack load in `ModuleRegistry`, 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 - `find(new ResourceKey<>(id, Keep.class))` needs no kind id. The class must be concrete; like settings it needs a - no-argument constructor, checked when the pack's description is built. +- **Lookup.** `PackResources.find(KEEPS, id)` and `ids(KEEPS)` take the kind itself, the constant the module registered, and + return its type. The host's own kinds are constants of `PackResources` (`BIOMES`, `REGIONS`, `OBJECTS`), so one call + 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 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 @@ -958,10 +963,10 @@ the resources it serves itself. - **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 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 - namespace, so only `String` fits, like the pack references of `@Ref`. A class that backs no kind of the pack - fails the load. + namespace in the JSON, like the pack references of `@Ref`; the field may be a `String` or a `ResourceId`, which the + host reads as the pack's id of the key. A class that backs no kind of the pack fails the load. ## Validators @@ -1044,9 +1049,10 @@ gives each module a `ModuleLog` instead. 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 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 - view shares the state store, and the graph 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 + agree: the runners hand a stage a view of the world whose log is its module's (built by the reference host around the + host's world, so a host implements no method for it; the view shares the state store and the extensions, and the graph + 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 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 @@ -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). `AmbientEffects` follows the same rule: the module decides which effects are due (interval and chance, kept in the world's state) and every random value they carry, the host only plays them. -- **Services now.** `ObjectsAt` (`ALL`): pack object keys 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 - 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 - platform structures the module starts or stands in for, and keys it places but cannot search for), and the +- **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`, by id; 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 structures it places but cannot search for), and the 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, `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) @@ -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. 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). -3. **Narrow facades for the host's own built-ins**, in that same exposed package: interfaces the host's worlds - implement, for what only the host's own features need from its internals, such as Iris's per-feature world seeds - (`IrisSeed`), which existing worlds depend on. A pack module never needs one. Every such type is a promise the host - keeps, so there are few, each answers one question, and none hands out an engine. +3. **Narrow facades for the host's own built-ins**, in that same exposed package, for what only the host's own + features need from its internals, such as Iris's per-feature world seeds (`IrisSeeds`), which existing worlds depend + on. A pack module never needs one. Every such type is a promise the host keeps, so there are few, each answers one + 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 values and its settings through `FeatureSettings`. Iris's mapping from its internals to this surface, with the diff --git a/README.md b/README.md index c70189b64..8fb1b1210 100644 --- a/README.md +++ b/README.md @@ -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. `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 -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 -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 +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 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. ```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 -Keep keep = resources.require(KEEPS.key(resources.idOf("towers/north"))); -List all = resources.ids(Keep.class); // every keep of the pack, in id order +Keep keep = resources.require(KEEPS, resources.idOf("towers/north")); +List 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 @@ -221,15 +223,16 @@ List all = resources.ids(Keep.class); // every keep of the pack, in field names. - 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. -- 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, naming both owners. - 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 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 - option that names a resource of a kind carries `@ResourceRef(Keep.class)` on a `String`, or a list, set or - array of them, and studio completes the kind's keys. Built-in kinds may read into a class the host describes + option that names a resource of a kind carries `@ResourceRef(Keep.class)` on a `String` or `ResourceId`, or a + 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. ``` @@ -244,8 +247,8 @@ problems with its own. ```java registry.registerValidator(pack -> { - for (ResourceId id : pack.resources().ids(Keep.class)) { - Keep keep = pack.resources().require(KEEPS.key(id)); + for (ResourceId id : pack.resources().ids(KEEPS)) { + Keep keep = pack.resources().require(KEEPS, id); if (keep.towers() > 8) { 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 { - public Set objectsAt(PackWorld world, int chunkX, int chunkZ) { - return planted(world).contains(chunkX, chunkZ) ? Set.of("ruins/arch") : Set.of(); + public Set objectsAt(PackWorld world, int chunkX, int chunkZ) { + 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; } } @@ -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. - 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. +- 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 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 @@ -370,7 +375,7 @@ final class RuinsObjects implements ObjectsAt { | 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. | -| `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. | | `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. | @@ -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 `snippet/example/flora/patch/`. A pack module's snippet names start with its module id as a folder 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, 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 @@ -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), `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. - 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. -- `@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 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 @@ -855,11 +861,17 @@ Optional clock = pack.catalog().service(Clock.class); // a Pro ## Values that stay -- `ResourceId` requires a namespace. `ResourceKey` 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. - It serves pack objects (`GeneratedObject`), biomes (`PackBiome`), regions (`PackRegion`) and every module - resource kind; the requested type selects the kind, so `BiomeSample` ids look up directly. `ids(type)` lists - a kind. + It serves pack objects (`OBJECTS`, `GeneratedObject`), biomes (`BIOMES`, `PackBiome`), regions (`REGIONS`, + `PackRegion`) and every module resource kind: `find(kind, id)` (empty when absent), `require(kind, id)` and + `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 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 @@ -870,7 +882,8 @@ Optional clock = pack.catalog().service(Clock.class); // a Pro - `Hunk` is a dense local volume; `ArrayHunk` is the bounds-checked reference. - The `mantle` package keeps namespaced typed layers, codecs, lifetimes and buffered edits. - `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 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 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 -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. diff --git a/src/main/java/com/volmit/config/LinkedBiomes.java b/src/main/java/com/volmit/config/LinkedBiomes.java index 5a08f7a09..180665e7b 100644 --- a/src/main/java/com/volmit/config/LinkedBiomes.java +++ b/src/main/java/com/volmit/config/LinkedBiomes.java @@ -1,6 +1,8 @@ package com.volmit.config; import com.volmit.IrisFeature; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import java.util.Collection; 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 * 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 - * settings like any other. Keys are pack biome keys as packs write them; blank keys and keys naming no biome are - * ignored. + * settings like any other. Biomes are named by their ids, {@link PackResources#idOf} of the keys the settings hold; ids + * naming no biome of the pack are ignored. */ 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 * 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 treeBiomes() { + default Set treeBiomes(PackResources pack) { 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 * 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 * declares, such as a band of its caves */ - default Set usedBiomes(Collection dimension) { + default Set usedBiomes(PackResources pack, Collection dimension) { return Set.of(); } } diff --git a/src/main/java/com/volmit/config/PackSettings.java b/src/main/java/com/volmit/config/PackSettings.java index 8a4859030..313add7dc 100644 --- a/src/main/java/com/volmit/config/PackSettings.java +++ b/src/main/java/com/volmit/config/PackSettings.java @@ -1,6 +1,7 @@ package com.volmit.config; 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 * 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. */ SettingsStack declared(Class 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 Optional extension(Class type) { + return Optional.empty(); + } } diff --git a/src/main/java/com/volmit/entity/EntitySpec.java b/src/main/java/com/volmit/entity/EntitySpec.java index 5eb6a06a1..66bb11c8a 100644 --- a/src/main/java/com/volmit/entity/EntitySpec.java +++ b/src/main/java/com/volmit/entity/EntitySpec.java @@ -2,51 +2,58 @@ package com.volmit.entity; import com.volmit.item.ItemAttribute; import com.volmit.item.ItemDrop; +import com.volmit.resource.ResourceId; import java.util.List; 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 * 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 specialType a mob of another plugin, written {@code PluginName:MobName}, or empty - * @param reason the platform's spawn reason by name, or null for a natural spawn - * @param customName the name shown above the entity, empty for none + * @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; empty for a natural spawn + * @param customName the name shown above the entity; empty for none * @param flags the settings that every entity kind understands * @param equipment what the entity wears and holds * @param passengers entities that ride this one * @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 leashHolder the entity that holds this one on a leash, or null - * @param spawnEffect an effect to show when the entity appears, 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; empty for none * @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 pandaHiddenGene for pandas the hidden 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; empty to leave it to the platform * @param applySettingsToSpecial whether the settings also apply to a mob of another plugin * @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, - List passengers, List attributes, List lootTables, - long lootShuffleSeed, EntitySpec leashHolder, SpawnEffect spawnEffect, boolean riseOutOfGround, - String pandaMainGene, String pandaHiddenGene, boolean applySettingsToSpecial, - List commands) { +public record EntitySpec(Optional type, Optional specialType, Optional reason, Optional customName, + Flags flags, Equipment equipment, List passengers, List attributes, + List lootTables, long lootShuffleSeed, Optional leashHolder, + Optional spawnEffect, boolean riseOutOfGround, Optional pandaMainGene, + Optional pandaHiddenGene, boolean applySettingsToSpecial, List commands) { public EntitySpec { Objects.requireNonNull(type, "type"); Objects.requireNonNull(specialType, "specialType"); + Objects.requireNonNull(reason, "reason"); Objects.requireNonNull(customName, "customName"); Objects.requireNonNull(flags, "flags"); Objects.requireNonNull(equipment, "equipment"); passengers = List.copyOf(passengers); attributes = List.copyOf(attributes); lootTables = List.copyOf(lootTables); + Objects.requireNonNull(leashHolder, "leashHolder"); + Objects.requireNonNull(spawnEffect, "spawnEffect"); + Objects.requireNonNull(pandaMainGene, "pandaMainGene"); + Objects.requireNonNull(pandaHiddenGene, "pandaHiddenGene"); commands = List.copyOf(commands); } /** Whether the entity is a mob of another plugin. */ 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. */ @@ -55,19 +62,36 @@ public record EntitySpec(String type, String specialType, String reason, String boolean keepEntity, boolean baby) { } - /** The items an entity wears and holds; null for an empty slot. */ - public record Equipment(ItemDrop helmet, ItemDrop chestplate, ItemDrop leggings, ItemDrop boots, ItemDrop mainHand, - ItemDrop offHand) { - public static final Equipment NONE = new Equipment(null, null, null, null, null, null); + /** The items an entity wears and holds; empty for an empty slot. */ + public record Equipment(Optional helmet, Optional chestplate, Optional leggings, + Optional boots, Optional mainHand, Optional offHand) { + 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 * 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, - String particle, int particleOffset, int particleCount, double altX, double altY, + public record SpawnEffect(Optional sound, int soundDistance, double minPitch, double maxPitch, double volume, + Optional particle, int particleOffset, int particleCount, double altX, double altY, double altZ, boolean randomAltX, boolean randomAltY, boolean randomAltZ, double extra) { + public SpawnEffect { + Objects.requireNonNull(sound, "sound"); + Objects.requireNonNull(particle, "particle"); + } } /** diff --git a/src/main/java/com/volmit/generation/GenerationContext.java b/src/main/java/com/volmit/generation/GenerationContext.java index 61ba3f125..9ce1d8a87 100644 --- a/src/main/java/com/volmit/generation/GenerationContext.java +++ b/src/main/java/com/volmit/generation/GenerationContext.java @@ -21,10 +21,12 @@ public interface GenerationContext extends ChunkContext { @Override TerrainSampler terrain(); - /** Non-null mantle access scoped to this invocation; the host owns its lifetime. Chunk stages read it - * only: the mantle pipeline has finished around the chunk, and writes throw. Like {@link #terrain()} it covers the - * chunk and the 16 blocks around it, so a stage that places something against a neighbor can see what the mantle - * holds there. + /** Non-null mantle access scoped to this invocation; the host owns its lifetime. Like {@link #terrain()} it covers + * the 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 + * 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(); diff --git a/src/main/java/com/volmit/generation/InvocationContext.java b/src/main/java/com/volmit/generation/InvocationContext.java index c168a049c..45b934c41 100644 --- a/src/main/java/com/volmit/generation/InvocationContext.java +++ b/src/main/java/com/volmit/generation/InvocationContext.java @@ -2,6 +2,7 @@ package com.volmit.generation; import com.volmit.ModuleLog; import com.volmit.world.PackWorld; +import java.util.Optional; /** Host-owned invocation inputs. Views must not be retained or used by detached tasks. * @@ -19,4 +20,14 @@ public interface InvocationContext { default ModuleLog 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 Optional extension(Class type) { + return Optional.empty(); + } } diff --git a/src/main/java/com/volmit/host/ChunkInvocation.java b/src/main/java/com/volmit/host/ChunkInvocation.java index 1ae3a48e3..8dc12079f 100644 --- a/src/main/java/com/volmit/host/ChunkInvocation.java +++ b/src/main/java/com/volmit/host/ChunkInvocation.java @@ -12,8 +12,9 @@ import com.volmit.stage.ChunkStageContext; import com.volmit.stage.Stage; import com.volmit.world.TerrainSampler; 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 { private final StageInvocation stages; private final GenerationContext inputs; @@ -59,7 +60,7 @@ final class ChunkInvocation implements ChunkStageContext { @Override public Mantle mantle() { - return new ReadOnlyMantle(inputs.mantle()); + return new ChunkMantle(inputs.mantle(), inputs.originX(), inputs.originZ()); } @Override @@ -72,6 +73,11 @@ final class ChunkInvocation implements ChunkStageContext { return stages.world(inputs.world()); } + @Override + public Optional extension(Class type) { + return inputs.extension(type); + } + @Override public WorldRandom random() { return stages.random(); diff --git a/src/main/java/com/volmit/host/ChunkMantle.java b/src/main/java/com/volmit/host/ChunkMantle.java new file mode 100644 index 000000000..2fd74f30b --- /dev/null +++ b/src/main/java/com/volmit/host/ChunkMantle.java @@ -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 MantleLayer layer(MantleKey key) { + return new OwnChunkLayer<>(mantle.layer(key)); + } + + @Override + public MantleLayer 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 implements MantleLayer { + private final MantleLayer layer; + + OwnChunkLayer(MantleLayer 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 visitor) { + layer.visit(area, visitor); + } + + @Override + public void clear(BlockBox area) { + requireOwnChunk(area); + layer.clear(area); + } + } + + private record ReadOnlyLayer(MantleLayer layer) implements MantleLayer { + @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 visitor) { + layer.visit(area, visitor); + } + + @Override + public void clear(BlockBox area) { + throw new UnsupportedOperationException(HOST_BLOCKS); + } + } +} diff --git a/src/main/java/com/volmit/host/ChunkRunner.java b/src/main/java/com/volmit/host/ChunkRunner.java index 39515c244..07ebde22b 100644 --- a/src/main/java/com/volmit/host/ChunkRunner.java +++ b/src/main/java/com/volmit/host/ChunkRunner.java @@ -6,7 +6,7 @@ import java.util.Objects; /** 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 - * 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 { private final ResolvedGraph graph; diff --git a/src/main/java/com/volmit/config/DeclaredFieldOrder.java b/src/main/java/com/volmit/host/DeclaredFieldOrder.java similarity index 98% rename from src/main/java/com/volmit/config/DeclaredFieldOrder.java rename to src/main/java/com/volmit/host/DeclaredFieldOrder.java index f9b34bbf9..8e94573b3 100644 --- a/src/main/java/com/volmit/config/DeclaredFieldOrder.java +++ b/src/main/java/com/volmit/host/DeclaredFieldOrder.java @@ -1,4 +1,4 @@ -package com.volmit.config; +package com.volmit.host; import java.io.IOException; import java.io.InputStream; diff --git a/src/main/java/com/volmit/host/FeatureDescriptor.java b/src/main/java/com/volmit/host/FeatureDescriptor.java index c80a6ce9c..7bf42df01 100644 --- a/src/main/java/com/volmit/host/FeatureDescriptor.java +++ b/src/main/java/com/volmit/host/FeatureDescriptor.java @@ -3,7 +3,6 @@ package com.volmit.host; import com.volmit.IrisFeature; import com.volmit.config.Feature; import com.volmit.config.Level; -import com.volmit.config.OptionsMetadata; import com.volmit.resource.ResourceId; import java.lang.annotation.IncompleteAnnotationException; import java.lang.reflect.Modifier; diff --git a/src/main/java/com/volmit/host/LifecycleRegistration.java b/src/main/java/com/volmit/host/LifecycleRegistration.java index c3bbc7961..ea8aca8f6 100644 --- a/src/main/java/com/volmit/host/LifecycleRegistration.java +++ b/src/main/java/com/volmit/host/LifecycleRegistration.java @@ -19,7 +19,7 @@ public record LifecycleRegistration(ModuleLifecycle lifecycle, DiscoveredModule * module's own. */ 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. */ diff --git a/src/main/java/com/volmit/host/MantleInvocation.java b/src/main/java/com/volmit/host/MantleInvocation.java index e67c20056..5703159ec 100644 --- a/src/main/java/com/volmit/host/MantleInvocation.java +++ b/src/main/java/com/volmit/host/MantleInvocation.java @@ -11,6 +11,7 @@ import com.volmit.stage.MantleStageContext; import com.volmit.stage.Stage; import com.volmit.world.TerrainSampler; import java.util.Objects; +import java.util.Optional; /** The context every stage of one mantle invocation receives. */ final class MantleInvocation implements MantleStageContext { @@ -66,6 +67,11 @@ final class MantleInvocation implements MantleStageContext { return stages.world(inputs.world()); } + @Override + public Optional extension(Class type) { + return inputs.extension(type); + } + @Override public WorldRandom random() { return stages.random(); diff --git a/src/main/java/com/volmit/host/ModuleWorld.java b/src/main/java/com/volmit/host/ModuleWorld.java new file mode 100644 index 000000000..0fcc4141f --- /dev/null +++ b/src/main/java/com/volmit/host/ModuleWorld.java @@ -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 state(Class type, Function create) { + Objects.requireNonNull(create, "create"); + return world.state(type, ignored -> create.apply(this)); + } + + @Override + public Optional extension(Class type) { + return world.extension(type); + } + + @Override + public ModuleLog log() { + return log; + } + + @Override + public String toString() { + return world + " as " + log; + } +} diff --git a/src/main/java/com/volmit/config/OptionsMetadata.java b/src/main/java/com/volmit/host/OptionsMetadata.java similarity index 89% rename from src/main/java/com/volmit/config/OptionsMetadata.java rename to src/main/java/com/volmit/host/OptionsMetadata.java index 7ead1b260..eeddb16fe 100644 --- a/src/main/java/com/volmit/config/OptionsMetadata.java +++ b/src/main/java/com/volmit/host/OptionsMetadata.java @@ -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.Modifier; import java.lang.reflect.Type; @@ -7,7 +16,9 @@ import java.util.ArrayList; import java.util.HashSet; 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