diff --git a/CONTRACTS.md b/CONTRACTS.md index 5523633ee..c74b725e1 100644 --- a/CONTRACTS.md +++ b/CONTRACTS.md @@ -1,40 +1,47 @@ -# Migration requirements +# Contracts -The authoritative design is [DESIGN.md](DESIGN.md). This replaces the earlier deferred-contract -backlog after the decision to establish the API first and modularize Iris afterwards. +[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 | Current contract | +| Requirement | Contract | | --- | --- | -| Annotated configuration and construction | `IrisFeature`, `FeatureRegistry`, typed factories, `OptionsMetadata` | -| Registered feature catalog and ordering | `ModuleRegistry`, `FeatureCatalog`, `GenerationPlan`, `PlacementPipeline` | -| Block states, predicates and palettes | `BlockState`, `BlockRegistry`, `BlockPalette` | +| Module identity and composition | `IrisModule`, `ModuleInfo`, `StageGraph` | +| Module-owned work and ordering | `Stage`, `StageRef`, stage definitions, `requires`/`softAfter`/`softBefore` | +| Activation by configuration | `when(settingsType)`, host `ConfiguredSettings` | +| 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`, `ChunkRunner` | +| Annotated settings | `IrisFeature`, `@Feature`, config annotations, `OptionsMetadata` | +| Geometry and mantle registration | `FeatureRegistry`, host `ModuleRegistry`, `FeatureCatalog` | +| Block states and palettes | `BlockState`, `BlockRegistry`, `BlockPalette` | | Pack-scoped resolution | `ResourceId`, `ResourceKey`, `PackResources` | -| Terrain, biome and effective feature sampling | `TerrainSampler`, `BiomeSample`, `TerrainSample`, `FeatureSettings` | -| Dense local output | `Hunk`, reference `ArrayHunk` | -| Sparse procedural geometry | `ObjectGenerator`, `GeneratedObject`, `ObjectBlock`, `ObjectMarker` | -| Host-owned transforms | `ObjectTransform`, `ObjectTransformer` | -| World-space placement and hooks | `PlacementRequest`, `PlacementPlan`, `PlacementModifier` | -| Buffered placement writes | `PlacementAccess`, host-owned `PlacementEdit` | -| Typed persistent/generation storage | existing `mantle/` contracts | +| Terrain and settings sampling | `TerrainSampler`, `BiomeSample`, `TerrainSample`, `FeatureSettings` | +| Dense chunk output | `Hunk`, `GenerationContext.hunk`, reference `ArrayHunk` | +| Sparse geometry and transforms | `ObjectGenerator`, `GeneratedObject`, `ObjectTransform`, `ObjectTransformer` | +| Buffered placement writes | `PlacementRequest`, `PlacementAccess`, host-owned `PlacementEdit` | +| Typed generation and persistent storage | `mantle` package | -Dense output, sparse geometry and world-space placement remain distinct. Configured modifiers -hold read-only snapshots; temporary state is carried by contexts and immutable results. +Stage bodies hold no invocation state. Everything per placement or chunk travels through the +context, outputs and accumulators. ## Requirements for the Iris adapter -- Preserve pack field names/defaults and explicit target-specific inheritance/combination rules. -- Preserve seed derivation, random consumption, coordinate conventions and iteration order. -- Bridge current engine ordering, including planned Mantle work, insertion and finishing steps. -- Prepare full read/write areas and predecessor work; never silently clip requested reach. -- Provide atomic generation-storage edits across blocks, block entities, markers and mantle. -- Preserve unknown persisted layers or fail explicitly; provide codecs for platform values. -- Handle chunk publication, native structure integration, cleanup and reload lifetimes in the host. +- 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. +- Build `ConfiguredSettings` per placement and per chunk from decoded pack JSON, with explicit + precedence between dimension, region, biome and placement declarations. +- Preserve pack field names and defaults, seed derivation, RNG draw order, coordinate + conventions and iteration order where existing worlds must not change. +- Prepare the full area a placement or chunk may read or write, including neighbors. Never clip. +- 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. -## Later extension families +## Open -Terrain/biome providers, pack transformations, structure assembly/import controls and runtime -spawning/effects/drop/tree/lifecycle contracts are designed as separate extension families in -DESIGN.md. They require feature ports to settle their exact Java methods. They must not be -implemented by exposing Engine, IrisData, Bukkit or native mutable handles. +- Per-stage reach declarations, replacing the removed modifier radii. +- Per-stage RNG streams, so adding a module does not shift other modules' random draws. +- Terrain/biome providers, pack transformations, structure assembly and the runtime family. diff --git a/DESIGN.md b/DESIGN.md index 6e9b3f59f..207f4c4c9 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1,291 +1,211 @@ -# Iris API design and migration contract +# Iris API design -Status: implemented draft for generation, geometry, placement, resources and typed storage; -reference registry/planners/examples verified without the Iris engine. Provider and runtime -families below describe the intended design, not Java interfaces already available. +Status: the stage graph, both pipelines' reference executors, settings catalog, geometry, +resources 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. -The project decision is to establish a usable public interface first, then migrate built-in -features, then refine composition. A stable published API should follow representative real -ports and compatibility checks. Existing built-ins have now been extracted into the -[default module](../IrisModule/README.md), preserving their legacy engine dependencies. -That source extraction does not yet make them public-API implementations. +## Model -## Target shape - -An Iris module owns annotated configuration and configured behavior. The host owns resource -loading, platform adapters, scheduling, storage, lifecycle, and publication. Built-ins and -external addons should eventually use the same feature registration interface. +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] --> Registry[Feature registration] - Registry --> Catalog[Frozen catalog and metadata] - Catalog --> Decode[Host JSON decoding and validation] - Decode --> Factories[Configured factories] - Factories --> Generation[Chunk modifiers] - Factories --> Geometry[Sparse object generators] - Factories --> Placement[Placement modifiers] - Geometry --> Objects[Immutable generated objects] - Objects --> Placement - Generation --> Hunk[Local dense output] - Placement --> Edit[Buffered world-space placement] - Resources[Pack snapshot and platform adapters] --> Generation - Resources --> Geometry - Resources --> Placement - Hunk --> Publish[Host publication] - Edit --> Publish + Modules[Built-in and addon modules] --> Install[install: define stages] + Modules --> Register[register: geometry, mantle layers] + 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 --> Chunk[Chunk graph] + Catalog --> Decode[Host JSON decoding] + Decode --> Configured[ConfiguredSettings per invocation] + Configured --> Placement + Configured --> Chunk + Placement --> Edit[Buffered placement edit] + Chunk --> Hunk[Local hunks] + Edit --> Publish[Host publication] + Hunk --> Publish ``` -The three execution interfaces are deliberately distinct: +## Stages -- Chunk modifiers work on dense local volumes. -- Geometry generators return reusable sparse objects without world writes. -- Placement modifiers inspect and change one attempt with ordered hooks and buffered writes. +A stage is a constant created by `Stage.placement`, `Stage.placementBlock` or `Stage.chunk`. 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. -A vacuum operation is a placement modifier, not a chunk modifier. A crystal generator produces -geometry, not a dense chunk. Surface decoration generally writes dense blocks but may share -palette and support adapters with object placement. Existing engine helper classes are -implementation details, not types to copy into the public interface. +| 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` | -## Registration and configuration +Rules enforced by `StageGraphBuilder` and the resolver: -`IrisModule.register(FeatureRegistry)` registers typed settings-to-behavior factories. Settings -implement `IrisFeature`; `@Feature` declares namespaced identity, display name, JSON field and -attachment targets. The module constructor/factory must not need predecessors to have run. +1. The stage namespace must equal the defining module's namespace. A second definition of an id + fails and names both modules. Two modules with the same id fail. +2. `requires(stage...)` adds a REQUIRED edge. If the stage is not installed, loading fails with + both stage ids, the requiring module and the namespace the missing module should have. +3. `softAfter(ref...)` and `softBefore(ref...)` add SOFT edges only when the referenced id is + installed. 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 `install` 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. -The current registration interface has four operations: +### Order -```java -registry.register(featureType, outputType, modifierFactory); -registry.registerObject(featureType, geometryFactory); -registry.registerPlacement(featureType, placementFactory); -registry.registerMantle(layerKey, lifetime, codec); -``` +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: -Feature IDs are unique across all kinds. A class can have one registration kind. A JSON field is -unique per attachment target, including existing host fields. The reference registry takes -reserved host fields explicitly; it cannot discover them from an engine it does not depend on. -Placement modifiers attach only to object-placement settings. Geometry may be declared at -biome/region/dimension scope, with host composition deciding which placement uses it. +- 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. -`ModuleRegistry` validates a registration before changing its catalog. At the end of collection, -`freeze()` prevents further mutation and exposes deterministic catalog lists. Module discovery -itself remains host-owned. The host must reject duplicate module identities and incompatible -API versions before publishing a pack runtime, and discard a registry build when a module -callback fails. Addon classloading must not expose engine implementation packages as public types. +The result depends only on ids and edges, never on install 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". -Host decoding preserves existing JSON field names and constructor/field defaults. It must invoke -constructors, reject invalid values with resource/field diagnostics and validate required fields, -numeric constraints, nested settings, lists, enums and typed resource references. Schema generation -uses the same metadata and resource registries. Existing registry-list annotations require -explicit metadata adapters during migration; the draft does not reproduce every old annotation. +### Block passes -`OptionsMetadata` currently describes reflected fields and checks annotation bounds. It is not a -decoder or complete schema implementation. No JSON library has been added to the public project. +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. -## Identity, order and applicability +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. -There are four different identities: +### Outputs -| Identity | Purpose | +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. + +### Activation + +The graph is resolved once per pack load. Activation is decided per invocation: + +1. The host passes `ConfiguredSettings`, at most one value per settings type, for the placement + or chunk. Merging dimension, region, biome and placement declarations is host policy. +2. The invocation looks up each distinct `when` type once. +3. One pass in resolved order marks a stage active when its settings are present (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. The settings value is passed to the body as its second argument. + +For chunks, activation is per chunk. A stage that varies inside the chunk still reads +`ctx.settings().at(...)` per position. + +### 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 + +`PlacementRunner.place(request, edit, inputs, settings)` 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. Stages receive a buffered +`PlacementAccess` view of the edit without commit or close, and it expires with the attempt. + +All stages of one attempt share the host's `PlacementContext`, including one RNG, consumed in +resolved order. Adding a module therefore changes what later stages draw unless modules derive +their own streams. The example ports use the shared RNG like Iris does today. + +## Chunk invocations + +`ChunkRunner.generate(inputs, settings)` runs active chunk stages once each in resolved order. +`GenerationContext.hunk(type)` returns the host-owned local volume of that value type, shared by +all stages of the invocation. Hunk coordinates are local; samples and mantle coordinates are +world blocks. The runner does no neighbor scheduling or rollback. A failed invocation must stop +the host from publishing the chunk. + +## Settings, geometry and storage + +Settings types implement `IrisFeature` and carry `@Feature` (namespaced id, display name, JSON +field, attachment targets). `when(type)` validates the annotation while the module installs. +`LoadedModules.load` catalogs those types with geometry generator settings and rejects duplicate +ids and JSON field collisions per attachment target, including reserved host fields. +`OptionsMetadata` reads field metadata; it does not decode JSON. + +`GeneratedObject` is sparse, immutable local geometry with bounds, an anchor, sorted blocks, +optional block entity payloads and markers. `ObjectGenerator` produces it from settings and an +RNG. `ObjectTransformer` is host-owned. + +The mantle contracts are unchanged: namespaced typed keys, versioned codecs, generation and +persistent lifetimes, ordered sparse visits and buffered edits. Only owners register a layer. +Unknown persisted layers must be preserved or fail explicitly. + +## Not implemented + +- Iris host wiring: module discovery and version gating, JSON decoding and validation, schema + generation, resource loaders, platform block adapters, storage and codecs. +- Reach. The old per-modifier `writeRadius` and `mantleRadius` are gone with the modifiers. The + host must prepare the whole area a pipeline may touch. Per-stage reach is an open question. +- Legacy random compatibility. Seed offsets and draw order must be matched by the adapter where + existing worlds are promised to stay the same. +- Real feature ports. The test examples are simplified slices, not parity ports. + +## Feature-family migration map + +This is an inventory of where each existing family should land, not a claim that it is ported. + +| Existing family | Target | | --- | --- | -| Module identity | Discovery, diagnostics and compatibility | -| Feature identity | Configuration registration and schema | -| Modifier identity | Dependency graph vertex shared by its configured occurrences | -| Occurrence identity | A specific configuration in one pack snapshot | - -Modifier IDs are stable and namespaced. Repeated configured instances must use the same -implementation and dependency declaration; generation instances must also agree on output type. -Their settings and reach may differ. Host occurrence IDs must be stable for the same pack input, -for example an owner ID plus the configuration path/index. - -`Dependencies` declares required predecessors and optional before/after edges. `GenerationPlan` -resolves the complete chunk graph across output types; `PlacementPipeline` resolves a separate -placement graph. Required dependencies never install or activate a feature. Self-dependencies, -missing required vertices, cycles and conflicting identities fail before generation. Ready -vertices and repeated occurrences use lexical order, independent of module discovery. - -Applicability is host-owned. Resolving a required modifier ID does not promise that its configured -feature writes at every position. An executor dispatches only the occurrences applicable to the -current invocation, respecting the resolved ordering. Per-position reads come through -`FeatureSettings.at(type, target, worldPosition)`; target declarations stay separate and results -follow pack declaration order after target-local inheritance rules. The host must define legacy -list combination and override policies explicitly, not assume one universal precedence. - -The host bridges current engine lifecycle barriers into the graph. For the current overworld, -that includes biome/Mantle/terrain preparation followed by carving, post-processing, floating -terrain, deposits, Mantle insertion, decoration, floating decoration, perfection and custom-block -recording. Moving ore work out of terrain must preserve its original replacement/random behavior. -A graph that violates engine barriers is a pack-load error, even if it is topologically acyclic. - -## Invocation inputs and concurrency - -Factories snapshot settings. No invocation views, scratch data or mutable RNG state belong on a -configured feature implementation. Different hunks/placements may invoke it concurrently. - -`InvocationContext` exposes world seed, one pack snapshot and a dedicated RNG. The host derives -streams from stable identities and invocation/variant position, not discovery or scheduler order. -An Iris compatibility adapter must preserve legacy seed offsets, random consumption and iteration -order where existing world output is promised; merely choosing a new deterministic RNG is not -compatibility. Objects may cache immutable variants, never the RNG or invocation context. - -`GenerationContext` adds world-block origin, terrain/settings views and invocation-scoped Mantle. -Hunk coordinates are local; samples and storage coordinates are world blocks. A dense block cell -corresponds to one world block. Native biome grids or coarser density grids require an explicit -adapter; do not reinterpret a Hunk index as a different unit silently. - -`TerrainSampler` is the prepared terrain field, including surface height, fluid height, slope and -pack biome identity. `BlockView` is prepared generation blocks, not live-world access. Placement -context block reads refer to the pre-placement state; hook access reads buffered changes. -All prepared views have explicit bounds/lifetimes. Unsupported access fails rather than clipping. - -## Resource and platform adapters - -`ResourceId` parses explicit namespaced identities; `ResourceKey` states the public value type. -`PackResources` resolves resources within one immutable loaded snapshot. A known ID requested -with the wrong type is an error. Missing and malformed resources are different states. Imports -and caches are snapshot-scoped; every reload produces a different snapshot ID. - -`BlockState` is an immutable description with value equality and sorted canonical properties. -Construction validates syntax. `BlockRegistry` resolves availability/valid properties and cached -traits, tags and attachment checks. No native handle escapes. Custom block identities remain -expressible; the host handles their generation placeholders and deferred application. -`BlockPalette` and `NoiseSampler` are resource types, not engine services reconstructed by addons. - -Block entity payloads have a format ID, version and defensive byte copies. Adapters interpret -them, enforce size/compatibility limits and reject unsupported versions. Markers carry an ID and -immutable attributes; registry owners define their meaning. Mutable NBT/Bukkit objects must not -appear in reusable geometry or public feature settings. - -## Geometry and transforms - -`GeneratedObject` contains local bounds, a local anchor, sorted sparse blocks, optional block -entity payloads and markers. Entries must lie inside bounds; duplicate block positions fail. -An anchor can lie outside geometry. Missing entries do not mean explicit air. Declaration order -is preserved for markers sharing a position. Geometry has no world coordinates or placement state. - -A configured `ObjectGenerator` receives only resources and a geometry invocation RNG and returns -immutable geometry. Terrain-aware adaptation happens in placement. The host controls variant -selection and cache keys, which must include the pack snapshot and relevant settings/seed. - -`ObjectTransformer` is host-owned. It updates geometry bounds/anchor, block orientation, markers -and block entities for an `ObjectTransform`. The transform specifies mirrors, positive per-axis -scale and rotations around the anchor; rasterization/interpolation is adapter-owned. Unsupported -transformations fail explicitly. Noise-based object warping/shaping needs a later typed transform -extension when the placement port demonstrates its requirements. - -## Placement lifecycle and ownership - -`PlacementRequest` aligns local anchor to world anchor with checked arithmetic. Geometry has -already been transformed; a prepare hook may replace it via the host transformer. It must keep -the same attempt ID. The host supplies enough prepared space for supported changes; unsupported -moves fail rather than silently cropping the object. - -The reference pipeline executes these barriers: - -| Barrier | What modules can do | -| --- | --- | -| Prepare | Return a new request or reject the attempt | -| Map blocks | Replace/skip individual proposed world-space blocks | -| Validate | Inspect the complete proposed plan and pre-placement views; no mutation | -| Before placement | Buffer boring or preparation after all validation succeeds | -| Object writes | Host buffers mapped blocks, block entities and markers | -| After placement | Buffer foundation/vacuum/snow/metadata work using overlay and accepted writes | -| Commit | Host publishes the entire edit once | - -`PlacementPlan.writtenBounds()` measures accepted object writes, not original geometry or later -finishing writes. An empty block plan has no written bounds. Markers are included in the attempt -but tracked separately. Skipped blocks cannot contribute falsely to a vacuum footprint. - -Hook `PlacementAccess` has no commit/close methods. The reference runner supplies a restricted -view covering the final object's footprint plus declared horizontal reach and authorized vertical -bounds, including a similarly restricted Mantle view. Nested Mantle edits are forbidden because -placement already owns the transaction. Retaining any view past completion is invalid. - -Host intrinsic validation covers collision/protection/support/material/payload policies. Every -buffered hook write must also satisfy host bounds and platform validation. Exceptions and -rejections close without commit. Commit is atomic across block/entity/marker/Mantle changes in -generation storage. This stronger guarantee still needs an Iris storage adapter; it is not -inherited automatically from existing placement behavior and does not imply disk/live-world -atomicity. The host aborts chunk publication when any generation work fails. - -## Typed storage and neighbor scheduling - -The Mantle interface retains namespaced typed keys, codecs, generation/persistent lifetime, -ordered sparse visits, world bounds and buffered edits. Only owners register layer keys. Known -type mismatches and duplicate IDs fail. Generation-only values still need codecs for unloading. -Missing reads allocate nothing. Unknown persisted layers are preserved or cause explicit failure. - -Chunk modifiers declare `mantleRadius`; placement modifiers declare `writeRadius`. The host -prepares bounds, relevant predecessor work and neighbors before execution and serializes -intersecting write areas. No dependency edge does not imply safe concurrent writes. Cleanup -waits for every consumer, including neighboring generation. Native chunk/section storage and -retention flags remain implementation details. - -## Complete feature-family migration map - -Each row names the existing feature family and where it fits. This is a migration inventory, -not a claim that those features are ported or that every interface below already exists. - -| Existing family | Target interface/composition | Readiness | -| --- | --- | --- | -| Surface, ceiling, shore, sea-surface, sea-floor and floating decoration | Chunk modifiers + palette/support/sampling adapters | Core contracts exist; real decorators still engine-dependent | -| Slab/wall/snow post-processing; unsupported foliage cleanup; ore hiding | Chunk modifiers + block traits/properties + neighbor views | Contracts exist; finish ports pending | -| Custom block recording and deferred application | Chunk modifier + persistent typed layers + host content adapter | Layer/block contracts exist; deferred adapter pending | -| Surface/underground ores and deposits/variants/shapes/scopes | Chunk modifiers + noise/palette resources + effective settings | Core contracts exist; precedence and parity port pending | -| Object selection, chance/density, transforms and all height/placement modes | Geometry resources + placement composition | Core contracts exist; real placement modes pending | -| Stilt, eroded/organic support, ceiling hang, vacuum variants, paint/floating | Placement prepare/map/validate/before/after hooks | Reference foundation proves hooks; original algorithms pending | -| Slope/support/limits/collision/protection, boring/melding/replacement/water/snow | Placement policies and hooks + prepared block view | Contracts exist; policy/algorithm ports pending | -| Object markers, tile data, tree/loot metadata | Object metadata + placement transaction + typed storage | Value contracts exist; codecs/consumers pending | -| Procedural trees, crystals, fungi, coral, formations and ruins | Object generators returning sparse geometry | Reference column proves composition; six real generators pending | -| Cave density profiles/modules, entries, biome blending and surface openings | Chunk planning/application + noise/sampling + typed carve layers | Core contracts exist; typed carve payloads and real ports pending | -| Cave fluids/lava, floor/ceiling palettes, decorations and cave objects | Ordered carve/placement composition + fluid/support layers | Core contracts exist; payloads and coordination pending | -| Floating child biomes/islands, palettes, merging/overrides and inverted objects | Terrain/biome sampling + chunk/placement composition | Core contracts exist; provider/algorithm ports pending | -| Structure distribution/anchors/Y bands, carving, foundations/stilts and pieces | Structure assembly produces placement plans; host schedules writes | Geometry/placement exist; assembly interface pending | -| Jigsaw pools/connectors/rules/themes/workcells/branch policies | Typed structure resources + host-independent assembly interface | Public assembly/resource models pending | -| Imported/native structures/features, frequency and ownership/protection | Host native-generation policy adapter + typed ownership records | Policy interface/adapter pending | -| Terrain generators/layers/palettes/fluids/bedrock, interpolation/overlays | Terrain providers + ordered chunk modifiers | Consumption interfaces exist; provider registration pending | -| Region/biome selection, rarity/children/scatter/custom derivatives | Biome providers + platform biome writer | Sampling exists; provider/writer interfaces pending | -| Overworld/islands/enclosure/superflat modes and upper dimensions | Host composition of registered terrain/biome/generation providers | Composition interface/adapter pending | -| Image height/color maps, masks/transforms/bindings | Immutable sampled resources composed into providers | Generic resource seam exists; image resource models pending | -| Noise styles/expressions and pack mod injection/replacement | Immutable noise resources + pack compilation transformations | Sampling exists; loader/transform interface pending | -| Entity/marker spawning, ambient effects, block drops and loot | Runtime registrations + scoped host actions/events | Separate runtime interface pending | -| Marker commands, tree growth/replacement/felling, time/weather | Runtime registrations + platform-specific action adapters | Separate runtime interface pending | -| World/pregen lifecycle, queries, locating and studio/editor tooling | Bridge existing integrations; consume public resources/providers | Integration/tooling adapters pending | +| Surface, ceiling, shore, sea and floating decoration | Chunk stages + palette/support/sampling resources | +| Slab/wall/snow post-processing, foliage cleanup, ore hiding | Chunk stages + block traits and neighbor views | +| Custom block recording and deferred application | Chunk stage + persistent typed layers + host content adapter | +| Ores and deposits | Chunk stages + noise/palette resources + configured settings | +| Object selection, transforms, height and placement modes | Geometry + placement stages per mode module | +| Stilt, erosion, ceiling hang, vacuum, paint, floating | Placement modules with block and invocation stages | +| Slope, support, limits, collision, protection, bore, meld, snow | Placement stages that reject or write | +| Markers, tile data, tree and loot metadata | Object metadata + placement edit + typed storage | +| Procedural trees, crystals, fungi, coral, ruins | Object generators returning sparse geometry | +| Cave profiles, carving, cave fluids and decoration | Chunk stages + typed carve layers | +| Floating islands and child biomes | Terrain/biome sampling + chunk and placement stages | +| Structures, jigsaw pools and foundations | Structure assembly producing placement requests | +| Imported/native structures and ownership | Host native-generation policy adapter | +| Terrain layers, fluids, bedrock, interpolation | Terrain providers + chunk stages | +| Region/biome selection | Biome providers + platform biome writer | +| Image maps, noise expressions, pack injection | Compiled immutable pack resources | +| Spawning, effects, drops, loot, tree growth, commands | Separate runtime family with host actions | +| World lifecycle, pregen, locate, studio tooling | Bridge existing integrations | ## Provider and runtime direction -These are design decisions for the next ports, not speculative stub Java methods: +- Terrain and biome providers should return sampled fields and identities. The host adapts them + to native chunk and biome formats. They must not own worlds or ticks. +- Structure assembly should consume immutable resources and return placement requests. The host + owns reach, scheduling and native-generation gates. +- Image maps and expressions should compile into pack resources before a snapshot is published. +- Runtime features need their own family with read-only event inputs and requested actions that + host adapters perform on the right scheduler. Generation hunks, RNGs and views never leak into + runtime work. -- Terrain and biome providers should return sampled fields/resolved identities. The host compiles - composition and adapts outputs to native chunk/biome formats. They must not own worlds or ticks. -- Structure assembly should consume immutable typed resources and return immutable placement - intents/results. The host owns reach preparation, scheduling, native-generation gates and edits. -- Image maps and expressions should be compiled pack resources reused by providers/features. - Pack transformations run during compilation, before a runtime snapshot is published. -- Runtime features need their own registration/execution family: read-only event/context inputs - and requested effects/actions, performed by host adapters on the correct platform scheduler. - Generation hunks/RNG/views must never be reused for entity spawning or live-world edits. -- Existing terrain-query, world lifecycle, pregeneration and tree integration interfaces should - be bridged and consolidated where useful, not duplicated just to fit the new package layout. +Exact signatures for these families should follow their first real port. -Exact method signatures for these families should be settled against their first real port. -The draft establishes how they compose without prematurely copying the full Engine interface. +## Readiness gate -## Implementation and validation gates - -Implemented: public contracts listed above, registry/catalog validation, dependency planner, -bounded reference Hunk, placement orchestration/restricted views and three example behaviors. -Not implemented: discovery/version gating, JSON/schema loaders, resource/platform/storage adapters, -neighbor scheduler, Iris lifecycle bridging, provider/runtime registrations or real Iris feature ports. - -The API tests exercise registry conflicts, ordering/cycles, immutability, checked coordinates, -placement validation/rejection, commit failure, hook reach/lifetime and all-or-nothing orchestration -against a test edit. The example tests exercise neutral block output, settings snapshots, -deterministic geometry, negative-height/boundary placement and foundation failure rollback. -Those test adapters do not prove production storage atomicity or Minecraft integration. - -A feature is ready to replace its legacy implementation only when existing pack JSON works, -representative seeds match promised output, negative heights/chunk boundaries pass, concurrent -execution is deterministic, reload caches expire and failures cannot publish partial chunks. -Until then keep the legacy path available and explicitly select one implementation per feature. +A feature replaces its legacy implementation only when existing pack JSON works, representative +seeds match promised output, negative heights and chunk boundaries pass, concurrent execution is +deterministic, reload caches expire and failures cannot publish partial chunks. Until then the +legacy path stays available. diff --git a/README.md b/README.md index 4cbeefd4e..e0f2a4468 100644 --- a/README.md +++ b/README.md @@ -1,153 +1,92 @@ # IrisApi Java 25 contracts for Iris modules, with a small host-independent reference implementation. -Main code depends only on the JDK. No Bukkit, Iris implementation, Gson, or Lombok types appear -in the public contracts. The draft interfaces may change before a stable release. +Main code depends only on the JDK. No Bukkit, Iris implementation, Gson or Lombok types appear +in the public contracts. Nothing here is stable yet. -The design-first migration plan is in [DESIGN.md](DESIGN.md). Existing Iris features have not -been modularized or wired into this project. +[DESIGN.md](DESIGN.md) explains the model and its rules. [CONTRACTS.md](CONTRACTS.md) lists +what the Iris host adapter still has to provide. Existing Iris features are not ported or wired +into this project; the test sources contain example ports only. -## Three kinds of executable feature +## Modules own their stages + +There are no host-defined hooks or phases. A module declares stages as constants and defines +them in `install`. Other modules order themselves against those constants. ```java -registry.register(DeepStoneFeature.class, BlockState.class, DeepStoneModifier::new); -registry.registerObject(StoneColumnFeature.class, StoneColumnGenerator::new); -registry.registerPlacement(FoundationFeature.class, FoundationModifier::new); +public final class MossModule implements IrisModule { + public static final PlacementStage SPREAD = Stage.placement("example:moss/spread"); + + public ModuleInfo info() { return ModuleInfo.of("example:moss", "1.0.0"); } + + public void install(StageGraph graph) { + graph.define(SPREAD) + .when(MossSettings.class) // only where a pack configures moss + .requires(AnchorModule.HEIGHT, BlocksModule.COMPLETE) + .softAfter(StageRef.of("iris:snow/finish")) // ordering only, if snow is installed + .run((ctx, moss) -> spread(ctx.output(AnchorModule.HEIGHT), moss)); + } +} ``` -Each settings class implements `IrisFeature` and declares `@Feature`: a namespaced feature ID, -a display name, a JSON field and its attachment targets. Constructor/field initializers retain -defaults. Factories accept only the configured settings and snapshot everything they need. +- `Stage.placement`, `Stage.placementBlock` and `Stage.chunk` create stages for the placement + pipeline (once per attempt), the placement pipeline (once per object block) and the chunk + pipeline. Pass an output class to give a stage a typed output. +- A stage id uses the namespace of the module that defines it. Defining an id twice fails. +- `requires(...)` takes another module's stage constant. It orders, makes the output readable + and deactivates this stage wherever the requirement is inactive. +- `softAfter` and `softBefore` take ids and only order. There is no hard "before". +- `run(...)` ends a stage without output, `produce(...)` a stage with output and + `accumulate(initial, collector)` a block stage whose accumulator becomes its output. +- `ctx.output(stage)` works only for stages the current stage transitively requires. -| Kind | Interface | Result | -| --- | --- | --- | -| Chunk generation | `GenerationModifier` | Edits an invocation-owned local `Hunk` | -| Procedural geometry | `ObjectGenerator` | Returns an immutable sparse `GeneratedObject` | -| Object placement | `PlacementModifier` | Prepares, validates and modifies one buffered world-space placement | +`IrisModule.register(FeatureRegistry)` stays for non-stage contributions: geometry generators +and mantle layers. -Placement features attach only to `OBJECT_PLACEMENT`. Chunk and geometry features may attach -to any declared supported target. Configuration identity is separate from modifier ordering -identity. Host settings resolution determines where each configured occurrence applies. - -See the sibling [IrisModule sources and build entry](../IrisModule/README.md) for the current built-in module. - -## Resources, blocks and sampling - -- `ResourceId` requires an explicit namespace. `ResourceKey` pairs it with a public type. -- `PackResources` exposes immutable resources and a block registry from one pack snapshot. - Reload always changes `snapshotId`; caches must not survive across it. -- `BlockState` has value equality and canonical, sorted property keys. It describes a state; - `BlockRegistry` checks platform availability/properties and supplies traits, tags and support. -- `BlockPalette` and `NoiseSampler` are reusable typed resources. The host owns their loading. -- `TerrainSampler` reads the prepared terrain field and pack biome identity, not current edits. -- `BlockView` reads prepared world-space generation blocks. Empty space is an air state. -- `FeatureSettings` looks up applicable configured settings by target and world position. - Dimension, region, biome and placement declarations remain distinct; no implicit merging. - -All invocation views expire when the invocation ends. No native platform object or live-world -handle is exposed. Modifiers must not retain views or start detached tasks using them. - -## Reference registry and ordering +## Host side ```java -var registry = new ModuleRegistry(reservedHostFields); -module.register(registry); -var catalog = registry.freeze(); -var registration = catalog.generation(DeepStoneFeature.class, BlockState.class); -var configured = registration.configure(occurrenceId, decodedFeature); -var plan = GenerationPlan.resolve(configuredModifiersIncludingHostSteps); -plan.execute(host::execute); +var loaded = LoadedModules.load(acceptedModules, reservedHostFields); +System.out.println(loaded.placement().describe()); + +var placer = new PlacementRunner(loaded.placement()); +PlacementOutcome outcome = placer.place(request, edit, inputs, ConfiguredSettings.of(stilt, snow)); + +new ChunkRunner(loaded.chunk()).generate(generationContext, chunkSettings); ``` -`ModuleRegistry` checks annotated concrete feature types, metadata, duplicate IDs, JSON field -collisions across feature kinds, placement targets, output types and mantle registrations. -A failed individual registration leaves the registry unchanged. Registration ends at `freeze()`; -the resulting catalog is immutable. If a module callback fails, discard the whole registry build. +`LoadedModules.load` installs every module, catalogs the settings types named in `when(...)` +together with geometry and mantle registrations, and resolves both pipelines. Graph errors +(missing requirement, cycle, foreign namespace, duplicate, cross-pipeline edge) fail here, at +pack load. `describe()` prints the order, owners, edge kinds, fused block passes and the stage +pairs that have no path between them. -`GenerationPlan` and `PlacementPipeline` resolve immutable dependency declarations. Missing -requirements, self-edges, cycles, duplicate occurrences and conflicting same-ID implementations -fail at pack load. Ready identities use lexical order; repeated configured instances use lexical -occurrence order. Repeated instances must agree on dependencies and generation output type. -Reach may vary per instance. Dependencies and modifier IDs require namespaces. +`PlacementRunner` owns the edit for one attempt. It commits once if no stage rejects or throws +and closes the edit in every case. Stages get buffered `PlacementAccess` without commit rights. -```java -return Dependencies.requires("iris:terrain") - .afterIfPresent("example:caves") - .beforeIfPresent("iris:ores"); -``` +## Values that stay -Required declarations do not activate features. Optional edges apply only when the identity -exists. Independent modifiers are not automatically safe to run in parallel. Chunk generation -and placement have separate dependency graphs. The host bridges its engine lifecycle into the -chunk graph and rejects edges that conflict with that lifecycle. +- `ResourceId` requires a namespace. `ResourceKey` pairs it with a public type. +- `PackResources` serves one immutable pack snapshot; caches must not survive a reload. +- `BlockState` has value equality and sorted properties; `BlockRegistry` checks it against the + platform. `BlockPalette` and `NoiseSampler` are typed resources. +- `GeneratedObject` is sparse, immutable local geometry. `PlacementRequest` aligns its anchor + with a world position using checked arithmetic. +- `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 and `OptionsMetadata` describe settings. -`GenerationPlan` orders across output types but delegates execution to the host, which prepares -and releases the correctly typed output/context for each applicable occurrence. It does not -implement chunk scheduling or rollback. A failed invocation must prevent chunk publication. -`ArrayHunk` is a small checked dense-volume reference adapter. - -## Geometry and placement - -`GeneratedObject` contains local bounds, an anchor, sorted sparse blocks, optional immutable -block entity payloads and ordered markers. Missing sparse entries and explicit air blocks are -different. The host owns object transforms, property orientation, rasterization and variant caches. - -`PlacementRequest` aligns the object's local anchor with a world anchor. Its arithmetic is checked; -maxima are exclusive. `PlacementPlan` contains proposed world-space writes after block mapping. -Its `writtenBounds()` covers those object block writes, excluding skipped blocks and markers. -It does not include additional writes made by finishing hooks. - -`PlacementPipeline` executes this lifecycle: - -1. Prepare all configured modifiers; any rejection stops the attempt. -2. Map or skip each candidate block; build the complete proposed plan. -3. Check bounds and run host/modifier validation before buffering mutations. -4. Run `beforePlace` hooks for boring or other preparation. -5. Buffer object blocks, block entity data and markers. -6. Run `afterPlace` hooks for foundations, vacuum, snow or other finishing. -7. Commit once; close on success, rejection or exception. - -The host supplies a fresh `PlacementEdit`, correctly prepared bounds, serialized storage, -per-occurrence contexts/RNGs, and read-only intrinsic validation. Hook `PlacementAccess` exposes -an overlay bounded to the footprint plus declared horizontal reach, without commit/close rights. -Its mantle view has the same restricted bounds and forbids nested edits. All buffered mutations -must be validated by the host adapter, including writes from hooks. - -Commit publishes block/entity/marker/mantle changes together or leaves parent generation storage -unchanged. This is a contract for a future storage adapter; the reference runner alone cannot -provide atomic storage. It is not a live-world, disk or crash-recovery guarantee. - -## Mantle - -The existing typed mantle contracts remain: namespaced keys, registered types, versioned codecs, -world-space bounds, ordered sparse visits, generation/persistent lifetimes and buffered edits. -Only layer owners register shared keys; consumers use their definitions. Generation-only layers -also require codecs. Missing reads must not allocate storage. Unknown persisted layers must be -preserved or cause an explicit failure, never silent loss. - -`GenerationModifier.mantleRadius()` and `PlacementModifier.writeRadius()` declare horizontal reach. -The host prepares bounds and predecessor work and excludes competing writes. Generation cleanup -waits for all consumers, including neighboring chunks. Mantle writes do not implicitly edit a Hunk. - -## Remaining host work - -Module discovery/version compatibility, JSON decoding and value validation, schema generation, -resource loaders, effective settings/biome resolution, legacy random compatibility, native block -adapters, storage/codecs, cross-chunk scheduling, engine lifecycle bridging and Iris feature ports -are not implemented here. Terrain/biome provider and runtime extension designs are documented -in [DESIGN.md](DESIGN.md); they are not yet Java interfaces. - -`OptionsMetadata` inspects inherited/private fields, skips static/transient state and validates -annotation bounds. It does not instantiate settings, extract defaults or validate supplied values. -A decoder must invoke constructors and reject unsupported metadata/types explicitly. +Invocation views expire when the invocation ends. Stage bodies are shared by concurrent +invocations and must not keep views or mutable state. ## Validation ```sh -./gradlew check jar sourcesJar +./gradlew check ``` -Tests cover real registry/factory binding, conflicts, deterministic ordering, graph errors, -immutable values, checked coordinates and placement rejection/failure/commit behavior. The -example module adds generated geometry and foundation composition tests against a test host. -There is no running Minecraft integration or production storage adapter in these tests. +The tests cover graph resolution and every error path, fusion, activation cascade, outputs, +rejection and rollback, and install-order determinism. The example 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. There is +no Minecraft integration or production storage in these tests.