Register saved keys per module, key mantle and saved ids by ResourceId

SavedKey moves to com.volmit.data and Codec becomes StorageCodec, which
ends the clash with JsonForms.Codec. SavedKey.id and MantleKey.id are
ResourceIds, so the copied id regex is gone. Modules register saved keys
in setup with FeatureRegistry.registerSaved, owned like mantle keys, and
RunningWorld.saved rejects a key that is not the registered one.
This commit is contained in:
piexel committed 2026-11-06 12:50:42 +01:00
1 parent 6c8fa31a7b
commit 307b89c5fe
19 files changed
+156 -88

No files matched your search

+1 -1
View File
@@ -25,7 +25,7 @@ types that carry them and lists what the Iris adapter still owes.
| Reference execution | host `PlacementRunner` (returns the API `PlacementOutcome`), `ChunkRunner`, `MantleRunner`, each timed through host `StageTimings` |
| Work across chunks and mantle writes | `Stage.mantle`, `MantleStage`, `MantleStageContext`, `MantleGenerationContext`; chunk stages write registered layers in their own chunk only and read the neighbors |
| Annotated settings | `IrisFeature`, `@Feature` (id, short JSON `key`, optional `root`), config annotations, host `OptionsMetadata`, `LinkedBiomes` (`treeBiomes`, `usedBiomes`: pack biomes the settings bring into the layout) |
| Module state that survives a restart | `RunningWorld.saved(SavedKey)`, `SavedKey` (id, type, `Codec`, `initial`), `com.volmit.data.Codec` (also the codec of mantle layers) |
| Module state that survives a restart | `RunningWorld.saved(SavedKey)`, `FeatureRegistry.registerSaved`, `SavedKey` (`ResourceId` id, type, `StorageCodec`, `initial`), `com.volmit.data.StorageCodec` (also the codec of mantle layers) |
| Host facades for the host's own modules | `PackWorld.extension(type)`, `InvocationContext.extension(type)`, `PackSettings.extension(type)` (each an `Optional`, empty by default) |
| Area a stage writes | `reach(blocks)`, `reach(PackReach)`, `writesMantle(...)` on stage definitions, `PackSettings` (with `resources()`, for a reach that depends on the size of the pack's objects), host `StageReach`, `ResolvedStage.reachBlocks`, `PipelineReach` |
| Settings described for studio | `@Desc`, `@Required`, `@MinNumber`, `@MaxNumber`, `@MinItems`, `@Snippet`, `@Ref`/`Reference`, `@ResourceRef`, `FeatureRegistry.registerSettings`, host `LoadedPack.schema()` (`PackSchema`, `FeatureSchema`, `ObjectType`, `SchemaOption`, `ValueKind` with `HostKind`), `ModuleHost.describingHostTypesIn` |
+6 -2
View File
@@ -1148,8 +1148,12 @@ each world a state store and tells modules when worlds start and stop.
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.
- **Saved state.** The store is memory, so what must survive a restart goes through `RunningWorld.saved(SavedKey)`
instead (the running world, because only it has a folder). A `SavedKey` is a namespaced id, the value class, a
`com.volmit.data.Codec` (the one mantle layers use) and an `initial` supplier. The host keeps one instance per key,
instead (the running world, because only it has a folder). A `SavedKey` is a `ResourceId`, the value class, a
`com.volmit.data.StorageCodec` (the one mantle layers use) and an `initial` supplier. A module registers it in its
setup with `FeatureRegistry.registerSaved`, owned like a mantle key (its id is the module's or below it), and `saved`
rejects a key nobody registered, so every stored file has a registered owner. `saved` cannot tell which module asks:
it accepts exactly the registered key, and rejects a key built with a registered id (such as one forged in another
module's namespace). The host keeps one instance per key,
reads it on the first ask, and writes it when it saves the world and when the world stops, so the world a hotload
starts reads what the stopped one wrote. The module mutates the value in place and owns its thread safety, so the
codec's `write` must tolerate concurrent changes. A payload the codec rejects is logged and replaced by `initial`: a
+12 -6
View File
@@ -355,10 +355,14 @@ static PlantedChunks planted(PackWorld world) {
- A state that is `AutoCloseable` is closed after the world stops, once nothing generates with it.
The state store is in memory and ends with the world. What must outlive a restart, such as when a spawner last fired,
a module keeps with `RunningWorld.saved`. Only a running world has a folder to save in, so a tool's world has none:
a module keeps with `RunningWorld.saved`. Only a running world has a folder to save in, so a tool's world has none.
The module registers the key in `setup` like a mantle layer, under its own id:
```java
private static final SavedKey<LastWaves> WAVES = new SavedKey<>("example:waves/last", LastWaves.class, new LastWavesCodec(), LastWaves::new);
private static final SavedKey<LastWaves> WAVES = new SavedKey<>(ResourceId.parse("example:waves/last"), LastWaves.class,
new LastWavesCodec(), LastWaves::new);
registry.registerSaved(WAVES); // in setup
LastWaves waves = world.running().orElseThrow().saved(WAVES); // the world's one instance, read on first ask
waves.record(now); // changed in place; the module owns its thread safety
@@ -367,8 +371,10 @@ waves.record(now); // changed in pl
- The host reads the value when it is first asked for (`initial` when none is stored), writes it when it saves the world
and when the world stops, and hands a world started over the same storage, such as after a hotload, what the old
one wrote.
- `Codec.write` may run while module threads change the value, so it must read it safely. A stored payload the codec
rejects is logged and replaced with `initial`.
- `StorageCodec.write` may run while module threads change the value, so it must read it safely. A stored payload the
codec rejects is logged and replaced with `initial`.
- `saved` throws `IllegalArgumentException` for a key nobody registered, and for another key with the id of a
registered one. The id is the module's id or starts with it and `/`, as a mantle key's does.
- The id names the stored file, so none of its segments is empty, `.` or `..`.
A module that wants to act when the host loads a pack or starts or stops a world registers a `ModuleLifecycle`. Every
@@ -1117,8 +1123,8 @@ Optional<Clock> clock = pack.catalog().service(Clock.class); // a Pro
a block with a block entity goes through `access.set(PlacedBlock)`. `BlockState.withProperty` copies the properties once.
- Invocation views (`ctx.mantle()`, its layers and blocks, a placement's `access().mantle()`) are made once per
invocation, so asking again returns the same view.
- The `mantle` package keeps namespaced typed layers, lifetimes and buffered edits; `com.volmit.data.Codec` stores
their values, and the values of `RunningWorld.saved`.
- The `mantle` package keeps namespaced typed layers, lifetimes and buffered edits; `com.volmit.data.StorageCodec` stores
their values, and the values of `RunningWorld.saved` (`com.volmit.data.SavedKey`).
- `IrisFeature`, `@Feature`, the config annotations (`@Desc`, `@Required`, `@MinNumber`,
`@MaxNumber`, `@MinItems`, `@Snippet`, `@Ref`) describe settings; the host reads them with `OptionsMetadata`
(`com.volmit.host`).
@@ -1,6 +1,7 @@
package com.volmit;
import com.volmit.data.Codec;
import com.volmit.data.SavedKey;
import com.volmit.data.StorageCodec;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
import com.volmit.resource.ResourceKind;
@@ -11,7 +12,7 @@ import java.util.Set;
/** Host implementation collects non-stage registrations before loading pack configuration.
* 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
* settings types stages name in {@code when(...)}. Feature IDs, mantle keys, saved 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}.
*/
public interface FeatureRegistry {
@@ -21,7 +22,13 @@ public interface FeatureRegistry {
* preserve unknown persisted layers or fail explicitly, never silently discard them.
* GENERATION layers also require codecs.
*/
<T> void registerMantle(MantleKey<T> key, MantleLifetime lifetime, Codec<T> codec);
<T> void registerMantle(MantleKey<T> key, MantleLifetime lifetime, StorageCodec<T> codec);
/** Registers a value the module keeps with each running world across restarts, so
* {@link com.volmit.world.RunningWorld#saved} serves it; that method throws IllegalArgumentException for a key
* nobody registered. Null arguments throw NullPointerException; a duplicate id throws IllegalArgumentException.
*/
void registerSaved(SavedKey<?> key);
/** 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
@@ -1,32 +1,30 @@
package com.volmit.world;
package com.volmit.data;
import com.volmit.data.Codec;
import com.volmit.resource.ResourceId;
import java.util.Objects;
import java.util.function.Supplier;
/** The identity and form of one value a module keeps with a running world across restarts
* ({@link RunningWorld#saved}). The id is namespaced like a mantle key and should start with the owning module's id; the host
* names its storage after it, so each segment of the namespace and of the {@code /} separated path must be a name,
* never empty, {@code .} or {@code ..}.
* ({@link com.volmit.world.RunningWorld#saved}). The module registers it in its setup
* ({@link com.volmit.FeatureRegistry#registerSaved}), and the id is the module's id or starts with it and {@code /},
* as a mantle key's does. The host names its storage after the id, so each segment of the namespace and of the
* {@code /} separated path must be a name, never empty, {@code .} or {@code ..}.
*
* @param id the stable storage identity, such as {@code example:moss/patches}
* @param type the value class
* @param codec how the value is stored; its version is written with the value
* @param initial the value for a world that has none stored, or whose stored one the codec rejects
*/
public record SavedKey<T>(String id, Class<T> type, Codec<T> codec, Supplier<T> initial) {
public record SavedKey<T>(ResourceId id, Class<T> type, StorageCodec<T> codec, Supplier<T> initial) {
public SavedKey {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(type, "type");
Objects.requireNonNull(codec, "codec");
Objects.requireNonNull(initial, "initial");
if (!id.matches("[a-z0-9_.-]+:[a-z0-9_./-]+")) {
throw new IllegalArgumentException("Expected a namespaced saved ID: " + id);
}
if (type.isPrimitive()) {
throw new IllegalArgumentException("Saved values require a reference type");
}
for (String segment : id.replace(':', '/').split("/", -1)) {
for (String segment : id.toString().replace(':', '/').split("/", -1)) {
if (segment.isEmpty() || segment.equals(".") || segment.equals("..")) {
throw new IllegalArgumentException("A saved ID names files, so it has no empty, . or .. segment: " + id);
}
@@ -5,11 +5,11 @@ import java.io.DataOutput;
import java.io.IOException;
/** Value serialization for data the host stores for a module: mantle layers ({@link com.volmit.mantle.MantleKey}) and
* saved world state ({@link com.volmit.world.SavedKey}). The host frames payloads and stores the key ID and version
* saved world state ({@link SavedKey}). The host frames payloads and stores the key ID and version
* separately. Implementations must support concurrent calls, must not close streams, and must reject malformed data or
* unsupported stored versions with IOException. Values cannot be null.
*/
public interface Codec<T> {
public interface StorageCodec<T> {
/** Nonnegative format version, stable for the registration lifetime. */
int version();
@@ -1,15 +1,13 @@
package com.volmit.mantle;
import com.volmit.resource.ResourceId;
import java.util.Objects;
/** Stable storage identity. Different IDs may use the same value class without sharing data. */
public record MantleKey<T>(String id, Class<T> type) {
public record MantleKey<T>(ResourceId id, Class<T> type) {
public MantleKey {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(type, "type");
if (!id.matches("[a-z0-9_.-]+:[a-z0-9_./-]+")) {
throw new IllegalArgumentException("Expected a namespaced mantle ID: " + id);
}
if (type.isPrimitive()) {
throw new IllegalArgumentException("Mantle values require a reference type");
}
@@ -1,6 +1,7 @@
package com.volmit.world;
import com.volmit.config.FeatureSettings;
import com.volmit.data.SavedKey;
import com.volmit.geometry.BlockPosition;
import com.volmit.placement.PlacementRecord;
import com.volmit.resource.ResourceId;
@@ -50,12 +51,14 @@ public interface RunningWorld {
* {@link PackWorld#state}.
*
* <p>The module changes the value in place and owns its thread safety. The host writes it while module threads may
* still change it, so {@link com.volmit.data.Codec#write} must read the value safely. A stored payload the codec
* still change it, so {@link com.volmit.data.StorageCodec#write} must read the value safely. A stored payload the codec
* rejects is logged and replaced by {@code key.initial()}; the next save overwrites it. A pack reload or hotload
* stops the world and starts another over the same storage, so the new world reads what the old one wrote when it
* stopped.
*
* @throws IllegalArgumentException if another key with the same id but another type was used for this world
* @throws IllegalArgumentException if {@code key} is not the key a module registered with
* {@link com.volmit.FeatureRegistry#registerSaved}: an unregistered key, or another key with the id of a
* registered one, such as one that another module built in its namespace
*/
<T> T saved(SavedKey<T> key);
@@ -1,6 +1,6 @@
package com.volmit.world;
package com.volmit.data;
import com.volmit.data.Codec;
import com.volmit.resource.ResourceId;
import org.junit.jupiter.api.Test;
import java.io.DataInput;
@@ -11,7 +11,9 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
class SavedKeyTest {
private static final Codec<String> TEXT = new Codec<>() {
private static final ResourceId ID = ResourceId.parse("a:b");
private static final StorageCodec<String> TEXT = new StorageCodec<>() {
@Override
public int version() {
return 1;
@@ -51,10 +53,10 @@ class SavedKeyTest {
@Test
void rejectsMissingPartsAndPrimitiveTypes() {
assertThrows(NullPointerException.class, () -> new SavedKey<>(null, String.class, TEXT, () -> ""));
assertThrows(NullPointerException.class, () -> new SavedKey<>("a:b", null, TEXT, () -> ""));
assertThrows(NullPointerException.class, () -> new SavedKey<>("a:b", String.class, null, () -> ""));
assertThrows(NullPointerException.class, () -> new SavedKey<>("a:b", String.class, TEXT, null));
Codec<Integer> number = new Codec<>() {
assertThrows(NullPointerException.class, () -> new SavedKey<>(ID, null, TEXT, () -> ""));
assertThrows(NullPointerException.class, () -> new SavedKey<>(ID, String.class, null, () -> ""));
assertThrows(NullPointerException.class, () -> new SavedKey<>(ID, String.class, TEXT, null));
StorageCodec<Integer> number = new StorageCodec<>() {
@Override
public int version() {
return 1;
@@ -70,10 +72,10 @@ class SavedKeyTest {
return input.readInt();
}
};
assertThrows(IllegalArgumentException.class, () -> new SavedKey<>("a:b", int.class, number, () -> 0));
assertThrows(IllegalArgumentException.class, () -> new SavedKey<>(ID, int.class, number, () -> 0));
}
private static SavedKey<String> key(String id) {
return new SavedKey<>(id, String.class, TEXT, () -> "");
return new SavedKey<>(ResourceId.parse(id), String.class, TEXT, () -> "");
}
}
@@ -1,6 +1,7 @@
package com.volmit.mantle;
import com.volmit.geometry.BlockBox;
import com.volmit.resource.ResourceId;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
@@ -33,20 +34,18 @@ class MantleValueTest {
@Test
void keysSeparateSameTypedLayersAndHaveValueEquality() {
var owner = new MantleKey<>("example:object-owner", String.class);
assertEquals(owner, new MantleKey<>("example:object-owner", String.class));
assertNotEquals(owner, new MantleKey<>("example:quest/location", String.class));
assertNotEquals(owner, new MantleKey<>("example:object-owner", Integer.class));
var owner = new MantleKey<>(ResourceId.parse("example:object-owner"), String.class);
assertEquals(owner, new MantleKey<>(ResourceId.parse("example:object-owner"), String.class));
assertNotEquals(owner, new MantleKey<>(ResourceId.parse("example:quest/location"), String.class));
assertNotEquals(owner, new MantleKey<>(ResourceId.parse("example:object-owner"), Integer.class));
}
@Test
void rejectsInvalidKeys() {
for (String id : new String[]{"", "owner", ":owner", "example:", "Example:owner", "a:b:c", "a: b"}) {
assertThrows(IllegalArgumentException.class, () -> new MantleKey<>(id, String.class));
}
void rejectsMissingPartsAndPrimitiveTypes() {
var id = ResourceId.parse("a:b");
assertThrows(NullPointerException.class, () -> new MantleKey<>(null, String.class));
assertThrows(NullPointerException.class, () -> new MantleKey<>("a:b", null));
assertThrows(IllegalArgumentException.class, () -> new MantleKey<>("a:b", int.class));
assertThrows(NullPointerException.class, () -> new MantleKey<>(id, null));
assertThrows(IllegalArgumentException.class, () -> new MantleKey<>(id, int.class));
}
@Test
@@ -1,5 +1,7 @@
package com.volmit.host;
import com.volmit.data.SavedKey;
import com.volmit.resource.ResourceId;
import com.volmit.service.Providers;
import com.volmit.service.Service;
import java.util.Collection;
@@ -31,7 +33,8 @@ public final class FeatureCatalog {
};
private final Map<Class<?>, FeatureDescriptor<?>> settings;
private final Map<String, MantleRegistration<?>> mantle;
private final Map<ResourceId, MantleRegistration<?>> mantle;
private final Map<ResourceId, SavedKey<?>> saved;
private final List<ResourceKindRegistration> resourceKinds;
private final List<ValidatorRegistration> validators;
private final List<LifecycleRegistration> lifecycles;
@@ -43,7 +46,8 @@ public final class FeatureCatalog {
FeatureCatalog(
Map<Class<?>, FeatureDescriptor<?>> settings,
Map<String, MantleRegistration<?>> mantle,
Map<ResourceId, MantleRegistration<?>> mantle,
Map<ResourceId, SavedKey<?>> saved,
Collection<ResourceKindRegistration> resourceKinds,
List<ValidatorRegistration> validators,
List<LifecycleRegistration> lifecycles,
@@ -56,6 +60,7 @@ public final class FeatureCatalog {
this.commands = sorted(commands, registration -> registration.command().name());
this.settings = Map.copyOf(settings);
this.mantle = Map.copyOf(mantle);
this.saved = Map.copyOf(saved);
this.resourceKinds = sorted(resourceKinds, registration -> registration.kind().id());
this.validators = inModuleOrder(validators, ValidatorRegistration::module);
this.lifecycles = inModuleOrder(lifecycles, LifecycleRegistration::module);
@@ -72,6 +77,11 @@ public final class FeatureCatalog {
return sorted(mantle.values(), registration -> registration.key().id());
}
/** The values modules keep with each running world ({@code FeatureRegistry.registerSaved}), by id. */
public List<SavedKey<?>> saved() {
return sorted(saved.values(), SavedKey::id);
}
/** The type packs write their object placements as, if a module declared it ({@code FeatureRegistry.registerPlacementType}). */
public Optional<PlacementTypeRegistration> placementType() {
return placementType;
@@ -1,6 +1,6 @@
package com.volmit.host;
import com.volmit.data.Codec;
import com.volmit.data.StorageCodec;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
import java.util.Objects;
@@ -8,7 +8,7 @@ import java.util.Objects;
public record MantleRegistration<T>(
MantleKey<T> key,
MantleLifetime lifetime,
Codec<T> codec,
StorageCodec<T> codec,
int version) {
public MantleRegistration {
Objects.requireNonNull(key, "key");
@@ -4,7 +4,8 @@ import com.volmit.FeatureRegistry;
import com.volmit.IrisFeature;
import com.volmit.ModuleLifecycle;
import com.volmit.config.Level;
import com.volmit.data.Codec;
import com.volmit.data.SavedKey;
import com.volmit.data.StorageCodec;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
import com.volmit.resource.ResourceId;
@@ -27,7 +28,7 @@ import java.util.Set;
* immutable. IDs are unique across feature kinds. A feature's JSON key (see {@link com.volmit.config.Feature#key})
* is unique per attachment target, and may not equal a host JSON field passed in to reserve it; a clash fails the
* registration naming the key, the target and both claimants. Modules register during their setup
* ({@link ModuleSetups#run}); mantle keys, resource kind ids and explicitly registered
* ({@link ModuleSetups#run}); mantle keys, saved keys, resource kind ids and explicitly registered
* settings ids must be the registering module's id or start with it and '/' ({@link com.volmit.ModuleInfo#ownsId}).
* Resource kinds have unique ids, types and folders, and no kind may read a folder the host reserves for its own
* files. Lifecycle hooks and service providers are registered by the module that owns them; a service whose providers
@@ -38,7 +39,8 @@ import java.util.Set;
*/
public final class ModuleRegistry implements FeatureRegistry, ToolingRegistry {
private final Map<Class<?>, FeatureDescriptor<?>> settings = new HashMap<>();
private final Map<String, MantleRegistration<?>> mantle = new HashMap<>();
private final Map<ResourceId, MantleRegistration<?>> mantle = new HashMap<>();
private final Map<ResourceId, SavedKey<?>> saved = new HashMap<>();
private final Set<ResourceId> featureIds = new HashSet<>();
private final Set<Class<?>> featureTypes = new HashSet<>();
private final Set<Class<?>> registeredByOwner = new HashSet<>();
@@ -84,11 +86,11 @@ public final class ModuleRegistry implements FeatureRegistry, ToolingRegistry {
}
@Override
public <T> void registerMantle(MantleKey<T> key, MantleLifetime lifetime, Codec<T> codec) {
public <T> void registerMantle(MantleKey<T> key, MantleLifetime lifetime, StorageCodec<T> codec) {
checkOpen();
Objects.requireNonNull(key, "key");
Objects.requireNonNull(codec, "codec");
requireOwnedId("Mantle layer", ResourceId.parse(key.id()));
requireOwnedId("Mantle layer", key.id());
var registration = new MantleRegistration<>(key, lifetime, codec, codec.version());
if (mantle.putIfAbsent(key.id(), registration) != null) {
@@ -96,6 +98,19 @@ public final class ModuleRegistry implements FeatureRegistry, ToolingRegistry {
}
}
@Override
public void registerSaved(SavedKey<?> key) {
checkOpen();
Objects.requireNonNull(key, "key");
requireOwnedId("Saved value", key.id());
if (key.codec().version() < 0) {
throw new IllegalArgumentException("Negative saved codec version");
}
if (saved.putIfAbsent(key.id(), key) != null) {
throw new IllegalArgumentException("Duplicate saved value: " + key.id());
}
}
@Override
public void registerSettings(Class<? extends IrisFeature> settingsType) {
checkOpen();
@@ -237,7 +252,7 @@ public final class ModuleRegistry implements FeatureRegistry, ToolingRegistry {
public FeatureCatalog freeze() {
if (catalog == null) {
catalog = new FeatureCatalog(settings, mantle, resourceKinds.values(), validators, lifecycles, services,
catalog = new FeatureCatalog(settings, mantle, saved, resourceKinds.values(), validators, lifecycles, services,
placementType, studioViews.values(), commands);
}
return catalog;
@@ -1,5 +1,6 @@
package com.volmit.host;
import com.volmit.resource.ResourceId;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
@@ -12,7 +13,7 @@ import java.util.TreeMap;
* @param mantleLayers for each mantle layer some stage writes, by layer id in id order, the largest
* reach of the stages that write it
*/
public record PipelineReach(int blocks, Map<String, Integer> mantleLayers) {
public record PipelineReach(int blocks, Map<ResourceId, Integer> mantleLayers) {
public PipelineReach {
if (blocks < 0) throw new IllegalArgumentException("Negative reach: " + blocks);
mantleLayers = Collections.unmodifiableMap(new TreeMap<>(mantleLayers));
@@ -20,7 +21,7 @@ public record PipelineReach(int blocks, Map<String, Integer> mantleLayers) {
static PipelineReach of(Iterable<ResolvedStage> stages) {
int blocks = 0;
var layers = new TreeMap<String, Integer>();
var layers = new TreeMap<ResourceId, Integer>();
for (var stage : stages) {
int stageBlocks = stage.fixedReachBlocks();
blocks = Math.max(blocks, stageBlocks);
@@ -1,6 +1,7 @@
package com.volmit.host;
import com.volmit.mantle.MantleKey;
import com.volmit.resource.ResourceId;
import com.volmit.stage.PackReach;
import java.util.HashSet;
import java.util.List;
@@ -22,7 +23,7 @@ public record StageReach(PackReach blocks, List<MantleKey<?>> mantleLayers) {
public StageReach {
Objects.requireNonNull(blocks, "blocks");
mantleLayers = List.copyOf(mantleLayers);
var ids = new HashSet<String>();
var ids = new HashSet<ResourceId>();
for (var layer : mantleLayers) {
if (!ids.add(Objects.requireNonNull(layer, "mantle layer").id())) {
throw new IllegalArgumentException("Mantle layer " + layer.id() + " declared twice");
@@ -7,9 +7,10 @@ import com.volmit.block.BlockState;
import com.volmit.config.PackSettings;
import com.volmit.generation.ChunkContext;
import com.volmit.geometry.BlockBox;
import com.volmit.data.Codec;
import com.volmit.data.StorageCodec;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
import com.volmit.resource.ResourceId;
import com.volmit.stage.ChunkStage;
import com.volmit.stage.ChunkStageContext;
import com.volmit.stage.MantleStage;
@@ -25,7 +26,7 @@ import java.io.IOException;
* its reach out when the pack loads.
*/
public final class VeinModule implements IrisModule {
public static final MantleKey<Integer> ORE = new MantleKey<>("example:veins/ore", Integer.class);
public static final MantleKey<Integer> ORE = new MantleKey<>(ResourceId.parse("example:veins/ore"),Integer.class);
public static final MantleStage PLAN = Stage.mantle("example:veins/plan");
public static final ChunkStage<Void> PLACE = Stage.chunk("example:veins/place");
public static final BlockState ORE_BLOCK = new BlockState("minecraft:iron_ore");
@@ -69,7 +70,7 @@ public final class VeinModule implements IrisModule {
blocks.set(x - context.originX(), y, z - context.originZ(), ORE_BLOCK));
}
private static final class IntegerCodec implements Codec<Integer> {
private static final class IntegerCodec implements StorageCodec<Integer> {
public int version() { return 0; }
public void write(DataOutput output, Integer value) throws IOException { output.writeInt(value); }
public Integer read(DataInput input, int storedVersion) throws IOException { return input.readInt(); }
@@ -3,8 +3,10 @@ package com.volmit.host;
import com.volmit.*;
import com.volmit.config.Feature;
import com.volmit.config.Level;
import com.volmit.data.Codec;
import com.volmit.data.SavedKey;
import com.volmit.data.StorageCodec;
import com.volmit.mantle.*;
import com.volmit.resource.ResourceId;
import com.volmit.resource.ResourceKind;
import com.volmit.service.Providers;
import com.volmit.service.Service;
@@ -79,12 +81,12 @@ class ModuleRegistryTest {
@Test
void mantleIdsAreUniqueAndCodecVersionIsSnapshotted() {
var registry = new ModuleRegistry();
var key = new MantleKey<>("test:core/layer", String.class);
var key = new MantleKey<>(ResourceId.parse("test:core/layer"), String.class);
var codec = codec(3);
registerAs(registry, "test:core", layers -> {
layers.registerMantle(key, MantleLifetime.GENERATION, codec);
assertThrows(IllegalArgumentException.class, () -> layers.registerMantle(key, MantleLifetime.PERSISTENT, codec));
assertThrows(IllegalArgumentException.class, () -> layers.registerMantle(new MantleKey<>("test:core/bad", String.class), MantleLifetime.GENERATION, codec(-1)));
assertThrows(IllegalArgumentException.class, () -> layers.registerMantle(new MantleKey<>(ResourceId.parse("test:core/bad"), String.class), MantleLifetime.GENERATION, codec(-1)));
});
assertEquals(3, registry.freeze().mantle().getFirst().version());
assertEquals(1, registry.freeze().mantle().size());
@@ -98,11 +100,11 @@ class ModuleRegistryTest {
assertTrue(sameNamespace.getMessage().contains("must be test:other or start with test:other/"), sameNamespace.getMessage());
var mantle = assertThrows(IllegalArgumentException.class, () -> registerAs(registry, "iris:snow",
layers -> layers.registerMantle(new MantleKey<>("iris:snowdepth", String.class), MantleLifetime.GENERATION, codec(1))));
layers -> layers.registerMantle(new MantleKey<>(ResourceId.parse("iris:snowdepth"), String.class), MantleLifetime.GENERATION, codec(1))));
assertEquals("Mantle layer iris:snowdepth must be iris:snow or start with iris:snow/, the id of its registering module "
+ "iris:snow from host classpath", mantle.getMessage());
assertThrows(IllegalStateException.class, () -> registry.registerMantle(new MantleKey<>("test:loose", String.class),
assertThrows(IllegalStateException.class, () -> registry.registerMantle(new MantleKey<>(ResourceId.parse("test:loose"), String.class),
MantleLifetime.GENERATION, codec(1)));
assertTrue(registry.freeze().settings().isEmpty());
assertTrue(registry.freeze().mantle().isEmpty());
@@ -208,16 +210,37 @@ class ModuleRegistryTest {
};
}
private static SavedKey<String> saved(String id) {
return new SavedKey<>(ResourceId.parse(id), String.class, codec(1), () -> "");
}
@Test
void savedKeysAreOwnedByTheRegisteringModuleAndUnique() {
var registry = new ModuleRegistry();
var key = saved("test:core/book");
registerAs(registry, "test:core", saves -> {
saves.registerSaved(key);
assertThrows(IllegalArgumentException.class, () -> saves.registerSaved(saved("test:core/book")));
assertThrows(NullPointerException.class, () -> saves.registerSaved(null));
});
assertEquals(List.of(key), registry.freeze().saved());
var foreign = assertThrows(IllegalArgumentException.class, () -> registerAs(new ModuleRegistry(), "test:other",
saves -> saves.registerSaved(key)));
assertTrue(foreign.getMessage().contains("must be test:other or start with test:other/"), foreign.getMessage());
assertThrows(IllegalStateException.class, () -> new ModuleRegistry().registerSaved(key));
}
@Test
void moduleMayRegisterItsOwnIdAndIdsBelowIt() {
var registry = new ModuleRegistry();
registerAs(registry, "iris:snow", layers -> {
layers.registerMantle(new MantleKey<>("iris:snow", String.class), MantleLifetime.GENERATION, codec(1));
layers.registerMantle(new MantleKey<>("iris:snow/depth/deep", String.class), MantleLifetime.GENERATION, codec(1));
layers.registerMantle(new MantleKey<>(ResourceId.parse("iris:snow"), String.class), MantleLifetime.GENERATION, codec(1));
layers.registerMantle(new MantleKey<>(ResourceId.parse("iris:snow/depth/deep"), String.class), MantleLifetime.GENERATION, codec(1));
});
assertEquals(List.of("iris:snow", "iris:snow/depth/deep"),
registry.freeze().mantle().stream().map(layer -> layer.key().id()).sorted().toList());
registry.freeze().mantle().stream().map(layer -> layer.key().id().toString()).sorted().toList());
}
@Test
@@ -592,8 +615,8 @@ class ModuleRegistryTest {
assertEquals("test:alpha", registrations.getFirst().module().info().id().toString());
}
private static Codec<String> codec(int version) {
return new Codec<>() {
private static StorageCodec<String> codec(int version) {
return new StorageCodec<>() {
public int version() { return version; }
public void write(DataOutput output, String value) {}
public String read(DataInput input, int storedVersion) { return ""; }
@@ -11,7 +11,7 @@ import com.volmit.config.Feature;
import com.volmit.config.FeatureSettings.Entry;
import com.volmit.geometry.BlockBox;
import com.volmit.geometry.BlockPosition;
import com.volmit.data.Codec;
import com.volmit.data.StorageCodec;
import com.volmit.mantle.MantleKey;
import com.volmit.mantle.MantleLifetime;
import com.volmit.object.GeneratedObject;
@@ -519,7 +519,7 @@ class StageGraphTest {
@Test
void onePlacementInvocationMakesItsMantleViewsOnce() {
var key = new MantleKey<>("test:views/depth", Integer.class);
var key = new MantleKey<>(ResourceId.parse("test:views/depth"),Integer.class);
var views = new ArrayList<Object>();
var graph = resolve(Pipeline.PLACEMENT, module("test:views", stages ->
stages.define(Stage.placement("test:views/read")).run(context -> {
@@ -569,8 +569,8 @@ class StageGraphTest {
@Test
void reachIsDeclaredPerStageAndCollectedPerPipelineAndLayer() {
var depth = new MantleKey<>("test:reach/depth", Integer.class);
var marks = new MantleKey<>("test:reach/marks", String.class);
var depth = new MantleKey<>(ResourceId.parse("test:reach/depth"), Integer.class);
var marks = new MantleKey<>(ResourceId.parse("test:reach/marks"), String.class);
var carve = Stage.mantle("test:reach/carve");
var mark = Stage.mantle("test:reach/mark");
var plain = Stage.mantle("test:reach/plain");
@@ -585,7 +585,7 @@ class StageGraphTest {
assertEquals(new StageReach(24, List.of(depth)), loaded.mantle().stages().getFirst().reach());
assertEquals(StageReach.NONE, loaded.mantle().stages().get(2).reach(), "an undeclared reach is 0 with no layers");
assertEquals(new PipelineReach(24, Map.of("test:reach/depth", 24, "test:reach/marks", 8)), loaded.mantle().reach());
assertEquals(new PipelineReach(24, Map.of(depth.id(), 24, marks.id(), 8)), loaded.mantle().reach());
assertEquals(new PipelineReach(2, Map.of()), loaded.placement().reach());
assertEquals(new PipelineReach(0, Map.of()), loaded.chunk().reach());
assertTrue(loaded.mantle().describe().contains(" reach 24 blocks, writes mantle test:reach/depth\n"), loaded.mantle().describe());
@@ -655,7 +655,7 @@ class StageGraphTest {
@Test
void reachMustBeValidAndNameRegisteredLayers() {
var depth = new MantleKey<>("test:reach/depth", Integer.class);
var depth = new MantleKey<>(ResourceId.parse("test:reach/depth"), Integer.class);
var carve = Stage.mantle("test:reach/carve");
var negative = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.MANTLE,
@@ -672,7 +672,7 @@ class StageGraphTest {
assertEquals("Stage test:reach/carve of module test:reach writes mantle layer test:reach/depth, which no module registers;"
+ " its owner registers it with FeatureRegistry.registerMantle", unregistered.getMessage());
var asText = new MantleKey<>("test:reach/depth", String.class);
var asText = new MantleKey<>(ResourceId.parse("test:reach/depth"), String.class);
var mismatch = assertThrows(ModuleLoadException.class, () -> LoadedModules.load(List.of(DiscoveredModule.builtIn(withMantle(
module("test:reach", stages -> stages.define(carve).writesMantle(asText).run(context -> {})), depth))), Map.of(), Set.of(), Set.of()));
assertEquals("Stage test:reach/carve of module test:reach writes mantle layer test:reach/depth as java.lang.String,"
@@ -694,8 +694,8 @@ class StageGraphTest {
registry.registerMantle(layer, MantleLifetime.GENERATION, codec(layer));
}
private static <T> Codec<T> codec(MantleKey<T> layer) {
return new Codec<>() {
private static <T> StorageCodec<T> codec(MantleKey<T> layer) {
return new StorageCodec<>() {
public int version() { return 0; }
public void write(java.io.DataOutput output, T value) {}
public T read(java.io.DataInput input, int storedVersion) { throw new UnsupportedOperationException(); }
@@ -21,15 +21,15 @@ public final class MemoryMantle {
.thenComparingInt(BlockPosition::y).thenComparingInt(BlockPosition::z);
/** Where the planned blocks are kept; the host owns them, so no module registers this layer. */
private static final MantleKey<BlockState> PLANNED_BLOCKS = new MantleKey<>("host:planned-blocks", BlockState.class);
private static final MantleKey<BlockState> PLANNED_BLOCKS = new MantleKey<>(ResourceId.parse("host:planned-blocks"),BlockState.class);
/** Where the carved voids are kept; the host owns them, so no module registers this layer. */
private static final MantleKey<CarvedVoid> CAVERNS = new MantleKey<>("host:caverns", CarvedVoid.class);
private static final MantleKey<CarvedVoid> CAVERNS = new MantleKey<>(ResourceId.parse("host:caverns"),CarvedVoid.class);
/** Where the platform biomes stages set are kept; the host owns them, so no module registers this layer. */
private static final MantleKey<ResourceId> PLATFORM_BIOMES = new MantleKey<>("host:platform-biomes", ResourceId.class);
private static final MantleKey<ResourceId> PLATFORM_BIOMES = new MantleKey<>(ResourceId.parse("host:platform-biomes"),ResourceId.class);
private final Map<String, TreeMap<BlockPosition, Object>> layers = new HashMap<>();
private final Map<ResourceId, TreeMap<BlockPosition, Object>> layers = new HashMap<>();
/** A view that accepts reads and writes inside {@code bounds} only. */
public Mantle within(BlockBox bounds) {