Baseline IrisApi draft before stage-graph redesign

This commit is contained in:
piexel committed 2026-10-05 17:01:18 +02:00
commit 9043d93fbd
91 files changed
+4045

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
.gradle/
build/
.idea/
*.iml
+40
View File
@@ -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<T>`, `PackResources` |
| Terrain, biome and effective feature sampling | `TerrainSampler`, `BiomeSample`, `TerrainSample`, `FeatureSettings` |
| Dense local output | `Hunk<T>`, reference `ArrayHunk<T>` |
| 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.
+291
View File
@@ -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<T>` 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.
+153
View File
@@ -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<T>` | Edits an invocation-owned local `Hunk<T>` |
| 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<T>` 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<T>` 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.
+25
View File
@@ -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()
}
Binary file not shown.
+9
View File
@@ -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
Vendored Executable
+248
View File
@@ -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" "$@"
Vendored
+82
View File
@@ -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%
+1
View File
@@ -0,0 +1 @@
rootProject.name = "IrisApi"
@@ -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<Target> 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");
}
}
@@ -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.
*/
<T> void registerMantle(MantleKey<T> key, MantleLifetime lifetime, MantleCodec<T> codec);
<F extends IrisFeature, T> void register(Class<F> featureType,
Class<T> outputType, ModifierFactory<F, T> factory);
<F extends IrisFeature> void registerObject(Class<F> featureType, ObjectGeneratorFactory<F> factory);
<F extends IrisFeature> void registerPlacement(Class<F> featureType, PlacementModifierFactory<F> factory);
}
@@ -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 {}
+10
View File
@@ -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);
}
@@ -0,0 +1,3 @@
package com.volmit.block;
public enum BlockFace { UP, DOWN, NORTH, SOUTH, EAST, WEST }
@@ -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);
}
@@ -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);
}
@@ -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<String, String> properties) {
public BlockState {
Objects.requireNonNull(material, "material");
var copy = new TreeMap<String, String>();
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(",", "[", "]"));
}
}
@@ -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
}
+10
View File
@@ -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();
}
@@ -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();
}
@@ -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 {
<F extends IrisFeature> List<Entry<F>> at(Class<F> featureType, FeatureAttachment.Target target,
int worldX, int worldY, int worldZ);
/** source identifies the configuration owner; occurrence is unique within the pack snapshot. */
record Entry<F extends IrisFeature>(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");
}
}
}
@@ -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();
}
@@ -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();
}
@@ -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<Option> options) {
public OptionsMetadata {
options = List.copyOf(options);
}
public record Option(String name, Type type, String description,
boolean required, Double minimum, Double maximum) {}
/** Reads private and inherited fields without constructing settings or accessing values.
* Nested object types are preserved for the schema builder to inspect recursively.
*/
public static OptionsMetadata inspect(Class<?> type) {
var options = new ArrayList<Option>();
var names = new HashSet<String>();
for (Class<?> current = type; current != null && current != Object.class;
current = current.getSuperclass()) {
for (var field : current.getDeclaredFields()) {
int modifiers = field.getModifiers();
if (field.isSynthetic() || Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers)) {
continue;
}
if (!names.add(field.getName())) {
throw new IllegalArgumentException("Duplicate option: " + field.getName());
}
var desc = field.getAnnotation(Desc.class);
var min = field.getAnnotation(MinNumber.class);
var max = field.getAnnotation(MaxNumber.class);
if ((min != null || max != null) && !isNumeric(field.getType())) {
throw new IllegalArgumentException("Numeric bounds on nonnumeric option: " + field.getName());
}
if ((min != null && !Double.isFinite(min.value()))
|| (max != null && !Double.isFinite(max.value()))
|| (min != null && max != null && min.value() > max.value())) {
throw new IllegalArgumentException("Invalid bounds for option: " + field.getName());
}
options.add(new Option(field.getName(), field.getGenericType(),
desc == null ? "" : desc.value(), field.isAnnotationPresent(Required.class),
min == null ? null : min.value(), max == null ? null : max.value()));
}
}
var desc = type.getAnnotation(Desc.class);
var snippet = type.getAnnotation(Snippet.class);
return new OptionsMetadata(desc == null ? "" : desc.value(),
snippet == null ? "" : snippet.value(), options);
}
private static boolean isNumeric(Class<?> type) {
return Number.class.isAssignableFrom(type) || type == byte.class || type == short.class
|| type == int.class || type == long.class || type == float.class || type == double.class;
}
}
@@ -0,0 +1,8 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Declares that a field must be supplied in configuration. */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Required {}
@@ -0,0 +1,10 @@
package com.volmit.config;
import java.lang.annotation.*;
/** Identifies a reusable settings snippet. */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Snippet {
String value();
}
@@ -0,0 +1,52 @@
package com.volmit.generation;
import java.util.HashSet;
import java.util.Set;
import com.volmit.resource.ResourceId;
/** Immutable ordering declarations referencing modifier IDs, not feature IDs.
* Requirements must exist and finish first. Optional constraints apply only when present.
* Nothing here activates a feature. The host resolves and validates the graph at pack load.
*/
public record Dependencies(Set<String> required, Set<String> after, Set<String> before) {
public Dependencies {
required = validatedCopy(required);
after = validatedCopy(after);
before = validatedCopy(before);
}
public static Dependencies none() {
return new Dependencies(Set.of(), Set.of(), Set.of());
}
public static Dependencies requires(String... ids) {
return none().andRequires(ids);
}
/** Adds required predecessors without changing this declaration. */
public Dependencies andRequires(String... ids) {
return new Dependencies(adding(required, ids), after, before);
}
public Dependencies afterIfPresent(String... ids) {
return new Dependencies(required, adding(after, ids), before);
}
public Dependencies beforeIfPresent(String... ids) {
return new Dependencies(required, after, adding(before, ids));
}
private static Set<String> adding(Set<String> existing, String[] ids) {
var result = new HashSet<>(existing);
for (String id : ids) result.add(id);
return result;
}
private static Set<String> validatedCopy(Set<String> ids) {
var copy = Set.copyOf(ids);
for (String id : copy) {
ResourceId.parse(id);
}
return copy;
}
}
@@ -0,0 +1,19 @@
package com.volmit.generation;
import com.volmit.mantle.Mantle;
import com.volmit.config.FeatureSettings;
import com.volmit.world.TerrainSampler;
/** Per-invocation state. Must not be retained by a modifier after execution. */
public interface GenerationContext extends InvocationContext {
/** World block coordinates corresponding to local volume coordinates (0, 0, 0). */
int originX();
int originY();
int originZ();
TerrainSampler terrain();
FeatureSettings settings();
/** Non-null mantle access scoped to this invocation; the host owns its lifetime. */
Mantle mantle();
}
@@ -0,0 +1,34 @@
package com.volmit.generation;
import com.volmit.hunk.Hunk;
/** Bound to one configured feature instance.
* Calls may occur concurrently for different volumes. Keep settings read-only and temporary
* state local to modify(). Exceptions propagate: the host must not publish partial output.
*/
public abstract class GenerationModifier<T> {
/** Stable, nonblank namespaced modifier identity, independent of feature identity.
* Configured instances of the same modifier share this ID and dependency declaration.
* Different modifier implementations must not claim the same ID.
*/
public abstract String id();
/** Stable requirements read at pack load, not per invocation. Constructors must not
* depend on prerequisite modifiers having run. Ordering does not guarantee that
* a prerequisite changed blocks at the current location.
*/
public Dependencies depends() {
return Dependencies.none();
}
/** Nonnegative horizontal reach in blocks beyond the output footprint; zero by default.
* Read once per configured instance at pack load. The host must prepare this area and
* required predecessor work before invocation, bound vertical access to the world, and
* serialize overlapping writes. It must reject negative or unsupported reach, not clip it.
*/
public int mantleRadius() {
return 0;
}
public abstract void modify(GenerationContext context, Hunk<T> output);
}
@@ -0,0 +1,14 @@
package com.volmit.generation;
import com.volmit.resource.PackResources;
import java.util.random.RandomGenerator;
/** Host-owned invocation inputs. RNG and views must not be retained or used by detached tasks.
* The host derives streams from world seed, stable feature/occurrence identity and position;
* module discovery order must not affect them. Keeping legacy random behavior is adapter work.
*/
public interface InvocationContext {
long worldSeed();
PackResources resources();
RandomGenerator random();
}
@@ -0,0 +1,9 @@
package com.volmit.generation;
import com.volmit.IrisFeature;
/** Connects a feature's decoded options to its executable modifier. */
@FunctionalInterface
public interface ModifierFactory<F extends IrisFeature, T> {
GenerationModifier<T> create(F feature);
}
@@ -0,0 +1,88 @@
package com.volmit.host;
import com.volmit.hunk.Hunk;
import java.util.Arrays;
import java.util.Objects;
/** Reference dense volume with checked local coordinates and non-null values.
* Each invocation owns its volume; concurrent writes to the same volume are unsupported.
*/
public final class ArrayHunk<T> implements Hunk<T> {
private final Class<T> type;
private final int width;
private final int height;
private final int depth;
private final Object[] values;
public ArrayHunk(Class<T> type, int width, int height, int depth, T initial) {
this.type = Objects.requireNonNull(type, "type");
if (type.isPrimitive()) {
throw new IllegalArgumentException("Hunk requires a reference type");
}
validateDimensions(width, height, depth);
this.width = width;
this.height = height;
this.depth = depth;
values = new Object[valueCount(width, height, depth)];
Arrays.fill(values, type.cast(Objects.requireNonNull(initial, "initial")));
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public int getDepth() {
return depth;
}
public T get(int x, int y, int z) {
return type.cast(values[index(x, y, z)]);
}
public void set(int x, int y, int z, T value) {
int valueIndex = index(x, y, z);
values[valueIndex] = type.cast(Objects.requireNonNull(value, "value"));
}
private static void validateDimensions(int width, int height, int depth) {
if (width < 0) {
throw negativeDimension();
}
if (height < 0) {
throw negativeDimension();
}
if (depth < 0) {
throw negativeDimension();
}
}
private static IllegalArgumentException negativeDimension() {
return new IllegalArgumentException("Negative hunk dimension");
}
private static int valueCount(int width, int height, int depth) {
return Math.multiplyExact(Math.multiplyExact(width, height), depth);
}
private int index(int x, int y, int z) {
if (x < 0 || x >= width) {
throw outOfBounds(x, y, z);
}
if (y < 0 || y >= height) {
throw outOfBounds(x, y, z);
}
if (z < 0 || z >= depth) {
throw outOfBounds(x, y, z);
}
return (y * depth + z) * width + x;
}
private static IndexOutOfBoundsException outOfBounds(int x, int y, int z) {
return new IndexOutOfBoundsException("Local hunk position: " + x + "," + y + "," + z);
}
}
@@ -0,0 +1,69 @@
package com.volmit.host;
import com.volmit.generation.Dependencies;
import com.volmit.generation.GenerationContext;
import com.volmit.generation.GenerationModifier;
import com.volmit.hunk.Hunk;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/** Pack-load snapshot of modifier identity, requirements, type and prepared reach.
* The occurrence identifies one configuration, independent of its shared ordering identity.
*/
public final class ConfiguredModifier<T> {
private final ResourceId occurrence;
private final Class<T> outputType;
private final GenerationModifier<T> modifier;
private final ResourceId id;
private final Dependencies dependencies;
private final int mantleRadius;
public ConfiguredModifier(
ResourceId occurrence,
Class<T> outputType,
GenerationModifier<T> modifier) {
this.occurrence = Objects.requireNonNull(occurrence, "occurrence");
this.outputType = Objects.requireNonNull(outputType, "outputType");
if (outputType.isPrimitive()) {
throw new IllegalArgumentException("Output requires a reference type");
}
this.modifier = Objects.requireNonNull(modifier, "modifier");
id = ResourceId.parse(modifier.id());
dependencies = Objects.requireNonNull(modifier.depends(), "dependencies");
mantleRadius = modifier.mantleRadius();
if (mantleRadius < 0) {
throw new IllegalArgumentException("Negative mantle radius: " + id);
}
}
public ResourceId occurrence() {
return occurrence;
}
public Class<T> outputType() {
return outputType;
}
public ResourceId id() {
return id;
}
public Dependencies dependencies() {
return dependencies;
}
public int mantleRadius() {
return mantleRadius;
}
public Class<?> implementationType() {
return modifier.getClass();
}
/** Host must prepare views/predecessor work and abort publication if this throws. */
public void modify(GenerationContext context, Hunk<T> output) {
modifier.modify(
Objects.requireNonNull(context, "context"),
Objects.requireNonNull(output, "output"));
}
}
@@ -0,0 +1,46 @@
package com.volmit.host;
import com.volmit.generation.Dependencies;
import com.volmit.placement.PlacementModifier;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/** Pack-load placement declaration snapshot. The configured modifier must be immutable. */
public final class ConfiguredPlacementModifier {
private final ResourceId occurrence;
private final PlacementModifier modifier;
private final ResourceId id;
private final Dependencies dependencies;
private final int writeRadius;
public ConfiguredPlacementModifier(ResourceId occurrence, PlacementModifier modifier) {
this.occurrence = Objects.requireNonNull(occurrence, "occurrence");
this.modifier = Objects.requireNonNull(modifier, "modifier");
id = ResourceId.parse(modifier.id());
dependencies = Objects.requireNonNull(modifier.depends(), "dependencies");
writeRadius = modifier.writeRadius();
if (writeRadius < 0) {
throw new IllegalArgumentException("Negative placement radius: " + id);
}
}
public ResourceId occurrence() {
return occurrence;
}
public PlacementModifier modifier() {
return modifier;
}
public ResourceId id() {
return id;
}
public Dependencies dependencies() {
return dependencies;
}
public int writeRadius() {
return writeRadius;
}
}
@@ -0,0 +1,144 @@
package com.volmit.host;
import com.volmit.generation.Dependencies;
import com.volmit.resource.ResourceId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.TreeSet;
/** Host-independent ordering of one complete modifier graph. Ready IDs use lexical order,
* independent of discovery. Required IDs must exist. Optional edges apply only when present.
* Self-dependencies and cycles fail. This graph never activates features or permits parallel writes.
*/
public final class DependencyOrder {
private DependencyOrder() {}
public static List<ResourceId> resolve(Map<ResourceId, Dependencies> declarations) {
var graph = Map.copyOf(declarations);
var incomingEdges = initializeIncomingEdges(graph.keySet());
var outgoingEdges = new HashMap<ResourceId, Set<ResourceId>>();
addDeclaredEdges(graph, incomingEdges, outgoingEdges);
return topologicalOrder(graph, incomingEdges, outgoingEdges);
}
private static Map<ResourceId, Integer> initializeIncomingEdges(Set<ResourceId> ids) {
var incomingEdges = new HashMap<ResourceId, Integer>();
ids.forEach(id -> incomingEdges.put(id, 0));
return incomingEdges;
}
private static void addDeclaredEdges(
Map<ResourceId, Dependencies> graph,
Map<ResourceId, Integer> incomingEdges,
Map<ResourceId, Set<ResourceId>> outgoingEdges) {
graph.forEach((id, dependencies) -> {
Objects.requireNonNull(dependencies, "dependencies");
addRequiredEdges(id, dependencies, graph, incomingEdges, outgoingEdges);
addOptionalEdges(id, dependencies, graph, incomingEdges, outgoingEdges);
});
}
private static void addRequiredEdges(
ResourceId id,
Dependencies dependencies,
Map<ResourceId, Dependencies> graph,
Map<ResourceId, Integer> incomingEdges,
Map<ResourceId, Set<ResourceId>> outgoingEdges) {
for (var name : dependencies.required()) {
var predecessor = ResourceId.parse(name);
if (!graph.containsKey(predecessor)) {
throw new IllegalArgumentException(id + " requires missing modifier " + predecessor);
}
addEdge(predecessor, id, incomingEdges, outgoingEdges);
}
}
private static void addOptionalEdges(
ResourceId id,
Dependencies dependencies,
Map<ResourceId, Dependencies> graph,
Map<ResourceId, Integer> incomingEdges,
Map<ResourceId, Set<ResourceId>> outgoingEdges) {
for (var name : dependencies.after()) {
var predecessor = ResourceId.parse(name);
rejectSelf(id, predecessor);
if (graph.containsKey(predecessor)) {
addEdge(predecessor, id, incomingEdges, outgoingEdges);
}
}
for (var name : dependencies.before()) {
var successor = ResourceId.parse(name);
rejectSelf(id, successor);
if (graph.containsKey(successor)) {
addEdge(id, successor, incomingEdges, outgoingEdges);
}
}
}
private static List<ResourceId> topologicalOrder(
Map<ResourceId, Dependencies> graph,
Map<ResourceId, Integer> incomingEdges,
Map<ResourceId, Set<ResourceId>> outgoingEdges) {
var ready = new PriorityQueue<ResourceId>();
incomingEdges.forEach((id, count) -> {
if (count == 0) {
ready.add(id);
}
});
var ordered = new ArrayList<ResourceId>(graph.size());
while (!ready.isEmpty()) {
var id = ready.remove();
ordered.add(id);
releaseSuccessors(id, outgoingEdges, incomingEdges, ready);
}
if (ordered.size() != graph.size()) {
throw cycleException(graph.keySet(), ordered);
}
return List.copyOf(ordered);
}
private static void releaseSuccessors(
ResourceId id,
Map<ResourceId, Set<ResourceId>> outgoingEdges,
Map<ResourceId, Integer> incomingEdges,
PriorityQueue<ResourceId> ready) {
for (var successor : outgoingEdges.getOrDefault(id, Set.of())) {
int remainingEdges = incomingEdges.compute(successor, (ignored, count) -> count - 1);
if (remainingEdges == 0) {
ready.add(successor);
}
}
}
private static IllegalArgumentException cycleException(Set<ResourceId> ids, List<ResourceId> ordered) {
var unresolved = new TreeSet<>(ids);
unresolved.removeAll(ordered);
return new IllegalArgumentException("Modifier dependency cycle: " + unresolved);
}
private static void rejectSelf(ResourceId id, ResourceId other) {
if (id.equals(other)) {
throw new IllegalArgumentException("Self-dependency: " + id);
}
}
private static void addEdge(
ResourceId from,
ResourceId to,
Map<ResourceId, Integer> incomingEdges,
Map<ResourceId, Set<ResourceId>> outgoingEdges) {
rejectSelf(from, to);
if (outgoingEdges.computeIfAbsent(from, ignored -> new HashSet<>()).add(to)) {
incomingEdges.compute(to, (ignored, count) -> count + 1);
}
}
}
@@ -0,0 +1,86 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.function.Function;
/** Frozen registrations. Lists use lexical feature/layer ID order, independent of discovery.
* Factory and codec implementations must themselves obey their concurrency contracts.
*/
public final class FeatureCatalog {
private final Map<Class<?>, GenerationRegistration<?, ?>> generation;
private final Map<Class<?>, ObjectRegistration<?>> objects;
private final Map<Class<?>, PlacementRegistration<?>> placement;
private final Map<String, MantleRegistration<?>> mantle;
FeatureCatalog(
Map<Class<?>, GenerationRegistration<?, ?>> generation,
Map<Class<?>, ObjectRegistration<?>> objects,
Map<Class<?>, PlacementRegistration<?>> placement,
Map<String, MantleRegistration<?>> mantle) {
this.generation = Map.copyOf(generation);
this.objects = Map.copyOf(objects);
this.placement = Map.copyOf(placement);
this.mantle = Map.copyOf(mantle);
}
public List<GenerationRegistration<?, ?>> generation() {
return sorted(generation.values(), registration -> registration.descriptor().id());
}
public List<ObjectRegistration<?>> objects() {
return sorted(objects.values(), registration -> registration.descriptor().id());
}
public List<PlacementRegistration<?>> placement() {
return sorted(placement.values(), registration -> registration.descriptor().id());
}
public List<MantleRegistration<?>> mantle() {
return sorted(mantle.values(), registration -> registration.key().id());
}
private static <T, K extends Comparable<? super K>> List<T> sorted(
Collection<T> registrations,
Function<? super T, ? extends K> key) {
return registrations.stream()
.sorted(Comparator.comparing(key))
.toList();
}
@SuppressWarnings("unchecked") // The registry key and output type establish the generic pairing.
public <F extends IrisFeature, T> GenerationRegistration<F, T> generation(
Class<F> type,
Class<T> outputType) {
var registration = generation.get(type);
if (registration == null) {
throw new NoSuchElementException("No generation feature: " + type.getName());
}
if (!registration.outputType().equals(outputType)) {
throw new IllegalArgumentException("Output type mismatch: " + type.getName());
}
return (GenerationRegistration<F, T>) registration;
}
@SuppressWarnings("unchecked") // The registry key is the factory's feature type.
public <F extends IrisFeature> ObjectRegistration<F> object(Class<F> type) {
var registration = objects.get(type);
if (registration == null) {
throw new NoSuchElementException("No object feature: " + type.getName());
}
return (ObjectRegistration<F>) registration;
}
@SuppressWarnings("unchecked") // The registry key is the factory's feature type.
public <F extends IrisFeature> PlacementRegistration<F> placement(Class<F> type) {
var registration = placement.get(type);
if (registration == null) {
throw new NoSuchElementException("No placement feature: " + type.getName());
}
return (PlacementRegistration<F>) registration;
}
}
@@ -0,0 +1,26 @@
package com.volmit.host;
import com.volmit.FeatureAttachment;
import com.volmit.IrisFeature;
import com.volmit.config.OptionsMetadata;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/** Validated registration metadata. It describes configuration, not executable ordering. */
public record FeatureDescriptor<F extends IrisFeature>(
ResourceId id,
String name,
Class<F> type,
FeatureAttachment attachment,
OptionsMetadata options) {
public FeatureDescriptor {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(name, "name");
if (name.isBlank()) {
throw new IllegalArgumentException("Blank feature name");
}
Objects.requireNonNull(type, "type");
Objects.requireNonNull(attachment, "attachment");
Objects.requireNonNull(options, "options");
}
}
@@ -0,0 +1,91 @@
package com.volmit.host;
import com.volmit.generation.Dependencies;
import com.volmit.resource.ResourceId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Immutable pack-load ordering across output types. Instances sharing a modifier ID must
* have the same implementation, output type and dependencies. Occurrence IDs must be unique.
* Instances within one identity use lexical occurrence order. Resolve once, dispatch many times.
* The host includes its built-in lifecycle steps in this graph and rejects incompatible edges.
*/
public final class GenerationPlan {
private final List<ConfiguredModifier<?>> ordered;
private GenerationPlan(List<ConfiguredModifier<?>> ordered) {
this.ordered = List.copyOf(ordered);
}
public static GenerationPlan resolve(List<? extends ConfiguredModifier<?>> modifiers) {
List<ConfiguredModifier<?>> instances = new ArrayList<>(modifiers);
var declarations = collectDeclarations(instances);
var modifierIds = DependencyOrder.resolve(declarations);
var orderedOccurrences = OccurrenceOrder.order(
modifierIds,
instances,
ConfiguredModifier::id,
ConfiguredModifier::occurrence);
return new GenerationPlan(orderedOccurrences);
}
private static Map<ResourceId, Dependencies> collectDeclarations(List<ConfiguredModifier<?>> instances) {
var representatives = new HashMap<ResourceId, ConfiguredModifier<?>>();
var occurrences = new HashSet<ResourceId>();
var declarations = new HashMap<ResourceId, Dependencies>();
for (var modifier : instances) {
checkUniqueOccurrence(modifier, occurrences);
checkCompatibleIdentity(modifier, representatives);
declarations.put(modifier.id(), modifier.dependencies());
}
return declarations;
}
private static void checkUniqueOccurrence(
ConfiguredModifier<?> modifier,
Set<ResourceId> occurrences) {
if (!occurrences.add(modifier.occurrence())) {
throw new IllegalArgumentException("Duplicate occurrence: " + modifier.occurrence());
}
}
private static void checkCompatibleIdentity(
ConfiguredModifier<?> modifier,
Map<ResourceId, ConfiguredModifier<?>> representatives) {
var previous = representatives.putIfAbsent(modifier.id(), modifier);
if (previous == null || isCompatible(previous, modifier)) {
return;
}
throw new IllegalArgumentException("Conflicting modifier identity: " + modifier.id());
}
private static boolean isCompatible(ConfiguredModifier<?> first, ConfiguredModifier<?> second) {
return first.implementationType().equals(second.implementationType())
&& first.outputType().equals(second.outputType())
&& first.dependencies().equals(second.dependencies());
}
public List<ConfiguredModifier<?>> ordered() {
return ordered;
}
/** Sequential dispatch only. Executor prepares/releases a dedicated context and typed output
* for each applicable occurrence; applicability is host-owned. Failures stop dispatch.
* This reference planner does not implement chunk scheduling, rollback or lifecycle bridging.
*/
public void execute(Executor executor) {
java.util.Objects.requireNonNull(executor, "executor");
for (var modifier : ordered) {
executor.execute(modifier);
}
}
public interface Executor {
<T> void execute(ConfiguredModifier<T> modifier);
}
}
@@ -0,0 +1,25 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.generation.ModifierFactory;
import com.volmit.resource.ResourceId;
import java.util.Objects;
public record GenerationRegistration<F extends IrisFeature, T>(
FeatureDescriptor<F> descriptor,
Class<T> outputType,
ModifierFactory<F, T> factory) {
public GenerationRegistration {
Objects.requireNonNull(descriptor, "descriptor");
Objects.requireNonNull(outputType, "outputType");
if (outputType.isPrimitive()) {
throw new IllegalArgumentException("Output requires a reference type");
}
Objects.requireNonNull(factory, "factory");
}
public ConfiguredModifier<T> configure(ResourceId occurrence, F feature) {
var configuredFeature = descriptor.type().cast(Objects.requireNonNull(feature, "feature"));
return new ConfiguredModifier<>(occurrence, outputType, factory.create(configuredFeature));
}
}
@@ -0,0 +1,21 @@
package com.volmit.host;
import com.volmit.mantle.MantleCodec;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
import java.util.Objects;
public record MantleRegistration<T>(
MantleKey<T> key,
MantleLifetime lifetime,
MantleCodec<T> codec,
int version) {
public MantleRegistration {
Objects.requireNonNull(key, "key");
Objects.requireNonNull(lifetime, "lifetime");
Objects.requireNonNull(codec, "codec");
if (version < 0) {
throw new IllegalArgumentException("Negative mantle codec version");
}
}
}
@@ -0,0 +1,180 @@
package com.volmit.host;
import com.volmit.FeatureAttachment;
import com.volmit.FeatureRegistry;
import com.volmit.IrisFeature;
import com.volmit.config.Feature;
import com.volmit.config.OptionsMetadata;
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;
import com.volmit.resource.ResourceId;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/** Reference host registry. Single-threaded registration ends with freeze(); the catalog is
* immutable. IDs are unique across feature kinds; JSON fields are unique per attachment target.
* Pass existing host JSON fields to reserve them before modules register. A failed registration
* leaves the registry unchanged. A failed module callback invalidates the host's whole build.
* This does not decode JSON, discover modules or instantiate settings.
*/
public final class ModuleRegistry implements FeatureRegistry {
private final Map<Class<?>, GenerationRegistration<?, ?>> generation = new HashMap<>();
private final Map<Class<?>, ObjectRegistration<?>> objects = new HashMap<>();
private final Map<Class<?>, PlacementRegistration<?>> placement = new HashMap<>();
private final Map<String, MantleRegistration<?>> mantle = new HashMap<>();
private final Set<ResourceId> featureIds = new HashSet<>();
private final Set<Class<?>> featureTypes = new HashSet<>();
private final Map<Field, String> fields = new HashMap<>();
private FeatureCatalog catalog;
public ModuleRegistry() {
this(Map.of());
}
public ModuleRegistry(Map<FeatureAttachment.Target, Set<String>> reservedFields) {
reserveHostFields(reservedFields);
}
@Override
public <F extends IrisFeature, T> void register(
Class<F> featureType,
Class<T> outputType,
ModifierFactory<F, T> factory) {
var descriptor = describe(featureType);
var registration = new GenerationRegistration<>(descriptor, outputType, factory);
claim(descriptor);
generation.put(featureType, registration);
}
@Override
public <F extends IrisFeature> void registerObject(
Class<F> featureType,
ObjectGeneratorFactory<F> factory) {
var descriptor = describe(featureType);
var registration = new ObjectRegistration<>(descriptor, factory);
claim(descriptor);
objects.put(featureType, registration);
}
@Override
public <F extends IrisFeature> void registerPlacement(
Class<F> featureType,
PlacementModifierFactory<F> factory) {
var descriptor = describe(featureType);
if (!isPlacementFeature(descriptor)) {
throw new IllegalArgumentException(
"Placement modifiers must attach only to OBJECT_PLACEMENT: " + descriptor.id());
}
var registration = new PlacementRegistration<>(descriptor, factory);
claim(descriptor);
placement.put(featureType, registration);
}
@Override
public <T> void registerMantle(MantleKey<T> key, MantleLifetime lifetime, MantleCodec<T> codec) {
checkOpen();
Objects.requireNonNull(key, "key");
Objects.requireNonNull(codec, "codec");
var registration = new MantleRegistration<>(key, lifetime, codec, codec.version());
if (mantle.putIfAbsent(key.id(), registration) != null) {
throw new IllegalArgumentException("Duplicate mantle layer: " + key.id());
}
}
public FeatureCatalog freeze() {
if (catalog == null) {
catalog = new FeatureCatalog(generation, objects, placement, mantle);
}
return catalog;
}
private void reserveHostFields(Map<FeatureAttachment.Target, Set<String>> reservedFields) {
for (var entry : reservedFields.entrySet()) {
for (var name : entry.getValue()) {
reserveHostField(entry.getKey(), name);
}
}
}
private void reserveHostField(FeatureAttachment.Target target, String name) {
new FeatureAttachment(name, Set.of(target));
fields.put(new Field(target, name), "host");
}
private <F extends IrisFeature> FeatureDescriptor<F> describe(Class<F> type) {
checkOpen();
Objects.requireNonNull(type, "featureType");
validateFeatureType(type);
var annotation = type.getDeclaredAnnotation(Feature.class);
if (annotation == null) {
throw new IllegalArgumentException("Missing @Feature: " + type.getName());
}
return new FeatureDescriptor<>(
ResourceId.parse(annotation.id()),
annotation.name(),
type,
new FeatureAttachment(annotation.field(), Set.of(annotation.targets())),
OptionsMetadata.inspect(type));
}
private static void validateFeatureType(Class<? extends IrisFeature> type) {
if (!IrisFeature.class.isAssignableFrom(type)
|| type.isInterface()
|| Modifier.isAbstract(type.getModifiers())) {
throw new IllegalArgumentException(
"Feature type must be a concrete IrisFeature: " + type.getName());
}
}
private static boolean isPlacementFeature(FeatureDescriptor<?> descriptor) {
return descriptor.attachment().targets().equals(Set.of(FeatureAttachment.Target.OBJECT_PLACEMENT));
}
private void claim(FeatureDescriptor<?> descriptor) {
validateClaim(descriptor);
recordClaim(descriptor);
}
private void validateClaim(FeatureDescriptor<?> descriptor) {
if (featureTypes.contains(descriptor.type()) || featureIds.contains(descriptor.id())) {
throw new IllegalArgumentException("Duplicate feature: " + descriptor.id());
}
for (var target : descriptor.attachment().targets()) {
var field = new Field(target, descriptor.attachment().field());
if (fields.containsKey(field)) {
throw new IllegalArgumentException(
"JSON field collision at " + field + ": " + fields.get(field));
}
}
}
private void recordClaim(FeatureDescriptor<?> descriptor) {
featureTypes.add(descriptor.type());
featureIds.add(descriptor.id());
for (var target : descriptor.attachment().targets()) {
var field = new Field(target, descriptor.attachment().field());
fields.put(field, descriptor.id().toString());
}
}
private void checkOpen() {
if (catalog != null) {
throw new IllegalStateException("Registration has ended");
}
}
private record Field(FeatureAttachment.Target target, String name) {}
}
@@ -0,0 +1,20 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.object.ObjectGenerator;
import com.volmit.object.ObjectGeneratorFactory;
import java.util.Objects;
public record ObjectRegistration<F extends IrisFeature>(
FeatureDescriptor<F> descriptor,
ObjectGeneratorFactory<F> factory) {
public ObjectRegistration {
Objects.requireNonNull(descriptor, "descriptor");
Objects.requireNonNull(factory, "factory");
}
public ObjectGenerator configure(F feature) {
var configuredFeature = descriptor.type().cast(Objects.requireNonNull(feature, "feature"));
return Objects.requireNonNull(factory.create(configuredFeature), "generator");
}
}
@@ -0,0 +1,45 @@
package com.volmit.host;
import com.volmit.resource.ResourceId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
/** Orders configured occurrences by dependency identity, then by occurrence ID. */
final class OccurrenceOrder {
private OccurrenceOrder() {}
static <T> List<T> order(
List<ResourceId> orderedIds,
List<T> occurrences,
Function<? super T, ResourceId> identity,
Function<? super T, ResourceId> occurrenceId) {
Map<ResourceId, List<T>> occurrencesByIdentity = groupByIdentity(occurrences, identity);
var ordered = new ArrayList<T>(occurrences.size());
for (var id : orderedIds) {
var group = occurrencesByIdentity.get(id);
if (group == null) {
continue;
}
group.sort((left, right) -> occurrenceId.apply(left).compareTo(occurrenceId.apply(right)));
ordered.addAll(group);
}
return List.copyOf(ordered);
}
private static <T> Map<ResourceId, List<T>> groupByIdentity(
List<T> occurrences,
Function<? super T, ResourceId> identity) {
var occurrencesByIdentity = new HashMap<ResourceId, List<T>>();
for (var occurrence : occurrences) {
occurrencesByIdentity.computeIfAbsent(identity.apply(occurrence), ignored -> new ArrayList<>())
.add(occurrence);
}
return occurrencesByIdentity;
}
}
@@ -0,0 +1,374 @@
package com.volmit.host;
import com.volmit.generation.Dependencies;
import com.volmit.mantle.BlockBox;
import com.volmit.object.ObjectBlock;
import com.volmit.placement.PlacedBlock;
import com.volmit.placement.PlacedMarker;
import com.volmit.placement.PlacementAccess;
import com.volmit.placement.PlacementContext;
import com.volmit.placement.PlacementEdit;
import com.volmit.placement.PlacementModifier;
import com.volmit.placement.PlacementPlan;
import com.volmit.placement.PlacementRequest;
import com.volmit.resource.ResourceId;
import com.volmit.world.BlockPosition;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
/** Reference placement orchestration, resolved at pack load. Same-ID instances must agree on
* implementation and dependencies; occurrences are unique and sorted lexically within an ID.
* The host supplies prepared, serialized storage and enforces platform/placement policies.
* This runner buffers all mapped candidates; host validation must reject collisions or unsupported
* writes before execution. It does not silently skip writes, transform geometry or place live blocks.
*/
public final class PlacementPipeline {
private final List<ConfiguredPlacementModifier> ordered;
private PlacementPipeline(List<ConfiguredPlacementModifier> ordered) {
this.ordered = List.copyOf(ordered);
}
public static PlacementPipeline resolve(List<ConfiguredPlacementModifier> modifiers) {
var instances = List.copyOf(modifiers);
var declarations = collectDeclarations(instances);
var modifierIds = DependencyOrder.resolve(declarations);
var orderedOccurrences = OccurrenceOrder.order(
modifierIds,
instances,
ConfiguredPlacementModifier::id,
ConfiguredPlacementModifier::occurrence);
return new PlacementPipeline(orderedOccurrences);
}
private static Map<ResourceId, Dependencies> collectDeclarations(
List<ConfiguredPlacementModifier> instances) {
var representatives = new HashMap<ResourceId, ConfiguredPlacementModifier>();
var occurrences = new HashSet<ResourceId>();
var declarations = new HashMap<ResourceId, Dependencies>();
for (var modifier : instances) {
checkUniqueOccurrence(modifier, occurrences);
checkCompatibleIdentity(modifier, representatives);
declarations.put(modifier.id(), modifier.dependencies());
}
return declarations;
}
private static void checkUniqueOccurrence(
ConfiguredPlacementModifier modifier,
Set<ResourceId> occurrences) {
if (!occurrences.add(modifier.occurrence())) {
throw new IllegalArgumentException("Duplicate placement occurrence: " + modifier.occurrence());
}
}
private static void checkCompatibleIdentity(
ConfiguredPlacementModifier modifier,
Map<ResourceId, ConfiguredPlacementModifier> representatives) {
var previous = representatives.putIfAbsent(modifier.id(), modifier);
if (previous == null || isCompatible(previous, modifier)) {
return;
}
throw new IllegalArgumentException("Conflicting placement identity: " + modifier.id());
}
private static boolean isCompatible(
ConfiguredPlacementModifier first,
ConfiguredPlacementModifier second) {
return first.modifier().getClass().equals(second.modifier().getClass())
&& first.dependencies().equals(second.dependencies());
}
public List<ConfiguredPlacementModifier> ordered() {
return ordered;
}
public int writeRadius() {
return ordered.stream()
.mapToInt(ConfiguredPlacementModifier::writeRadius)
.max()
.orElse(0);
}
/** Takes ownership of a fresh edit, closing it on success, rejection or exception.
* Contexts are opened once per occurrence and must use dedicated RNGs from one pack snapshot.
* The caller releases those invocation views after this call. The host must prepare the full
* footprint plus declared reach; a prepare hook that moves outside it fails without clipping.
* hostValidation must be read-only and covers collisions, support, protection, state/payload
* validity and any policies beyond modifier validation. Callbacks must not commit the edit.
*/
public Optional<PlacementPlan> place(
PlacementRequest request,
PlacementEdit edit,
Function<ConfiguredPlacementModifier, PlacementContext> contexts,
Predicate<PlacementPlan> hostValidation) {
Objects.requireNonNull(edit, "edit");
try (edit) {
requireInputs(request, contexts, hostValidation);
var invocations = openInvocations(contexts);
var preparedRequest = prepareAll(request, invocations);
if (preparedRequest.isEmpty()) {
return Optional.empty();
}
var prepared = preparedRequest.orElseThrow();
checkPreparedArea(prepared, edit);
var plan = createPlan(prepared, invocations, edit);
if (!validatePlan(plan, invocations, hostValidation)) {
return Optional.empty();
}
var hooks = openHookInvocations(prepared, invocations, edit);
runBeforeHooks(plan, hooks);
writePlan(plan, edit);
runAfterHooks(plan, hooks);
edit.commit();
return Optional.of(plan);
}
}
private static void requireInputs(
PlacementRequest request,
Function<ConfiguredPlacementModifier, PlacementContext> contexts,
Predicate<PlacementPlan> hostValidation) {
Objects.requireNonNull(request, "request");
Objects.requireNonNull(contexts, "contexts");
Objects.requireNonNull(hostValidation, "hostValidation");
}
private List<PlacementInvocation> openInvocations(
Function<ConfiguredPlacementModifier, PlacementContext> contexts) {
var invocations = new ArrayList<PlacementInvocation>(ordered.size());
for (var modifier : ordered) {
var context = Objects.requireNonNull(contexts.apply(modifier), "context");
invocations.add(new PlacementInvocation(modifier, context));
}
return List.copyOf(invocations);
}
private static Optional<PlacementRequest> prepareAll(
PlacementRequest initialRequest,
List<PlacementInvocation> invocations) {
var attemptId = initialRequest.id();
var request = initialRequest;
for (var invocation : invocations) {
var prepared = Objects.requireNonNull(
invocation.modifier().modifier().prepare(invocation.context(), request),
"prepared request");
if (prepared.isEmpty()) {
return Optional.empty();
}
request = prepared.orElseThrow();
if (!request.id().equals(attemptId)) {
throw new IllegalArgumentException("Prepare must preserve placement attempt ID");
}
}
return Optional.of(request);
}
private PlacementPlan createPlan(
PlacementRequest request,
List<PlacementInvocation> invocations,
PlacementEdit edit) {
var blocks = mapBlocks(request, invocations);
var markers = mapMarkers(request);
var plan = new PlacementPlan(request, blocks, markers);
// Compute checked half-open bounds before any mutation, including integer extremes.
plan.writtenBounds();
validateMappedPositions(plan, request, edit, writeRadius());
return plan;
}
private static List<PlacedBlock> mapBlocks(
PlacementRequest request,
List<PlacementInvocation> invocations) {
var mappedBlocks = new ArrayList<PlacedBlock>();
for (var block : request.object().blocks()) {
var mapped = mapBlock(request, block, invocations);
mapped.ifPresent(mappedBlocks::add);
}
return mappedBlocks;
}
private static Optional<PlacedBlock> mapBlock(
PlacementRequest request,
ObjectBlock block,
List<PlacementInvocation> invocations) {
Optional<PlacedBlock> mapped = Optional.of(new PlacedBlock(
request.worldPosition(block.position()),
block.state(),
block.blockEntity()));
for (var invocation : invocations) {
var modifier = invocation.modifier().modifier();
var next = Objects.requireNonNull(
modifier.mapBlock(invocation.context(), mapped.orElseThrow()),
"mapped block");
if (next.isEmpty()) {
return Optional.empty();
}
mapped = next;
}
return mapped;
}
private static List<PlacedMarker> mapMarkers(PlacementRequest request) {
var markers = new ArrayList<PlacedMarker>();
for (var marker : request.object().markers()) {
markers.add(new PlacedMarker(
request.worldPosition(marker.position()),
marker.type(),
marker.attributes()));
}
return markers;
}
private static void validateMappedPositions(
PlacementPlan plan,
PlacementRequest request,
PlacementEdit edit,
int radius) {
for (var block : plan.blocks()) {
checkPosition(block.position(), request.footprint(), edit.bounds(), radius);
}
for (var marker : plan.markers()) {
checkPosition(marker.position(), request.footprint(), edit.bounds(), radius);
}
}
private static boolean validatePlan(
PlacementPlan plan,
List<PlacementInvocation> invocations,
Predicate<PlacementPlan> hostValidation) {
if (!hostValidation.test(plan)) {
return false;
}
for (var invocation : invocations) {
if (!invocation.modifier().modifier().validate(invocation.context(), plan)) {
return false;
}
}
return true;
}
private List<HookInvocation> openHookInvocations(
PlacementRequest request,
List<PlacementInvocation> invocations,
PlacementEdit edit) {
var hooks = new ArrayList<HookInvocation>(invocations.size());
for (var invocation : invocations) {
var access = hookAccess(invocation.modifier(), request, edit);
hooks.add(new HookInvocation(invocation, access));
}
return List.copyOf(hooks);
}
private static void runBeforeHooks(PlacementPlan plan, List<HookInvocation> hooks) {
for (var hook : hooks) {
hook.invocation().modifier().modifier().beforePlace(
hook.invocation().context(),
hook.access(),
plan);
}
}
private static void writePlan(PlacementPlan plan, PlacementEdit edit) {
for (var block : plan.blocks()) {
edit.set(block);
}
for (var marker : plan.markers()) {
edit.marker(marker);
}
}
private static void runAfterHooks(PlacementPlan plan, List<HookInvocation> hooks) {
for (var hook : hooks) {
hook.invocation().modifier().modifier().afterPlace(
hook.invocation().context(),
hook.access(),
plan);
}
}
private static PlacementAccess hookAccess(
ConfiguredPlacementModifier modifier,
PlacementRequest request,
PlacementEdit edit) {
var footprint = request.footprint();
int radius = modifier.writeRadius();
var bounds = new BlockBox(
Math.subtractExact(footprint.minX(), radius),
edit.bounds().minY(),
Math.subtractExact(footprint.minZ(), radius),
Math.addExact(footprint.maxX(), radius),
edit.bounds().maxY(),
Math.addExact(footprint.maxZ(), radius));
return PlacementViews.restrict(edit, bounds);
}
private void checkPreparedArea(PlacementRequest request, PlacementEdit edit) {
var footprint = request.footprint();
var preparedBounds = edit.bounds();
if (!preparedBounds.contains(footprint)
|| !containsHorizontalReach(preparedBounds, footprint, writeRadius())) {
throw new IndexOutOfBoundsException("Placement footprint/reach outside prepared bounds");
}
}
private static void checkPosition(
BlockPosition position,
BlockBox footprint,
BlockBox preparedBounds,
int radius) {
if (!preparedBounds.contains(position.x(), position.y(), position.z())
|| !isWithinHorizontalReach(position.x(), position.z(), footprint, radius)) {
throw new IndexOutOfBoundsException("Mapped placement write outside declared reach: " + position);
}
}
private static boolean containsHorizontalReach(BlockBox outer, BlockBox footprint, int radius) {
return containsReachOnAxis(outer.minX(), outer.maxX(), footprint.minX(), footprint.maxX(), radius)
&& containsReachOnAxis(outer.minZ(), outer.maxZ(), footprint.minZ(), footprint.maxZ(), radius);
}
private static boolean isWithinHorizontalReach(
int x,
int z,
BlockBox footprint,
int radius) {
return isWithinReachOnAxis(x, footprint.minX(), footprint.maxX(), radius)
&& isWithinReachOnAxis(z, footprint.minZ(), footprint.maxZ(), radius);
}
private static boolean containsReachOnAxis(
int outerMin,
int outerMax,
int footprintMin,
int footprintMax,
int radius) {
return (long) footprintMin - radius >= outerMin
&& (long) footprintMax + radius <= outerMax;
}
private static boolean isWithinReachOnAxis(int position, int min, int max, int radius) {
return position >= (long) min - radius && position < (long) max + radius;
}
private record PlacementInvocation(
ConfiguredPlacementModifier modifier,
PlacementContext context) {}
private record HookInvocation(PlacementInvocation invocation, PlacementAccess access) {}
}
@@ -0,0 +1,20 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.placement.PlacementModifierFactory;
import com.volmit.resource.ResourceId;
import java.util.Objects;
public record PlacementRegistration<F extends IrisFeature>(
FeatureDescriptor<F> descriptor,
PlacementModifierFactory<F> factory) {
public PlacementRegistration {
Objects.requireNonNull(descriptor, "descriptor");
Objects.requireNonNull(factory, "factory");
}
public ConfiguredPlacementModifier configure(ResourceId occurrence, F feature) {
var configuredFeature = descriptor.type().cast(Objects.requireNonNull(feature, "feature"));
return new ConfiguredPlacementModifier(occurrence, factory.create(configuredFeature));
}
}
@@ -0,0 +1,149 @@
package com.volmit.host;
import com.volmit.block.BlockState;
import com.volmit.mantle.BlockBox;
import com.volmit.mantle.Mantle;
import com.volmit.mantle.MantleEdit;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLayer;
import com.volmit.mantle.MantleVisitor;
import com.volmit.placement.PlacedBlock;
import com.volmit.placement.PlacedMarker;
import com.volmit.placement.PlacementAccess;
import com.volmit.placement.PlacementEdit;
import java.util.Objects;
/** Internal hook views: limit horizontal reach and hide transaction ownership. */
final class PlacementViews {
private PlacementViews() {}
static PlacementAccess restrict(PlacementEdit edit, BlockBox bounds) {
return new RestrictedPlacementAccess(edit, bounds);
}
private static Mantle restrictMantle(Mantle parent, BlockBox bounds) {
checkArea(parent.bounds(), bounds);
return new RestrictedMantle(parent, bounds);
}
private static void checkPosition(BlockBox bounds, int x, int y, int z) {
if (!bounds.contains(x, y, z)) {
throw new IndexOutOfBoundsException("Placement access outside declared reach");
}
}
private static void checkArea(BlockBox bounds, BlockBox area) {
if (!bounds.contains(area)) {
throw new IndexOutOfBoundsException("Placement area outside declared reach");
}
}
private static final class RestrictedPlacementAccess implements PlacementAccess {
private final PlacementEdit edit;
private final BlockBox allowedBounds;
private RestrictedPlacementAccess(PlacementEdit edit, BlockBox allowedBounds) {
this.edit = Objects.requireNonNull(edit, "edit");
this.allowedBounds = Objects.requireNonNull(allowedBounds, "bounds");
}
@Override
public BlockBox bounds() {
edit.bounds();
return allowedBounds;
}
@Override
public BlockState get(int x, int y, int z) {
checkPosition(bounds(), x, y, z);
return edit.get(x, y, z);
}
@Override
public void set(PlacedBlock block) {
var position = block.position();
checkPosition(bounds(), position.x(), position.y(), position.z());
edit.set(block);
}
@Override
public void marker(PlacedMarker marker) {
var position = marker.position();
checkPosition(bounds(), position.x(), position.y(), position.z());
edit.marker(marker);
}
@Override
public Mantle mantle() {
return restrictMantle(edit.mantle(), bounds());
}
}
private static final class RestrictedMantle implements Mantle {
private final Mantle parent;
private final BlockBox allowedBounds;
private RestrictedMantle(Mantle parent, BlockBox allowedBounds) {
this.parent = Objects.requireNonNull(parent, "parent");
this.allowedBounds = Objects.requireNonNull(allowedBounds, "bounds");
}
@Override
public BlockBox bounds() {
parent.bounds();
return allowedBounds;
}
@Override
public MantleEdit edit() {
bounds();
throw new UnsupportedOperationException("Placement owns the mantle edit");
}
@Override
public <T> MantleLayer<T> layer(MantleKey<T> key) {
bounds();
return new RestrictedMantleLayer<>(this, parent.layer(key));
}
}
private static final class RestrictedMantleLayer<T> implements MantleLayer<T> {
private final RestrictedMantle owner;
private final MantleLayer<T> layer;
private RestrictedMantleLayer(RestrictedMantle owner, MantleLayer<T> layer) {
this.owner = Objects.requireNonNull(owner, "owner");
this.layer = Objects.requireNonNull(layer, "layer");
}
@Override
public T get(int x, int y, int z) {
checkPosition(owner.bounds(), x, y, z);
return layer.get(x, y, z);
}
@Override
public void set(int x, int y, int z, T value) {
checkPosition(owner.bounds(), x, y, z);
layer.set(x, y, z, value);
}
@Override
public void remove(int x, int y, int z) {
checkPosition(owner.bounds(), x, y, z);
layer.remove(x, y, z);
}
@Override
public void visit(BlockBox area, MantleVisitor<T> visitor) {
checkArea(owner.bounds(), area);
layer.visit(area, Objects.requireNonNull(visitor, "visitor"));
}
@Override
public void clear(BlockBox area) {
checkArea(owner.bounds(), area);
layer.clear(area);
}
}
}
+14
View File
@@ -0,0 +1,14 @@
package com.volmit.hunk;
/** Dense local volume. Coordinates range from zero inclusive to each dimension exclusive.
* Reads/writes outside that range throw IndexOutOfBoundsException. Null values are forbidden;
* block volumes represent empty space with an air state. Invocation-owned hunks must not escape.
* This is a new minimal contract, not a copy of Iris's full Hunk implementation.
*/
public interface Hunk<T> {
int getWidth();
int getHeight();
int getDepth();
T get(int x, int y, int z);
void set(int x, int y, int z, T value);
}
@@ -0,0 +1,23 @@
package com.volmit.mantle;
import java.util.Objects;
/** World block bounds, minimum inclusive and maximum exclusive. Empty boxes are valid. */
public record BlockBox(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) {
public BlockBox {
if (minX > maxX || minY > maxY || minZ > maxZ) {
throw new IllegalArgumentException("Inverted block bounds");
}
}
public boolean contains(int x, int y, int z) {
return x >= minX && x < maxX && y >= minY && y < maxY && z >= minZ && z < maxZ;
}
public boolean contains(BlockBox area) {
Objects.requireNonNull(area, "area");
return area.minX >= minX && area.maxX <= maxX
&& area.minY >= minY && area.maxY <= maxY
&& area.minZ >= minZ && area.maxZ <= maxZ;
}
}
@@ -0,0 +1,28 @@
package com.volmit.mantle;
/**
* Invocation-scoped access to typed mantle data. Coordinates are world block coordinates,
* including negative Y; the host translates them to storage coordinates.
*
* <p>The host owns chunk acquisition, release, persistence and the permitted access area.
* Out-of-area access throws IndexOutOfBoundsException. Access after the invocation ends
* throws IllegalStateException. Do not retain this interface or use it from detached tasks.
* Concurrent use of one instance is not supported unless the host explicitly permits it.
*
* <p>Only registered layers are supported. Unknown IDs or mismatched registered types throw
* IllegalArgumentException. Null arguments are rejected. Layer views share this view's lifetime.
*
* <p>Writes affect generation storage, not necessarily the current chunk Hunk or live world.
* Direct writes have no rollback guarantee. Use edit() to buffer multi-layer changes.
* The host must serialize overlapping writes; read-modify-write is not independently atomic.
*/
public interface Mantle {
BlockBox bounds();
<T> MantleLayer<T> layer(MantleKey<T> key);
/** Only one edit may be active per view. Parent reads remain allowed, but parent
* mutations are prohibited until the edit ends (IllegalStateException).
*/
MantleEdit edit();
}
@@ -0,0 +1,18 @@
package com.volmit.mantle;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/** Value serialization. Host frames payloads and stores key ID and version separately.
* Implementations must support concurrent calls, must not close streams, and must reject
* malformed data or unsupported stored versions with IOException. Values cannot be null.
*/
public interface MantleCodec<T> {
/** Nonnegative format version, stable for the registration lifetime. */
int version();
void write(DataOutput output, T value) throws IOException;
T read(DataInput input, int storedVersion) throws IOException;
}
@@ -0,0 +1,19 @@
package com.volmit.mantle;
/** Buffered changes across layers, with the parent's bounds and registrations.
* Reads and visits include buffered replacements/removals over the unchanged parent.
* Nested edits are unsupported: edit() throws UnsupportedOperationException.
* The host excludes competing writers; this is not a concurrent or disk transaction.
*/
public interface MantleEdit extends Mantle, AutoCloseable {
/** Publishes all changes to the parent or leaves it unchanged on failure.
* Successful commit ends the edit and invalidates its layer views. On failure the
* edit can only be closed. Repeated commit throws IllegalStateException.
* This guarantee applies to generation storage, not crash recovery or world writes.
*/
void commit();
/** Discards uncommitted changes and invalidates edit views. Idempotent after commit/close. */
@Override
void close();
}
@@ -0,0 +1,17 @@
package com.volmit.mantle;
import java.util.Objects;
/** Stable storage identity. Different IDs may use the same value class without sharing data. */
public record MantleKey<T>(String id, Class<T> type) {
public MantleKey {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(type, "type");
if (!id.matches("[a-z0-9_.-]+:[a-z0-9_./-]+")) {
throw new IllegalArgumentException("Expected a namespaced mantle ID: " + id);
}
if (type.isPrimitive()) {
throw new IllegalArgumentException("Mantle values require a reference type");
}
}
}
@@ -0,0 +1,25 @@
package com.volmit.mantle;
/** A registered layer bounded by its owning Mantle view and sharing its lifetime.
* Values must be non-null and treated as immutable. Wrong value types are rejected with
* IllegalArgumentException; null arguments with NullPointerException.
*/
public interface MantleLayer<T> {
/** Returns null on absence, without allocating a storage section. */
T get(int x, int y, int z);
void set(int x, int y, int z, T value);
/** Removing an absent entry is a no-op. */
void remove(int x, int y, int z);
/** Visits stored entries only, in ascending x, then y, then z order.
* Area must be fully within bounds (no silent clipping). Callbacks must not mutate
* this layer directly. An edit may buffer changes while visiting its parent layer.
* Callback exceptions propagate and stop traversal. No snapshot allocation is required.
*/
void visit(BlockBox area, MantleVisitor<T> visitor);
/** Removes all entries in the fully bounded area; other layers are untouched. */
void clear(BlockBox area);
}
@@ -0,0 +1,8 @@
package com.volmit.mantle;
public enum MantleLifetime {
/** May be removed only after all generation consumers, including neighbors, finish. */
GENERATION,
/** Survives generation cleanup; explicit removal is still permitted. */
PERSISTENT
}
@@ -0,0 +1,6 @@
package com.volmit.mantle;
@FunctionalInterface
public interface MantleVisitor<T> {
void accept(int x, int y, int z, T value);
}
@@ -0,0 +1,34 @@
package com.volmit.object;
import com.volmit.resource.ResourceId;
import java.util.Arrays;
import java.util.Objects;
/** Immutable versioned payload. The host's adapter owns interpretation and size limits.
* Unsupported formats/versions fail explicitly; native objects and mutable buffers never escape.
*/
public final class BlockEntityData {
private final ResourceId format;
private final int version;
private final byte[] payload;
public BlockEntityData(ResourceId format, int version, byte[] payload) {
this.format = Objects.requireNonNull(format, "format");
if (version < 0) throw new IllegalArgumentException("Negative block entity format version");
this.version = version;
this.payload = Objects.requireNonNull(payload, "payload").clone();
}
public ResourceId format() { return format; }
public int version() { return version; }
public byte[] payload() { return payload.clone(); }
@Override
public boolean equals(Object other) {
return other instanceof BlockEntityData data && format.equals(data.format)
&& version == data.version && Arrays.equals(payload, data.payload);
}
@Override
public int hashCode() { return 31 * Objects.hash(format, version) + Arrays.hashCode(payload); }
}
@@ -0,0 +1,36 @@
package com.volmit.object;
import com.volmit.mantle.BlockBox;
import com.volmit.world.BlockPosition;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
/** Immutable sparse geometry, safe to cache per pack snapshot.
* Bounds are local, minima inclusive/maxima exclusive, and include blocks and markers.
* The anchor may lie outside the bounds. Placement aligns it with a requested world position.
* Blocks are sorted by x/y/z; duplicates fail. Marker order at an equal position is declaration
* order. This value contains no placement settings, random state, or native platform objects.
*/
public record GeneratedObject(BlockBox bounds, BlockPosition anchor,
List<ObjectBlock> blocks, List<ObjectMarker> markers) {
public GeneratedObject {
Objects.requireNonNull(bounds, "bounds");
Objects.requireNonNull(anchor, "anchor");
blocks = List.copyOf(blocks).stream().sorted(Comparator.comparing(ObjectBlock::position)).toList();
markers = List.copyOf(markers).stream().sorted(Comparator.comparing(ObjectMarker::position)).toList();
var positions = new HashSet<BlockPosition>();
for (var block : blocks) {
checkPosition(bounds, block.position());
if (!positions.add(block.position())) throw new IllegalArgumentException("Duplicate object block: " + block.position());
}
for (var marker : markers) checkPosition(bounds, marker.position());
}
private static void checkPosition(BlockBox bounds, BlockPosition position) {
if (!bounds.contains(position.x(), position.y(), position.z())) {
throw new IllegalArgumentException("Object entry outside bounds: " + position);
}
}
}
@@ -0,0 +1,17 @@
package com.volmit.object;
import com.volmit.block.BlockState;
import com.volmit.world.BlockPosition;
import java.util.Objects;
import java.util.Optional;
/** One sparse block in object-local coordinates. Absence is distinct from an explicit air block. */
public record ObjectBlock(BlockPosition position, BlockState state, Optional<BlockEntityData> blockEntity) {
public ObjectBlock {
Objects.requireNonNull(position, "position");
Objects.requireNonNull(state, "state");
Objects.requireNonNull(blockEntity, "blockEntity");
}
public ObjectBlock(BlockPosition position, BlockState state) { this(position, state, Optional.empty()); }
}
@@ -0,0 +1,8 @@
package com.volmit.object;
import com.volmit.generation.InvocationContext;
/** Geometry-only invocation. The host chooses the variant seed and enforces size limits.
* Placement and terrain adaptation happen later; generators return reusable local geometry.
*/
public interface ObjectGenerationContext extends InvocationContext {}
@@ -0,0 +1,9 @@
package com.volmit.object;
/** Configured geometry generator. Snapshot settings; concurrent calls use only invocation-local
* state. Return a non-null object. The host owns variant selection and snapshot-scoped caching.
*/
@FunctionalInterface
public interface ObjectGenerator {
GeneratedObject generate(ObjectGenerationContext context);
}
@@ -0,0 +1,8 @@
package com.volmit.object;
import com.volmit.IrisFeature;
@FunctionalInterface
public interface ObjectGeneratorFactory<F extends IrisFeature> {
ObjectGenerator create(F feature);
}
@@ -0,0 +1,15 @@
package com.volmit.object;
import com.volmit.resource.ResourceId;
import com.volmit.world.BlockPosition;
import java.util.Map;
import java.util.Objects;
/** Immutable, named metadata in object-local coordinates. The registered host/module owns meaning. */
public record ObjectMarker(BlockPosition position, ResourceId type, Map<String, String> attributes) {
public ObjectMarker {
Objects.requireNonNull(position, "position");
Objects.requireNonNull(type, "type");
attributes = Map.copyOf(attributes);
}
}
@@ -0,0 +1,20 @@
package com.volmit.object;
/** Requested transform. The host owns rasterization, property orientation and interpolation.
* Rotation is in degrees about the object's anchor; mirrors precede scale, then X/Y/Z rotation.
* Unsupported transformations fail rather than silently changing the request.
*/
public record ObjectTransform(double rotationX, double rotationY, double rotationZ,
double scaleX, double scaleY, double scaleZ,
boolean mirrorX, boolean mirrorY, boolean mirrorZ) {
public ObjectTransform {
for (double angle : new double[]{rotationX, rotationY, rotationZ}) {
if (!Double.isFinite(angle)) throw new IllegalArgumentException("Non-finite rotation");
}
for (double scale : new double[]{scaleX, scaleY, scaleZ}) {
if (!Double.isFinite(scale) || scale <= 0) throw new IllegalArgumentException("Scale must be finite and positive");
}
}
public static ObjectTransform identity() { return new ObjectTransform(0, 0, 0, 1, 1, 1, false, false, false); }
}
@@ -0,0 +1,9 @@
package com.volmit.object;
/** Host adapter returning immutable transformed geometry with updated bounds, block properties,
* block entities and markers. Cache keys include pack snapshot, source geometry and transform.
*/
@FunctionalInterface
public interface ObjectTransformer {
GeneratedObject transform(GeneratedObject object, ObjectTransform transform);
}
@@ -0,0 +1,16 @@
package com.volmit.placement;
import com.volmit.block.BlockState;
import com.volmit.object.BlockEntityData;
import com.volmit.world.BlockPosition;
import java.util.Objects;
import java.util.Optional;
/** A proposed or buffered write in world coordinates, including its block entity payload. */
public record PlacedBlock(BlockPosition position, BlockState state, Optional<BlockEntityData> blockEntity) {
public PlacedBlock {
Objects.requireNonNull(position, "position");
Objects.requireNonNull(state, "state");
Objects.requireNonNull(blockEntity, "blockEntity");
}
}
@@ -0,0 +1,15 @@
package com.volmit.placement;
import com.volmit.resource.ResourceId;
import com.volmit.world.BlockPosition;
import java.util.Map;
import java.util.Objects;
/** Marker metadata in world coordinates. */
public record PlacedMarker(BlockPosition position, ResourceId type, Map<String, String> attributes) {
public PlacedMarker {
Objects.requireNonNull(position, "position");
Objects.requireNonNull(type, "type");
attributes = Map.copyOf(attributes);
}
}
@@ -0,0 +1,15 @@
package com.volmit.placement;
import com.volmit.mantle.Mantle;
import com.volmit.world.BlockView;
/** Buffered world-space access for placement hooks, without ownership of commit/close.
* Reads include the overlay. Bounds cover the object's footprint plus declared horizontal reach
* and host-authorized vertical area. Block/entity/marker/mantle writes share the host edit.
* Out-of-area access throws; nested mantle edits are unsupported. Do not retain this view.
*/
public interface PlacementAccess extends BlockView {
void set(PlacedBlock block);
void marker(PlacedMarker marker);
Mantle mantle();
}
@@ -0,0 +1,18 @@
package com.volmit.placement;
import com.volmit.config.FeatureSettings;
import com.volmit.generation.InvocationContext;
import com.volmit.object.ObjectTransformer;
import com.volmit.world.TerrainSampler;
import com.volmit.world.BlockView;
/** Read-only inputs to placement hooks. Working state is carried by returned immutable requests
* and blocks, never stored on a configured modifier. Context lifetime ends with placement.
*/
public interface PlacementContext extends InvocationContext {
TerrainSampler terrain();
FeatureSettings settings();
ObjectTransformer objects();
/** Prepared blocks before this placement. Use hook access for reads of buffered changes. */
BlockView blocks();
}
@@ -0,0 +1,14 @@
package com.volmit.placement;
/** Host-owned buffered placement writes, in world coordinates, including cross-chunk writes.
* All reads see the overlay. Block/entity/marker/mantle mutations participate in one commit.
* Out-of-bounds access fails, never clips. The host excludes competing writers and handles
* block entity replacement/removal when states change. Nested mantle edits are unsupported.
* Successful commit ends the edit; failure leaves the parent unchanged and permits only close.
* Close is idempotent and discards uncommitted work. Views expire when this edit ends.
* This is a generation-storage transaction, not live-world or disk/crash atomicity.
*/
public interface PlacementEdit extends PlacementAccess, AutoCloseable {
void commit();
@Override void close();
}
@@ -0,0 +1,24 @@
package com.volmit.placement;
import com.volmit.generation.Dependencies;
import java.util.Optional;
/** Configured placement behavior. IDs are namespaced; dependencies refer only to placement
* modifier IDs, not chunk modifiers. Snapshot settings; calls may occur concurrently.
* The host runs prepare for all modifiers, mapBlock for each candidate, then validate for all
* modifiers before buffering any write. beforePlace runs after validation but before object
* writes, for boring/preparation. afterPlace runs only after all accepted blocks and
* markers are buffered, allowing vacuum/stilts to observe the final footprint and overlay.
* Exceptions discard the attempt. Empty prepare rejects it; empty mapBlock skips one block.
*/
public abstract class PlacementModifier {
public abstract String id();
public Dependencies depends() { return Dependencies.none(); }
/** Horizontal access beyond the resulting object footprint; nonnegative, read at pack load. */
public int writeRadius() { return 0; }
public Optional<PlacementRequest> prepare(PlacementContext context, PlacementRequest request) { return Optional.of(request); }
public Optional<PlacedBlock> mapBlock(PlacementContext context, PlacedBlock block) { return Optional.of(block); }
public boolean validate(PlacementContext context, PlacementPlan plan) { return true; }
public void beforePlace(PlacementContext context, PlacementAccess access, PlacementPlan proposed) {}
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan written) {}
}
@@ -0,0 +1,8 @@
package com.volmit.placement;
import com.volmit.IrisFeature;
@FunctionalInterface
public interface PlacementModifierFactory<F extends IrisFeature> {
PlacementModifier create(F feature);
}
@@ -0,0 +1,37 @@
package com.volmit.placement;
import com.volmit.mantle.BlockBox;
import com.volmit.world.BlockPosition;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/** Complete proposed writes, constructed before validation or mutation.
* Block positions are unique and ordered x/y/z. writtenBounds describes block writes only;
* markers and the original object's declared footprint are tracked separately.
*/
public record PlacementPlan(PlacementRequest request, List<PlacedBlock> blocks, List<PlacedMarker> markers) {
public PlacementPlan {
Objects.requireNonNull(request, "request");
blocks = List.copyOf(blocks).stream().sorted(Comparator.comparing(PlacedBlock::position)).toList();
markers = List.copyOf(markers).stream().sorted(Comparator.comparing(PlacedMarker::position)).toList();
var positions = new HashSet<BlockPosition>();
for (var block : blocks) {
if (!positions.add(block.position())) throw new IllegalArgumentException("Duplicate placement write: " + block.position());
}
}
public Optional<BlockBox> writtenBounds() {
if (blocks.isEmpty()) return Optional.empty();
int minX = Integer.MAX_VALUE, minY = Integer.MAX_VALUE, minZ = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE, maxY = Integer.MIN_VALUE, maxZ = Integer.MIN_VALUE;
for (var block : blocks) {
var position = block.position();
minX = Math.min(minX, position.x()); minY = Math.min(minY, position.y()); minZ = Math.min(minZ, position.z());
maxX = Math.max(maxX, position.x()); maxY = Math.max(maxY, position.y()); maxZ = Math.max(maxZ, position.z());
}
return Optional.of(new BlockBox(minX, minY, minZ, Math.addExact(maxX, 1), Math.addExact(maxY, 1), Math.addExact(maxZ, 1)));
}
}
@@ -0,0 +1,36 @@
package com.volmit.placement;
import com.volmit.mantle.BlockBox;
import com.volmit.object.GeneratedObject;
import com.volmit.resource.ResourceId;
import com.volmit.world.BlockPosition;
import java.util.Objects;
/** One placement attempt. Geometry is already transformed; anchor is a world block position.
* World position = local position - object anchor + request anchor. Arithmetic never wraps.
* id identifies this attempt within the host's generation plan.
*/
public record PlacementRequest(ResourceId id, GeneratedObject object, BlockPosition anchor) {
public PlacementRequest {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(object, "object");
Objects.requireNonNull(anchor, "anchor");
}
public BlockPosition worldPosition(BlockPosition local) {
return new BlockPosition(translate(local.x(), object.anchor().x(), anchor.x()),
translate(local.y(), object.anchor().y(), anchor.y()),
translate(local.z(), object.anchor().z(), anchor.z()));
}
public BlockBox footprint() {
var bounds = object.bounds();
var min = worldPosition(new BlockPosition(bounds.minX(), bounds.minY(), bounds.minZ()));
var max = worldPosition(new BlockPosition(bounds.maxX(), bounds.maxY(), bounds.maxZ()));
return new BlockBox(min.x(), min.y(), min.z(), max.x(), max.y(), max.z());
}
private static int translate(int local, int objectAnchor, int worldAnchor) {
return Math.toIntExact((long) local - objectAnchor + worldAnchor);
}
}
@@ -0,0 +1,23 @@
package com.volmit.resource;
import com.volmit.block.BlockRegistry;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.UUID;
/** Immutable view of one loaded pack snapshot, safe for concurrent reads.
* Reload produces a different snapshotId, even for the same pack. Resources must be immutable
* or explicitly thread-safe. Unknown IDs return empty; a known ID with the wrong requested
* type throws IllegalArgumentException. Broken resources fail loading rather than appearing absent.
* The host owns resolution, imports, native handles and caches; no filesystem paths escape.
*/
public interface PackResources {
ResourceId packId();
UUID snapshotId();
BlockRegistry blocks();
<T> Optional<T> find(ResourceKey<T> key);
default <T> T require(ResourceKey<T> key) {
return find(key).orElseThrow(() -> new NoSuchElementException("Missing resource: " + key.id()));
}
}
@@ -0,0 +1,27 @@
package com.volmit.resource;
import java.util.Objects;
/** Case-sensitive namespaced identity. Parsing never supplies an implicit namespace. */
public record ResourceId(String namespace, String path) implements Comparable<ResourceId> {
public ResourceId {
Objects.requireNonNull(namespace, "namespace");
Objects.requireNonNull(path, "path");
if (!namespace.matches("[a-z0-9_.-]+") || !path.matches("[a-z0-9_./-]+")) {
throw new IllegalArgumentException("Invalid resource ID: " + namespace + ":" + path);
}
}
public static ResourceId parse(String value) {
Objects.requireNonNull(value, "value");
int separator = value.indexOf(':');
if (separator < 0) throw new IllegalArgumentException("Expected a namespaced ID: " + value);
return new ResourceId(value.substring(0, separator), value.substring(separator + 1));
}
@Override
public String toString() { return namespace + ":" + path; }
@Override
public int compareTo(ResourceId other) { return toString().compareTo(other.toString()); }
}
@@ -0,0 +1,14 @@
package com.volmit.resource;
import java.util.Objects;
/** A resource ID paired with its public value type; the host owns loading and caching. */
public record ResourceKey<T>(ResourceId id, Class<T> type) {
public ResourceKey {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(type, "type");
if (type.isPrimitive()) throw new IllegalArgumentException("Resources require a reference type");
}
public ResourceKey(String id, Class<T> type) { this(ResourceId.parse(id), type); }
}
@@ -0,0 +1,14 @@
package com.volmit.world;
import com.volmit.resource.ResourceId;
import java.util.Objects;
import java.util.Optional;
/** Pack biome identity, distinct from the platform biome written into the chunk. */
public record BiomeSample(ResourceId region, ResourceId surfaceBiome, Optional<ResourceId> caveBiome) {
public BiomeSample {
Objects.requireNonNull(region, "region");
Objects.requireNonNull(surfaceBiome, "surfaceBiome");
Objects.requireNonNull(caveBiome, "caveBiome");
}
}
@@ -0,0 +1,19 @@
package com.volmit.world;
/** A block position. Owning contracts specify whether it is local or world space. */
public record BlockPosition(int x, int y, int z) implements Comparable<BlockPosition> {
public BlockPosition add(BlockPosition offset) {
return new BlockPosition(Math.addExact(x, offset.x), Math.addExact(y, offset.y), Math.addExact(z, offset.z));
}
public BlockPosition subtract(BlockPosition offset) {
return new BlockPosition(Math.subtractExact(x, offset.x), Math.subtractExact(y, offset.y), Math.subtractExact(z, offset.z));
}
@Override
public int compareTo(BlockPosition other) {
int result = Integer.compare(x, other.x);
if (result == 0) result = Integer.compare(y, other.y);
return result == 0 ? Integer.compare(z, other.z) : result;
}
}
@@ -0,0 +1,13 @@
package com.volmit.world;
import com.volmit.block.BlockState;
import com.volmit.mantle.BlockBox;
/** Read-only prepared generation blocks in world coordinates, not the live server world.
* Empty space is a non-null air state. Out-of-area access throws IndexOutOfBoundsException.
* Views expire with the owning invocation; access afterwards throws IllegalStateException.
*/
public interface BlockView {
BlockBox bounds();
BlockState get(int worldX, int worldY, int worldZ);
}
@@ -0,0 +1,9 @@
package com.volmit.world;
/** Immutable, seeded noise resource. Coordinates are world-space sample coordinates.
* Range and scale belong to the resource; no implicit normalization is performed.
*/
@FunctionalInterface
public interface NoiseSampler {
double sample(double worldX, double worldY, double worldZ);
}
@@ -0,0 +1,18 @@
package com.volmit.world;
import java.util.Objects;
import java.util.OptionalInt;
/** Pre-modification terrain sample in world coordinates.
* surfaceY is the top solid surface height, not the first air block. fluidY is the top fluid
* block when present. Slope is nonnegative height change per horizontal block.
* This is the host's terrain field, not a scan of current edited blocks.
*/
public record TerrainSample(double surfaceY, OptionalInt fluidY, double slope) {
public TerrainSample {
Objects.requireNonNull(fluidY, "fluidY");
if (!Double.isFinite(surfaceY) || !Double.isFinite(slope) || slope < 0) {
throw new IllegalArgumentException("Invalid terrain sample");
}
}
}
@@ -0,0 +1,13 @@
package com.volmit.world;
import com.volmit.mantle.BlockBox;
/** Read-only host sampling for the same pack snapshot as the invocation.
* Bounds are world blocks, maxima exclusive. Sampling outside prepared bounds fails with
* IndexOutOfBoundsException. Views expire with the invocation and must not escape it.
*/
public interface TerrainSampler {
BlockBox bounds();
TerrainSample column(int worldX, int worldZ);
BiomeSample biome(int worldX, int worldY, int worldZ);
}
@@ -0,0 +1,79 @@
package com.volmit;
import com.volmit.block.BlockState;
import com.volmit.host.ArrayHunk;
import com.volmit.mantle.BlockBox;
import com.volmit.object.*;
import com.volmit.placement.PlacementRequest;
import com.volmit.resource.*;
import com.volmit.world.*;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.OptionalInt;
import static org.junit.jupiter.api.Assertions.*;
class ApiValuesTest {
@Test
void idsAndStateKeysAreExplicitCanonicalImmutableValues() {
for (String invalid : List.of("stone", "Minecraft:stone", "a:b:c", "a:", ":a")) {
assertThrows(IllegalArgumentException.class, () -> ResourceId.parse(invalid));
}
var properties = new HashMap<>(Map.of("waterlogged", "false", "axis", "y"));
var state = new BlockState(ResourceId.parse("minecraft:oak_log"), properties);
properties.clear();
assertEquals("minecraft:oak_log[axis=y,waterlogged=false]", state.key());
assertEquals("y", state.properties().get("axis"));
assertEquals("x", state.withProperty("axis", "x").properties().get("axis"));
assertThrows(UnsupportedOperationException.class, () -> state.properties().clear());
assertThrows(IllegalArgumentException.class, () -> new ResourceKey<>("test:value", int.class));
}
@Test
void sparseObjectsCopySortAndRejectDuplicateOrOutOfBoundsBlocks() {
var a = new ObjectBlock(new BlockPosition(-1, 0, 0), new BlockState("minecraft:stone"));
var b = new ObjectBlock(new BlockPosition(1, 0, 0), new BlockState("minecraft:stone"));
var blocks = new ArrayList<>(List.of(b, a));
var bounds = new BlockBox(-1, 0, 0, 2, 1, 1);
var object = new GeneratedObject(bounds, new BlockPosition(0, 0, 0), blocks, List.of());
blocks.clear();
assertEquals(List.of(a, b), object.blocks());
assertThrows(IllegalArgumentException.class, () -> new GeneratedObject(bounds, object.anchor(), List.of(a, a), List.of()));
assertThrows(IllegalArgumentException.class, () -> new GeneratedObject(new BlockBox(0, 0, 0, 1, 1, 1), object.anchor(), List.of(a), List.of()));
}
@Test
void payloadBuffersDoNotEscapeAndHaveValueEquality() {
byte[] source = {1, 2};
var payload = new BlockEntityData(ResourceId.parse("test:tile"), 1, source);
source[0] = 99;
payload.payload()[0] = 98;
assertArrayEquals(new byte[]{1, 2}, payload.payload());
assertEquals(payload, new BlockEntityData(ResourceId.parse("test:tile"), 1, new byte[]{1, 2}));
}
@Test
void placementAlignsAnchorsAndCheckedArithmeticNeverWraps() {
var object = new GeneratedObject(new BlockBox(-1, -1, -1, 2, 2, 2), new BlockPosition(1, 1, 1), List.of(), List.of());
var request = new PlacementRequest(ResourceId.parse("test:placement"), object, new BlockPosition(-16, -64, -16));
assertEquals(new BlockPosition(-16, -64, -16), request.worldPosition(object.anchor()));
assertEquals(new BlockBox(-18, -66, -18, -15, -63, -15), request.footprint());
var overflow = new PlacementRequest(request.id(), object, new BlockPosition(Integer.MAX_VALUE, 0, 0));
assertThrows(ArithmeticException.class, overflow::footprint);
}
@Test
void boundedHunksAndTerrainSamplesRejectInvalidInputs() {
var hunk = new ArrayHunk<>(String.class, 2, 3, 4, "air");
hunk.set(1, 2, 3, "stone");
assertEquals("stone", hunk.get(1, 2, 3));
assertEquals("air", hunk.get(0, 0, 0));
assertThrows(IndexOutOfBoundsException.class, () -> hunk.get(2, 0, 0));
assertThrows(IndexOutOfBoundsException.class, () -> hunk.set(-1, 0, 0, "stone"));
assertThrows(NullPointerException.class, () -> hunk.set(0, 0, 0, null));
assertThrows(IllegalArgumentException.class, () -> new TerrainSample(Double.NaN, OptionalInt.empty(), 0));
assertThrows(IllegalArgumentException.class, () -> new TerrainSample(0, OptionalInt.empty(), -1));
}
}
@@ -0,0 +1,77 @@
package com.volmit;
import com.volmit.config.*;
import com.volmit.generation.*;
import com.volmit.hunk.Hunk;
import com.volmit.host.ArrayHunk;
import com.volmit.host.ModuleRegistry;
import com.volmit.resource.ResourceId;
import com.volmit.support.TestContexts;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class FeatureContractTest {
@Desc("Example settings")
@Snippet("fill-settings")
@Feature(id = "example:fill", name = "Fill", field = "fill", targets = FeatureAttachment.Target.BIOME)
public static class FillOptions implements IrisFeature {
@Desc("Replacement value")
@MinNumber(0)
@MaxNumber(128)
private int value = 12;
private transient int cache;
private static int ignored;
}
@Test
void readsPrivateAnnotatedOptionsWithoutIncludingRuntimeState() {
var metadata = OptionsMetadata.inspect(FillOptions.class);
assertEquals("Example settings", metadata.description());
assertEquals("fill-settings", metadata.snippet());
assertEquals(1, metadata.options().size());
var option = metadata.options().getFirst();
assertEquals("value", option.name());
assertEquals(int.class, option.type());
assertEquals("Replacement value", option.description());
assertEquals(0.0, option.minimum());
assertEquals(128.0, option.maximum());
}
@Test
void registryBindsDecodedOptionsToTheCorrectModifier() {
var host = new ModuleRegistry();
host.register(FillOptions.class, Integer.class, FillModifier::new);
var registration = host.freeze().generation(FillOptions.class, Integer.class);
var modifier = registration.configure(ResourceId.parse("test:fill/0"), new FillOptions());
var output = new ArrayHunk<>(Integer.class, 1, 1, 1, 0);
modifier.modify(TestContexts.generation(), output);
assertEquals(12, output.get(0, 0, 0));
}
private static class FillModifier extends GenerationModifier<Integer> {
private final FillOptions options;
FillModifier(FillOptions options) {
this.options = options;
}
public String id() { return "example:fill-modifier"; }
public void modify(GenerationContext context, Hunk<Integer> volume) {
volume.set(0, 0, 0, options.value);
}
}
static class InvalidOptions {
@MinNumber(10) @MaxNumber(2) private int value;
}
static class NonnumericOptions {
@MinNumber(0) private String value;
}
@Test
void rejectsInconsistentAnnotationBounds() {
assertThrows(IllegalArgumentException.class, () -> OptionsMetadata.inspect(InvalidOptions.class));
assertThrows(IllegalArgumentException.class, () -> OptionsMetadata.inspect(NonnumericOptions.class));
}
}
@@ -0,0 +1,54 @@
package com.volmit.generation;
import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
class DependenciesTest {
@Test
void accumulatesAndDeduplicatesWithoutMutatingEarlierDeclarations() {
var original = Dependencies.requires("iris:terrain", "iris:terrain");
var result = original.andRequires("iris:carving")
.afterIfPresent("example:caves").afterIfPresent("example:lakes")
.beforeIfPresent("iris:ores").beforeIfPresent("iris:ores", "iris:objects");
assertEquals(Set.of("iris:terrain"), original.required());
assertTrue(original.after().isEmpty());
assertTrue(original.before().isEmpty());
assertEquals(Set.of("iris:terrain", "iris:carving"), result.required());
assertEquals(Set.of("example:caves", "example:lakes"), result.after());
assertEquals(Set.of("iris:ores", "iris:objects"), result.before());
}
@Test
void copiesInputsAndExposesImmutableSets() {
var ids = new HashSet<>(Set.of("iris:terrain"));
var result = new Dependencies(ids, ids, ids);
ids.clear();
assertEquals(Set.of("iris:terrain"), result.required());
assertThrows(UnsupportedOperationException.class, () -> result.required().clear());
assertThrows(UnsupportedOperationException.class, () -> result.after().clear());
assertThrows(UnsupportedOperationException.class, () -> result.before().clear());
String[] input = {"iris:terrain"};
var fromArray = Dependencies.requires(input);
input[0] = "iris:ores";
assertEquals(Set.of("iris:terrain"), fromArray.required());
}
@Test
void supportsEmptyAndOptionalOnlyDeclarations() {
assertEquals(new Dependencies(Set.of(), Set.of(), Set.of()), Dependencies.none());
assertEquals(Dependencies.none(), Dependencies.requires());
assertEquals(Set.of("iris:ores"), Dependencies.none().beforeIfPresent("iris:ores").before());
}
@Test
void rejectsNullAndBlankIds() {
assertThrows(IllegalArgumentException.class, () -> Dependencies.requires(" "));
assertThrows(IllegalArgumentException.class, () -> Dependencies.none().afterIfPresent(""));
assertThrows(IllegalArgumentException.class, () -> Dependencies.none().beforeIfPresent("\n"));
assertThrows(NullPointerException.class, () -> Dependencies.requires((String) null));
assertThrows(NullPointerException.class, () -> Dependencies.requires((String[]) null));
assertThrows(NullPointerException.class, () -> new Dependencies(null, Set.of(), Set.of()));
}
}
@@ -0,0 +1,85 @@
package com.volmit.host;
import com.volmit.generation.*;
import com.volmit.hunk.Hunk;
import com.volmit.resource.ResourceId;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class GenerationPlanTest {
private static ResourceId id(String path) { return ResourceId.parse("test:" + path); }
private static ConfiguredModifier<String> binding(String occurrence, String name, Dependencies dependencies) {
return new ConfiguredModifier<>(id(occurrence), String.class, new Modifier(name, dependencies));
}
private static class Modifier extends GenerationModifier<String> {
private final String name;
private final Dependencies dependencies;
Modifier(String name, Dependencies dependencies) { this.name = name; this.dependencies = dependencies; }
public String id() { return "test:" + name; }
public Dependencies depends() { return dependencies; }
public void modify(GenerationContext context, Hunk<String> output) {}
}
@Test
void orderingIsIndependentOfDiscoveryAndIncludesRepeatedOccurrences() {
var first = binding("terrain/1", "terrain", Dependencies.none());
var second = binding("terrain/0", "terrain", Dependencies.none());
var caves = binding("caves/0", "caves", Dependencies.requires("test:terrain"));
var decoration = binding("decoration/0", "decoration", Dependencies.requires("test:caves").beforeIfPresent("test:missing"));
var a = GenerationPlan.resolve(List.of(decoration, first, caves, second));
var b = GenerationPlan.resolve(List.of(second, caves, decoration, first));
var expected = List.of(id("terrain/0"), id("terrain/1"), id("caves/0"), id("decoration/0"));
assertEquals(expected, a.ordered().stream().map(ConfiguredModifier::occurrence).toList());
assertEquals(expected, b.ordered().stream().map(ConfiguredModifier::occurrence).toList());
var executed = new ArrayList<ResourceId>();
a.execute(new GenerationPlan.Executor() {
public <T> void execute(ConfiguredModifier<T> modifier) { executed.add(modifier.occurrence()); }
});
assertEquals(expected, executed);
assertThrows(UnsupportedOperationException.class, () -> a.ordered().clear());
}
@Test
void rejectsMissingRequirementsSelfEdgesAndCycles() {
assertThrows(IllegalArgumentException.class, () -> DependencyOrder.resolve(Map.of(id("a"), Dependencies.requires("test:missing"))));
assertThrows(IllegalArgumentException.class, () -> DependencyOrder.resolve(Map.of(id("a"), Dependencies.none().beforeIfPresent("test:a"))));
assertThrows(IllegalArgumentException.class, () -> DependencyOrder.resolve(Map.of(id("a"), Dependencies.requires("test:b"), id("b"), Dependencies.requires("test:a"))));
}
@Test
void rejectsDuplicateOccurrencesAndConflictingImplementationsOrDeclarations() {
var a = binding("a/0", "a", Dependencies.none());
assertThrows(IllegalArgumentException.class, () -> GenerationPlan.resolve(List.of(a, a)));
assertThrows(IllegalArgumentException.class, () -> GenerationPlan.resolve(List.of(a,
binding("a/1", "a", Dependencies.none().afterIfPresent("test:b")))));
var otherImplementation = new ConfiguredModifier<>(id("a/2"), String.class, new Modifier("a", Dependencies.none()) {});
assertThrows(IllegalArgumentException.class, () -> GenerationPlan.resolve(List.of(a, otherImplementation)));
}
@Test
void repeatedEdgesAreCountedOnceAndIndependentIdsUseLexicalOrder() {
var graph = Map.of(id("a"), Dependencies.none(), id("z"), Dependencies.none(),
id("b"), Dependencies.requires("test:a").afterIfPresent("test:a"));
assertEquals(List.of(id("a"), id("b"), id("z")), DependencyOrder.resolve(graph));
}
@Test
void failuresStopDispatchAndNegativeReachFailsAtPackLoad() {
var plan = GenerationPlan.resolve(List.of(binding("a", "a", Dependencies.none()), binding("b", "b", Dependencies.none())));
var visited = new ArrayList<ResourceId>();
assertThrows(IllegalStateException.class, () -> plan.execute(new GenerationPlan.Executor() {
public <T> void execute(ConfiguredModifier<T> modifier) {
visited.add(modifier.id());
throw new IllegalStateException("Failed output");
}
}));
assertEquals(List.of(id("a")), visited);
assertThrows(IllegalArgumentException.class, () -> new ConfiguredModifier<>(id("negative"), String.class,
new Modifier("a", Dependencies.none()) { public int mantleRadius() { return -1; } }));
}
}
@@ -0,0 +1,95 @@
package com.volmit.host;
import com.volmit.*;
import com.volmit.config.Feature;
import com.volmit.generation.*;
import com.volmit.hunk.Hunk;
import com.volmit.mantle.*;
import com.volmit.placement.PlacementModifier;
import org.junit.jupiter.api.Test;
import java.io.DataInput;
import java.io.DataOutput;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
class ModuleRegistryTest {
@Feature(id = "test:one", name = "One", field = "shared", targets = FeatureAttachment.Target.BIOME)
static class One implements IrisFeature {}
@Feature(id = "test:two", name = "Two", field = "shared", targets = FeatureAttachment.Target.DIMENSION)
static class Two implements IrisFeature {}
@Feature(id = "test:collision", name = "Collision", field = "shared", targets = {FeatureAttachment.Target.DIMENSION, FeatureAttachment.Target.BIOME})
static class Collision implements IrisFeature {}
@Feature(id = "test:one", name = "Duplicate", field = "different", targets = FeatureAttachment.Target.REGION)
static class Duplicate implements IrisFeature {}
@Feature(id = "test:placement", name = "Placement", field = "foundation", targets = FeatureAttachment.Target.OBJECT_PLACEMENT)
static class Placement implements IrisFeature {}
static class MissingAnnotation implements IrisFeature {}
@Feature(id = "test:abstract", name = "Abstract", field = "abstract", targets = FeatureAttachment.Target.BIOME)
abstract static class AbstractFeature implements IrisFeature {}
private static GenerationModifier<String> modifier(IrisFeature ignored) {
return new GenerationModifier<>() {
public String id() { return "test:modifier"; }
public void modify(GenerationContext context, Hunk<String> output) {}
};
}
@Test
void validatesIdsTypesAndFieldsAcrossFeatureKindsWithoutPartialRegistration() {
var registry = new ModuleRegistry();
registry.register(One.class, String.class, ModuleRegistryTest::modifier);
assertThrows(IllegalArgumentException.class, () -> registry.register(Collision.class, String.class, ModuleRegistryTest::modifier));
registry.register(Two.class, String.class, ModuleRegistryTest::modifier);
assertThrows(IllegalArgumentException.class, () -> registry.registerObject(Duplicate.class, ignored -> context -> null));
assertThrows(IllegalArgumentException.class, () -> registry.register(One.class, String.class, ModuleRegistryTest::modifier));
var catalog = registry.freeze();
assertEquals(List.of("test:one", "test:two"), catalog.generation().stream().map(value -> value.descriptor().id().toString()).toList());
assertThrows(IllegalArgumentException.class, () -> catalog.generation(One.class, Integer.class));
}
@Test
void reservesHostFieldsAndRejectsInvalidFeaturesOrFactories() {
var registry = new ModuleRegistry(Map.of(FeatureAttachment.Target.BIOME, Set.of("shared")));
assertThrows(IllegalArgumentException.class, () -> registry.register(One.class, String.class, ModuleRegistryTest::modifier));
assertThrows(IllegalArgumentException.class, () -> registry.register(MissingAnnotation.class, String.class, ModuleRegistryTest::modifier));
assertThrows(IllegalArgumentException.class, () -> registry.register(AbstractFeature.class, String.class, ModuleRegistryTest::modifier));
assertThrows(NullPointerException.class, () -> registry.register(Two.class, String.class, null));
registry.register(Two.class, String.class, ModuleRegistryTest::modifier);
}
@Test
void placementMustAttachToPlacementAndFreezeEndsRegistration() {
var registry = new ModuleRegistry();
assertThrows(IllegalArgumentException.class, () -> registry.registerPlacement(One.class, ignored -> new PlacementModifier() {
public String id() { return "test:placement"; }
}));
registry.registerPlacement(Placement.class, ignored -> new PlacementModifier() {
public String id() { return "test:placement"; }
});
assertEquals(1, registry.freeze().placement().size());
assertSame(registry.freeze(), registry.freeze());
assertThrows(IllegalStateException.class, () -> registry.register(One.class, String.class, ModuleRegistryTest::modifier));
}
@Test
void mantleIdsAreUniqueAndCodecVersionIsSnapshotted() {
var registry = new ModuleRegistry();
var key = new MantleKey<>("test:owners", String.class);
var codec = codec(3);
registry.registerMantle(key, MantleLifetime.GENERATION, codec);
assertThrows(IllegalArgumentException.class, () -> registry.registerMantle(key, MantleLifetime.PERSISTENT, codec));
assertThrows(IllegalArgumentException.class, () -> registry.registerMantle(new MantleKey<>("test:bad", String.class), MantleLifetime.GENERATION, codec(-1)));
assertEquals(3, registry.freeze().mantle().getFirst().version());
assertEquals(1, registry.freeze().mantle().size());
}
private static MantleCodec<String> codec(int version) {
return new MantleCodec<>() {
public int version() { return version; }
public void write(DataOutput output, String value) {}
public String read(DataInput input, int storedVersion) { return ""; }
};
}
}
@@ -0,0 +1,259 @@
package com.volmit.host;
import com.volmit.block.BlockState;
import com.volmit.generation.Dependencies;
import com.volmit.mantle.*;
import com.volmit.object.*;
import com.volmit.placement.*;
import com.volmit.resource.ResourceId;
import com.volmit.support.TestContexts;
import com.volmit.world.BlockPosition;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
class PlacementPipelineTest {
private static final BlockState STONE = new BlockState("minecraft:stone");
private static final BlockState AIR = new BlockState("minecraft:air");
private static ResourceId id(String name) { return ResourceId.parse("test:" + name); }
private static PlacementRequest request() {
var object = new GeneratedObject(new BlockBox(0, 0, 0, 2, 1, 1), new BlockPosition(1, 0, 0),
List.of(new ObjectBlock(new BlockPosition(1, 0, 0), STONE), new ObjectBlock(new BlockPosition(0, 0, 0), STONE)),
List.of(new ObjectMarker(new BlockPosition(1, 0, 0), id("owner"), Map.of("name", "column"))));
return new PlacementRequest(id("attempt"), object, new BlockPosition(-2, -60, -3));
}
private static ConfiguredPlacementModifier configured(PlacementModifier modifier) {
return new ConfiguredPlacementModifier(ResourceId.parse(modifier.id() + "/0"), modifier);
}
@Test
void validatesCompletePlanBeforeWritesAndAfterHooksSeeOverlayAndActualBounds() {
var events = new ArrayList<String>();
var modifier = new PlacementModifier() {
public String id() { return "test:foundation"; }
public Optional<PlacementRequest> prepare(PlacementContext context, PlacementRequest request) {
events.add("prepare"); return Optional.of(request);
}
public Optional<PlacedBlock> mapBlock(PlacementContext context, PlacedBlock block) {
events.add("map");
return block.position().x() == -3 ? Optional.empty() : Optional.of(block);
}
public boolean validate(PlacementContext context, PlacementPlan plan) {
events.add("validate");
assertEquals(1, plan.blocks().size());
return true;
}
public void beforePlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) {
events.add("before");
assertEquals(AIR, access.get(-2, -60, -3));
}
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan written) {
events.add("after");
assertEquals(STONE, access.get(-2, -60, -3));
assertEquals(new BlockBox(-2, -60, -3, -1, -59, -2), written.writtenBounds().orElseThrow());
assertFalse(access instanceof PlacementEdit);
access.set(new PlacedBlock(new BlockPosition(-2, -61, -3), STONE, Optional.empty()));
}
};
var pipeline = PlacementPipeline.resolve(List.of(configured(modifier)));
var edit = new RecordingEdit(events);
var result = pipeline.place(request(), edit, ignored -> TestContexts.placement(), plan -> {
events.add("host-validate"); assertEquals(0, edit.mutations); return true;
});
assertTrue(result.isPresent());
assertEquals(List.of("prepare", "map", "map", "host-validate", "validate", "before", "write", "marker", "after", "write", "commit", "close"), events);
assertEquals(2, edit.published.size());
assertEquals(1, edit.publishedMarkers.size());
assertThrows(IllegalStateException.class, () -> edit.get(-2, -60, -3));
}
@Test
void validationRejectionPublishesNothingAndDoesNotStartMutating() {
var modifier = new PlacementModifier() {
public String id() { return "test:reject"; }
public boolean validate(PlacementContext context, PlacementPlan plan) { return false; }
};
var edit = new RecordingEdit(new ArrayList<>());
assertTrue(PlacementPipeline.resolve(List.of(configured(modifier)))
.place(request(), edit, ignored -> TestContexts.placement(), ignored -> true).isEmpty());
assertEquals(0, edit.mutations);
assertTrue(edit.published.isEmpty());
assertTrue(edit.closed);
}
@Test
void failureAfterBufferedObjectWritesDiscardsEntireAttempt() {
var modifier = new PlacementModifier() {
public String id() { return "test:failure"; }
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) {
access.set(new PlacedBlock(new BlockPosition(-2, -61, -3), STONE, Optional.empty()));
throw new IllegalStateException("Foundation failed");
}
};
var edit = new RecordingEdit(new ArrayList<>());
assertThrows(IllegalStateException.class, () -> PlacementPipeline.resolve(List.of(configured(modifier)))
.place(request(), edit, ignored -> TestContexts.placement(), ignored -> true));
assertTrue(edit.mutations > 0);
assertTrue(edit.published.isEmpty());
assertTrue(edit.publishedMarkers.isEmpty());
assertTrue(edit.closed);
}
@Test
void prepareRejectionAndFailedCommitCloseWithoutPublication() {
var rejection = new PlacementModifier() {
public String id() { return "test:prepare-reject"; }
public Optional<PlacementRequest> prepare(PlacementContext context, PlacementRequest request) { return Optional.empty(); }
};
var rejected = new RecordingEdit(new ArrayList<>());
assertTrue(PlacementPipeline.resolve(List.of(configured(rejection)))
.place(request(), rejected, ignored -> TestContexts.placement(), ignored -> true).isEmpty());
assertEquals(0, rejected.mutations);
var failed = new RecordingEdit(new ArrayList<>());
failed.failCommit = true;
assertThrows(IllegalStateException.class, () -> PlacementPipeline.resolve(List.of())
.place(request(), failed, ignored -> TestContexts.placement(), ignored -> true));
assertTrue(failed.closed);
assertTrue(failed.published.isEmpty());
}
@Test
void rejectsMappedBoundsDuplicateWritesAndInsufficientPreparedReachBeforeMutation() {
var escape = new PlacementModifier() {
public String id() { return "test:escape"; }
public Optional<PlacedBlock> mapBlock(PlacementContext context, PlacedBlock block) {
return Optional.of(new PlacedBlock(new BlockPosition(5, -60, -3), block.state(), block.blockEntity()));
}
};
var escaped = new RecordingEdit(new ArrayList<>());
assertThrows(IllegalArgumentException.class, () -> PlacementPipeline.resolve(List.of(configured(escape)))
.place(request(), escaped, ignored -> TestContexts.placement(), ignored -> true));
assertEquals(0, escaped.mutations);
var radius = new PlacementModifier() {
public String id() { return "test:radius"; }
public int writeRadius() { return 32; }
};
var unprepared = new RecordingEdit(new ArrayList<>());
assertThrows(IndexOutOfBoundsException.class, () -> PlacementPipeline.resolve(List.of(configured(radius)))
.place(request(), unprepared, ignored -> TestContexts.placement(), ignored -> true));
assertEquals(0, unprepared.mutations);
}
@Test
void hooksCannotWriteBeyondReachOrRetainUsableViews() {
var retained = new AtomicReference<PlacementAccess>();
var retainedLayer = new AtomicReference<MantleLayer<String>>();
var modifier = new PlacementModifier() {
public String id() { return "test:bounded"; }
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) {
retained.set(access);
retainedLayer.set(access.mantle().layer(new MantleKey<>("test:owner", String.class)));
assertThrows(IndexOutOfBoundsException.class, () -> access.set(new PlacedBlock(new BlockPosition(5, -60, -3), STONE, Optional.empty())));
assertThrows(UnsupportedOperationException.class, () -> access.mantle().edit());
assertThrows(IndexOutOfBoundsException.class, () -> access.mantle().layer(new MantleKey<>("test:owner", String.class)).get(5, -60, -3));
}
};
var edit = new RecordingEdit(new ArrayList<>());
PlacementPipeline.resolve(List.of(configured(modifier))).place(request(), edit, ignored -> TestContexts.placement(), ignored -> true);
assertThrows(IllegalStateException.class, () -> retained.get().get(-2, -60, -3));
assertThrows(IllegalStateException.class, () -> retainedLayer.get().get(-2, -60, -3));
}
@Test
void placementDependenciesStayInTheirOwnGraphAndRejectConflicts() {
var first = new PlacementModifier() { public String id() { return "test:first"; } };
var second = new PlacementModifier() {
public String id() { return "test:second"; }
public Dependencies depends() { return Dependencies.requires("test:first"); }
};
assertEquals(List.of(ResourceId.parse("test:first"), ResourceId.parse("test:second")),
PlacementPipeline.resolve(List.of(configured(second), configured(first))).ordered().stream().map(ConfiguredPlacementModifier::id).toList());
assertThrows(IllegalArgumentException.class, () -> PlacementPipeline.resolve(List.of(configured(second))));
assertThrows(IllegalArgumentException.class, () -> PlacementPipeline.resolve(List.of(configured(first), configured(first))));
}
@Test
void mappedWritesOutsideReachFailBeforeMutationAndEachHookKeepsItsOwnReach() {
var moved = new PlacementModifier() {
public String id() { return "test:moved"; }
public Optional<PlacedBlock> mapBlock(PlacementContext context, PlacedBlock block) {
return Optional.of(new PlacedBlock(block.position().add(new BlockPosition(8, 0, 0)), block.state(), block.blockEntity()));
}
};
var edit = new RecordingEdit(new ArrayList<>());
assertThrows(IndexOutOfBoundsException.class, () -> PlacementPipeline.resolve(List.of(configured(moved)))
.place(request(), edit, ignored -> TestContexts.placement(), ignored -> true));
assertEquals(0, edit.mutations);
var large = new PlacementModifier() {
public String id() { return "test:large"; }
public int writeRadius() { return 2; }
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) {
assertEquals(AIR, access.get(0, -60, -3));
assertEquals(new BlockBox(-5, -64, -5, 1, 320, 0), access.mantle().bounds());
assertNull(access.mantle().layer(new MantleKey<>("test:owner", String.class))
.get(0, -60, -3));
}
};
var small = new PlacementModifier() {
public String id() { return "test:small"; }
public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) {
assertThrows(IndexOutOfBoundsException.class, () -> access.get(0, -60, -3));
assertEquals(new BlockBox(-3, -64, -3, -1, 320, -2), access.mantle().bounds());
assertThrows(IndexOutOfBoundsException.class, () -> access.mantle()
.layer(new MantleKey<>("test:owner", String.class)).get(0, -60, -3));
}
};
assertTrue(PlacementPipeline.resolve(List.of(configured(small), configured(large)))
.place(request(), new RecordingEdit(new ArrayList<>()), ignored -> TestContexts.placement(), ignored -> true).isPresent());
}
/** In-memory transactional test adapter; production storage/persistence is deliberately absent. */
private static class RecordingEdit implements PlacementEdit {
final List<String> events;
final Map<BlockPosition, BlockState> pending = new HashMap<>();
final Map<BlockPosition, BlockState> published = new HashMap<>();
final List<PlacedMarker> pendingMarkers = new ArrayList<>();
final List<PlacedMarker> publishedMarkers = new ArrayList<>();
boolean closed;
boolean failCommit;
int mutations;
RecordingEdit(List<String> events) { this.events = events; }
private void checkOpen() { if (closed) throw new IllegalStateException("Closed edit"); }
public BlockBox bounds() { checkOpen(); return new BlockBox(-16, -64, -16, 16, 320, 16); }
public BlockState get(int x, int y, int z) { checkOpen(); return pending.getOrDefault(new BlockPosition(x, y, z), AIR); }
public void set(PlacedBlock block) { checkOpen(); mutations++; events.add("write"); pending.put(block.position(), block.state()); }
public void marker(PlacedMarker marker) { checkOpen(); mutations++; events.add("marker"); pendingMarkers.add(marker); }
public Mantle mantle() {
checkOpen();
return new Mantle() {
public BlockBox bounds() { return RecordingEdit.this.bounds(); }
public MantleEdit edit() { throw new UnsupportedOperationException(); }
public <T> MantleLayer<T> layer(MantleKey<T> key) {
return new MantleLayer<>() {
public T get(int x, int y, int z) { checkOpen(); return null; }
public void set(int x, int y, int z, T value) { throw new AssertionError("Unused mantle mutation"); }
public void remove(int x, int y, int z) { throw new AssertionError("Unused mantle mutation"); }
public void clear(BlockBox area) { throw new AssertionError("Unused mantle mutation"); }
public void visit(BlockBox area, MantleVisitor<T> visitor) { checkOpen(); }
};
}
};
}
public void commit() {
checkOpen();
if (failCommit) throw new IllegalStateException("Commit failed");
events.add("commit"); published.putAll(pending); publishedMarkers.addAll(pendingMarkers); closed = true;
}
public void close() {
if (!events.contains("close")) events.add("close");
closed = true; pending.clear(); pendingMarkers.clear();
}
}
}
@@ -0,0 +1,50 @@
package com.volmit.mantle;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class MantleValueTest {
@Test
void boundsUseWorldCoordinatesAndExclusiveMaximum() {
var box = new BlockBox(-16, -64, -16, 16, 320, 16);
assertTrue(box.contains(-16, -64, -16));
assertTrue(box.contains(15, 319, 15));
assertFalse(box.contains(16, 0, 0));
assertFalse(box.contains(0, 320, 0));
assertFalse(box.contains(0, 0, 16));
assertFalse(box.contains(0, -65, 0));
assertTrue(box.contains(box));
assertTrue(box.contains(new BlockBox(0, 0, 0, 1, 1, 1)));
assertFalse(box.contains(new BlockBox(-17, 0, 0, 1, 1, 1)));
assertThrows(NullPointerException.class, () -> box.contains(null));
}
@Test
void rejectsInversionButAllowsEmptyBounds() {
assertThrows(IllegalArgumentException.class, () -> new BlockBox(1, 0, 0, 0, 1, 1));
assertThrows(IllegalArgumentException.class, () -> new BlockBox(0, 1, 0, 1, 0, 1));
assertThrows(IllegalArgumentException.class, () -> new BlockBox(0, 0, 1, 1, 1, 0));
assertFalse(new BlockBox(0, 0, 0, 0, 0, 0).contains(0, 0, 0));
var extremes = new BlockBox(Integer.MIN_VALUE, -64, 0, Integer.MAX_VALUE, 320, 1);
assertTrue(extremes.contains(Integer.MIN_VALUE, 0, 0));
}
@Test
void keysSeparateSameTypedLayersAndHaveValueEquality() {
var owner = new MantleKey<>("example:object-owner", String.class);
assertEquals(owner, new MantleKey<>("example:object-owner", String.class));
assertNotEquals(owner, new MantleKey<>("example:quest/location", String.class));
assertNotEquals(owner, new MantleKey<>("example:object-owner", Integer.class));
}
@Test
void rejectsInvalidKeys() {
for (String id : new String[]{"", "owner", ":owner", "example:", "Example:owner", "a:b:c", "a: b"}) {
assertThrows(IllegalArgumentException.class, () -> new MantleKey<>(id, String.class));
}
assertThrows(NullPointerException.class, () -> new MantleKey<>(null, String.class));
assertThrows(NullPointerException.class, () -> new MantleKey<>("a:b", null));
assertThrows(IllegalArgumentException.class, () -> new MantleKey<>("a:b", int.class));
}
}
@@ -0,0 +1,45 @@
package com.volmit.support;
import com.volmit.config.FeatureSettings;
import com.volmit.generation.GenerationContext;
import com.volmit.mantle.Mantle;
import com.volmit.object.ObjectTransformer;
import com.volmit.placement.PlacementContext;
import com.volmit.resource.PackResources;
import com.volmit.world.TerrainSampler;
import com.volmit.world.BlockView;
import java.util.Random;
import java.util.random.RandomGenerator;
/** Tests needing no platform facilities fail loudly if code starts using one. */
public final class TestContexts {
private TestContexts() {}
public static GenerationContext generation() {
return new GenerationContext() {
private final RandomGenerator random = new Random(42);
public int originX() { return 0; }
public int originY() { return -64; }
public int originZ() { return 0; }
public long worldSeed() { return 42; }
public RandomGenerator random() { return random; }
public PackResources resources() { throw new AssertionError("Unused resources"); }
public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); }
public FeatureSettings settings() { throw new AssertionError("Unused settings"); }
public Mantle mantle() { throw new AssertionError("Unused mantle"); }
};
}
public static PlacementContext placement() {
return new PlacementContext() {
private final RandomGenerator random = new Random(42);
public long worldSeed() { return 42; }
public RandomGenerator random() { return random; }
public PackResources resources() { throw new AssertionError("Unused resources"); }
public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); }
public FeatureSettings settings() { throw new AssertionError("Unused settings"); }
public ObjectTransformer objects() { throw new AssertionError("Unused transforms"); }
public BlockView blocks() { throw new AssertionError("Unused blocks"); }
};
}
}