Batch 1 of the API review: one setup entry point, per-pipeline definitions

- IrisModule.setup(ModuleSetup) replaces install(StageGraph) and
  register(FeatureRegistry); ModuleSetups.run is the host entry point.
- The conditional definition variants are gone: a stage body reads the
  settings it is conditioned on through ctx.configured(Type.class).
- Placement, block, chunk and mantle stages each get their own
  definition interface; chunk definitions offer neither reach nor
  writesMantle. MantleStage is no longer generic.
- softAfter/softBefore take stage constants as well as StageRefs.
- A producer that rejected the attempt may return null.
- PlacementRunner, ChunkRunner and MantleRunner all take StageTimings.
- ConfiguredSettings groups entries by the type that declares @Feature.
- README, DESIGN and CONTRACTS updated, with the edge choice table.
This commit is contained in:
piexel committed 2026-10-23 13:00:07 +02:00
1 parent d3c0e4d6cc
commit 1677f4414b
75 files changed
+1201 -838

No files matched your search

+6 -3
View File
@@ -13,13 +13,14 @@ types that carry them and lists what the Iris adapter still owes.
| Namespace ownership | module-prefixed stage, feature and mantle ids, `ModuleInfo.ownsStage`/`ownsId`; no reserved namespaces | | Namespace ownership | module-prefixed stage, feature and mantle ids, `ModuleInfo.ownsStage`/`ownsId`; no reserved namespaces |
| Randomness independent of other modules | `StageContext.random()`, host `StageStreams`, invocation seed passed to the runners | | Randomness independent of other modules | `StageContext.random()`, host `StageStreams`, invocation seed passed to the runners |
| Random values identical on every JDK | `WorldRandom`, pinned by `WorldRandomTest` | | Random values identical on every JDK | `WorldRandom`, pinned by `WorldRandomTest` |
| Module-owned work and ordering | `Stage`, `StageRef`, stage definitions, `requires`/`softAfter`/`softBefore` | | Module entry point | `IrisModule.info()`, `IrisModule.setup(ModuleSetup)` (`stages()`, `registry()`, `log()`), host `ModuleSetups.run` |
| Activation by configuration | `when(settingsType)`, host `ConfiguredSettings` (entries per type; any column of a chunk) | | Module-owned work and ordering | `Stage`, `StageRef`, one stage definition type per pipeline, `requires`/`softAfter`/`softBefore` |
| Activation by configuration | `when(settingsType)`, `StageContext.configured(settingsType)`, host `ConfiguredSettings` (entries per declared `@Feature` type; any column of a chunk) |
| Stacked settings levels, read per column | `FeatureSettings.at(type, x, z)`, `FeatureSettings.Entry` (level, source, value) | | Stacked settings levels, read per column | `FeatureSettings.at(type, x, z)`, `FeatureSettings.Entry` (level, source, value) |
| Typed results between modules | stage outputs, `StageContext.output` | | Typed results between modules | stage outputs, `StageContext.output` |
| Per-block work with single-pass cost | `BlockStage`, fused block passes | | Per-block work with single-pass cost | `BlockStage`, fused block passes |
| Pack-load validation and diagnostics | host `StageGraphBuilder`, `ResolvedGraph`, `LoadedModules` | | Pack-load validation and diagnostics | host `StageGraphBuilder`, `ResolvedGraph`, `LoadedModules` |
| Reference execution | host `PlacementRunner`, `ChunkRunner`, `MantleRunner` | | Reference execution | host `PlacementRunner`, `ChunkRunner`, `MantleRunner`, each timed through host `StageTimings` |
| Work across chunks and mantle writes | `Stage.mantle`, `MantleStage`, `MantleStageContext`, `MantleGenerationContext`; chunk stages read the mantle only | | Work across chunks and mantle writes | `Stage.mantle`, `MantleStage`, `MantleStageContext`, `MantleGenerationContext`; chunk stages read the mantle only |
| Annotated settings | `IrisFeature`, `@Feature` (id, short JSON `key`, optional `root`), config annotations, `OptionsMetadata`, `LinkedBiomes` (`treeBiomes`, `usedBiomes`: pack biomes the settings bring into the layout) | | Annotated settings | `IrisFeature`, `@Feature` (id, short JSON `key`, optional `root`), config annotations, `OptionsMetadata`, `LinkedBiomes` (`treeBiomes`, `usedBiomes`: pack biomes the settings bring into the layout) |
| Area a stage writes | `reach(blocks)`, `reach(PackReach)`, `writesMantle(...)` on stage definitions, `PackSettings`, host `StageReach`, `ResolvedStage.reachBlocks`, `PipelineReach` | | Area a stage writes | `reach(blocks)`, `reach(PackReach)`, `writesMantle(...)` on stage definitions, `PackSettings`, host `StageReach`, `ResolvedStage.reachBlocks`, `PipelineReach` |
@@ -118,6 +119,8 @@ running Iris is the pack publisher's responsibility.
work inside the ported stages. work inside the ported stages.
- Derive one seed per placement (world seed and the placement's stable identity) and per chunk - Derive one seed per placement (world seed and the placement's stable identity) and per chunk
(world seed and chunk position) and pass it to `PlacementRunner.place` / `ChunkRunner.generate`. (world seed and chunk position) and pass it to `PlacementRunner.place` / `ChunkRunner.generate`.
- Pass every runner a `StageTimings` that records into the host's metrics (or `StageTimings.NONE`), so
placement, mantle and chunk stages are all timed by the host rather than by the modules.
- Prepare the area a placement may read or write, including neighbors: the placement pipeline's - Prepare the area a placement may read or write, including neighbors: the placement pipeline's
`reach()` around the placed object's bounds, each mantle layer by its own maximum. Never clip. `reach()` around the placed object's bounds, each mantle layer by its own maximum. Never clip.
- Work out each mantle stage's reach once per pack load (`ResolvedStage.reachBlocks(PackSettings)`), - Work out each mantle stage's reach once per pack load (`ResolvedStage.reachBlocks(PackSettings)`),
+49 -31
View File
@@ -15,8 +15,9 @@ phase or hook has special status in the API.
```mermaid ```mermaid
flowchart TD flowchart TD
Modules[Built-in and addon modules] --> Install[install: define stages] Modules[Built-in and addon modules] --> Setup[setup]
Modules --> Register[register: geometry, mantle layers, resource kinds, validators, hooks, services] Setup --> Install[stages: define stages]
Setup --> Register[registry: geometry, mantle layers, resource kinds, validators, hooks, services]
Install --> Resolve[Resolve per pipeline at pack load] Install --> Resolve[Resolve per pipeline at pack load]
Install --> Settings[when settings types] Install --> Settings[when settings types]
Settings --> Catalog[Frozen feature catalog] Settings --> Catalog[Frozen feature catalog]
@@ -243,13 +244,13 @@ expected is not a problem to show in studio.
A class the host hides fails, even though the pack might never run that code, because it exists: A class the host hides fails, even though the pack might never run that code, because it exists:
the module was written against Iris's copy, and the error says to ship the library or use the API the module was written against Iris's copy, and the error says to ship the library or use the API
instead of leaving the author with a `NoClassDefFoundError` during install or generation. instead of leaving the author with a `NoClassDefFoundError` during setup or generation.
There is no version gating. Packs ship their module jars and Iris never downloads any, so whether There is no version gating. Packs ship their module jars and Iris never downloads any, so whether
a jar works with the running Iris is the pack publisher's responsibility. The class check catches a jar works with the running Iris is the pack publisher's responsibility. The class check catches
API and exposed classes that no longer exist. It does not check methods and fields: a jar built API and exposed classes that no longer exist. It does not check methods and fields: a jar built
against an API whose methods have changed fails with a linkage error, which `LoadedModules.load` against an API whose methods have changed fails with a linkage error, which `LoadedModules.load`
reports with the module's jar when it happens during install, and which surfaces at generation reports with the module's jar when it happens during setup, and which surfaces at generation
time when it happens only in a stage body. time when it happens only in a stage body.
Closing `PackModules` closes the loader and then deletes the copies. Classes loaded before that Closing `PackModules` closes the loader and then deletes the copies. Classes loaded before that
@@ -301,20 +302,26 @@ resolve time.
| `PlacementStage<O>` | PLACEMENT | once per placement attempt | `PlacementStageContext` | | `PlacementStage<O>` | PLACEMENT | once per placement attempt | `PlacementStageContext` |
| `BlockStage<O>` | PLACEMENT | once per object block, in a block pass | `BlockStageContext` | | `BlockStage<O>` | PLACEMENT | once per object block, in a block pass | `BlockStageContext` |
| `ChunkStage<O>` | CHUNK | once per chunk invocation | `ChunkStageContext` | | `ChunkStage<O>` | CHUNK | once per chunk invocation | `ChunkStageContext` |
| `MantleStage<Void>` | MANTLE | once per chunk, before the chunks it reaches generate, each stage its own pass | `MantleStageContext` | | `MantleStage` | MANTLE | once per chunk, before the chunks it reaches generate, each stage its own pass | `MantleStageContext` |
`StageGraph.define` returns one definition type per stage type: `PlacementStageDefinition<O>`,
`BlockStageDefinition<O>`, `ChunkStageDefinition<O>` and `MantleStageDefinition`. Each offers only
what its pipeline allows, so these rules are compile errors instead of load failures: a chunk
stage has no `reach` or `writesMantle`, only a mantle stage has `reach(PackReach)`, and only a
block stage has `accumulate`.
Rules enforced by `StageGraphBuilder` and the resolver: Rules enforced by `StageGraphBuilder` and the resolver:
1. The stage id must start with the defining module's id and `/`. A second definition of an id 1. The stage id must start with the defining module's id and `/`. A second definition of an id
fails. Two modules with the same id fail. fails. Two modules with the same id fail.
2. `requires(stage...)` adds a REQUIRED edge. If the stage is not installed, loading fails with 2. `requires(stage...)` adds a REQUIRED edge. If the stage is not defined by any module, loading
both stage ids, the requiring module and the namespace the missing module should have. fails with both stage ids, the requiring module and the namespace the missing module should have.
3. `softAfter(ref...)` and `softBefore(ref...)` add SOFT edges only when the referenced id is 3. `softAfter(...)` and `softBefore(...)` take stage constants or `StageRef` ids and add SOFT edges
installed. Absent targets are kept for diagnostics. A module cannot force itself before only when the referenced id is defined. Absent targets are kept for diagnostics. A module cannot
another module's stage with a hard edge. force itself before another module's stage with a hard edge.
4. A stage with output must be defined with `produce` (or `accumulate` for block stages), and a 4. A stage with output must be defined with `produce` (or `accumulate` for block stages), and a
stage without output with `run`. Every defined stage needs exactly one body before its stage without output with `run`. Every defined stage needs exactly one body before its
module's `install` returns. module's `setup` returns.
5. A stage and everything it references must be in the same pipeline, soft references included. 5. A stage and everything it references must be in the same pipeline, soft references included.
6. Cycles fail and print the whole cycle: each stage with its module and the kind of each edge. 6. Cycles fail and print the whole cycle: each stage with its module and the kind of each edge.
@@ -327,7 +334,7 @@ all run, the lexically smallest id goes first, with one refinement for fusion:
- otherwise a ready invocation stage runs first; - otherwise a ready invocation stage runs first;
- otherwise a block stage opens a new pass. - otherwise a block stage opens a new pass.
The result depends only on ids and edges, never on install order. A tie-break on raw lexical id The result depends only on ids and edges, never on setup order. A tie-break on raw lexical id
alone would interleave unrelated invocation stages into block passes and split them. Note that alone would interleave unrelated invocation stages into block passes and split them. Note that
no topological order can put every unordered pair in lexical order once edges point against the no topological order can put every unordered pair in lexical order once edges point against the
alphabet, so "lexical" here always means "lexical among ready stages". alphabet, so "lexical" here always means "lexical among ready stages".
@@ -352,7 +359,8 @@ identity, which is a handful of entries, then reads the array. There is no hashi
Reading anything outside that list throws `IllegalStateException` and names the fix. A block Reading anything outside that list throws `IllegalStateException` and names the fix. A block
stage's accumulator is created once per placement and becomes readable when its pass ends; stage's accumulator is created once per placement and becomes readable when its pass ends;
reading it from inside the same pass throws. A null output from a stage that declares one fails reading it from inside the same pass throws. A null output from a stage that declares one fails
the invocation. the invocation, unless the stage rejected the placement attempt. These checks run when a stage
reads or produces, not at load: the graph knows which outputs a stage may read, not which it does.
### Activation ### Activation
@@ -368,8 +376,15 @@ The graph is resolved once per pack load. Activation is decided per invocation:
So an inactive requirement deactivates its dependents. That is not an error. Soft edges never So an inactive requirement deactivates its dependents. That is not an error. Soft edges never
affect activation. The cost per invocation is two small arrays and one pass over stages and affect activation. The cost per invocation is two small arrays and one pass over stages and
REQUIRED edges, plus, for chunks, one settings read per column and conditioned type. The entries are REQUIRED edges, plus, for chunks, one settings read per column and conditioned type. The body reads
passed to the body as its second argument, a never-empty `List<FeatureSettings.Entry<S>>`. the entries with `ctx.configured(type)`, a never-empty `List<FeatureSettings.Entry<S>>`. Only the
stage's own `when` type is readable that way; any other type, or a stage without a condition,
throws and names `when(...)` and `settings()` as the fixes. Bodies take only the context, so one
definition type per pipeline covers conditioned and unconditioned stages alike.
`ConfiguredSettings` groups a value under the class whose `@Feature` declares it: the value's class or
its nearest superclass that carries the annotation. So a subclass value is found by `when(Base.class)`,
and a placement that configures a base and a subclass value configures the type twice.
A chunk stage is active when any column of the chunk configures it, so a biome border inside a chunk A chunk stage is active when any column of the chunk configures it, so a biome border inside a chunk
never hides a feature on either side. The body then reads `ctx.settings().at(type, x, z)` per column, never hides a feature on either side. The body then reads `ctx.settings().at(type, x, z)` per column,
@@ -396,9 +411,11 @@ are ordered only by the tie-break, so they are where two modules can silently co
## Placement attempts ## Placement attempts
`PlacementRunner.place(request, edit, inputs, invocationSeed, settings)` owns the edit. It runs active stages in `PlacementRunner.place(request, edit, inputs, invocationSeed, settings, timings)` owns the edit. It runs active stages in
order, stops after the current stage or block once a stage calls `reject(reason)`, commits only order, stops after the current stage or block once a stage calls `reject(reason)`, commits only
when nothing rejected or threw, and closes the edit in every case. Stages receive a buffered when nothing rejected or threw, and closes the edit in every case. A producer that rejects may
return null, since no later stage reads its output; a null output without a rejection fails the
attempt. Stages receive a buffered
`PlacementAccess` view of the edit without commit or close, and it expires with the attempt. `PlacementAccess` view of the edit without commit or close, and it expires with the attempt.
## Random streams ## Random streams
@@ -488,7 +505,7 @@ the platform's Y at its boundary.
## Chunk invocations ## Chunk invocations
`ChunkRunner.generate(inputs, invocationSeed)` runs active chunk stages once each in resolved order. `ChunkRunner.generate(inputs, invocationSeed, timings)` runs active chunk stages once each in resolved order.
`GenerationContext.hunk(type)` returns the host-owned local volume of that value type, shared by `GenerationContext.hunk(type)` returns the host-owned local volume of that value type, shared by
all stages of the invocation. Hunk coordinates are local. Samples and mantle coordinates use all stages of the invocation. Hunk coordinates are local. Samples and mantle coordinates use
world X and Z, and Y as the height above the dimension's bottom. A chunk stage writes only its own chunk and reads the mantle: the runner hands it a view world X and Z, and Y as the height above the dimension's bottom. A chunk stage writes only its own chunk and reads the mantle: the runner hands it a view
@@ -504,8 +521,9 @@ structures): a chunk stage copies them into its chunk, as Iris's `iris:matter` d
need no registration, and stages only read them; placements keep writing blocks through `PlacementAccess.set`. need no registration, and stages only read them; placements keep writing blocks through `PlacementAccess.set`.
A mantle stage's `TerrainSampler` covers the same margin (at least 16 blocks, more when its reach is larger): a carver blends A mantle stage's `TerrainSampler` covers the same margin (at least 16 blocks, more when its reach is larger): a carver blends
the profiles of the columns around its chunk, so it reads their heights and biomes though it writes only the mantle. the profiles of the columns around its chunk, so it reads their heights and biomes though it writes only the mantle.
`ChunkRunner.generate(inputs, seed, timings)` reports how long each stage that ran took, so the host times modules All three runners take a `StageTimings` and report how long each stage that ran took, so the host times modules
instead of modules timing themselves. instead of modules timing themselves. A block stage is reported once per placement, its time summed over the blocks
of its pass; an inactive stage or one that throws is not reported.
The ground a chunk stage fills in needs more of the host than heights. `surfaceBiome(x, z)` answers the biome id of a column without working out the The ground a chunk stage fills in needs more of the host than heights. `surfaceBiome(x, z)` answers the biome id of a column without working out the
cave biome; `surfaceKind` says what that biome was generated as (land, sea or shore; a cave biome is always `CAVE`), `surfaceBlock` the block an image cave biome; `surfaceKind` says what that biome was generated as (land, sea or shore; a cave biome is always `CAVE`), `surfaceBlock` the block an image
@@ -521,7 +539,7 @@ marked need not show in the chunk (under a dimension above, the cave stage leave
Some work writes beyond its chunk: a carver whose tunnels cross chunk borders, a vein running on into Some work writes beyond its chunk: a carver whose tunnels cross chunk borders, a vein running on into
the next chunk. A chunk stage cannot do that, because the host may already have generated the the next chunk. A chunk stage cannot do that, because the host may already have generated the
neighbor. Such work is a mantle stage. `MantleRunner.generate(stage, inputs, invocationSeed)` runs one neighbor. Such work is a mantle stage. `MantleRunner.generate(stage, inputs, invocationSeed, timings)` runs one
mantle stage for one chunk, if it is active there, against the mantle around it mantle stage for one chunk, if it is active there, against the mantle around it
(`MantleGenerationContext`: origin, terrain, settings, mantle), without a block hunk. (`MantleGenerationContext`: origin, terrain, settings, mantle), without a block hunk.
@@ -530,7 +548,7 @@ order for every chunk within that stage's reach plus the reach of every later st
then the next stage the same way. A stage therefore sees, in the chunks around it, everything earlier then the next stage the same way. A stage therefore sees, in the chunks around it, everything earlier
stages wrote, and a chunk's mantle is complete when its chunk stages read it. In Iris each mantle stage stages wrote, and a chunk's mantle is complete when its chunk stages read it. In Iris each mantle stage
is one mantle component, a pass of its own, whose radius is the stage's reach. Because stages of one is one mantle component, a pass of its own, whose radius is the stage's reach. Because stages of one
chunk run in different invocations, mantle stages have no outputs: `Stage.mantle` declares `Void`, and chunk run in different invocations, mantle stages have no outputs: `MantleStage` is not generic, and
stages pass data on through mantle layers. `requires(...)` still orders mantle stages and still stages pass data on through mantle layers. `requires(...)` still orders mantle stages and still
deactivates a stage in a chunk where a stage it requires is inactive; the runner works that out from deactivates a stage in a chunk where a stage it requires is inactive; the runner works that out from
the settings of the stage and everything it requires, and collects only those. the settings of the stage and everything it requires, and collects only those.
@@ -552,20 +570,20 @@ graph.define(CARVE).reach(32).writesMantle(CaveModule.CAVES).run(CaveModule::car
- `reach(blocks)`: how far, in blocks along X and Z, the stage writes blocks or mantle values beyond - `reach(blocks)`: how far, in blocks along X and Z, the stage writes blocks or mantle values beyond
its footprint. The footprint is the chunk's 16 by 16 columns for a mantle stage and the X/Z bounds of its footprint. The footprint is the chunk's 16 by 16 columns for a mantle stage and the X/Z bounds of
the placed object for a placement or block stage. A chunk stage writes only its chunk; declaring a the placed object for a placement or block stage. A chunk stage writes only its chunk, so
reach above 0 on one fails the install, naming mantle stages as the place for the work. Whole `ChunkStageDefinition` has no `reach`. Whole
columns: height is not limited, because Iris prepares chunks and mantle as full columns. Leaving it out means 0. Declaring it twice or columns: height is not limited, because Iris prepares chunks and mantle as full columns. Leaving it out means 0. Declaring it twice or
negative fails while the module installs. negative fails during the module's setup.
- `reach(PackReach)`: for a mantle stage whose reach depends on the pack, such as the largest object - `reach(PackReach)`: for a mantle stage whose reach depends on the pack, such as the largest object
or the longest vein any level configures. The host works it out once per pack load from or the longest vein any level configures. The host works it out once per pack load from
`PackSettings`, every entry of a settings type the dimension and its reachable regions and biomes `PackSettings`, every entry of a settings type the dimension and its reachable regions and biomes
declare, and asks each stage with `ResolvedStage.reachBlocks(settings)`; a negative result fails declare, and asks each stage with `ResolvedStage.reachBlocks(settings)`; a negative result fails
there, naming the stage. Placement and chunk stages may not declare one: placement areas and chunks there, naming the stage. Only `MantleStageDefinition` offers it: placement areas and chunks
are sized without the pack's settings. It counts as declaring the reach, so it cannot be combined are sized without the pack's settings. It counts as declaring the reach, so it cannot be combined
with `reach(blocks)`. with `reach(blocks)`.
- `writesMantle(layers...)`: the mantle layers the stage writes. Every layer must be registered by - `writesMantle(layers...)`: the mantle layers the stage writes. Every layer must be registered by
some module with the same value type, or the pack load fails naming stage and layer. Chunk stages some module with the same value type, or the pack load fails naming stage and layer.
cannot declare any. `ChunkStageDefinition` has no `writesMantle`.
Each resolved stage carries its `StageReach`. `ResolvedGraph.reach()` collects a `PipelineReach`: Each resolved stage carries its `StageReach`. `ResolvedGraph.reach()` collects a `PipelineReach`:
the largest reach of the pipeline's stages, and per mantle layer the largest reach of the stages the largest reach of the pipeline's stages, and per mantle layer the largest reach of the stages
@@ -583,7 +601,7 @@ as its reach. Terrain samples are computed, not prepared, and need nothing.
## Settings, geometry and storage ## Settings, geometry and storage
Settings types implement `IrisFeature` and carry `@Feature` (namespaced id, display name, attachment targets). `when(type)` validates the annotation while the module installs. The id Settings types implement `IrisFeature` and carry `@Feature` (namespaced id, display name, attachment targets). `when(type)` validates the annotation during the module's setup. The id
must be owned by a module naming the type (see Namespaces), or the owner registers the type itself must be owned by a module naming the type (see Namespaces), or the owner registers the type itself
with `FeatureRegistry.registerSettings`. That is for settings no stage names, such as settings read with `FeatureRegistry.registerSettings`. That is for settings no stage names, such as settings read
only through `FeatureSettings.at(...)`; registering a type a stage also names changes nothing, and a only through `FeatureSettings.at(...)`; registering a type a stage also names changes nothing, and a
@@ -740,7 +758,7 @@ instance of each class with it and reads the fields of that instance as the defa
alternatives were worse: reading no defaults leaves studio without the values a pack gets when it alternatives were worse: reading no defaults leaves studio without the values a pack gets when it
leaves a field out, and parsing initializers from class files cannot see values a constructor sets. leaves a field out, and parsing initializers from class files cannot see values a constructor sets.
Running module code is not new at this point: the load has already run the module's constructor, Running module code is not new at this point: the load has already run the module's constructor,
`info()`, `install` and `register`. The host creates settings this way anyway before decoding JSON `info()` and `setup`. The host creates settings this way anyway before decoding JSON
into them, so a constructor that would fail here would fail on every decode: the load fails with the into them, so a constructor that would fail here would fail on every decode: the load fails with the
constructor's exception, and a class without the constructor fails too, rather than describing constructor's exception, and a class without the constructor fails too, rather than describing
settings the host cannot create. settings the host cannot create.
@@ -1013,7 +1031,7 @@ gives each module a `ModuleLog` instead.
supplies the `System.Logger`. `warnOnce` keys are kept per log, so they belong to the module, and past a few hundred new supplies the `System.Logger`. `warnOnce` keys are kept per log, so they belong to the module, and past a few hundred new
keys it only debugs, which keeps a key space nobody bounded from growing. keys it only debugs, which keeps a key space nobody bounded from growing.
- **Where a module reaches it.** `InvocationContext.log()` for stage bodies and generators, `PackWorld.log()` for services - **Where a module reaches it.** `InvocationContext.log()` for stage bodies and generators, `PackWorld.log()` for services
and lifecycle hooks, `FeatureRegistry.log()` during `register`. The world and the context agree: the runners hand a stage a and lifecycle hooks, `ModuleSetup.log()` during `setup`. The world and the context agree: the runners hand a stage a
view of the world whose log is its module's (`PackWorld.withLog`, a host method; the view shares the state store), and view of the world whose log is its module's (`PackWorld.withLog`, a host method; the view shares the state store), and
`LifecycleRunner` and `ServiceRegistration.scope` do the same for hooks and providers. A host that calls a provider itself `LifecycleRunner` and `ServiceRegistration.scope` do the same for hooks and providers. A host that calls a provider itself
must scope the world, or the provider's lines carry the host's label. must scope the world, or the provider's lines carry the host's label.
+63 -36
View File
@@ -11,7 +11,7 @@ into this project; the test sources contain example ports only.
## Modules own their stages ## Modules own their stages
There are no host-defined hooks or phases. A module declares stages as constants and defines There are no host-defined hooks or phases. A module declares stages as constants and defines
them in `install`. Other modules order themselves against those constants. them in `setup`. Other modules order themselves against those constants.
```java ```java
public final class MossModule implements IrisModule { public final class MossModule implements IrisModule {
@@ -19,16 +19,20 @@ public final class MossModule implements IrisModule {
public ModuleInfo info() { return ModuleInfo.of("example:moss", "Moss", "1.0.0"); } public ModuleInfo info() { return ModuleInfo.of("example:moss", "Moss", "1.0.0"); }
public void install(StageGraph graph) { public void setup(ModuleSetup setup) {
graph.define(SPREAD) setup.stages().define(SPREAD)
.when(MossSettings.class) // only where a pack configures moss .when(MossSettings.class) // only where a pack configures moss
.requires(AnchorModule.HEIGHT, BlocksModule.COMPLETE) .requires(AnchorModule.HEIGHT, BlocksModule.COMPLETE)
.softAfter(StageRef.of("iris:snow/finish")) // ordering only, if snow is installed .softAfter(StageRef.of("iris:snow/finish")) // ordering only, if snow is set up
.run((ctx, moss) -> spread(ctx.output(AnchorModule.HEIGHT), moss.getFirst().value())); .run(ctx -> spread(ctx.output(AnchorModule.HEIGHT), ctx.configured(MossSettings.class).getFirst().value()));
} }
} }
``` ```
`IrisModule` has two methods: `info()` and `setup(ModuleSetup)`. `setup` runs once while the pack
loads. `setup.stages()` defines stages, `setup.registry()` takes every other contribution and
`setup.log()` is the module's log.
- `Stage.placement`, `Stage.placementBlock`, `Stage.chunk` and `Stage.mantle` create stages for the - `Stage.placement`, `Stage.placementBlock`, `Stage.chunk` and `Stage.mantle` create stages for the
placement pipeline (once per attempt), the placement pipeline (once per object block), the chunk placement pipeline (once per attempt), the placement pipeline (once per object block), the chunk
pipeline (once per chunk, writing only that chunk) and the mantle pipeline (once per chunk, before pipeline (once per chunk, writing only that chunk) and the mantle pipeline (once per chunk, before
@@ -39,18 +43,33 @@ public final class MossModule implements IrisModule {
Defining an id twice fails. Defining an id twice fails.
- `requires(...)` takes another module's stage constant. It orders, makes the output readable - `requires(...)` takes another module's stage constant. It orders, makes the output readable
and deactivates this stage wherever the requirement is inactive. and deactivates this stage wherever the requirement is inactive.
- `softAfter` and `softBefore` take ids and only order. There is no hard "before". - `softAfter` and `softBefore` only order. They take a stage constant, or a `StageRef` id when the
other module may be absent and you cannot compile against it. There is no hard "before".
- `run(...)` ends a stage without output, `produce(...)` a stage with output and - `run(...)` ends a stage without output, `produce(...)` a stage with output and
`accumulate(initial, collector)` a block stage whose accumulator becomes its output. `accumulate(initial, collector)` a block stage whose accumulator becomes its output. A producer that
- `when(settingsType)` runs the stage only where those settings are configured, and the body gets every rejects the placement attempt may return null; any other null output fails the attempt.
configured entry (see Settings levels below). - `when(settingsType)` runs the stage only where those settings are configured.
`ctx.configured(settingsType)` gives the body every configured entry that activated it (see Settings
levels below); asking for any other type throws.
- `ctx.output(stage)` works only for stages the current stage transitively requires. - `ctx.output(stage)` works only for stages the current stage transitively requires.
- `define` returns a definition for the stage's pipeline, so it offers only what that pipeline allows:
`reach` and `writesMantle` exist on placement and mantle definitions, never on chunk ones.
Which edge to use:
| You need | Use |
| --- | --- |
| Another stage's output, or to run only where it runs | `requires(stage)` |
| To run after a stage that may be absent or inactive, without reading it | `softAfter(stage)` |
| Another module's stage to run after yours, without it naming you | `softBefore(stage)` |
| To order against a module you do not compile against | `softAfter(StageRef.of("id"))` / `softBefore(StageRef.of("id"))` |
| To run only where settings are configured | `when(Settings.class)` |
- `ctx.random()` is the stage's own random stream, derived from the invocation seed and the stage - `ctx.random()` is the stage's own random stream, derived from the invocation seed and the stage
id. Installing or removing other modules, or how much they draw, never changes what a stage id. Installing or removing other modules, or how much they draw, never changes what a stage
draws. A block stage has one stream per placement, drawn across the blocks of its pass. draws. A block stage has one stream per placement, drawn across the blocks of its pass.
The stream is a `WorldRandom` (see Random streams below). The stream is a `WorldRandom` (see Random streams below).
`IrisModule.register(FeatureRegistry)` stays for non-stage contributions: geometry generators, `setup.registry()` takes the non-stage contributions: geometry generators,
mantle layers, settings no stage names (see Settings for studio), pack resource kinds, validators, mantle layers, settings no stage names (see Settings for studio), pack resource kinds, validators,
lifecycle hooks and services (see below). Their feature ids, mantle keys and kind ids are the module id or start with it and `/`, lifecycle hooks and services (see below). Their feature ids, mantle keys and kind ids are the module id or start with it and `/`,
like stage ids: `iris:snow` or `iris:snow/depth` for module `iris:snow`. A settings type named in `when(...)` needs a feature id that at least one like stage ids: `iris:snow` or `iris:snow/depth` for module `iris:snow`. A settings type named in `when(...)` needs a feature id that at least one
@@ -74,11 +93,12 @@ for (var entry : ctx.settings().at(DepositSettings.class, worldX, worldZ)) { /
Settings are read per column, at the column's surface biome. A chunk or mantle stage conditioned with Settings are read per column, at the column's surface biome. A chunk or mantle stage conditioned with
`when(...)` runs when any column of the chunk has an entry, so a biome border inside a chunk never `when(...)` runs when any column of the chunk has an entry, so a biome border inside a chunk never
hides a feature, and its body receives every distinct entry of the chunk. It then reads hides a feature, and `ctx.configured(type)` gives every distinct entry of the chunk. It then reads
`ctx.settings().at(...)` per column, or at the chunk's centre column (local 7, 7) for something that `ctx.settings().at(...)` per column, or at the chunk's centre column (local 7, 7) for something that
happens once per chunk. Something that spans several columns, such as a placed object, uses the column happens once per chunk. Something that spans several columns, such as a placed object, uses the column
it treats as its origin. In a placement the body receives the placement's own entry; a placement it treats as its origin. In a placement `ctx.configured(type)` gives the placement's own entry; a
declares each settings type once. placement declares each settings type once. An entry is found under the class whose `@Feature` declares
it, so a value of a subclass counts as its annotated superclass.
A feature whose settings class has exactly one option may be written as that option's value, such as A feature whose settings class has exactly one option may be written as that option's value, such as
`"snow": 0.5` for `"snow": {"amount": 0.5}` or a bare list for a class holding one list. `"snow": 0.5` for `"snow": {"amount": 0.5}` or a bare list for a class holding one list.
@@ -115,7 +135,7 @@ chunks around it, and the chunk's mantle is complete when its chunk stages read
no outputs: they pass data on through mantle layers. The two pipelines meet only in the mantle. no outputs: they pass data on through mantle layers. The two pipelines meet only in the mantle.
```java ```java
public static final MantleStage<Void> CARVE = Stage.mantle("example:caves/carve"); public static final MantleStage CARVE = Stage.mantle("example:caves/carve");
public static final ChunkStage<Void> APPLY = Stage.chunk("example:caves/apply"); public static final ChunkStage<Void> APPLY = Stage.chunk("example:caves/apply");
graph.define(CARVE).when(CaveSettings.class).reach(32).writesMantle(CAVES).run(CaveModule::carve); graph.define(CARVE).when(CaveSettings.class).reach(32).writesMantle(CAVES).run(CaveModule::carve);
@@ -145,7 +165,7 @@ graph.define(INSERT).run(ctx -> {
`reach(blocks)` is the distance in blocks along X and Z beyond the stage's footprint: the chunk for a `reach(blocks)` is the distance in blocks along X and Z beyond the stage's footprint: the chunk for a
mantle stage, the X/Z bounds of the placed object for a placement stage, whole columns in both cases. mantle stage, the X/Z bounds of the placed object for a placement stage, whole columns in both cases.
It defaults to 0. `writesMantle(...)` names the mantle layers the stage writes; each must be It defaults to 0. `writesMantle(...)` names the mantle layers the stage writes; each must be
registered by some module. A chunk stage that declares either fails the install, and its mantle is registered by some module. A chunk stage's definition has neither method, and its mantle is
read-only. `pack.placement().reach()` gives the host the largest reach of a pipeline and the largest read-only. `pack.placement().reach()` gives the host the largest reach of a pipeline and the largest
per mantle layer. per mantle layer.
@@ -153,7 +173,7 @@ When how far a mantle stage writes depends on the pack, such as the longest vein
any level configures, it declares a `PackReach` instead of a number. The host works it out from the any level configures, it declares a `PackReach` instead of a number. The host works it out from the
pack's settings (`PackSettings.declared(type)`: every entry of the dimension and of the regions and pack's settings (`PackSettings.declared(type)`: every entry of the dimension and of the regions and
biomes it can reach) when the pack loads, and asks each mantle stage with biomes it can reach) when the pack loads, and asks each mantle stage with
`ResolvedStage.reachBlocks(settings)`. Only mantle stages may declare one. `ResolvedStage.reachBlocks(settings)`. Only mantle definitions offer it.
```java ```java
graph.define(PLAN).when(VeinSettings.class).reach(VeinModule::reach).writesMantle(ORE).run(VeinModule::plan); graph.define(PLAN).when(VeinSettings.class).reach(VeinModule::reach).writesMantle(ORE).run(VeinModule::plan);
@@ -176,8 +196,8 @@ of the pack, each read into a new instance of a class of the module.
```java ```java
public static final ResourceKind<Keep> KEEPS = ResourceKind.of("example:castle/keep", "keeps", Keep.class); public static final ResourceKind<Keep> KEEPS = ResourceKind.of("example:castle/keep", "keeps", Keep.class);
public void register(FeatureRegistry registry) { public void setup(ModuleSetup setup) {
registry.registerResourceKind(KEEPS); // reads <pack>/keeps/**/*.json setup.registry().registerResourceKind(KEEPS); // reads <pack>/keeps/**/*.json
} }
// anywhere the pack's resources are at hand, such as a stage or a validator // anywhere the pack's resources are at hand, such as a stage or a validator
@@ -256,8 +276,8 @@ hook does nothing by default, and a module class may implement it and register i
```java ```java
public final class RuinsModule implements IrisModule, ModuleLifecycle { public final class RuinsModule implements IrisModule, ModuleLifecycle {
public void register(FeatureRegistry registry) { public void setup(ModuleSetup setup) {
registry.registerLifecycle(this); setup.registry().registerLifecycle(this);
} }
public void worldStarted(PackWorld world) { public void worldStarted(PackWorld world) {
@@ -301,8 +321,8 @@ private static void decorate(ChunkStageContext context) {
- A message is plain text, never a format string. - A message is plain text, never a format string.
- `context.log()` (stage bodies, object generators), `fit.log()` (vanilla structure fits), `world.log()` (services and - `context.log()` (stage bodies, object generators), `fit.log()` (vanilla structure fits), `world.log()` (services and
lifecycle hooks, which get a world as their argument) and `registry.log()` (while `register` runs) are the same module's log. Keep the registry's log in a lifecycle hooks, which get a world as their argument) and `setup.log()` are the same module's log. Keep the setup's log in a
field when `packLoaded`, which has no world, needs to log. `registry.log()` outside `register` throws. field when `packLoaded`, which has no world, needs to log.
- Do not use `System.out`, `System.getLogger` or a logging library of your own: the host cannot label or report them. - Do not use `System.out`, `System.getLogger` or a logging library of your own: the host cannot label or report them.
## Services ## Services
@@ -312,8 +332,8 @@ services: small interfaces marked `@Service` in `com.volmit.service`. A module r
them up in the pack's catalog instead of knowing the feature. them up in the pack's catalog instead of knowing the feature.
```java ```java
public void register(FeatureRegistry registry) { public void setup(ModuleSetup setup) {
registry.registerService(ObjectsAt.class, new RuinsObjects()); setup.registry().registerService(ObjectsAt.class, new RuinsObjects());
} }
final class RuinsObjects implements ObjectsAt { final class RuinsObjects implements ObjectsAt {
@@ -496,7 +516,7 @@ public final class FloraSettings implements IrisFeature {
use them. use them.
- Settings named in `when(...)` and object generator settings are described automatically. Settings - Settings named in `when(...)` and object generator settings are described automatically. Settings
that no stage names, such as ones read only through `FeatureSettings.at(...)`, are registered with that no stage names, such as ones read only through `FeatureSettings.at(...)`, are registered with
`registry.registerSettings(WindSettings.class)` in `register`. Their feature id follows the module `setup.registry().registerSettings(WindSettings.class)` in `setup`. Their feature id follows the module
id like any other, and once registered, other modules may name them in `when(...)`. id like any other, and once registered, other modules may name them in `when(...)`.
- A class of a built-in module that Iris's own classes hold, such as the clamp field of an object placement, is - A class of a built-in module that Iris's own classes hold, such as the clamp field of an object placement, is
registered with `registry.registerHeldType(Clamp.class)`, so studio describes it from the class (as an registered with `registry.registerHeldType(Clamp.class)`, so studio describes it from the class (as an
@@ -577,8 +597,8 @@ A module decides over the platform's own structures, the ones Minecraft, data pa
generates it (`BLOCK`). generates it (`BLOCK`).
```java ```java
public void register(FeatureRegistry registry) { public void setup(ModuleSetup setup) {
registry.registerService(VanillaStructures.class, new VanillaStructures() { setup.registry().registerService(VanillaStructures.class, new VanillaStructures() {
@Override @Override
public VanillaStructureRule rule(ResourceId structure, VanillaStructureContext world) { public VanillaStructureRule rule(ResourceId structure, VanillaStructureContext world) {
return world.settings().declared(CastleSettings.class).stream() return world.settings().declared(CastleSettings.class).stream()
@@ -656,23 +676,29 @@ var host = ModuleHost.of(builtInModules)
try (var pack = LoadedPack.load(packRoot, host)) { try (var pack = LoadedPack.load(packRoot, host)) {
System.out.println(pack.placement().describe()); System.out.println(pack.placement().describe());
StageTimings timings = (stage, nanos) -> metrics.time(stage, nanos); // or StageTimings.NONE
var placer = new PlacementRunner(pack.placement()); var placer = new PlacementRunner(pack.placement());
PlacementOutcome outcome = placer.place(request, edit, inputs, placementSeed, PlacementOutcome outcome = placer.place(request, edit, inputs, placementSeed,
ConfiguredSettings.placement(objectId, stilt, snow)); ConfiguredSettings.placement(objectId, stilt, snow), timings);
var mantle = new MantleRunner(pack.mantle()); var mantle = new MantleRunner(pack.mantle());
for (var stage : pack.mantle().stages()) { // each stage its own pass, first for (var stage : pack.mantle().stages()) { // each stage its own pass, first
mantle.generate(stage.stage(), mantleContext, chunkSeed); // for each chunk it reaches mantle.generate(stage.stage(), mantleContext, chunkSeed, timings); // for each chunk it reaches
} }
new ChunkRunner(pack.chunk()).generate(generationContext, chunkSeed, (stage, nanos) -> metrics.time(stage, nanos)); new ChunkRunner(pack.chunk()).generate(generationContext, chunkSeed, timings);
} // stop using the runners before the pack closes } // stop using the runners before the pack closes
``` ```
All three runners report how long each stage that ran took to their `StageTimings`. A block stage is
reported once per placement, with its time summed over the blocks of its pass. Stages that are
inactive or throw are not reported.
`ModuleHost` holds what the host passes to every pack load: built-in modules (their `info()` is read `ModuleHost` holds what the host passes to every pack load: built-in modules (their `info()` is read
once, here), the host packages pack modules may use, the JSON fields it uses itself per target, the once, here), the host packages pack modules may use, the JSON fields it uses itself per target, the
packages of the classes it describes itself and the pack folders it reads itself. Each method adds to what earlier calls configured. Package names, packages of the classes it describes itself and the pack folders it reads itself. Each method adds to what earlier calls configured. Package names,
reserved fields and reserved folders are checked when it is built. `LoadedPack.load` reserved fields and reserved folders are checked when it is built. `LoadedPack.load`
loads the pack's jars, installs them after the built-ins, catalogs settings and registrations, loads the pack's jars, sets them up after the built-ins, catalogs settings and registrations,
describes them for studio and resolves the three pipelines. It returns a complete pack or throws with nothing left open. `close()` describes them for studio and resolves the three pipelines. It returns a complete pack or throws with nothing left open. `close()`
releases the pack's class loader and its jar copies. `PackModules` and `LoadedModules`, which it releases the pack's class loader and its jar copies. `PackModules` and `LoadedModules`, which it
uses, stay available for tests and special cases. uses, stay available for tests and special cases.
@@ -742,14 +768,14 @@ Pack overworld uses 2 modules:
A pack without jars logs `Pack overworld uses no modules: no jars in its modules directory`. A pack without jars logs `Pack overworld uses no modules: no jars in its modules directory`.
`LoadedModules.load` installs every module, catalogs the settings types named in `when(...)` `LoadedModules.load` sets up every module, catalogs the settings types named in `when(...)`
together with explicitly registered settings, geometry and mantle registrations, resource kinds and together with explicitly registered settings, geometry and mantle registrations, resource kinds and
validators and service providers (`catalog().resourceKinds()`, `catalog().validators()`, validators and service providers (`catalog().resourceKinds()`, `catalog().validators()`,
`catalog().registrations(service)`), describes them and resolves the pipelines. Graph errors `catalog().registrations(service)`), describes them and resolves the pipelines. Graph errors
(missing requirement, cycle, a stage outside its module's id, duplicate, cross-pipeline edge) fail (missing requirement, cycle, a stage outside its module's id, duplicate, cross-pipeline edge) fail
here, at pack load, and so do duplicate module ids and feature ids or mantle keys outside the here, at pack load, and so do duplicate module ids and feature ids or mantle keys outside the
module's id, and a settings key two features take at one target or that is a reserved host field. Errors about one module name its jar or "host classpath", and so does a module module's id, and a settings key two features take at one target or that is a reserved host field. Errors about one module name its jar or "host classpath", and so does a module
that fails to link a class while installing, such as a jar built against an API whose methods have that fails to link a class during setup, such as a jar built against an API whose methods have
since changed: since changed:
``` ```
@@ -843,7 +869,8 @@ world's state store (`PackWorld.state`).
``` ```
The tests cover graph resolution and every error path, fusion, activation cascade, outputs, The tests cover graph resolution and every error path, fusion, activation cascade, outputs,
rejection and rollback, install-order determinism, id ownership of stages, settings, objects and rejection and rollback, setup-order determinism, `configured` reads, stage timings of all three
runners, id ownership of stages, settings, objects and
mantle keys, reach per stage, pipeline and mantle layer, reach worked out when the pack loads (mantle mantle keys, reach per stage, pipeline and mantle layer, reach worked out when the pack loads (mantle
stages only, never negative), one mantle stage per runner call with activation that follows its stages only, never negative), one mantle stage per runner call with activation that follows its
requirements, chunk stages that declare reach or mantle writes (`StageGraphTest`, `ModuleRegistryTest`), settings entries per type in level order requirements, chunk stages that declare reach or mantle writes (`StageGraphTest`, `ModuleRegistryTest`), settings entries per type in level order
@@ -884,7 +911,7 @@ outside the platform loader, non-exported JDK packages (`sun.misc.Unsafe` and `j
load), several kinds of unusable class in one error, classes missing from an load), several kinds of unusable class in one error, classes missing from an
exposed package, optional dependencies that only warn, declared optional packages (fully and partly exposed package, optional dependencies that only warn, declared optional packages (fully and partly
excused, per jar, never excusing an error, invalid names), references that must still load excused, per jar, never excusing an error, invalid names), references that must still load
(arrays, the JDK, other pack jars, missing annotation types), linkage errors during install, and a (arrays, the JDK, other pack jars, missing annotation types), linkage errors during setup, and a
pack jar that requires a stage of a built-in module in `example.builtin`, outside `com.volmit`, pack jar that requires a stage of a built-in module in `example.builtin`, outside `com.volmit`,
which loads only when the host exposes that package. `ExposedHostClassLoaderTest` checks what the which loads only when the host exposes that package. `ExposedHostClassLoaderTest` checks what the
pack loader's parent shows, `ExposedPackagesTest` which package names it accepts and how they pack loader's parent shows, `ExposedPackagesTest` which package names it accepts and how they
@@ -15,11 +15,6 @@ import com.volmit.validation.Validator;
* registers are its module id or start with it and {@code /}, such as {@code iris:snow} or {@code iris:snow/depth}. * registers are its module id or start with it and {@code /}, such as {@code iris:snow} or {@code iris:snow/depth}.
*/ */
public interface FeatureRegistry { public interface FeatureRegistry {
/** The registering module's own log. A module that wants to log from its hooks keeps the one it gets here; a call
* outside {@link IrisModule#register} throws IllegalStateException.
*/
ModuleLog log();
/** Registers a layer before pack loading. Null arguments throw NullPointerException; /** Registers a layer before pack loading. Null arguments throw NullPointerException;
* duplicate IDs and negative codec versions throw IllegalArgumentException. * duplicate IDs and negative codec versions throw IllegalArgumentException.
* Only the owner registers a shared layer; consumers refer to its key. The host must * Only the owner registers a shared layer; consumers refer to its key. The host must
+5 -10
View File
@@ -1,7 +1,5 @@
package com.volmit; package com.volmit;
import com.volmit.stage.StageGraph;
/** A unit of world-generation behavior. The core engine is an ordinary module too. /** A unit of world-generation behavior. The core engine is an ordinary module too.
* *
* <p>In a pack's module jar this class is the entry point. The jar names it in * <p>In a pack's module jar this class is the entry point. The jar names it in
@@ -11,13 +9,10 @@ import com.volmit.stage.StageGraph;
public interface IrisModule { public interface IrisModule {
ModuleInfo info(); ModuleInfo info();
/** Defines this module's stages, before settings are decoded or generation starts. /** Defines this module's stages and registers its other contributions (geometry generators, mantle layers,
* Called once per pack load; stage bodies must not capture per-invocation state. * settings no stage names, pack resource kinds, validators, lifecycle hooks and services), before settings are
* decoded or generation starts. Called once per pack load, in any order relative to other modules; stage bodies
* must not capture per-invocation state.
*/ */
void install(StageGraph graph); void setup(ModuleSetup setup);
/** Registers non-stage contributions: geometry generators, mantle layers, settings no stage names, pack
* resource kinds, validators, lifecycle hooks and services.
*/
default void register(FeatureRegistry registry) {}
} }
+1 -1
View File
@@ -4,7 +4,7 @@ package com.volmit;
* to its own log, so a module never needs a logging library of its own and its lines are easy to find. Each module has * to its own log, so a module never needs a logging library of its own and its lines are easy to find. Each module has
* its own: reach it as {@code context.log()} in stage bodies and generators * its own: reach it as {@code context.log()} in stage bodies and generators
* ({@link com.volmit.generation.InvocationContext#log}), as {@link com.volmit.world.PackWorld#log} in services and * ({@link com.volmit.generation.InvocationContext#log}), as {@link com.volmit.world.PackWorld#log} in services and
* lifecycle hooks, and as {@link FeatureRegistry#log} while the module registers. * lifecycle hooks, and as {@link ModuleSetup#log} during the module's setup.
* *
* <p>Safe to use from any thread. A message is plain text, not a format string. * <p>Safe to use from any thread. A message is plain text, not a format string.
*/ */
+16
View File
@@ -0,0 +1,16 @@
package com.volmit;
import com.volmit.stage.StageGraph;
/** What a module gets in {@link IrisModule#setup}: the stage graph it defines its stages in, the registry for
* everything else, and its own log. Stages and registrations are accepted only while {@code setup} runs; the log
* may be kept and used later, such as from lifecycle hooks.
*/
public interface ModuleSetup {
StageGraph stages();
FeatureRegistry registry();
/** This module's log, the same one its stages and lifecycle hooks see through their world. */
ModuleLog log();
}
@@ -5,18 +5,14 @@ import com.volmit.mantle.MantleKey;
import com.volmit.stage.BlockCollector; import com.volmit.stage.BlockCollector;
import com.volmit.stage.BlockStageContext; import com.volmit.stage.BlockStageContext;
import com.volmit.stage.BlockStageDefinition; import com.volmit.stage.BlockStageDefinition;
import com.volmit.stage.ConditionalBlockStageDefinition;
import com.volmit.stage.SettingsAction;
import com.volmit.stage.SettingsBlockCollector;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.stage.StageAction; import com.volmit.stage.StageAction;
import com.volmit.stage.StageRef; import com.volmit.stage.StageRef;
import java.util.Objects; import java.util.Objects;
import java.util.function.Supplier; import java.util.function.Supplier;
/** Builder behind both block stage definition views; S is unused until when(...). */ /** Builder behind {@link BlockStageDefinition}. */
final class BlockStageDraft<S extends IrisFeature, O> final class BlockStageDraft<O> implements BlockStageDefinition<O> {
implements BlockStageDefinition<O>, ConditionalBlockStageDefinition<S, O> {
private final StageDeclaration declaration; private final StageDeclaration declaration;
BlockStageDraft(StageDeclaration declaration) { BlockStageDraft(StageDeclaration declaration) {
@@ -24,66 +20,64 @@ final class BlockStageDraft<S extends IrisFeature, O>
} }
@Override @Override
public BlockStageDraft<S, O> requires(Stage<?>... stages) { public BlockStageDraft<O> requires(Stage<?>... stages) {
declaration.require(stages); declaration.require(stages);
return this; return this;
} }
@Override @Override
public BlockStageDraft<S, O> softAfter(StageRef... stages) { public BlockStageDraft<O> softAfter(Stage<?>... stages) {
declaration.softAfter(stages); declaration.softAfter(stages);
return this; return this;
} }
@Override @Override
public BlockStageDraft<S, O> softBefore(StageRef... stages) { public BlockStageDraft<O> softAfter(StageRef... stages) {
declaration.softAfter(stages);
return this;
}
@Override
public BlockStageDraft<O> softBefore(Stage<?>... stages) {
declaration.softBefore(stages); declaration.softBefore(stages);
return this; return this;
} }
@Override @Override
public BlockStageDraft<S, O> reach(int blocks) { public BlockStageDraft<O> softBefore(StageRef... stages) {
declaration.softBefore(stages);
return this;
}
@Override
public BlockStageDraft<O> reach(int blocks) {
declaration.reach(blocks); declaration.reach(blocks);
return this; return this;
} }
@Override @Override
public BlockStageDraft<S, O> writesMantle(MantleKey<?>... layers) { public BlockStageDraft<O> writesMantle(MantleKey<?>... layers) {
declaration.writesMantle(layers); declaration.writesMantle(layers);
return this; return this;
} }
@Override @Override
@SuppressWarnings("unchecked") // S is a phantom parameter until the condition is recorded here. public BlockStageDraft<O> when(Class<? extends IrisFeature> settingsType) {
public <N extends IrisFeature> BlockStageDraft<N, O> when(Class<N> settingsType) {
declaration.condition(settingsType); declaration.condition(settingsType);
return (BlockStageDraft<N, O>) (BlockStageDraft<?, ?>) this; return this;
} }
@Override @Override
public void run(StageAction<BlockStageContext> action) { public void run(StageAction<BlockStageContext> action) {
Objects.requireNonNull(action, "action"); Objects.requireNonNull(action, "action");
complete(null, (context, settings, accumulator) -> action.run(context)); complete(null, (context, accumulator) -> action.run(context));
} }
@Override @Override
public void accumulate(Supplier<O> initial, BlockCollector<O> collector) { public void accumulate(Supplier<O> initial, BlockCollector<O> collector) {
Objects.requireNonNull(collector, "collector"); Objects.requireNonNull(collector, "collector");
complete(Objects.requireNonNull(initial, "initial"), complete(Objects.requireNonNull(initial, "initial"),
(context, settings, accumulator) -> collector.collect(context, cast(accumulator))); (context, accumulator) -> collector.collect(context, cast(accumulator)));
}
@Override
public void run(SettingsAction<BlockStageContext, S> action) {
Objects.requireNonNull(action, "action");
complete(null, (context, settings, accumulator) -> action.run(context, cast(settings)));
}
@Override
public void accumulate(Supplier<O> initial, SettingsBlockCollector<S, O> collector) {
Objects.requireNonNull(collector, "collector");
complete(Objects.requireNonNull(initial, "initial"),
(context, settings, accumulator) -> collector.collect(context, cast(settings), cast(accumulator)));
} }
private void complete(Supplier<?> initial, StageBody.BlockWork work) { private void complete(Supplier<?> initial, StageBody.BlockWork work) {
@@ -91,7 +85,7 @@ final class BlockStageDraft<S extends IrisFeature, O>
declaration.complete(new StageBody.Block(initial, work), accumulates, accumulates ? "run" : "accumulate"); declaration.complete(new StageBody.Block(initial, work), accumulates, accumulates ? "run" : "accumulate");
} }
@SuppressWarnings("unchecked") // The executor passes the settings and accumulator this stage was declared with. @SuppressWarnings("unchecked") // The executor passes the accumulator this stage was declared with.
private static <T> T cast(Object value) { private static <T> T cast(Object value) {
return (T) value; return (T) value;
} }
@@ -1,6 +1,8 @@
package com.volmit.host; package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.config.FeatureSettings; import com.volmit.config.FeatureSettings;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.generation.GenerationContext; import com.volmit.generation.GenerationContext;
import com.volmit.hunk.Hunk; import com.volmit.hunk.Hunk;
import com.volmit.mantle.Mantle; import com.volmit.mantle.Mantle;
@@ -10,6 +12,7 @@ import com.volmit.world.PackWorld;
import com.volmit.stage.ChunkStageContext; import com.volmit.stage.ChunkStageContext;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.world.TerrainSampler; import com.volmit.world.TerrainSampler;
import java.util.List;
import java.util.Objects; import java.util.Objects;
/** The context every stage of one chunk invocation receives. The mantle is read-only. */ /** The context every stage of one chunk invocation receives. The mantle is read-only. */
@@ -31,6 +34,11 @@ final class ChunkInvocation implements ChunkStageContext {
return stages.output(stage); return stages.output(stage);
} }
@Override
public <S extends IrisFeature> List<Entry<S>> configured(Class<S> settingsType) {
return stages.configured(settingsType);
}
@Override @Override
public int originX() { public int originX() {
return inputs.originX(); return inputs.originX();
+4 -11
View File
@@ -18,17 +18,10 @@ public final class ChunkRunner {
} }
} }
/** Runs one chunk. A conditional stage is active when any of the chunk's 16 by 16 columns has an /** Runs one chunk and reports to {@code timings} how long each stage that ran took. A conditional stage is active
* entry of its settings in {@code inputs.settings()}, and receives every distinct entry of those * when any of the chunk's 16 by 16 columns has an entry of its settings in {@code inputs.settings()}, and reads
* columns. The host derives {@code invocationSeed} from the world seed and the chunk position; each * every distinct entry of those columns. The host derives {@code invocationSeed} from the world seed and the chunk
* stage draws from its own stream of that seed ({@link StageStreams}). * position; each stage draws from its own stream of that seed ({@link StageStreams}).
*/
public void generate(GenerationContext inputs, long invocationSeed) {
generate(inputs, invocationSeed, StageTimings.NONE);
}
/** Runs one chunk like {@link #generate(GenerationContext, long)} and reports to {@code timings} how long each
* stage that ran took.
*/ */
public void generate(GenerationContext inputs, long invocationSeed, StageTimings timings) { public void generate(GenerationContext inputs, long invocationSeed, StageTimings timings) {
Objects.requireNonNull(timings, "timings"); Objects.requireNonNull(timings, "timings");
@@ -0,0 +1,64 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.stage.ChunkStageContext;
import com.volmit.stage.ChunkStageDefinition;
import com.volmit.stage.Stage;
import com.volmit.stage.StageAction;
import com.volmit.stage.StageFunction;
import com.volmit.stage.StageRef;
/** Builder behind {@link ChunkStageDefinition}. */
final class ChunkStageDraft<O> implements ChunkStageDefinition<O> {
private final StageDeclaration declaration;
ChunkStageDraft(StageDeclaration declaration) {
this.declaration = declaration;
}
@Override
public ChunkStageDraft<O> requires(Stage<?>... stages) {
declaration.require(stages);
return this;
}
@Override
public ChunkStageDraft<O> softAfter(Stage<?>... stages) {
declaration.softAfter(stages);
return this;
}
@Override
public ChunkStageDraft<O> softAfter(StageRef... stages) {
declaration.softAfter(stages);
return this;
}
@Override
public ChunkStageDraft<O> softBefore(Stage<?>... stages) {
declaration.softBefore(stages);
return this;
}
@Override
public ChunkStageDraft<O> softBefore(StageRef... stages) {
declaration.softBefore(stages);
return this;
}
@Override
public ChunkStageDraft<O> when(Class<? extends IrisFeature> settingsType) {
declaration.condition(settingsType);
return this;
}
@Override
public void run(StageAction<ChunkStageContext> action) {
declaration.run(action);
}
@Override
public void produce(StageFunction<ChunkStageContext, O> function) {
declaration.produce(function);
}
}
@@ -12,10 +12,11 @@ import java.util.Map;
import java.util.Objects; import java.util.Objects;
/** The settings entries configured for one invocation, per settings type, in level order. A stage /** The settings entries configured for one invocation, per settings type, in level order. A stage
* conditioned on a type is active when the type has at least one entry, and its body receives them * conditioned on a type is active when the type has at least one entry, and reads them all with
* all. For a placement these are the placement's own declarations; for a chunk the runners collect * {@link com.volmit.stage.StageContext#configured}. For a placement these are the placement's own declarations; for
* every distinct entry of the chunk's columns themselves. Build once and reuse it for every invocation * a chunk the runners collect every distinct entry of the chunk's columns themselves. Entries are grouped by their
* with the same configuration. * declared settings type ({@link FeatureDescriptor#declaredType}), so a value of a subclass counts as the type it is
* declared as. Build once and reuse it for every invocation with the same configuration.
*/ */
public final class ConfiguredSettings { public final class ConfiguredSettings {
private static final ConfiguredSettings NONE = new ConfiguredSettings(Map.of()); private static final ConfiguredSettings NONE = new ConfiguredSettings(Map.of());
@@ -31,26 +32,27 @@ public final class ConfiguredSettings {
return NONE; return NONE;
} }
/** These entries, grouped by settings type, each group in level order and otherwise as given. */ /** These entries, grouped by declared settings type, each group in level order and otherwise as given. */
public static ConfiguredSettings of(List<? extends Entry<?>> entries) { public static ConfiguredSettings of(List<? extends Entry<?>> entries) {
var grouped = new HashMap<Class<?>, List<Entry<?>>>(); var grouped = new HashMap<Class<?>, List<Entry<?>>>();
for (var entry : entries) { for (var entry : entries) {
Objects.requireNonNull(entry, "entry"); Objects.requireNonNull(entry, "entry");
grouped.computeIfAbsent(entry.value().getClass(), ignored -> new ArrayList<>()).add(entry); grouped.computeIfAbsent(FeatureDescriptor.declaredType(entry.value().getClass()), ignored -> new ArrayList<>()).add(entry);
} }
grouped.replaceAll((type, group) -> group.stream().sorted(LEVEL_ORDER).toList()); grouped.replaceAll((type, group) -> group.stream().sorted(LEVEL_ORDER).toList());
return grouped.isEmpty() ? NONE : new ConfiguredSettings(grouped); return grouped.isEmpty() ? NONE : new ConfiguredSettings(grouped);
} }
/** One placement's own settings, at most one value per type, declared by {@code source}. */ /** One placement's own settings, at most one value per declared type, declared by {@code source}. */
public static ConfiguredSettings placement(ResourceId source, IrisFeature... settings) { public static ConfiguredSettings placement(ResourceId source, IrisFeature... settings) {
Objects.requireNonNull(source, "source"); Objects.requireNonNull(source, "source");
var entries = new ArrayList<Entry<?>>(); var entries = new ArrayList<Entry<?>>();
var types = new HashMap<Class<?>, IrisFeature>(); var types = new HashMap<Class<?>, IrisFeature>();
for (var value : settings) { for (var value : settings) {
Objects.requireNonNull(value, "settings"); Objects.requireNonNull(value, "settings");
if (types.putIfAbsent(value.getClass(), value) != null) { var declared = FeatureDescriptor.declaredType(value.getClass());
throw new IllegalArgumentException("Settings configured twice: " + value.getClass().getName()); if (types.putIfAbsent(declared, value) != null) {
throw new IllegalArgumentException("Settings configured twice: " + declared.getName());
} }
entries.add(new Entry<>(FeatureAttachment.Target.OBJECT_PLACEMENT, source, value)); entries.add(new Entry<>(FeatureAttachment.Target.OBJECT_PLACEMENT, source, value));
} }
@@ -58,7 +60,7 @@ public final class ConfiguredSettings {
} }
/** The entries of {@code type}, in level order; empty when nothing configures it. */ /** The entries of {@code type}, in level order; empty when nothing configures it. */
@SuppressWarnings("unchecked") // Entries are grouped by the class of their value. @SuppressWarnings("unchecked") // Entries are grouped by the declared type of their value.
public <S extends IrisFeature> List<Entry<S>> find(Class<S> type) { public <S extends IrisFeature> List<Entry<S>> find(Class<S> type) {
var found = entries.get(type); var found = entries.get(type);
return found == null ? List.of() : (List<Entry<S>>) (List<?>) found; return found == null ? List.of() : (List<Entry<S>>) (List<?>) found;
@@ -64,6 +64,25 @@ public record FeatureDescriptor<F extends IrisFeature>(
} }
} }
/** The settings type a value of {@code valueClass} is configured as: the nearest class of its hierarchy that
* declares {@code @Feature}, so a subclass without its own declaration counts as its declared superclass.
*/
public static Class<?> declaredType(Class<?> valueClass) {
return DECLARED_TYPES.get(Objects.requireNonNull(valueClass, "valueClass"));
}
private static final ClassValue<Class<?>> DECLARED_TYPES = new ClassValue<>() {
@Override
protected Class<?> computeValue(Class<?> valueClass) {
for (Class<?> type = valueClass; type != null; type = type.getSuperclass()) {
if (type.getDeclaredAnnotation(Feature.class) != null) {
return type;
}
}
throw new IllegalArgumentException("Missing @Feature: " + valueClass.getName() + " and its superclasses declare none");
}
};
private static void requireKey(ResourceId id, String key) { private static void requireKey(ResourceId id, String key) {
try { try {
FeatureAttachment.requireFieldName(key); FeatureAttachment.requireFieldName(key);
@@ -3,7 +3,7 @@ package com.volmit.host;
import com.volmit.config.PackSettings; import com.volmit.config.PackSettings;
import com.volmit.stage.PackReach; import com.volmit.stage.PackReach;
/** A reach declared as a number at install, the same for every pack. */ /** A reach declared as a number during setup, the same for every pack. */
record FixedReach(int blocks) implements PackReach { record FixedReach(int blocks) implements PackReach {
static final FixedReach NONE = new FixedReach(0); static final FixedReach NONE = new FixedReach(0);
@@ -17,7 +17,7 @@ import java.util.Optional;
import java.util.TreeMap; import java.util.TreeMap;
/** Validates and orders the stages of one pipeline. Nodes are numbered in lexical id order, /** Validates and orders the stages of one pipeline. Nodes are numbered in lexical id order,
* which makes every choice below independent of module install order. * which makes every choice below independent of module setup order.
*/ */
final class GraphResolver { final class GraphResolver {
private final Pipeline pipeline; private final Pipeline pipeline;
@@ -1,107 +0,0 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.mantle.MantleKey;
import com.volmit.stage.ConditionalStageDefinition;
import com.volmit.stage.PackReach;
import com.volmit.stage.SettingsAction;
import com.volmit.stage.SettingsFunction;
import com.volmit.stage.Stage;
import com.volmit.stage.StageAction;
import com.volmit.stage.StageContext;
import com.volmit.stage.StageDefinition;
import com.volmit.stage.StageFunction;
import com.volmit.stage.StageRef;
import java.util.Objects;
/** Builder behind both invocation stage definition views; S is unused until when(...). */
final class InvocationStageDraft<C extends StageContext, S extends IrisFeature, O>
implements StageDefinition<C, O>, ConditionalStageDefinition<C, S, O> {
private final StageDeclaration declaration;
InvocationStageDraft(StageDeclaration declaration) {
this.declaration = declaration;
}
@Override
public InvocationStageDraft<C, S, O> requires(Stage<?>... stages) {
declaration.require(stages);
return this;
}
@Override
public InvocationStageDraft<C, S, O> softAfter(StageRef... stages) {
declaration.softAfter(stages);
return this;
}
@Override
public InvocationStageDraft<C, S, O> softBefore(StageRef... stages) {
declaration.softBefore(stages);
return this;
}
@Override
public InvocationStageDraft<C, S, O> reach(int blocks) {
declaration.reach(blocks);
return this;
}
@Override
public InvocationStageDraft<C, S, O> reach(PackReach reach) {
declaration.reach(reach);
return this;
}
@Override
public InvocationStageDraft<C, S, O> writesMantle(MantleKey<?>... layers) {
declaration.writesMantle(layers);
return this;
}
@Override
@SuppressWarnings("unchecked") // S is a phantom parameter until the condition is recorded here.
public <N extends IrisFeature> InvocationStageDraft<C, N, O> when(Class<N> settingsType) {
declaration.condition(settingsType);
return (InvocationStageDraft<C, N, O>) (InvocationStageDraft<?, ?, ?>) this;
}
@Override
public void run(StageAction<C> action) {
Objects.requireNonNull(action, "action");
complete(false, "produce", (context, settings) -> {
action.run(cast(context));
return null;
});
}
@Override
public void produce(StageFunction<C, O> function) {
Objects.requireNonNull(function, "function");
complete(true, "run", (context, settings) -> function.run(cast(context)));
}
@Override
public void run(SettingsAction<C, S> action) {
Objects.requireNonNull(action, "action");
complete(false, "produce", (context, settings) -> {
action.run(cast(context), cast(settings));
return null;
});
}
@Override
public void produce(SettingsFunction<C, S, O> function) {
Objects.requireNonNull(function, "function");
complete(true, "run", (context, settings) -> function.run(cast(context), cast(settings)));
}
private void complete(boolean producesOutput, String alternativeMethod, StageBody.InvocationWork work) {
declaration.complete(new StageBody.Invocation(work), producesOutput, alternativeMethod);
}
@SuppressWarnings("unchecked") // The executor passes the context and settings this stage was declared with.
private static <T> T cast(Object value) {
return (T) value;
}
}
@@ -39,7 +39,7 @@ public record LoadedModules(
var registry = new ModuleRegistry(reservedHostFields, Set.copyOf(reservedFolders)); var registry = new ModuleRegistry(reservedHostFields, Set.copyOf(reservedFolders));
var stages = new StageGraphBuilder(); var stages = new StageGraphBuilder();
for (var discovered : modules) { for (var discovered : modules) {
installModule(discovered, stages, registry); setUpModule(discovered, stages, registry);
} }
stages.settingsTypes(registry::registeredByOwner).forEach(registry::registerStageSettings); stages.settingsTypes(registry::registeredByOwner).forEach(registry::registerStageSettings);
var catalog = registry.freeze(); var catalog = registry.freeze();
@@ -75,13 +75,12 @@ public record LoadedModules(
/** The pack load checks that every class a module uses exists, not that every method or field /** The pack load checks that every class a module uses exists, not that every method or field
* it uses does, so a jar built against another Iris API can still fail to link here. * it uses does, so a jar built against another Iris API can still fail to link here.
*/ */
private static void installModule(DiscoveredModule discovered, StageGraphBuilder stages, ModuleRegistry registry) { private static void setUpModule(DiscoveredModule discovered, StageGraphBuilder stages, ModuleRegistry registry) {
try { try {
stages.install(discovered); ModuleSetups.run(discovered, stages, registry);
registry.register(discovered);
} catch (LinkageError error) { } catch (LinkageError error) {
throw new IllegalArgumentException("Module " + discovered.info().id() + " from " throw new IllegalArgumentException("Module " + discovered.info().id() + " from "
+ discovered.origin() + " failed to link or initialize a class while installing: " + error + discovered.origin() + " failed to link or initialize a class during setup: " + error
+ "; a missing method or field means the jar was built against a different Iris API", error); + "; a missing method or field means the jar was built against a different Iris API", error);
} catch (IncompleteFeatureException incomplete) { } catch (IncompleteFeatureException incomplete) {
throw new IllegalArgumentException("Module " + discovered.info().id() + " from " + discovered.origin() + ": " throw new IllegalArgumentException("Module " + discovered.info().id() + " from " + discovered.origin() + ": "
@@ -29,7 +29,7 @@ public final class LoadedPack implements AutoCloseable {
this.loaded = loaded; this.loaded = loaded;
} }
/** Loads the pack's module jars, installs them with the host's built-in modules and resolves the /** Loads the pack's module jars, sets them up with the host's built-in modules and resolves the
* pipelines. Fails with the first load error, naming the jar or module at fault. * pipelines. Fails with the first load error, naming the jar or module at fault.
*/ */
public static LoadedPack load(Path packRoot, ModuleHost host) { public static LoadedPack load(Path packRoot, ModuleHost host) {
@@ -1,6 +1,8 @@
package com.volmit.host; package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.config.FeatureSettings; import com.volmit.config.FeatureSettings;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.generation.MantleGenerationContext; import com.volmit.generation.MantleGenerationContext;
import com.volmit.mantle.Mantle; import com.volmit.mantle.Mantle;
import com.volmit.random.WorldRandom; import com.volmit.random.WorldRandom;
@@ -9,6 +11,7 @@ import com.volmit.world.PackWorld;
import com.volmit.stage.MantleStageContext; import com.volmit.stage.MantleStageContext;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.world.TerrainSampler; import com.volmit.world.TerrainSampler;
import java.util.List;
import java.util.Objects; import java.util.Objects;
/** The context every stage of one mantle invocation receives. */ /** The context every stage of one mantle invocation receives. */
@@ -30,6 +33,11 @@ final class MantleInvocation implements MantleStageContext {
return stages.output(stage); return stages.output(stage);
} }
@Override
public <S extends IrisFeature> List<Entry<S>> configured(Class<S> settingsType) {
return stages.configured(settingsType);
}
@Override @Override
public int originX() { public int originX() {
return inputs.originX(); return inputs.originX();
@@ -32,16 +32,22 @@ public final class MantleRunner {
activationSettings = activationSettings(graph); activationSettings = activationSettings(graph);
} }
/** Runs {@code stage} for one chunk, if it is active there. A conditional stage is active when any of /** Runs {@code stage} for one chunk, if it is active there, and reports to {@code timings} how long it took. A
* the chunk's 16 by 16 columns has an entry of its settings, and receives every distinct entry of those * conditional stage is active when any of the chunk's 16 by 16 columns has an entry of its settings, and reads
* columns; it is inactive wherever a stage it requires is. The host derives {@code invocationSeed} from * every distinct entry of those columns; it is inactive wherever a stage it requires is. The host derives
* the world seed and the chunk position; each stage draws from its own stream of it. * {@code invocationSeed} from the world seed and the chunk position; each stage draws from its own stream of it.
*/ */
public void generate(Stage<?> stage, MantleGenerationContext inputs, long invocationSeed) { public void generate(Stage<?> stage, MantleGenerationContext inputs, long invocationSeed, StageTimings timings) {
Objects.requireNonNull(timings, "timings");
int position = position(stage); int position = position(stage);
var settings = ChunkSettings.collect(activationSettings.get(position), inputs::settings, inputs.originX(), inputs.originZ()); var settings = ChunkSettings.collect(activationSettings.get(position), inputs::settings, inputs.originX(), inputs.originZ());
var mantle = new MantleInvocation(new StageInvocation(graph, invocationSeed, settings), inputs); var mantle = new MantleInvocation(new StageInvocation(graph, invocationSeed, settings), inputs);
if (!mantle.stages().isActive(position)) {
return;
}
long started = System.nanoTime();
mantle.stages().runInvocationStage(position, mantle); mantle.stages().runInvocationStage(position, mantle);
timings.record(graph.stages().get(position), System.nanoTime() - started);
} }
private int position(Stage<?> stage) { private int position(Stage<?> stage) {
@@ -0,0 +1,78 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.mantle.MantleKey;
import com.volmit.stage.MantleStageContext;
import com.volmit.stage.MantleStageDefinition;
import com.volmit.stage.PackReach;
import com.volmit.stage.Stage;
import com.volmit.stage.StageAction;
import com.volmit.stage.StageRef;
/** Builder behind {@link MantleStageDefinition}. */
final class MantleStageDraft implements MantleStageDefinition {
private final StageDeclaration declaration;
MantleStageDraft(StageDeclaration declaration) {
this.declaration = declaration;
}
@Override
public MantleStageDraft requires(Stage<?>... stages) {
declaration.require(stages);
return this;
}
@Override
public MantleStageDraft softAfter(Stage<?>... stages) {
declaration.softAfter(stages);
return this;
}
@Override
public MantleStageDraft softAfter(StageRef... stages) {
declaration.softAfter(stages);
return this;
}
@Override
public MantleStageDraft softBefore(Stage<?>... stages) {
declaration.softBefore(stages);
return this;
}
@Override
public MantleStageDraft softBefore(StageRef... stages) {
declaration.softBefore(stages);
return this;
}
@Override
public MantleStageDraft reach(int blocks) {
declaration.reach(blocks);
return this;
}
@Override
public MantleStageDraft reach(PackReach reach) {
declaration.reach(reach);
return this;
}
@Override
public MantleStageDraft writesMantle(MantleKey<?>... layers) {
declaration.writesMantle(layers);
return this;
}
@Override
public MantleStageDraft when(Class<? extends IrisFeature> settingsType) {
declaration.condition(settingsType);
return this;
}
@Override
public void run(StageAction<MantleStageContext> action) {
declaration.run(action);
}
}
@@ -130,7 +130,7 @@ public record ModuleHost(
reservedFolders, bundledJars, jarCopyRoot, logger); reservedFolders, bundledJars, jarCopyRoot, logger);
} }
/** The built-in modules followed by a pack's modules, in the order {@link LoadedModules} installs them. */ /** The built-in modules followed by a pack's modules, in the order {@link LoadedModules} sets them up. */
List<DiscoveredModule> withPackModules(List<DiscoveredModule> packModules) { List<DiscoveredModule> withPackModules(List<DiscoveredModule> packModules) {
var modules = new ArrayList<>(builtIns); var modules = new ArrayList<>(builtIns);
modules.addAll(Objects.requireNonNull(packModules, "packModules")); modules.addAll(Objects.requireNonNull(packModules, "packModules"));
@@ -3,9 +3,7 @@ package com.volmit.host;
import com.volmit.FeatureAttachment; import com.volmit.FeatureAttachment;
import com.volmit.FeatureRegistry; import com.volmit.FeatureRegistry;
import com.volmit.IrisFeature; import com.volmit.IrisFeature;
import com.volmit.IrisModule;
import com.volmit.ModuleLifecycle; import com.volmit.ModuleLifecycle;
import com.volmit.ModuleLog;
import com.volmit.mantle.MantleCodec; import com.volmit.mantle.MantleCodec;
import com.volmit.mantle.MantleKey; import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime; import com.volmit.mantle.MantleLifetime;
@@ -26,8 +24,8 @@ import java.util.Set;
/** Reference host registry. Single-threaded registration ends with freeze(); the catalog is /** Reference host registry. Single-threaded registration ends with freeze(); the catalog is
* immutable. IDs are unique across feature kinds. A feature's JSON key (see {@link com.volmit.config.Feature#key}) * immutable. IDs are unique across feature kinds. A feature's JSON key (see {@link com.volmit.config.Feature#key})
* is unique per attachment target, and may not equal a host JSON field passed in to reserve it; a clash fails the * is unique per attachment target, and may not equal a host JSON field passed in to reserve it; a clash fails the
* registration naming the key, the target and both claimants. Modules register through * registration naming the key, the target and both claimants. Modules register during their setup
* {@link #register(DiscoveredModule)}; object feature ids, mantle keys, resource kind ids and explicitly registered * ({@link ModuleSetups#run}); object feature ids, mantle keys, resource kind ids and explicitly registered
* settings ids must be the registering module's id or start with it and '/' ({@link com.volmit.ModuleInfo#ownsId}). * settings ids must be the registering module's id or start with it and '/' ({@link com.volmit.ModuleInfo#ownsId}).
* Resource kinds have unique ids, types and folders, and no kind may read a folder the host reserves for its own * Resource kinds have unique ids, types and folders, and no kind may read a folder the host reserves for its own
* files. Lifecycle hooks and service providers are registered by the module that owns them; a service whose providers * files. Lifecycle hooks and service providers are registered by the module that owns them; a service whose providers
@@ -66,28 +64,19 @@ public final class ModuleRegistry implements FeatureRegistry {
this.reservedFolders = Set.copyOf(reservedFolders); this.reservedFolders = Set.copyOf(reservedFolders);
} }
/** Lets the module register its contributions through {@link IrisModule#register}. */ /** Accepts {@code discovered}'s registrations until {@link #endSetup()}; see {@link ModuleSetups#run}. */
public void register(DiscoveredModule discovered) { void beginSetup(DiscoveredModule discovered) {
Objects.requireNonNull(discovered, "discovered"); Objects.requireNonNull(discovered, "discovered");
checkOpen(); checkOpen();
if (registering != null) { if (registering != null) {
throw new IllegalStateException("Module " + discovered.info().id() + " registered during " + registering.info().id()); throw new IllegalStateException("Module " + discovered.info().id() + " set up during " + registering.info().id());
} }
registering = discovered; registering = discovered;
registered.add(discovered); registered.add(discovered);
try {
discovered.module().register(this);
} finally {
registering = null;
}
} }
@Override void endSetup() {
public ModuleLog log() { registering = null;
if (registering == null) {
throw new IllegalStateException("The registry's log is only available during IrisModule.register");
}
return registering.log();
} }
@Override @Override
@@ -151,7 +140,7 @@ public final class ModuleRegistry implements FeatureRegistry {
checkOpen(); checkOpen();
Objects.requireNonNull(validator, "validator"); Objects.requireNonNull(validator, "validator");
if (registering == null) { if (registering == null) {
throw new IllegalStateException("Validator " + validator + " registered outside IrisModule.register"); throw new IllegalStateException("Validator " + validator + " registered outside IrisModule.setup");
} }
validators.add(new ValidatorRegistration(validator, registering)); validators.add(new ValidatorRegistration(validator, registering));
} }
@@ -225,7 +214,7 @@ public final class ModuleRegistry implements FeatureRegistry {
private void requireOwnedId(String registration, ResourceId id) { private void requireOwnedId(String registration, ResourceId id) {
if (registering == null) { if (registering == null) {
throw new IllegalStateException(registration + " " + id + " registered outside IrisModule.register"); throw new IllegalStateException(registration + " " + id + " registered outside IrisModule.setup");
} }
var info = registering.info(); var info = registering.info();
if (info.ownsId(id)) return; if (info.ownsId(id)) return;
@@ -235,7 +224,7 @@ public final class ModuleRegistry implements FeatureRegistry {
private void requireRegistering(String registration) { private void requireRegistering(String registration) {
if (registering == null) { if (registering == null) {
throw new IllegalStateException(registration + " registered outside IrisModule.register"); throw new IllegalStateException(registration + " registered outside IrisModule.setup");
} }
} }
@@ -0,0 +1,33 @@
package com.volmit.host;
import com.volmit.FeatureRegistry;
import com.volmit.ModuleLog;
import com.volmit.ModuleSetup;
import com.volmit.stage.StageGraph;
import java.util.Objects;
/** Runs a module's {@link com.volmit.IrisModule#setup} against one pack load's stage graph and registry. While it
* runs, the graph accepts the module's stages and the registry its registrations, both scoped to the module; after
* it returns, every stage the module defined must have a body.
*/
public final class ModuleSetups {
private ModuleSetups() {}
public static void run(DiscoveredModule discovered, StageGraphBuilder stages, ModuleRegistry registry) {
Objects.requireNonNull(discovered, "discovered");
Objects.requireNonNull(stages, "stages");
Objects.requireNonNull(registry, "registry");
stages.beginSetup(discovered);
registry.beginSetup(discovered);
boolean completed = false;
try {
discovered.module().setup(new Setup(stages, registry, discovered.log()));
completed = true;
} finally {
registry.endSetup();
stages.endSetup(completed);
}
}
private record Setup(StageGraph stages, FeatureRegistry registry, ModuleLog log) implements ModuleSetup {}
}
@@ -5,7 +5,7 @@ import java.util.List;
/** Checks the classes of all jars of one pack before its class loader exists, so a pack that /** Checks the classes of all jars of one pack before its class loader exists, so a pack that
* cannot link fails at load with the jar to fix, not later with a {@link NoClassDefFoundError} * cannot link fails at load with the jar to fix, not later with a {@link NoClassDefFoundError}
* during install or generation. * during setup or generation.
*/ */
final class PackClassCheck { final class PackClassCheck {
private PackClassCheck() {} private PackClassCheck() {}
@@ -1,6 +1,8 @@
package com.volmit.host; package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.config.FeatureSettings; import com.volmit.config.FeatureSettings;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.object.ObjectBlock; import com.volmit.object.ObjectBlock;
import com.volmit.object.ObjectTransformer; import com.volmit.object.ObjectTransformer;
import com.volmit.placement.PlacementAccess; import com.volmit.placement.PlacementAccess;
@@ -13,6 +15,7 @@ import com.volmit.stage.BlockStageContext;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.world.BlockView; import com.volmit.world.BlockView;
import com.volmit.world.TerrainSampler; import com.volmit.world.TerrainSampler;
import java.util.List;
import java.util.Objects; import java.util.Objects;
/** The context every stage of one placement attempt receives. Block accessors work only while /** The context every stage of one placement attempt receives. Block accessors work only while
@@ -70,6 +73,11 @@ final class PlacementInvocation implements BlockStageContext {
return stages.output(stage); return stages.output(stage);
} }
@Override
public <S extends IrisFeature> List<Entry<S>> configured(Class<S> settingsType) {
return stages.configured(settingsType);
}
@Override @Override
public PlacementRequest request() { public PlacementRequest request() {
return request; return request;
@@ -25,20 +25,23 @@ public final class PlacementRunner {
* The host prepares the edit area, the read-only inputs and the settings configured for this * The host prepares the edit area, the read-only inputs and the settings configured for this
* placement, and derives {@code invocationSeed} from the world seed and the placement's stable * placement, and derives {@code invocationSeed} from the world seed and the placement's stable
* identity. Each stage draws from its own stream of that seed ({@link StageStreams}). Stages never * identity. Each stage draws from its own stream of that seed ({@link StageStreams}). Stages never
* receive commit/close rights. * receive commit/close rights. {@code timings} hears how long each stage that ran took; a block stage
* is reported once per pass, with its time summed over the blocks it ran for, when the pass ends.
*/ */
public PlacementOutcome place( public PlacementOutcome place(
PlacementRequest request, PlacementRequest request,
PlacementEdit edit, PlacementEdit edit,
PlacementContext inputs, PlacementContext inputs,
long invocationSeed, long invocationSeed,
ConfiguredSettings settings) { ConfiguredSettings settings,
StageTimings timings) {
Objects.requireNonNull(edit, "edit"); Objects.requireNonNull(edit, "edit");
try (edit) { try (edit) {
Objects.requireNonNull(timings, "timings");
var stages = new StageInvocation(graph, invocationSeed, settings); var stages = new StageInvocation(graph, invocationSeed, settings);
var access = PlacementViews.restrict(edit, edit.bounds()); var access = PlacementViews.restrict(edit, edit.bounds());
var placement = new PlacementInvocation(stages, request, inputs, access); var placement = new PlacementInvocation(stages, request, inputs, access);
runSegments(placement); runSegments(placement, timings);
if (placement.isRejected()) { if (placement.isRejected()) {
return PlacementOutcome.rejected(placement.rejection()); return PlacementOutcome.rejected(placement.rejection());
} }
@@ -47,48 +50,88 @@ public final class PlacementRunner {
} }
} }
private void runSegments(PlacementInvocation placement) { private void runSegments(PlacementInvocation placement, StageTimings timings) {
for (var segment : graph.segments()) { for (var segment : graph.segments()) {
if (placement.isRejected()) { if (placement.isRejected()) {
return; return;
} }
switch (segment.kind()) { switch (segment.kind()) {
case INVOCATION -> placement.stages().runInvocationStage(segment.start(), placement); case INVOCATION -> runInvocationStage(segment.start(), placement, timings);
case BLOCK -> runBlockPass(segment, placement); case BLOCK -> runBlockPass(segment, placement, timings);
} }
} }
} }
private static void runBlockPass(Segment segment, PlacementInvocation placement) { private void runInvocationStage(int position, PlacementInvocation placement, StageTimings timings) {
if (!placement.stages().isActive(position)) {
return;
}
long started = System.nanoTime();
placement.stages().runInvocationStage(position, placement, placement::isRejected);
timings.record(graph.stages().get(position), System.nanoTime() - started);
}
private void runBlockPass(Segment segment, PlacementInvocation placement, StageTimings timings) {
var stages = placement.stages(); var stages = placement.stages();
int[] active = stages.activePositions(segment); int[] active = stages.activePositions(segment);
if (active.length == 0) { if (active.length == 0) {
return; return;
} }
var accumulators = new Object[active.length]; var pass = new BlockPass(active.length);
for (int index = 0; index < active.length; index++) { for (int index = 0; index < active.length; index++) {
accumulators[index] = stages.newAccumulator(active[index]); pass.accumulators[index] = stages.newAccumulator(active[index]);
} }
for (var block : placement.request().object().blocks()) { for (var block : placement.request().object().blocks()) {
placement.beginBlock(block); placement.beginBlock(block);
runBlockStages(active, accumulators, placement); runBlockStages(active, pass, placement);
if (placement.isRejected()) { if (placement.isRejected()) {
return; break;
} }
} }
placement.endBlockPass(); placement.endBlockPass();
reportBlockPass(active, pass, timings);
if (placement.isRejected()) {
return;
}
for (int index = 0; index < active.length; index++) { for (int index = 0; index < active.length; index++) {
stages.complete(active[index], accumulators[index]); stages.complete(active[index], pass.accumulators[index]);
} }
} }
private static void runBlockStages(int[] active, Object[] accumulators, PlacementInvocation placement) { /** One nanoTime per stage boundary: each stage's time ends where the next one's starts. */
private static void runBlockStages(int[] active, BlockPass pass, PlacementInvocation placement) {
long started = System.nanoTime();
for (int index = 0; index < active.length; index++) { for (int index = 0; index < active.length; index++) {
placement.stages().runBlockStage(active[index], placement, accumulators[index]); placement.stages().runBlockStage(active[index], placement, pass.accumulators[index]);
long finished = System.nanoTime();
pass.nanos[index] += finished - started;
pass.ran[index] = true;
started = finished;
if (placement.isRejected() || placement.isBlockSkipped()) { if (placement.isRejected() || placement.isBlockSkipped()) {
return; return;
} }
} }
} }
private void reportBlockPass(int[] active, BlockPass pass, StageTimings timings) {
for (int index = 0; index < active.length; index++) {
if (pass.ran[index]) {
timings.record(graph.stages().get(active[index]), pass.nanos[index]);
}
}
}
/** Per active stage of one block pass, in pass order: its accumulator, its summed time and whether it ran. */
private static final class BlockPass {
final Object[] accumulators;
final long[] nanos;
final boolean[] ran;
BlockPass(int stages) {
accumulators = new Object[stages];
nanos = new long[stages];
ran = new boolean[stages];
}
}
} }
@@ -0,0 +1,77 @@
package com.volmit.host;
import com.volmit.IrisFeature;
import com.volmit.mantle.MantleKey;
import com.volmit.stage.PlacementStageContext;
import com.volmit.stage.PlacementStageDefinition;
import com.volmit.stage.Stage;
import com.volmit.stage.StageAction;
import com.volmit.stage.StageFunction;
import com.volmit.stage.StageRef;
/** Builder behind {@link PlacementStageDefinition}. */
final class PlacementStageDraft<O> implements PlacementStageDefinition<O> {
private final StageDeclaration declaration;
PlacementStageDraft(StageDeclaration declaration) {
this.declaration = declaration;
}
@Override
public PlacementStageDraft<O> requires(Stage<?>... stages) {
declaration.require(stages);
return this;
}
@Override
public PlacementStageDraft<O> softAfter(Stage<?>... stages) {
declaration.softAfter(stages);
return this;
}
@Override
public PlacementStageDraft<O> softAfter(StageRef... stages) {
declaration.softAfter(stages);
return this;
}
@Override
public PlacementStageDraft<O> softBefore(Stage<?>... stages) {
declaration.softBefore(stages);
return this;
}
@Override
public PlacementStageDraft<O> softBefore(StageRef... stages) {
declaration.softBefore(stages);
return this;
}
@Override
public PlacementStageDraft<O> reach(int blocks) {
declaration.reach(blocks);
return this;
}
@Override
public PlacementStageDraft<O> writesMantle(MantleKey<?>... layers) {
declaration.writesMantle(layers);
return this;
}
@Override
public PlacementStageDraft<O> when(Class<? extends IrisFeature> settingsType) {
declaration.condition(settingsType);
return this;
}
@Override
public void run(StageAction<PlacementStageContext> action) {
declaration.run(action);
}
@Override
public void produce(StageFunction<PlacementStageContext, O> function) {
declaration.produce(function);
}
}
@@ -6,7 +6,7 @@ import java.util.PriorityQueue;
/** Choice among stages whose predecessors have all run. Node numbers follow lexical stage id /** Choice among stages whose predecessors have all run. Node numbers follow lexical stage id
* order, so each queue yields the lexically smallest ready stage. To keep block passes fused, * order, so each queue yields the lexically smallest ready stage. To keep block passes fused,
* an open pass continues while a block stage is ready, and ready invocation stages run before * an open pass continues while a block stage is ready, and ready invocation stages run before
* a new pass opens. The choice depends only on ids and edges, never on install order. * a new pass opens. The choice depends only on ids and edges, never on setup order.
*/ */
final class ReadyStages { final class ReadyStages {
private final PriorityQueue<Integer> invocation = new PriorityQueue<>(); private final PriorityQueue<Integer> invocation = new PriorityQueue<>();
+2 -2
View File
@@ -14,11 +14,11 @@ sealed interface StageBody {
@FunctionalInterface @FunctionalInterface
interface InvocationWork { interface InvocationWork {
Object run(Object context, Object settings); Object run(Object context);
} }
@FunctionalInterface @FunctionalInterface
interface BlockWork { interface BlockWork {
void run(BlockStageContext context, Object settings, Object accumulator); void run(BlockStageContext context, Object accumulator);
} }
} }
@@ -5,16 +5,16 @@ import com.volmit.ModuleLog;
import com.volmit.mantle.MantleKey; import com.volmit.mantle.MantleKey;
import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceId;
import com.volmit.stage.PackReach; import com.volmit.stage.PackReach;
import com.volmit.stage.Pipeline;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.stage.StageAction;
import com.volmit.stage.StageFunction;
import com.volmit.stage.StageRef; import com.volmit.stage.StageRef;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
/** One stage as declared during install. It becomes immutable once its body is set. */ /** One stage as declared during setup. It becomes immutable once its body is set. */
final class StageDeclaration { final class StageDeclaration {
private final Stage<?> stage; private final Stage<?> stage;
private final ResourceId module; private final ResourceId module;
@@ -46,10 +46,26 @@ final class StageDeclaration {
addSoftReferences(softAfter, references); addSoftReferences(softAfter, references);
} }
void softAfter(Stage<?>... stages) {
addSoftReferences(softAfter, references(stages));
}
void softBefore(StageRef... references) { void softBefore(StageRef... references) {
addSoftReferences(softBefore, references); addSoftReferences(softBefore, references);
} }
void softBefore(Stage<?>... stages) {
addSoftReferences(softBefore, references(stages));
}
private static StageRef[] references(Stage<?>... stages) {
var references = new StageRef[stages.length];
for (int index = 0; index < stages.length; index++) {
references[index] = Objects.requireNonNull(stages[index], "stage").ref();
}
return references;
}
void condition(Class<? extends IrisFeature> settingsType) { void condition(Class<? extends IrisFeature> settingsType) {
checkOpen(); checkOpen();
if (settings != null) { if (settings != null) {
@@ -60,7 +76,6 @@ final class StageDeclaration {
void reach(int blocks) { void reach(int blocks) {
checkOpen(); checkOpen();
if (blocks > 0) requireOutsideChunkPipeline("a reach of " + blocks + " blocks");
if (blocks < 0) { if (blocks < 0) {
throw new IllegalArgumentException("Stage " + this + " declares a negative reach of " + blocks + " blocks"); throw new IllegalArgumentException("Stage " + this + " declares a negative reach of " + blocks + " blocks");
} }
@@ -69,13 +84,7 @@ final class StageDeclaration {
void reach(PackReach computed) { void reach(PackReach computed) {
checkOpen(); checkOpen();
Objects.requireNonNull(computed, "reach"); declareReach(Objects.requireNonNull(computed, "reach"));
if (stage.pipeline() != Pipeline.MANTLE) {
throw new IllegalArgumentException("Stage " + this + " is a " + stage.pipeline().name().toLowerCase(Locale.ROOT)
+ " stage and declares a reach worked out when the pack loads, which only mantle stages may;"
+ " declare a number of blocks with reach(blocks)");
}
declareReach(computed);
} }
private void declareReach(PackReach declared) { private void declareReach(PackReach declared) {
@@ -93,7 +102,6 @@ final class StageDeclaration {
void writesMantle(MantleKey<?>... layers) { void writesMantle(MantleKey<?>... layers) {
checkOpen(); checkOpen();
requireOutsideChunkPipeline("mantle writes");
for (var layer : layers) { for (var layer : layers) {
Objects.requireNonNull(layer, "mantle layer"); Objects.requireNonNull(layer, "mantle layer");
if (mantleLayers.stream().anyMatch(declared -> declared.id().equals(layer.id()))) { if (mantleLayers.stream().anyMatch(declared -> declared.id().equals(layer.id()))) {
@@ -103,6 +111,26 @@ final class StageDeclaration {
} }
} }
/** Sets an invocation body without output. */
void run(StageAction<?> action) {
Objects.requireNonNull(action, "action");
complete(new StageBody.Invocation(context -> {
action.run(cast(context));
return null;
}), false, "produce");
}
/** Sets an invocation body with output. */
void produce(StageFunction<?, ?> function) {
Objects.requireNonNull(function, "function");
complete(new StageBody.Invocation(context -> function.run(cast(context))), true, "run");
}
@SuppressWarnings("unchecked") // The executor passes the context of the pipeline this stage was declared in.
private static <T> T cast(Object value) {
return (T) value;
}
/** Sets the only body. alternativeMethod names the builder method for the other output kind. */ /** Sets the only body. alternativeMethod names the builder method for the other output kind. */
void complete(StageBody body, boolean bodyProducesOutput, String alternativeMethod) { void complete(StageBody body, boolean bodyProducesOutput, String alternativeMethod) {
checkOpen(); checkOpen();
@@ -180,14 +208,6 @@ final class StageDeclaration {
return "Stage " + this + " " + declared + "; define it with " + alternativeMethod + "(...)"; return "Stage " + this + " " + declared + "; define it with " + alternativeMethod + "(...)";
} }
/** Chunk stages write only their own chunk: the host may already have generated its neighbors. */
private void requireOutsideChunkPipeline(String declared) {
if (stage.pipeline() != Pipeline.CHUNK) return;
throw new IllegalArgumentException("Stage " + this + " is a chunk stage and declares " + declared
+ ", but chunk stages write only their own chunk and read the mantle; define work that writes the"
+ " mantle or reaches beyond its chunk as a mantle stage (Stage.mantle), which runs before the chunks it reaches");
}
private void checkOpen() { private void checkOpen() {
if (body != null) { if (body != null) {
throw new IllegalStateException("Stage " + this + " is already complete"); throw new IllegalStateException("Stage " + this + " is already complete");
@@ -5,14 +5,13 @@ import com.volmit.resource.ResourceId;
import com.volmit.stage.BlockStage; import com.volmit.stage.BlockStage;
import com.volmit.stage.BlockStageDefinition; import com.volmit.stage.BlockStageDefinition;
import com.volmit.stage.ChunkStage; import com.volmit.stage.ChunkStage;
import com.volmit.stage.ChunkStageContext; import com.volmit.stage.ChunkStageDefinition;
import com.volmit.stage.MantleStage; import com.volmit.stage.MantleStage;
import com.volmit.stage.MantleStageContext; import com.volmit.stage.MantleStageDefinition;
import com.volmit.stage.Pipeline; import com.volmit.stage.Pipeline;
import com.volmit.stage.PlacementStage; import com.volmit.stage.PlacementStage;
import com.volmit.stage.PlacementStageContext; import com.volmit.stage.PlacementStageDefinition;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.stage.StageDefinition;
import com.volmit.stage.StageGraph; import com.volmit.stage.StageGraph;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
@@ -24,8 +23,8 @@ import java.util.TreeSet;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** Reference host collection of module stages. Install every module, then resolve each pipeline /** Reference host collection of module stages. Set up every module ({@link ModuleSetups#run}), then resolve each
* once per pack load. Install order never affects the result. If a module's install throws, * pipeline once per pack load. Setup order never affects the result. If a module's setup throws,
* discard the whole builder: it may hold a partial module. Errors about one module name its origin. * discard the whole builder: it may hold a partial module. Errors about one module name its origin.
* *
* <p>A module defines only stages whose ids start with its own id and '/', and a settings type * <p>A module defines only stages whose ids start with its own id and '/', and a settings type
@@ -36,23 +35,27 @@ import java.util.stream.Collectors;
public final class StageGraphBuilder implements StageGraph { public final class StageGraphBuilder implements StageGraph {
private final Map<ResourceId, StageDeclaration> declarations = new HashMap<>(); private final Map<ResourceId, StageDeclaration> declarations = new HashMap<>();
private final Map<ResourceId, DiscoveredModule> modules = new HashMap<>(); private final Map<ResourceId, DiscoveredModule> modules = new HashMap<>();
private DiscoveredModule installing; private DiscoveredModule settingUp;
public void install(DiscoveredModule discovered) { /** Accepts {@code discovered}'s stages until {@link #endSetup(boolean)}; see {@link ModuleSetups#run}. */
void beginSetup(DiscoveredModule discovered) {
Objects.requireNonNull(discovered, "discovered"); Objects.requireNonNull(discovered, "discovered");
claimModule(discovered); claimModule(discovered);
installing = discovered; settingUp = discovered;
try { }
discovered.module().install(this);
} finally { /** Stops accepting the module's stages. With {@code completed}, every stage it defined must have a body. */
installing = null; void endSetup(boolean completed) {
var moduleId = settingUp.info().id();
settingUp = null;
if (completed) {
requireCompleteDefinitions(moduleId);
} }
requireCompleteDefinitions(discovered.info().id());
} }
@Override @Override
public <O> StageDefinition<PlacementStageContext, O> define(PlacementStage<O> stage) { public <O> PlacementStageDefinition<O> define(PlacementStage<O> stage) {
return new InvocationStageDraft<>(declare(stage)); return new PlacementStageDraft<>(declare(stage));
} }
@Override @Override
@@ -61,13 +64,13 @@ public final class StageGraphBuilder implements StageGraph {
} }
@Override @Override
public <O> StageDefinition<ChunkStageContext, O> define(ChunkStage<O> stage) { public <O> ChunkStageDefinition<O> define(ChunkStage<O> stage) {
return new InvocationStageDraft<>(declare(stage)); return new ChunkStageDraft<>(declare(stage));
} }
@Override @Override
public <O> StageDefinition<MantleStageContext, O> define(MantleStage<O> stage) { public MantleStageDefinition define(MantleStage stage) {
return new InvocationStageDraft<>(declare(stage)); return new MantleStageDraft(declare(stage));
} }
public ResolvedGraph resolve(Pipeline pipeline) { public ResolvedGraph resolve(Pipeline pipeline) {
@@ -91,8 +94,8 @@ public final class StageGraphBuilder implements StageGraph {
private void claimModule(DiscoveredModule discovered) { private void claimModule(DiscoveredModule discovered) {
var moduleId = discovered.info().id(); var moduleId = discovered.info().id();
if (installing != null) { if (settingUp != null) {
throw new IllegalStateException("Module " + moduleId + " installed during " + installing.info().id()); throw new IllegalStateException("Module " + moduleId + " set up during " + settingUp.info().id());
} }
var previous = modules.putIfAbsent(moduleId, discovered); var previous = modules.putIfAbsent(moduleId, discovered);
if (previous != null) { if (previous != null) {
@@ -139,7 +142,7 @@ public final class StageGraphBuilder implements StageGraph {
private StageDeclaration declare(Stage<?> stage) { private StageDeclaration declare(Stage<?> stage) {
Objects.requireNonNull(stage, "stage"); Objects.requireNonNull(stage, "stage");
var discovered = requireInstallingModule(stage); var discovered = requireModuleInSetup(stage);
requireOwnedStageId(stage, discovered); requireOwnedStageId(stage, discovered);
var module = discovered.info().id(); var module = discovered.info().id();
@@ -152,11 +155,11 @@ public final class StageGraphBuilder implements StageGraph {
return declaration; return declaration;
} }
private DiscoveredModule requireInstallingModule(Stage<?> stage) { private DiscoveredModule requireModuleInSetup(Stage<?> stage) {
if (installing == null) { if (settingUp == null) {
throw new IllegalStateException("Stage " + stage + " defined outside IrisModule.install"); throw new IllegalStateException("Stage " + stage + " defined outside IrisModule.setup");
} }
return installing; return settingUp;
} }
private static void requireOwnedStageId(Stage<?> stage, DiscoveredModule discovered) { private static void requireOwnedStageId(Stage<?> stage, DiscoveredModule discovered) {
@@ -1,12 +1,15 @@
package com.volmit.host; package com.volmit.host;
import com.volmit.IrisFeature; import com.volmit.IrisFeature;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.random.WorldRandom; import com.volmit.random.WorldRandom;
import com.volmit.stage.BlockStageContext; import com.volmit.stage.BlockStageContext;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.world.PackWorld; import com.volmit.world.PackWorld;
import java.util.Arrays; import java.util.Arrays;
import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.function.BooleanSupplier;
import java.util.stream.IntStream; import java.util.stream.IntStream;
/** Pipeline-independent state of one invocation: activation, settings, stage outputs and stage /** Pipeline-independent state of one invocation: activation, settings, stage outputs and stage
@@ -19,6 +22,7 @@ import java.util.stream.IntStream;
final class StageInvocation { final class StageInvocation {
private static final Object PENDING = new Object(); private static final Object PENDING = new Object();
private static final int NO_STAGE = -1; private static final int NO_STAGE = -1;
private static final BooleanSupplier NEVER_REJECTED = () -> false;
private final ResolvedGraph graph; private final ResolvedGraph graph;
private final Object[] settingsBySlot; private final Object[] settingsBySlot;
@@ -51,15 +55,23 @@ final class StageInvocation {
} }
void runInvocationStage(int position, Object context) { void runInvocationStage(int position, Object context) {
runInvocationStage(position, context, NEVER_REJECTED);
}
/** {@code rejected} tells, after the stage ran, whether it rejected the attempt; a rejecting stage may return null. */
void runInvocationStage(int position, Object context, BooleanSupplier rejected) {
if (!active[position]) { if (!active[position]) {
return; return;
} }
var executable = graph.executable(position); var executable = graph.executable(position);
var work = ((StageBody.Invocation) executable.body()).work(); var work = ((StageBody.Invocation) executable.body()).work();
current = position; current = position;
var output = work.run(context, settings(executable)); var output = work.run(context);
current = NO_STAGE; current = NO_STAGE;
complete(position, requireDeclaredOutput(executable, output)); if (output == null && executable.stage().producesOutput() && !rejected.getAsBoolean()) {
throw new NullPointerException("Stage " + executable.stage() + " produced a null output");
}
complete(position, output);
} }
Object newAccumulator(int position) { Object newAccumulator(int position) {
@@ -75,7 +87,7 @@ final class StageInvocation {
var executable = graph.executable(position); var executable = graph.executable(position);
var work = ((StageBody.Block) executable.body()).work(); var work = ((StageBody.Block) executable.body()).work();
current = position; current = position;
work.run(context, settings(executable), accumulator); work.run(context, accumulator);
current = NO_STAGE; current = NO_STAGE;
} }
@@ -128,16 +140,21 @@ final class StageInvocation {
return graph.executable(current); return graph.executable(current);
} }
private Object settings(ExecutableStage executable) { /** The entries that activated the running stage, which must be conditioned on {@code type}. */
int slot = executable.settingsSlot(); @SuppressWarnings("unchecked") // The slot holds the entries of the type the stage is conditioned on.
return slot == ExecutableStage.NO_SETTINGS ? null : settingsBySlot[slot]; <S extends IrisFeature> List<Entry<S>> configured(Class<S> type) {
} Objects.requireNonNull(type, "settingsType");
if (current == NO_STAGE) {
private static Object requireDeclaredOutput(ExecutableStage executable, Object output) { throw new IllegalStateException("Configured settings can only be read while a stage runs");
if (output == null && executable.stage().producesOutput()) {
throw new NullPointerException("Stage " + executable.stage() + " produced a null output");
} }
return output; var executable = graph.executable(current);
int slot = executable.settingsSlot();
if (slot == ExecutableStage.NO_SETTINGS || graph.settingsTypes().get(slot) != type) {
throw new IllegalStateException("Stage " + executable.stage() + " read configured(" + type.getSimpleName()
+ ") but is not conditioned on it; add when(" + type.getSimpleName() + ".class) to its definition,"
+ " or read other settings through settings()");
}
return (List<Entry<S>>) settingsBySlot[slot];
} }
@SuppressWarnings("unchecked") // Settings types come from when(Class<? extends IrisFeature>). @SuppressWarnings("unchecked") // Settings types come from when(Class<? extends IrisFeature>).
@@ -11,7 +11,7 @@ import java.util.Objects;
* @param blocks how far, in blocks along X and Z, the stage writes blocks or mantle values beyond its * @param blocks how far, in blocks along X and Z, the stage writes blocks or mantle values beyond its
* footprint: the chunk's 16 by 16 columns for a mantle stage, the X/Z bounds of the placed object * footprint: the chunk's 16 by 16 columns for a mantle stage, the X/Z bounds of the placed object
* for a placement stage. 0 means only inside it, and is all a chunk stage may declare. Height is not * for a placement stage. 0 means only inside it, and is all a chunk stage may declare. Height is not
* limited: the footprint is whole columns. A number declared at install, or for a mantle stage a * limited: the footprint is whole columns. A number declared during setup, or for a mantle stage a
* {@link PackReach} worked out from the pack's settings when the pack loads. * {@link PackReach} worked out from the pack's settings when the pack loads.
* @param mantleLayers the mantle layers the stage writes, each once, in declaration order * @param mantleLayers the mantle layers the stage writes, each once, in declaration order
*/ */
@@ -30,7 +30,7 @@ public record StageReach(PackReach blocks, List<MantleKey<?>> mantleLayers) {
} }
} }
/** A reach of a number of blocks declared at install. */ /** A reach of a number of blocks declared during setup. */
public StageReach(int blocks, List<MantleKey<?>> mantleLayers) { public StageReach(int blocks, List<MantleKey<?>> mantleLayers) {
this(new FixedReach(blocks), mantleLayers); this(new FixedReach(blocks), mantleLayers);
} }
@@ -1,7 +1,10 @@
package com.volmit.host; package com.volmit.host;
/** Where a runner reports how long each stage it ran took, such as the host's generation metrics. Called on the /** Where a runner reports how long each stage it ran took, such as the host's generation metrics. Every runner takes
* invocation's thread, once per stage that ran, in run order; a stage the invocation left inactive is not reported. * one ({@link PlacementRunner#place}, {@link ChunkRunner#generate}, {@link MantleRunner#generate}). Called on the
* invocation's thread, once per stage that ran, in run order; a block stage is reported once at the end of its pass
* with its time summed over the blocks it ran for. A stage the invocation left inactive, or one that threw, is not
* reported.
*/ */
@FunctionalInterface @FunctionalInterface
public interface StageTimings { public interface StageTimings {
@@ -1,29 +1,36 @@
package com.volmit.stage; package com.volmit.stage;
import com.volmit.mantle.MantleKey;
import com.volmit.IrisFeature; import com.volmit.IrisFeature;
import com.volmit.mantle.MantleKey;
import java.util.function.Supplier; import java.util.function.Supplier;
/** Declares one per-block placement stage. Requiring another block stage orders the two per /** Declares one per-block placement stage. Requiring another block stage orders the two per block within a fused
* block within a fused pass. A block stage's accumulator becomes readable only after its pass. * pass. A block stage's accumulator becomes readable only after its pass. Edges work as on
* {@link PlacementStageDefinition}.
*/ */
public interface BlockStageDefinition<O> { public interface BlockStageDefinition<O> {
BlockStageDefinition<O> requires(Stage<?>... stages); BlockStageDefinition<O> requires(Stage<?>... stages);
BlockStageDefinition<O> softAfter(Stage<?>... stages);
BlockStageDefinition<O> softAfter(StageRef... stages); BlockStageDefinition<O> softAfter(StageRef... stages);
BlockStageDefinition<O> softBefore(Stage<?>... stages);
BlockStageDefinition<O> softBefore(StageRef... stages); BlockStageDefinition<O> softBefore(StageRef... stages);
/** Declares how far, in blocks along X and Z, this stage writes blocks or mantle values beyond the /** Declares how far, in blocks along X and Z, this stage writes blocks or mantle values beyond the placed
* placed object's X/Z bounds. The host prepares that much around every placement. Leaving it out means 0. * object's X/Z bounds. The host prepares that much around every placement. Leaving it out means 0.
*/ */
BlockStageDefinition<O> reach(int blocks); BlockStageDefinition<O> reach(int blocks);
/** Declares the mantle layers this stage writes; each must be registered by some module. */ /** Declares the mantle layers this stage writes; each must be registered by some module. */
BlockStageDefinition<O> writesMantle(MantleKey<?>... layers); BlockStageDefinition<O> writesMantle(MantleKey<?>... layers);
<S extends IrisFeature> ConditionalBlockStageDefinition<S, O> when(Class<S> settingsType); /** Activates the stage only where the placement declares the given settings; the body reads them with
* {@link StageContext#configured}. See {@link StageGraph} for who may name a settings type.
*/
BlockStageDefinition<O> when(Class<? extends IrisFeature> settingsType);
/** Body for a block stage without accumulator. */ /** Body for a block stage without accumulator. */
void run(StageAction<BlockStageContext> action); void run(StageAction<BlockStageContext> action);
@@ -0,0 +1,31 @@
package com.volmit.stage;
import com.volmit.IrisFeature;
/** Declares one chunk stage. A chunk stage writes only its own chunk and reads the mantle, so it declares neither a
* reach nor mantle layers: work that writes the mantle or reaches beyond its chunk is a {@link MantleStage}. Edges
* work as on {@link PlacementStageDefinition}.
*/
public interface ChunkStageDefinition<O> {
ChunkStageDefinition<O> requires(Stage<?>... stages);
ChunkStageDefinition<O> softAfter(Stage<?>... stages);
ChunkStageDefinition<O> softAfter(StageRef... stages);
ChunkStageDefinition<O> softBefore(Stage<?>... stages);
ChunkStageDefinition<O> softBefore(StageRef... stages);
/** Activates the stage only where any column of the chunk configures the given settings; the body reads every
* distinct entry of those columns with {@link StageContext#configured}. See {@link StageGraph} for who may name a
* settings type.
*/
ChunkStageDefinition<O> when(Class<? extends IrisFeature> settingsType);
/** Body for a stage without output. */
void run(StageAction<ChunkStageContext> action);
/** Body for a stage with output; a null result fails the invocation. */
void produce(StageFunction<ChunkStageContext, O> function);
}
@@ -1,23 +0,0 @@
package com.volmit.stage;
import com.volmit.IrisFeature;
import com.volmit.mantle.MantleKey;
import java.util.function.Supplier;
/** A block stage active only where its settings are configured; bodies receive every configured entry. */
public interface ConditionalBlockStageDefinition<S extends IrisFeature, O> {
ConditionalBlockStageDefinition<S, O> requires(Stage<?>... stages);
ConditionalBlockStageDefinition<S, O> softAfter(StageRef... stages);
ConditionalBlockStageDefinition<S, O> softBefore(StageRef... stages);
ConditionalBlockStageDefinition<S, O> reach(int blocks);
ConditionalBlockStageDefinition<S, O> writesMantle(MantleKey<?>... layers);
void run(SettingsAction<BlockStageContext, S> action);
void accumulate(Supplier<O> initial, SettingsBlockCollector<S, O> collector);
}
@@ -1,23 +0,0 @@
package com.volmit.stage;
import com.volmit.IrisFeature;
import com.volmit.mantle.MantleKey;
/** An invocation stage active only where its settings are configured; bodies receive every configured entry. */
public interface ConditionalStageDefinition<C extends StageContext, S extends IrisFeature, O> {
ConditionalStageDefinition<C, S, O> requires(Stage<?>... stages);
ConditionalStageDefinition<C, S, O> softAfter(StageRef... stages);
ConditionalStageDefinition<C, S, O> softBefore(StageRef... stages);
ConditionalStageDefinition<C, S, O> reach(int blocks);
ConditionalStageDefinition<C, S, O> reach(PackReach reach);
ConditionalStageDefinition<C, S, O> writesMantle(MantleKey<?>... layers);
void run(SettingsAction<C, S> action);
void produce(SettingsFunction<C, S, O> function);
}
@@ -5,9 +5,9 @@ package com.volmit.stage;
* so a stage sees what earlier stages wrote into neighboring chunks. Mantle stages therefore have no * so a stage sees what earlier stages wrote into neighboring chunks. Mantle stages therefore have no
* output; they pass data on through mantle layers. * output; they pass data on through mantle layers.
*/ */
public final class MantleStage<O> extends Stage<O> { public final class MantleStage extends Stage<Void> {
MantleStage(String id, Class<O> outputType) { MantleStage(String id) {
super(id, outputType); super(id, Void.class);
} }
@Override @Override
@@ -0,0 +1,40 @@
package com.volmit.stage;
import com.volmit.IrisFeature;
import com.volmit.mantle.MantleKey;
/** Declares one mantle stage. Mantle stages have no output: each runs as its own pass and passes data on through
* mantle layers. Edges work as on {@link PlacementStageDefinition}.
*/
public interface MantleStageDefinition {
MantleStageDefinition requires(Stage<?>... stages);
MantleStageDefinition softAfter(Stage<?>... stages);
MantleStageDefinition softAfter(StageRef... stages);
MantleStageDefinition softBefore(Stage<?>... stages);
MantleStageDefinition softBefore(StageRef... stages);
/** Declares how far, in blocks along X and Z, this stage writes mantle values beyond its chunk. The host prepares
* that much around every chunk the stage runs for. Leaving it out means 0.
*/
MantleStageDefinition reach(int blocks);
/** Declares a reach the host works out from the pack's settings when the pack loads, for a stage whose reach
* depends on the pack, such as the largest object any level configures.
*/
MantleStageDefinition reach(PackReach reach);
/** Declares the mantle layers this stage writes; each must be registered by some module. */
MantleStageDefinition writesMantle(MantleKey<?>... layers);
/** Activates the stage only where any column of the chunk configures the given settings; the body reads every
* distinct entry of those columns with {@link StageContext#configured}. See {@link StageGraph} for who may name a
* settings type.
*/
MantleStageDefinition when(Class<? extends IrisFeature> settingsType);
void run(StageAction<MantleStageContext> action);
}
@@ -0,0 +1,40 @@
package com.volmit.stage;
import com.volmit.IrisFeature;
import com.volmit.mantle.MantleKey;
/** Declares one placement stage, run once per placement attempt. {@code requires(...)} is a hard dependency on
* another module's stage constant: it orders this stage after it, allows reading its output, and deactivates this
* stage wherever the requirement is inactive. Soft edges only order, and only when the referenced stage is installed
* in the same pipeline. There is deliberately no hard "before".
*/
public interface PlacementStageDefinition<O> {
PlacementStageDefinition<O> requires(Stage<?>... stages);
PlacementStageDefinition<O> softAfter(Stage<?>... stages);
PlacementStageDefinition<O> softAfter(StageRef... stages);
PlacementStageDefinition<O> softBefore(Stage<?>... stages);
PlacementStageDefinition<O> softBefore(StageRef... stages);
/** Declares how far, in blocks along X and Z, this stage writes blocks or mantle values beyond the placed
* object's X/Z bounds. The host prepares that much around every placement. Leaving it out means 0.
*/
PlacementStageDefinition<O> reach(int blocks);
/** Declares the mantle layers this stage writes; each must be registered by some module. */
PlacementStageDefinition<O> writesMantle(MantleKey<?>... layers);
/** Activates the stage only where the placement declares the given settings; the body reads them with
* {@link StageContext#configured}. See {@link StageGraph} for who may name a settings type.
*/
PlacementStageDefinition<O> when(Class<? extends IrisFeature> settingsType);
/** Body for a stage without output. */
void run(StageAction<PlacementStageContext> action);
/** Body for a stage with output. A null result fails the attempt, unless the stage rejected it. */
void produce(StageFunction<PlacementStageContext, O> function);
}
@@ -1,13 +0,0 @@
package com.volmit.stage;
import com.volmit.IrisFeature;
import com.volmit.config.FeatureSettings.Entry;
import java.util.List;
/** Body of a conditional stage without output. {@code settings} holds every entry configured for the
* invocation, in level order, and is never empty.
*/
@FunctionalInterface
public interface SettingsAction<C, S extends IrisFeature> {
void run(C context, List<Entry<S>> settings);
}
@@ -1,13 +0,0 @@
package com.volmit.stage;
import com.volmit.IrisFeature;
import com.volmit.config.FeatureSettings.Entry;
import java.util.List;
/** Body of a conditional accumulating block stage. {@code settings} holds every entry configured for
* the placement, in level order, and is never empty.
*/
@FunctionalInterface
public interface SettingsBlockCollector<S extends IrisFeature, O> {
void collect(BlockStageContext context, List<Entry<S>> settings, O accumulator);
}
@@ -1,13 +0,0 @@
package com.volmit.stage;
import com.volmit.IrisFeature;
import com.volmit.config.FeatureSettings.Entry;
import java.util.List;
/** Body of a conditional stage with output. {@code settings} holds every entry configured for the
* invocation, in level order, and is never empty.
*/
@FunctionalInterface
public interface SettingsFunction<C, S extends IrisFeature, O> {
O run(C context, List<Entry<S>> settings);
}
+2 -2
View File
@@ -47,8 +47,8 @@ public abstract sealed class Stage<O> permits PlacementStage, BlockStage, ChunkS
} }
/** Mantle stages have no output: each runs as its own pass, so they pass data on through mantle layers. */ /** Mantle stages have no output: each runs as its own pass, so they pass data on through mantle layers. */
public static MantleStage<Void> mantle(String id) { public static MantleStage mantle(String id) {
return new MantleStage<>(id, Void.class); return new MantleStage(id);
} }
public final ResourceId id() { public final ResourceId id() {
@@ -1,6 +1,9 @@
package com.volmit.stage; package com.volmit.stage;
import com.volmit.IrisFeature;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.random.WorldRandom; import com.volmit.random.WorldRandom;
import java.util.List;
/** Per-invocation view handed to one stage body. Do not retain it after the body returns. */ /** Per-invocation view handed to one stage body. Do not retain it after the body returns. */
public interface StageContext { public interface StageContext {
@@ -16,4 +19,11 @@ public interface StageContext {
* reading a block stage's accumulator before its block pass has finished. * reading a block stage's accumulator before its block pass has finished.
*/ */
<O> O output(Stage<O> stage); <O> O output(Stage<O> stage);
/** The entries of the settings this stage is conditioned on with {@code when(settingsType)}, in level order: the
* ones that activated it in this invocation, so never empty. A placement has its own declarations; a chunk or
* mantle invocation has every distinct entry of the chunk's columns. Any other type, or a stage without a
* condition, throws IllegalStateException; read other settings through the context's {@code settings()}.
*/
<S extends IrisFeature> List<Entry<S>> configured(Class<S> settingsType);
} }
@@ -1,50 +0,0 @@
package com.volmit.stage;
import com.volmit.mantle.MantleKey;
import com.volmit.IrisFeature;
/** Declares one invocation stage. requires(...) is a hard dependency on another module's
* stage constant: it orders this stage after it, allows reading its output, and deactivates
* this stage wherever the requirement is inactive. Soft edges only order, and only when the
* referenced stage is installed in the same pipeline. There is deliberately no hard "before".
*/
public interface StageDefinition<C extends StageContext, O> {
StageDefinition<C, O> requires(Stage<?>... stages);
StageDefinition<C, O> softAfter(StageRef... stages);
StageDefinition<C, O> softBefore(StageRef... stages);
/** Declares how far, in blocks along X and Z, this stage writes blocks or mantle values beyond its
* footprint: the chunk for a mantle stage, the placed object's X/Z bounds for a placement stage. The
* host prepares that much around every chunk the stage runs for, or every placement. Leaving it out means 0.
* Chunk stages write only their own chunk, so a reach above 0 on one fails the install.
*/
StageDefinition<C, O> reach(int blocks);
/** Declares a reach the host works out from the pack's settings when the pack loads, for a mantle
* stage whose reach depends on the pack. Only mantle stages may declare one: placement areas and
* chunks are sized without the pack's settings, so it fails the install on any other stage.
*/
StageDefinition<C, O> reach(PackReach reach);
/** Declares the mantle layers this stage writes; each must be registered by some module. Chunk stages
* only read the mantle, so declaring layers on one fails the install.
*/
StageDefinition<C, O> writesMantle(MantleKey<?>... layers);
/** Activates the stage only where the given feature settings are configured: in a placement where the
* placement declares them, in a chunk or mantle invocation where any column of the chunk has an entry.
* The body receives every configured entry, in level order. At least one module naming the type must
* own its feature id: the id is that module's id or starts with it and '/'. Other modules may name it
* too, such as moss conditioning on {@code iris:snow}.
*/
<S extends IrisFeature> ConditionalStageDefinition<C, S, O> when(Class<S> settingsType);
/** Body for a stage without output. */
void run(StageAction<C> action);
/** Body for a stage with output; null results fail the invocation. */
void produce(StageFunction<C, O> function);
}
+15 -8
View File
@@ -1,17 +1,24 @@
package com.volmit.stage; package com.volmit.stage;
/** Collects the stages a module defines during {@code IrisModule.install}. Each define call must /** Collects the stages a module defines during {@code IrisModule.setup}. Each define call must end with exactly one
* end with exactly one body (run, produce or accumulate). The graph is resolved once at pack load: * body (run, produce or accumulate). Each pipeline has its own definition type, so what a pipeline does not allow,
* missing requirements, cycles, duplicate definitions, stage ids outside the module's id and * such as a chunk stage writing the mantle, does not compile. The graph is resolved once at pack load: missing
* cross-pipeline edges are load errors. Bodies are shared by concurrent invocations and must not capture * requirements, cycles, duplicate definitions, stage ids outside the module's id and cross-pipeline edges are load
* invocation state; everything per-invocation arrives through the context and outputs. * errors. Bodies are shared by concurrent invocations and must not capture invocation state; everything
* per-invocation arrives through the context and outputs.
*
* <p>{@code when(settingsType)} activates a stage only where the settings are configured, and the body reads them
* with {@link StageContext#configured}. A stage has at most one condition. At least one module naming the type must
* own its feature id: the id is that module's id or starts with it and '/'. Other modules may name it too, such as
* moss conditioning on {@code iris:snow}, and any module may name a type its owner registered with
* {@code FeatureRegistry.registerSettings}.
*/ */
public interface StageGraph { public interface StageGraph {
<O> StageDefinition<PlacementStageContext, O> define(PlacementStage<O> stage); <O> PlacementStageDefinition<O> define(PlacementStage<O> stage);
<O> BlockStageDefinition<O> define(BlockStage<O> stage); <O> BlockStageDefinition<O> define(BlockStage<O> stage);
<O> StageDefinition<ChunkStageContext, O> define(ChunkStage<O> stage); <O> ChunkStageDefinition<O> define(ChunkStage<O> stage);
<O> StageDefinition<MantleStageContext, O> define(MantleStage<O> stage); MantleStageDefinition define(MantleStage stage);
} }
@@ -4,6 +4,7 @@ import com.volmit.FeatureAttachment.Target;
import com.volmit.IrisFeature; import com.volmit.IrisFeature;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.ModuleInfo; import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
import com.volmit.block.BlockState; import com.volmit.block.BlockState;
import com.volmit.config.Feature; import com.volmit.config.Feature;
import com.volmit.config.FeatureSettings.Entry; import com.volmit.config.FeatureSettings.Entry;
@@ -17,17 +18,17 @@ import com.volmit.host.ChunkRunner;
import com.volmit.host.DiscoveredModule; import com.volmit.host.DiscoveredModule;
import com.volmit.host.LoadedModules; import com.volmit.host.LoadedModules;
import com.volmit.host.MantleRunner; import com.volmit.host.MantleRunner;
import com.volmit.host.StageGraphBuilder; import com.volmit.host.StageTimings;
import com.volmit.hunk.Hunk; import com.volmit.hunk.Hunk;
import com.volmit.mantle.BlockBox; import com.volmit.mantle.BlockBox;
import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceId;
import com.volmit.stage.Pipeline; import com.volmit.stage.Pipeline;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
import com.volmit.support.ColumnSettings; import com.volmit.support.ColumnSettings;
import com.volmit.support.DeclaredSettings; import com.volmit.support.DeclaredSettings;
import com.volmit.support.MemoryMantle; import com.volmit.support.MemoryMantle;
import com.volmit.support.TestContexts; import com.volmit.support.TestContexts;
import com.volmit.support.TestSetups;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -52,10 +53,7 @@ class ChunkPipelineTest {
static final class Marker implements IrisFeature {} static final class Marker implements IrisFeature {}
private static ChunkRunner runner() { private static ChunkRunner runner() {
var builder = new StageGraphBuilder(); var graph = TestSetups.stages(new GrassModule(), new TerrainModule()).resolve(Pipeline.CHUNK);
builder.install(DiscoveredModule.builtIn(new GrassModule()));
builder.install(DiscoveredModule.builtIn(new TerrainModule()));
var graph = builder.resolve(Pipeline.CHUNK);
assertEquals(List.of("iris:terrain/surface", "example:grass/top"), assertEquals(List.of("iris:terrain/surface", "example:grass/top"),
graph.stages().stream().map(stage -> stage.stage().id().toString()).toList()); graph.stages().stream().map(stage -> stage.stage().id().toString()).toList());
assertTrue(graph.blockPasses().isEmpty()); assertTrue(graph.blockPasses().isEmpty());
@@ -64,7 +62,7 @@ class ChunkPipelineTest {
private static Hunk<BlockState> generate(ColumnSettings settings) { private static Hunk<BlockState> generate(ColumnSettings settings) {
var blocks = new ArrayHunk<>(BlockState.class, SIZE, HEIGHT, SIZE, AIR); var blocks = new ArrayHunk<>(BlockState.class, SIZE, HEIGHT, SIZE, AIR);
runner().generate(TestContexts.generation(Map.of(BlockState.class, blocks), settings, null), TestContexts.SEED); runner().generate(TestContexts.generation(Map.of(BlockState.class, blocks), settings, null), TestContexts.SEED, StageTimings.NONE);
return blocks; return blocks;
} }
@@ -116,18 +114,17 @@ class ChunkPipelineTest {
var stage = Stage.chunk("test:levels/read"); var stage = Stage.chunk("test:levels/read");
IrisModule module = new IrisModule() { IrisModule module = new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of("test:levels", "Levels", "1"); } public ModuleInfo info() { return ModuleInfo.of("test:levels", "Levels", "1"); }
public void install(StageGraph graph) { public void setup(ModuleSetup setup) {
graph.define(stage).when(Marker.class).run((context, entries) -> { setup.stages().define(stage).when(Marker.class).run(context -> {
received.add(entries.stream().map(Entry::source).toList()); received.add(context.configured(Marker.class).stream().map(Entry::source).toList());
received.add(context.settings().at(Marker.class, 0, 0).stream().map(Entry::source).toList()); received.add(context.settings().at(Marker.class, 0, 0).stream().map(Entry::source).toList());
}); });
} }
}; };
var builder = new StageGraphBuilder();
builder.install(DiscoveredModule.builtIn(module));
var settings = new ColumnSettings((x, z) -> List.of(dimension, x < 8 ? swamp : plains)); var settings = new ColumnSettings((x, z) -> List.of(dimension, x < 8 ? swamp : plains));
new ChunkRunner(builder.resolve(Pipeline.CHUNK)).generate(TestContexts.generation(Map.of(), settings, null), TestContexts.SEED); new ChunkRunner(TestSetups.stages(module).resolve(Pipeline.CHUNK))
.generate(TestContexts.generation(Map.of(), settings, null), TestContexts.SEED, StageTimings.NONE);
assertEquals(List.of(List.of(DIMENSION, SWAMP, PLAINS), List.of(DIMENSION, SWAMP)), received, assertEquals(List.of(List.of(DIMENSION, SWAMP, PLAINS), List.of(DIMENSION, SWAMP)), received,
"the body sees every level of every column, a column read that column's levels"); "the body sees every level of every column, a column read that column's levels");
@@ -143,13 +140,14 @@ class ChunkPipelineTest {
var reachArea = new BlockBox(-reach, BOTTOM, -reach, CHUNK + reach, TOP, CHUNK + reach); var reachArea = new BlockBox(-reach, BOTTOM, -reach, CHUNK + reach, TOP, CHUNK + reach);
new MantleRunner(loaded.mantle()).generate(VeinModule.PLAN, new MantleRunner(loaded.mantle()).generate(VeinModule.PLAN,
TestContexts.mantle(0, 0, ColumnSettings.everywhere(vein), mantle.within(reachArea)), TestContexts.SEED); TestContexts.mantle(0, 0, ColumnSettings.everywhere(vein), mantle.within(reachArea)), TestContexts.SEED, StageTimings.NONE);
assertEquals(1, mantle.get(VeinModule.ORE, 18, 4, 7), "the vein runs on into the next chunk"); assertEquals(1, mantle.get(VeinModule.ORE, 18, 4, 7), "the vein runs on into the next chunk");
var blocks = new ArrayHunk<>(BlockState.class, CHUNK, HEIGHT, CHUNK, AIR); var blocks = new ArrayHunk<>(BlockState.class, CHUNK, HEIGHT, CHUNK, AIR);
var chunkArea = new BlockBox(0, BOTTOM, 0, CHUNK, TOP, CHUNK); var chunkArea = new BlockBox(0, BOTTOM, 0, CHUNK, TOP, CHUNK);
new ChunkRunner(loaded.chunk()).generate( new ChunkRunner(loaded.chunk()).generate(
TestContexts.generation(Map.of(BlockState.class, blocks), ColumnSettings.NONE, mantle.within(chunkArea)), TestContexts.SEED); TestContexts.generation(Map.of(BlockState.class, blocks), ColumnSettings.NONE, mantle.within(chunkArea)), TestContexts.SEED,
StageTimings.NONE);
assertEquals(VeinModule.ORE_BLOCK, blocks.get(7, 4, 7)); assertEquals(VeinModule.ORE_BLOCK, blocks.get(7, 4, 7));
assertEquals(VeinModule.ORE_BLOCK, blocks.get(15, 4, 7)); assertEquals(VeinModule.ORE_BLOCK, blocks.get(15, 4, 7));
assertEquals(AIR, blocks.get(6, 4, 7)); assertEquals(AIR, blocks.get(6, 4, 7));
@@ -165,19 +163,18 @@ class ChunkPipelineTest {
var copy = Stage.chunk("test:copy/insert"); var copy = Stage.chunk("test:copy/insert");
IrisModule module = new IrisModule() { IrisModule module = new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of("test:copy", "Copy", "1"); } public ModuleInfo info() { return ModuleInfo.of("test:copy", "Copy", "1"); }
public void install(StageGraph graph) { public void setup(ModuleSetup setup) {
graph.define(copy).run(context -> { setup.stages().define(copy).run(context -> {
var blocks = context.hunk(BlockState.class); var blocks = context.hunk(BlockState.class);
context.mantle().blocks().visit(chunkArea, (x, y, z, block) -> blocks.set(x, y, z, block)); context.mantle().blocks().visit(chunkArea, (x, y, z, block) -> blocks.set(x, y, z, block));
}); });
} }
}; };
var builder = new StageGraphBuilder();
builder.install(DiscoveredModule.builtIn(module));
var blocks = new ArrayHunk<>(BlockState.class, CHUNK, HEIGHT, CHUNK, GRASS); var blocks = new ArrayHunk<>(BlockState.class, CHUNK, HEIGHT, CHUNK, GRASS);
new ChunkRunner(builder.resolve(Pipeline.CHUNK)).generate( new ChunkRunner(TestSetups.stages(module).resolve(Pipeline.CHUNK)).generate(
TestContexts.generation(Map.of(BlockState.class, blocks), ColumnSettings.NONE, mantle.within(chunkArea)), TestContexts.SEED); TestContexts.generation(Map.of(BlockState.class, blocks), ColumnSettings.NONE, mantle.within(chunkArea)), TestContexts.SEED,
StageTimings.NONE);
assertEquals(stone, blocks.get(3, 2, 5)); assertEquals(stone, blocks.get(3, 2, 5));
assertEquals(AIR, blocks.get(4, 2, 5), "air a placement planned replaces what the chunk had"); assertEquals(AIR, blocks.get(4, 2, 5), "air a placement planned replaces what the chunk had");
@@ -194,20 +191,19 @@ class ChunkPipelineTest {
var probe = Stage.chunk("test:caves/probe"); var probe = Stage.chunk("test:caves/probe");
IrisModule module = new IrisModule() { IrisModule module = new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of("test:caves", "Caves", "1"); } public ModuleInfo info() { return ModuleInfo.of("test:caves", "Caves", "1"); }
public void install(StageGraph graph) { public void setup(ModuleSetup setup) {
graph.define(probe).run(context -> { setup.stages().define(probe).run(context -> {
var caverns = context.mantle().caverns(); var caverns = context.mantle().caverns();
carved.add(String.valueOf(caverns.get(6, 9, 2))); carved.add(String.valueOf(caverns.get(6, 9, 2)));
carved.add(String.valueOf(caverns.get(6, 10, 2))); carved.add(String.valueOf(caverns.get(6, 10, 2)));
}); });
} }
}; };
var builder = new StageGraphBuilder();
builder.install(DiscoveredModule.builtIn(module));
var blocks = new ArrayHunk<>(BlockState.class, CHUNK, HEIGHT, CHUNK, AIR); var blocks = new ArrayHunk<>(BlockState.class, CHUNK, HEIGHT, CHUNK, AIR);
new ChunkRunner(builder.resolve(Pipeline.CHUNK)).generate( new ChunkRunner(TestSetups.stages(module).resolve(Pipeline.CHUNK)).generate(
TestContexts.generation(Map.of(BlockState.class, blocks), ColumnSettings.NONE, mantle.within(chunkArea)), TestContexts.SEED); TestContexts.generation(Map.of(BlockState.class, blocks), ColumnSettings.NONE, mantle.within(chunkArea)), TestContexts.SEED,
StageTimings.NONE);
assertEquals(List.of("true", "null"), carved); assertEquals(List.of("true", "null"), carved);
assertThrows(UnsupportedOperationException.class, () -> mantle.within(chunkArea).caverns().set(0, 0, 0, true)); assertThrows(UnsupportedOperationException.class, () -> mantle.within(chunkArea).caverns().set(0, 0, 0, true));
@@ -230,16 +226,15 @@ class ChunkPipelineTest {
var mantle = new MemoryMantle(); var mantle = new MemoryMantle();
IrisModule module = new IrisModule() { IrisModule module = new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of("test:writer", "Writer", "1"); } public ModuleInfo info() { return ModuleInfo.of("test:writer", "Writer", "1"); }
public void install(StageGraph graph) { public void setup(ModuleSetup setup) {
graph.define(stage).run(context -> context.mantle().layer(VeinModule.ORE).set(0, 0, 0, 1)); setup.stages().define(stage).run(context -> context.mantle().layer(VeinModule.ORE).set(0, 0, 0, 1));
} }
}; };
var builder = new StageGraphBuilder(); var graph = TestSetups.stages(module).resolve(Pipeline.CHUNK);
builder.install(DiscoveredModule.builtIn(module));
var inputs = TestContexts.generation(Map.of(), ColumnSettings.NONE, mantle.within(new BlockBox(0, BOTTOM, 0, CHUNK, TOP, CHUNK))); var inputs = TestContexts.generation(Map.of(), ColumnSettings.NONE, mantle.within(new BlockBox(0, BOTTOM, 0, CHUNK, TOP, CHUNK)));
var failure = assertThrows(UnsupportedOperationException.class, var failure = assertThrows(UnsupportedOperationException.class,
() -> new ChunkRunner(builder.resolve(Pipeline.CHUNK)).generate(inputs, TestContexts.SEED)); () -> new ChunkRunner(graph).generate(inputs, TestContexts.SEED, StageTimings.NONE));
assertEquals("Chunk stages read the mantle but do not write it; write it from a mantle stage (Stage.mantle)," assertEquals("Chunk stages read the mantle but do not write it; write it from a mantle stage (Stage.mantle),"
+ " which runs before the chunks it reaches", failure.getMessage()); + " which runs before the chunks it reaches", failure.getMessage());
assertNull(mantle.get(VeinModule.ORE, 0, 0, 0)); assertNull(mantle.get(VeinModule.ORE, 0, 0, 0));
@@ -2,15 +2,15 @@ package com.volmit.example;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.ModuleInfo; import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
import com.volmit.block.BlockState; import com.volmit.block.BlockState;
import com.volmit.example.placement.*; import com.volmit.example.placement.*;
import com.volmit.host.ConfiguredSettings; import com.volmit.host.ConfiguredSettings;
import com.volmit.host.DiscoveredModule;
import com.volmit.host.LoadedModules; import com.volmit.host.LoadedModules;
import com.volmit.host.PlacementRunner; import com.volmit.host.PlacementRunner;
import com.volmit.host.ResolvedGraph; import com.volmit.host.ResolvedGraph;
import com.volmit.host.StageGraphBuilder;
import com.volmit.host.StageStreams; import com.volmit.host.StageStreams;
import com.volmit.host.StageTimings;
import com.volmit.mantle.BlockBox; import com.volmit.mantle.BlockBox;
import com.volmit.object.GeneratedObject; import com.volmit.object.GeneratedObject;
import com.volmit.object.ObjectBlock; import com.volmit.object.ObjectBlock;
@@ -20,9 +20,9 @@ import com.volmit.resource.ResourceId;
import com.volmit.stage.Pipeline; import com.volmit.stage.Pipeline;
import com.volmit.stage.PlacementStage; import com.volmit.stage.PlacementStage;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
import com.volmit.support.MemoryEdit; import com.volmit.support.MemoryEdit;
import com.volmit.support.TestContexts; import com.volmit.support.TestContexts;
import com.volmit.support.TestSetups;
import com.volmit.support.TestTerrain; import com.volmit.support.TestTerrain;
import com.volmit.world.BlockPosition; import com.volmit.world.BlockPosition;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@@ -86,9 +86,7 @@ class PlacementLifecyclePortTest {
"""; """;
private static ResolvedGraph resolve(List<? extends IrisModule> modules) { private static ResolvedGraph resolve(List<? extends IrisModule> modules) {
var builder = new StageGraphBuilder(); return TestSetups.stages(modules.toArray(IrisModule[]::new)).resolve(Pipeline.PLACEMENT);
modules.stream().map(DiscoveredModule::builtIn).forEach(builder::install);
return builder.resolve(Pipeline.PLACEMENT);
} }
private static List<String> order(ResolvedGraph graph) { private static List<String> order(ResolvedGraph graph) {
@@ -112,7 +110,8 @@ class PlacementLifecyclePortTest {
private static MemoryEdit place(ResolvedGraph graph, ConfiguredSettings settings) { private static MemoryEdit place(ResolvedGraph graph, ConfiguredSettings settings) {
var terrain = terrain(); var terrain = terrain();
var edit = new MemoryEdit(terrain); var edit = new MemoryEdit(terrain);
var outcome = new PlacementRunner(graph).place(request(), edit, TestContexts.placement(terrain), TestContexts.SEED, settings); var outcome = new PlacementRunner(graph).place(request(), edit, TestContexts.placement(terrain), TestContexts.SEED, settings,
StageTimings.NONE);
assertTrue(outcome.isPlaced()); assertTrue(outcome.isPlaced());
return edit; return edit;
} }
@@ -183,8 +182,8 @@ class PlacementLifecyclePortTest {
var capModule = new IrisModule() { var capModule = new IrisModule() {
static final PlacementStage<Void> CAP = Stage.placement("example:cap/top"); static final PlacementStage<Void> CAP = Stage.placement("example:cap/top");
public ModuleInfo info() { return ModuleInfo.of("example:cap", "Cap", "1"); } public ModuleInfo info() { return ModuleInfo.of("example:cap", "Cap", "1"); }
public void install(StageGraph graph) { public void setup(ModuleSetup setup) {
graph.define(CAP).requires(StiltModule.FILL).run(context -> context.access().set( setup.stages().define(CAP).requires(StiltModule.FILL).run(context -> context.access().set(
new PlacedBlock(new BlockPosition(5, 20, 5), PLANKS, Optional.empty()))); new PlacedBlock(new BlockPosition(5, 20, 5), PLANKS, Optional.empty())));
} }
}; };
@@ -2,13 +2,11 @@ package com.volmit.example.chunk;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.ModuleInfo; import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
import com.volmit.block.BlockState; import com.volmit.block.BlockState;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.stage.ChunkStage; import com.volmit.stage.ChunkStage;
import com.volmit.stage.ChunkStageContext; import com.volmit.stage.ChunkStageContext;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
import java.util.List;
/** Third-party decoration: tops terrain columns using the terrain module's typed output. It runs where any /** Third-party decoration: tops terrain columns using the terrain module's typed output. It runs where any
* column of the chunk has grass and reads the settings per column, so a biome border inside the chunk * column of the chunk has grass and reads the settings per column, so a biome border inside the chunk
@@ -23,14 +21,14 @@ public final class GrassModule implements IrisModule {
} }
@Override @Override
public void install(StageGraph graph) { public void setup(ModuleSetup setup) {
graph.define(TOP) setup.stages().define(TOP)
.when(GrassSettings.class) .when(GrassSettings.class)
.requires(TerrainModule.SURFACE) .requires(TerrainModule.SURFACE)
.run(GrassModule::cover); .run(GrassModule::cover);
} }
private static void cover(ChunkStageContext context, List<Entry<GrassSettings>> inChunk) { private static void cover(ChunkStageContext context) {
var heights = context.output(TerrainModule.SURFACE); var heights = context.output(TerrainModule.SURFACE);
var blocks = context.hunk(BlockState.class); var blocks = context.hunk(BlockState.class);
for (int x = 0; x < blocks.getWidth(); x++) { for (int x = 0; x < blocks.getWidth(); x++) {
@@ -2,11 +2,11 @@ package com.volmit.example.chunk;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.ModuleInfo; import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
import com.volmit.block.BlockState; import com.volmit.block.BlockState;
import com.volmit.stage.ChunkStage; import com.volmit.stage.ChunkStage;
import com.volmit.stage.ChunkStageContext; import com.volmit.stage.ChunkStageContext;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
/** Core terrain shaping as an ordinary module: fills stone and reports surface heights. */ /** Core terrain shaping as an ordinary module: fills stone and reports surface heights. */
public final class TerrainModule implements IrisModule { public final class TerrainModule implements IrisModule {
@@ -21,8 +21,8 @@ public final class TerrainModule implements IrisModule {
} }
@Override @Override
public void install(StageGraph graph) { public void setup(ModuleSetup setup) {
graph.define(SURFACE).produce(TerrainModule::shape); setup.stages().define(SURFACE).produce(TerrainModule::shape);
} }
public static int surfaceHeight(int worldX, int worldZ) { public static int surfaceHeight(int worldX, int worldZ) {
@@ -1,10 +1,9 @@
package com.volmit.example.chunk; package com.volmit.example.chunk;
import com.volmit.FeatureRegistry;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.ModuleInfo; import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
import com.volmit.block.BlockState; import com.volmit.block.BlockState;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.config.PackSettings; import com.volmit.config.PackSettings;
import com.volmit.mantle.BlockBox; import com.volmit.mantle.BlockBox;
import com.volmit.mantle.MantleCodec; import com.volmit.mantle.MantleCodec;
@@ -15,11 +14,9 @@ import com.volmit.stage.ChunkStageContext;
import com.volmit.stage.MantleStage; import com.volmit.stage.MantleStage;
import com.volmit.stage.MantleStageContext; import com.volmit.stage.MantleStageContext;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
import java.io.DataInput; import java.io.DataInput;
import java.io.DataOutput; import java.io.DataOutput;
import java.io.IOException; import java.io.IOException;
import java.util.List;
/** Work across chunks: a mantle stage plans veins into the mantle, past its own chunk, and a chunk stage /** Work across chunks: a mantle stage plans veins into the mantle, past its own chunk, and a chunk stage
* later turns its own chunk's part of the mantle into blocks. The two pipelines meet only in the mantle. * later turns its own chunk's part of the mantle into blocks. The two pipelines meet only in the mantle.
@@ -28,7 +25,7 @@ import java.util.List;
*/ */
public final class VeinModule implements IrisModule { public final class VeinModule implements IrisModule {
public static final MantleKey<Integer> ORE = new MantleKey<>("example:veins/ore", Integer.class); public static final MantleKey<Integer> ORE = new MantleKey<>("example:veins/ore", Integer.class);
public static final MantleStage<Void> PLAN = Stage.mantle("example:veins/plan"); public static final MantleStage PLAN = Stage.mantle("example:veins/plan");
public static final ChunkStage<Void> PLACE = Stage.chunk("example:veins/place"); public static final ChunkStage<Void> PLACE = Stage.chunk("example:veins/place");
public static final BlockState ORE_BLOCK = new BlockState("minecraft:iron_ore"); public static final BlockState ORE_BLOCK = new BlockState("minecraft:iron_ore");
private static final int CHUNK_WIDTH = 16; private static final int CHUNK_WIDTH = 16;
@@ -41,14 +38,10 @@ public final class VeinModule implements IrisModule {
} }
@Override @Override
public void install(StageGraph graph) { public void setup(ModuleSetup setup) {
graph.define(PLAN).when(VeinSettings.class).reach(VeinModule::reach).writesMantle(ORE).run(VeinModule::plan); setup.registry().registerMantle(ORE, MantleLifetime.GENERATION, new IntegerCodec());
graph.define(PLACE).run(VeinModule::place); setup.stages().define(PLAN).when(VeinSettings.class).reach(VeinModule::reach).writesMantle(ORE).run(VeinModule::plan);
} setup.stages().define(PLACE).run(VeinModule::place);
@Override
public void register(FeatureRegistry registry) {
registry.registerMantle(ORE, MantleLifetime.GENERATION, new IntegerCodec());
} }
/** How far the longest vein any level of the pack declares runs past its chunk. */ /** How far the longest vein any level of the pack declares runs past its chunk. */
@@ -58,7 +51,7 @@ public final class VeinModule implements IrisModule {
} }
/** One vein per level that configures veins at the chunk's centre column: levels stack. */ /** One vein per level that configures veins at the chunk's centre column: levels stack. */
private static void plan(MantleStageContext context, List<Entry<VeinSettings>> inChunk) { private static void plan(MantleStageContext context) {
int startX = context.originX() + CHUNK_CENTRE; int startX = context.originX() + CHUNK_CENTRE;
int z = context.originZ() + CHUNK_CENTRE; int z = context.originZ() + CHUNK_CENTRE;
var ore = context.mantle().layer(ORE); var ore = context.mantle().layer(ORE);
@@ -1,9 +1,8 @@
package com.volmit.example.held; package com.volmit.example.held;
import com.volmit.FeatureRegistry;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.ModuleInfo; import com.volmit.ModuleInfo;
import com.volmit.stage.StageGraph; import com.volmit.ModuleSetup;
/** A built-in module whose settings class is held by a class of the host, not by a feature. */ /** A built-in module whose settings class is held by a class of the host, not by a feature. */
public final class HeldModule implements IrisModule { public final class HeldModule implements IrisModule {
@@ -13,11 +12,8 @@ public final class HeldModule implements IrisModule {
} }
@Override @Override
public void install(StageGraph graph) {} public void setup(ModuleSetup setup) {
setup.registry().registerHeldType(ClampSettings.class);
@Override setup.registry().registerHeldType(ClampSettings.class);
public void register(FeatureRegistry registry) {
registry.registerHeldType(ClampSettings.class);
registry.registerHeldType(ClampSettings.class);
} }
} }
@@ -2,10 +2,10 @@ package com.volmit.example.placement;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.ModuleInfo; import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
import com.volmit.stage.PlacementStage; import com.volmit.stage.PlacementStage;
import com.volmit.stage.PlacementStageContext; import com.volmit.stage.PlacementStageContext;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
import com.volmit.world.BlockPosition; import com.volmit.world.BlockPosition;
import com.volmit.world.BlockView; import com.volmit.world.BlockView;
@@ -19,8 +19,8 @@ public final class AnchorModule implements IrisModule {
} }
@Override @Override
public void install(StageGraph graph) { public void setup(ModuleSetup setup) {
graph.define(HEIGHT) setup.stages().define(HEIGHT)
.requires(PrepareModule.TRANSFORMS) .requires(PrepareModule.TRANSFORMS)
.produce(AnchorModule::restOnSurface); .produce(AnchorModule::restOnSurface);
} }
@@ -2,12 +2,12 @@ package com.volmit.example.placement;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.ModuleInfo; import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
import com.volmit.placement.PlacedBlock; import com.volmit.placement.PlacedBlock;
import com.volmit.stage.BlockStage; import com.volmit.stage.BlockStage;
import com.volmit.stage.BlockStageContext; import com.volmit.stage.BlockStageContext;
import com.volmit.stage.PlacementStage; import com.volmit.stage.PlacementStage;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
/** Port of PlacementModuleBlocks: write each transformed block; COMPLETE marks the pass done. */ /** Port of PlacementModuleBlocks: write each transformed block; COMPLETE marks the pass done. */
public final class BlocksModule implements IrisModule { public final class BlocksModule implements IrisModule {
@@ -21,11 +21,12 @@ public final class BlocksModule implements IrisModule {
} }
@Override @Override
public void install(StageGraph graph) { public void setup(ModuleSetup setup) {
graph.define(WRITE) var stages = setup.stages();
stages.define(WRITE)
.requires(PrepareModule.ROTATE, AnchorModule.HEIGHT) .requires(PrepareModule.ROTATE, AnchorModule.HEIGHT)
.run(BlocksModule::write); .run(BlocksModule::write);
graph.define(COMPLETE) stages.define(COMPLETE)
.requires(WRITE) .requires(WRITE)
.run(context -> {}); .run(context -> {});
} }
@@ -2,16 +2,14 @@ package com.volmit.example.placement;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.ModuleInfo; import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
import com.volmit.block.BlockState; import com.volmit.block.BlockState;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.placement.PlacedBlock; import com.volmit.placement.PlacedBlock;
import com.volmit.stage.PlacementStage; import com.volmit.stage.PlacementStage;
import com.volmit.stage.PlacementStageContext; import com.volmit.stage.PlacementStageContext;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
import com.volmit.stage.StageRef; import com.volmit.stage.StageRef;
import com.volmit.world.BlockPosition; import com.volmit.world.BlockPosition;
import java.util.List;
import java.util.Optional; import java.util.Optional;
/** Third-party module: turns the ground under the anchor into moss. It requires the core /** Third-party module: turns the ground under the anchor into moss. It requires the core
@@ -27,16 +25,16 @@ public final class MossModule implements IrisModule {
} }
@Override @Override
public void install(StageGraph graph) { public void setup(ModuleSetup setup) {
graph.define(SPREAD) setup.stages().define(SPREAD)
.when(MossSettings.class) .when(MossSettings.class)
.requires(AnchorModule.HEIGHT, BlocksModule.COMPLETE) .requires(AnchorModule.HEIGHT, BlocksModule.COMPLETE)
.softAfter(StageRef.of("iris:snow/finish")) .softAfter(StageRef.of("iris:snow/finish"))
.run(MossModule::spread); .run(MossModule::spread);
} }
private static void spread(PlacementStageContext context, List<Entry<MossSettings>> settings) { private static void spread(PlacementStageContext context) {
var moss = settings.getFirst().value(); // a placement declares its settings once var moss = context.configured(MossSettings.class).getFirst().value(); // a placement declares its settings once
var anchor = context.output(AnchorModule.HEIGHT).anchor(); var anchor = context.output(AnchorModule.HEIGHT).anchor();
var access = context.access(); var access = context.access();
int groundY = anchor.y() - 1; int groundY = anchor.y() - 1;
@@ -2,12 +2,12 @@ package com.volmit.example.placement;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.ModuleInfo; import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
import com.volmit.object.ObjectBlock; import com.volmit.object.ObjectBlock;
import com.volmit.stage.BlockStage; import com.volmit.stage.BlockStage;
import com.volmit.stage.BlockStageContext; import com.volmit.stage.BlockStageContext;
import com.volmit.stage.PlacementStage; import com.volmit.stage.PlacementStage;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
/** Port of PlacementModulePreparation: choose transforms once, rotate each block in the pass. */ /** Port of PlacementModulePreparation: choose transforms once, rotate each block in the pass. */
public final class PrepareModule implements IrisModule { public final class PrepareModule implements IrisModule {
@@ -21,10 +21,11 @@ public final class PrepareModule implements IrisModule {
} }
@Override @Override
public void install(StageGraph graph) { public void setup(ModuleSetup setup) {
graph.define(TRANSFORMS) var stages = setup.stages();
stages.define(TRANSFORMS)
.produce(context -> new Transforms(context.random().nextInt(QUARTER_TURNS))); .produce(context -> new Transforms(context.random().nextInt(QUARTER_TURNS)));
graph.define(ROTATE) stages.define(ROTATE)
.requires(TRANSFORMS) .requires(TRANSFORMS)
.run(PrepareModule::rotate); .run(PrepareModule::rotate);
} }
@@ -2,17 +2,15 @@ package com.volmit.example.placement;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.ModuleInfo; import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
import com.volmit.block.BlockState; import com.volmit.block.BlockState;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.placement.PlacedBlock; import com.volmit.placement.PlacedBlock;
import com.volmit.stage.BlockStage; import com.volmit.stage.BlockStage;
import com.volmit.stage.PlacementStage; import com.volmit.stage.PlacementStage;
import com.volmit.stage.PlacementStageContext; import com.volmit.stage.PlacementStageContext;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
import com.volmit.stage.StageRef; import com.volmit.stage.StageRef;
import com.volmit.world.BlockPosition; import com.volmit.world.BlockPosition;
import java.util.List;
import java.util.Optional; import java.util.Optional;
/** Port of PlacementModuleSnow: collect written tops, then cover them after the finishing work /** Port of PlacementModuleSnow: collect written tops, then cover them after the finishing work
@@ -29,21 +27,22 @@ public final class SnowModule implements IrisModule {
} }
@Override @Override
public void install(StageGraph graph) { public void setup(ModuleSetup setup) {
graph.define(COLLECT) var stages = setup.stages();
stages.define(COLLECT)
.when(SnowSettings.class) .when(SnowSettings.class)
.requires(BlocksModule.WRITE) .requires(BlocksModule.WRITE)
.accumulate(SnowHeights::new, (context, snow, heights) -> heights.include( .accumulate(SnowHeights::new, (context, heights) -> heights.include(
context.output(AnchorModule.HEIGHT).worldPosition(context.request(), context.block().position()))); context.output(AnchorModule.HEIGHT).worldPosition(context.request(), context.block().position())));
graph.define(FINISH) stages.define(FINISH)
.when(SnowSettings.class) .when(SnowSettings.class)
.requires(COLLECT, BlocksModule.COMPLETE) .requires(COLLECT, BlocksModule.COMPLETE)
.softAfter(StageRef.of("iris:stilt/fill"), StageRef.of("iris:vacuum/finish")) .softAfter(StageRef.of("iris:stilt/fill"), StageRef.of("iris:vacuum/finish"))
.run(SnowModule::cover); .run(SnowModule::cover);
} }
private static void cover(PlacementStageContext context, List<Entry<SnowSettings>> settings) { private static void cover(PlacementStageContext context) {
var snow = settings.getFirst().value(); // a placement declares its settings once var snow = context.configured(SnowSettings.class).getFirst().value(); // a placement declares its settings once
var layer = SNOW.withProperty("layers", Integer.toString(snow.layers())); var layer = SNOW.withProperty("layers", Integer.toString(snow.layers()));
var access = context.access(); var access = context.access();
for (var top : context.output(COLLECT).tops()) { for (var top : context.output(COLLECT).tops()) {
@@ -2,16 +2,14 @@ package com.volmit.example.placement;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.ModuleInfo; import com.volmit.ModuleInfo;
import com.volmit.config.FeatureSettings.Entry; import com.volmit.ModuleSetup;
import com.volmit.object.ObjectBlock; import com.volmit.object.ObjectBlock;
import com.volmit.placement.PlacedBlock; import com.volmit.placement.PlacedBlock;
import com.volmit.stage.BlockStage; import com.volmit.stage.BlockStage;
import com.volmit.stage.PlacementStage; import com.volmit.stage.PlacementStage;
import com.volmit.stage.PlacementStageContext; import com.volmit.stage.PlacementStageContext;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
import com.volmit.world.BlockPosition; import com.volmit.world.BlockPosition;
import java.util.List;
import java.util.Optional; import java.util.Optional;
/** Port of PlacementModuleStilt: collect the lowest layer per block, then fill down after writes. */ /** Port of PlacementModuleStilt: collect the lowest layer per block, then fill down after writes. */
@@ -25,19 +23,20 @@ public final class StiltModule implements IrisModule {
} }
@Override @Override
public void install(StageGraph graph) { public void setup(ModuleSetup setup) {
graph.define(BOUNDS) var stages = setup.stages();
stages.define(BOUNDS)
.when(StiltSettings.class) .when(StiltSettings.class)
.requires(PrepareModule.ROTATE, AnchorModule.HEIGHT) .requires(PrepareModule.ROTATE, AnchorModule.HEIGHT)
.accumulate(StiltBounds::new, (context, stilt, bounds) -> bounds.include(context.block())); .accumulate(StiltBounds::new, (context, bounds) -> bounds.include(context.block()));
graph.define(FILL) stages.define(FILL)
.when(StiltSettings.class) .when(StiltSettings.class)
.requires(BOUNDS, BlocksModule.COMPLETE) .requires(BOUNDS, BlocksModule.COMPLETE)
.run(StiltModule::fill); .run(StiltModule::fill);
} }
private static void fill(PlacementStageContext context, List<Entry<StiltSettings>> settings) { private static void fill(PlacementStageContext context) {
var stilt = settings.getFirst().value(); // a placement declares its settings once var stilt = context.configured(StiltSettings.class).getFirst().value(); // a placement declares its settings once
var anchor = context.output(AnchorModule.HEIGHT); var anchor = context.output(AnchorModule.HEIGHT);
for (var block : context.output(BOUNDS).lowestLayer()) { for (var block : context.output(BOUNDS).lowestLayer()) {
var bottom = anchor.worldPosition(context.request(), block.position()); var bottom = anchor.worldPosition(context.request(), block.position());
@@ -1,9 +1,8 @@
package com.volmit.example.terrain; package com.volmit.example.terrain;
import com.volmit.FeatureRegistry;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.ModuleInfo; import com.volmit.ModuleInfo;
import com.volmit.stage.StageGraph; import com.volmit.ModuleSetup;
/** A built-in module whose settings use host types; it only registers them. */ /** A built-in module whose settings use host types; it only registers them. */
public final class LayersModule implements IrisModule { public final class LayersModule implements IrisModule {
@@ -13,10 +12,7 @@ public final class LayersModule implements IrisModule {
} }
@Override @Override
public void install(StageGraph graph) {} public void setup(ModuleSetup setup) {
setup.registry().registerSettings(LayersSettings.class);
@Override
public void register(FeatureRegistry registry) {
registry.registerSettings(LayersSettings.class);
} }
} }
@@ -1,18 +1,18 @@
package com.volmit.example.world; package com.volmit.example.world;
import com.volmit.FeatureRegistry;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.ModuleInfo; import com.volmit.ModuleInfo;
import com.volmit.ModuleLifecycle; import com.volmit.ModuleLifecycle;
import com.volmit.ModuleSetup;
import com.volmit.host.ChunkRunner; import com.volmit.host.ChunkRunner;
import com.volmit.host.DiscoveredModule; import com.volmit.host.DiscoveredModule;
import com.volmit.host.LifecycleRunner; import com.volmit.host.LifecycleRunner;
import com.volmit.host.LoadedModules; import com.volmit.host.LoadedModules;
import com.volmit.host.StageTimings;
import com.volmit.service.ObjectsAt; import com.volmit.service.ObjectsAt;
import com.volmit.stage.ChunkStage; import com.volmit.stage.ChunkStage;
import com.volmit.stage.ChunkStageContext; import com.volmit.stage.ChunkStageContext;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
import com.volmit.support.ColumnSettings; import com.volmit.support.ColumnSettings;
import com.volmit.support.TestContexts; import com.volmit.support.TestContexts;
import com.volmit.support.TestWorld; import com.volmit.support.TestWorld;
@@ -43,11 +43,9 @@ class WorldStateExampleTest {
public ModuleInfo info() { return ModuleInfo.of("example:ruins", "Ruins", "1"); } public ModuleInfo info() { return ModuleInfo.of("example:ruins", "Ruins", "1"); }
public void install(StageGraph graph) { public void setup(ModuleSetup setup) {
graph.define(PLANT).run(RuinsModule::plant); setup.stages().define(PLANT).run(RuinsModule::plant);
} var registry = setup.registry();
public void register(FeatureRegistry registry) {
registry.registerLifecycle(this); registry.registerLifecycle(this);
registry.registerService(ObjectsAt.class, new ObjectsAt() { registry.registerService(ObjectsAt.class, new ObjectsAt() {
@Override @Override
@@ -95,7 +93,8 @@ class WorldStateExampleTest {
var startedWith = RuinsModule.planted(world); var startedWith = RuinsModule.planted(world);
assertEquals(TestContexts.SEED, startedWith.seed); assertEquals(TestContexts.SEED, startedWith.seed);
new ChunkRunner(pack.chunk()).generate(TestContexts.generation(Map.of(), ColumnSettings.NONE, null, world), TestContexts.SEED); new ChunkRunner(pack.chunk()).generate(TestContexts.generation(Map.of(), ColumnSettings.NONE, null, world), TestContexts.SEED,
StageTimings.NONE);
assertSame(startedWith, RuinsModule.planted(world), "the stage used the state the hook built"); assertSame(startedWith, RuinsModule.planted(world), "the stage used the state the hook built");
assertEquals(Set.of("ruins/arch"), objects.objectsAt(world, 0, 0)); assertEquals(Set.of("ruins/arch"), objects.objectsAt(world, 0, 0));
@@ -32,6 +32,20 @@ class ConfiguredSettingsTest {
assertEquals(List.of(), ConfiguredSettings.none().find(Levels.class)); assertEquals(List.of(), ConfiguredSettings.none().find(Levels.class));
} }
@Feature(id = "test:base", name = "Base", key = "base", targets = {Target.BIOME, Target.OBJECT_PLACEMENT})
static class Base implements IrisFeature {}
static final class Refined extends Base {}
@Test
void aSubclassValueIsFoundUnderTheTypeThatDeclaresItsFeature() {
var refined = new Entry<>(Target.BIOME, BIOME, new Refined());
assertEquals(List.of(refined), ConfiguredSettings.of(List.of(refined)).find(Base.class));
var twice = assertThrows(IllegalArgumentException.class, () -> ConfiguredSettings.placement(OBJECT, new Base(), new Refined()));
assertEquals("Settings configured twice: " + Base.class.getName(), twice.getMessage());
}
@Test @Test
void aPlacementDeclaresEachTypeOnce() { void aPlacementDeclaresEachTypeOnce() {
var levels = new Levels(); var levels = new Levels();
@@ -2,8 +2,8 @@ package com.volmit.host;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.ModuleInfo; import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -20,8 +20,8 @@ class DiscoveredModuleTest {
return infoCalls == 1 ? ModuleInfo.of("first:core", "First", "1") : ModuleInfo.of("second:core", "Second", "2"); return infoCalls == 1 ? ModuleInfo.of("first:core", "First", "1") : ModuleInfo.of("second:core", "Second", "2");
} }
public void install(StageGraph graph) { public void setup(ModuleSetup setup) {
graph.define(Stage.placement("first:core/mark")).run(context -> {}); setup.stages().define(Stage.placement("first:core/mark")).run(context -> {});
} }
} }
@@ -42,7 +42,7 @@ class DiscoveredModuleTest {
void builtInWhoseInfoIsNullFailsNamingTheClass() { void builtInWhoseInfoIsNullFailsNamingTheClass() {
var module = new IrisModule() { var module = new IrisModule() {
public ModuleInfo info() { return null; } public ModuleInfo info() { return null; }
public void install(StageGraph graph) {} public void setup(ModuleSetup setup) {}
}; };
var error = assertThrows(NullPointerException.class, () -> DiscoveredModule.builtIn(module)); var error = assertThrows(NullPointerException.class, () -> DiscoveredModule.builtIn(module));
@@ -1,12 +1,11 @@
package com.volmit.host; package com.volmit.host;
import com.volmit.FeatureRegistry;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.ModuleInfo; import com.volmit.ModuleInfo;
import com.volmit.ModuleLifecycle; import com.volmit.ModuleLifecycle;
import com.volmit.ModuleSetup;
import com.volmit.config.PackSettings; import com.volmit.config.PackSettings;
import com.volmit.resource.PackResources; import com.volmit.resource.PackResources;
import com.volmit.stage.StageGraph;
import com.volmit.support.EmptyResources; import com.volmit.support.EmptyResources;
import com.volmit.support.TestWorld; import com.volmit.support.TestWorld;
import com.volmit.world.PackWorld; import com.volmit.world.PackWorld;
@@ -23,9 +22,8 @@ class LifecycleRunnerTest {
private static IrisModule module(String id, List<String> calls, String failingHook) { private static IrisModule module(String id, List<String> calls, String failingHook) {
return new IrisModule() { return new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of(id, "Lifecycle " + id, "1"); } public ModuleInfo info() { return ModuleInfo.of(id, "Lifecycle " + id, "1"); }
public void install(StageGraph graph) {} public void setup(ModuleSetup setup) {
public void register(FeatureRegistry registry) { setup.registry().registerLifecycle(new ModuleLifecycle() {
registry.registerLifecycle(new ModuleLifecycle() {
public void packLoaded(PackResources resources, PackSettings settings) { record("loaded"); } public void packLoaded(PackResources resources, PackSettings settings) { record("loaded"); }
public void worldStarted(PackWorld world) { record("started"); } public void worldStarted(PackWorld world) { record("started"); }
public void warmUp(PackWorld world) { record("warmed"); } public void warmUp(PackWorld world) { record("warmed"); }
@@ -118,8 +116,7 @@ class LifecycleRunnerTest {
void modulesWithoutAWarmUpHookWarmUpNothing() { void modulesWithoutAWarmUpHookWarmUpNothing() {
var module = new IrisModule() { var module = new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of("test:plain", "Plain", "1"); } public ModuleInfo info() { return ModuleInfo.of("test:plain", "Plain", "1"); }
public void install(StageGraph graph) {} public void setup(ModuleSetup setup) { setup.registry().registerLifecycle(new ModuleLifecycle() {}); }
public void register(FeatureRegistry registry) { registry.registerLifecycle(new ModuleLifecycle() {}); }
}; };
try (var world = new TestWorld()) { try (var world = new TestWorld()) {
runner(module).warmUp(world); runner(module).warmUp(world);
@@ -1,16 +1,16 @@
package com.volmit.host; package com.volmit.host;
import com.volmit.FeatureRegistry;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.ModuleInfo; import com.volmit.ModuleInfo;
import com.volmit.ModuleLifecycle; import com.volmit.ModuleLifecycle;
import com.volmit.ModuleLog; import com.volmit.ModuleLog;
import com.volmit.ModuleSetup;
import com.volmit.stage.ChunkStage; import com.volmit.stage.ChunkStage;
import com.volmit.stage.Pipeline; import com.volmit.stage.Pipeline;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
import com.volmit.support.TestContexts; import com.volmit.support.TestContexts;
import com.volmit.support.TestModuleJar; import com.volmit.support.TestModuleJar;
import com.volmit.support.TestSetups;
import com.volmit.support.TestWorld; import com.volmit.support.TestWorld;
import com.volmit.world.PackWorld; import com.volmit.world.PackWorld;
import java.lang.System.Logger.Level; import java.lang.System.Logger.Level;
@@ -64,7 +64,7 @@ class ModuleLogTest {
private static IrisModule module(String id) { private static IrisModule module(String id) {
return new IrisModule() { return new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of(id, "Log " + id, "1"); } public ModuleInfo info() { return ModuleInfo.of(id, "Log " + id, "1"); }
public void install(StageGraph graph) {} public void setup(ModuleSetup setup) {}
}; };
} }
@@ -197,21 +197,18 @@ class ModuleLogTest {
} }
@Test @Test
void theRegistryGivesTheRegisteringModuleItsLogDuringRegister() { void setupGivesTheModuleItsOwnLog() {
var logger = new RecordingLogger(); var logger = new RecordingLogger();
var logs = new ArrayList<ModuleLog>(); var logs = new ArrayList<ModuleLog>();
var registering = new IrisModule() { var settingUp = new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of(BETA, "Registers", "1"); } public ModuleInfo info() { return ModuleInfo.of(BETA, "Sets up", "1"); }
public void install(StageGraph graph) {} public void setup(ModuleSetup setup) { logs.add(setup.log()); }
public void register(FeatureRegistry registry) { logs.add(registry.log()); }
}; };
var registry = new ModuleRegistry();
registry.register(DiscoveredModule.builtIn(registering).loggingTo(logger)); TestSetups.install(new StageGraphBuilder(), DiscoveredModule.builtIn(settingUp).loggingTo(logger));
logs.get(0).info("registered"); logs.get(0).info("set up");
assertEquals(List.of("[test:beta] registered"), logger.messages()); assertEquals(List.of("[test:beta] set up"), logger.messages());
assertThrows(IllegalStateException.class, registry::log);
} }
@Test @Test
@@ -220,12 +217,12 @@ class ModuleLogTest {
var alphaStage = Stage.chunk("test:alpha/first"); var alphaStage = Stage.chunk("test:alpha/first");
var betaStage = Stage.chunk("test:beta/second"); var betaStage = Stage.chunk("test:beta/second");
var builder = new StageGraphBuilder(); var builder = new StageGraphBuilder();
builder.install(DiscoveredModule.builtIn(stagedModule(ALPHA, alphaStage, null)).loggingTo(logger)); TestSetups.install(builder, DiscoveredModule.builtIn(stagedModule(ALPHA, alphaStage, null)).loggingTo(logger));
builder.install(DiscoveredModule.builtIn(stagedModule(BETA, betaStage, alphaStage)).loggingTo(logger)); TestSetups.install(builder, DiscoveredModule.builtIn(stagedModule(BETA, betaStage, alphaStage)).loggingTo(logger));
var runner = new ChunkRunner(builder.resolve(Pipeline.CHUNK)); var runner = new ChunkRunner(builder.resolve(Pipeline.CHUNK));
try (var world = new TestWorld()) { try (var world = new TestWorld()) {
runner.generate(TestContexts.generation(Map.of(), null, null, world), TestContexts.SEED); runner.generate(TestContexts.generation(Map.of(), null, null, world), TestContexts.SEED, StageTimings.NONE);
} }
assertEquals(List.of("[test:alpha] context", "[test:alpha] world", "[test:beta] context", "[test:beta] world"), assertEquals(List.of("[test:alpha] context", "[test:alpha] world", "[test:beta] context", "[test:beta] world"),
@@ -235,10 +232,10 @@ class ModuleLogTest {
private static IrisModule stagedModule(String id, ChunkStage<Void> stage, ChunkStage<Void> after) { private static IrisModule stagedModule(String id, ChunkStage<Void> stage, ChunkStage<Void> after) {
return new IrisModule() { return new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of(id, "Stage " + id, "1"); } public ModuleInfo info() { return ModuleInfo.of(id, "Stage " + id, "1"); }
public void install(StageGraph graph) { public void setup(ModuleSetup setup) {
var definition = graph.define(stage); var definition = setup.stages().define(stage);
if (after != null) { if (after != null) {
definition.softAfter(after.ref()); definition.softAfter(after);
} }
definition.run(context -> { definition.run(context -> {
context.log().info("context"); context.log().info("context");
@@ -254,9 +251,8 @@ class ModuleLogTest {
var seen = new ArrayList<ModuleLog>(); var seen = new ArrayList<ModuleLog>();
var module = new IrisModule() { var module = new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of(ALPHA, "Hooks", "1"); } public ModuleInfo info() { return ModuleInfo.of(ALPHA, "Hooks", "1"); }
public void install(StageGraph graph) {} public void setup(ModuleSetup setup) {
public void register(FeatureRegistry registry) { setup.registry().registerLifecycle(new ModuleLifecycle() {
registry.registerLifecycle(new ModuleLifecycle() {
public void worldStarted(PackWorld world) { seen.add(world.log()); } public void worldStarted(PackWorld world) { seen.add(world.log()); }
}); });
} }
@@ -10,7 +10,6 @@ import com.volmit.validation.Validator;
import com.volmit.service.VanillaStructures; import com.volmit.service.VanillaStructures;
import com.volmit.stage.PlacementStage; import com.volmit.stage.PlacementStage;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.io.DataInput; import java.io.DataInput;
import java.io.DataOutput; import java.io.DataOutput;
@@ -40,13 +39,12 @@ class ModuleRegistryTest {
@Feature(id = "test:core/abstract", name = "Abstract", key = "coreAbstract", targets = FeatureAttachment.Target.BIOME) @Feature(id = "test:core/abstract", name = "Abstract", key = "coreAbstract", targets = FeatureAttachment.Target.BIOME)
abstract static class AbstractFeature implements IrisFeature {} abstract static class AbstractFeature implements IrisFeature {}
/** Runs {@code registrations} as the register(...) of a built-in module with the given id. */ /** Runs {@code registrations} as the setup(...) of a built-in module with the given id. */
private static void registerAs(ModuleRegistry registry, String moduleId, Consumer<FeatureRegistry> registrations) { private static void registerAs(ModuleRegistry registry, String moduleId, Consumer<FeatureRegistry> registrations) {
registry.register(DiscoveredModule.builtIn(new IrisModule() { ModuleSetups.run(DiscoveredModule.builtIn(new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of(moduleId, "Test module " + moduleId, "1"); } public ModuleInfo info() { return ModuleInfo.of(moduleId, "Test module " + moduleId, "1"); }
public void install(StageGraph graph) {} public void setup(ModuleSetup setup) { registrations.accept(setup.registry()); }
public void register(FeatureRegistry registry) { registrations.accept(registry); } }), new StageGraphBuilder(), registry);
}));
} }
@Test @Test
@@ -132,8 +130,10 @@ class ModuleRegistryTest {
var conditioned = new IrisModule() { var conditioned = new IrisModule() {
static final PlacementStage<Void> WORK = Stage.placement("test:core/work"); static final PlacementStage<Void> WORK = Stage.placement("test:core/work");
public ModuleInfo info() { return ModuleInfo.of("test:core", "Conditioned", "1"); } public ModuleInfo info() { return ModuleInfo.of("test:core", "Conditioned", "1"); }
public void install(StageGraph graph) { graph.define(WORK).when(One.class).run((context, one) -> {}); } public void setup(ModuleSetup setup) {
public void register(FeatureRegistry registry) { registry.registerObject(Two.class, ignored -> context -> null); } setup.stages().define(WORK).when(One.class).run(context -> {});
setup.registry().registerObject(Two.class, ignored -> context -> null);
}
}; };
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(conditioned)), Map.of(), Set.of(), Set.of()); var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(conditioned)), Map.of(), Set.of(), Set.of());
assertEquals(List.of("test:core/one"), loaded.catalog().settings().stream().map(value -> value.id().toString()).toList()); assertEquals(List.of("test:core/one"), loaded.catalog().settings().stream().map(value -> value.id().toString()).toList());
@@ -157,8 +157,7 @@ class ModuleRegistryTest {
private static IrisModule settingsModule(String id, Class<? extends IrisFeature> settings) { private static IrisModule settingsModule(String id, Class<? extends IrisFeature> settings) {
return new IrisModule() { return new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of(id, id, "1"); } public ModuleInfo info() { return ModuleInfo.of(id, id, "1"); }
public void install(StageGraph graph) {} public void setup(ModuleSetup setup) { setup.registry().registerSettings(settings); }
public void register(FeatureRegistry registry) { registry.registerSettings(settings); }
}; };
} }
@@ -217,8 +216,7 @@ class ModuleRegistryTest {
var conditioned = new IrisModule() { var conditioned = new IrisModule() {
static final PlacementStage<Void> WORK = Stage.placement("test:minerals/work"); static final PlacementStage<Void> WORK = Stage.placement("test:minerals/work");
public ModuleInfo info() { return ModuleInfo.of("test:minerals", "Minerals", "1"); } public ModuleInfo info() { return ModuleInfo.of("test:minerals", "Minerals", "1"); }
public void install(StageGraph graph) { graph.define(WORK).when(Minerals.class).run((context, minerals) -> {}); } public void setup(ModuleSetup setup) { setup.stages().define(WORK).when(Minerals.class).run(context -> {}); }
public void register(FeatureRegistry registry) {}
}; };
var stage = assertThrows(IllegalArgumentException.class, var stage = assertThrows(IllegalArgumentException.class,
() -> LoadedModules.load(discovered(settingsModule("test:ores", Ores.class), conditioned), Map.of(), Set.of(), Set.of())); () -> LoadedModules.load(discovered(settingsModule("test:ores", Ores.class), conditioned), Map.of(), Set.of(), Set.of()));
@@ -238,8 +236,7 @@ class ModuleRegistryTest {
private static IrisModule ownerOfOne(String name) { private static IrisModule ownerOfOne(String name) {
return new IrisModule() { return new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of("test:core", name, "1"); } public ModuleInfo info() { return ModuleInfo.of("test:core", name, "1"); }
public void install(StageGraph graph) {} public void setup(ModuleSetup setup) { setup.registry().registerSettings(One.class); }
public void register(FeatureRegistry registry) { registry.registerSettings(One.class); }
}; };
} }
@@ -276,13 +273,12 @@ class ModuleRegistryTest {
void settingsTheirOwnerRegisteredMayBeNamedByAnyModule() { void settingsTheirOwnerRegisteredMayBeNamedByAnyModule() {
var owner = new IrisModule() { var owner = new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of("test:core", "Owner", "1"); } public ModuleInfo info() { return ModuleInfo.of("test:core", "Owner", "1"); }
public void install(StageGraph graph) {} public void setup(ModuleSetup setup) { setup.registry().registerSettings(One.class); }
public void register(FeatureRegistry registry) { registry.registerSettings(One.class); }
}; };
var user = new IrisModule() { var user = new IrisModule() {
static final PlacementStage<Void> WORK = Stage.placement("test:user/work"); static final PlacementStage<Void> WORK = Stage.placement("test:user/work");
public ModuleInfo info() { return ModuleInfo.of("test:user", "User", "1"); } public ModuleInfo info() { return ModuleInfo.of("test:user", "User", "1"); }
public void install(StageGraph graph) { graph.define(WORK).when(One.class).run((context, one) -> {}); } public void setup(ModuleSetup setup) { setup.stages().define(WORK).when(One.class).run(context -> {}); }
}; };
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(owner), DiscoveredModule.builtIn(user)), Map.of(), Set.of(), Set.of()); var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(owner), DiscoveredModule.builtIn(user)), Map.of(), Set.of(), Set.of());
@@ -370,7 +366,7 @@ class ModuleRegistryTest {
}); });
assertThrows(IllegalStateException.class, () -> registry.registerLifecycle(new ModuleLifecycle() {}), assertThrows(IllegalStateException.class, () -> registry.registerLifecycle(new ModuleLifecycle() {}),
"registration outside IrisModule.register"); "registration outside IrisModule.setup");
var catalog = registry.freeze(); var catalog = registry.freeze();
assertEquals(List.of(first, second, other), catalog.lifecycles().stream().map(LifecycleRegistration::lifecycle).toList()); assertEquals(List.of(first, second, other), catalog.lifecycles().stream().map(LifecycleRegistration::lifecycle).toList());
assertEquals("test:alpha", catalog.lifecycles().getFirst().module().info().id().toString()); assertEquals("test:alpha", catalog.lifecycles().getFirst().module().info().id().toString());
@@ -22,7 +22,7 @@ class PackModulesTest {
private static final String ALPHA_MEMBERS = private static final String ALPHA_MEMBERS =
"public static final PlacementStage<Void> MARK = Stage.placement(\"alpha:core/mark\");"; "public static final PlacementStage<Void> MARK = Stage.placement(\"alpha:core/mark\");";
private static final String NO_MEMBERS = ""; private static final String NO_MEMBERS = "";
private static final String NO_STAGES = ""; private static final String NO_SETUP = "";
private static final String SHARED_CLASS = "pack.shared.Util"; private static final String SHARED_CLASS = "pack.shared.Util";
private static final String SHARED_SOURCE = "package pack.shared; public final class Util {}"; private static final String SHARED_SOURCE = "package pack.shared; public final class Util {}";
private static final byte[] UNUSED_CLASS_BYTES = {(byte) 0xCA, (byte) 0xFE}; private static final byte[] UNUSED_CLASS_BYTES = {(byte) 0xCA, (byte) 0xFE};
@@ -111,7 +111,7 @@ class PackModulesTest {
@Test @Test
void packClassLoaderSeesOnlyTheApiTheJdkAndThePack() throws Exception { void packClassLoaderSeesOnlyTheApiTheJdkAndThePack() throws Exception {
module("pack.gamma.GammaModule", "gamma:core", NO_MEMBERS, NO_STAGES).writeInto(pack, "gamma.jar"); module("pack.gamma.GammaModule", "gamma:core", NO_MEMBERS, NO_SETUP).writeInto(pack, "gamma.jar");
try (var packModules = PackModules.load(pack)) { try (var packModules = PackModules.load(pack)) {
var loader = packModules.modules().getFirst().module().getClass().getClassLoader(); var loader = packModules.modules().getFirst().module().getClass().getClassLoader();
@@ -123,7 +123,7 @@ class PackModulesTest {
@Test @Test
void closingThePackStopsItsClassLoaderFromLoadingMoreClasses() throws Exception { void closingThePackStopsItsClassLoaderFromLoadingMoreClasses() throws Exception {
module("pack.gamma.GammaModule", "gamma:core", NO_MEMBERS, NO_STAGES) module("pack.gamma.GammaModule", "gamma:core", NO_MEMBERS, NO_SETUP)
.source("pack.gamma.Unused", "package pack.gamma; final class Unused {}") .source("pack.gamma.Unused", "package pack.gamma; final class Unused {}")
.writeInto(pack, "gamma.jar"); .writeInto(pack, "gamma.jar");
@@ -145,8 +145,8 @@ class PackModulesTest {
@Test @Test
void jarNamingSeveralEntryPointsLoadsEachModuleInListedOrder() { void jarNamingSeveralEntryPointsLoadsEachModuleInListedOrder() {
module("pack.First", "first:core", NO_MEMBERS, NO_STAGES) module("pack.First", "first:core", NO_MEMBERS, NO_SETUP)
.alsoModule("pack.Second", "second:core", NO_MEMBERS, NO_STAGES) .alsoModule("pack.Second", "second:core", NO_MEMBERS, NO_SETUP)
.writeInto(pack, "two.jar"); .writeInto(pack, "two.jar");
try (var packModules = PackModules.load(pack)) { try (var packModules = PackModules.load(pack)) {
@@ -160,7 +160,7 @@ class PackModulesTest {
@Test @Test
void secondEntryPointOfAJarThatBreaksNamesItsClass() { void secondEntryPointOfAJarThatBreaksNamesItsClass() {
module("pack.First", "first:core", NO_MEMBERS, NO_STAGES) module("pack.First", "first:core", NO_MEMBERS, NO_SETUP)
.entryPoint("pack.Missing") .entryPoint("pack.Missing")
.writeInto(pack, "two.jar"); .writeInto(pack, "two.jar");
@@ -170,7 +170,7 @@ class PackModulesTest {
@Test @Test
void entryPointOfAnotherJarFailsNamingTheJarThatListsIt() { void entryPointOfAnotherJarFailsNamingTheJarThatListsIt() {
module("pack.First", "first:core", NO_MEMBERS, NO_STAGES).writeInto(pack, "first.jar"); module("pack.First", "first:core", NO_MEMBERS, NO_SETUP).writeInto(pack, "first.jar");
new TestModuleJar().entryPoint("pack.First").writeInto(pack, "second.jar"); new TestModuleJar().entryPoint("pack.First").writeInto(pack, "second.jar");
assertMentions(failure(() -> PackModules.load(pack)), assertMentions(failure(() -> PackModules.load(pack)),
@@ -180,8 +180,8 @@ class PackModulesTest {
@Test @Test
void optionalPackagesOfAnyModuleOfAJarExcuseItsMissingClasses(@TempDir Path build) { void optionalPackagesOfAnyModuleOfAJarExcuseItsMissingClasses(@TempDir Path build) {
module("pack.First", "first:core", List.of("org.optional"), NO_MEMBERS, NO_STAGES) module("pack.First", "first:core", List.of("org.optional"), NO_MEMBERS, NO_SETUP)
.alsoModule("pack.Second", "second:core", using(OPTIONAL_CLASS), NO_STAGES) .alsoModule("pack.Second", "second:core", using(OPTIONAL_CLASS), NO_SETUP)
.compileAgainst(library(build, "optional.jar", OPTIONAL_CLASS)) .compileAgainst(library(build, "optional.jar", OPTIONAL_CLASS))
.writeInto(pack, "two.jar"); .writeInto(pack, "two.jar");
@@ -204,7 +204,7 @@ class PackModulesTest {
"Module jar " + origin("plain.jar") + " has a broken entry point pack.Plain: class does not implement com.volmit.IrisModule"); "Module jar " + origin("plain.jar") + " has a broken entry point pack.Plain: class does not implement com.volmit.IrisModule");
var throwing = pack.resolve("throwing"); var throwing = pack.resolve("throwing");
module("pack.Throwing", "throwing:core", "public Throwing() { throw new IllegalStateException(\"boom\"); }", NO_STAGES) module("pack.Throwing", "throwing:core", "public Throwing() { throw new IllegalStateException(\"boom\"); }", NO_SETUP)
.writeInto(throwing, "throwing.jar"); .writeInto(throwing, "throwing.jar");
assertMentions(failure(() -> PackModules.load(throwing)), assertMentions(failure(() -> PackModules.load(throwing)),
"Module jar " + origin("throwing.jar") + " has a broken entry point pack.Throwing: constructor threw", "Module jar " + origin("throwing.jar") + " has a broken entry point pack.Throwing: constructor threw",
@@ -220,9 +220,9 @@ class PackModulesTest {
@Test @Test
void sameClassInTwoJarsFailsBeforeAnyModuleIsConstructed() { void sameClassInTwoJarsFailsBeforeAnyModuleIsConstructed() {
var constructorMarker = "public %s() { System.setProperty(\"" + DEFINED_PROPERTY + "\", \"true\"); }"; var constructorMarker = "public %s() { System.setProperty(\"" + DEFINED_PROPERTY + "\", \"true\"); }";
module("pack.alpha.Alpha", "alpha:core", constructorMarker.formatted("Alpha"), NO_STAGES) module("pack.alpha.Alpha", "alpha:core", constructorMarker.formatted("Alpha"), NO_SETUP)
.source(SHARED_CLASS, SHARED_SOURCE).writeInto(pack, "alpha.jar"); .source(SHARED_CLASS, SHARED_SOURCE).writeInto(pack, "alpha.jar");
module("pack.beta.Beta", "beta:core", constructorMarker.formatted("Beta"), NO_STAGES) module("pack.beta.Beta", "beta:core", constructorMarker.formatted("Beta"), NO_SETUP)
.source(SHARED_CLASS, SHARED_SOURCE).writeInto(pack, "beta.jar"); .source(SHARED_CLASS, SHARED_SOURCE).writeInto(pack, "beta.jar");
try { try {
@@ -236,9 +236,9 @@ class PackModulesTest {
@Test @Test
void moduleDescriptorsMayRepeatAcrossJars() { void moduleDescriptorsMayRepeatAcrossJars() {
module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_STAGES) module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_SETUP)
.resource("module-info.class", UNUSED_CLASS_BYTES).writeInto(pack, "alpha.jar"); .resource("module-info.class", UNUSED_CLASS_BYTES).writeInto(pack, "alpha.jar");
module("pack.beta.Beta", "beta:core", NO_MEMBERS, NO_STAGES) module("pack.beta.Beta", "beta:core", NO_MEMBERS, NO_SETUP)
.resource("module-info.class", UNUSED_CLASS_BYTES).writeInto(pack, "beta.jar"); .resource("module-info.class", UNUSED_CLASS_BYTES).writeInto(pack, "beta.jar");
try (var packModules = PackModules.load(pack)) { try (var packModules = PackModules.load(pack)) {
@@ -248,9 +248,9 @@ class PackModulesTest {
@Test @Test
void versionedClassOfAMultiReleaseJarCountsUnderItsBaseName() { void versionedClassOfAMultiReleaseJarCountsUnderItsBaseName() {
module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_STAGES) module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_SETUP)
.source(SHARED_CLASS, SHARED_SOURCE).writeInto(pack, "alpha.jar"); .source(SHARED_CLASS, SHARED_SOURCE).writeInto(pack, "alpha.jar");
module("pack.beta.Beta", "beta:core", NO_MEMBERS, NO_STAGES) module("pack.beta.Beta", "beta:core", NO_MEMBERS, NO_SETUP)
.multiRelease() .multiRelease()
.resource(VERSIONED_SHARED_CLASS, sharedClassFile()) .resource(VERSIONED_SHARED_CLASS, sharedClassFile())
.writeInto(pack, "beta.jar"); .writeInto(pack, "beta.jar");
@@ -261,11 +261,11 @@ class PackModulesTest {
@Test @Test
void versionedEntriesOutsideAMultiReleaseJarAreNotClasses() { void versionedEntriesOutsideAMultiReleaseJarAreNotClasses() {
module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_STAGES) module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_SETUP)
.source(SHARED_CLASS, SHARED_SOURCE) .source(SHARED_CLASS, SHARED_SOURCE)
.resource(VERSIONED_SHARED_CLASS, UNUSED_CLASS_BYTES) .resource(VERSIONED_SHARED_CLASS, UNUSED_CLASS_BYTES)
.writeInto(pack, "alpha.jar"); .writeInto(pack, "alpha.jar");
module("pack.beta.Beta", "beta:core", NO_MEMBERS, NO_STAGES) module("pack.beta.Beta", "beta:core", NO_MEMBERS, NO_SETUP)
.resource(VERSIONED_SHARED_CLASS, UNUSED_CLASS_BYTES) .resource(VERSIONED_SHARED_CLASS, UNUSED_CLASS_BYTES)
.writeInto(pack, "beta.jar"); .writeInto(pack, "beta.jar");
@@ -276,7 +276,7 @@ class PackModulesTest {
@Test @Test
void multiReleaseJarMayHoldAVersionedCopyOfItsOwnClass() { void multiReleaseJarMayHoldAVersionedCopyOfItsOwnClass() {
module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_STAGES) module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_SETUP)
.source(SHARED_CLASS, SHARED_SOURCE) .source(SHARED_CLASS, SHARED_SOURCE)
.multiRelease() .multiRelease()
.resource(VERSIONED_SHARED_CLASS, sharedClassFile()) .resource(VERSIONED_SHARED_CLASS, sharedClassFile())
@@ -289,7 +289,7 @@ class PackModulesTest {
@Test @Test
void apiClassInAJarFailsNamingTheJarAndTheClass() { void apiClassInAJarFailsNamingTheJarAndTheClass() {
module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_STAGES) module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_SETUP)
.source("com.volmit.extra.Helper", "package com.volmit.extra; public final class Helper {}") .source("com.volmit.extra.Helper", "package com.volmit.extra; public final class Helper {}")
.source("com.volmit.extra.Other", "package com.volmit.extra; public final class Other {}") .source("com.volmit.extra.Other", "package com.volmit.extra; public final class Other {}")
.writeInto(pack, "alpha.jar"); .writeInto(pack, "alpha.jar");
@@ -302,7 +302,7 @@ class PackModulesTest {
@Test @Test
void referenceToAHostLibraryFailsNamingTheJarAndBothClasses() { void referenceToAHostLibraryFailsNamingTheJarAndBothClasses() {
module("pack.user.User", "user:core", "static Object probe() { return org.junit.jupiter.api.Test.class; }", NO_STAGES) module("pack.user.User", "user:core", "static Object probe() { return org.junit.jupiter.api.Test.class; }", NO_SETUP)
.compileAgainstHostOf(Test.class) .compileAgainstHostOf(Test.class)
.writeInto(pack, "user.jar"); .writeInto(pack, "user.jar");
@@ -315,7 +315,7 @@ class PackModulesTest {
@Test @Test
void referenceToAJdkModuleOutsideThePlatformLoaderFailsNamingTheModule() { void referenceToAJdkModuleOutsideThePlatformLoaderFailsNamingTheModule() {
module("pack.user.User", "user:core", using("com.sun.source.tree.Tree", "java.sql.Connection"), NO_STAGES) module("pack.user.User", "user:core", using("com.sun.source.tree.Tree", "java.sql.Connection"), NO_SETUP)
.writeInto(pack, "user.jar"); .writeInto(pack, "user.jar");
assertEquals("Module jar " + origin("user.jar") + " uses classes of JDK modules that are not available to modules:\n" assertEquals("Module jar " + origin("user.jar") + " uses classes of JDK modules that are not available to modules:\n"
@@ -327,7 +327,7 @@ class PackModulesTest {
@Test @Test
void referenceToANonExportedJdkPackageFailsNamingThePackageAndModule() { void referenceToANonExportedJdkPackageFailsNamingThePackageAndModule() {
module("pack.user.User", "user:core", using("jdk.internal.misc.Unsafe", "java.lang.String"), NO_STAGES) module("pack.user.User", "user:core", using("jdk.internal.misc.Unsafe", "java.lang.String"), NO_SETUP)
.compileWithAccessTo("java.base", "jdk.internal.misc") .compileWithAccessTo("java.base", "jdk.internal.misc")
.writeInto(pack, "user.jar"); .writeInto(pack, "user.jar");
@@ -341,7 +341,7 @@ class PackModulesTest {
@Test @Test
void supportedUnsafeFromJdkUnsupportedIsUsable() { void supportedUnsafeFromJdkUnsupportedIsUsable() {
module("pack.user.User", "user:core", using("sun.misc.Unsafe", "java.lang.String"), NO_STAGES) module("pack.user.User", "user:core", using("sun.misc.Unsafe", "java.lang.String"), NO_SETUP)
.writeInto(pack, "user.jar"); .writeInto(pack, "user.jar");
try (var packModules = PackModules.load(pack)) { try (var packModules = PackModules.load(pack)) {
@@ -351,7 +351,7 @@ class PackModulesTest {
@Test @Test
void oneFailureReportsEveryKindOfUnusableClass() { void oneFailureReportsEveryKindOfUnusableClass() {
module("pack.user.User", "user:core", using("org.junit.jupiter.api.Test", "com.sun.source.tree.Tree"), NO_STAGES) module("pack.user.User", "user:core", using("org.junit.jupiter.api.Test", "com.sun.source.tree.Tree"), NO_SETUP)
.compileAgainstHostOf(Test.class) .compileAgainstHostOf(Test.class)
.writeInto(pack, "user.jar"); .writeInto(pack, "user.jar");
@@ -390,7 +390,7 @@ class PackModulesTest {
module("pack.user.User", "user:core", """ module("pack.user.User", "user:core", """
static Object optional() { return org.optional.Feature.class; } static Object optional() { return org.optional.Feature.class; }
static Object hidden() { return org.junit.jupiter.api.Test.class; } static Object hidden() { return org.junit.jupiter.api.Test.class; }
""", NO_STAGES) """, NO_SETUP)
.compileAgainst(optionalLibrary) .compileAgainst(optionalLibrary)
.compileAgainstHostOf(Test.class) .compileAgainstHostOf(Test.class)
.writeInto(pack, "user.jar"); .writeInto(pack, "user.jar");
@@ -402,7 +402,7 @@ class PackModulesTest {
@Test @Test
void missingClassesInDeclaredOptionalPackagesDoNotWarn(@TempDir Path build) { void missingClassesInDeclaredOptionalPackagesDoNotWarn(@TempDir Path build) {
module("pack.user.User", "user:core", List.of("org.optional", "org.other."), using(OPTIONAL_CLASS, "org.other.deep.Thing"), NO_STAGES) module("pack.user.User", "user:core", List.of("org.optional", "org.other."), using(OPTIONAL_CLASS, "org.other.deep.Thing"), NO_SETUP)
.compileAgainst(library(build, "optional.jar", OPTIONAL_CLASS, "org.other.deep.Thing")) .compileAgainst(library(build, "optional.jar", OPTIONAL_CLASS, "org.other.deep.Thing"))
.writeInto(pack, "user.jar"); .writeInto(pack, "user.jar");
@@ -413,7 +413,7 @@ class PackModulesTest {
@Test @Test
void missingClassesOutsideDeclaredOptionalPackagesStillWarn(@TempDir Path build) { void missingClassesOutsideDeclaredOptionalPackagesStillWarn(@TempDir Path build) {
module("pack.user.User", "user:core", List.of("org.optional"), using(OPTIONAL_CLASS, "org.optionalx.Other", "org.slf4j.Logger"), NO_STAGES) module("pack.user.User", "user:core", List.of("org.optional"), using(OPTIONAL_CLASS, "org.optionalx.Other", "org.slf4j.Logger"), NO_SETUP)
.compileAgainst(library(build, "optional.jar", OPTIONAL_CLASS, "org.optionalx.Other", "org.slf4j.Logger")) .compileAgainst(library(build, "optional.jar", OPTIONAL_CLASS, "org.optionalx.Other", "org.slf4j.Logger"))
.writeInto(pack, "user.jar"); .writeInto(pack, "user.jar");
@@ -426,10 +426,10 @@ class PackModulesTest {
@Test @Test
void optionalPackagesExcuseOnlyTheirOwnJar(@TempDir Path build) { void optionalPackagesExcuseOnlyTheirOwnJar(@TempDir Path build) {
var optionalLibrary = library(build, "optional.jar", OPTIONAL_CLASS); var optionalLibrary = library(build, "optional.jar", OPTIONAL_CLASS);
module("pack.alpha.Alpha", "alpha:core", List.of("org.optional"), using(OPTIONAL_CLASS), NO_STAGES) module("pack.alpha.Alpha", "alpha:core", List.of("org.optional"), using(OPTIONAL_CLASS), NO_SETUP)
.compileAgainst(optionalLibrary) .compileAgainst(optionalLibrary)
.writeInto(pack, "alpha.jar"); .writeInto(pack, "alpha.jar");
module("pack.beta.Beta", "beta:core", using(OPTIONAL_CLASS), NO_STAGES) module("pack.beta.Beta", "beta:core", using(OPTIONAL_CLASS), NO_SETUP)
.compileAgainst(optionalLibrary) .compileAgainst(optionalLibrary)
.writeInto(pack, "beta.jar"); .writeInto(pack, "beta.jar");
@@ -441,14 +441,14 @@ class PackModulesTest {
@Test @Test
void optionalPackagesNeverExcuseALoadError(@TempDir Path build) { void optionalPackagesNeverExcuseALoadError(@TempDir Path build) {
var hidden = pack.resolve("hidden"); var hidden = pack.resolve("hidden");
module("pack.user.User", "user:core", List.of("org.junit"), using("org.junit.jupiter.api.Test"), NO_STAGES) module("pack.user.User", "user:core", List.of("org.junit"), using("org.junit.jupiter.api.Test"), NO_SETUP)
.compileAgainstHostOf(Test.class) .compileAgainstHostOf(Test.class)
.writeInto(hidden, "user.jar"); .writeInto(hidden, "user.jar");
assertMentions(failure(() -> PackModules.load(hidden)), assertMentions(failure(() -> PackModules.load(hidden)),
"uses classes that exist in Iris but are hidden from modules:\n pack.user.User -> org.junit.jupiter.api.Test"); "uses classes that exist in Iris but are hidden from modules:\n pack.user.User -> org.junit.jupiter.api.Test");
var newerApi = pack.resolve("newer-api"); var newerApi = pack.resolve("newer-api");
module("pack.user.User", "user:core", List.of("com.volmit"), using("com.volmit.Newer"), NO_STAGES) module("pack.user.User", "user:core", List.of("com.volmit"), using("com.volmit.Newer"), NO_SETUP)
.compileAgainst(library(build, "newer-api.jar", "com.volmit.Newer")) .compileAgainst(library(build, "newer-api.jar", "com.volmit.Newer"))
.writeInto(newerApi, "user.jar"); .writeInto(newerApi, "user.jar");
assertMentions(failure(() -> PackModules.load(newerApi)), assertMentions(failure(() -> PackModules.load(newerApi)),
@@ -457,7 +457,7 @@ class PackModulesTest {
@Test @Test
void invalidOptionalPackageFailsNamingTheJar() { void invalidOptionalPackageFailsNamingTheJar() {
module("pack.user.User", "user:core", List.of("org.*"), NO_MEMBERS, NO_STAGES).writeInto(pack, "user.jar"); module("pack.user.User", "user:core", List.of("org.*"), NO_MEMBERS, NO_SETUP).writeInto(pack, "user.jar");
assertMentions(failure(() -> PackModules.load(pack)), assertMentions(failure(() -> PackModules.load(pack)),
"Module jar " + origin("user.jar") + " has a broken entry point pack.user.User: info() failed", "Module jar " + origin("user.jar") + " has a broken entry point pack.user.User: info() failed",
@@ -469,7 +469,7 @@ class PackModulesTest {
var newerApi = new TestModuleJar() var newerApi = new TestModuleJar()
.source("com.volmit.Newer", "package com.volmit; public final class Newer {}") .source("com.volmit.Newer", "package com.volmit; public final class Newer {}")
.writeInto(build, "newer-api.jar"); .writeInto(build, "newer-api.jar");
module("pack.user.User", "user:core", "static Object probe() { return com.volmit.Newer.class; }", NO_STAGES) module("pack.user.User", "user:core", "static Object probe() { return com.volmit.Newer.class; }", NO_SETUP)
.compileAgainst(newerApi) .compileAgainst(newerApi)
.writeInto(pack, "user.jar"); .writeInto(pack, "user.jar");
@@ -487,7 +487,7 @@ class PackModulesTest {
public @interface Marker {} public @interface Marker {}
""") """)
.writeInto(build, "marker.jar"); .writeInto(build, "marker.jar");
var alpha = module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_STAGES) var alpha = module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_SETUP)
.source("pack.alpha.Shared", """ .source("pack.alpha.Shared", """
package pack.alpha; package pack.alpha;
public record Shared(int[] values, String[][] names) { public record Shared(int[] values, String[][] names) {
@@ -551,7 +551,7 @@ class PackModulesTest {
var newerBuiltIns = new TestModuleJar() var newerBuiltIns = new TestModuleJar()
.source("example.builtin.Newer", "package example.builtin; public final class Newer {}") .source("example.builtin.Newer", "package example.builtin; public final class Newer {}")
.writeInto(build, "newer-built-ins.jar"); .writeInto(build, "newer-built-ins.jar");
module("pack.user.User", "user:core", "static Object probe() { return example.builtin.Newer.class; }", NO_STAGES) module("pack.user.User", "user:core", "static Object probe() { return example.builtin.Newer.class; }", NO_SETUP)
.compileAgainst(newerBuiltIns) .compileAgainst(newerBuiltIns)
.writeInto(pack, "user.jar"); .writeInto(pack, "user.jar");
@@ -561,7 +561,7 @@ class PackModulesTest {
@Test @Test
void classOfAnExposedHostPackageInAJarFails() { void classOfAnExposedHostPackageInAJarFails() {
module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_STAGES) module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_SETUP)
.source("example.builtin.Copy", "package example.builtin; public final class Copy {}") .source("example.builtin.Copy", "package example.builtin; public final class Copy {}")
.writeInto(pack, "alpha.jar"); .writeInto(pack, "alpha.jar");
@@ -598,8 +598,8 @@ class PackModulesTest {
public final class Once implements IrisModule { public final class Once implements IrisModule {
%s %s
public void install(StageGraph graph) { public void setup(com.volmit.ModuleSetup setup) {
graph.define(Stage.placement("once:core/mark")).run(context -> {}); setup.stages().define(Stage.placement("once:core/mark")).run(context -> {});
} }
} }
""".formatted(answersOnce)) """.formatted(answersOnce))
@@ -614,11 +614,11 @@ class PackModulesTest {
} }
@Test @Test
void methodMissingAtInstallFailsNamingTheJar(@TempDir Path build) { void methodMissingAtSetupFailsNamingTheJar(@TempDir Path build) {
var libraryWithMethod = new TestModuleJar() var libraryWithMethod = new TestModuleJar()
.source("pack.lib.Lib", "package pack.lib; public final class Lib { public static void added() {} }") .source("pack.lib.Lib", "package pack.lib; public final class Lib { public static void added() {} }")
.writeInto(build, "lib.jar"); .writeInto(build, "lib.jar");
module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_STAGES) module("pack.alpha.Alpha", "alpha:core", NO_MEMBERS, NO_SETUP)
.source("pack.lib.Lib", "package pack.lib; public final class Lib {}") .source("pack.lib.Lib", "package pack.lib; public final class Lib {}")
.writeInto(pack, "alpha.jar"); .writeInto(pack, "alpha.jar");
module("pack.beta.Beta", "beta:core", NO_MEMBERS, "pack.lib.Lib.added();") module("pack.beta.Beta", "beta:core", NO_MEMBERS, "pack.lib.Lib.added();")
@@ -627,7 +627,7 @@ class PackModulesTest {
try (var packModules = PackModules.load(pack)) { try (var packModules = PackModules.load(pack)) {
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())), assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())),
"Module beta:core from " + origin("beta.jar") + " failed to link or initialize a class while installing", "Module beta:core from " + origin("beta.jar") + " failed to link or initialize a class during setup",
"java.lang.NoSuchMethodError", "pack.lib.Lib.added()"); "java.lang.NoSuchMethodError", "pack.lib.Lib.added()");
} }
} }
@@ -646,10 +646,9 @@ class PackModulesTest {
} }
""").writeInto(build, "api-without-keys.jar"); """).writeInto(build, "api-without-keys.jar");
module("pack.old.Old", "old:flora", """ module("pack.old.Old", "old:flora", """
public void register(com.volmit.FeatureRegistry registry) { registry.registerSettings(Patch.class); }
@com.volmit.config.Feature(id = "old:flora/wild-patch", name = "Patch", targets = com.volmit.FeatureAttachment.Target.BIOME) @com.volmit.config.Feature(id = "old:flora/wild-patch", name = "Patch", targets = com.volmit.FeatureAttachment.Target.BIOME)
public static final class Patch implements com.volmit.IrisFeature {} public static final class Patch implements com.volmit.IrisFeature {}
""", NO_STAGES) """, "registry.registerSettings(Patch.class);")
.compileAgainstOlderApi(apiWithoutKeys) .compileAgainstOlderApi(apiWithoutKeys)
.writeInto(pack, "old.jar"); .writeInto(pack, "old.jar");
@@ -663,8 +662,8 @@ class PackModulesTest {
@Test @Test
void duplicateModuleIdsAcrossJarsFailNamingBothJars() { void duplicateModuleIdsAcrossJarsFailNamingBothJars() {
module("pack.one.Duplicate", "dup:core", NO_MEMBERS, NO_STAGES).writeInto(pack, "one.jar"); module("pack.one.Duplicate", "dup:core", NO_MEMBERS, NO_SETUP).writeInto(pack, "one.jar");
module("pack.two.Duplicate", "dup:core", NO_MEMBERS, NO_STAGES).writeInto(pack, "two.jar"); module("pack.two.Duplicate", "dup:core", NO_MEMBERS, NO_SETUP).writeInto(pack, "two.jar");
try (var packModules = PackModules.load(pack)) { try (var packModules = PackModules.load(pack)) {
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())), assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())),
@@ -675,7 +674,7 @@ class PackModulesTest {
@Test @Test
void duplicateOfABuiltInModuleFailsNamingTheJar() { void duplicateOfABuiltInModuleFailsNamingTheJar() {
module("pack.Moss", "example:moss", NO_MEMBERS, NO_STAGES).writeInto(pack, "moss.jar"); module("pack.Moss", "example:moss", NO_MEMBERS, NO_SETUP).writeInto(pack, "moss.jar");
try (var packModules = PackModules.load(pack)) { try (var packModules = PackModules.load(pack)) {
assertMentions(failure(() -> loadWithBuiltIns(packModules)), assertMentions(failure(() -> loadWithBuiltIns(packModules)),
@@ -686,8 +685,7 @@ class PackModulesTest {
@Test @Test
void settingsKeyTakenByABuiltInFailsNamingBothModulesAndTheirJars() { void settingsKeyTakenByABuiltInFailsNamingBothModulesAndTheirJars() {
module("pack.Clash", "mine:core", "public void register(com.volmit.FeatureRegistry registry) { registry.registerSettings(ClashSettings.class); }", module("pack.Clash", "mine:core", NO_MEMBERS, "registry.registerSettings(ClashSettings.class);")
NO_STAGES)
.source("pack.ClashSettings", """ .source("pack.ClashSettings", """
package pack; package pack;
@@ -722,8 +720,8 @@ class PackModulesTest {
@Test @Test
void duplicateModuleIdWithinOneJarFailsNamingBothClasses() { void duplicateModuleIdWithinOneJarFailsNamingBothClasses() {
module("pack.One", "dup:core", NO_MEMBERS, NO_STAGES) module("pack.One", "dup:core", NO_MEMBERS, NO_SETUP)
.alsoModule("pack.Two", "dup:core", NO_MEMBERS, NO_STAGES) .alsoModule("pack.Two", "dup:core", NO_MEMBERS, NO_SETUP)
.writeInto(pack, "both.jar"); .writeInto(pack, "both.jar");
try (var packModules = PackModules.load(pack)) { try (var packModules = PackModules.load(pack)) {
@@ -53,23 +53,19 @@ class PackSchemaTest {
private static final String FLORA = "example:flora"; private static final String FLORA = "example:flora";
private static final String HOST_TYPES = "com.volmit.example.hosttypes"; private static final String HOST_TYPES = "com.volmit.example.hosttypes";
private static final String FLORA_SOURCE = "settings example:flora (module example:flora from modules/flora.jar)"; private static final String FLORA_SOURCE = "settings example:flora (module example:flora from modules/flora.jar)";
private static final String NO_STAGES = ""; private static final String NO_MEMBERS = "";
@TempDir @TempDir
Path packs; Path packs;
private int brokenPacks; private int brokenPacks;
private static final String FLORA_MODULE_MEMBERS = """ private static final String FLORA_SETUP = """
public void register(com.volmit.FeatureRegistry registry) { registry.registerSettings(WindSettings.class);
registry.registerSettings(WindSettings.class); registry.registerSettings(FloraSettings.class);
registry.registerSettings(FloraSettings.class); registry.registerObject(BushSettings.class, bush -> context -> null);
registry.registerObject(BushSettings.class, bush -> context -> null); graph.define(Stage.chunk("example:flora/plant")).when(FloraSettings.class).run(context -> {});
}
"""; """;
private static final String FLORA_INSTALL =
"graph.define(Stage.chunk(\"example:flora/plant\")).when(FloraSettings.class).run((context, flora) -> {});";
private static final String FLORA_SETTINGS = """ private static final String FLORA_SETTINGS = """
package pack.flora; package pack.flora;
@@ -165,7 +161,7 @@ class PackSchemaTest {
"""; """;
private static TestModuleJar flora() { private static TestModuleJar flora() {
return module("pack.flora.FloraModule", FLORA, FLORA_MODULE_MEMBERS, FLORA_INSTALL) return module("pack.flora.FloraModule", FLORA, NO_MEMBERS, FLORA_SETUP)
.source("pack.flora.FloraSettings", FLORA_SETTINGS) .source("pack.flora.FloraSettings", FLORA_SETTINGS)
.source("pack.flora.Season", SEASON) .source("pack.flora.Season", SEASON)
.source("pack.flora.Patch", PATCH) .source("pack.flora.Patch", PATCH)
@@ -314,7 +310,7 @@ class PackSchemaTest {
@Test @Test
void sameModulesGiveTheSameDescriptionWhateverTheJarOrder() { void sameModulesGiveTheSameDescriptionWhateverTheJarOrder() {
var other = module("pack.other.OtherModule", "example:other", NO_STAGES, NO_STAGES); var other = module("pack.other.OtherModule", "example:other", NO_MEMBERS, "");
var first = pack("first"); var first = pack("first");
flora().writeInto(first, "a.jar"); flora().writeInto(first, "a.jar");
other.writeInto(first, "b.jar"); other.writeInto(first, "b.jar");
@@ -381,7 +377,7 @@ class PackSchemaTest {
@Test @Test
void packModulesCannotRegisterHeldTypes() { void packModulesCannotRegisterHeldTypes() {
var jar = module("pack.flora.FloraModule", FLORA, var jar = module("pack.flora.FloraModule", FLORA,
"public void register(com.volmit.FeatureRegistry registry) { registry.registerHeldType(pack.flora.Clamp.class); }", NO_STAGES) NO_MEMBERS, "registry.registerHeldType(pack.flora.Clamp.class);")
.source("pack.flora.Clamp", "package pack.flora; public final class Clamp { private int minimum; }"); .source("pack.flora.Clamp", "package pack.flora; public final class Clamp { private int minimum; }");
var pack = pack("held-by-pack"); var pack = pack("held-by-pack");
jar.writeInto(pack, "flora.jar"); jar.writeInto(pack, "flora.jar");
@@ -394,7 +390,7 @@ class PackSchemaTest {
@Test @Test
void packModulesMayDescribeAHostClassOfAnExposedPackage() { void packModulesMayDescribeAHostClassOfAnExposedPackage() {
var jar = module("pack.flora.FloraModule", FLORA, var jar = module("pack.flora.FloraModule", FLORA,
"public void register(com.volmit.FeatureRegistry registry) { registry.registerHeldType(com.volmit.example.held.ClampSettings.class); }", NO_STAGES) NO_MEMBERS, "registry.registerHeldType(com.volmit.example.held.ClampSettings.class);")
.compileAgainstHostOf(ClampSettings.class); .compileAgainstHostOf(ClampSettings.class);
var pack = pack("held-exposed"); var pack = pack("held-exposed");
jar.writeInto(pack, "flora.jar"); jar.writeInto(pack, "flora.jar");
@@ -420,7 +416,7 @@ class PackSchemaTest {
private IllegalArgumentException loadFailure(ModuleHost host, String body, String... otherSources) { private IllegalArgumentException loadFailure(ModuleHost host, String body, String... otherSources) {
var jar = module("pack.flora.FloraModule", FLORA, var jar = module("pack.flora.FloraModule", FLORA,
"public void register(com.volmit.FeatureRegistry registry) { registry.registerSettings(FloraSettings.class); }", NO_STAGES) NO_MEMBERS, "registry.registerSettings(FloraSettings.class);")
.compileAgainstHostOf(Palette.class) .compileAgainstHostOf(Palette.class)
.source("pack.flora.FloraSettings", """ .source("pack.flora.FloraSettings", """
package pack.flora; package pack.flora;
@@ -453,7 +449,7 @@ class PackSchemaTest {
void settingsWhoseJsonIsOneOptionsValueNameThatOptionAsTheRoot() { void settingsWhoseJsonIsOneOptionsValueNameThatOptionAsTheRoot() {
var pack = pack("rooted"); var pack = pack("rooted");
module("pack.flora.FloraModule", FLORA, module("pack.flora.FloraModule", FLORA,
"public void register(com.volmit.FeatureRegistry registry) { registry.registerSettings(FloraSettings.class); }", NO_STAGES) NO_MEMBERS, "registry.registerSettings(FloraSettings.class);")
.source("pack.flora.FloraSettings", """ .source("pack.flora.FloraSettings", """
package pack.flora; package pack.flora;
@@ -486,7 +482,7 @@ class PackSchemaTest {
void settingsMayHoldTheApisValueTypesWhichAreDescribedLikeSettings() { void settingsMayHoldTheApisValueTypesWhichAreDescribedLikeSettings() {
var pack = pack("values"); var pack = pack("values");
module("pack.flora.FloraModule", FLORA, module("pack.flora.FloraModule", FLORA,
"public void register(com.volmit.FeatureRegistry registry) { registry.registerSettings(FloraSettings.class); }", NO_STAGES) NO_MEMBERS, "registry.registerSettings(FloraSettings.class);")
.source("pack.flora.FloraSettings", """ .source("pack.flora.FloraSettings", """
package pack.flora; package pack.flora;
@@ -558,7 +554,7 @@ class PackSchemaTest {
void defaultsLeaveOutWhatJsonCannotHold() { void defaultsLeaveOutWhatJsonCannotHold() {
var pack = pack("defaults"); var pack = pack("defaults");
module("pack.flora.FloraModule", FLORA, module("pack.flora.FloraModule", FLORA,
"public void register(com.volmit.FeatureRegistry registry) { registry.registerSettings(FloraSettings.class); }", NO_STAGES) NO_MEMBERS, "registry.registerSettings(FloraSettings.class);")
.source("pack.flora.FloraSettings", """ .source("pack.flora.FloraSettings", """
package pack.flora; package pack.flora;
@@ -663,7 +659,7 @@ class PackSchemaTest {
var pack = pack("module-folder"); var pack = pack("module-folder");
module("pack.flora.FloraModule", FLORA, module("pack.flora.FloraModule", FLORA,
"public void register(com.volmit.FeatureRegistry registry) { registry.registerSettings(FloraSettings.class); }", NO_STAGES) NO_MEMBERS, "registry.registerSettings(FloraSettings.class);")
.source("pack.flora.FloraSettings", """ .source("pack.flora.FloraSettings", """
package pack.flora; package pack.flora;
@@ -689,7 +685,7 @@ class PackSchemaTest {
void inheritedOptionsComeBeforeTheirSubclasssOwn() { void inheritedOptionsComeBeforeTheirSubclasssOwn() {
var pack = pack("inherited"); var pack = pack("inherited");
module("pack.flora.FloraModule", FLORA, module("pack.flora.FloraModule", FLORA,
"public void register(com.volmit.FeatureRegistry registry) { registry.registerSettings(FloraSettings.class); }", NO_STAGES) NO_MEMBERS, "registry.registerSettings(FloraSettings.class);")
.source("pack.flora.Base", "package pack.flora; abstract class Base { private int zeta; private int alpha; }") .source("pack.flora.Base", "package pack.flora; abstract class Base { private int zeta; private int alpha; }")
.source("pack.flora.FloraSettings", """ .source("pack.flora.FloraSettings", """
package pack.flora; package pack.flora;
@@ -705,15 +701,13 @@ class PackSchemaTest {
} }
private static final String CASTLE = "example:castle"; private static final String CASTLE = "example:castle";
private static final String CASTLE_MEMBERS = """ private static final String CASTLE_SETUP = """
public void register(com.volmit.FeatureRegistry registry) { registry.registerResourceKind(com.volmit.resource.ResourceKind.of("example:castle/keep", "keeps", Keep.class));
registry.registerResourceKind(com.volmit.resource.ResourceKind.of("example:castle/keep", "keeps", Keep.class)); registry.registerSettings(CastleSettings.class);
registry.registerSettings(CastleSettings.class);
}
"""; """;
private static TestModuleJar castle() { private static TestModuleJar castle() {
return module("pack.castle.CastleModule", CASTLE, CASTLE_MEMBERS, NO_STAGES) return module("pack.castle.CastleModule", CASTLE, NO_MEMBERS, CASTLE_SETUP)
.source("pack.castle.Keep", """ .source("pack.castle.Keep", """
package pack.castle; package pack.castle;
@@ -793,12 +787,10 @@ class PackSchemaTest {
@Test @Test
void packKindsCannotReadIntoHostTypes() { void packKindsCannotReadIntoHostTypes() {
var jar = module("pack.castle.CastleModule", CASTLE, """ var jar = module("pack.castle.CastleModule", CASTLE, NO_MEMBERS, """
public void register(com.volmit.FeatureRegistry registry) { registry.registerResourceKind(com.volmit.resource.ResourceKind.of("example:castle/palette", "palettes",
registry.registerResourceKind(com.volmit.resource.ResourceKind.of("example:castle/palette", "palettes", %s.class));
%s.class)); """.formatted(Palette.class.getName())).compileAgainstHostOf(Palette.class);
}
""".formatted(Palette.class.getName()), NO_STAGES).compileAgainstHostOf(Palette.class);
var pack = pack("castle-host-type"); var pack = pack("castle-host-type");
jar.writeInto(pack, "castle.jar"); jar.writeInto(pack, "castle.jar");
var host = NO_BUILT_INS.exposing(HOST_TYPES).describingHostTypesIn(HOST_TYPES); var host = NO_BUILT_INS.exposing(HOST_TYPES).describingHostTypesIn(HOST_TYPES);
@@ -828,8 +820,7 @@ class PackSchemaTest {
private static com.volmit.IrisModule registering(String id, ResourceKind<?> kind) { private static com.volmit.IrisModule registering(String id, ResourceKind<?> kind) {
return new com.volmit.IrisModule() { return new com.volmit.IrisModule() {
public com.volmit.ModuleInfo info() { return com.volmit.ModuleInfo.of(id, "Kinds", "test"); } public com.volmit.ModuleInfo info() { return com.volmit.ModuleInfo.of(id, "Kinds", "test"); }
public void install(com.volmit.stage.StageGraph graph) {} public void setup(com.volmit.ModuleSetup setup) { setup.registry().registerResourceKind(kind); }
public void register(com.volmit.FeatureRegistry registry) { registry.registerResourceKind(kind); }
}; };
} }
} }
+108 -53
View File
@@ -5,6 +5,7 @@ import com.volmit.FeatureRegistry;
import com.volmit.IrisFeature; import com.volmit.IrisFeature;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.ModuleInfo; import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
import com.volmit.block.BlockState; import com.volmit.block.BlockState;
import com.volmit.config.Feature; import com.volmit.config.Feature;
import com.volmit.config.FeatureSettings.Entry; import com.volmit.config.FeatureSettings.Entry;
@@ -29,6 +30,7 @@ import com.volmit.support.ColumnSettings;
import com.volmit.support.DeclaredSettings; import com.volmit.support.DeclaredSettings;
import com.volmit.support.MemoryEdit; import com.volmit.support.MemoryEdit;
import com.volmit.support.TestContexts; import com.volmit.support.TestContexts;
import com.volmit.support.TestSetups;
import com.volmit.support.TestTerrain; import com.volmit.support.TestTerrain;
import com.volmit.world.BlockPosition; import com.volmit.world.BlockPosition;
import com.volmit.example.placement.SnowModule; import com.volmit.example.placement.SnowModule;
@@ -53,20 +55,16 @@ class StageGraphTest {
private static IrisModule module(String id, Consumer<StageGraph> install) { private static IrisModule module(String id, Consumer<StageGraph> install) {
return new IrisModule() { return new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of(id, "Test module " + id, "1"); } public ModuleInfo info() { return ModuleInfo.of(id, "Test module " + id, "1"); }
public void install(StageGraph graph) { install.accept(graph); } public void setup(ModuleSetup setup) { install.accept(setup.stages()); }
}; };
} }
private static ResolvedGraph resolve(Pipeline pipeline, IrisModule... modules) { private static ResolvedGraph resolve(Pipeline pipeline, IrisModule... modules) {
var builder = new StageGraphBuilder(); return TestSetups.stages(modules).resolve(pipeline);
for (var module : modules) builder.install(DiscoveredModule.builtIn(module));
return builder.resolve(pipeline);
} }
private static List<Class<? extends IrisFeature>> resolveSettings(IrisModule... modules) { private static List<Class<? extends IrisFeature>> resolveSettings(IrisModule... modules) {
var builder = new StageGraphBuilder(); return TestSetups.stages(modules).settingsTypes(type -> false);
for (var module : modules) builder.install(DiscoveredModule.builtIn(module));
return builder.settingsTypes(type -> false);
} }
private static List<String> order(ResolvedGraph graph) { private static List<String> order(ResolvedGraph graph) {
@@ -89,7 +87,11 @@ class StageGraphTest {
} }
private static PlacementOutcome place(ResolvedGraph graph, MemoryEdit edit, ConfiguredSettings settings) { private static PlacementOutcome place(ResolvedGraph graph, MemoryEdit edit, ConfiguredSettings settings) {
return new PlacementRunner(graph).place(twoBlockRequest(), edit, TestContexts.placement(), TestContexts.SEED, settings); return place(graph, edit, settings, StageTimings.NONE);
}
private static PlacementOutcome place(ResolvedGraph graph, MemoryEdit edit, ConfiguredSettings settings, StageTimings timings) {
return new PlacementRunner(graph).place(twoBlockRequest(), edit, TestContexts.placement(), TestContexts.SEED, settings, timings);
} }
@Test @Test
@@ -172,6 +174,21 @@ class StageGraphTest {
assertTrue(graph.unorderedPairs().isEmpty()); assertTrue(graph.unorderedPairs().isEmpty());
} }
@Test
void softEdgesTakeTheStageConstantLikeItsId() {
var late = Stage.placement("test:soft/late");
var early = Stage.placement("test:soft/early");
var last = Stage.placement("test:soft/last");
var graph = resolve(Pipeline.PLACEMENT, module("test:soft", stages -> {
stages.define(early).softAfter(late).run(context -> {});
stages.define(last).run(context -> {});
stages.define(late).softBefore(last).run(context -> {});
}));
assertEquals(List.of("test:soft/late", "test:soft/early", "test:soft/last"), order(graph));
assertEquals(List.of(new StageEdge(late.id(), early.id(), StageEdge.Kind.SOFT)), graph.stages().get(1).incoming());
}
@Test @Test
void missingRequirementNamesBothStagesAndTheirModules() { void missingRequirementNamesBothStagesAndTheirModules() {
var absent = Stage.placement("other:gone/absent"); var absent = Stage.placement("other:gone/absent");
@@ -203,7 +220,7 @@ class StageGraphTest {
stages.define(a).requires(b).run(context -> {}); stages.define(a).requires(b).run(context -> {});
stages.define(c).requires(a).run(context -> {}); stages.define(c).requires(a).run(context -> {});
}), }),
module("other:second", stages -> stages.define(b).softAfter(c.ref()).run(context -> {})))); module("other:second", stages -> stages.define(b).softAfter(c).run(context -> {}))));
assertEquals("Stage cycle in pipeline PLACEMENT: other:second/b (module other:second) -[required]-> " assertEquals("Stage cycle in pipeline PLACEMENT: other:second/b (module other:second) -[required]-> "
+ "test:first/a (module test:first) -[required]-> test:first/c (module test:first) -[soft]-> " + "test:first/a (module test:first) -[required]-> test:first/c (module test:first) -[soft]-> "
@@ -232,31 +249,30 @@ class StageGraphTest {
assertTrue(duplicate.getMessage().contains("already defined by module test:one"), duplicate.getMessage()); assertTrue(duplicate.getMessage().contains("already defined by module test:one"), duplicate.getMessage());
var module = module("test:twice", stages -> {}); var module = module("test:twice", stages -> {});
var builder = new StageGraphBuilder(); var builder = TestSetups.stages(module);
builder.install(DiscoveredModule.builtIn(module)); assertThrows(IllegalArgumentException.class, () -> TestSetups.install(builder, DiscoveredModule.builtIn(module)));
assertThrows(IllegalArgumentException.class, () -> builder.install(DiscoveredModule.builtIn(module)));
} }
@Test @Test
void settingsMustBeOwnedByAModuleThatNamesThem() { void settingsMustBeOwnedByAModuleThatNamesThem() {
var foreign = assertThrows(IllegalArgumentException.class, () -> resolveSettings( var foreign = assertThrows(IllegalArgumentException.class, () -> resolveSettings(
module("other:user", stages -> stages.define(Stage.placement("other:user/work")).when(Toggle.class).run((context, toggle) -> {})))); module("other:user", stages -> stages.define(Stage.placement("other:user/work")).when(Toggle.class).run(context -> {}))));
assertEquals("Settings type " + Toggle.class.getName() + " has feature id test:owner/toggle, which none of the modules " assertEquals("Settings type " + Toggle.class.getName() + " has feature id test:owner/toggle, which none of the modules "
+ "naming it in when(...) owns: other:user from host classpath. A feature id is the id of the module that owns " + "naming it in when(...) owns: other:user from host classpath. A feature id is the id of the module that owns "
+ "the settings, such as other:user, or starts with it and '/', such as other:user/toggle", foreign.getMessage()); + "the settings, such as other:user, or starts with it and '/', such as other:user/toggle", foreign.getMessage());
var sameNamespace = assertThrows(IllegalArgumentException.class, () -> resolveSettings( var sameNamespace = assertThrows(IllegalArgumentException.class, () -> resolveSettings(
module("test:user", stages -> stages.define(Stage.placement("test:user/work")).when(Toggle.class).run((context, toggle) -> {})))); module("test:user", stages -> stages.define(Stage.placement("test:user/work")).when(Toggle.class).run(context -> {}))));
assertTrue(sameNamespace.getMessage().contains("none of the modules naming it in when(...) owns: test:user from host classpath"), assertTrue(sameNamespace.getMessage().contains("none of the modules naming it in when(...) owns: test:user from host classpath"),
sameNamespace.getMessage()); sameNamespace.getMessage());
var shared = resolveSettings( var shared = resolveSettings(
module("test:owner", stages -> stages.define(Stage.placement("test:owner/work")).when(Toggle.class).run((context, toggle) -> {})), module("test:owner", stages -> stages.define(Stage.placement("test:owner/work")).when(Toggle.class).run(context -> {})),
module("other:user", stages -> stages.define(Stage.placement("other:user/work")).when(Toggle.class).run((context, toggle) -> {}))); module("other:user", stages -> stages.define(Stage.placement("other:user/work")).when(Toggle.class).run(context -> {})));
assertEquals(List.of(Toggle.class), shared); assertEquals(List.of(Toggle.class), shared);
var snowOnMoss = resolveSettings(new SnowModule(), module("example:moss", stages -> var snowOnMoss = resolveSettings(new SnowModule(), module("example:moss", stages ->
stages.define(Stage.placement("example:moss/on-snow")).when(SnowSettings.class).run((context, snow) -> {}))); stages.define(Stage.placement("example:moss/on-snow")).when(SnowSettings.class).run(context -> {})));
assertTrue(snowOnMoss.contains(SnowSettings.class), "moss may condition on iris:snow, which iris:snow owns"); assertTrue(snowOnMoss.contains(SnowSettings.class), "moss may condition on iris:snow, which iris:snow owns");
} }
@@ -303,7 +319,7 @@ class StageGraphTest {
} }
@Test @Test
void invalidDeclarationsFailWhileInstalling() { void invalidDeclarationsFailDuringSetup() {
assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT, module("test:self", stages -> { assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT, module("test:self", stages -> {
var self = Stage.placement("test:self/work"); var self = Stage.placement("test:self/work");
stages.define(self).requires(self).run(context -> {}); stages.define(self).requires(self).run(context -> {});
@@ -314,10 +330,10 @@ class StageGraphTest {
definition.when(Toggle.class); definition.when(Toggle.class);
}))); })));
assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT, module("test:plain", stages -> assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT, module("test:plain", stages ->
stages.define(Stage.placement("test:plain/work")).when(Unannotated.class).run((context, settings) -> {})))); stages.define(Stage.placement("test:plain/work")).when(Unannotated.class).run(context -> {}))));
var retained = new ArrayList<StageGraph>(); var retained = new ArrayList<StageGraph>();
new StageGraphBuilder().install(DiscoveredModule.builtIn(module("test:retained", retained::add))); TestSetups.stages(module("test:retained", retained::add));
assertThrows(IllegalStateException.class, () -> retained.getFirst().define(Stage.placement("test:retained/late"))); assertThrows(IllegalStateException.class, () -> retained.getFirst().define(Stage.placement("test:retained/late")));
} }
@@ -366,7 +382,7 @@ class StageGraphTest {
var unrelated = Stage.placement("test:cascade/unrelated"); var unrelated = Stage.placement("test:cascade/unrelated");
var events = new ArrayList<String>(); var events = new ArrayList<String>();
var graph = resolve(Pipeline.PLACEMENT, module("test:cascade", stages -> { var graph = resolve(Pipeline.PLACEMENT, module("test:cascade", stages -> {
stages.define(toggled).when(Toggle.class).produce((context, toggle) -> { stages.define(toggled).when(Toggle.class).produce(context -> {
events.add("toggled"); events.add("toggled");
return 1; return 1;
}); });
@@ -381,6 +397,64 @@ class StageGraphTest {
assertEquals(List.of("toggled", "dependent:1", "unrelated"), events); assertEquals(List.of("toggled", "dependent:1", "unrelated"), events);
} }
@Test
void aConditionedStageReadsOnlyTheSettingsItIsConditionedOn() {
var configured = new ArrayList<Object>();
var refusals = new ArrayList<String>();
var graph = resolve(Pipeline.PLACEMENT, module("test:owner", stages -> {
stages.define(Stage.placement("test:owner/toggled")).when(Toggle.class).run(context -> {
configured.add(context.configured(Toggle.class).getFirst().value());
refusals.add(assertThrows(IllegalStateException.class, () -> context.configured(SnowSettings.class)).getMessage());
});
stages.define(Stage.placement("test:owner/plain")).run(context -> refusals.add(
assertThrows(IllegalStateException.class, () -> context.configured(Toggle.class)).getMessage()));
}));
var toggle = new Toggle();
place(graph, flatEdit(), ConfiguredSettings.placement(ResourceId.parse("test:placement"), toggle));
assertEquals(List.of(toggle), configured);
assertEquals(List.of(
"Stage test:owner/plain read configured(Toggle) but is not conditioned on it; add when(Toggle.class) to its"
+ " definition, or read other settings through settings()",
"Stage test:owner/toggled read configured(SnowSettings) but is not conditioned on it; add when(SnowSettings.class)"
+ " to its definition, or read other settings through settings()"), refusals);
}
@Test
void aProducerThatRejectsTheAttemptMayReturnNull() {
var graph = resolve(Pipeline.PLACEMENT, module("test:reject", stages ->
stages.define(Stage.placement("test:reject/height", Integer.class)).produce(context -> {
context.reject("no ground");
return null;
})));
var edit = flatEdit();
var outcome = place(graph, edit, ConfiguredSettings.none());
assertEquals(PlacementOutcome.Status.REJECTED, outcome.status());
assertEquals(Optional.of("no ground"), outcome.rejection());
assertFalse(edit.committed());
}
@Test
void placementTimesEachStageThatRanOnceAndABlockStageOncePerPass() {
var prepare = Stage.placement("test:timed/prepare");
var write = Stage.placementBlock("test:timed/write");
var graph = resolve(Pipeline.PLACEMENT, module("test:timed", stages -> {
stages.define(prepare).run(context -> {});
stages.define(write).requires(prepare).run(context -> {});
stages.define(Stage.placement("test:timed/off")).when(Toggle.class).run(context -> {});
}));
var timed = new ArrayList<String>();
place(graph, flatEdit(), ConfiguredSettings.none(), (stage, nanos) -> {
assertTrue(nanos >= 0);
timed.add(stage.stage().id().toString());
});
assertEquals(List.of("test:timed/prepare", "test:timed/write"), timed);
}
@Test @Test
void skippedBlocksAreHiddenFromLaterStagesOfThePass() { void skippedBlocksAreHiddenFromLaterStagesOfThePass() {
var written = new ArrayList<Integer>(); var written = new ArrayList<Integer>();
@@ -510,18 +584,12 @@ class StageGraphTest {
} }
@Test @Test
void onlyMantleStagesWorkOutTheirReachAndNeverANegativeOne() { void aWorkedOutReachIsNeverNegativeAndIsDeclaredOnce() {
var negative = LoadedModules.load(List.of(DiscoveredModule.builtIn(module("test:reach", stages -> var negative = LoadedModules.load(List.of(DiscoveredModule.builtIn(module("test:reach", stages ->
stages.define(Stage.mantle("test:reach/carve")).reach(settings -> -1).run(context -> {})))), Map.of(), Set.of(), Set.of()); stages.define(Stage.mantle("test:reach/carve")).reach(settings -> -1).run(context -> {})))), Map.of(), Set.of(), Set.of());
var failure = assertThrows(IllegalStateException.class, () -> negative.mantle().stages().getFirst().reachBlocks(DeclaredSettings.NONE)); var failure = assertThrows(IllegalStateException.class, () -> negative.mantle().stages().getFirst().reachBlocks(DeclaredSettings.NONE));
assertEquals("Stage test:reach/carve of module test:reach worked out a negative reach of -1 blocks for this pack", failure.getMessage()); assertEquals("Stage test:reach/carve of module test:reach worked out a negative reach of -1 blocks for this pack", failure.getMessage());
var placement = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT, module("test:reach", stages ->
stages.define(Stage.placement("test:reach/work")).reach(settings -> 1).run(context -> {}))));
assertEquals("Stage test:reach/work (module test:reach) is a placement stage and declares a reach worked out when the pack"
+ " loads, which only mantle stages may; declare a number of blocks with reach(blocks)", placement.getMessage());
assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.CHUNK, module("test:reach", stages ->
stages.define(Stage.chunk("test:reach/work")).reach(settings -> 0).run(context -> {}))));
var twice = assertThrows(IllegalStateException.class, () -> resolve(Pipeline.MANTLE, module("test:reach", stages -> var twice = assertThrows(IllegalStateException.class, () -> resolve(Pipeline.MANTLE, module("test:reach", stages ->
stages.define(Stage.mantle("test:reach/carve")).reach(2).reach(settings -> 1).run(context -> {})))); stages.define(Stage.mantle("test:reach/carve")).reach(2).reach(settings -> 1).run(context -> {}))));
assertEquals("Stage test:reach/carve (module test:reach) already declares a reach of 2 blocks", twice.getMessage()); assertEquals("Stage test:reach/carve (module test:reach) already declares a reach of 2 blocks", twice.getMessage());
@@ -533,7 +601,7 @@ class StageGraphTest {
var follower = Stage.mantle("test:owner/follower"); var follower = Stage.mantle("test:owner/follower");
var ran = new ArrayList<String>(); var ran = new ArrayList<String>();
var graph = resolve(Pipeline.MANTLE, module("test:owner", stages -> { var graph = resolve(Pipeline.MANTLE, module("test:owner", stages -> {
stages.define(toggled).when(Toggle.class).run((context, entries) -> ran.add("toggled")); stages.define(toggled).when(Toggle.class).run(context -> ran.add("toggled"));
stages.define(follower).requires(toggled).run(context -> ran.add("follower")); stages.define(follower).requires(toggled).run(context -> ran.add("follower"));
})); }));
var runner = new MantleRunner(graph); var runner = new MantleRunner(graph);
@@ -541,14 +609,18 @@ class StageGraphTest {
var nowhere = TestContexts.mantle(0, 0, ColumnSettings.NONE, null); var nowhere = TestContexts.mantle(0, 0, ColumnSettings.NONE, null);
var oneColumn = TestContexts.mantle(0, 0, new ColumnSettings((x, z) -> x == 15 && z == 0 ? List.of(toggle) : List.of()), null); var oneColumn = TestContexts.mantle(0, 0, new ColumnSettings((x, z) -> x == 15 && z == 0 ? List.of(toggle) : List.of()), null);
runner.generate(follower, nowhere, TestContexts.SEED); var timed = new ArrayList<String>();
StageTimings timings = (stage, nanos) -> timed.add(stage.stage().id().toString());
runner.generate(follower, nowhere, TestContexts.SEED, timings);
assertEquals(List.of(), ran, "a stage whose requirement is inactive in the chunk is inactive too"); assertEquals(List.of(), ran, "a stage whose requirement is inactive in the chunk is inactive too");
runner.generate(follower, oneColumn, TestContexts.SEED); runner.generate(follower, oneColumn, TestContexts.SEED, timings);
assertEquals(List.of("follower"), ran, "only the asked stage runs; its requirement ran in its own pass"); assertEquals(List.of("follower"), ran, "only the asked stage runs; its requirement ran in its own pass");
runner.generate(toggled, oneColumn, TestContexts.SEED); runner.generate(toggled, oneColumn, TestContexts.SEED, timings);
assertEquals(List.of("follower", "toggled"), ran); assertEquals(List.of("follower", "toggled"), ran);
assertEquals(List.of("test:owner/follower", "test:owner/toggled"), timed, "only stages that ran are timed");
var foreign = assertThrows(IllegalArgumentException.class, var foreign = assertThrows(IllegalArgumentException.class,
() -> runner.generate(Stage.mantle("test:owner/absent"), nowhere, TestContexts.SEED)); () -> runner.generate(Stage.mantle("test:owner/absent"), nowhere, TestContexts.SEED, StageTimings.NONE));
assertEquals("Stage test:owner/absent is not a stage of this mantle graph", foreign.getMessage()); assertEquals("Stage test:owner/absent is not a stage of this mantle graph", foreign.getMessage());
} }
@@ -578,30 +650,13 @@ class StageGraphTest {
+ " but it is registered as java.lang.Integer", mismatch.getMessage()); + " but it is registered as java.lang.Integer", mismatch.getMessage());
} }
@Test
void chunkStagesNeitherReachBeyondTheirChunkNorWriteTheMantle() {
var depth = new MantleKey<>("test:reach/depth", Integer.class);
var carve = Stage.chunk("test:reach/carve");
var reach = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.CHUNK,
module("test:reach", stages -> stages.define(carve).reach(8).run(context -> {}))));
assertEquals("Stage test:reach/carve (module test:reach) is a chunk stage and declares a reach of 8 blocks, but chunk"
+ " stages write only their own chunk and read the mantle; define work that writes the mantle or reaches beyond"
+ " its chunk as a mantle stage (Stage.mantle), which runs before the chunks it reaches", reach.getMessage());
var writes = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.CHUNK,
module("test:reach", stages -> stages.define(carve).writesMantle(depth).run(context -> {}))));
assertTrue(writes.getMessage().startsWith("Stage test:reach/carve (module test:reach) is a chunk stage and declares mantle writes"),
writes.getMessage());
assertDoesNotThrow(() -> resolve(Pipeline.CHUNK, module("test:reach", stages -> stages.define(carve).reach(0).run(context -> {}))));
}
/** {@code module}, also registering {@code layers}. */ /** {@code module}, also registering {@code layers}. */
private static IrisModule withMantle(IrisModule module, MantleKey<?>... layers) { private static IrisModule withMantle(IrisModule module, MantleKey<?>... layers) {
return new IrisModule() { return new IrisModule() {
public ModuleInfo info() { return module.info(); } public ModuleInfo info() { return module.info(); }
public void install(StageGraph graph) { module.install(graph); } public void setup(ModuleSetup setup) {
public void register(FeatureRegistry registry) { module.setup(setup);
for (var layer : layers) registerLayer(registry, layer); for (var layer : layers) registerLayer(setup.registry(), layer);
} }
}; };
} }
@@ -2,6 +2,7 @@ package com.volmit.host;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.ModuleInfo; import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
import com.volmit.block.BlockState; import com.volmit.block.BlockState;
import com.volmit.mantle.BlockBox; import com.volmit.mantle.BlockBox;
import com.volmit.object.GeneratedObject; import com.volmit.object.GeneratedObject;
@@ -14,6 +15,7 @@ import com.volmit.stage.StageContext;
import com.volmit.stage.StageGraph; import com.volmit.stage.StageGraph;
import com.volmit.support.MemoryEdit; import com.volmit.support.MemoryEdit;
import com.volmit.support.TestContexts; import com.volmit.support.TestContexts;
import com.volmit.support.TestSetups;
import com.volmit.support.TestTerrain; import com.volmit.support.TestTerrain;
import com.volmit.world.BlockPosition; import com.volmit.world.BlockPosition;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@@ -38,14 +40,12 @@ class StageStreamsTest {
private static IrisModule module(String id, Consumer<StageGraph> install) { private static IrisModule module(String id, Consumer<StageGraph> install) {
return new IrisModule() { return new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of(id, "Test module " + id, "1"); } public ModuleInfo info() { return ModuleInfo.of(id, "Test module " + id, "1"); }
public void install(StageGraph graph) { install.accept(graph); } public void setup(ModuleSetup setup) { install.accept(setup.stages()); }
}; };
} }
private static ResolvedGraph resolve(Pipeline pipeline, IrisModule... modules) { private static ResolvedGraph resolve(Pipeline pipeline, IrisModule... modules) {
var builder = new StageGraphBuilder(); return TestSetups.stages(modules).resolve(pipeline);
for (var module : modules) builder.install(DiscoveredModule.builtIn(module));
return builder.resolve(pipeline);
} }
private static PlacementRequest request() { private static PlacementRequest request() {
@@ -57,7 +57,7 @@ class StageStreamsTest {
private Map<String, List<Long>> place(ResolvedGraph graph, long invocationSeed) { private Map<String, List<Long>> place(ResolvedGraph graph, long invocationSeed) {
draws.clear(); draws.clear();
var outcome = new PlacementRunner(graph).place(request(), new MemoryEdit(new TestTerrain((x, z) -> 5)), var outcome = new PlacementRunner(graph).place(request(), new MemoryEdit(new TestTerrain((x, z) -> 5)),
TestContexts.placement(), invocationSeed, ConfiguredSettings.none()); TestContexts.placement(), invocationSeed, ConfiguredSettings.none(), StageTimings.NONE);
assertTrue(outcome.isPlaced()); assertTrue(outcome.isPlaced());
return Map.copyOf(draws); return Map.copyOf(draws);
} }
@@ -131,7 +131,7 @@ class StageStreamsTest {
var graph = resolve(Pipeline.CHUNK, module("a:mod", stages -> stages.define(Stage.chunk("a:mod/ores")) var graph = resolve(Pipeline.CHUNK, module("a:mod", stages -> stages.define(Stage.chunk("a:mod/ores"))
.run(context -> drawn.add((long) context.random().nextInt(BOUND))))); .run(context -> drawn.add((long) context.random().nextInt(BOUND)))));
new ChunkRunner(graph).generate(TestContexts.generation(Map.of()), TestContexts.SEED); new ChunkRunner(graph).generate(TestContexts.generation(Map.of()), TestContexts.SEED, StageTimings.NONE);
assertEquals(firstDraws(TestContexts.SEED, "a:mod/ores", 1), drawn); assertEquals(firstDraws(TestContexts.SEED, "a:mod/ores", 1), drawn);
} }
@@ -38,7 +38,7 @@ public final class TestModuleJar {
private final List<Path> classpath = new ArrayList<>(List.of(classesOf(IrisModule.class))); private final List<Path> classpath = new ArrayList<>(List.of(classesOf(IrisModule.class)));
private final List<String> compilerExports = new ArrayList<>(); private final List<String> compilerExports = new ArrayList<>();
/** An entry class with the given module id whose install body may use {@code graph}. */ /** An entry class with the given module id whose setup body may use {@code graph} and {@code registry}. */
public static TestModuleJar module(String className, String moduleId, String members, String install) { public static TestModuleJar module(String className, String moduleId, String members, String install) {
return module(className, moduleId, List.of(), members, install); return module(className, moduleId, List.of(), members, install);
} }
@@ -198,7 +198,11 @@ public final class TestModuleJar {
public ModuleInfo info() { return %s; } public ModuleInfo info() { return %s; }
public void install(StageGraph graph) { %s } public void setup(com.volmit.ModuleSetup setup) {
StageGraph graph = setup.stages();
com.volmit.FeatureRegistry registry = setup.registry();
%s
}
} }
""".formatted(className.substring(0, dot), className.substring(dot + 1), members, info, install); """.formatted(className.substring(0, dot), className.substring(dot + 1), members, info, install);
} }
@@ -0,0 +1,27 @@
package com.volmit.support;
import com.volmit.IrisModule;
import com.volmit.host.DiscoveredModule;
import com.volmit.host.ModuleRegistry;
import com.volmit.host.ModuleSetups;
import com.volmit.host.StageGraphBuilder;
/** Sets modules up into a stage graph for tests that only need their stages; registrations go to a registry of
* their own.
*/
public final class TestSetups {
private TestSetups() {}
/** A builder with every module set up as a built-in. */
public static StageGraphBuilder stages(IrisModule... modules) {
var builder = new StageGraphBuilder();
for (var module : modules) {
install(builder, DiscoveredModule.builtIn(module));
}
return builder;
}
public static void install(StageGraphBuilder builder, DiscoveredModule module) {
ModuleSetups.run(module, builder, new ModuleRegistry());
}
}
@@ -2,9 +2,9 @@ package example.builtin;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.ModuleInfo; import com.volmit.ModuleInfo;
import com.volmit.ModuleSetup;
import com.volmit.stage.PlacementStage; import com.volmit.stage.PlacementStage;
import com.volmit.stage.Stage; import com.volmit.stage.Stage;
import com.volmit.stage.StageGraph;
/** A built-in module outside the API's package, like the engine modules inside Iris. Pack jars can /** A built-in module outside the API's package, like the engine modules inside Iris. Pack jars can
* require its stages only when the host exposes this package. * require its stages only when the host exposes this package.
@@ -18,7 +18,7 @@ public final class CarveModule implements IrisModule {
} }
@Override @Override
public void install(StageGraph graph) { public void setup(ModuleSetup setup) {
graph.define(CLEAR).run(context -> {}); setup.stages().define(CLEAR).run(context -> {});
} }
} }