diff --git a/CONTRACTS.md b/CONTRACTS.md index 578c8b688..ffb5bf56b 100644 --- a/CONTRACTS.md +++ b/CONTRACTS.md @@ -16,7 +16,8 @@ types that carry them and lists what the Iris adapter still owes. | Module entry point | `IrisModule.info()`, `IrisModule.setup(ModuleSetup)` (`stages()`, `registry()`, `log()`), host `ModuleSetups.run` | | Module-owned work and ordering | `Stage`, `StageRef`, one stage definition type per pipeline, `requires`/`softAfter`/`softBefore` | | Activation by configuration | `when(settingsType)`, `StageContext.configured(settingsType)`, host `ConfiguredSettings` (entries per declared `@Feature` type; any column of a chunk) | -| Stacked settings levels, read per column | `FeatureSettings.at(type, x, z)`, `FeatureSettings.Entry` (level, source, value) | +| Stacked settings levels, read per column | `Level`, `FeatureSettings.at(type, x, z)` and `declaredInChunk(type, chunkX, chunkZ)`, `SettingsStack` (`values`, `dimension`, `level`, `mostSpecific`), `FeatureSettings.Entry` (level, source, value) | +| Chunk coordinates in stages | `ChunkContext` (`chunkX`, `chunkZ`, `centreX`, `centreZ`, `area`), shared by `GenerationContext` and `MantleGenerationContext` | | Typed results between modules | stage outputs, `StageContext.output` | | Per-block work with single-pass cost | `BlockStage`, fused block passes | | Pack-load validation and diagnostics | host `StageGraphBuilder`, `ResolvedGraph`, `LoadedModules` | @@ -34,7 +35,7 @@ types that carry them and lists what the Iris adapter still owes. | Module-owned pack resources | `ResourceKind`, `FeatureRegistry.registerResourceKind`, `@ResourceRef`, host `ModuleHost.reservingFolders`, `FeatureCatalog.resourceKinds()`, `ResourceKindSchema`, `ValueKind.ResourceReferenceKind` | | Module-owned pack checks | `Validator`, `ValidationContext`, `Problem`, `Severity`, `Subject`, `FeatureRegistry.registerValidator`, host `FeatureCatalog.validators()` | | Per-world module state | `PackWorld` (`state`), `InvocationContext.world()`, host `WorldStates` | -| Module lifecycle across loads, hotloads and reloads | `ModuleLifecycle`, `FeatureRegistry.registerLifecycle`, host `FeatureCatalog.lifecycles()`, `LifecycleRunner` | +| Module lifecycle across loads, hotloads and reloads | `ModuleLifecycle`, `PackContext`, `FeatureRegistry.registerLifecycle`, host `FeatureCatalog.lifecycles()`, `LifecycleRunner` | | Host questions answered by modules | `@Service`, `Providers`, `FeatureRegistry.registerService`, host `FeatureCatalog.services(type)` / `service(type)`; services `ObjectsAt`, `StructureLocator` (`LocateResult`), `SaplingGrowth`, `Loot`, `BlockDrops`, `EntitySpawns`, `CaveBiomes`, `AmbientEffects`, `VanillaFeatures` (`DecorationStep`); values `ItemDrop`, `EntitySpec`, `ItemRegistry` (`PackResources.items()`) | | Terrain and settings sampling | `TerrainSampler`, `BiomeSample`, `TerrainSample`, `FeatureSettings` | | Dense chunk output | `Hunk`, `GenerationContext.hunk`, reference `ArrayHunk` | @@ -141,7 +142,12 @@ running Iris is the pack publisher's responsibility. settings the biome declares itself (empty when it declares none or is unknown); `BlockRegistry.oreFor` answers from the platform. - Answer `TerrainSampler.fluidHeight()` (the height the host fills with fluid below) and `upperDimensionY(x, z)` (where a dimension stacked above begins; empty when none does). `surfaceY(x, z)` equals `column(x, z).surfaceY()`; a host - overrides it when the height costs less than the whole column. + overrides it when the height costs less than the whole column. `surfaceHeight(x, z)` must equal + `(int) Math.round(surfaceY(x, z))`. +- Answer `FeatureSettings.at` in level order with no allocation a column read can avoid, and `declaredInChunk` with + exactly the distinct entries (by level and source) of the chunk's 16 by 16 columns, in the order the default gives: + level order, then the order the first column holding an entry was found, columns by X and then Z. Answer it from the + regions and biomes the chunk holds where the host knows them. - Make placement edits atomic across blocks, block entities, markers and mantle in generation storage. Abort chunk publication when any stage fails. - Preserve unknown persisted mantle layers or fail explicitly. @@ -188,6 +194,8 @@ running Iris is the pack publisher's responsibility. - Keep one `PackWorld` per world and pack snapshot and pass it to every invocation of the world (`InvocationContext.world()`), to service calls and to hooks. Use `WorldStates` (or the same rules) for its store. + A placement a tool makes outside those worlds (a studio paste) gets a `PackWorld` of its own: the pack's resources + and settings, a seed the host picks, a store closed when the placement ends, and no hooks. `world()` never throws. - Call the hooks with `LifecycleRunner`: `packLoaded` once per pack snapshot before its first world starts, `worldStarted` before the world generates anything, `warmUp` after it (on a thread of your choice, and wait for it before the world's first generation; report a failure naming the module and carry on), `worldStopped` when it stops. On a hotload, and when the pack's diff --git a/DESIGN.md b/DESIGN.md index eafc9699d..4d8228421 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -368,16 +368,17 @@ The graph is resolved once per pack load. Activation is decided per invocation: 1. The invocation gets `ConfiguredSettings`: for each settings type, the entries configured for it, in level order. For a placement the host passes the placement's own declarations. For a chunk or mantle - invocation the runner collects them itself from `FeatureSettings`: every distinct entry, by level and - source, of the chunk's 16 by 16 columns. + invocation the runner asks `FeatureSettings.declaredInChunk` for each conditioned type: every distinct + entry, by level and source, of the chunk's 16 by 16 columns. Its default reads every column; a host + that knows the regions and biomes of a chunk answers from those instead (Iris does). 2. The invocation looks up each distinct `when` type once. 3. One pass in resolved order marks a stage active when its settings have an entry (or it has no condition) and every stage it requires is active. So an inactive requirement deactivates its dependents. That is not an error. Soft edges never affect activation. The cost per invocation is two small arrays and one pass over stages and -REQUIRED edges, plus, for chunks, one settings read per column and conditioned type. The body reads -the entries with `ctx.configured(type)`, a never-empty `List>`. Only the +REQUIRED edges, plus, for chunks, one `declaredInChunk` per conditioned type. The body reads +the entries with `ctx.configured(type)`, a never-empty `SettingsStack`. Only the stage's own `when` type is readable that way; any other type, or a stage without a condition, throws and names `when(...)` and `settings()` as the fixes. Bodies take only the context, so one definition type per pipeline covers conditioned and unconditioned stages alike. @@ -388,15 +389,20 @@ and a placement that configures a base and a subclass value configures the type A chunk stage is active when any column of the chunk configures it, so a biome border inside a chunk never hides a feature on either side. The body then reads `ctx.settings().at(type, x, z)` per column, -or at the chunk's centre column (local 7, 7) for behaviour that happens once per chunk. +or at the chunk's centre column (`ChunkContext.centreX()`/`centreZ()`, local 7, 7) for behaviour that +happens once per chunk. `ChunkContext`, shared by chunk and mantle contexts, also names the chunk +(`chunkX()`, `chunkZ()`) and its `area()`, so no module hand-builds chunk boxes or shifts by 4. ### Settings levels -Settings are declared at levels: the dimension, a region, a biome (the column's surface biome) and a -placement. `FeatureSettings.at(type, x, z)` returns one entry per level that declares the type at that -column, in that order, each with its level, the declaring resource and the value. Levels stack: there is -no "most specific wins" and no field merge. A module decides what several entries mean: deposits run -once per entry, a surface block may take the most specific. The alternatives each hide a decision from +Settings are declared at levels (`com.volmit.config.Level`): `DIMENSION`, `REGION`, `BIOME` (the +column's surface biome) and `PLACEMENT`. `@Feature(targets = ...)` names the levels a type may be +declared at, and the same enum orders the entries. `FeatureSettings.at(type, x, z)` returns a +`SettingsStack`: one entry per level that declares the type at that column, in that order, each with its +level, the declaring resource and the value. Levels stack: there is no "most specific wins" and no field +merge. A module decides what several entries mean: deposits run once per entry (`values()`), a surface +block may take the most specific (`mostSpecific()`), a dimension-wide setting reads `dimension()`. The +stack offers those picks so modules do not each write their own; it never merges. The alternatives each hide a decision from the module: overriding would make a biome's deposits silently drop the dimension's, merging would need a rule per field. Something spanning several columns reads at one origin column: per chunk the centre column, per placed object the column it is anchored at. Cave biomes are not a level. @@ -514,7 +520,8 @@ the host from publishing the chunk. A chunk stage writes only its chunk but may look around it: its `TerrainSampler` covers the chunk and the 16 blocks around it, so a stage that smooths a surface reads its neighbors' heights (`surfaceY`, which spares the host the slope -that `column` works out). The sampler also gives the dimension's +that `column` works out, or `surfaceHeight`, the same height rounded to a block, which every stage placing on the +surface used to write out as `(int) Math.round(surfaceY(x, z))`). The sampler also gives the dimension's `fluidHeight()` and, per column, `upperDimensionY` where a dimension stacked above begins; a stage writes nothing at or above it. The mantle's `blocks()` are the blocks placements wrote into the mantle for chunks to take over (objects, structures): a chunk stage copies them into its chunk, as Iris's `iris:matter` does. They are the host's layer, so they @@ -827,7 +834,7 @@ Why these lines: builds the noise. It hangs off `PackResources`, like `blocks()`, because noise depends on the pack snapshot (its expressions and image maps), and every context that has resources (stages, validators, hooks) can build noise. The host caches per snapshot, so stage bodies may ask for a sampler per invocation. The seed is - the module's: noise lines up across chunks only when it comes from `worldSeed()`, not a stage's stream. + the module's: noise lines up across chunks only when it comes from `world().seed()`, not a stage's stream. - **`NoiseSampler` moved to `com.volmit.noise`** and gained a two-dimensional `sample(x, z)`: Iris's noise gives different fields in two and three dimensions, and most features sample columns. - **`NoiseSampler.scaled(factor)`** is a style with an extra coordinate scale that the host folds into its generator: a cave @@ -979,20 +986,25 @@ each world a state store and tells modules when worlds start and stop. - **The world.** `PackWorld` is one world generating with one pack snapshot: seed, resources, the settings of its dimension and of the regions and biomes it can reach (what mantle reaches see), and `state(type, create)`. - `InvocationContext.world()` hands it to every stage; services take it as their first argument; hooks get it. A - placement outside any world, such as a studio paste, has none and throws. + `InvocationContext.world()` hands it to every stage and never throws; services take it as their first argument; + hooks get it. The context once also carried `worldSeed()` and `resources()`, copies of the world's, kept because a + studio paste had no world; the host now builds a world for each placement a tool makes outside the worlds it + generates (the pack's resources and settings, a seed it picks, a state store closed when the placement ends, no + hooks), so the copies are gone and the world is the one place for seed and resources. - **The store.** One instance per type, keyed by class: a class is compile-checked and module-owned, so two modules never share an entry by accident, and it matches the internal `state(Class, factory)` Iris already used. A factory runs once per type even when threads race (the others wait and get the same instance); it may ask for other state on its own thread, since creation holds one re-entrant lock, and asking for the type being created fails naming the chain instead of recursing or deadlocking. A factory that throws keeps nothing. Reads of existing state take no lock. `WorldStates` is the reference store hosts use. -- **Hooks.** `ModuleLifecycle` has `packLoaded(resources, settings)`, `worldStarted(world)`, `warmUp(world)` and +- **Hooks.** `ModuleLifecycle` has `packLoaded(pack)`, `worldStarted(world)`, `warmUp(world)` and `worldStopped(world)`, each a no-op by default, registered with `FeatureRegistry.registerLifecycle` like validators, so the host knows the owning module for errors and orders hooks by module id. A module class may implement it and register itself. `packLoaded` runs once per snapshot before its first world starts; a pack that is only validated or edited in studio - is not loaded in this sense. The settings it gets are the whole pack's, as validators see them. + is not loaded in this sense. Its `PackContext` gives the snapshot's resources, the whole pack's settings (as + validators see them) and the module's log; a context rather than two arguments, so the hook can log without the + module keeping its setup log in a field. - **Hotload semantics.** A world's state lives as long as the world runs with one pack snapshot. A hotload stops the world and starts a new one with the reloaded pack; so does a reload of the pack's resources while the world runs, such as a tool rewriting structure files. State therefore never outlives the resources it was built from, and @@ -1031,8 +1043,10 @@ 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 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 - 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 + and lifecycle hooks, `PackContext.log()` in `packLoaded`, `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 the graph keeps the last view per module, so a run of invocations of one world builds + it once; several worlds sharing one graph only rebuild it when they alternate), and `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. - **Why not `System.Logger` for modules.** A module that logs through the JDK works where the host installed a logger diff --git a/README.md b/README.md index 6cf7a6e51..c70189b64 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ public final class MossModule implements IrisModule { .when(MossSettings.class) // only where a pack configures moss .requires(AnchorModule.HEIGHT, BlocksModule.COMPLETE) .softAfter(StageRef.of("iris:snow/finish")) // ordering only, if snow is set up - .run(ctx -> spread(ctx.output(AnchorModule.HEIGHT), ctx.configured(MossSettings.class).getFirst().value())); + .run(ctx -> spread(ctx.output(AnchorModule.HEIGHT), ctx.configured(MossSettings.class).mostSpecific().orElseThrow())); } } ``` @@ -78,24 +78,31 @@ still condition its stages on it, as moss does on `iris:snow`. ## Settings levels -Settings can be declared at several levels: the dimension, a region, a biome and, in a placement, the -placement itself. Each level's declaration is its own entry, and levels stack: nothing is merged and no -level overrides another. A module decides what several entries mean, such as running a deposit once per -entry, or using the most specific one. +Settings can be declared at several levels (`com.volmit.config.Level`): the dimension, a region, a biome +and, in a placement, the placement itself. Each level's declaration is its own entry, and levels stack: +nothing is merged and no level overrides another. A module decides what several entries mean, such as +running a deposit once per entry, or using the most specific one. + +Every lookup answers a `SettingsStack`: the entries in level order, with what modules usually pick from them. ```java -for (var entry : ctx.settings().at(DepositSettings.class, worldX, worldZ)) { // every level at this column - entry.level(); // DIMENSION, REGION, BIOME or OBJECT_PLACEMENT, in that order - entry.source(); // the declaring resource, such as overworld:biome/desert/dunes - entry.value(); // the decoded settings +var here = ctx.settings().at(DepositSettings.class, worldX, worldZ); // every level at this column +here.values(); // every level's value: DIMENSION, REGION, BIOME, PLACEMENT, in that order +here.dimension(); // the dimension's value, if it declares one +here.level(Level.BIOME); +here.mostSpecific(); // the last level's value +for (var entry : here) { + entry.level(); // where it is declared + entry.source(); // the declaring resource, such as overworld:biome/desert/dunes + entry.value(); // the decoded settings } ``` 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 -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 -happens once per chunk. Something that spans several columns, such as a placed object, uses the column +`when(...)` runs when any column of the chunk has an entry (`FeatureSettings.declaredInChunk`), so a +biome border inside a chunk never 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 +(`ctx.centreX()`, `ctx.centreZ()`) for something that 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 `ctx.configured(type)` gives the placement's own entry; a 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. @@ -145,7 +152,7 @@ graph.define(APPLY).run(CaveModule::apply); // reads its own chunk's CAVES and A chunk stage writes only its own chunk but may look around it: `ctx.terrain()` covers the chunk and the 16 blocks around it, gives the dimension's `fluidHeight()` and, per column, `upperDimensionY(x, z)` where a dimension stacked above begins (write nothing there). `surfaceY(x, z)` is a column's height alone, cheaper than `column(x, z)` when a stage needs -no slope. `surfaceBiome(x, z)` is the id of a column's surface biome alone and `surfaceKind(x, z)` what it was generated as (`BiomeKind`: land, sea, +no slope, and `surfaceHeight(x, z)` the same height rounded to the block a stage places on. `surfaceBiome(x, z)` is the id of a column's surface biome alone and `surfaceKind(x, z)` what it was generated as (`BiomeKind`: land, sea, shore); `surfaceBlock(x, z)` is the block an image map gives the ground there, `minWorldY()` the world Y of the dimension's bottom, and `upperDimension()` the dimension stacked above (`UpperDimension`: its own settings, resources and image-map blocks), for a stage that fills in its ground. `ctx.settings().declaredBy(biomeId, Type.class)` reads what a biome declares itself, such as a cave biome of a `BiomeSample`, which is no level of @@ -157,11 +164,14 @@ carved a void, whatever the chunk's blocks show there. Stages only read both. `b ```java graph.define(INSERT).run(ctx -> { var blocks = ctx.hunk(BlockState.class); - var chunk = new BlockBox(ctx.originX(), 0, ctx.originZ(), ctx.originX() + 16, blocks.getHeight(), ctx.originZ() + 16); - ctx.mantle().blocks().visit(chunk, (x, y, z, block) -> blocks.set(x - ctx.originX(), y, z - ctx.originZ(), block)); + ctx.mantle().blocks().visit(ctx.area(), (x, y, z, block) -> blocks.set(x - ctx.originX(), y, z - ctx.originZ(), block)); }); ``` +Chunk and mantle contexts share `ChunkContext`: `originX()`/`originZ()` (the chunk's first block), `chunkX()`/`chunkZ()`, +`centreX()`/`centreZ()` (the world X and Z of the centre column) and `area()`, the chunk's columns at the terrain's full +height. + `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. It defaults to 0. `writesMantle(...)` names the mantle layers the stage writes; each must be @@ -179,7 +189,7 @@ biomes it can reach) when the pack loads, and asks each mantle stage with graph.define(PLAN).when(VeinSettings.class).reach(VeinModule::reach).writesMantle(ORE).run(VeinModule::plan); static int reach(PackSettings settings) { - int longest = settings.declared(VeinSettings.class).stream().mapToInt(vein -> vein.value().length()).max().orElse(0); + int longest = settings.declared(VeinSettings.class).values().stream().mapToInt(VeinSettings::length).max().orElse(0); return Math.max(0, longest - 9); // a vein starts at the chunk's centre column } ``` @@ -255,7 +265,7 @@ it builds for one world, such as a cache or a worker, it keeps in that world's s ```java private static void plant(ChunkStageContext context) { - planted(context.world()).add(context.originX() >> 4, context.originZ() >> 4); + planted(context.world()).add(context.chunkX(), context.chunkZ()); } static PlantedChunks planted(PackWorld world) { @@ -264,8 +274,9 @@ static PlantedChunks planted(PackWorld world) { ``` - `ctx.world()` is the `PackWorld` an invocation generates: its seed, the pack snapshot's resources, the settings of - its dimension and the regions and biomes it can reach, and `state(type, create)`. Every stage context has it; a - placement outside any world, such as a studio paste, throws. + its dimension and the regions and biomes it can reach, and `state(type, create)`. Every stage context has it and it + never throws: a placement outside the worlds the host generates, such as a studio paste, gets a world of its own with + the pack's resources and settings, a seed the host picks and a state store that lives as long as the placement. - `state` creates each type once per world, even when threads race, and hands every caller the same instance. A factory may ask for other state; asking for the type being created fails instead of recursing. A factory that throws keeps nothing. Use a class of the module as the type. @@ -286,8 +297,8 @@ public final class RuinsModule implements IrisModule, ModuleLifecycle { } ``` -- `packLoaded(resources, settings)` runs once per pack snapshot, before the first world using it starts; `settings` - holds every entry of the whole pack. +- `packLoaded(pack)` runs once per pack snapshot, before the first world using it starts: `pack.resources()`, + `pack.settings()` (every entry of the whole pack) and `pack.log()`, the module's log. - `worldStarted(world)` runs before the world generates anything, `worldStopped(world)` when it stops; its state is still readable there. - `warmUp(world)` runs after every module's `worldStarted` and may be slow: build caches in the world's state there, @@ -321,8 +332,8 @@ private static void decorate(ChunkStageContext context) { - A message is plain text, never a format string. - `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 `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. + lifecycle hooks, which get a world as their argument), `pack.log()` (`packLoaded`) and `setup.log()` are the same + module's log. - Do not use `System.out`, `System.getLogger` or a logging library of your own: the host cannot label or report them. ## Services @@ -454,7 +465,7 @@ completion from it. ```java @Desc("Plants flowers and bushes") -@Feature(id = "example:flora", name = "Flora", key = "flora", targets = Target.BIOME) // packs write "flora": {...} +@Feature(id = "example:flora", name = "Flora", key = "flora", targets = Level.BIOME) // packs write "flora": {...} public final class FloraSettings implements IrisFeature { @Desc("Plants per chunk") @Required @MinNumber(0) @MaxNumber(64) private int density = 4; // default 4 @@ -516,7 +527,7 @@ public final class FloraSettings implements IrisFeature { use them. - 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 - `setup.registry().registerSettings(WindSettings.class)` in `setup`. Their feature id follows the module + `setup.registry().registerSettings(WindSettings.class, GustSettings.class)` in `setup`. Their feature id follows the module 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 registered with `registry.registerHeldType(Clamp.class)`, so studio describes it from the class (as an @@ -557,19 +568,20 @@ Settings describe blocks, noise and ranges with IrisApi's value types, which rea | `Object` | any JSON value | as decoded: objects as maps, arrays as lists, numbers as `Double` | ```java -@Feature(id = "example:veins", name = "Veins", key = "veins", targets = Target.BIOME) +@Feature(id = "example:veins", name = "Veins", key = "veins", targets = Level.BIOME) public final class VeinSettings implements IrisFeature { private List palette = List.of(BlockSpec.of("iron_ore")); private NoiseStyle density = NoiseStyle.of("SIMPLEX").withZoom(16); } // in a stage -NoiseSampler density = ctx.resources().noise().sampler(veins.density(), ctx.worldSeed() ^ VEIN_SALT); -BlockState ore = ctx.resources().blocks().resolve(veins.palette().getFirst()); +var resources = ctx.world().resources(); +NoiseSampler density = resources.noise().sampler(veins.density(), ctx.world().seed() ^ VEIN_SALT); +BlockState ore = resources.blocks().resolve(veins.palette().getFirst()); ``` Noise belongs to the host: a style names one of its noise generators (`@Ref(Reference.NOISE_STYLE)`), or an -expression or image map of the pack, and the host builds the noise. Seed it from `worldSeed()`, so the noise +expression or image map of the pack, and the host builds the noise. Seed it from `world().seed()`, so the noise lines up across chunks; the host keeps what it builds for the pack, so asking again is cheap. A `BlockSpec` may name a block without a namespace, a custom block of the pack's `blocks` folder, or a block only some platforms have; resolving it never fails: the backup, then air, stands in. A `PaletteSpec` picks one of its blocks per position @@ -601,8 +613,8 @@ public void setup(ModuleSetup setup) { setup.registry().registerService(VanillaStructures.class, new VanillaStructures() { @Override public VanillaStructureRule rule(ResourceId structure, VanillaStructureContext world) { - return world.settings().declared(CastleSettings.class).stream() - .anyMatch(castle -> castle.value().replaces().equals(structure.toString())) + return world.settings().declared(CastleSettings.class).values().stream() + .anyMatch(castle -> castle.replaces().equals(structure.toString())) ? VanillaStructureRule.REPLACE : VanillaStructureRule.GENERATE; } }); @@ -649,7 +661,7 @@ Every method has a default that changes nothing, so a provider implements only w @Override public List starts(int chunkX, int chunkZ, VanillaStructureStartContext context) { if (!castleChunk(context.world().seed(), chunkX, chunkZ)) return List.of(); - int surface = (int) context.terrain().column((chunkX << 4) + 8, (chunkZ << 4) + 8).surfaceY(); + int surface = context.terrain().surfaceHeight((chunkX << 4) + 8, (chunkZ << 4) + 8); return List.of(VanillaStructureStart.at(ResourceId.parse("minecraft:village_plains"), chunkX, chunkZ, surface) .withMemo(new StartMemo("{\"mode\":\"VACUUM\"}", ""))); } @@ -730,7 +742,7 @@ class of the pack is defined. The last error below lists every kind of unusable uses, one group per kind: ``` -Module jar modules/alpha.jar contains Iris API class com.volmit.FeatureAttachment and 130 more; Iris provides the API at runtime, so mark the Iris API dependency compileOnly (Maven: provided) and keep module classes out of com.volmit.* +Module jar modules/alpha.jar contains Iris API class com.volmit.FeatureRegistry and 130 more; Iris provides the API at runtime, so mark the Iris API dependency compileOnly (Maven: provided) and keep module classes out of com.volmit.* Module jar modules/caves.jar contains class art.arcane.iris.engine.modules.CarveModule of package art.arcane.iris.engine.modules, which Iris provides to modules at runtime; compile against it compileOnly (Maven: provided) instead of shipping it, and keep module classes out of art.arcane.iris.engine.modules.* @@ -807,10 +819,10 @@ no JSON. The host renders it and merges it with its own fields: files' type: an `ObjectKind` naming an entry of `types()`, or a `HostKind` for a built-in kind whose class the host describes itself. `ResourceReferenceKind(kind)` is an option naming a resource of a kind by its key. -For the stilt example the host sees one `OBJECT_PLACEMENT` feature. The records are abridged: +For the stilt example the host sees one `PLACEMENT` feature. The records are abridged: ``` -FeatureSchema[id=iris:stilt, name=Stilt, role=SETTINGS, module=Stilts (iris:stilt), key=stilt, root=Optional.empty, targets=[OBJECT_PLACEMENT], +FeatureSchema[id=iris:stilt, name=Stilt, role=SETTINGS, module=Stilts (iris:stilt), key=stilt, root=Optional.empty, targets=[PLACEMENT], settings=ObjectType[name=com.volmit.example.placement.StiltSettings, description=Fills the space below an object down to the ground, snippet=Optional.empty, options=[SchemaOption[name=maxDepth, kind=IntegerKind[], description=Maximum blocks filled below each lowest object block, required=false, minimum=OptionalDouble[1.0], maximum=OptionalDouble.empty, defaultValue=Optional[16]]]]] @@ -824,7 +836,9 @@ schema, after a module jar changes. `PlacementRunner` owns the edit for one attempt. It commits once if no stage rejects or throws and closes the edit in every case. Stages get buffered `PlacementAccess` without commit rights. -The host keeps one `PackWorld` per world and pack snapshot. `WorldStates` is the reference store behind +The host keeps one `PackWorld` per world and pack snapshot, and builds one for each placement a tool makes outside +those worlds (a studio paste), with its own `WorldStates` that it closes when the placement ends; no hook runs for it. +`WorldStates` is the reference store behind `PackWorld.state`, and `LifecycleRunner` calls a pack's hooks the way `ModuleLifecycle` promises: ```java diff --git a/src/main/java/com/volmit/FeatureAttachment.java b/src/main/java/com/volmit/FeatureAttachment.java deleted file mode 100644 index c216613ee..000000000 --- a/src/main/java/com/volmit/FeatureAttachment.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.volmit; - -import java.util.Objects; -import java.util.Set; - -/** Where settings appear in pack JSON: the targets. The JSON key is declared by {@link com.volmit.config.Feature#key}. */ -public record FeatureAttachment(Set targets) { - public enum Target { DIMENSION, REGION, BIOME, OBJECT_PLACEMENT } - - private static final char NAMESPACE_SEPARATOR = ':'; - - public FeatureAttachment { - targets = Set.copyOf(targets); - if (targets.isEmpty()) throw new IllegalArgumentException("At least one target is required"); - } - - /** Checks a JSON field name that is not a feature id: a settings key or a field the host itself uses. - * It is not blank and has no ':', which every feature id has. - */ - public static String requireFieldName(String name) { - Objects.requireNonNull(name, "name"); - if (name.isBlank()) throw new IllegalArgumentException("Field must not be blank"); - if (name.indexOf(NAMESPACE_SEPARATOR) >= 0) { - throw new IllegalArgumentException("Field " + name + " contains ':', which only feature ids may contain"); - } - return name; - } -} diff --git a/src/main/java/com/volmit/FeatureRegistry.java b/src/main/java/com/volmit/FeatureRegistry.java index 6601e85ce..81f1a5815 100644 --- a/src/main/java/com/volmit/FeatureRegistry.java +++ b/src/main/java/com/volmit/FeatureRegistry.java @@ -10,7 +10,7 @@ import com.volmit.stage.StageGraph; import com.volmit.validation.Validator; /** Host implementation collects non-stage registrations before loading pack configuration. - * Feature IDs must be unique. JSON fields must be unique per attachment target, including the + * Feature IDs must be unique. JSON keys must be unique per {@link com.volmit.config.Level}, including the * settings types stages name in {@code when(...)}. Feature IDs, mantle keys and resource kind ids a module * registers are its module id or start with it and {@code /}, such as {@code iris:snow} or {@code iris:snow/depth}. */ @@ -25,14 +25,14 @@ public interface FeatureRegistry { void registerObject(Class featureType, ObjectGeneratorFactory factory); - /** Catalogs a settings type that no stage names in {@code when(...)}, such as one read only - * through {@link com.volmit.config.FeatureSettings#at}, so the host decodes it and studio - * describes it. Settings that a stage names are catalogued without this; registering them as - * well changes nothing. The type's feature id must be this module's id or start with it and - * {@code /}. Once registered, other modules may name the type in {@code when(...)} (see - * {@link StageGraph}). + /** Catalogs settings types that no stage names in {@code when(...)}, such as ones read only + * through {@link com.volmit.config.FeatureSettings#at}, so the host decodes them and studio + * describes them: {@code registerSettings(WindSettings.class, GustSettings.class)}. Settings that a + * stage names are catalogued without this; registering them as well changes nothing. Each type's + * feature id must be this module's id or start with it and {@code /}. Once registered, other + * modules may name the types in {@code when(...)} (see {@link StageGraph}). */ - void registerSettings(Class settingsType); + void registerSettings(Class... settingsTypes); /** Describes a class that Iris's own classes hold, such as the clamp of an object placement, so studio shows * its fields as this class declares them. The class must be one the host loads: a built-in module's class, or a diff --git a/src/main/java/com/volmit/ModuleLifecycle.java b/src/main/java/com/volmit/ModuleLifecycle.java index 182b2035c..dd40047e7 100644 --- a/src/main/java/com/volmit/ModuleLifecycle.java +++ b/src/main/java/com/volmit/ModuleLifecycle.java @@ -1,7 +1,5 @@ package com.volmit; -import com.volmit.config.PackSettings; -import com.volmit.resource.PackResources; import com.volmit.world.PackWorld; /** What a module does when the host loads a pack and starts or stops a world with it. Every hook does nothing by @@ -19,11 +17,11 @@ import com.volmit.world.PackWorld; * serve several packs and worlds at once. */ public interface ModuleLifecycle { - /** The pack's modules are installed and its resources can be read. {@code settings} holds every entry of every - * dimension, region and biome of the pack, as validators see them. A hook that throws stops the pack's worlds from - * starting, naming its module. + /** The pack's modules are set up and its resources can be read: {@code pack} gives the resources, every settings + * entry of every dimension, region and biome of the pack (as validators see them) and the module's log. A hook that + * throws stops the pack's worlds from starting, naming its module. */ - default void packLoaded(PackResources resources, PackSettings settings) {} + default void packLoaded(PackContext pack) {} /** {@code world} starts, before it generates anything: the place to build state eagerly, such as caches a world * would otherwise build on its first chunk. A hook that throws stops the world from starting, naming its module; the diff --git a/src/main/java/com/volmit/PackContext.java b/src/main/java/com/volmit/PackContext.java new file mode 100644 index 000000000..2691592c6 --- /dev/null +++ b/src/main/java/com/volmit/PackContext.java @@ -0,0 +1,18 @@ +package com.volmit; + +import com.volmit.config.PackSettings; +import com.volmit.resource.PackResources; + +/** A pack snapshot the host loaded, as {@link ModuleLifecycle#packLoaded} sees it. Do not retain it after the hook + * returns: what a module builds from it for a world belongs in that world's state. + */ +public interface PackContext { + /** The snapshot's resources. */ + PackResources resources(); + + /** Every settings entry of every dimension, region and biome of the pack, as validators see them. */ + PackSettings settings(); + + /** The log of the module the hook belongs to, labelled with its id. */ + ModuleLog log(); +} diff --git a/src/main/java/com/volmit/block/PaletteSampler.java b/src/main/java/com/volmit/block/PaletteSampler.java index 39bf4eef2..7c5222505 100644 --- a/src/main/java/com/volmit/block/PaletteSampler.java +++ b/src/main/java/com/volmit/block/PaletteSampler.java @@ -1,9 +1,8 @@ package com.volmit.block; /** The block a {@link PaletteSpec} picks at a position, built by the host ({@link BlockRegistry#palette}). The - * coordinates are the noise's input, so they are the same kind the module's other noise uses: world X and Z, and Y as the - * module counts it, which is the height above the dimension's bottom unless the module documents otherwise. The same - * position always gives the same block. Safe for concurrent calls. + * coordinates are the noise's input and follow the API's coordinate rule: world X and Z, and Y as the height above the + * dimension's bottom (0 = bottom block). The same position always gives the same block. Safe for concurrent calls. */ @FunctionalInterface public interface PaletteSampler { diff --git a/src/main/java/com/volmit/config/Feature.java b/src/main/java/com/volmit/config/Feature.java index 79bed2a8d..a46b19770 100644 --- a/src/main/java/com/volmit/config/Feature.java +++ b/src/main/java/com/volmit/config/Feature.java @@ -4,7 +4,8 @@ import java.lang.annotation.*; /** Identity and JSON attachment for an IrisFeature configuration class. The {@code id}, such as * {@code "example:moss"}, is the feature's identity in the stage graph, logs and lookups by class. Packs write - * the settings under the short {@code key}, such as {@code "moss": {...}}, at each of the targets. + * the settings under the short {@code key}, such as {@code "moss": {...}}, at each of the targets, the {@link Level}s + * of a pack's dimension, region, biome or object placement files. * *

The key is a plain JSON field name: not blank, no ':'. It is unique per target across all loaded modules * and the JSON fields the host itself uses at that target, so it must not be a field of a biome, region or @@ -22,5 +23,6 @@ public @interface Feature { String name(); String key(); String root() default ""; - com.volmit.FeatureAttachment.Target[] targets(); + /** The levels packs may write the settings at. */ + Level[] targets(); } diff --git a/src/main/java/com/volmit/config/FeatureSettings.java b/src/main/java/com/volmit/config/FeatureSettings.java index 4803a8aeb..76478702e 100644 --- a/src/main/java/com/volmit/config/FeatureSettings.java +++ b/src/main/java/com/volmit/config/FeatureSettings.java @@ -1,9 +1,10 @@ package com.volmit.config; -import com.volmit.FeatureAttachment; import com.volmit.IrisFeature; +import com.volmit.generation.ChunkContext; import com.volmit.resource.ResourceId; -import java.util.List; +import java.util.ArrayList; +import java.util.HashSet; import java.util.Objects; import java.util.Optional; @@ -12,16 +13,39 @@ import java.util.Optional; *

Every level that declares the settings contributes its own entry: the dimension, the region and * the biome of the column, and in a placement the placement itself. Levels stack: nothing is merged or * overridden, and a module decides what several entries mean, such as running a deposit once per - * entry. Entries are immutable lists in level order ({@link FeatureAttachment.Target} order). The - * biome is the column's surface biome; cave biomes are not a level. Values must be treated as + * entry. The biome is the column's surface biome; cave biomes are not a level. Values must be treated as * read-only. Bounds and lifetime match the invocation's sampler. * *

Something that spans several columns, such as a chunk-wide pass or a placed object, reads the * settings at one column it treats as its origin; per-chunk behaviour reads the chunk's centre column - * (local 7, 7). + * ({@link ChunkContext#centreX()}, {@link ChunkContext#centreZ()}). */ public interface FeatureSettings { - List> at(Class featureType, int worldX, int worldZ); + /** The entries of {@code featureType} at this column, in level order; empty when no level declares it. */ + SettingsStack at(Class featureType, int worldX, int worldZ); + + /** Every distinct entry of {@code featureType} at the 16 by 16 columns of chunk {@code chunkX}, {@code chunkZ}, in + * level order; entries of one level in the order their first column was found, columns by X and then Z. Entries are + * distinct by level and source. The chunk and mantle runners decide with it whether a conditioned stage runs in a + * chunk. The default asks {@link #at} for every column; a host that knows which regions and biomes a chunk holds + * answers it from them. + */ + default SettingsStack declaredInChunk(Class featureType, int chunkX, int chunkZ) { + var declarations = new HashSet(); + var distinct = new ArrayList>(); + int originX = chunkX * ChunkContext.CHUNK_WIDTH; + int originZ = chunkZ * ChunkContext.CHUNK_WIDTH; + for (int x = 0; x < ChunkContext.CHUNK_WIDTH; x++) { + for (int z = 0; z < ChunkContext.CHUNK_WIDTH; z++) { + for (var entry : at(featureType, originX + x, originZ + z)) { + if (declarations.add(new Declaration(entry.level(), entry.source()))) { + distinct.add(entry); + } + } + } + } + return SettingsStack.of(distinct); + } /** The settings {@code biome} declares itself, whichever column it is found at: for a biome that is not a column's * surface biome, such as the cave biome of {@link com.volmit.world.BiomeSample#caveBiome()}, which is no level of @@ -38,7 +62,7 @@ public interface FeatureSettings { * @param source the resource that declares them, such as {@code overworld:biome/desert/dunes} * @param value the decoded settings */ - record Entry(FeatureAttachment.Target level, ResourceId source, F value) { + record Entry(Level level, ResourceId source, F value) { public Entry { Objects.requireNonNull(level, "level"); Objects.requireNonNull(source, "source"); @@ -46,3 +70,6 @@ public interface FeatureSettings { } } } + +/** What makes two entries of a chunk the same declaration. */ +record Declaration(Level level, ResourceId source) {} diff --git a/src/main/java/com/volmit/config/Level.java b/src/main/java/com/volmit/config/Level.java new file mode 100644 index 000000000..aea914dc9 --- /dev/null +++ b/src/main/java/com/volmit/config/Level.java @@ -0,0 +1,7 @@ +package com.volmit.config; + +/** Where a pack declares settings, from the least to the most specific: the dimension, a region, a biome, and an + * object placement. {@link Feature#targets()} names the levels a feature may be written at, and every + * {@link FeatureSettings.Entry} carries the level that declared it. Settings stacks keep this order. + */ +public enum Level { DIMENSION, REGION, BIOME, PLACEMENT } diff --git a/src/main/java/com/volmit/config/PackSettings.java b/src/main/java/com/volmit/config/PackSettings.java index 0727a239e..8a4859030 100644 --- a/src/main/java/com/volmit/config/PackSettings.java +++ b/src/main/java/com/volmit/config/PackSettings.java @@ -1,8 +1,6 @@ package com.volmit.config; import com.volmit.IrisFeature; -import com.volmit.config.FeatureSettings.Entry; -import java.util.List; /** Every settings declaration of the pack the host is loading, for what depends on the whole pack rather * than one column, such as how far a mantle stage reaches ({@link com.volmit.stage.PackReach}). @@ -15,5 +13,5 @@ public interface PackSettings { /** Every entry of {@code featureType} the pack declares, dimension first, then regions, then biomes; * empty when nothing declares it. */ - List> declared(Class featureType); + SettingsStack declared(Class featureType); } diff --git a/src/main/java/com/volmit/config/SettingsStack.java b/src/main/java/com/volmit/config/SettingsStack.java new file mode 100644 index 000000000..0f56491fa --- /dev/null +++ b/src/main/java/com/volmit/config/SettingsStack.java @@ -0,0 +1,105 @@ +package com.volmit.config; + +import com.volmit.IrisFeature; +import com.volmit.config.FeatureSettings.Entry; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +/** The entries of one settings type that apply somewhere, in {@link Level} order: what a column stacks + * ({@link FeatureSettings#at}), what a chunk or a placement configures ({@link com.volmit.stage.StageContext#configured}) + * or what a pack declares ({@link PackSettings#declared}). Levels stack and nothing is merged, so a module picks what it + * needs: every entry, the dimension's, the most specific one. Several entries may share a level, such as the biomes of + * a chunk or of a pack; they keep the order they were found in. + * + *

An immutable value; equal when the entries are equal. Hosts build it with {@link #of}. + */ +public final class SettingsStack implements Iterable> { + private static final SettingsStack EMPTY = new SettingsStack<>(List.of()); + private static final Comparator> LEVEL_ORDER = Comparator.comparing(Entry::level); + + private final List> entries; + private final List values; + + private SettingsStack(List> entries) { + this.entries = entries; + this.values = entries.stream().map(Entry::value).toList(); + } + + @SuppressWarnings("unchecked") // The empty stack holds no entry of any type. + public static SettingsStack empty() { + return (SettingsStack) EMPTY; + } + + /** These entries in level order; entries of one level keep the order given. */ + public static SettingsStack of(List> entries) { + Objects.requireNonNull(entries, "entries"); + if (entries.isEmpty()) { + return empty(); + } + var sorted = new ArrayList>(entries); + sorted.forEach(entry -> Objects.requireNonNull(entry, "entry")); + sorted.sort(LEVEL_ORDER); + return new SettingsStack<>(List.copyOf(sorted)); + } + + public boolean isEmpty() { + return entries.isEmpty(); + } + + /** Every entry, in level order. */ + public List> entries() { + return entries; + } + + /** Every entry's value, in level order. */ + public List values() { + return values; + } + + /** The dimension's value; empty when the dimension declares none. */ + public Optional dimension() { + return level(Level.DIMENSION); + } + + /** The first value declared at {@code level}; empty when that level declares none. */ + public Optional level(Level level) { + Objects.requireNonNull(level, "level"); + for (var entry : entries) { + if (entry.level() == level) { + return Optional.of(entry.value()); + } + } + return Optional.empty(); + } + + /** The value of the last entry, the most specific level's (a placement before a biome before a region before the + * dimension); empty when the stack is. + */ + public Optional mostSpecific() { + return entries.isEmpty() ? Optional.empty() : Optional.of(entries.getLast().value()); + } + + @Override + public Iterator> iterator() { + return entries.iterator(); + } + + @Override + public boolean equals(Object other) { + return other instanceof SettingsStack stack && entries.equals(stack.entries); + } + + @Override + public int hashCode() { + return entries.hashCode(); + } + + @Override + public String toString() { + return "SettingsStack" + entries; + } +} diff --git a/src/main/java/com/volmit/generation/ChunkContext.java b/src/main/java/com/volmit/generation/ChunkContext.java new file mode 100644 index 000000000..ebb051f8f --- /dev/null +++ b/src/main/java/com/volmit/generation/ChunkContext.java @@ -0,0 +1,52 @@ +package com.volmit.generation; + +import com.volmit.config.FeatureSettings; +import com.volmit.mantle.BlockBox; +import com.volmit.world.TerrainSampler; + +/** What chunk and mantle invocations share: the chunk they run for, its terrain and its settings. X and Z are world + * coordinates; heights are above the dimension's bottom. Must not be retained after execution. + */ +public interface ChunkContext extends InvocationContext { + /** The width of a chunk along X and Z, in blocks. */ + int CHUNK_WIDTH = 16; + + /** The local X and Z of a chunk's centre column, where something that happens once per chunk reads its settings. */ + int CENTRE_COLUMN = 7; + + /** The chunk's first block along X, in world coordinates. */ + int originX(); + + /** The chunk's first block along Z, in world coordinates. */ + int originZ(); + + TerrainSampler terrain(); + + FeatureSettings settings(); + + /** The chunk's X in chunk coordinates. */ + default int chunkX() { + return Math.floorDiv(originX(), CHUNK_WIDTH); + } + + /** The chunk's Z in chunk coordinates. */ + default int chunkZ() { + return Math.floorDiv(originZ(), CHUNK_WIDTH); + } + + /** The world X of the chunk's centre column (local 7). */ + default int centreX() { + return originX() + CENTRE_COLUMN; + } + + /** The world Z of the chunk's centre column (local 7). */ + default int centreZ() { + return originZ() + CENTRE_COLUMN; + } + + /** The chunk's 16 by 16 columns in world coordinates, at the full height the terrain covers. */ + default BlockBox area() { + var bounds = terrain().bounds(); + return new BlockBox(originX(), bounds.minY(), originZ(), originX() + CHUNK_WIDTH, bounds.maxY(), originZ() + CHUNK_WIDTH); + } +} diff --git a/src/main/java/com/volmit/generation/GenerationContext.java b/src/main/java/com/volmit/generation/GenerationContext.java index ec92d6bbe..61ba3f125 100644 --- a/src/main/java/com/volmit/generation/GenerationContext.java +++ b/src/main/java/com/volmit/generation/GenerationContext.java @@ -2,22 +2,24 @@ package com.volmit.generation; import com.volmit.hunk.Hunk; import com.volmit.mantle.Mantle; -import com.volmit.config.FeatureSettings; import com.volmit.world.TerrainSampler; /** Per-invocation chunk generation inputs. Must not be retained after execution. */ -public interface GenerationContext extends InvocationContext { +public interface GenerationContext extends ChunkContext { /** World coordinates of the local volume's first column. The volume starts at the dimension's bottom: * local y is the height above it (0 = bottom block). */ + @Override int originX(); + + @Override int originZ(); /** The terrain of the chunk and of the 16 blocks around it on every side, at full height: a chunk stage writes only * its own chunk, but may look at its neighbors' terrain, such as their heights. */ + @Override TerrainSampler terrain(); - FeatureSettings settings(); /** Non-null mantle access scoped to this invocation; the host owns its lifetime. Chunk stages read it * only: the mantle pipeline has finished around the chunk, and writes throw. Like {@link #terrain()} it covers the diff --git a/src/main/java/com/volmit/generation/InvocationContext.java b/src/main/java/com/volmit/generation/InvocationContext.java index 8c78b0e6b..c168a049c 100644 --- a/src/main/java/com/volmit/generation/InvocationContext.java +++ b/src/main/java/com/volmit/generation/InvocationContext.java @@ -1,7 +1,6 @@ package com.volmit.generation; import com.volmit.ModuleLog; -import com.volmit.resource.PackResources; import com.volmit.world.PackWorld; /** Host-owned invocation inputs. Views must not be retained or used by detached tasks. @@ -10,17 +9,13 @@ import com.volmit.world.PackWorld; * a stream of its own, and an object generator from {@link com.volmit.object.ObjectGenerationContext#random()}. */ public interface InvocationContext { - long worldSeed(); - PackResources resources(); - - /** The world this invocation generates, where modules keep their per-world state ({@link PackWorld#state}). An - * invocation outside any world, such as an object a studio tool pastes, throws IllegalStateException. + /** The world this invocation generates: its seed, the pack snapshot's resources, its settings and the state modules + * keep for it ({@link PackWorld#state}). Every invocation has one. A placement a tool makes outside a world the host + * generates, such as a studio paste, gets a world of its own that lives for that placement. */ PackWorld world(); - /** The log of the module this invocation runs for, labelled with the module's id. The same as - * {@code world().log()}, which a host overrides where an invocation has no world. - */ + /** The log of the module this invocation runs for, labelled with the module's id. The same as {@code world().log()}. */ default ModuleLog log() { return world().log(); } diff --git a/src/main/java/com/volmit/generation/MantleGenerationContext.java b/src/main/java/com/volmit/generation/MantleGenerationContext.java index 9024981b1..254671e34 100644 --- a/src/main/java/com/volmit/generation/MantleGenerationContext.java +++ b/src/main/java/com/volmit/generation/MantleGenerationContext.java @@ -1,25 +1,17 @@ package com.volmit.generation; -import com.volmit.config.FeatureSettings; import com.volmit.mantle.Mantle; import com.volmit.world.TerrainSampler; /** Per-invocation inputs of the mantle pipeline for one chunk. Must not be retained after execution. */ -public interface MantleGenerationContext extends InvocationContext { - /** The chunk's first block along X, in world coordinates. Heights are above the dimension's bottom. */ - int originX(); - - /** The chunk's first block along Z, in world coordinates. */ - int originZ(); - +public interface MantleGenerationContext extends ChunkContext { /** The terrain of the chunk and of the larger of the stage's reach and 16 blocks around it on every side, at full * height: a mantle stage writes only the mantle, but may look at the terrain around its chunk, such as the heights * a cave blends over its borders. */ + @Override TerrainSampler terrain(); - FeatureSettings settings(); - /** The mantle of the chunk widened by the pipeline's reach, full height (heights 0 up to the dimension height). Writes outside it throw. */ Mantle mantle(); } diff --git a/src/main/java/com/volmit/host/ChunkInvocation.java b/src/main/java/com/volmit/host/ChunkInvocation.java index d8593d246..1ae3a48e3 100644 --- a/src/main/java/com/volmit/host/ChunkInvocation.java +++ b/src/main/java/com/volmit/host/ChunkInvocation.java @@ -2,17 +2,15 @@ package com.volmit.host; import com.volmit.IrisFeature; import com.volmit.config.FeatureSettings; -import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.SettingsStack; import com.volmit.generation.GenerationContext; import com.volmit.hunk.Hunk; import com.volmit.mantle.Mantle; import com.volmit.random.WorldRandom; -import com.volmit.resource.PackResources; import com.volmit.world.PackWorld; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.Stage; import com.volmit.world.TerrainSampler; -import java.util.List; import java.util.Objects; /** The context every stage of one chunk invocation receives. The mantle is read-only. */ @@ -35,7 +33,7 @@ final class ChunkInvocation implements ChunkStageContext { } @Override - public List> configured(Class settingsType) { + public SettingsStack configured(Class settingsType) { return stages.configured(settingsType); } @@ -69,21 +67,11 @@ final class ChunkInvocation implements ChunkStageContext { return inputs.hunk(type); } - @Override - public long worldSeed() { - return inputs.worldSeed(); - } - @Override public PackWorld world() { return stages.world(inputs.world()); } - @Override - public PackResources resources() { - return inputs.resources(); - } - @Override public WorldRandom random() { return stages.random(); diff --git a/src/main/java/com/volmit/host/ChunkSettings.java b/src/main/java/com/volmit/host/ChunkSettings.java index 762ab526c..27bb746aa 100644 --- a/src/main/java/com/volmit/host/ChunkSettings.java +++ b/src/main/java/com/volmit/host/ChunkSettings.java @@ -1,25 +1,18 @@ package com.volmit.host; -import com.volmit.FeatureAttachment; import com.volmit.IrisFeature; import com.volmit.config.FeatureSettings; -import com.volmit.config.FeatureSettings.Entry; -import com.volmit.resource.ResourceId; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; +import com.volmit.config.SettingsStack; +import com.volmit.generation.ChunkContext; +import java.util.HashMap; import java.util.List; import java.util.function.Supplier; /** The settings one chunk's stages see: for every settings type the running stages condition on, each - * distinct entry of the chunk's 16 by 16 columns. A stage is therefore active when any column of the chunk - * configures its settings, also where a biome border crosses the chunk. Entries are distinct by level - * and source and keep the order their first column was read in, columns by X and then Z. + * distinct entry of the chunk's 16 by 16 columns ({@link FeatureSettings#declaredInChunk}). A stage is therefore + * active when any column of the chunk configures its settings, also where a biome border crosses the chunk. */ final class ChunkSettings { - /** The chunk's width along X and Z, in blocks: the footprint of chunk and mantle stages. */ - static final int CHUNK_WIDTH = 16; - private ChunkSettings() {} /** {@code settings} is asked only when {@code types} is not empty. */ @@ -28,25 +21,12 @@ final class ChunkSettings { return ConfiguredSettings.none(); } var view = settings.get(); - var entries = new ArrayList>(); + int chunkX = Math.floorDiv(originX, ChunkContext.CHUNK_WIDTH); + int chunkZ = Math.floorDiv(originZ, ChunkContext.CHUNK_WIDTH); + var stacks = new HashMap, SettingsStack>(); for (var type : types) { - entries.addAll(distinctEntries(type.asSubclass(IrisFeature.class), view, originX, originZ)); + stacks.put(type, view.declaredInChunk(type.asSubclass(IrisFeature.class), chunkX, chunkZ)); } - return ConfiguredSettings.of(entries); + return ConfiguredSettings.ofStacks(stacks); } - - private static Collection> distinctEntries( - Class type, FeatureSettings view, int originX, int originZ) { - var distinct = new LinkedHashMap>(); - for (int x = 0; x < CHUNK_WIDTH; x++) { - for (int z = 0; z < CHUNK_WIDTH; z++) { - for (var entry : view.at(type, originX + x, originZ + z)) { - distinct.putIfAbsent(new Declaration(entry.level(), entry.source()), entry); - } - } - } - return distinct.values(); - } - - private record Declaration(FeatureAttachment.Target level, ResourceId source) {} } diff --git a/src/main/java/com/volmit/host/ConfiguredSettings.java b/src/main/java/com/volmit/host/ConfiguredSettings.java index 5e3451719..21fb78caf 100644 --- a/src/main/java/com/volmit/host/ConfiguredSettings.java +++ b/src/main/java/com/volmit/host/ConfiguredSettings.java @@ -1,18 +1,18 @@ package com.volmit.host; -import com.volmit.FeatureAttachment; import com.volmit.IrisFeature; import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.Level; +import com.volmit.config.SettingsStack; import com.volmit.resource.ResourceId; import java.util.ArrayList; -import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; -/** 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 reads them all with +/** The settings configured for one invocation, one {@link SettingsStack} per settings type. A stage + * conditioned on a type is active when its stack is not empty, and reads it with * {@link com.volmit.stage.StageContext#configured}. For a placement these are the placement's own declarations; for * a chunk the runners collect every distinct entry of the chunk's columns themselves. Entries are grouped by their * declared settings type ({@link FeatureDescriptor#declaredType}), so a value of a subclass counts as the type it is @@ -20,12 +20,11 @@ import java.util.Objects; */ public final class ConfiguredSettings { private static final ConfiguredSettings NONE = new ConfiguredSettings(Map.of()); - private static final Comparator> LEVEL_ORDER = Comparator.comparing(Entry::level); - private final Map, List>> entries; + private final Map, SettingsStack> stacks; - private ConfiguredSettings(Map, List>> entries) { - this.entries = Map.copyOf(entries); + private ConfiguredSettings(Map, SettingsStack> stacks) { + this.stacks = Map.copyOf(stacks); } public static ConfiguredSettings none() { @@ -39,8 +38,23 @@ public final class ConfiguredSettings { Objects.requireNonNull(entry, "entry"); grouped.computeIfAbsent(FeatureDescriptor.declaredType(entry.value().getClass()), ignored -> new ArrayList<>()).add(entry); } - grouped.replaceAll((type, group) -> group.stream().sorted(LEVEL_ORDER).toList()); - return grouped.isEmpty() ? NONE : new ConfiguredSettings(grouped); + if (grouped.isEmpty()) { + return NONE; + } + var stacks = new HashMap, SettingsStack>(); + grouped.forEach((type, group) -> stacks.put(type, stackOf(group))); + return new ConfiguredSettings(stacks); + } + + /** The stacks of these types, each kept under its own type; empty stacks are left out. */ + static ConfiguredSettings ofStacks(Map, SettingsStack> stacks) { + var configured = new HashMap, SettingsStack>(); + stacks.forEach((type, stack) -> { + if (!stack.isEmpty()) { + configured.put(type, stack); + } + }); + return configured.isEmpty() ? NONE : new ConfiguredSettings(configured); } /** One placement's own settings, at most one value per declared type, declared by {@code source}. */ @@ -54,15 +68,20 @@ public final class ConfiguredSettings { 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<>(Level.PLACEMENT, source, value)); } return of(entries); } - /** The entries of {@code type}, in level order; empty when nothing configures it. */ - @SuppressWarnings("unchecked") // Entries are grouped by the declared type of their value. - public List> find(Class type) { - var found = entries.get(type); - return found == null ? List.of() : (List>) (List) found; + /** The stack of {@code type}; empty when nothing configures it. */ + @SuppressWarnings("unchecked") // Stacks are grouped by the declared type of their values. + public SettingsStack find(Class type) { + var found = stacks.get(type); + return found == null ? SettingsStack.empty() : (SettingsStack) found; + } + + @SuppressWarnings({"unchecked", "rawtypes"}) // A group holds entries of one declared type. + private static SettingsStack stackOf(List> group) { + return SettingsStack.of((List) group); } } diff --git a/src/main/java/com/volmit/host/ExecutableStage.java b/src/main/java/com/volmit/host/ExecutableStage.java index d2441668e..ff433116a 100644 --- a/src/main/java/com/volmit/host/ExecutableStage.java +++ b/src/main/java/com/volmit/host/ExecutableStage.java @@ -1,13 +1,12 @@ package com.volmit.host; -import com.volmit.ModuleLog; import com.volmit.stage.Stage; /** Execution data of one resolved stage. Indices are positions in the resolved order. * readableStages/readablePositions are the transitive requirements whose outputs it may read. * settingsSlot indexes the graph's distinct settings types, or is NO_SETTINGS. idHash keys the - * stage's random stream ({@link StageStreams}), computed once per pack load. log is the log of the module that - * defined the stage. + * stage's random stream ({@link StageStreams}), computed once per pack load. worlds gives the world as the module + * that defined the stage sees it, shared by that module's stages. */ record ExecutableStage( Stage stage, @@ -17,7 +16,7 @@ record ExecutableStage( int[] readablePositions, int settingsSlot, long idHash, - ModuleLog log) { + ScopedWorlds worlds) { static final int NO_SETTINGS = -1; static final int NOT_READABLE = -1; diff --git a/src/main/java/com/volmit/host/FeatureDescriptor.java b/src/main/java/com/volmit/host/FeatureDescriptor.java index 9924604b5..c80a6ce9c 100644 --- a/src/main/java/com/volmit/host/FeatureDescriptor.java +++ b/src/main/java/com/volmit/host/FeatureDescriptor.java @@ -1,12 +1,14 @@ package com.volmit.host; -import com.volmit.FeatureAttachment; import com.volmit.IrisFeature; import com.volmit.config.Feature; +import com.volmit.config.Level; import com.volmit.config.OptionsMetadata; import com.volmit.resource.ResourceId; import java.lang.annotation.IncompleteAnnotationException; import java.lang.reflect.Modifier; +import java.util.Collections; +import java.util.EnumSet; import java.util.List; import java.util.Objects; import java.util.Optional; @@ -17,6 +19,7 @@ import java.util.Set; * @param key the JSON key packs write the settings under at each target; see {@link Feature#key} * @param root the option whose value the key holds, when the JSON is one option's value instead of an object * of options; see {@link Feature#root} + * @param targets the levels whose pack files hold the key, at least one */ public record FeatureDescriptor( ResourceId id, @@ -24,8 +27,10 @@ public record FeatureDescriptor( String key, Optional root, Class type, - FeatureAttachment attachment, + Set targets, OptionsMetadata options) { + private static final char NAMESPACE_SEPARATOR = ':'; + public FeatureDescriptor { Objects.requireNonNull(id, "id"); Objects.requireNonNull(name, "name"); @@ -35,11 +40,33 @@ public record FeatureDescriptor( requireKey(id, key); Objects.requireNonNull(root, "root"); Objects.requireNonNull(type, "type"); - Objects.requireNonNull(attachment, "attachment"); + targets = requireTargets(targets); Objects.requireNonNull(options, "options"); root.ifPresent(option -> requireOnlyOption(type, option, options)); } + /** Checks a JSON field name that is not a feature id: a settings key or a field the host itself uses. + * It is not blank and has no ':', which every feature id has. + */ + public static String requireFieldName(String name) { + Objects.requireNonNull(name, "name"); + if (name.isBlank()) { + throw new IllegalArgumentException("Field must not be blank"); + } + if (name.indexOf(NAMESPACE_SEPARATOR) >= 0) { + throw new IllegalArgumentException("Field " + name + " contains ':', which only feature ids may contain"); + } + return name; + } + + private static Set requireTargets(Set targets) { + Objects.requireNonNull(targets, "targets"); + if (targets.isEmpty()) { + throw new IllegalArgumentException("At least one target is required"); + } + return Collections.unmodifiableSet(EnumSet.copyOf(targets)); + } + /** Reads the @Feature declaration of a concrete settings class. */ public static FeatureDescriptor of(Class type) { Objects.requireNonNull(type, "featureType"); @@ -57,7 +84,7 @@ public record FeatureDescriptor( annotation.key(), annotation.root().isEmpty() ? Optional.empty() : Optional.of(annotation.root()), type, - new FeatureAttachment(Set.of(annotation.targets())), + Set.of(annotation.targets()), OptionsMetadata.inspect(type)); } catch (IncompleteAnnotationException missing) { throw IncompleteFeatureException.of(type, annotation, missing); @@ -85,7 +112,7 @@ public record FeatureDescriptor( private static void requireKey(ResourceId id, String key) { try { - FeatureAttachment.requireFieldName(key); + requireFieldName(key); } catch (IllegalArgumentException invalid) { throw new IllegalArgumentException("Invalid key of feature " + id + ": " + invalid.getMessage() + "; a key is a plain JSON field name such as \"deposits\"", invalid); diff --git a/src/main/java/com/volmit/host/GraphResolver.java b/src/main/java/com/volmit/host/GraphResolver.java index b2de3f015..0a1eb3929 100644 --- a/src/main/java/com/volmit/host/GraphResolver.java +++ b/src/main/java/com/volmit/host/GraphResolver.java @@ -1,5 +1,6 @@ package com.volmit.host; +import com.volmit.ModuleLog; import com.volmit.resource.ResourceId; import com.volmit.stage.Pipeline; import com.volmit.stage.Stage; @@ -11,6 +12,7 @@ import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; +import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -212,6 +214,7 @@ final class GraphResolver { var executables = new ExecutableStage[order.length]; var readable = new BitSet[order.length]; var settingsTypes = new ArrayList>(); + var worldsByLog = new IdentityHashMap(); for (int index = 0; index < order.length; index++) { int node = order[index]; var declaration = nodes.get(node); @@ -226,7 +229,7 @@ final class GraphResolver { readable[index].stream().toArray(), settingsSlot(declaration, settingsTypes), StageStreams.idHash(declaration.stage().id()), - declaration.log()); + worldsByLog.computeIfAbsent(declaration.log(), ScopedWorlds::new)); stages.add(new ResolvedStage(declaration.stage(), declaration.module(), declaration.settings(), incomingEdges(node, position), absentSoftTargets.get(node), declaration.reach())); } diff --git a/src/main/java/com/volmit/host/LifecycleRegistration.java b/src/main/java/com/volmit/host/LifecycleRegistration.java index 0629025e0..c3bbc7961 100644 --- a/src/main/java/com/volmit/host/LifecycleRegistration.java +++ b/src/main/java/com/volmit/host/LifecycleRegistration.java @@ -1,6 +1,10 @@ package com.volmit.host; import com.volmit.ModuleLifecycle; +import com.volmit.ModuleLog; +import com.volmit.PackContext; +import com.volmit.config.PackSettings; +import com.volmit.resource.PackResources; import com.volmit.world.PackWorld; import java.util.Objects; @@ -17,4 +21,11 @@ public record LifecycleRegistration(ModuleLifecycle lifecycle, DiscoveredModule PackWorld scope(PackWorld world) { return world.withLog(module.log()); } + + /** The pack snapshot as this hook's module sees it, whose {@link PackContext#log} is the module's own. */ + PackContext pack(PackResources resources, PackSettings settings) { + return new LoadedPackContext(resources, settings, module.log()); + } + + private record LoadedPackContext(PackResources resources, PackSettings settings, ModuleLog log) implements PackContext {} } diff --git a/src/main/java/com/volmit/host/LifecycleRunner.java b/src/main/java/com/volmit/host/LifecycleRunner.java index e52afc211..40656187b 100644 --- a/src/main/java/com/volmit/host/LifecycleRunner.java +++ b/src/main/java/com/volmit/host/LifecycleRunner.java @@ -28,15 +28,16 @@ public final class LifecycleRunner { this.lifecycles = Objects.requireNonNull(catalog, "catalog").lifecycles(); } - /** Runs every {@code packLoaded} hook in order; the first that throws ends the run with an IllegalStateException - * naming its module, and the hooks after it do not run. + /** Runs every {@code packLoaded} hook in order, each with a {@link com.volmit.PackContext} whose log is its module's; + * the first that throws ends the run with an IllegalStateException naming its module, and the hooks after it do not + * run. */ public void packLoaded(PackResources resources, PackSettings settings) { Objects.requireNonNull(resources, "resources"); Objects.requireNonNull(settings, "settings"); for (var registration : lifecycles) { try { - registration.lifecycle().packLoaded(resources, settings); + registration.lifecycle().packLoaded(registration.pack(resources, settings)); } catch (RuntimeException failure) { throw failed("loading pack " + resources.packId(), registration, failure); } diff --git a/src/main/java/com/volmit/host/LoadedModules.java b/src/main/java/com/volmit/host/LoadedModules.java index c0dda950b..11c1435f5 100644 --- a/src/main/java/com/volmit/host/LoadedModules.java +++ b/src/main/java/com/volmit/host/LoadedModules.java @@ -1,6 +1,6 @@ package com.volmit.host; -import com.volmit.FeatureAttachment; +import com.volmit.config.Level; import com.volmit.host.schema.PackSchema; import com.volmit.stage.Pipeline; import java.util.Collection; @@ -33,7 +33,7 @@ public record LoadedModules( */ public static LoadedModules load( List modules, - Map> reservedHostFields, + Map> reservedHostFields, Collection hostTypePackages, Collection reservedFolders) { var registry = new ModuleRegistry(reservedHostFields, Set.copyOf(reservedFolders)); diff --git a/src/main/java/com/volmit/host/MantleInvocation.java b/src/main/java/com/volmit/host/MantleInvocation.java index 80a487886..e67c20056 100644 --- a/src/main/java/com/volmit/host/MantleInvocation.java +++ b/src/main/java/com/volmit/host/MantleInvocation.java @@ -2,16 +2,14 @@ package com.volmit.host; import com.volmit.IrisFeature; import com.volmit.config.FeatureSettings; -import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.SettingsStack; import com.volmit.generation.MantleGenerationContext; import com.volmit.mantle.Mantle; import com.volmit.random.WorldRandom; -import com.volmit.resource.PackResources; import com.volmit.world.PackWorld; import com.volmit.stage.MantleStageContext; import com.volmit.stage.Stage; import com.volmit.world.TerrainSampler; -import java.util.List; import java.util.Objects; /** The context every stage of one mantle invocation receives. */ @@ -34,7 +32,7 @@ final class MantleInvocation implements MantleStageContext { } @Override - public List> configured(Class settingsType) { + public SettingsStack configured(Class settingsType) { return stages.configured(settingsType); } @@ -63,21 +61,11 @@ final class MantleInvocation implements MantleStageContext { return inputs.mantle(); } - @Override - public long worldSeed() { - return inputs.worldSeed(); - } - @Override public PackWorld world() { return stages.world(inputs.world()); } - @Override - public PackResources resources() { - return inputs.resources(); - } - @Override public WorldRandom random() { return stages.random(); diff --git a/src/main/java/com/volmit/host/ModuleHost.java b/src/main/java/com/volmit/host/ModuleHost.java index 4e9925b25..37b63cd39 100644 --- a/src/main/java/com/volmit/host/ModuleHost.java +++ b/src/main/java/com/volmit/host/ModuleHost.java @@ -1,7 +1,7 @@ package com.volmit.host; -import com.volmit.FeatureAttachment; import com.volmit.IrisModule; +import com.volmit.config.Level; import com.volmit.resource.ResourceKind; import java.nio.file.Path; import java.util.ArrayList; @@ -34,7 +34,7 @@ import java.util.TreeSet; public record ModuleHost( List builtIns, Set exposedHostPackages, - Map> reservedHostFields, + Map> reservedHostFields, Set hostTypePackages, Set reservedFolders, List bundledJars, @@ -75,9 +75,9 @@ public record ModuleHost( } /** This configuration with {@code fields} also reserved as JSON fields the host itself uses, - * merged per attachment target with the fields reserved before. + * merged per level with the fields reserved before. */ - public ModuleHost reservingFields(Map> fields) { + public ModuleHost reservingFields(Map> fields) { return new ModuleHost(builtIns, exposedHostPackages, merge(reservedHostFields, fields), hostTypePackages, reservedFolders, bundledJars, jarCopyRoot, logger); } @@ -141,15 +141,15 @@ public record ModuleHost( return Path.of(System.getProperty(TEMPORARY_DIRECTORY_PROPERTY)); } - private static Map> copyOf(Map> fields) { - var copy = new EnumMap>(FeatureAttachment.Target.class); + private static Map> copyOf(Map> fields) { + var copy = new EnumMap>(Level.class); fields.forEach((target, names) -> copy.put(target, Set.copyOf(names))); return Map.copyOf(copy); } /** A blank field name, or one with ':' like a feature id, fails here, as it would as a settings key. */ - private static void requireFieldNames(Map> fields) { - fields.values().forEach(names -> names.forEach(FeatureAttachment::requireFieldName)); + private static void requireFieldNames(Map> fields) { + fields.values().forEach(names -> names.forEach(FeatureDescriptor::requireFieldName)); } private static void requireFolderNames(Set folders) { @@ -161,10 +161,10 @@ public record ModuleHost( } } - private static Map> merge( - Map> existing, - Map> added) { - var merged = new EnumMap>(FeatureAttachment.Target.class); + private static Map> merge( + Map> existing, + Map> added) { + var merged = new EnumMap>(Level.class); existing.forEach((target, names) -> merged.put(target, new TreeSet<>(names))); added.forEach((target, names) -> merged.computeIfAbsent(target, ignored -> new TreeSet<>()).addAll(names)); return merged; diff --git a/src/main/java/com/volmit/host/ModuleRegistry.java b/src/main/java/com/volmit/host/ModuleRegistry.java index 2615e018f..7b1a80104 100644 --- a/src/main/java/com/volmit/host/ModuleRegistry.java +++ b/src/main/java/com/volmit/host/ModuleRegistry.java @@ -1,9 +1,9 @@ package com.volmit.host; -import com.volmit.FeatureAttachment; import com.volmit.FeatureRegistry; import com.volmit.IrisFeature; import com.volmit.ModuleLifecycle; +import com.volmit.config.Level; import com.volmit.mantle.MantleCodec; import com.volmit.mantle.MantleKey; import com.volmit.mantle.MantleLifetime; @@ -56,10 +56,10 @@ public final class ModuleRegistry implements FeatureRegistry { } /** - * @param reservedHostFields JSON fields the host itself uses, per attachment target, which no settings key may take + * @param reservedHostFields JSON fields the host itself uses, per level, which no settings key may take * @param reservedFolders folders below the pack root that the host reads itself, which no resource kind may read */ - public ModuleRegistry(Map> reservedHostFields, Set reservedFolders) { + public ModuleRegistry(Map> reservedHostFields, Set reservedFolders) { reservedHostFields.forEach((target, names) -> names.forEach(name -> reserveHostField(target, name))); this.reservedFolders = Set.copyOf(reservedFolders); } @@ -105,8 +105,14 @@ public final class ModuleRegistry implements FeatureRegistry { } @Override - public void registerSettings(Class settingsType) { + public void registerSettings(Class... settingsTypes) { checkOpen(); + for (var settingsType : settingsTypes) { + registerOneSettings(settingsType); + } + } + + private void registerOneSettings(Class settingsType) { var descriptor = FeatureDescriptor.of(settingsType); requireOwnedId("Settings " + settingsType.getName() + " with feature id", descriptor.id()); catalogSettings(descriptor, registering); @@ -261,8 +267,8 @@ public final class ModuleRegistry implements FeatureRegistry { } } - private void reserveHostField(FeatureAttachment.Target target, String name) { - keyClaimants.put(new KeyAtTarget(target, FeatureAttachment.requireFieldName(name)), KeyClaimant.hostField()); + private void reserveHostField(Level target, String name) { + keyClaimants.put(new KeyAtTarget(target, FeatureDescriptor.requireFieldName(name)), KeyClaimant.hostField()); } private void claim(FeatureDescriptor descriptor, DiscoveredModule owner) { @@ -270,7 +276,7 @@ public final class ModuleRegistry implements FeatureRegistry { requireUnclaimedKeys(descriptor, owner); featureTypes.add(descriptor.type()); featureIds.add(descriptor.id()); - descriptor.attachment().targets().forEach(target -> + descriptor.targets().forEach(target -> keyClaimants.put(new KeyAtTarget(target, descriptor.key()), KeyClaimant.of(descriptor, owner))); } @@ -284,7 +290,7 @@ public final class ModuleRegistry implements FeatureRegistry { * names the claimants in a fixed order, so it does not depend on which module registered first. */ private void requireUnclaimedKeys(FeatureDescriptor descriptor, DiscoveredModule owner) { - for (var target : descriptor.attachment().targets()) { + for (var target : descriptor.targets()) { var earlier = keyClaimants.get(new KeyAtTarget(target, descriptor.key())); if (earlier == null) continue; var later = KeyClaimant.of(descriptor, owner); @@ -295,8 +301,8 @@ public final class ModuleRegistry implements FeatureRegistry { } } - private static String targetName(FeatureAttachment.Target target) { - return target.name().toLowerCase(Locale.ROOT).replace('_', ' '); + private static String targetName(Level target) { + return target.name().toLowerCase(Locale.ROOT); } private void checkOpen() { @@ -305,7 +311,7 @@ public final class ModuleRegistry implements FeatureRegistry { } } - private record KeyAtTarget(FeatureAttachment.Target target, String key) {} + private record KeyAtTarget(Level target, String key) {} /** Who holds a key: a field of the host's own JSON, a built-in module's feature or a pack module's, in that order. */ private record KeyClaimant(Source source, String feature, String text) implements Comparable { diff --git a/src/main/java/com/volmit/host/PackSchemaBuilder.java b/src/main/java/com/volmit/host/PackSchemaBuilder.java index 6ae91bf77..8b863b8b3 100644 --- a/src/main/java/com/volmit/host/PackSchemaBuilder.java +++ b/src/main/java/com/volmit/host/PackSchemaBuilder.java @@ -86,7 +86,7 @@ final class PackSchemaBuilder { FeatureSchema complete(Map types) { var descriptor = catalogued.descriptor(); return new FeatureSchema(descriptor.id(), descriptor.name(), catalogued.role(), owner.info(), descriptor.key(), descriptor.root(), - descriptor.attachment().targets(), types.get(descriptor.type().getName())); + descriptor.targets(),types.get(descriptor.type().getName())); } } diff --git a/src/main/java/com/volmit/host/PlacementInvocation.java b/src/main/java/com/volmit/host/PlacementInvocation.java index 630cb4d0f..e9ac78e5d 100644 --- a/src/main/java/com/volmit/host/PlacementInvocation.java +++ b/src/main/java/com/volmit/host/PlacementInvocation.java @@ -2,20 +2,18 @@ package com.volmit.host; import com.volmit.IrisFeature; import com.volmit.config.FeatureSettings; -import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.SettingsStack; import com.volmit.object.ObjectBlock; import com.volmit.object.ObjectTransformer; import com.volmit.placement.PlacementAccess; import com.volmit.placement.PlacementContext; import com.volmit.placement.PlacementRequest; import com.volmit.random.WorldRandom; -import com.volmit.resource.PackResources; import com.volmit.world.PackWorld; import com.volmit.stage.BlockStageContext; import com.volmit.stage.Stage; import com.volmit.world.BlockView; import com.volmit.world.TerrainSampler; -import java.util.List; import java.util.Objects; /** The context every stage of one placement attempt receives. Block accessors work only while @@ -74,7 +72,7 @@ final class PlacementInvocation implements BlockStageContext { } @Override - public List> configured(Class settingsType) { + public SettingsStack configured(Class settingsType) { return stages.configured(settingsType); } @@ -115,21 +113,11 @@ final class PlacementInvocation implements BlockStageContext { blockStatus = BlockStatus.SKIPPED; } - @Override - public long worldSeed() { - return inputs.worldSeed(); - } - @Override public PackWorld world() { return stages.world(inputs.world()); } - @Override - public PackResources resources() { - return inputs.resources(); - } - @Override public WorldRandom random() { return stages.random(); diff --git a/src/main/java/com/volmit/host/ScopedWorlds.java b/src/main/java/com/volmit/host/ScopedWorlds.java new file mode 100644 index 000000000..6250b36d7 --- /dev/null +++ b/src/main/java/com/volmit/host/ScopedWorlds.java @@ -0,0 +1,31 @@ +package com.volmit.host; + +import com.volmit.ModuleLog; +import com.volmit.world.PackWorld; +import java.util.Objects; + +/** The views of worlds one module's stages get, whose log is the module's own ({@link PackWorld#withLog}). It keeps + * the view of the world it was last asked for, so the stages of a host that generates one world per resolved graph + * get it without a new view per invocation; a host that alternates worlds on one graph asks the world each time. + * The kept world is released when the next one is asked for or the graph is dropped. Safe for concurrent use. + */ +final class ScopedWorlds { + private final ModuleLog log; + private volatile Scoped last; + + ScopedWorlds(ModuleLog log) { + this.log = Objects.requireNonNull(log, "log"); + } + + PackWorld of(PackWorld world) { + var scoped = last; + if (scoped != null && scoped.world() == world) { + return scoped.view(); + } + var view = world.withLog(log); + last = new Scoped(world, view); + return view; + } + + private record Scoped(PackWorld world, PackWorld view) {} +} diff --git a/src/main/java/com/volmit/host/StageInvocation.java b/src/main/java/com/volmit/host/StageInvocation.java index b7fa3864d..960fe0264 100644 --- a/src/main/java/com/volmit/host/StageInvocation.java +++ b/src/main/java/com/volmit/host/StageInvocation.java @@ -1,13 +1,12 @@ package com.volmit.host; import com.volmit.IrisFeature; -import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.SettingsStack; import com.volmit.random.WorldRandom; import com.volmit.stage.BlockStageContext; import com.volmit.stage.Stage; import com.volmit.world.PackWorld; import java.util.Arrays; -import java.util.List; import java.util.Objects; import java.util.function.BooleanSupplier; import java.util.stream.IntStream; @@ -30,7 +29,6 @@ final class StageInvocation { private final Object[] outputs; private final long invocationSeed; private final WorldRandom[] streams; - private final PackWorld[] scopedWorlds; private int current = NO_STAGE; StageInvocation(ResolvedGraph graph, long invocationSeed, ConfiguredSettings settings) { @@ -41,7 +39,6 @@ final class StageInvocation { Arrays.fill(outputs, PENDING); this.invocationSeed = invocationSeed; streams = new WorldRandom[graph.size()]; - scopedWorlds = new PackWorld[graph.size()]; } boolean isActive(int position) { @@ -127,10 +124,7 @@ final class StageInvocation { if (current == NO_STAGE) { return world; } - if (scopedWorlds[current] == null) { - scopedWorlds[current] = world.withLog(graph.executable(current).log()); - } - return scopedWorlds[current]; + return graph.executable(current).worlds().of(world); } private ExecutableStage currentStage() { @@ -140,9 +134,9 @@ final class StageInvocation { return graph.executable(current); } - /** The entries that activated the running stage, which must be conditioned on {@code type}. */ - @SuppressWarnings("unchecked") // The slot holds the entries of the type the stage is conditioned on. - List> configured(Class type) { + /** The stack that activated the running stage, which must be conditioned on {@code type}. */ + @SuppressWarnings("unchecked") // The slot holds the stack of the type the stage is conditioned on. + SettingsStack configured(Class type) { Objects.requireNonNull(type, "settingsType"); if (current == NO_STAGE) { throw new IllegalStateException("Configured settings can only be read while a stage runs"); @@ -154,7 +148,7 @@ final class StageInvocation { + ") but is not conditioned on it; add when(" + type.getSimpleName() + ".class) to its definition," + " or read other settings through settings()"); } - return (List>) settingsBySlot[slot]; + return (SettingsStack) settingsBySlot[slot]; } @SuppressWarnings("unchecked") // Settings types come from when(Class). @@ -162,8 +156,8 @@ final class StageInvocation { var types = graph.settingsTypes(); var values = new Object[types.size()]; for (int slot = 0; slot < values.length; slot++) { - var entries = settings.find((Class) types.get(slot)); - values[slot] = entries.isEmpty() ? null : entries; + var stack = settings.find((Class) types.get(slot)); + values[slot] = stack.isEmpty() ? null : stack; } return values; } diff --git a/src/main/java/com/volmit/host/schema/FeatureSchema.java b/src/main/java/com/volmit/host/schema/FeatureSchema.java index 3c5ed911b..c03890810 100644 --- a/src/main/java/com/volmit/host/schema/FeatureSchema.java +++ b/src/main/java/com/volmit/host/schema/FeatureSchema.java @@ -1,7 +1,7 @@ package com.volmit.host.schema; -import com.volmit.FeatureAttachment; import com.volmit.ModuleInfo; +import com.volmit.config.Level; import com.volmit.resource.ResourceId; import java.util.Collections; import java.util.EnumSet; @@ -16,7 +16,7 @@ import java.util.Set; * @param module the module that owns the feature id * @param key the JSON key the settings are written under, declared by the feature, the same at every target * @param root the option whose value the key holds, when the JSON is that value and not an object of options - * @param targets where the keys appear, in {@link FeatureAttachment.Target} order + * @param targets the levels whose files hold the key, in {@link Level} order * @param settings the settings class; its description describes the value */ public record FeatureSchema( @@ -26,7 +26,7 @@ public record FeatureSchema( ModuleInfo module, String key, Optional root, - Set targets, + Set targets, ObjectType settings) { public FeatureSchema { Objects.requireNonNull(id, "id"); diff --git a/src/main/java/com/volmit/host/schema/PackSchema.java b/src/main/java/com/volmit/host/schema/PackSchema.java index 3e4c3580d..c995312fa 100644 --- a/src/main/java/com/volmit/host/schema/PackSchema.java +++ b/src/main/java/com/volmit/host/schema/PackSchema.java @@ -1,6 +1,6 @@ package com.volmit.host.schema; -import com.volmit.FeatureAttachment; +import com.volmit.config.Level; import com.volmit.resource.ResourceId; import java.util.Comparator; import java.util.List; @@ -34,8 +34,8 @@ public record PackSchema(List features, List .orElseThrow(() -> new NoSuchElementException("No resource kind: " + id)); } - /** The module features of one attachment target, by JSON key. */ - public List fields(FeatureAttachment.Target target) { + /** The module features written in the files of one level, by JSON key. */ + public List fields(Level target) { Objects.requireNonNull(target, "target"); return features.stream() .filter(feature -> feature.targets().contains(target)) diff --git a/src/main/java/com/volmit/noise/NoiseFactory.java b/src/main/java/com/volmit/noise/NoiseFactory.java index 9f1f0e899..aa6d4717b 100644 --- a/src/main/java/com/volmit/noise/NoiseFactory.java +++ b/src/main/java/com/volmit/noise/NoiseFactory.java @@ -6,7 +6,7 @@ package com.volmit.noise; */ public interface NoiseFactory { /** The noise {@code style} describes, seeded with {@code seed}. The same style and seed give the same values - * in every world of the pack, so derive the seed from the world seed ({@code context.worldSeed()}), not from a + * in every world of the pack, so derive the seed from the world seed ({@code context.world().seed()}), not from a * stage's random stream, when the noise must line up across chunks. The host keeps what it builds for the pack * snapshot, so asking again for the same style and seed is cheap. * diff --git a/src/main/java/com/volmit/stage/StageContext.java b/src/main/java/com/volmit/stage/StageContext.java index 64d3ebe8f..34fb2bb1d 100644 --- a/src/main/java/com/volmit/stage/StageContext.java +++ b/src/main/java/com/volmit/stage/StageContext.java @@ -1,9 +1,8 @@ package com.volmit.stage; import com.volmit.IrisFeature; -import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.SettingsStack; 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. */ public interface StageContext { @@ -20,10 +19,10 @@ public interface StageContext { */ O output(Stage stage); - /** The entries of the settings this stage is conditioned on with {@code when(settingsType)}, in level order: the + /** The stack 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()}. */ - List> configured(Class settingsType); + SettingsStack configured(Class settingsType); } diff --git a/src/main/java/com/volmit/world/PackWorld.java b/src/main/java/com/volmit/world/PackWorld.java index 93f5431f5..4945b4bbd 100644 --- a/src/main/java/com/volmit/world/PackWorld.java +++ b/src/main/java/com/volmit/world/PackWorld.java @@ -15,6 +15,10 @@ import java.util.function.Function; * such as after a tool rewrote some of its files. State therefore never outlives the resources it was built from. * Invocations that began before the restart finish with the world they began with. * + *

A placement a tool makes outside the worlds the host generates, such as a studio paste, runs in a world of its own + * that the host builds for that placement: the pack's resources and settings, a seed the host picks, and a state store + * that lives as long as the placement. No lifecycle hook runs for it. + * *

Safe to use from any thread. */ public interface PackWorld { diff --git a/src/main/java/com/volmit/world/TerrainSampler.java b/src/main/java/com/volmit/world/TerrainSampler.java index c420d5365..cdc0eb1b0 100644 --- a/src/main/java/com/volmit/world/TerrainSampler.java +++ b/src/main/java/com/volmit/world/TerrainSampler.java @@ -21,6 +21,14 @@ public interface TerrainSampler { default double surfaceY(int worldX, int worldZ) { return column(worldX, worldZ).surfaceY(); } + + /** The column's surface height in whole blocks: {@link #surfaceY} rounded to the nearest block, for a module that + * places blocks at the surface. The host may answer it from the whole height it keeps. Outside the bounds it throws + * like {@link #column}. + */ + default int surfaceHeight(int worldX, int worldZ) { + return (int) Math.round(surfaceY(worldX, worldZ)); + } BiomeSample biome(int worldX, int y, int worldZ); /** The {@link BiomeSample#caveBiome()} alone, for a module that asks it block by block and needs neither the region @@ -43,7 +51,9 @@ public interface TerrainSampler { OptionalInt upperDimensionY(int worldX, int worldZ); /** The id of the column's surface biome, as {@link BiomeSample#surfaceBiome()} gives it, for a module that asks about every - * column of a chunk and has no use for the rest of the sample. The host may answer it without working out the cave biome. + * column of a chunk and has no use for the rest of the sample. The surface biome is the column's, the same at every + * height, so this takes no Y; the default samples at the bottom. The host may answer it without working out the cave + * biome. Outside the bounds it throws like {@link #column}. */ default ResourceId surfaceBiome(int worldX, int worldZ) { return biome(worldX, bounds().minY(), worldZ).surfaceBiome(); diff --git a/src/test/java/com/volmit/FeatureContractTest.java b/src/test/java/com/volmit/FeatureContractTest.java index 40e0fa97d..cb970ece6 100644 --- a/src/test/java/com/volmit/FeatureContractTest.java +++ b/src/test/java/com/volmit/FeatureContractTest.java @@ -11,7 +11,7 @@ import static org.junit.jupiter.api.Assertions.*; class FeatureContractTest { @Desc("Example settings") @Snippet("fill-settings") - @Feature(id = "example:fill", name = "Fill", key = "fill", targets = FeatureAttachment.Target.BIOME) + @Feature(id = "example:fill", name = "Fill", key = "fill", targets = Level.BIOME) public static class FillOptions implements IrisFeature { @Desc("Replacement value") @MinNumber(0) @@ -41,27 +41,27 @@ class FeatureContractTest { assertEquals(ResourceId.parse("example:fill"), descriptor.id()); assertEquals("fill", descriptor.key()); assertEquals(java.util.Optional.empty(), descriptor.root()); - assertEquals(java.util.Set.of(FeatureAttachment.Target.BIOME), descriptor.attachment().targets()); + assertEquals(java.util.Set.of(Level.BIOME), descriptor.targets()); assertEquals(1, descriptor.options().options().size()); } - @Feature(id = "example:blank", name = "Blank", key = " ", targets = FeatureAttachment.Target.BIOME) + @Feature(id = "example:blank", name = "Blank", key = " ", targets = Level.BIOME) static class BlankKey implements IrisFeature {} - @Feature(id = "example:namespaced", name = "Namespaced", key = "example:namespaced", targets = FeatureAttachment.Target.BIOME) + @Feature(id = "example:namespaced", name = "Namespaced", key = "example:namespaced", targets = Level.BIOME) static class NamespacedKey implements IrisFeature {} - @Feature(id = "example:list", name = "List", key = "items", root = "items", targets = FeatureAttachment.Target.BIOME) + @Feature(id = "example:list", name = "List", key = "items", root = "items", targets = Level.BIOME) static class ListRoot implements IrisFeature { private java.util.List items = java.util.List.of(); } - @Feature(id = "example:missing", name = "Missing", key = "missing", root = "absent", targets = FeatureAttachment.Target.BIOME) + @Feature(id = "example:missing", name = "Missing", key = "missing", root = "absent", targets = Level.BIOME) static class RootNamingNoOption implements IrisFeature { private java.util.List items = java.util.List.of(); } - @Feature(id = "example:two", name = "Two", key = "two", root = "items", targets = FeatureAttachment.Target.BIOME) + @Feature(id = "example:two", name = "Two", key = "two", root = "items", targets = Level.BIOME) static class RootWithAnotherOption implements IrisFeature { private java.util.List items = java.util.List.of(); private int unreachable = 1; diff --git a/src/test/java/com/volmit/config/SettingsStackTest.java b/src/test/java/com/volmit/config/SettingsStackTest.java new file mode 100644 index 000000000..2b857fcf9 --- /dev/null +++ b/src/test/java/com/volmit/config/SettingsStackTest.java @@ -0,0 +1,91 @@ +package com.volmit.config; + +import com.volmit.IrisFeature; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.resource.ResourceId; +import com.volmit.support.ColumnSettings; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +class SettingsStackTest { + private static final ResourceId DIMENSION = ResourceId.parse("pack:dimension/overworld"); + private static final ResourceId REGION = ResourceId.parse("pack:region/temperate"); + private static final ResourceId PLAINS = ResourceId.parse("pack:biome/plains"); + private static final ResourceId SWAMP = ResourceId.parse("pack:biome/swamp"); + private static final ResourceId TREE = ResourceId.parse("pack:object/tree"); + + @Feature(id = "test:depth", name = "Depth", key = "depth", targets = {Level.DIMENSION, Level.REGION, Level.BIOME, Level.PLACEMENT}) + record Depth(int value) implements IrisFeature {} + + private static Entry entry(Level level, ResourceId source, int depth) { + return new Entry<>(level, source, new Depth(depth)); + } + + @Test + void sortsByLevelAndKeepsTheOrderWithinALevel() { + var swamp = entry(Level.BIOME, SWAMP, 3); + var plains = entry(Level.BIOME, PLAINS, 4); + var region = entry(Level.REGION, REGION, 2); + var dimension = entry(Level.DIMENSION, DIMENSION, 1); + + var stack = SettingsStack.of(List.of(swamp, region, plains, dimension)); + + assertEquals(List.of(dimension, region, swamp, plains), stack.entries()); + assertEquals(List.of(1, 2, 3, 4), stack.values().stream().map(Depth::value).toList()); + } + + @Test + void picksTheDimensionALevelOrTheMostSpecificValue() { + var stack = SettingsStack.of(List.of(entry(Level.PLACEMENT, TREE, 9), entry(Level.BIOME, SWAMP, 3), + entry(Level.BIOME, PLAINS, 4), entry(Level.DIMENSION, DIMENSION, 1))); + + assertEquals(Optional.of(new Depth(1)), stack.dimension()); + assertEquals(Optional.of(new Depth(3)), stack.level(Level.BIOME), "the first entry of the level"); + assertEquals(Optional.empty(), stack.level(Level.REGION)); + assertEquals(Optional.of(new Depth(9)), stack.mostSpecific()); + } + + @Test + void anEmptyStackHasNothingToPick() { + var empty = SettingsStack.of(List.of()); + + assertSame(SettingsStack.empty(), empty); + assertTrue(empty.isEmpty()); + assertEquals(Optional.empty(), empty.dimension()); + assertEquals(Optional.empty(), empty.mostSpecific()); + assertEquals(List.of(), empty.values()); + } + + @Test + void stacksOfEqualEntriesAreEqualAndImmutable() { + var first = SettingsStack.of(List.of(entry(Level.BIOME, PLAINS, 4))); + var second = SettingsStack.of(List.of(entry(Level.BIOME, PLAINS, 4))); + + assertEquals(first, second); + assertEquals(first.hashCode(), second.hashCode()); + assertThrows(UnsupportedOperationException.class, () -> first.entries().clear()); + } + + @Test + void aChunkDeclaresEveryDistinctEntryOfItsColumnsInLevelOrder() { + var dimension = entry(Level.DIMENSION, DIMENSION, 1); + var swamp = entry(Level.BIOME, SWAMP, 3); + var plains = entry(Level.BIOME, PLAINS, 4); + var settings = new ColumnSettings((x, z) -> List.of(Math.floorMod(x, 16) < 8 ? swamp : plains, dimension)); + + assertEquals(List.of(dimension, swamp, plains), settings.declaredInChunk(Depth.class, -1, 2).entries()); + assertTrue(ColumnSettings.NONE.declaredInChunk(Depth.class, 0, 0).isEmpty()); + } + + @Test + void aChunkReadsItsOwnColumnsOnly() { + var plains = entry(Level.BIOME, PLAINS, 4); + var onlyChunkOneZero = new ColumnSettings((x, z) -> x >= 16 && x < 32 && z >= 0 && z < 16 ? List.of(plains) : List.of()); + + assertEquals(List.of(plains), onlyChunkOneZero.declaredInChunk(Depth.class, 1, 0).entries()); + assertTrue(onlyChunkOneZero.declaredInChunk(Depth.class, 0, 0).isEmpty()); + assertTrue(onlyChunkOneZero.declaredInChunk(Depth.class, 2, 0).isEmpty()); + } +} diff --git a/src/test/java/com/volmit/example/ChunkPipelineTest.java b/src/test/java/com/volmit/example/ChunkPipelineTest.java index 22e788fd8..43e33391a 100644 --- a/src/test/java/com/volmit/example/ChunkPipelineTest.java +++ b/src/test/java/com/volmit/example/ChunkPipelineTest.java @@ -1,6 +1,5 @@ package com.volmit.example; -import com.volmit.FeatureAttachment.Target; import com.volmit.IrisFeature; import com.volmit.IrisModule; import com.volmit.ModuleInfo; @@ -8,6 +7,7 @@ import com.volmit.ModuleSetup; import com.volmit.block.BlockState; import com.volmit.config.Feature; import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.Level; import com.volmit.example.chunk.GrassModule; import com.volmit.example.chunk.GrassSettings; import com.volmit.example.chunk.TerrainModule; @@ -49,7 +49,7 @@ class ChunkPipelineTest { private static final ResourceId PLAINS = ResourceId.parse("pack:biome/plains"); private static final ResourceId SWAMP = ResourceId.parse("pack:biome/swamp"); - @Feature(id = "test:levels", name = "Levels", key = "levels", targets = {Target.DIMENSION, Target.BIOME}) + @Feature(id = "test:levels", name = "Levels", key = "levels", targets = {Level.DIMENSION, Level.BIOME}) static final class Marker implements IrisFeature {} private static ChunkRunner runner() { @@ -67,7 +67,7 @@ class ChunkPipelineTest { } private static Entry grass(ResourceId biome) { - return new Entry<>(Target.BIOME, biome, new GrassSettings()); + return new Entry<>(Level.BIOME, biome, new GrassSettings()); } @Test @@ -107,17 +107,17 @@ class ChunkPipelineTest { @Test void levelsStackAndTheBodyGetsEveryDistinctEntryOfTheChunkInLevelOrder() { - var dimension = new Entry<>(Target.DIMENSION, DIMENSION, new Marker()); - var plains = new Entry<>(Target.BIOME, PLAINS, new Marker()); - var swamp = new Entry<>(Target.BIOME, SWAMP, new Marker()); + var dimension = new Entry<>(Level.DIMENSION, DIMENSION, new Marker()); + var plains = new Entry<>(Level.BIOME, PLAINS, new Marker()); + var swamp = new Entry<>(Level.BIOME, SWAMP, new Marker()); var received = new ArrayList>(); var stage = Stage.chunk("test:levels/read"); IrisModule module = new IrisModule() { public ModuleInfo info() { return ModuleInfo.of("test:levels", "Levels", "1"); } public void setup(ModuleSetup setup) { setup.stages().define(stage).when(Marker.class).run(context -> { - 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.configured(Marker.class).entries().stream().map(Entry::source).toList()); + received.add(context.settings().at(Marker.class, 0, 0).entries().stream().map(Entry::source).toList()); }); } }; @@ -133,7 +133,7 @@ class ChunkPipelineTest { @Test void mantleStagesWriteBeyondTheirChunkAndChunkStagesReadTheirOwnPart() { var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(new VeinModule())), Map.of(), Set.of(), Set.of()); - var vein = new Entry<>(Target.BIOME, PLAINS, new VeinSettings(12, 4)); + var vein = new Entry<>(Level.BIOME, PLAINS, new VeinSettings(12, 4)); int reach = loaded.mantle().stages().getFirst().reachBlocks(new DeclaredSettings(vein)); assertEquals(3, reach, "a 12 block vein from the centre column runs 3 blocks into the next chunk"); var mantle = new MemoryMantle(); diff --git a/src/test/java/com/volmit/example/chunk/GrassModule.java b/src/test/java/com/volmit/example/chunk/GrassModule.java index fc4ab6e05..52694da35 100644 --- a/src/test/java/com/volmit/example/chunk/GrassModule.java +++ b/src/test/java/com/volmit/example/chunk/GrassModule.java @@ -33,12 +33,12 @@ public final class GrassModule implements IrisModule { var blocks = context.hunk(BlockState.class); for (int x = 0; x < blocks.getWidth(); x++) { for (int z = 0; z < blocks.getDepth(); z++) { - var here = context.settings().at(GrassSettings.class, context.originX() + x, context.originZ() + z); + var here = context.settings().at(GrassSettings.class, context.originX() + x, context.originZ() + z).mostSpecific(); int height = heights.at(x, z); if (here.isEmpty() || height <= 0) { continue; } - blocks.set(x, height - 1, z, here.getLast().value().block()); // the most specific level wins here + blocks.set(x, height - 1, z, here.get().block()); } } } diff --git a/src/test/java/com/volmit/example/chunk/GrassSettings.java b/src/test/java/com/volmit/example/chunk/GrassSettings.java index 939a65e6b..dd6cb1460 100644 --- a/src/test/java/com/volmit/example/chunk/GrassSettings.java +++ b/src/test/java/com/volmit/example/chunk/GrassSettings.java @@ -1,13 +1,13 @@ package com.volmit.example.chunk; -import com.volmit.FeatureAttachment; import com.volmit.IrisFeature; import com.volmit.block.BlockState; import com.volmit.config.Desc; import com.volmit.config.Feature; +import com.volmit.config.Level; @Desc("Covers the top of every terrain column") -@Feature(id = "example:grass", name = "Grass", key = "grass", targets = FeatureAttachment.Target.BIOME) +@Feature(id = "example:grass", name = "Grass", key = "grass", targets = Level.BIOME) public final class GrassSettings implements IrisFeature { @Desc("Block placed on top of each column") private BlockState block = new BlockState("minecraft:grass_block"); diff --git a/src/test/java/com/volmit/example/chunk/VeinModule.java b/src/test/java/com/volmit/example/chunk/VeinModule.java index f27b470c8..86359beba 100644 --- a/src/test/java/com/volmit/example/chunk/VeinModule.java +++ b/src/test/java/com/volmit/example/chunk/VeinModule.java @@ -5,6 +5,7 @@ import com.volmit.ModuleInfo; import com.volmit.ModuleSetup; import com.volmit.block.BlockState; import com.volmit.config.PackSettings; +import com.volmit.generation.ChunkContext; import com.volmit.mantle.BlockBox; import com.volmit.mantle.MantleCodec; import com.volmit.mantle.MantleKey; @@ -28,8 +29,6 @@ public final class VeinModule implements IrisModule { public static final MantleStage PLAN = Stage.mantle("example:veins/plan"); public static final ChunkStage PLACE = Stage.chunk("example:veins/place"); public static final BlockState ORE_BLOCK = new BlockState("minecraft:iron_ore"); - private static final int CHUNK_WIDTH = 16; - private static final int CHUNK_CENTRE = 7; private static final int PLANNED = 1; @Override @@ -46,18 +45,18 @@ public final class VeinModule implements IrisModule { /** How far the longest vein any level of the pack declares runs past its chunk. */ public static int reach(PackSettings settings) { - int longest = settings.declared(VeinSettings.class).stream().mapToInt(vein -> vein.value().length()).max().orElse(0); - return Math.max(0, longest - (CHUNK_WIDTH - CHUNK_CENTRE)); + int longest = settings.declared(VeinSettings.class).values().stream().mapToInt(VeinSettings::length).max().orElse(0); + return Math.max(0, longest - (ChunkContext.CHUNK_WIDTH - ChunkContext.CENTRE_COLUMN)); } /** One vein per level that configures veins at the chunk's centre column: levels stack. */ private static void plan(MantleStageContext context) { - int startX = context.originX() + CHUNK_CENTRE; - int z = context.originZ() + CHUNK_CENTRE; + int startX = context.centreX(); + int z = context.centreZ(); var ore = context.mantle().layer(ORE); - for (var vein : context.settings().at(VeinSettings.class, startX, z)) { - for (int step = 0; step < vein.value().length(); step++) { - ore.set(startX + step, vein.value().y(), z, PLANNED); + for (var vein : context.settings().at(VeinSettings.class, startX, z).values()) { + for (int step = 0; step < vein.length(); step++) { + ore.set(startX + step, vein.y(), z, PLANNED); } } } diff --git a/src/test/java/com/volmit/example/chunk/VeinSettings.java b/src/test/java/com/volmit/example/chunk/VeinSettings.java index b1b791ffe..ac1fdf70a 100644 --- a/src/test/java/com/volmit/example/chunk/VeinSettings.java +++ b/src/test/java/com/volmit/example/chunk/VeinSettings.java @@ -1,12 +1,12 @@ package com.volmit.example.chunk; -import com.volmit.FeatureAttachment; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; +import com.volmit.config.Level; @Desc("Plans a horizontal ore vein from the centre of each chunk, which may run into the next chunk") -@Feature(id = "example:veins", name = "Veins", key = "veins", targets = {FeatureAttachment.Target.DIMENSION, FeatureAttachment.Target.BIOME}) +@Feature(id = "example:veins", name = "Veins", key = "veins", targets = {Level.DIMENSION, Level.BIOME}) public final class VeinSettings implements IrisFeature { @Desc("Blocks along X, starting at the chunk's centre column") private int length = 12; diff --git a/src/test/java/com/volmit/example/placement/MossModule.java b/src/test/java/com/volmit/example/placement/MossModule.java index 3a3e20751..156a7ebe9 100644 --- a/src/test/java/com/volmit/example/placement/MossModule.java +++ b/src/test/java/com/volmit/example/placement/MossModule.java @@ -34,7 +34,7 @@ public final class MossModule implements IrisModule { } private static void spread(PlacementStageContext context) { - var moss = context.configured(MossSettings.class).getFirst().value(); // a placement declares its settings once + var moss = context.configured(MossSettings.class).mostSpecific().orElseThrow(); // a placement declares its settings once var anchor = context.output(AnchorModule.HEIGHT).anchor(); var access = context.access(); int groundY = anchor.y() - 1; diff --git a/src/test/java/com/volmit/example/placement/MossSettings.java b/src/test/java/com/volmit/example/placement/MossSettings.java index 754ca6054..177e136af 100644 --- a/src/test/java/com/volmit/example/placement/MossSettings.java +++ b/src/test/java/com/volmit/example/placement/MossSettings.java @@ -1,11 +1,11 @@ package com.volmit.example.placement; -import com.volmit.FeatureAttachment; import com.volmit.IrisFeature; import com.volmit.config.Feature; +import com.volmit.config.Level; import com.volmit.config.MinNumber; -@Feature(id = "example:moss", name = "Moss", key = "moss", targets = FeatureAttachment.Target.OBJECT_PLACEMENT) +@Feature(id = "example:moss", name = "Moss", key = "moss", targets = Level.PLACEMENT) public final class MossSettings implements IrisFeature { @MinNumber(0) private int radius; diff --git a/src/test/java/com/volmit/example/placement/SnowModule.java b/src/test/java/com/volmit/example/placement/SnowModule.java index 32fd499b5..f55125051 100644 --- a/src/test/java/com/volmit/example/placement/SnowModule.java +++ b/src/test/java/com/volmit/example/placement/SnowModule.java @@ -42,7 +42,7 @@ public final class SnowModule implements IrisModule { } private static void cover(PlacementStageContext context) { - var snow = context.configured(SnowSettings.class).getFirst().value(); // a placement declares its settings once + var snow = context.configured(SnowSettings.class).mostSpecific().orElseThrow(); // a placement declares its settings once var layer = SNOW.withProperty("layers", Integer.toString(snow.layers())); var access = context.access(); for (var top : context.output(COLLECT).tops()) { diff --git a/src/test/java/com/volmit/example/placement/SnowSettings.java b/src/test/java/com/volmit/example/placement/SnowSettings.java index db7127ba4..da8207d67 100644 --- a/src/test/java/com/volmit/example/placement/SnowSettings.java +++ b/src/test/java/com/volmit/example/placement/SnowSettings.java @@ -1,12 +1,12 @@ package com.volmit.example.placement; -import com.volmit.FeatureAttachment; import com.volmit.IrisFeature; import com.volmit.config.Feature; +import com.volmit.config.Level; import com.volmit.config.MaxNumber; import com.volmit.config.MinNumber; -@Feature(id = "iris:snow", name = "Snow", key = "snow", targets = FeatureAttachment.Target.OBJECT_PLACEMENT) +@Feature(id = "iris:snow", name = "Snow", key = "snow", targets = Level.PLACEMENT) public final class SnowSettings implements IrisFeature { @MinNumber(1) @MaxNumber(8) diff --git a/src/test/java/com/volmit/example/placement/StiltModule.java b/src/test/java/com/volmit/example/placement/StiltModule.java index 654d99418..5bd1b5036 100644 --- a/src/test/java/com/volmit/example/placement/StiltModule.java +++ b/src/test/java/com/volmit/example/placement/StiltModule.java @@ -36,7 +36,7 @@ public final class StiltModule implements IrisModule { } private static void fill(PlacementStageContext context) { - var stilt = context.configured(StiltSettings.class).getFirst().value(); // a placement declares its settings once + var stilt = context.configured(StiltSettings.class).mostSpecific().orElseThrow(); // a placement declares its settings once var anchor = context.output(AnchorModule.HEIGHT); for (var block : context.output(BOUNDS).lowestLayer()) { var bottom = anchor.worldPosition(context.request(), block.position()); diff --git a/src/test/java/com/volmit/example/placement/StiltSettings.java b/src/test/java/com/volmit/example/placement/StiltSettings.java index 6bc5b8df4..c0ca4e5c1 100644 --- a/src/test/java/com/volmit/example/placement/StiltSettings.java +++ b/src/test/java/com/volmit/example/placement/StiltSettings.java @@ -1,13 +1,13 @@ package com.volmit.example.placement; -import com.volmit.FeatureAttachment; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; +import com.volmit.config.Level; import com.volmit.config.MinNumber; @Desc("Fills the space below an object down to the ground") -@Feature(id = "iris:stilt", name = "Stilt", key = "stilt", targets = FeatureAttachment.Target.OBJECT_PLACEMENT) +@Feature(id = "iris:stilt", name = "Stilt", key = "stilt", targets = Level.PLACEMENT) public final class StiltSettings implements IrisFeature { @Desc("Maximum blocks filled below each lowest object block") @MinNumber(1) diff --git a/src/test/java/com/volmit/example/terrain/LayersSettings.java b/src/test/java/com/volmit/example/terrain/LayersSettings.java index 0a91936dd..d460e03f9 100644 --- a/src/test/java/com/volmit/example/terrain/LayersSettings.java +++ b/src/test/java/com/volmit/example/terrain/LayersSettings.java @@ -1,14 +1,14 @@ package com.volmit.example.terrain; -import com.volmit.FeatureAttachment; import com.volmit.IrisFeature; import com.volmit.config.Desc; import com.volmit.config.Feature; +import com.volmit.config.Level; import com.volmit.example.hosttypes.Palette; import java.util.List; /** Built-in settings holding host types, written in pack JSON as a bare list: {@code "layers": [...]}. */ -@Feature(id = "iris:layers", name = "Layers", key = "layers", targets = FeatureAttachment.Target.BIOME) +@Feature(id = "iris:layers", name = "Layers", key = "layers", targets = Level.BIOME) public final class LayersSettings implements IrisFeature { @Desc("Rock layers from the surface down") private List layers = List.of(); diff --git a/src/test/java/com/volmit/example/world/WorldStateExampleTest.java b/src/test/java/com/volmit/example/world/WorldStateExampleTest.java index 1ca09ca98..4c08861f3 100644 --- a/src/test/java/com/volmit/example/world/WorldStateExampleTest.java +++ b/src/test/java/com/volmit/example/world/WorldStateExampleTest.java @@ -70,7 +70,7 @@ class WorldStateExampleTest { } private static void plant(ChunkStageContext context) { - planted(context.world()).chunks.add(key(context.originX() >> 4, context.originZ() >> 4)); + planted(context.world()).chunks.add(key(context.chunkX(), context.chunkZ())); } private static Set objectsAt(PackWorld world, int chunkX, int chunkZ) { diff --git a/src/test/java/com/volmit/generation/ChunkContextTest.java b/src/test/java/com/volmit/generation/ChunkContextTest.java new file mode 100644 index 000000000..9c75f51b5 --- /dev/null +++ b/src/test/java/com/volmit/generation/ChunkContextTest.java @@ -0,0 +1,58 @@ +package com.volmit.generation; + +import com.volmit.config.FeatureSettings; +import com.volmit.mantle.BlockBox; +import com.volmit.mantle.Mantle; +import com.volmit.world.PackWorld; +import com.volmit.world.TerrainSampler; +import java.lang.reflect.Proxy; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +class ChunkContextTest { + private static final int BOTTOM = 0; + private static final int TOP = 384; + + /** A sampler that only knows its bounds. */ + private static TerrainSampler terrainWithin(BlockBox bounds) { + return (TerrainSampler) Proxy.newProxyInstance(TerrainSampler.class.getClassLoader(), new Class[] {TerrainSampler.class}, + (proxy, method, arguments) -> { + if (method.getName().equals("bounds")) { + return bounds; + } + throw new AssertionError("Unused " + method.getName()); + }); + } + + private static ChunkContext chunkAt(int originX, int originZ) { + var terrain = terrainWithin(new BlockBox(originX - 8, BOTTOM, originZ - 8, originX + 24, TOP, originZ + 24)); + return new MantleGenerationContext() { + public int originX() { return originX; } + public int originZ() { return originZ; } + public PackWorld world() { throw new AssertionError("Unused world"); } + public TerrainSampler terrain() { return terrain; } + public FeatureSettings settings() { throw new AssertionError("Unused settings"); } + public Mantle mantle() { throw new AssertionError("Unused mantle"); } + }; + } + + @Test + void namesTheChunkItsCentreColumnAndItsArea() { + var chunk = chunkAt(32, -48); + + assertEquals(2, chunk.chunkX()); + assertEquals(-3, chunk.chunkZ()); + assertEquals(39, chunk.centreX()); + assertEquals(-41, chunk.centreZ()); + assertEquals(new BlockBox(32, BOTTOM, -48, 48, TOP, -32), chunk.area(), "the chunk's columns at the terrain's full height"); + } + + @Test + void theChunkLeftOfTheOriginIsMinusOne() { + var chunk = chunkAt(-16, -16); + + assertEquals(-1, chunk.chunkX()); + assertEquals(-1, chunk.chunkZ()); + assertEquals(-9, chunk.centreX()); + } +} diff --git a/src/test/java/com/volmit/host/ConfiguredSettingsTest.java b/src/test/java/com/volmit/host/ConfiguredSettingsTest.java index db9ee64cc..68acadd12 100644 --- a/src/test/java/com/volmit/host/ConfiguredSettingsTest.java +++ b/src/test/java/com/volmit/host/ConfiguredSettingsTest.java @@ -1,9 +1,9 @@ package com.volmit.host; -import com.volmit.FeatureAttachment.Target; import com.volmit.IrisFeature; import com.volmit.config.Feature; import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.Level; import com.volmit.resource.ResourceId; import java.util.List; import org.junit.jupiter.api.Test; @@ -14,34 +14,34 @@ class ConfiguredSettingsTest { private static final ResourceId BIOME = ResourceId.parse("pack:biome/plains"); private static final ResourceId OBJECT = ResourceId.parse("pack:object/tree"); - @Feature(id = "test:levels", name = "Levels", key = "levels", targets = {Target.DIMENSION, Target.BIOME, Target.OBJECT_PLACEMENT}) + @Feature(id = "test:levels", name = "Levels", key = "levels", targets = {Level.DIMENSION, Level.BIOME, Level.PLACEMENT}) static final class Levels implements IrisFeature {} - @Feature(id = "test:other", name = "Other", key = "other", targets = Target.BIOME) + @Feature(id = "test:other", name = "Other", key = "other", targets = Level.BIOME) static final class Other implements IrisFeature {} @Test void entriesAreGroupedByTypeInLevelOrderAndNeverMerged() { - var biome = new Entry<>(Target.BIOME, BIOME, new Levels()); - var dimension = new Entry<>(Target.DIMENSION, DIMENSION, new Levels()); + var biome = new Entry<>(Level.BIOME, BIOME, new Levels()); + var dimension = new Entry<>(Level.DIMENSION, DIMENSION, new Levels()); var settings = ConfiguredSettings.of(List.of(biome, dimension)); - assertEquals(List.of(dimension, biome), settings.find(Levels.class)); - assertEquals(List.of(), settings.find(Other.class)); - assertEquals(List.of(), ConfiguredSettings.none().find(Levels.class)); + assertEquals(List.of(dimension, biome), settings.find(Levels.class).entries()); + assertTrue(settings.find(Other.class).isEmpty()); + assertTrue(ConfiguredSettings.none().find(Levels.class).isEmpty()); } - @Feature(id = "test:base", name = "Base", key = "base", targets = {Target.BIOME, Target.OBJECT_PLACEMENT}) + @Feature(id = "test:base", name = "Base", key = "base", targets = {Level.BIOME, Level.PLACEMENT}) static class Base implements IrisFeature {} static final class Refined extends Base {} @Test void aSubclassValueIsFoundUnderTheTypeThatDeclaresItsFeature() { - var refined = new Entry<>(Target.BIOME, BIOME, new Refined()); + var refined = new Entry<>(Level.BIOME, BIOME, new Refined()); - assertEquals(List.of(refined), ConfiguredSettings.of(List.of(refined)).find(Base.class)); + assertEquals(List.of(refined), ConfiguredSettings.of(List.of(refined)).find(Base.class).entries()); var twice = assertThrows(IllegalArgumentException.class, () -> ConfiguredSettings.placement(OBJECT, new Base(), new Refined())); assertEquals("Settings configured twice: " + Base.class.getName(), twice.getMessage()); } @@ -49,8 +49,8 @@ class ConfiguredSettingsTest { @Test void aPlacementDeclaresEachTypeOnce() { var levels = new Levels(); - assertEquals(List.of(new Entry<>(Target.OBJECT_PLACEMENT, OBJECT, levels)), - ConfiguredSettings.placement(OBJECT, levels).find(Levels.class)); + assertEquals(List.of(new Entry<>(Level.PLACEMENT, OBJECT, levels)), + ConfiguredSettings.placement(OBJECT, levels).find(Levels.class).entries()); var twice = assertThrows(IllegalArgumentException.class, () -> ConfiguredSettings.placement(OBJECT, new Levels(), new Levels())); assertEquals("Settings configured twice: " + Levels.class.getName(), twice.getMessage()); } diff --git a/src/test/java/com/volmit/host/LifecycleRunnerTest.java b/src/test/java/com/volmit/host/LifecycleRunnerTest.java index 315337761..e9d9e003b 100644 --- a/src/test/java/com/volmit/host/LifecycleRunnerTest.java +++ b/src/test/java/com/volmit/host/LifecycleRunnerTest.java @@ -4,7 +4,7 @@ import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.ModuleLifecycle; import com.volmit.ModuleSetup; -import com.volmit.config.PackSettings; +import com.volmit.PackContext; import com.volmit.resource.PackResources; import com.volmit.support.EmptyResources; import com.volmit.support.TestWorld; @@ -24,7 +24,7 @@ class LifecycleRunnerTest { public ModuleInfo info() { return ModuleInfo.of(id, "Lifecycle " + id, "1"); } public void setup(ModuleSetup setup) { setup.registry().registerLifecycle(new ModuleLifecycle() { - public void packLoaded(PackResources resources, PackSettings settings) { record("loaded"); } + @Override public void packLoaded(PackContext pack) { record("loaded"); } public void worldStarted(PackWorld world) { record("started"); } public void warmUp(PackWorld world) { record("warmed"); } public void worldStopped(PackWorld world) { record("stopped"); } diff --git a/src/test/java/com/volmit/host/LoadedPackTest.java b/src/test/java/com/volmit/host/LoadedPackTest.java index 81c51ae05..55e166096 100644 --- a/src/test/java/com/volmit/host/LoadedPackTest.java +++ b/src/test/java/com/volmit/host/LoadedPackTest.java @@ -1,6 +1,6 @@ package com.volmit.host; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.support.TestModuleJar; import example.builtin.CarveModule; import org.junit.jupiter.api.AfterEach; @@ -84,8 +84,8 @@ class LoadedPackTest { void invalidHostConfigurationFailsWhenBuilt() { var host = ModuleHost.of(List.of()); assertThrows(IllegalArgumentException.class, () -> host.exposing("org.*")); - assertThrows(IllegalArgumentException.class, () -> host.reservingFields(Map.of(Target.BIOME, Set.of(" ")))); - assertThrows(IllegalArgumentException.class, () -> host.reservingFields(Map.of(Target.BIOME, Set.of("iris:carve")))); + assertThrows(IllegalArgumentException.class, () -> host.reservingFields(Map.of(Level.BIOME, Set.of(" ")))); + assertThrows(IllegalArgumentException.class, () -> host.reservingFields(Map.of(Level.BIOME, Set.of("iris:carve")))); assertEquals(List.of(), host.builtIns()); assertEquals(Set.of(), host.exposedHostPackages()); } @@ -95,13 +95,13 @@ class LoadedPackTest { var host = ModuleHost.of(List.of()) .exposing("example.first") .exposing("example.second") - .reservingFields(Map.of(Target.BIOME, Set.of("carving"), Target.REGION, Set.of("spawns"))) - .reservingFields(Map.of(Target.BIOME, Set.of("objects"))) + .reservingFields(Map.of(Level.BIOME, Set.of("carving"), Level.REGION, Set.of("spawns"))) + .reservingFields(Map.of(Level.BIOME, Set.of("objects"))) .reservingFolders("biomes") .reservingFolders("regions"); assertEquals(Set.of("example.first", "example.second"), host.exposedHostPackages()); - assertEquals(Map.of(Target.BIOME, Set.of("carving", "objects"), Target.REGION, Set.of("spawns")), host.reservedHostFields()); + assertEquals(Map.of(Level.BIOME, Set.of("carving", "objects"), Level.REGION, Set.of("spawns")), host.reservedHostFields()); assertEquals(Set.of("biomes", "regions"), host.reservedFolders()); } diff --git a/src/test/java/com/volmit/host/ModuleLogTest.java b/src/test/java/com/volmit/host/ModuleLogTest.java index 64ba7a77a..bc4f1f1ce 100644 --- a/src/test/java/com/volmit/host/ModuleLogTest.java +++ b/src/test/java/com/volmit/host/ModuleLogTest.java @@ -5,9 +5,11 @@ import com.volmit.ModuleInfo; import com.volmit.ModuleLifecycle; import com.volmit.ModuleLog; import com.volmit.ModuleSetup; +import com.volmit.PackContext; import com.volmit.stage.ChunkStage; import com.volmit.stage.Pipeline; import com.volmit.stage.Stage; +import com.volmit.support.EmptyResources; import com.volmit.support.TestContexts; import com.volmit.support.TestModuleJar; import com.volmit.support.TestSetups; @@ -268,4 +270,46 @@ class ModuleLogTest { assertEquals(List.of("[test:alpha] from a service", "[test:alpha] from a hook"), logger.messages()); } + + @Test + void packLoadedGetsThePackWithTheModulesOwnLog() { + var logger = new RecordingLogger(); + var module = new IrisModule() { + public ModuleInfo info() { return ModuleInfo.of(ALPHA, "Loads", "1"); } + public void setup(ModuleSetup setup) { + setup.registry().registerLifecycle(new ModuleLifecycle() { + @Override + public void packLoaded(PackContext pack) { pack.log().info("loaded " + pack.resources().packId()); } + }); + } + }; + var catalog = LoadedModules.load(List.of(DiscoveredModule.builtIn(module).loggingTo(logger)), Map.of(), Set.of(), Set.of()) + .catalog(); + + try (var world = new TestWorld()) { + new LifecycleRunner(catalog).packLoaded(new EmptyResources(), world.settings()); + } + + assertEquals(List.of("[test:alpha] loaded test:pack"), logger.messages()); + } + + @Test + void aStageBodySeesTheSameScopedWorldOnEveryInvocationOfTheSameWorld() { + var seen = new ArrayList(); + var stage = Stage.chunk("test:alpha/scope"); + var module = new IrisModule() { + public ModuleInfo info() { return ModuleInfo.of(ALPHA, "Scope", "1"); } + public void setup(ModuleSetup setup) { setup.stages().define(stage).run(context -> seen.add(context.world())); } + }; + var runner = new ChunkRunner(TestSetups.stages(module).resolve(Pipeline.CHUNK)); + + try (var first = new TestWorld(); var second = new TestWorld()) { + for (var world : List.of(first, first, second)) { + runner.generate(TestContexts.generation(Map.of(), null, null, world), TestContexts.SEED, StageTimings.NONE); + } + } + + assertSame(seen.get(0), seen.get(1), "the module's view of a world is built once, not per invocation"); + assertNotSame(seen.get(1), seen.get(2), "another world gets its own view"); + } } diff --git a/src/test/java/com/volmit/host/ModuleRegistryTest.java b/src/test/java/com/volmit/host/ModuleRegistryTest.java index 2ab7bfdbb..56234fedc 100644 --- a/src/test/java/com/volmit/host/ModuleRegistryTest.java +++ b/src/test/java/com/volmit/host/ModuleRegistryTest.java @@ -2,6 +2,7 @@ package com.volmit.host; import com.volmit.*; import com.volmit.config.Feature; +import com.volmit.config.Level; import com.volmit.mantle.*; import com.volmit.resource.ResourceKind; import com.volmit.service.Providers; @@ -21,22 +22,22 @@ import java.util.function.Consumer; import static org.junit.jupiter.api.Assertions.*; class ModuleRegistryTest { - @Feature(id = "test:core/one", name = "One", key = "coreOne", targets = FeatureAttachment.Target.BIOME) + @Feature(id = "test:core/one", name = "One", key = "coreOne", targets = Level.BIOME) static class One implements IrisFeature {} - @Feature(id = "test:core/two", name = "Two", key = "coreTwo", targets = FeatureAttachment.Target.DIMENSION) + @Feature(id = "test:core/two", name = "Two", key = "coreTwo", targets = Level.DIMENSION) static class Two implements IrisFeature {} - @Feature(id = "test:core/one", name = "Duplicate", key = "coreOne", targets = FeatureAttachment.Target.REGION) + @Feature(id = "test:core/one", name = "Duplicate", key = "coreOne", targets = Level.REGION) static class Duplicate implements IrisFeature {} - @Feature(id = "test:ores", name = "Ores", key = "deposits", targets = {FeatureAttachment.Target.BIOME, FeatureAttachment.Target.REGION}) + @Feature(id = "test:ores", name = "Ores", key = "deposits", targets = {Level.BIOME, Level.REGION}) static class Ores implements IrisFeature {} - @Feature(id = "test:minerals", name = "Minerals", key = "deposits", targets = FeatureAttachment.Target.REGION) + @Feature(id = "test:minerals", name = "Minerals", key = "deposits", targets = Level.REGION) static class Minerals implements IrisFeature {} - @Feature(id = "test:veins", name = "Veins", key = "deposits", targets = FeatureAttachment.Target.DIMENSION) + @Feature(id = "test:veins", name = "Veins", key = "deposits", targets = Level.DIMENSION) static class Veins implements IrisFeature {} - @Feature(id = "test:named", name = "Named", key = "name", targets = FeatureAttachment.Target.BIOME) + @Feature(id = "test:named", name = "Named", key = "name", targets = Level.BIOME) static class Named implements IrisFeature {} static class MissingAnnotation implements IrisFeature {} - @Feature(id = "test:core/abstract", name = "Abstract", key = "coreAbstract", targets = FeatureAttachment.Target.BIOME) + @Feature(id = "test:core/abstract", name = "Abstract", key = "coreAbstract", targets = Level.BIOME) abstract static class AbstractFeature implements IrisFeature {} /** Runs {@code registrations} as the setup(...) of a built-in module with the given id. */ @@ -187,7 +188,7 @@ class ModuleRegistryTest { @Test void aKeyTheHostUsesAsAFieldOfTheTargetIsRefusedNamingIris() { - var reserved = Map.of(FeatureAttachment.Target.BIOME, Set.of("name", "generators")); + var reserved = Map.of(Level.BIOME, Set.of("name", "generators")); var clash = assertThrows(IllegalArgumentException.class, () -> LoadedModules.load(discovered(settingsModule("test:named", Named.class)), reserved, Set.of(), Set.of())); @@ -198,7 +199,7 @@ class ModuleRegistryTest { @Test void aHostFieldOfAnotherTargetDoesNotTakeTheKey() { - var reserved = Map.of(FeatureAttachment.Target.REGION, Set.of("name")); + var reserved = Map.of(Level.REGION, Set.of("name")); var loaded = LoadedModules.load(discovered(settingsModule("test:named", Named.class)), reserved, Set.of(), Set.of()); @@ -225,7 +226,7 @@ class ModuleRegistryTest { @Test void aRefusedKeyLeavesNothingClaimedByTheFailedFeature() { - var registry = new ModuleRegistry(Map.of(FeatureAttachment.Target.REGION, Set.of("deposits")), Set.of()); + var registry = new ModuleRegistry(Map.of(Level.REGION, Set.of("deposits")), Set.of()); assertThrows(IllegalArgumentException.class, () -> registerAs(registry, "test:ores", settings -> settings.registerSettings(Ores.class))); @@ -253,6 +254,15 @@ class ModuleRegistryTest { assertTrue(registry.registeredByOwner(One.class)); } + @Test + void oneCallRegistersSeveralSettingsTypes() { + var registry = new ModuleRegistry(); + registerAs(registry, "test:core", settings -> settings.registerSettings(One.class, Two.class)); + + assertEquals(List.of("test:core/one", "test:core/two"), + registry.freeze().settings().stream().map(value -> value.id().toString()).sorted().toList()); + } + @Test void explicitSettingsFollowTheRegisteringModulesIdAndStillCollide() { var registry = new ModuleRegistry(); diff --git a/src/test/java/com/volmit/host/PackModulesTest.java b/src/test/java/com/volmit/host/PackModulesTest.java index b9c92f8e9..cd6142c07 100644 --- a/src/test/java/com/volmit/host/PackModulesTest.java +++ b/src/test/java/com/volmit/host/PackModulesTest.java @@ -642,11 +642,11 @@ class PackModulesTest { public @interface Feature { String id(); String name(); - com.volmit.FeatureAttachment.Target[] targets(); + com.volmit.config.Level[] targets(); } """).writeInto(build, "api-without-keys.jar"); module("pack.old.Old", "old:flora", """ - @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.config.Level.BIOME) public static final class Patch implements com.volmit.IrisFeature {} """, "registry.registerSettings(Patch.class);") .compileAgainstOlderApi(apiWithoutKeys) @@ -689,18 +689,18 @@ class PackModulesTest { .source("pack.ClashSettings", """ package pack; - import com.volmit.FeatureAttachment.Target; + import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Feature; - @Feature(id = "mine:core/clash", name = "Clash", key = "moss", targets = Target.OBJECT_PLACEMENT) + @Feature(id = "mine:core/clash", name = "Clash", key = "moss", targets = Level.PLACEMENT) public final class ClashSettings implements IrisFeature { } """) .writeInto(pack, "clash.jar"); try (var packModules = PackModules.load(pack)) { - assertEquals("object placement key \"moss\" is claimed by example:moss (host classpath) and mine:core/clash (" + assertEquals("placement key \"moss\" is claimed by example:moss (host classpath) and mine:core/clash (" + origin("clash.jar") + "); give one of the settings another key in its @Feature", failure(() -> loadWithBuiltIns(packModules))); } diff --git a/src/test/java/com/volmit/host/PackSchemaTest.java b/src/test/java/com/volmit/host/PackSchemaTest.java index d0051daba..8285ffc0d 100644 --- a/src/test/java/com/volmit/host/PackSchemaTest.java +++ b/src/test/java/com/volmit/host/PackSchemaTest.java @@ -1,6 +1,6 @@ package com.volmit.host; -import com.volmit.FeatureAttachment.Target; +import com.volmit.config.Level; import com.volmit.config.Reference; import com.volmit.example.chunk.GrassModule; import com.volmit.example.chunk.TerrainModule; @@ -69,7 +69,7 @@ class PackSchemaTest { private static final String FLORA_SETTINGS = """ package pack.flora; - import com.volmit.FeatureAttachment.Target; + import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.block.BlockState; import com.volmit.config.*; @@ -77,7 +77,7 @@ class PackSchemaTest { import java.util.*; @Desc("Plants flowers and bushes") - @Feature(id = "example:flora", name = "Flora", key = "flora", targets = {Target.REGION, Target.BIOME}) + @Feature(id = "example:flora", name = "Flora", key = "flora", targets = {Level.REGION, Level.BIOME}) public final class FloraSettings implements IrisFeature { @Desc("Plants per chunk") @Required @MinNumber(0) @MaxNumber(64) private int density = 4; @@ -135,11 +135,11 @@ class PackSchemaTest { private static final String WIND_SETTINGS = """ package pack.flora; - import com.volmit.FeatureAttachment.Target; + import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.*; - @Feature(id = "example:flora/wind", name = "Wind", key = "floraWind", targets = Target.DIMENSION) + @Feature(id = "example:flora/wind", name = "Wind", key = "floraWind", targets = Level.DIMENSION) public final class WindSettings implements IrisFeature { @Desc("How far plants sway") private double strength = 1.5; @@ -149,12 +149,12 @@ class PackSchemaTest { private static final String BUSH_SETTINGS = """ package pack.flora; - import com.volmit.FeatureAttachment.Target; + import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.*; @Snippet("example/flora/bush") - @Feature(id = "example:flora/bush", name = "Bush", key = "floraBush", targets = Target.OBJECT_PLACEMENT) + @Feature(id = "example:flora/bush", name = "Bush", key = "floraBush", targets = Level.PLACEMENT) public final class BushSettings implements IrisFeature { private int height = 2; } @@ -201,10 +201,10 @@ class PackSchemaTest { void attachesEveryModuleFeatureToItsTargetsUnderItsDeclaredKey() { var schema = floraSchema(); - assertEquals(List.of("flora"), names(schema.fields(Target.BIOME), FeatureSchema::key)); - assertEquals(List.of("flora"), names(schema.fields(Target.REGION), FeatureSchema::key)); - assertEquals(List.of("floraWind"), names(schema.fields(Target.DIMENSION), FeatureSchema::key)); - assertEquals(List.of("floraBush"), names(schema.fields(Target.OBJECT_PLACEMENT), FeatureSchema::key)); + assertEquals(List.of("flora"), names(schema.fields(Level.BIOME), FeatureSchema::key)); + assertEquals(List.of("flora"), names(schema.fields(Level.REGION), FeatureSchema::key)); + assertEquals(List.of("floraWind"), names(schema.fields(Level.DIMENSION), FeatureSchema::key)); + assertEquals(List.of("floraBush"), names(schema.fields(Level.PLACEMENT), FeatureSchema::key)); assertEquals(List.of("example:flora", "example:flora/bush", "example:flora/wind"), names(schema.features(), FeatureSchema::id)); var flora = schema.features().getFirst(); @@ -212,7 +212,7 @@ class PackSchemaTest { assertEquals(FeatureRole.SETTINGS, flora.role()); assertEquals(FLORA, flora.module().id().toString()); assertEquals(displayName(FLORA), flora.module().name()); - assertEquals(List.of(Target.REGION, Target.BIOME), List.copyOf(flora.targets())); + assertEquals(List.of(Level.REGION, Level.BIOME), List.copyOf(flora.targets())); assertEquals("pack.flora.FloraSettings", flora.settings().name()); assertEquals("Plants flowers and bushes", flora.settings().description()); assertEquals(Optional.empty(), flora.settings().snippet()); @@ -301,7 +301,7 @@ class PackSchemaTest { assertEquals(FeatureRole.OBJECT_GENERATOR, bush.role()); assertEquals(Optional.of(2L), option(bush.settings(), "height").defaultValue()); - var wind = schema.fields(Target.DIMENSION).getFirst(); + var wind = schema.fields(Level.DIMENSION).getFirst(); assertEquals(FeatureRole.SETTINGS, wind.role()); assertEquals("example:flora/wind", wind.id().toString()); assertEquals(new SchemaOption("strength", new DecimalKind(), "How far plants sway", false, @@ -332,15 +332,15 @@ class PackSchemaTest { var schema = schemaOf(pack("empty"), ModuleHost.of(builtIns)); assertEquals(List.of("example:grass", "example:moss", "iris:snow", "iris:stilt"), names(schema.features(), FeatureSchema::id)); - assertEquals(List.of("moss", "snow", "stilt"), names(schema.fields(Target.OBJECT_PLACEMENT), FeatureSchema::key)); + assertEquals(List.of("moss", "snow", "stilt"), names(schema.fields(Level.PLACEMENT), FeatureSchema::key)); - var stilt = schema.fields(Target.OBJECT_PLACEMENT).get(2); + var stilt = schema.fields(Level.PLACEMENT).get(2); assertEquals("Stilts", stilt.module().name()); assertEquals(new ObjectType("com.volmit.example.placement.StiltSettings", "Fills the space below an object down to the ground", Optional.empty(), List.of(new SchemaOption("maxDepth", new IntegerKind(), "Maximum blocks filled below each lowest object block", false, OptionalDouble.of(1), OptionalDouble.empty(), OptionalInt.empty(), Optional.of(16L)))), stilt.settings()); - var grass = schema.fields(Target.BIOME).getFirst(); + var grass = schema.fields(Level.BIOME).getFirst(); assertEquals(new SchemaOption("block", new ReferenceKind(Reference.BLOCK, TextFormat.BLOCK_STATE), "Block placed on top of each column", false, OptionalDouble.empty(), OptionalDouble.empty(), OptionalInt.empty(), Optional.of("minecraft:grass_block")), grass.settings().options().getFirst()); } @@ -350,7 +350,7 @@ class PackSchemaTest { var builtIns = List.of(new LayersModule()); var schema = schemaOf(pack("layers"), ModuleHost.of(builtIns).describingHostTypesIn(HOST_TYPES)); - var layers = schema.fields(Target.BIOME).getFirst(); + var layers = schema.fields(Level.BIOME).getFirst(); var option = layers.settings().options().getFirst(); assertEquals(new ListKind(new HostKind(Palette.class.getName()), false), option.kind()); assertEquals(Optional.of(List.of()), option.defaultValue()); @@ -421,14 +421,14 @@ class PackSchemaTest { .source("pack.flora.FloraSettings", """ package pack.flora; - import com.volmit.FeatureAttachment.Target; + import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.block.BlockState; import com.volmit.config.*; import com.volmit.resource.*; import java.util.*; - @Feature(id = "example:flora", name = "Flora", key = "flora", targets = Target.BIOME) + @Feature(id = "example:flora", name = "Flora", key = "flora", targets = Level.BIOME) public final class FloraSettings implements IrisFeature { %s } @@ -453,19 +453,19 @@ class PackSchemaTest { .source("pack.flora.FloraSettings", """ package pack.flora; - import com.volmit.FeatureAttachment.Target; + import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.*; import java.util.*; - @Feature(id = "example:flora", name = "Flora", key = "flowers", root = "flowers", targets = Target.BIOME) + @Feature(id = "example:flora", name = "Flora", key = "flowers", root = "flowers", targets = Level.BIOME) public final class FloraSettings implements IrisFeature { @MinItems(1) private List flowers = List.of("poppy"); } """) .writeInto(pack, "flora.jar"); - var flora = schemaOf(pack, NO_BUILT_INS).fields(Target.BIOME).getFirst(); + var flora = schemaOf(pack, NO_BUILT_INS).fields(Level.BIOME).getFirst(); assertEquals("flowers", flora.key()); assertEquals(Optional.of("flowers"), flora.root()); @@ -486,7 +486,7 @@ class PackSchemaTest { .source("pack.flora.FloraSettings", """ package pack.flora; - import com.volmit.FeatureAttachment.Target; + import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.block.BlockSpec; import com.volmit.block.PaletteSpec; @@ -497,7 +497,7 @@ class PackSchemaTest { import com.volmit.world.BlockPosition; import java.util.*; - @Feature(id = "example:flora", name = "Flora", key = "flora", targets = Target.BIOME) + @Feature(id = "example:flora", name = "Flora", key = "flora", targets = Level.BIOME) public final class FloraSettings implements IrisFeature { private List palette = List.of(BlockSpec.of("poppy")); private NoiseStyle style = NoiseStyle.of("SIMPLEX").withZoom(4); @@ -558,12 +558,12 @@ class PackSchemaTest { .source("pack.flora.FloraSettings", """ package pack.flora; - import com.volmit.FeatureAttachment.Target; + import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.Feature; import java.util.*; - @Feature(id = "example:flora", name = "Flora", key = "flora", targets = Target.BIOME) + @Feature(id = "example:flora", name = "Flora", key = "flora", targets = Level.BIOME) public final class FloraSettings implements IrisFeature { private Node node = new Node(); private double ratio = Double.NaN; @@ -664,7 +664,7 @@ class PackSchemaTest { package pack.flora; @com.volmit.config.Snippet("example/flora") - @com.volmit.config.Feature(id = "example:flora", name = "Flora", key = "flora", targets = com.volmit.FeatureAttachment.Target.BIOME) + @com.volmit.config.Feature(id = "example:flora", name = "Flora", key = "flora", targets = com.volmit.config.Level.BIOME) public final class FloraSettings implements com.volmit.IrisFeature {} """) .writeInto(pack, "flora.jar"); @@ -690,7 +690,7 @@ class PackSchemaTest { .source("pack.flora.FloraSettings", """ package pack.flora; - @com.volmit.config.Feature(id = "example:flora", name = "Flora", key = "flora", targets = com.volmit.FeatureAttachment.Target.BIOME) + @com.volmit.config.Feature(id = "example:flora", name = "Flora", key = "flora", targets = com.volmit.config.Level.BIOME) public final class FloraSettings extends Base implements com.volmit.IrisFeature { private int omega; private int beta; } """) .writeInto(pack, "flora.jar"); @@ -724,12 +724,12 @@ class PackSchemaTest { .source("pack.castle.CastleSettings", """ package pack.castle; - import com.volmit.FeatureAttachment.Target; + import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.config.*; import java.util.List; - @Feature(id = "example:castle", name = "Castle", key = "castle", targets = Target.BIOME) + @Feature(id = "example:castle", name = "Castle", key = "castle", targets = Level.BIOME) public final class CastleSettings implements IrisFeature { @ResourceRef(Keep.class) private List keeps = List.of("main"); @@ -757,7 +757,7 @@ class PackSchemaTest { assertEquals(new SchemaOption("towers", new IntegerKind(), "Towers on the walls", false, OptionalDouble.of(1), OptionalDouble.empty(), OptionalInt.empty(), Optional.of(4L)), keep.options().getFirst()); assertEquals(new ResourceReferenceKind(keepKind), keep.options().get(1).kind(), "a resource may name others of its kind"); - var keeps = schema.fields(Target.BIOME).getFirst().settings().options().getFirst(); + var keeps = schema.fields(Level.BIOME).getFirst().settings().options().getFirst(); assertEquals(new ListKind(new ResourceReferenceKind(keepKind), false), keeps.kind()); assertEquals(Optional.of(List.of("main")), keeps.defaultValue()); } diff --git a/src/test/java/com/volmit/host/StageGraphTest.java b/src/test/java/com/volmit/host/StageGraphTest.java index 73c9c1fcd..c748babf9 100644 --- a/src/test/java/com/volmit/host/StageGraphTest.java +++ b/src/test/java/com/volmit/host/StageGraphTest.java @@ -1,7 +1,7 @@ package com.volmit.host; -import com.volmit.FeatureAttachment; import com.volmit.FeatureRegistry; +import com.volmit.config.Level; import com.volmit.IrisFeature; import com.volmit.IrisModule; import com.volmit.ModuleInfo; @@ -47,7 +47,7 @@ import static org.junit.jupiter.api.Assertions.*; class StageGraphTest { private static final BlockState STONE = new BlockState("minecraft:stone"); - @Feature(id = "test:owner/toggle", name = "Toggle", key = "ownerToggle", targets = FeatureAttachment.Target.OBJECT_PLACEMENT) + @Feature(id = "test:owner/toggle", name = "Toggle", key = "ownerToggle", targets = Level.PLACEMENT) static final class Toggle implements IrisFeature {} static final class Unannotated implements IrisFeature {} @@ -403,7 +403,7 @@ class StageGraphTest { var refusals = new ArrayList(); 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()); + configured.add(context.configured(Toggle.class).mostSpecific().orElseThrow()); refusals.add(assertThrows(IllegalStateException.class, () -> context.configured(SnowSettings.class)).getMessage()); }); stages.define(Stage.placement("test:owner/plain")).run(context -> refusals.add( @@ -572,7 +572,7 @@ class StageGraphTest { stages.define(mark).reach(2).run(context -> {}); }))), Map.of(), Set.of(), Set.of()); var computed = loaded.mantle().stages().getFirst(); - var toggled = new DeclaredSettings(new Entry<>(FeatureAttachment.Target.DIMENSION, ResourceId.parse("pack:dimension/main"), new Toggle())); + var toggled = new DeclaredSettings(new Entry<>(Level.DIMENSION, ResourceId.parse("pack:dimension/main"), new Toggle())); assertEquals(4, computed.reachBlocks(DeclaredSettings.NONE)); assertEquals(40, computed.reachBlocks(toggled)); @@ -605,7 +605,7 @@ class StageGraphTest { stages.define(follower).requires(toggled).run(context -> ran.add("follower")); })); var runner = new MantleRunner(graph); - var toggle = new Entry<>(FeatureAttachment.Target.BIOME, ResourceId.parse("pack:biome/plains"), new Toggle()); + var toggle = new Entry<>(Level.BIOME, ResourceId.parse("pack:biome/plains"), new Toggle()); 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); diff --git a/src/test/java/com/volmit/support/ColumnSettings.java b/src/test/java/com/volmit/support/ColumnSettings.java index 3be7da00c..e458a792c 100644 --- a/src/test/java/com/volmit/support/ColumnSettings.java +++ b/src/test/java/com/volmit/support/ColumnSettings.java @@ -2,6 +2,7 @@ package com.volmit.support; import com.volmit.IrisFeature; import com.volmit.config.FeatureSettings; +import com.volmit.config.SettingsStack; import java.util.List; import java.util.function.BiFunction; @@ -23,10 +24,10 @@ public final class ColumnSettings implements FeatureSettings { @Override @SuppressWarnings("unchecked") // Filtered by the requested type. - public List> at(Class featureType, int worldX, int worldZ) { - return columns.apply(worldX, worldZ).stream() + public SettingsStack at(Class featureType, int worldX, int worldZ) { + return SettingsStack.of(columns.apply(worldX, worldZ).stream() .filter(entry -> featureType.isInstance(entry.value())) .map(entry -> (Entry) entry) - .toList(); + .toList()); } } diff --git a/src/test/java/com/volmit/support/DeclaredSettings.java b/src/test/java/com/volmit/support/DeclaredSettings.java index 033b6f2de..c49154945 100644 --- a/src/test/java/com/volmit/support/DeclaredSettings.java +++ b/src/test/java/com/volmit/support/DeclaredSettings.java @@ -3,6 +3,7 @@ package com.volmit.support; import com.volmit.IrisFeature; import com.volmit.config.FeatureSettings.Entry; import com.volmit.config.PackSettings; +import com.volmit.config.SettingsStack; import java.util.List; /** A pack's settings as a fixed list of declarations, for reach tests. */ @@ -17,10 +18,10 @@ public final class DeclaredSettings implements PackSettings { @Override @SuppressWarnings("unchecked") // Filtered by the requested type. - public List> declared(Class featureType) { - return entries.stream() + public SettingsStack declared(Class featureType) { + return SettingsStack.of(entries.stream() .filter(entry -> featureType.isInstance(entry.value())) .map(entry -> (Entry) entry) - .toList(); + .toList()); } } diff --git a/src/test/java/com/volmit/support/TestContexts.java b/src/test/java/com/volmit/support/TestContexts.java index f9c903cb0..74b57704e 100644 --- a/src/test/java/com/volmit/support/TestContexts.java +++ b/src/test/java/com/volmit/support/TestContexts.java @@ -7,7 +7,6 @@ import com.volmit.hunk.Hunk; import com.volmit.mantle.Mantle; import com.volmit.object.ObjectTransformer; import com.volmit.placement.PlacementContext; -import com.volmit.resource.PackResources; import com.volmit.world.TerrainSampler; import com.volmit.world.BlockView; import com.volmit.world.PackWorld; @@ -33,8 +32,6 @@ public final class TestContexts { return new GenerationContext() { public int originX() { return 0; } public int originZ() { return 0; } - public long worldSeed() { return SEED; } - public PackResources resources() { throw new AssertionError("Unused resources"); } public PackWorld world() { return used(world, "world"); } public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); } public FeatureSettings settings() { return used(settings, "settings"); } @@ -53,8 +50,6 @@ public final class TestContexts { return new MantleGenerationContext() { public int originX() { return originX; } public int originZ() { return originZ; } - public long worldSeed() { return SEED; } - public PackResources resources() { throw new AssertionError("Unused resources"); } public PackWorld world() { throw new AssertionError("Unused world"); } public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); } public FeatureSettings settings() { return settings; } @@ -68,8 +63,6 @@ public final class TestContexts { public static PlacementContext placement(BlockView blocks) { return new PlacementContext() { - public long worldSeed() { return SEED; } - public PackResources resources() { throw new AssertionError("Unused resources"); } public PackWorld world() { throw new AssertionError("Unused world"); } public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); } public FeatureSettings settings() { throw new AssertionError("Unused settings"); } diff --git a/src/test/java/com/volmit/support/TestWorld.java b/src/test/java/com/volmit/support/TestWorld.java index 22efd93db..03b62eec3 100644 --- a/src/test/java/com/volmit/support/TestWorld.java +++ b/src/test/java/com/volmit/support/TestWorld.java @@ -2,13 +2,12 @@ package com.volmit.support; import com.volmit.IrisFeature; import com.volmit.ModuleLog; -import com.volmit.config.FeatureSettings.Entry; import com.volmit.config.PackSettings; +import com.volmit.config.SettingsStack; import com.volmit.host.ModuleLogs; import com.volmit.host.WorldStates; import com.volmit.resource.PackResources; import com.volmit.world.PackWorld; -import java.util.List; import java.util.function.Function; /** A world for tests: the test seed, no resources, no declared settings, and a real state store. */ @@ -38,8 +37,8 @@ public final class TestWorld implements PackWorld, AutoCloseable { @Override public PackSettings settings() { return new PackSettings() { - public List> declared(Class featureType) { - return List.of(); + public SettingsStack declared(Class featureType) { + return SettingsStack.empty(); } }; }