diff --git a/api/.gitignore b/api/.gitignore new file mode 100644 index 000000000..c346668cb --- /dev/null +++ b/api/.gitignore @@ -0,0 +1,5 @@ +.gradle/ +build/ +.idea/ +*.iml +__pycache__/ diff --git a/api/CONTRACTS.md b/api/CONTRACTS.md new file mode 100644 index 000000000..9b36ee862 --- /dev/null +++ b/api/CONTRACTS.md @@ -0,0 +1,331 @@ +# Contracts + +[DESIGN.md](DESIGN.md) is the authoritative description. This file maps requirements to the +types that carry them and lists what the Iris adapter still owes. + +## Adopted seams + +| Requirement | Contract | +| --- | --- | +| Module identity and composition | `IrisModule`, `ModuleInfo`, `StageGraph` | +| Loading and unloading a pack | host `LoadedPack`, `ModuleHost` | +| Module jars in a pack | `META-INF/services/com.volmit.IrisModule`, host `PackModules` (jar copies), `DiscoveredModule`, `MissingClasses` | +| Platform tooling parts of a jar | manifest `Iris-Tooling-Parts`, host `ToolingPart`, `ToolingPlatform`, `PlatformApi`, `ModuleHost.runningOn`, `ToolingPartLoader`, `ModuleJarCheck --platform` | +| Namespace ownership | module-prefixed stage, feature and mantle ids, `ModuleInfo.ownsStage`/`ownsId`; no reserved namespaces | +| Randomness independent of other modules | `StageContext.random()`, host `StageStreams`, invocation seed passed to the runners | +| Random values identical on every JDK | `WorldRandom`, pinned by `WorldRandomTest` | +| Module entry point | `IrisModule.info()`, `IrisModule.setup(ModuleSetup)` (`stages()`, `registry()`, `log()`), host `ModuleSetups.run` | +| Module-owned work and ordering | `Stage`, `StageRef`, one stage definition type per pipeline, `requires`/`softAfter`/`softBefore` | +| Activation by configuration | `when(settingsType)`, `StageContext.configured(settingsType)`, host `ConfiguredSettings` (entries per declared `@Feature` type; any column of a chunk) | +| Stacked settings levels, read per column | `Level`, `FeatureSettings.at(type, x, z)` and `declaredInChunk(type, chunkX, chunkZ)`, `SettingsStack` (`values`, `dimension`, `level`, `mostSpecific`), `FeatureSettings.Entry` (level, source, value) | +| Chunk coordinates in stages | `ChunkContext` (`chunkX`, `chunkZ`, `centreX`, `centreZ`, `area`), shared by `GenerationContext` and `MantleGenerationContext` | +| Typed results between modules | stage outputs, `StageContext.output` | +| Per-block work with single-pass cost | `BlockStage`, fused block passes | +| Pack-load validation and diagnostics | host `StageGraphBuilder`, `ResolvedGraph`, `LoadedModules` | +| Reference execution | host `PlacementRunner` (returns the API `PlacementOutcome`), `ChunkRunner`, `MantleRunner`, each timed through host `StageTimings` | +| 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) | +| Module state that survives a restart | `RunningWorld.saved(SavedKey)`, `FeatureRegistry.registerSaved`, `SavedKey` (`ResourceId` id, type, `StorageCodec`, `initial`), `com.volmit.data.StorageCodec` (also the codec of mantle layers) | +| 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` (with `resources()`, for a reach that depends on the size of the pack's objects), host `StageReach`, `ResolvedStage.reachBlocks`, `PipelineReach` | +| Settings described for studio | `@Desc`, `@Required`, `@MinNumber`, `@MaxNumber`, `@MinItems`, `@Snippet`, `@Ref`/`Reference`, `@ResourceRef`, `FeatureRegistry.registerSettings`, host `LoadedPack.schema()` (`PackSchema`, `FeatureSchema`, `ObjectType`, `SchemaOption`, `ValueKind` with `HostKind`), `ModuleHost.describingHostTypesIn` | +| Geometry and mantle registration | `FeatureRegistry`, host `ModuleRegistry`, `FeatureCatalog` | +| Block states and palettes | `BlockState`, `BlockRegistry` (`resolve(BlockSpec)`, `find(key)`, `blockEntity`, `hasTrait`, `oreFor`, `rotate(state, BlockTurn)`, `merge`, `withPropertyIfAccepted`, `matches`), `BlockTurn`, `BlockTrait` (with `STORAGE`), `BlockSpec`, `PaletteSpec` and `PaletteSampler` (`BlockRegistry.palette`) | +| A pack's objects | `PlaceableObject` (`name`, size, `center`, `geometry`), `PackObjects` (`object`, `sizeOf`, `scaled` with `ScaleMethod`, `smartBored`, `build`), `PackResources.objects()` | +| Placing through the pack's placement graph | `Placements.place(PlacementRun)` (`PackWorld.placements()`), `PlacementRun` (request, name, settings JSON, area, terrain, input, seed), `PlacementTerrain` (`recordPlacement` / `placementAt` with a `PlacementRecord`), `StructureVolumes`, `PlacedMarker`, `PlacementOutcome`; stages read `PlacementContext.placementTerrain()` and `input(type)`; mantle stages get a terrain from `MantleGenerationContext.placementTerrain()`; `RunningWorld.placementAt` reads what a placement recorded; `FeatureRegistry.registerPlacementType` names the type packs write placements as (host `FeatureCatalog.placementType()`, `PackSchema.placementType()`) | +| Noise from pack-described styles | `NoiseStyle`, `StyledRange`, `PackResources.noise()`, `NoiseFactory`, `NoiseSampler` | +| Values in settings | `BlockSpec`, `PaletteSpec`, `NoiseStyle`, `StyledRange`, `Range`, `BlockPosition`, `JigsawOverrides`, `Object` as `ValueKind.AnyKind` | +| Decisions over and fit of the platform's own structures | service `VanillaStructures` (`rule`, `starts`, `shift`, `reach`, `beforePieces`, `afterPieces`, `setup`), `VanillaStructureRule`, `VanillaStructureContext`, `VanillaStructureStart`, `VanillaStructureStartContext`, `VanillaStructureSetup`, `PlatformStart`, `StartMemo`, `StartReach`, `StructureFit` (`Start`, `Piece`, `ColumnVisitor`), `DecorationStep`, `TerrainAdaptation`, `PieceKind`, `TemplateCells`, `world.BlockAccess`, host `FeatureCatalog.registrations(service)` | +| Pack-scoped resolution | `ResourceId` (`ofPackKey`, `ofPlatformKey`), `ContentKey`, `PackResources` (`find(kind, id)`, `require`, `ids(kind)`, `idOf`; kinds `BIOMES`, `REGIONS`, `OBJECTS`, `EXPRESSIONS`, `IMAGE_MAPS`), `PackBiome`, `PackRegion`, `PackExpression`, `PackImageMap` | +| Module-owned pack resources | `ResourceKind`, `FeatureRegistry.registerResourceKind`, `@ResourceRef`, host `ModuleHost.reservingFolders`, `FeatureCatalog.resourceKinds()`, `ResourceKindSchema`, `ValueKind.ResourceReferenceKind` | +| Module-owned pack checks | `Validator`, `ValidationContext`, `Problem`, `Severity`, `Subject`, `FeatureRegistry.registerValidator`, host `FeatureCatalog.validators()` | +| Per-world module state | `PackWorld` (`state`), `InvocationContext.world()`, host `WorldStates` | +| Module lifecycle across loads, hotloads and reloads | `ModuleLifecycle`, `PackContext`, `FeatureRegistry.registerLifecycle`, host `FeatureCatalog.lifecycles()`, `LifecycleRunner` | +| Host questions answered by modules | `@Service`, `Providers`, `FeatureRegistry.registerService`, host `FeatureCatalog.services(type)` / `service(type)`; services `ObjectsAt`, `StructureLocator` (`LocateResult`, `startedStructures`, `locatableStarts`, `locateStart`, `ChunkFilter`), `SaplingGrowth`, `Loot` (with `shuffleSeed`), `BlockDrops`, `EntitySpawns`, `CaveBiomes`, `ProtectedFloor`, `AmbientEffects`, `VanillaFeatures` (`DecorationStep`); values `ItemDrop`, `EntitySpec`, `ItemRegistry` (`PackResources.items()`) | +| Terrain and settings sampling | `TerrainSampler`, `BiomeSample`, `TerrainSample`, `FeatureSettings` | +| Dense chunk output | `Hunk`, `GenerationContext.blocks`, reference `ArrayHunk` | +| Positions, boxes and faces | `com.volmit.geometry`: `BlockPosition`, `BlockBox`, `BlockFace` | +| Sparse geometry | `GeneratedObject` | +| Studio views of what a module builds | `com.volmit.tooling`: `ModuleSetup.tooling()` (`ToolingRegistry.registerView`), sealed `StudioView` (`SceneView` with `SceneEntry`, `PatternView` with `PatternEntry`, `PatternArea`, `BlockPattern`), `EditableSceneView` (`SceneFile`, `NodeGraph`, `GraphNode` with `Link`, `NodeSettings`, `Edits`, `Addition`), `JsonText`, `JsonPath` (`Key`, `Index`), host `StudioViewRegistration` | +| Commands of a module | `com.volmit.tooling`: `ToolingRegistry.registerCommand`, immutable `Command` (`named`, `alias`, `describe`, `child`, `argument`, `runs`, `openToEveryone`), typed `Argument` (`word`, `text`, `integer`, `decimal`, `flag`, `choice`, `resource`, `registered`, `orElse`, `suggesting`), `CommandAction`, `CommandContext` (`get`, `sender`, `pack`, `world`, `platform`), plain-text `Sender`, `ToolPack` (`edit` with `PackEdit`, `outputFolder`, `objects` with `ObjectCodec`), host `CommandRegistration` in `FeatureCatalog.commands()` | +| Buffered placement writes | `PlacementRequest`, `PlacementAccess`, host-owned `PlacementEdit` | +| Typed generation and persistent storage | `mantle` package | + +Stage bodies hold no invocation state. Everything per placement or chunk travels through the +context, outputs and accumulators. Each stage draws only from its own stream, derived from the +invocation seed and its id, so other modules never change its draws. Every value a stream produces is +defined by IrisApi (`WorldRandom`), not by the JDK, so a JDK update never changes a world. + +A module owns its id (`ns:name`, no `/`) and the ids below it (`ns:name/...`). Its stage ids are +below it; feature ids, mantle keys and resource kind ids it registers are its id or below it; a settings type in +`when(...)` is owned in that sense by a module that names it. Pack modules cannot use the +namespaces the host reserves. + +A pack load works on copies of the module jars, so the originals are never held open. + +Modules describe their settings only through their settings classes; jars ship no schema files. The +pack load turns every catalogued settings type into a `PackSchema` and fails, naming field, settings +and module, on a field type it cannot describe, a `@Ref` or `@ResourceRef` on a field that is not text, both on +one field, a class without +a working no-argument constructor (a `@JsonForms` class needs none: it is described as any JSON value), a bad or repeated snippet name, or a pack class's snippet name +outside its module's folder. Defaults come from an instance made by that constructor. Options are in +declaration order. + +Packs write settings under the short key the feature declares, as the settings object, or as the value of the +one option its `root` names; there is no second form. A key is unique per target across modules and the host's own +JSON fields. The description is in a fixed order and holds module entries only. + +Modules compile against the API (`com.volmit:iris-api`) `compileOnly` and never ship it. At runtime they can use the +API (`com.volmit.*` except the host side `com.volmit.host`, artifact `com.volmit:iris-host`), the host packages the host chooses to expose, the JDK and the classes in their +own pack's jars. A host may expose libraries it shares with modules (Iris exposes VolmLib and Gson); any other +library a module ships in the pack, never borrowing the host's copy. JDK modules +outside the platform class loader, such as `jdk.compiler`, are not available, and neither are JDK +packages not exported to unnamed modules, such as `jdk.internal.misc`, unless the server is started +with `--add-exports /=ALL-UNNAMED`. `sun.misc.Unsafe` from `jdk.unsupported` is the +supported way for modules to use Unsafe. A class Iris has but hides, a class of an unavailable JDK +module or non-exported JDK package, or one missing from an exposed package fails the pack load, +naming the jar and the classes. A class nobody has (an optional dependency) only warns, unless +its package is one the jar's manifest declares optional (`Iris-Optional-Packages`, read by the host's +`ModuleJar`). That declaration never excuses a load error. + +A jar can carry tooling for one platform, such as Bukkit, as a part named in its manifest (`Iris-Tooling-Parts: += ...`): the entry class's package and subpackages. Parts are not generation code. Generation code +that uses a part class fails the pack load ("Generation code cannot use the bukkit part; move the call into the part"). +A host that runs on a platform (`ModuleHost.runningOn`) checks that platform's parts at pack load: they may use their own +packages, the platform's api and what modules can use, and not Iris internals, the server's own classes +(`net.minecraft`, `org.bukkit.craftbukkit`, `com.mojang`), `com.volmit.host` or another part. Other platforms' parts are +skipped unread. The host opens a part through its own class loader (`ToolingPartLoader`, a child of the pack's), which +the adapter creates and closes; the generation loader never sees `com.volmit.tooling.`. Enabling a part, +and what it mounts, is the adapter's. `ModuleJarCheck --platform=:` makes a build check the parts. + +Stage bodies and service providers keep no state; what a module keeps for a world lives in that world's state store, +created once per type and world. A world's state lives while the world runs with one pack snapshot: a hotload or a +reload of the pack's resources starts the world again with empty state; what must outlive that is a +`RunningWorld.saved` value, which the host reads on first use, writes when it saves the world and when the world stops, +and replaces by its `initial` when the codec rejects the stored payload. A service names how its providers combine +(`ALL`, `FIRST`, `ONE`); a second provider of a `ONE` service fails the pack load, naming both modules. Services +return values and never act on the platform. + +A resource kind reads one folder directly below the pack root, with a class no other kind uses; a folder two +kinds claim, or one the host reads itself, fails the pack load naming both owners. Resources of a kind are +values, read once per pack snapshot. Validators only report: an `ERROR` blocks the pack, a `WARNING` is shown. + +IrisApi's value types are values: the host decodes them like settings, and nothing changes them afterwards. +Noise belongs to the host; modules describe it and get samplers built from the description. A +`VanillaStructures` rule answers per structure and world, never per position. + +There is no API version gating. Packs ship their module jars, so their compatibility with the +running Iris is the pack publisher's responsibility. + +## Requirements for the Iris adapter + +- Port the engine as ordinary modules. Keep `iris:*` stage ids stable once packs or addons + depend on them, because soft references and diagnostics use them. +- Answer `FeatureSettings.at(type, x, z)` with one entry per level that declares the type at that + column: the dimension, the column's region, its surface biome and, in a placement, the placement, in + that order. Never merge or override levels. Pass each placement's own declarations as + `ConfiguredSettings.placement(...)`; the chunk and mantle runners collect a chunk's settings + themselves. +- Name the packages of the classes Iris describes itself with `ModuleHost.describingHostTypesIn(...)`, + decode them as Iris does, and render each `HostKind` with Iris's own description of the class. These are + deprecated for removal: transitional, until the cut-over. +- 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()` (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. +- Preserve pack field names and defaults, seed derivation, RNG draw order, coordinate + conventions and iteration order where existing worlds must not change. Per-stage streams do not + reproduce Iris's current shared draws; matching them where worlds must stay the same is adapter + work inside the ported stages. +- Derive one seed per placement (world seed and the placement's stable identity) and per chunk + (world seed and chunk position) and pass it to `PlacementRunner.place` / `ChunkRunner.generate`. +- Pass every runner a `StageTimings` that records into the host's metrics (or `StageTimings.NONE`), so + placement, mantle and chunk stages are all timed by the host rather than by the modules. +- Prepare the area a placement may read or write, including neighbors: the placement pipeline's + `reach()` around the placed object's bounds, each mantle layer by its own maximum. Never clip. +- Work out each mantle stage's reach once per pack load (`ResolvedStage.reachBlocks(PackSettings)`), + answering `PackSettings.declared(type)` with every entry of the dimension and of the regions and + biomes it can reach. +- 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` 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.carved()` in every invocation, keeping the voids in the host's own form: a mantle stage's view writes them, a chunk + stage's view only reads them (its writes throw UnsupportedOperationException), and a dimension that keeps no mantle holds none. Answer + `carved().get(x, y, z)` (null where it holds none) 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. +- Answer `TerrainSampler.biomeHeight(biome, x, z, seed)` (the height above the bottom the biome's terrain generators give the + column when shaped with `seed`) and `skyBiome(biome, x, z)` (the platform biome the biome shows as in the sky; empty when it + names none) for any biome of the pack, throwing IllegalArgumentException for one it does not have. Store + `Mantle.setPlatformBiome(x, y, z, biome)` where the biome pass that writes the chunk's biomes reads it; a chunk stage's + mantle accepts it inside the chunk's own columns only, and a placement's mantle or an edit may refuse it. +- Answer `TerrainSampler.fluidHeight()` (the height the host fills with fluid below) and `upperDimensionY(x, z)` (where a + dimension stacked above begins; empty when none does). `surfaceY(x, z)` equals `column(x, z).surfaceY()`; a host + overrides it when the height costs less than the whole column. `surfaceHeight(x, z)` must equal + `(int) Math.round(surfaceY(x, z))`. +- Answer `FeatureSettings.at` in level order with no allocation a column read can avoid, and `declaredInChunk` with + exactly the distinct entries (by level and source) of the chunk's 16 by 16 columns, in the order the default gives: + level order, then the order the first column holding an entry was found, columns by X and then Z. Answer it from the + regions and biomes the chunk holds where the host knows them. +- Make placement edits atomic across blocks, block entities, markers and mantle in generation + storage. Abort chunk publication when any stage fails. +- Preserve unknown persisted mantle layers or fail explicitly. +- Build one `ModuleHost` at startup with the built-in modules, exposed packages, reserved JSON + fields. Its methods accumulate, so the configuration can be + built in steps. Load each pack with `LoadedPack.load(packRoot, host)` + and close it only after nothing built from it is in use. Catch `ModuleLoadException`, the one type of every load + error, not `RuntimeException`. +- Depend on both `com.volmit:iris-api` and `com.volmit:iris-host` and ship both; expose neither the host side nor + anything below it to packs (the loader refuses to). +- Implement both `PlacementEdit.set` overloads; buffer a plain block (`set(x, y, z, state)`) without building a + `PlacedBlock` for it. +- Pass a `System.Logger` that writes to the server log to `ModuleHost.loggingTo(...)`, so the + per-pack module summary and missing-classes warning are visible, and a cache directory of the host + to `ModuleHost.copyingJarsTo(...)` for the jar copies. +- Provide the API at runtime from the plugin's class loader, for example by shading it into the + Iris plugin jar. Pack jars must not ship it. +- Pass the packages of built-in modules whose stages packs may require, and of libraries the host shares with + modules, to `ModuleHost.exposing(...)`. They must be on the loader that defines the + API. Keep them narrow: everything in an exposed package and its subpackages becomes visible to + packs and is part of what packs can break on. Stage output types and settings types that pack + code uses through those stages must be in exposed packages too. The API is always exposed. +- Consider showing `PackModules.missingClasses()` in studio. +- Pass the host's own JSON fields per target to `ModuleHost.reservingFields(...)`, so a settings key can never + shadow one; a clash refuses the pack load. +- Decode module settings under the declared key, as a JSON object (or a snippet reference for a `@Snippet` type), or, + for a feature with a `root`, as exactly that option's value. Render one shape for each. +- Render `pack.schema()` into studio's files: merge each target's `fields(target)` into the schema + of the matching Iris file type (dimension, region, biome, object placement) under the key, write `types()` as definitions, a `/snippet/` schema per entry of `snippets()`, and + completion lists per `Reference` from the server registries and the pack's biome, region and + object folders. `PACK_*` references are pack paths without a namespace, as Iris writes them. Pack + snippet names are under their module's folder, so they cannot collide with Iris's own; built-in + names are Iris's to keep distinct. +- Refuse to open a pack in studio when its load fails, showing the error, rather than writing a + schema without the modules. +- Load the pack again and rebuild the schema files after a module jar in `/modules` changes. +- Create settings with their no-argument constructor and decode JSON into that instance, so an + omitted field keeps the default studio shows. +- Read every module resource kind (`catalog().resourceKinds()`) from `//**/*.json` the way settings + are decoded, keyed by path without `.json`, id `:`, and serve it through + `PackResources.find` by type and `PackResources.ids`. Read each resource once per pack snapshot, fail `find` for a + file that does not read, and read the files again on every reload. +- Reserve the folders the host reads itself with `ModuleHost.reservingFolders(...)`. +- Write a studio schema per kind for the files below its folder (the host's own description for a `HostKind`), and + complete `ResourceReferenceKind` options, and the host's own references to a kind's class, with the kind's keys. +- Run every validator (`catalog().validators()`) wherever the host validates packs, after its own checks: an + `ERROR` blocks the pack, a `WARNING` is shown; show each problem with its subject. A validator that throws is an + error naming its module, and the others still run. + +- Keep one `PackWorld` per world and pack snapshot and pass it to every invocation of the world + (`InvocationContext.world()`), to service calls and to hooks. Use `WorldStates` (or the same rules) for its store. + A placement a tool makes outside those worlds (a studio paste) gets a `PackWorld` of its own: the pack's resources + and settings, a seed the host picks, a store closed when the placement ends, and no hooks. `world()` never throws. +- Don't override `PackWorld.seed(purpose)`: its default, `WorldRandom.purposeSeed(seed(), purpose)`, is the rule for + every purpose, the host's own built-ins included. +- Answer `PackWorld.running()` for a world the host runs, empty for a tool's world. Its `layout()` covers every column of + the world (not one chunk), with the same values chunk stages read; its `settings()` are the settings at a column and a + biome's declarations as chunk stages see them; `highest` is the platform's highest block now; `caveFloors` are + the cave floor markers of a chunk, in heights above the bottom; `sky()` is empty until the platform has the world. +- Call the hooks with `LifecycleRunner`: `packLoaded` once per pack snapshot before its first world starts, + `worldStarted` before the world generates anything, `warmUp` after it (on a thread of your choice, and wait for it before + the world's first generation; report a failure naming the module and carry on), `worldStopped` when it stops. On a hotload, and when the pack's + resources are read again while worlds run, stop each world, load the new snapshot and start the world again with + a new store. Close a stopped world's store only once no invocation uses it any more. +- A failed `packLoaded` or `worldStarted` keeps the world from starting and names the module; report `worldStopped` + failures without skipping the other modules. +- Ask modules through services instead of reading their features: combine `ALL` providers, ask `FIRST` providers in + catalog order until one answers, and use `service(type)` for `ONE`. Call providers from any thread, but long + searches off the server's main thread, and carry out what they return on the thread the platform needs. +- Read a `StructureLocator` position's Y as a height above the dimension's bottom and convert it to the platform's Y + at the boundary, like every other IrisApi height; the same goes for the positions of `Loot.Site`, `BlockDrops.Broken`, + `EntitySpawns` and `SaplingGrowth`. +- Create what `ItemDrop` and `EntitySpec` describe on the platform, skip what the platform lacks (an unknown enchantment, + attribute or item flag) with a warning, route a `ContentKey.Provided` (and a `Registered` id of a namespace another + plugin owns) to that plugin, and run the checks that come with an `EntitySpawns.Attempt` (light, surface, + free space) before spawning. Report how many entities appeared with `EntitySpawns.spawned`. Apply `Arrival.reason` + (the platform's own name for the spawn reason, natural when it is empty or unknown), `Arrival.risesFromGround`, a + panda's `Appearance` genes, and `adjustsProvidedMob` (a `ContentKey.Provided` mob is otherwise left as its provider set it up). +- Shuffle a filled container's slots with `Loot.shuffleSeed` (the first seed in module order; leave the order alone when + no module gives one), and discard the blocks written at height 0 when a `ProtectedFloor` provider says the floor is + protected (ask once per world). +- Keep a `PlacementRecord` beside the block a placement recorded it at and return it from `placementAt` (the host chooses + the form it stores); read the settings of `PlacementRun.settings` from the JSON at `Level.PLACEMENT`. +- `AmbientEffects.due`: ask for the player's last sampled position (not every tick's), carry out an `Effect` in the order + sound, particles, commands, potion, skip a part the platform lacks, and give no potion to a player who already has the + same one with a higher amplifier. +- Decode IrisApi's value types like settings: `BlockSpec`, `PaletteSpec`, `NoiseStyle`, `StyledRange`, `Range` and + `BlockPosition` from the JSON shapes in their docs, `Object` as maps, lists, `Double`s, strings and booleans. + Read and write a `@JsonForms` class through its codec, created once with its no-argument constructor, handing it + those same plain values; a member written as `null` stays left out and never reaches the codec. + Read a `"snippet/"` or `"snippet//"` string of a `@Snippet` type from + `snippet//.json`. Complete `NOISE_STYLE` references and `@ResourceRef` of the host kinds + (`EXPRESSIONS`, `IMAGE_MAPS` among them); + rendering a value type with the host's own description of the same JSON is allowed. +- Serve `PackResources.noise()`: build each style's noise from the host's generators, expressions and image maps, + the same values for the same style and seed, cached per pack snapshot; an unknown style name, a missing expression and a + missing image map fail. + Answer `NoiseSampler.signed(...)` with the generator's own signed read (and its per-thread coordinate memo) when it + has one; the default is `sample * 2 - 1`. + Answer `NoiseSampler.scaled(factor)` by building the generator again with the factor folded into its scale, leaving the sampler it + is called on untouched (the default multiplies the coordinates, which may round differently). +- Answer `PackWorld.minWorldY()` with the platform's Y of the dimension's bottom, the same number `TerrainSampler.minWorldY()`, + `PlatformStart.minWorldY()` and `StructureFit.minWorldY()` give. Answer `BlockRegistry.find(key)` with the platform's block at + its default properties, empty for a block or property the platform lacks. +- Answer `PackResources.idOf(key)` (the ids the host gives + its own resources, characters an id cannot hold replaced) and `TerrainSampler.caveBiome(x, y, z)` (the cave biome of a block, + without the work of the rest of the sample) when the defaults do not fit the host. +- Answer `BlockRegistry.hasTrait` (`VINE` included) and `canPlaceOn` (the support rule decorations need) as the platform + does; stages ask per block, so answer from memory once a state was seen. +- Resolve `BlockSpec`s in `BlockRegistry` as packs expect (pack block, platform block, backup, air) and turn their + `tileData` into the host's block entity format. +- Build `BlockRegistry.palette(spec, seed)` pickers: blocks expanded by weight, the style's noise at (x, y, z) over + the zoom picks the entry, resolved as above, cached per pack snapshot; refuse a palette without a block to pick. +- Ask every `VanillaStructures` provider (`catalog().registrations(VanillaStructures.class)`, module id order) before + the platform starts one of its structures and when it locates one, combine the rules with `VanillaStructureRule.and`, + keep the result per world, structure and pack snapshot, and apply it on every platform: block the platform's starts + of a blocked structure, and report a structure a module places as that module's. A provider that throws or answers + nothing fails naming its module. +- Before publishing a start the platform made, add up every provider's `shift` for it (after the host's own + alignment of monuments and temples) and move the start by it, less where it would leave the world. Before + publishing any start, cover every provider's `reach` in its references (`PLATFORM`: the platform's own terrain + adaptation envelope), within Minecraft's reference range; a recorded envelope only grows. +- Per chunk, call every provider's `beforePieces` once before the platform places any piece of the chunk's starts, + then per start in placing order the platform's placement and `afterPieces`. Give `StructureFit` in the API's heights + (above the bottom, maxima exclusive): the processed template cells of a piece, its template columns, its legacy + template air, the surface per column without fluids and the dimension's natural block. `BlockAccess.is` answers + `AIR`, `SOLID`, `FLUID`, `LOG` and `LEAVES` as the platform's world does and refuses other traits. +- Persist every start's `StartMemo` with its ownership record, unchanged, and hand it back in `reach` and + `StructureFit`; a start without a memo stays without one. +- Ask `starts` per chunk, in module id order, refuse a start outside the chunk asked for, keep the first start per + structure, let a start take the chunk from a platform start only when it says so or the structure is `REPLACE`d, + apply its jigsaw overrides, keep its memo, and ask again (same answer) when locating or verifying a start found in + the world. +- Send the platform's locate of a structure some `StructureLocator` provider lists in `startedStructures` to that + provider's `locateStart` (module id order, the first that lists it in `locatableStarts`), convert the start's Y to the platform's, + check the start the platform made there before reporting it, and search again refusing that chunk when the check fails. + Route the host's own structure commands by `startedStructures` the same way. +- Ask `setup` per dimension before its worlds build their structure state and when installing data packs; multiply + frequencies per structure set (0.01 to 16), protect the platform's definitions in every installed data pack once + any dimension of any loaded pack asks for it. +- Run the platform's own placed features over a world only when some `VanillaFeatures` provider's `generates` says so; + then skip a decoration step any provider refuses (`generatesStep`, empty for a step the API does not name) and a + feature any provider refuses (`generatesFeature`). Ask once per world, step and feature, and keep the answers while + the world runs. Keep the platform's own pass otherwise unchanged: its biome tables, order and seeds. + +## Open + +- Terrain/biome providers, pack transformations, structure assembly and the runtime family. diff --git a/api/DESIGN.md b/api/DESIGN.md new file mode 100644 index 000000000..761218c22 --- /dev/null +++ b/api/DESIGN.md @@ -0,0 +1,1459 @@ +# Iris API design + +Status: pack module loading (`LoadedPack`), the stage graph, per-stage random streams, both +pipelines' reference executors, settings catalog and its description for studio, geometry, +resources, module resource kinds, validators, per-world state, lifecycle hooks, services and typed storage contracts +exist and are tested without the Iris +engine. Provider and runtime families at the end are design notes, not Java interfaces. + +## Model + +An Iris module owns its settings types and the stages that act on them. The host owns resource +loading, platform adapters, scheduling, storage and publication. The core engine is meant to be +a set of ordinary modules (`iris:prepare`, `iris:anchor`, `iris:blocks` and so on). No stage, +phase or hook has special status in the API. + +```mermaid +flowchart TD + Modules[Built-in and addon modules] --> Setup[setup] + Setup --> Install[stages: define stages] + Setup --> Register[registry: geometry, mantle layers, resource kinds, validators, hooks, services] + Install --> Resolve[Resolve per pipeline at pack load] + Install --> Settings[when settings types] + Settings --> Catalog[Frozen feature catalog] + Register --> Catalog + Resolve --> Placement[Placement graph] + Resolve --> MantleGraph[Mantle graph] + Resolve --> Chunk[Chunk graph] + Catalog --> Schema[PackSchema for studio] + Schema --> Render[Host JSON Schema and workspace] + Catalog --> Decode[Host JSON decoding] + Decode --> Configured[ConfiguredSettings per invocation] + Configured --> Placement + Configured --> MantleGraph + Configured --> Chunk + Placement --> Edit[Buffered placement edit] + MantleGraph --> MantleData[Mantle around the chunk] + MantleData --> Chunk + Chunk --> Hunk[Local hunks] + Edit --> Publish[Host publication] + Hunk --> Publish +``` + +## Module loading + +The `IrisModule` implementation is the module's entry point. `info()` returns its id, display +name and version; there is no separate descriptor. What the jar needs at load (its optional packages) is in the jar's +manifest, because it is the jar's, shared by every module in it, and because a module's identity should not carry +class loading mechanics. A pack keeps its modules in +`/modules/*.jar`, one or more modules per jar. + +The host loads a pack with `LoadedPack.load(packRoot, host)`. `ModuleHost` is the host's fixed +configuration, built once and the same for every pack: built-in modules, exposed host packages, +the JSON fields the host uses itself, host type packages and reserved folders. Each of its methods adds to what earlier calls +configured, and all names are checked when it is built. `LoadedPack` runs `PackModules.load` (below), then +`LoadedModules.load` on the built-ins followed by the pack's modules. If the second step fails it +closes the first before rethrowing, so a failed load leaves no class loader or jar copy behind. + +Every load error is one unchecked type, `ModuleLoadException`, with `moduleId()` and `origin()` when the error is +one module's or one jar's. Jar errors throw it directly with the jar. Anything a module's `setup` throws, the +registry's and stage graph's checks included, is wrapped with that module's id and jar, the message unchanged; errors +after setup (catalog, studio description, resolution) are wrapped without a module unless the check knows the stage's +module. So hosts catch `ModuleLoadException` instead of `RuntimeException`, and a bug in the host itself still +surfaces as what it is. `ModuleHost`'s own argument checks stay `IllegalArgumentException`: they are the host's +configuration, not a pack's. +`close()` closes the pack's class loader, then deletes its jar copies. + +A jar names its entry classes, one per line, in `META-INF/services/com.volmit.IrisModule`, the +provider format of `ServiceLoader`. The host reads that file from the jar itself rather than calling +`ServiceLoader`, which would also return providers of parent class loaders and could not say +which jar a broken provider came from. The rejected alternatives: + +- A manifest attribute such as `Iris-Module: com.example.MossModule`. It needs the same reading + code but is not a Java convention, IDEs do not check it, and fat-jar tools tend to rewrite + manifests. +- A descriptor file with id and version. It duplicates `info()`, so the two can disagree, and + parsing it needs a format the JDK does not ship. + +`PackModules.load(packRoot, exposedHostPackages)` (or `load(packRoot)`, which exposes only the +API): + +1. Validates the exposed packages. The API's package is always one of them. +2. Lists regular files ending in `.jar` in `/modules`, sorted by file name. A missing + directory means no modules. +3. Copies them into a fresh temporary directory (see "Jar copies"). Every later step reads the + copies; messages name the originals. +4. Reads each jar's entry point file, its class files and its manifest's tooling parts (see "Tooling parts"). Comments + (`#`) and blank lines are ignored; zero entry class names fail, several load in the order listed. +5. Fails if a jar holds a class of an exposed package, naming the jar and the first such class. +6. Fails if a class is in two jars, naming the class and both jars. +7. Resolves every class each class uses (see below). A class that Iris has but hides, a class of a + JDK module packs cannot see or of a JDK package packs may not use, or a class missing from an + exposed package fails the load, listing + each referencing and referenced class per jar and kind. Classes that nobody has are collected + per jar. Generation code that uses a tooling part's class fails too; the classes of a part are judged apart, or + skipped (see "Tooling parts"). Nothing has been defined up to here. +8. Creates one `URLClassLoader` for all copies, parent = `ExposedHostClassLoader`. +9. Loads each entry class, checks that it implements `IrisModule` and comes from its own jar, + instantiates it with the public no-argument constructor and calls `info()`, once. +10. Drops each jar's missing classes that lie in the optional packages its manifest declares + (`Iris-Optional-Packages`; an invalid name fails the load when the jar is read, in step 1). +11. Logs one INFO summary of the pack's modules, and one WARNING if any missing classes remain. + +Any failure after step 3 closes the loader, if it exists, and deletes the copies. + +One loader per pack, not per jar, because `requires(...)` takes another module's stage constant. +A pack jar that requires a stage of another pack jar must see its classes. Packs stay isolated +from each other. The cost is a shared class namespace: with two copies of a class, the loader +would silently use the one first in file name order. Step 6 turns that into a load error, so two +jars that shade the same library must relocate it, and shared code belongs in one module that the +others require. + +### Jar copies + +A `URLClassLoader` keeps every jar it reads open until it closes. On Windows an open file cannot be +replaced, so a loaded pack would stop its module author from rebuilding a jar while studio runs. +The load therefore copies the jars first (`JarSnapshot`) and gives the class check and the loader +only the copies. The originals are closed again as soon as they are copied. This also means a load +works on one consistent set of jars: a jar rebuilt during the load affects the next load, not half +of this one. + +Copies live in a new directory `iris-pack-modules-*` under `java.io.tmpdir`, or under the directory +the host passes to `ModuleHost.copyingJarsTo(...)`, which is created when missing, named by their +original file name, next to an owner file holding a fixed header and the id of the process that made +it. Origins and messages always use the original path relative to the pack: the copy's path would +mean nothing to the author. When an entry class turns out to come from another jar of the pack, the +message names that jar's origin too. + +A process that crashes never closes its packs, so its copies stay. A later load removes such a +directory only when it can show that this code made it and that nobody uses it: the name has the +prefix, the owner file has the header, its process no longer runs +(`ProcessHandle.of(pid)` finds no live process), and the directory holds nothing but the owner file +and `.jar` files. Directories of a process that still runs, including another server sharing the +temporary directory, are left alone; a reused process id can only keep a stale directory, never +remove a live one. A crash between creating the directory and writing the owner file leaves an +empty directory that is never removed, because nothing proves who made it. + +The class check reads jars the way the loader does. `module-info.class` is ignored. A +multi-release jar (`Multi-Release: true`) contributes each class once, under its base name, from +the highest `META-INF/versions/N` that the running JDK selects; a versioned copy of a class in one +jar therefore clashes with the plain class in another. In a jar without that manifest attribute the +loader never reads `META-INF/versions`, so those entries are skipped. + +### What a module can see + +Modules depend on the Iris API. They compile against it `compileOnly` and never ship it, because +Iris provides it at runtime; in production it is shaded into the Iris plugin jar. That loader also +holds Iris internals and the libraries Iris bundles, so it is not the pack loader's parent. +`ExposedHostClassLoader` is: it delegates every class in an exposed package, and its subpackages, +to the host's loader (the loader that defines the API) and everything else to the platform class +loader, which holds the JDK. + +The host side, `com.volmit.host` (with `com.volmit.host.schema`), is never exposed, although it lies inside the +API's root package. It is its own Gradle subproject and artifact (`host`, `com.volmit:iris-host`) next to the API +(`api`, `com.volmit:iris-api`); Iris depends on both and shades both. `ExposedPackages` carves the host package out +of every exposed package (`com.volmit` and anything the host passes), and the host may not expose it explicitly. A +pack class that references a host class is therefore a hidden host class and fails the load, and a jar that ships a +class anywhere under `com.volmit`, the host side included, fails as shipping API classes. + +*Why keep the name `com.volmit.host`.* The finding allowed a new root such as `com.volmit.hosting`, but any name +under `com.volmit` would be exposed as well, and a root outside it (`com.volmithost`) reads like a different +vendor. The exposure check can exclude one package exactly, so the carve-out is a single rule in one class, and no +import in Iris or the tests changes. + +The platform loader provides the JDK modules defined to it and to the boot loader: `java.base`, +`java.sql`, `java.net.http`, `java.compiler` and the other standard modules. JDK modules defined to +the application loader, such as `jdk.compiler`, `jdk.jshell` and `jdk.attach`, are not available +to modules, and neither are JDK modules the runtime did not resolve. + +Seeing a class is not enough to use it. Pack classes live in their loader's unnamed module, and a +JDK module lets an unnamed module use only the packages it exports to all unnamed modules. Internal +packages such as `jdk.internal.misc` (`jdk.internal.misc.Unsafe`) are not, so code using them would +fail with `IllegalAccessError` when it runs. Packages exported only to named JDK modules (qualified +exports) count as not exported. The supported way to use Unsafe is `sun.misc.Unsafe`, which +`jdk.unsupported` exports. A server started with `--add-exports /=ALL-UNNAMED` +exports that package to every unnamed module, and then modules may use it. + +The exposed packages (`ExposedPackages`) are the API's package, `com.volmit` (the package of +`IrisModule`), plus whatever the host passes to `ModuleHost.exposing` (and so to `PackModules.load`). The host decides those; the +intended use is the packages that hold built-in modules' stage constants, so that a pack jar can +`requires(...)` a stage of the core engine or a built-in feature. A pack jar then links against +the host's class and the same stage constant, which resolution requires: a copy would be a second +definition of the id. Names match whole packages: `com.volmit` does not expose `com.volmitx`. A +trailing dot is accepted; anything that is not a package name, such as a blank string or a +wildcard, is rejected. The host's `PackageName` holds these rules; a jar's optional packages use them too. + +A module may use any library. A library the host does not expose it ships itself, inside its own jar or as another +jar of the pack, and never borrows the host's hidden copy: those can change with any host update, and two modules would +otherwise depend on whatever version the host happens to bundle. A host may instead expose a library it promises to +keep, by passing its packages to `ModuleHost.exposing`; the pack loader then gives modules the host's classes of it, +like the API's. Iris exposes VolmLib (`art.arcane.volmlib`, its utility library, shaded unrelocated) and Gson +(`com.google.gson`, which every platform it runs on provides), so Iris's built-ins and pack modules share one copy of +each. A module jar may not contain classes of an exposed library, as it may not contain API classes. + +Resources follow the same rule by path: `com/volmit/...` and the paths of other exposed packages +from the host's loader, everything else from the platform loader, then the pack's jars. A class +and its class file come from the same place, and a pack never sees Iris's own resources such as +`plugin.yml` or its service files. + +The pack loader asks its parent first, so a packaged copy of a host class would be silently +replaced by the host's, and a module class in an exposed package could be replaced by a later host +class of the same name. Step 5 rejects both; exposed packages belong to the host. For the API the +message points at `compileOnly`, the usual cause. A module class that shares a name with a hidden +Iris internal is harmless, because the pack loader cannot see it. A module class that shares a name +with a JDK class is replaced by the JDK's; that is not checked. + +Step 7 reads every class file with the JDK's `java.lang.classfile` API. A class uses every class +in its constant pool (supertypes, and instantiated, cast, caught, called-on and class-literal +types) and every type in the descriptors of its own fields and methods and of the members and +call sites it uses. Arrays count as their element type; primitives do not count. Annotations and +generic signatures are left out: the JVM never resolves them while linking, and reflection skips an +annotation whose type is missing, so a `compileOnly` annotation library such as JetBrains +annotations needs nothing at runtime. Each used class outside the pack is judged by its class +file, so nothing is loaded or initialized: + +| The class is | Result | +| --- | --- | +| in a package of a JDK module the platform loader provides, not exported to unnamed modules, such as `jdk.internal.misc` | load error: names the package and module; points to `sun.misc.Unsafe` and `--add-exports` | +| in a jar of the pack, an exposed package of the host, or the JDK | resolves | +| in an exposed package, but the host does not have it | load error: the jar was built against a different Iris API or Iris version | +| in a JDK module the platform loader does not provide, such as `jdk.compiler` | load error: names the JDK module, which is not available to modules | +| not exposed, but the host's loader has it (Iris internals, Iris's copy of a library) | load error: modules cannot use Iris's classes; ship the library in the pack or use the API | +| nowhere | the pack loads, with a warning unless the jar's manifest declares the package optional | + +The rows are checked in that order. The export row comes first because access does not depend on +which loader finds the class: whoever loads `jdk.internal.misc.Unsafe`, `java.base` decides who may +use it. It asks the boot layer's `Module` objects whether they export the package to an unnamed +module that no export names (`Module.isExported(package, unnamedModule)`), so exports added with +`--add-exports ...=ALL-UNNAMED` count, exactly as they do at run time, and qualified exports do not. +Modules the platform loader does not provide are left to the unavailable-module row, so the two +never overlap. The unavailable-module row comes before the host row because the host's loader +can usually load application-loader JDK classes, which would otherwise be reported as hidden Iris +classes. Whether a class belongs to such a module is decided by its package, from the JDK's module +descriptors (`ModuleFinder.ofSystem()`) and the loader the boot layer gives each module, so nothing +is loaded. When a jar uses several kinds of unusable class, the error has one group per kind and +jar, each with its own advice. + +The JVM resolves a class only when code first needs it, so a class that nobody has is usually an +optional dependency of a bundled library, used only when present. Rejecting those would be stricter +than the JVM and would make many ordinary libraries unusable. Instead the pack loads, +`PackModules.missingClasses()` lists the missing classes per jar (`MissingClasses`), and the load +logs one WARNING for the pack, one line per jar with at most five class names +(`MissingClassesWarning`), so a large shaded library cannot flood the log. Code that needs a missing +class throws `NoClassDefFoundError` when it runs; the verifier may also need it while linking a +class that uses it, which then fails when that class is first used. + +A jar that knows it uses such classes declares their packages as optional in its manifest, separated by spaces or +commas: + +``` +Iris-Optional-Packages: org.slf4j org.apache.logging.log4j +``` + +Each package covers its subpackages. Missing classes of that jar inside them are dropped from the +warning and from `missingClasses()`; the rest still warn, and other jars of the pack are not +affected. A jar with several modules declares once for all of them. Invalid names fail the load +when the jar is read, naming the jar. + +The declaration lives in the manifest because it is about the jar, not about any one module: a jar shades a +library for all of its modules, and the host already applied the declarations per jar. It used to be +`ModuleInfo.withOptionalPackages`, which put class loading mechanics into a module's identity and could only be +read once the entry classes were defined. The declaration only removes warnings. Every load error is decided in +step 7, without it, so a declared package can never turn a hidden Iris class, an unavailable or non-exported JDK class +or a class missing from an exposed package into a pass. `missingClasses()` drops the excused classes instead +of flagging them: it then says exactly what the warning says, and a class the author declared +expected is not a problem to show in studio. + +A class the host hides fails, even though the pack might never run that code, because it exists: +the module was written against Iris's copy, and the error says to ship the library or use the API +instead of leaving the author with a `NoClassDefFoundError` during setup or generation. + +There is no version gating. Packs ship their module jars and Iris never downloads any, so whether +a jar works with the running Iris is the pack publisher's responsibility. The class check catches +API and exposed classes that no longer exist. It does not check methods and fields: a jar built +against an API whose methods have changed fails with a linkage error, which `LoadedModules.load` +reports with the module's jar when it happens during setup, and which surfaces at generation +time when it happens only in a stage body. + +Closing `PackModules` closes the loader and then deletes the copies. Classes loaded before that +keep working, so the host must drop everything built from the pack first. + +Each module reaches `LoadedModules.load` as a `DiscoveredModule`: the module, its `ModuleInfo` and +its origin, the jar path relative to the pack or "host classpath" for built-ins. `info()` is called +exactly once, when the module is discovered (`DiscoveredModule.builtIn`, or step 9 for a jar), and +everything afterwards uses the stored value, so a module whose `info()` changes between calls cannot +give the host two answers. Errors about a module name its origin. Every jar error names the jar. + +### Tooling parts + +A module's platform tooling (the Bukkit studio, importers that read the server's structure files) cannot live in the pack +loader, which cannot see the platform: step 7 rejects every class Iris's loader has but does not expose, and Bukkit is +one. It also must not run on every server. The jar therefore names each part's entry class per platform in its manifest: + +``` +Iris-Tooling-Parts: bukkit=art.arcane.iris.tools.bukkit.StudioPart bukkit=art.arcane.iris.tools.bukkit.ImportPart +``` + +A part is the entry class's package with its subpackages. Entries of one platform may repeat, even in one package; any +other overlap fails when the jar is read (step 4), as does a malformed entry or an entry class the jar lacks, so no class +is ever in two parts. The manifest is right for the same reason as `Iris-Optional-Packages`: the declaration decides +which loader defines a package, which is class loading mechanics of the jar and not a module's identity. The rejected +alternatives: a service file per platform cannot name a package, and the class check needs the partition before anything +loads; an annotation means scanning every class; a second jar per platform makes a module two artifacts and the pack +loader would still have to skip it. + +**The class check partitions the jar** (`ToolingPartition`, used by `PackReferenceCheck`): + +- Generation classes are checked as before, and may not use a part class of any platform. The failure names both classes: + "Generation code cannot use the bukkit part; move the call into the part." +- Part classes are not generation code. When the host runs on a platform (`ModuleHost.runningOn(PlatformApi)`), that + platform's parts are checked at pack load, so a broken part fails early while its class still loads lazily. The check + takes what a part may see: its own packages, generation classes, the platform's api packages (which must exist in the + platform's loader), and whatever generation code may see. Denied packages fail first: a part may not use Iris + internals, the server's own classes or the host, or another part's classes. A class the host exposes to modules is + never denied, which is how `art.arcane.iris.builtin` stays usable inside the denied `art.arcane.iris`. +- Parts of other platforms are skipped unread, as are all parts when the host runs on no platform. `ModuleJarCheck` + does the same at build time, with `--platform=:` standing in for the platform's loader. + +`ToolingPlatform` describes a platform as a value: its name, the package prefixes of its api and the denied prefixes. +`ToolingPlatform.BUKKIT` is Paper's. `PlatformApi` pairs it with the loader that holds the api classes, which the check +asks by class file, so nothing loads. + +**`ToolingPartLoader`** is a child of the pack's loader, one per part. It defines the part's own packages itself, child +first, from the same jar copy; refuses denied packages with a `ClassNotFoundException`; hands the platform's api packages +to the platform's loader; and asks the pack's loader for everything else. Being a child of the pack's loader is the point: +the part then gets the same `Class` objects the modules registered, where a sibling loader would turn a resource the jar +defines into a `ClassCastException`. The caller opens and closes it; closing it never closes the pack's loader. + +`ExposedPackages` carves out every `com.volmit.tooling.` package like `com.volmit.host`: only a part sees a +platform's tooling api. `com.volmit.tooling` itself, the neutral api, stays exposed. Enabling parts lazily, mounting their +commands and listeners, and disabling them belongs to the platform adapter, not to the host. + +### Namespaces + +A module owns its id: `ns:name`, with no `/` in the name. It may define only stages whose ids start +with its id and `/` (`iris:stilt/fill`), so no module can define stages under another module's +path, and a stage id names exactly one possible owner. A `/` in a module id would let `iris:stilt/x` +define stages under `iris:stilt`, so `ModuleInfo` rejects it. + +Feature ids of geometry generators and mantle keys a module registers follow the same rule +(`ModuleInfo.ownsId`): they are the module id or start with it and `/`, such as `iris:snow` or +`iris:snow/depth`. Sharing the namespace is not enough, or `iris:snow` could claim `iris:stilt`'s +ids. A settings type named in `when(...)` must have a feature id that at least one module naming it +owns in this sense: its owner. Other modules may name it too, to run only where that setting is +configured. Checking against the module that names it alone would forbid that; checking nothing +would let any module claim another module's settings id. + +No namespace is reserved: `iris` is as free to a pack module as any other. A host that ships +modules of its own protects nothing by a reservation, so a module id is only ever loaded once: a +second module with the same id fails the load wherever it comes from (one jar, two jars, the host's +built-ins), naming both the origin and the class of each. That one check is what keeps a built-in +module that moves into a pack jar from being loaded twice. + +The load summary and the missing-classes warning go to the `System.Logger` the host passes to +`ModuleHost.loggingTo(...)`, by default `System.getLogger(PackModules.class.getName())`. A host +argument rather than a `System.LoggerFinder`: the JDK finds a finder through the system class loader, +which a plugin's classes are not on. The summary lists display name, id, version and jar for each module in load +order, or says the pack has no module jars. `PackModulesSummary` and `MissingClassesWarning` build +the texts and are tested on their own. + +## Stages + +A stage is a constant created by `Stage.placement`, `Stage.placementBlock`, `Stage.chunk` or `Stage.mantle`. Its +identity is that object. Another module that wants to depend on it references the owner's +constant, which makes the dependency a compile-time one. A copy with the same id is rejected at +resolve time. + +| Stage type | Pipeline | Runs | Context | +| --- | --- | --- | --- | +| `PlacementStage` | PLACEMENT | once per placement attempt | `PlacementStageContext` | +| `BlockStage` | PLACEMENT | once per object block, in a block pass | `BlockStageContext` | +| `ChunkStage` | CHUNK | once per chunk invocation | `ChunkStageContext` | +| `MantleStage` | MANTLE | once per chunk, before the chunks it reaches generate, each stage its own pass | `MantleStageContext` | + +`StageGraph.define` returns one definition type per stage type: `PlacementStageDefinition`, +`BlockStageDefinition`, `ChunkStageDefinition` and `MantleStageDefinition`. Each offers only +what its pipeline allows, so these rules are compile errors instead of load failures: a chunk +stage has no `reach` or `writesMantle`, only a mantle stage has `reach(PackReach)`, and only a +block stage has `accumulate`. + +Rules enforced by `StageGraphBuilder` and the resolver: + +1. The stage id must start with the defining module's id and `/`. A second definition of an id + fails. Two modules with the same id fail. +2. `requires(stage...)` adds a REQUIRED edge. If the stage is not defined by any module, loading + fails with both stage ids, the requiring module and the namespace the missing module should have. +3. `softAfter(...)` and `softBefore(...)` take stage constants or `StageRef` ids and add SOFT edges + only when the referenced id is defined. Absent targets are kept for diagnostics. A module cannot + force itself before another module's stage with a hard edge. +4. A stage with output must be defined with `produce` (or `accumulate` for block stages), and a + stage without output with `run`. Every defined stage needs exactly one body before its + module's `setup` returns. +5. A stage and everything it references must be in the same pipeline, soft references included. +6. Cycles fail and print the whole cycle: each stage with its module and the kind of each edge. + +### Order + +Resolution is Kahn's algorithm over the pipeline's stages. Among stages whose predecessors have +all run, the lexically smallest id goes first, with one refinement for fusion: + +- while a block pass is open, a ready block stage continues it; +- otherwise a ready invocation stage runs first; +- otherwise a block stage opens a new pass. + +The result depends only on ids and edges, never on setup order. A tie-break on raw lexical id +alone would interleave unrelated invocation stages into block passes and split them. Note that +no topological order can put every unordered pair in lexical order once edges point against the +alphabet, so "lexical" here always means "lexical among ready stages". + +### Block passes + +Adjacent block stages in the resolved order form one block pass. The placement runner loops over +the request object's blocks once per pass and runs every active stage of the pass on a block +before moving to the next block. A block stage that requires another block stage runs after it +for the same block. An invocation stage between two block stages splits the pass, even when it +is inactive for a particular invocation. The split is static so that `describe()` matches what +runs. + +Each pass starts from the request object's blocks. `replace` and `skip` affect only later stages +of the same pass for the same block. Work that later passes need belongs in an accumulator. + +### Outputs + +Outputs live in a per-invocation array indexed by resolved position. Stage definitions never hold +them. `ctx.output(stage)` scans the current stage's precomputed list of transitive requirements by +identity, which is a handful of entries, then reads the array. There is no hashing per call. +Reading anything outside that list throws `IllegalStateException` and names the fix. A block +stage's accumulator is created once per placement and becomes readable when its pass ends; +reading it from inside the same pass throws. A null output from a stage that declares one fails +the invocation, unless the stage rejected the placement attempt. These checks run when a stage +reads or produces, not at load: the graph knows which outputs a stage may read, not which it does. + +### Activation + +The graph is resolved once per pack load. Activation is decided per invocation: + +1. The invocation gets `ConfiguredSettings`: for each settings type, the entries configured for it, in + level order. For a placement the host passes the placement's own declarations. For a chunk or mantle + invocation the runner asks `FeatureSettings.declaredInChunk` for each conditioned type: every distinct + entry, by level and source, of the chunk's 16 by 16 columns. Its default reads every column; a host + that knows the regions and biomes of a chunk answers from those instead (Iris does). +2. The invocation looks up each distinct `when` type once. +3. One pass in resolved order marks a stage active when its settings have an entry (or it has no + condition) and every stage it requires is active. + +So an inactive requirement deactivates its dependents. That is not an error. Soft edges never +affect activation. The cost per invocation is two small arrays and one pass over stages and +REQUIRED edges, plus, for chunks, one `declaredInChunk` per conditioned type. The body reads +the entries with `ctx.configured(type)`, a never-empty `SettingsStack`. Only the +stage's own `when` type is readable that way; any other type, or a stage without a condition, +throws and names `when(...)` and `settings()` as the fixes. Bodies take only the context, so one +definition type per pipeline covers conditioned and unconditioned stages alike. + +`ConfiguredSettings` groups a value under the class whose `@Feature` declares it: the value's class or +its nearest superclass that carries the annotation. So a subclass value is found by `when(Base.class)`, +and a placement that configures a base and a subclass value configures the type twice. + +A chunk stage is active when any column of the chunk configures it, so a biome border inside a chunk +never hides a feature on either side. The body then reads `ctx.settings().at(type, x, z)` per column, +or at the chunk's centre column (`ChunkContext.centreX()`/`centreZ()`, local 7, 7) for behaviour that +happens once per chunk. `ChunkContext`, shared by chunk and mantle contexts, also names the chunk +(`chunkX()`, `chunkZ()`) and its `area()`, so no module hand-builds chunk boxes or shifts by 4. + +### Settings levels + +Settings are declared at levels (`com.volmit.config.Level`): `DIMENSION`, `REGION`, `BIOME` (the +column's surface biome) and `PLACEMENT`. `@Feature(targets = ...)` names the levels a type may be +declared at, and the same enum orders the entries. `FeatureSettings.at(type, x, z)` returns a +`SettingsStack`: one entry per level that declares the type at that column, in that order, each with its +level, the declaring resource and the value. Levels stack: there is no "most specific wins" and no field +merge. A module decides what several entries mean: deposits run once per entry (`values()`), a surface +block may take the most specific (`mostSpecific()`), a dimension-wide setting reads `dimension()`. The +stack offers those picks so modules do not each write their own; it never merges. The alternatives each hide a decision from +the module: overriding would make a biome's deposits silently drop the dimension's, merging would need a +rule per field. Something spanning several columns reads at one origin column: per chunk the centre +column, per placed object the column it is anchored at. Cave biomes are not a level. + +### Diagnostics + +`ResolvedGraph.describe()` lists every stage in order with its kind, block pass, owner module, +`when` feature, required and soft predecessors and absent soft targets. It also lists the fused +block passes and every pair of stages with no path between them in either direction. Those pairs +are ordered only by the tie-break, so they are where two modules can silently conflict. +`stages()`, `blockPasses()` and `unorderedPairs()` expose the same data as values. + +## Placement attempts + +A module places an object through the pack's placement graph with `PackWorld.placements().place(PlacementRun)`; the +host runs `PlacementRunner` over an edit that buffers into the run's `PlacementTerrain`, and returns the API +`PlacementOutcome`. One service, one request and one outcome: the run carries the object, its display name, the +placement as the pack wrote it (JSON, from which the host reads the settings other modules declare at `Level.PLACEMENT`), +the area, the terrain, the placing module's own input and the seed, and nothing names a host. The module that owns the +placement type declares it with `registerPlacementType(type, jsonFields)`: its option names are reserved at the placement +level, as the host's own fields are at the others, and studio adds the placement-level settings to the type's schema. The +host decodes the placement JSON once per text. A placed object is remembered by a `PlacementRecord` (object id, the +module's placement number, optional structure id) that the terrain keeps beside the blocks and `RunningWorld.placementAt` +reads back; the host stores it in its own form. The terrain is an interface so a module can hold +writes (an island that only accepts blocks over itself, a cave that keeps an object inside it) and commit or drop them +as one; the host's terrain for a mantle invocation is `MantleGenerationContext.placementTerrain()`. Objects come from +`PackResources.objects()` (`PackObjects`), which loads, scales and builds them per pack snapshot. + +`PlacementRunner.place(request, edit, inputs, invocationSeed, settings, timings)` owns the edit. It runs active stages in +order, stops after the current stage or block once a stage calls `reject(reason)`, commits only +when nothing rejected or threw, and closes the edit in every case. A producer that rejects may +return null, since no later stage reads its output; a null output without a rejection fails the +attempt. Stages receive a buffered +`PlacementAccess` view of the edit without commit or close, and it expires with the attempt. + +`PlacementAccess.set(x, y, z, state)` is the per-block write: a placement writes thousands of blocks, and the record +form (`set(PlacedBlock)`, for a block entity) costs a position, a record and an `Optional` per block. The edit +implements both, so a host buffers a plain block as it likes (Iris keeps states and block entities in separate maps, +so a plain block costs only its position key; an index into the placement area does not work, because a placement's +area may be unbounded). The access view, its mantle view and that mantle's layer views are made once per attempt, as +the chunk runner's mantle view is once per chunk invocation; asking again returns the same object. + +## Random streams + +Every stage has its own random stream per invocation, `StageContext.random()`. There is no shared +stream: `InvocationContext` has no `random()`, and the host passes a `long` invocation seed to +`PlacementRunner.place` and `ChunkRunner.generate` instead of a generator stages could see. With one +shared stream, every draw of an earlier stage shifts what later stages get, so installing a module +would change other modules' output for the same seed. + +The stream depends only on the invocation seed and the stage id (`StageStreams`): + +1. `idHash` = 64-bit FNV-1a of the UTF-8 bytes of `namespace:path`, computed once per pack load; +2. `streamSeed` = `mix(mix(invocationSeed) ^ idHash)`, `mix` being the SplitMix64 finalizer + (Stafford variant 13); +3. the stream is `new WorldRandom(streamSeed)`, created when the stage first draws. + +`mix` is a bijection, so a stage gets a different stream for every invocation seed, and in one +invocation stages with different id hashes get different streams. The hash and the mixer are written +out in IrisApi, not taken from `String.hashCode` or a JDK class whose output may change. + +A test pins the derivation to values computed outside Java from this description. + +### WorldRandom + +`com.volmit.random.WorldRandom` is the generator stages and object generators see. No JDK generator +fits: `SplittableRandom` and the `RandomGeneratorFactory` algorithms promise identical sequences only +within one program, and `java.util.Random` fixes only some methods. The ones it inherits from +`RandomGenerator`, such as `nextInt(origin, bound)`, `nextDouble(bound)` and `nextExponential()`, are +JDK defaults that a JDK update may change, and those are the ones module authors reach for. +`Random` is also a 48-bit LCG with an atomic update per draw, a cost in per-block stages. + +`WorldRandom` therefore does not implement `RandomGenerator`. Overriding every default would hold +only until a JDK adds another one; a type of its own exposes nothing IrisApi does not define. The +price is that it cannot be passed to JDK methods that take a `Random` or `RandomGenerator`, such as +`Collections.shuffle`; `pick` and `shuffle` cover the list cases instead. Its methods: + +| Method | Definition | +| --- | --- | +| `nextLong()` | SplitMix64 (Steele, Lea and Flood): `state += 0x9e3779b97f4a7c15`, return `mix(state)` | +| `nextInt()` | the high 32 bits of `nextLong()` | +| `nextBoolean()` | whether `nextLong()` is negative | +| `nextFloat()` | the high 24 bits of `nextLong()` times 2^-24, in `[0, 1)` | +| `nextDouble()` | the high 53 bits of `nextLong()` times 2^-53, in `[0, 1)` | +| `nextInt(bound)`, `nextInt(origin, bound)`, `nextLong(bound)`, `nextLong(origin, bound)` | Lemire's multiply-and-reject method, unbiased; ranges wider than `MAX_VALUE` work | +| `nextDouble(bound)`, `nextDouble(origin, bound)` | `origin + nextDouble() * (bound - origin)`, a result rounded up to `bound` replaced by the double below it; a width beyond `Double.MAX_VALUE` is halved first | +| `nextGaussian()` | Marsaglia's polar method on `StrictMath.log` and `StrictMath.sqrt`; the pair's second value is discarded | +| `chance(probability)` | `nextDouble() < probability` | +| `pick(items)` | `items.get(nextInt(items.size()))`; an empty list throws | +| `shuffle(items)` | Fisher-Yates in place: for `i` from `size - 1` down to `1`, swap `i` with `nextInt(i + 1)` | + +The state is one `long`, initially the seed. Methods without rejection draw exactly one value; how +many values a method draws is part of the sequence. `StrictMath` is fixed bit for bit by the Java SE +specification (fdlibm), so the gaussian needs no math of its own. Invalid bounds (`bound <= 0`, +`origin >= bound`, NaN or infinite doubles, a probability outside `[0, 1]`) throw +`IllegalArgumentException`, as does `pick` on an empty list. `pick` draws what `nextInt(size)` +draws. A shuffle of `n >= 2` elements makes `n - 1` `nextInt` calls; a shorter list draws nothing +and is not touched. `RandomAccess` lists are swapped through `List.set`; other lists are copied to +an array, shuffled there and written back through their `ListIterator`, like `Collections.shuffle`, +with the same result. A list that does not support `set` throws its `UnsupportedOperationException` +before any element changes. Weighted picking is left out until a stage needs it. The generator is +not thread-safe: one stage uses its stream within one invocation. + +`WorldRandomTest` pins every method to values computed by `src/test/reference/world_random.py`, an +independent implementation of this table with Python integers and IEEE doubles. Python's `math.log` +is the platform's, so the script carries a port of fdlibm's `log`. The build does not run it. The test +also fails if `WorldRandom` gains a public method without pinned values or implements +`RandomGenerator`. + +A block stage gets one stream per placement and draws from it across the blocks of its pass in block +order. Fused block stages interleave per block, but each still draws only from its own stream. A +stage that never draws never creates its stream. + +## Coordinates + +X and Z are world coordinates. Y is the height above the dimension's bottom: 0 is always the dimension's +bottom block, whatever its minimum height is in the platform, so Y is never negative. That applies to +every value that carries a height: `TerrainSample` heights, `TerrainSampler` and `BlockView` positions and +bounds, `PaletteSampler` and `NoiseSampler` sample positions, `PlacedBlock` and `PlacedMarker` positions, +placement anchors, `Mantle` positions and bounds, and a chunk `Hunk`'s local y. `BlockBox` carries +whichever coordinates its owner defines; an object's bounds are local to the object, and a placed +footprint can extend below height 0 where the object overhangs the bottom. The host converts to and from +the platform's Y at its boundary. + +## Chunk invocations + +`ChunkRunner.generate(inputs, invocationSeed, timings)` runs active chunk stages once each in resolved order. +`GenerationContext.blocks()` returns the host-owned local volume of the chunk's blocks, shared by +all stages of the invocation. Hunk coordinates are local. Samples and mantle coordinates use +world X and Z, and Y as the height above the dimension's bottom. A chunk stage writes only its own chunk and reads the mantle: the runner hands it a view +whose writes throw. The runner does no neighbor scheduling or rollback. A failed invocation must stop +the host from publishing the chunk. + +A chunk stage writes only its chunk but may look around it: its `TerrainSampler` covers the chunk and the 16 blocks +around it, so a stage that smooths a surface reads its neighbors' heights (`surfaceY`, which spares the host the slope +that `column` works out, or `surfaceHeight`, the same height rounded to a block, which every stage placing on the +surface used to write out as `(int) Math.round(surfaceY(x, z))`). The sampler also gives the dimension's +`fluidHeight()` and, per column, `upperDimensionY` where a dimension stacked above begins; a stage writes nothing at or +above it. The mantle's `blocks()` are the blocks placements wrote into the mantle for chunks to take over (objects, +structures): a chunk stage copies them into its chunk, as Iris's `iris:matter` does. They are the host's layer, so they +need no registration, and stages only read them; placements keep writing blocks through `PlacementAccess.set`. +A mantle stage's `TerrainSampler` covers the same margin (at least 16 blocks, more when its reach is larger): a carver blends +the profiles of the columns around its chunk, so it reads their heights and biomes though it writes only the mantle. +All three runners take a `StageTimings` and report how long each stage that ran took, so the host times modules +instead of modules timing themselves. A block stage is reported once per placement, its time summed over the blocks +of its pass; an inactive stage or one that throws is not reported. + +The ground a chunk stage fills in needs more of the host than heights. `surfaceBiome(x, z)` answers the biome id of a column without working out the +cave biome; `surfaceKind` says what that biome was generated as (land, sea or shore; a cave biome is always `CAVE`), `surfaceBlock` the block an image +map gives the ground, `minWorldY` the world Y of the dimension's bottom (settings that name world heights, such as a deposit variant's band, are in it), and +`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. 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.carved()` is the host's layer of carved voids (`CarvedVoid`: what fills the void, `OPEN`, `FLUID`, `LAVA` or `AIR`, and optionally the +biome it shows), as `blocks()` is its layer of planned blocks. It is the one host layer a module writes: a mantle stage plans the voids +(Iris's cave carver does, thousands per chunk, so the plain fills are shared constants and the host keeps them in its own form), and a chunk +stage reads them, around its chunk as far as its mantle reaches, and cuts them out of its terrain. A chunk stage's writes throw, as the +mantle is complete when chunk stages run. A void the planner marked need not show in the chunk (under a dimension above, the cave stage +leaves it solid), so a stage that places something solid asks `carved().get(x, y, z) != null`; there is no separate `isCarved` on the mantle. +`Mantle.setPlatformBiome(x, y, z, biome)` is the other way round: modules write it and only the host's biome pass reads it, in the host's own form +(Iris stores the platform's id for the biome), so it is a write rather than a layer a module could read back. It is general rather than a +floating-island call: any stage that makes a block belong elsewhere, such as an island floating over another biome, can set the biome it shows. +`TerrainSampler.biomeHeight` and `skyBiome` answer for a biome that need not stand at the column, because such a stage builds that biome's ground +away from where the layout puts it. Neither takes a random: Iris picks sky and custom biomes with a generator seeded from the world's biome seed. +`BlockRegistry.oreFor(rock, ore)` is the platform's answer to which variant of an ore belongs in a rock. + +## Mantle invocations + +Some work writes beyond its chunk: a carver whose tunnels cross chunk borders, a vein running on into +the next chunk. A chunk stage cannot do that, because the host may already have generated the +neighbor. Such work is a mantle stage. `MantleRunner.generate(stage, inputs, invocationSeed, timings)` runs one +mantle stage for one chunk, if it is active there, against the mantle around it +(`MantleGenerationContext`: origin, terrain, settings, mantle), without a block hunk. + +Every mantle stage is its own pass. Before a chunk generates, the host runs the first stage in resolved +order for every chunk within that stage's reach plus the reach of every later stage, each chunk once, +then the next stage the same way. A stage therefore sees, in the chunks around it, everything earlier +stages wrote, and a chunk's mantle is complete when its chunk stages read it. In Iris each mantle stage +is one mantle component, a pass of its own, whose radius is the stage's reach. Because stages of one +chunk run in different invocations, mantle stages have no outputs: `MantleStage` is not generic, and +stages pass data on through mantle layers. `requires(...)` still orders mantle stages and still +deactivates a stage in a chunk where a stage it requires is inactive; the runner works that out from +the settings of the stage and everything it requires, and collects only those. + +The mantle pipeline is the only place that writes the mantle during generation, and mantle and chunk +pipelines meet only through mantle layers: an edge between them is a cross-pipeline edge and fails the +load. A mantle stage may rely on what earlier stages wrote around its chunk, but not on what a stage of +its own pass wrote in other chunks: that depends on the order the host generates chunks in. + +## Reach + +A stage may write outside its footprint: a carver reaches into neighbor chunks, a tree's leaves spread +past the object's trunk. The host has to prepare that area, and the mantle in it, before the stage +runs. Stages declare it in their definition: + +```java +graph.define(CARVE).reach(32).writesMantle(CaveModule.CAVES).run(CaveModule::carve); // CARVE is a mantle stage +``` + +- `reach(blocks)`: how far, in blocks along X and Z, the stage writes blocks or mantle values beyond + its footprint. The footprint is the chunk's 16 by 16 columns for a mantle stage and the X/Z bounds of + the placed object for a placement or block stage. A chunk stage writes only its chunk, so + `ChunkStageDefinition` has no `reach`. Whole + columns: height is not limited, because Iris prepares chunks and mantle as full columns. Leaving it out means 0. Declaring it twice or + negative fails during the module's setup. +- `reach(PackReach)`: for a mantle stage whose reach depends on the pack, such as the largest object + or the longest vein any level configures. The host works it out once per pack load from + `PackSettings`, every entry of a settings type the dimension and its reachable regions and biomes + declare, and asks each stage with `ResolvedStage.reachBlocks(settings)`; a negative result fails + there, naming the stage. Only `MantleStageDefinition` offers it: placement areas and chunks + are sized without the pack's settings. It counts as declaring the reach, so it cannot be combined + with `reach(blocks)`. +- `writesMantle(layers...)`: the mantle layers the stage writes. Every layer must be registered by + some module with the same value type, or the pack load fails naming stage and layer. + `ChunkStageDefinition` has no `writesMantle`. + +Each resolved stage carries its `StageReach`. `ResolvedGraph.reach()` collects a `PipelineReach`: +the largest reach of the pipeline's stages, and per mantle layer the largest reach of the stages +that write it. Inactive stages count, because activation is per invocation and the prepared area is +decided once per pack load. A mantle pipeline with a reach worked out per pack has no such number, so +`reach()` throws there; the host sizes each mantle pass from its own stage instead. `describe()` lists +each stage's reach. + +One number per stage, not per layer: a stage that writes two layers at different distances declares +the larger. The host can still size each layer's mantle from the per-layer maximum. Reads are not +declared separately: the host prepares the pipeline's reach around every placement, and each mantle +stage's own reach around its chunk, so a stage may read what others wrote that far out (for mantle +stages, see the ordering caveat under Mantle invocations). A stage that must read farther declares that distance +as its reach. Terrain samples are computed, not prepared, and need nothing. + +## Settings, geometry and storage + +Settings types implement `IrisFeature` and carry `@Feature` (namespaced id, display name, attachment targets). `when(type)` validates the annotation during the module's setup. The id +must be owned by a module naming the type (see Namespaces), or the owner registers the type itself +with `FeatureRegistry.registerSettings`. That is for settings no stage names, such as settings read +only through `FeatureSettings.at(...)`; registering a type a stage also names changes nothing, and a +type its owner registered may be named in `when(...)` by any module. +`LoadedModules.load` catalogs those types with geometry generator settings and rejects duplicate +ids. Two modules with one id never get that far: the load fails naming both ("Duplicate module"). +`OptionsMetadata` reads field metadata, in declaration order; it does not decode JSON. + +### JSON keys + +Packs write a feature's settings under the short key its `@Feature` declares (`key`, required), at each of +its targets: `"moss": {...}`. The feature id (`example:moss`) is the identity everywhere else (stage graph, logs, +lookups by class) and is never a JSON key. A key is a plain field name, not blank and without `:`. + +*Why a declared key and not the id.* Pack authors write these keys by hand, and a biome already says `deposits`, +`decorators`; `"iris:deposit": {"generators": [...]}` would make every existing pack unreadable and every file longer. +The id carried an implicit uniqueness guarantee (module ids are unique); a declared key has to be checked instead. + +*Uniqueness.* A key is unique per target (dimension, region, biome, object placement), across all loaded modules and +the host's own JSON fields of that target. The host passes its fields with `ModuleHost.reservingFields` (the same +fields it reads itself: a module may not take `name` or `generators` for a biome). `ModuleRegistry` claims `(target, +key)` for every feature it catalogs, settings and object generators alike, including types only a stage names, and a +clash fails the registration, so the pack load, with one message naming the key, the target and both claimants (feature +id and the module's jar, or `Iris` for a host field): `biome key "deposits" is claimed by iris:deposit (host classpath) +and acme:ores (modules/acme-ores.jar)`. Claimants are listed host field first, then built-in features, then pack +features, then by feature id, so the message does not depend on which module registered first. + +*One shape.* The JSON under a key is the object of the class's options, unless `@Feature(root = "