commit 9043d93fbd50aa5e25c283f3c5659077cea9006c Author: piexel Date: Mon Oct 5 17:01:18 2026 +0200 Baseline IrisApi draft before stage-graph redesign diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..e81a89f7a --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.gradle/ +build/ +.idea/ +*.iml diff --git a/CONTRACTS.md b/CONTRACTS.md new file mode 100644 index 000000000..5523633ee --- /dev/null +++ b/CONTRACTS.md @@ -0,0 +1,40 @@ +# Migration requirements + +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. + +## Adopted seams + +| Requirement | Current 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` | +| 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 | + +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. + +## 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. + +## Later extension families + +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. diff --git a/DESIGN.md b/DESIGN.md new file mode 100644 index 000000000..6e9b3f59f --- /dev/null +++ b/DESIGN.md @@ -0,0 +1,291 @@ +# Iris API design and migration contract + +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. + +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. + +## 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. + +```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 +``` + +The three execution interfaces are deliberately distinct: + +- 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 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. + +## Registration and configuration + +`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. + +The current registration interface has four operations: + +```java +registry.register(featureType, outputType, modifierFactory); +registry.registerObject(featureType, geometryFactory); +registry.registerPlacement(featureType, placementFactory); +registry.registerMantle(layerKey, lifetime, codec); +``` + +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. + +`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. + +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. + +`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. + +## Identity, order and applicability + +There are four different identities: + +| Identity | Purpose | +| --- | --- | +| 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 | + +## 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/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 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. + +## 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. diff --git a/README.md b/README.md new file mode 100644 index 000000000..4cbeefd4e --- /dev/null +++ b/README.md @@ -0,0 +1,153 @@ +# 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. + +The design-first migration plan is in [DESIGN.md](DESIGN.md). Existing Iris features have not +been modularized or wired into this project. + +## Three kinds of executable feature + +```java +registry.register(DeepStoneFeature.class, BlockState.class, DeepStoneModifier::new); +registry.registerObject(StoneColumnFeature.class, StoneColumnGenerator::new); +registry.registerPlacement(FoundationFeature.class, FoundationModifier::new); +``` + +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. + +| 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 | + +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 + +```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); +``` + +`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. + +`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. + +```java +return Dependencies.requires("iris:terrain") + .afterIfPresent("example:caves") + .beforeIfPresent("iris:ores"); +``` + +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. + +`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. + +## Validation + +```sh +./gradlew check jar sourcesJar +``` + +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. diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 000000000..12daa96c9 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,25 @@ +plugins { + id("java-library") +} + +group = "com.volmit" +version = "1.0-SNAPSHOT" + +java { + toolchain.languageVersion.set(JavaLanguageVersion.of(25)) + withSourcesJar() +} + +repositories { + mavenCentral() +} + +dependencies { + testImplementation(platform("org.junit:junit-bom:6.0.0")) + testImplementation("org.junit.jupiter:junit-jupiter") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") +} + +tasks.test { + useJUnitPlatform() +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..b1b8ef56b Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..eb84db68d --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,9 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.0-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 000000000..249efbb03 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 000000000..a51ec4f58 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,82 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 000000000..a15e5bded --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "IrisApi" \ No newline at end of file diff --git a/src/main/java/com/volmit/FeatureAttachment.java b/src/main/java/com/volmit/FeatureAttachment.java new file mode 100644 index 000000000..42d7130bf --- /dev/null +++ b/src/main/java/com/volmit/FeatureAttachment.java @@ -0,0 +1,16 @@ +package com.volmit; + +import java.util.Objects; +import java.util.Set; + +/** Maps settings to an ordinary existing JSON field, without an extension wrapper. */ +public record FeatureAttachment(String field, Set targets) { + public enum Target { DIMENSION, REGION, BIOME, OBJECT_PLACEMENT } + + public FeatureAttachment { + Objects.requireNonNull(field, "field"); + if (field.isBlank()) throw new IllegalArgumentException("Field must not be blank"); + targets = Set.copyOf(targets); + if (targets.isEmpty()) throw new IllegalArgumentException("At least one target is required"); + } +} diff --git a/src/main/java/com/volmit/FeatureRegistry.java b/src/main/java/com/volmit/FeatureRegistry.java new file mode 100644 index 000000000..a2174b341 --- /dev/null +++ b/src/main/java/com/volmit/FeatureRegistry.java @@ -0,0 +1,30 @@ +package com.volmit; + +import com.volmit.generation.ModifierFactory; +import com.volmit.mantle.MantleCodec; +import com.volmit.mantle.MantleKey; +import com.volmit.mantle.MantleLifetime; +import com.volmit.object.ObjectGeneratorFactory; +import com.volmit.placement.PlacementModifierFactory; + +/** Host implementation collects registrations before loading pack configuration. + * Feature IDs must be unique. JSON fields must be unique per attachment target. + * Modifiers own their IDs and dependency declarations, independently of feature IDs. + * All configured instances of a modifier follow the same ordering. + */ +public interface FeatureRegistry { + /** Registers a layer before pack loading. Null arguments throw NullPointerException; + * duplicate IDs and negative codec versions throw IllegalArgumentException. + * Only the owner registers a shared layer; consumers refer to its key. The host must + * preserve unknown persisted layers or fail explicitly, never silently discard them. + * GENERATION layers also require codecs. + */ + void registerMantle(MantleKey key, MantleLifetime lifetime, MantleCodec codec); + + void register(Class featureType, + Class outputType, ModifierFactory factory); + + void registerObject(Class featureType, ObjectGeneratorFactory factory); + + void registerPlacement(Class featureType, PlacementModifierFactory factory); +} diff --git a/src/main/java/com/volmit/IrisFeature.java b/src/main/java/com/volmit/IrisFeature.java new file mode 100644 index 000000000..8a668a668 --- /dev/null +++ b/src/main/java/com/volmit/IrisFeature.java @@ -0,0 +1,6 @@ +package com.volmit; + +/** A configured feature instance. @Feature declares identity and attachment; + * annotated fields define settings. Each configuration occurrence is decoded separately. + */ +public interface IrisFeature {} diff --git a/src/main/java/com/volmit/IrisModule.java b/src/main/java/com/volmit/IrisModule.java new file mode 100644 index 000000000..33c48820f --- /dev/null +++ b/src/main/java/com/volmit/IrisModule.java @@ -0,0 +1,10 @@ +package com.volmit; + +public interface IrisModule { + + String name(); + + String displayVersion(); + /** Called during registration, before settings are decoded or generation starts. */ + void register(FeatureRegistry registry); +} diff --git a/src/main/java/com/volmit/block/BlockFace.java b/src/main/java/com/volmit/block/BlockFace.java new file mode 100644 index 000000000..7e16105ce --- /dev/null +++ b/src/main/java/com/volmit/block/BlockFace.java @@ -0,0 +1,3 @@ +package com.volmit.block; + +public enum BlockFace { UP, DOWN, NORTH, SOUTH, EAST, WEST } diff --git a/src/main/java/com/volmit/block/BlockPalette.java b/src/main/java/com/volmit/block/BlockPalette.java new file mode 100644 index 000000000..e21c1e159 --- /dev/null +++ b/src/main/java/com/volmit/block/BlockPalette.java @@ -0,0 +1,11 @@ +package com.volmit.block; + +import java.util.random.RandomGenerator; + +/** Resolved, immutable palette. Coordinates are world blocks; selection uses only this RNG. + * An empty/unresolvable palette is a pack-load error. Implementations must support concurrent calls. + */ +@FunctionalInterface +public interface BlockPalette { + BlockState select(int worldX, int worldY, int worldZ, RandomGenerator random); +} diff --git a/src/main/java/com/volmit/block/BlockRegistry.java b/src/main/java/com/volmit/block/BlockRegistry.java new file mode 100644 index 000000000..1a6147c76 --- /dev/null +++ b/src/main/java/com/volmit/block/BlockRegistry.java @@ -0,0 +1,16 @@ +package com.volmit.block; + +import com.volmit.resource.ResourceId; + +/** Host adapter for resolved states and cached behavior. No native platform objects escape. + * Unknown materials, unsupported properties, and malformed states throw IllegalArgumentException. + * Methods are safe for concurrent generation calls; predicates must not read the live world. + */ +public interface BlockRegistry { + BlockState resolve(String key); + default BlockState resolve(BlockState state) { return resolve(state.key()); } + boolean hasTrait(BlockState state, BlockTrait trait); + boolean inTag(BlockState state, ResourceId tag); + /** Whether state can attach to the specified face of support, ignoring other neighbors. */ + boolean canAttach(BlockState state, BlockState support, BlockFace face); +} diff --git a/src/main/java/com/volmit/block/BlockState.java b/src/main/java/com/volmit/block/BlockState.java new file mode 100644 index 000000000..8fa6303ce --- /dev/null +++ b/src/main/java/com/volmit/block/BlockState.java @@ -0,0 +1,43 @@ +package com.volmit.block; + +import com.volmit.resource.ResourceId; +import java.util.Collections; +import java.util.Map; +import java.util.Objects; +import java.util.TreeMap; +import java.util.stream.Collectors; + +/** Immutable, platform-neutral block description with value equality. + * Construction validates syntax, not platform availability or valid material properties. + * Resolve through BlockRegistry before writing. Custom-content IDs are allowed. + */ +public record BlockState(ResourceId material, Map properties) { + public BlockState { + Objects.requireNonNull(material, "material"); + var copy = new TreeMap(); + properties.forEach((name, value) -> { + if (name == null || value == null) throw new NullPointerException("Block property"); + if (!name.matches("[a-z0-9_]+") || !value.matches("[a-z0-9_.-]+")) { + throw new IllegalArgumentException("Invalid block property: " + name + "=" + value); + } + copy.put(name, value); + }); + properties = Collections.unmodifiableMap(copy); + } + + public BlockState(String material) { this(ResourceId.parse(material), Map.of()); } + + public BlockState withProperty(String name, String value) { + var changed = new TreeMap<>(properties); + changed.put(name, value); + return new BlockState(material, changed); + } + + /** Stable representation with properties in lexical order. */ + public String key() { + if (properties.isEmpty()) return material.toString(); + return material + properties.entrySet().stream() + .map(entry -> entry.getKey() + "=" + entry.getValue()) + .collect(Collectors.joining(",", "[", "]")); + } +} diff --git a/src/main/java/com/volmit/block/BlockTrait.java b/src/main/java/com/volmit/block/BlockTrait.java new file mode 100644 index 000000000..db39ce0d7 --- /dev/null +++ b/src/main/java/com/volmit/block/BlockTrait.java @@ -0,0 +1,7 @@ +package com.volmit.block; + +/** Host-defined block behavior; tags provide extensible material groups. */ +public enum BlockTrait { + AIR, SOLID, OCCLUDING, FLUID, WATER, GRAVITY, FOLIAGE, DECORATION, + LOG, LEAVES, ORE, INVENTORY, BLOCK_ENTITY, CUSTOM, NEEDS_UPDATE +} diff --git a/src/main/java/com/volmit/config/Desc.java b/src/main/java/com/volmit/config/Desc.java new file mode 100644 index 000000000..72a88eef9 --- /dev/null +++ b/src/main/java/com/volmit/config/Desc.java @@ -0,0 +1,10 @@ +package com.volmit.config; + +import java.lang.annotation.*; + +/** Human-readable documentation for a settings type or field. */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.TYPE, ElementType.FIELD}) +public @interface Desc { + String value(); +} diff --git a/src/main/java/com/volmit/config/Feature.java b/src/main/java/com/volmit/config/Feature.java new file mode 100644 index 000000000..7dc783341 --- /dev/null +++ b/src/main/java/com/volmit/config/Feature.java @@ -0,0 +1,13 @@ +package com.volmit.config; + +import java.lang.annotation.*; + +/** Identity and JSON attachment for an IrisFeature configuration class. */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface Feature { + String id(); + String name(); + String field(); + com.volmit.FeatureAttachment.Target[] targets(); +} diff --git a/src/main/java/com/volmit/config/FeatureSettings.java b/src/main/java/com/volmit/config/FeatureSettings.java new file mode 100644 index 000000000..785dc8cba --- /dev/null +++ b/src/main/java/com/volmit/config/FeatureSettings.java @@ -0,0 +1,26 @@ +package com.volmit.config; + +import com.volmit.FeatureAttachment; +import com.volmit.IrisFeature; +import com.volmit.resource.ResourceId; +import java.util.List; + +/** Invocation-scoped lookup of applicable settings by attachment and world position. + * Results are immutable lists in pack declaration order, after the host applies inheritance + * rules. Targets remain separate: this interface never silently merges dimension/region/biome + * values. OBJECT_PLACEMENT is read from the current placement, or returns an empty list. + * Values must be treated as read-only. Bounds and lifetime match the invocation's sampler. + */ +public interface FeatureSettings { + List> at(Class featureType, FeatureAttachment.Target target, + int worldX, int worldY, int worldZ); + + /** source identifies the configuration owner; occurrence is unique within the pack snapshot. */ + record Entry(ResourceId source, ResourceId occurrence, F value) { + public Entry { + java.util.Objects.requireNonNull(source, "source"); + java.util.Objects.requireNonNull(occurrence, "occurrence"); + java.util.Objects.requireNonNull(value, "value"); + } + } +} diff --git a/src/main/java/com/volmit/config/MaxNumber.java b/src/main/java/com/volmit/config/MaxNumber.java new file mode 100644 index 000000000..5f9192bc4 --- /dev/null +++ b/src/main/java/com/volmit/config/MaxNumber.java @@ -0,0 +1,10 @@ +package com.volmit.config; + +import java.lang.annotation.*; + +/** Inclusive numeric upper bound. Enforcement belongs to the configuration loader. */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface MaxNumber { + double value(); +} diff --git a/src/main/java/com/volmit/config/MinNumber.java b/src/main/java/com/volmit/config/MinNumber.java new file mode 100644 index 000000000..52aec4651 --- /dev/null +++ b/src/main/java/com/volmit/config/MinNumber.java @@ -0,0 +1,10 @@ +package com.volmit.config; + +import java.lang.annotation.*; + +/** Inclusive numeric lower bound. Enforcement belongs to the configuration loader. */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface MinNumber { + double value(); +} diff --git a/src/main/java/com/volmit/config/OptionsMetadata.java b/src/main/java/com/volmit/config/OptionsMetadata.java new file mode 100644 index 000000000..3b4c6ec26 --- /dev/null +++ b/src/main/java/com/volmit/config/OptionsMetadata.java @@ -0,0 +1,60 @@ +package com.volmit.config; + +import java.lang.reflect.Modifier; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; + +/** Annotation metadata, independent of JSON libraries. Does not decode or validate values. */ +public record OptionsMetadata(String description, String snippet, List