mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-12-03 03:31:32 +00:00
Add RunningWorld.saved, state a module keeps with the world across restarts
A world's state store is memory only, so Iris offered spawner cooldowns through a facade to persist them. SavedKey names a value with its codec and initial value; the host reads it on first ask and writes it when it saves and stops the world.
This commit is contained in:
1 parent
7cc3302c32
commit
a0fcb74365
6 files changed
+166
-11
No files matched your search
+4
-1
@@ -25,6 +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` |
|
| 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 |
|
| 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) |
|
| 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) |
|
||||||
| Host facades for the host's own modules | `PackWorld.extension(type)`, `InvocationContext.extension(type)`, `PackSettings.extension(type)` (each an `Optional`, empty by default) |
|
| 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` |
|
| 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` |
|
| 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` |
|
||||||
@@ -99,7 +100,9 @@ and what it mounts, is the adapter's. `ModuleJarCheck --platform=<name>:<platfor
|
|||||||
|
|
||||||
Stage bodies and service providers keep no state; what a module keeps for a world lives in that world's state store,
|
Stage bodies and service providers keep no state; what a module keeps for a world lives in that world's state store,
|
||||||
created once per type and world. A world's state lives while the world runs with one pack snapshot: a hotload or a
|
created once per type and world. A world's state lives while the world runs with one pack snapshot: a hotload or a
|
||||||
reload of the pack's resources starts the world again with empty state. A service names how its providers combine
|
reload of the pack's resources starts the world again with empty state; what must outlive that is a
|
||||||
|
`RunningWorld.saved` value, which the host reads on first use, writes when it saves the world and when the world stops,
|
||||||
|
and replaces by its `initial` when the codec rejects the stored payload. A service names how its providers combine
|
||||||
(`ALL`, `FIRST`, `ONE`); a second provider of a `ONE` service fails the pack load, naming both modules. Services
|
(`ALL`, `FIRST`, `ONE`); a second provider of a `ONE` service fails the pack load, naming both modules. Services
|
||||||
return values and never act on the platform.
|
return values and never act on the platform.
|
||||||
|
|
||||||
|
|||||||
@@ -1145,6 +1145,15 @@ each world a state store and tells modules when worlds start and stop.
|
|||||||
on its own thread, since creation holds one re-entrant lock, and asking for the type being created fails naming the
|
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.
|
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.
|
`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,
|
||||||
|
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
|
||||||
|
module's saved state is a convenience, so a bad file never keeps a world from starting. The id names the stored
|
||||||
|
file, so it is checked against path tricks when the key is made. It replaced Iris's spawner-cooldown facade, which
|
||||||
|
existed only because API state was memory only.
|
||||||
- **Hooks.** `ModuleLifecycle` has `packLoaded(pack)`, `worldStarted(world)`, `warmUp(world)` and
|
- **Hooks.** `ModuleLifecycle` has `packLoaded(pack)`, `worldStarted(world)`, `warmUp(world)` and
|
||||||
`worldStopped(world)`,
|
`worldStopped(world)`,
|
||||||
each a no-op by default, registered with `FeatureRegistry.registerLifecycle` like validators, so the host knows the
|
each a no-op by default, registered with `FeatureRegistry.registerLifecycle` like validators, so the host knows the
|
||||||
@@ -1291,16 +1300,15 @@ A module jar sees three things besides the JDK and its own pack's jars, and noth
|
|||||||
built-in modules read stays in their jar, unexposed. Its snippets live under its module's id in a pack's snippet
|
built-in modules read stays in their jar, unexposed. Its snippets live under its module's id in a pack's snippet
|
||||||
folders (`snippet/iris/objects/...`), as every built-in's do.
|
folders (`snippet/iris/objects/...`), as every built-in's do.
|
||||||
3. **Narrow facades for the host's own built-ins**, in that same exposed package, for what only the host's own
|
3. **Narrow facades for the host's own built-ins**, in that same exposed package, for what only the host's own
|
||||||
features need from its internals, such as the legacy random streams Iris's object placement draws from, which
|
features need from its internals, such as the structure placer. A pack module never needs one. Every such type is a promise the host keeps, so there are few, each answers one
|
||||||
existing worlds depend on. A pack module never needs one. Every such type is a promise the host keeps, so there are few, each answers one
|
|
||||||
question, and none hands out an engine.
|
question, and none hands out an engine.
|
||||||
|
|
||||||
**The extension point.** A built-in reaches its facade through one door: `PackWorld.extension(type)` for what belongs to
|
**The extension point.** A built-in reaches its facade through one door: `PackWorld.extension(type)` for what belongs to
|
||||||
a world (Iris's legacy random streams, spawner cooldowns Iris persists), `InvocationContext.extension(type)` for what belongs to one invocation (the
|
a world (Iris's structure host), `InvocationContext.extension(type)` for what belongs to one invocation (the
|
||||||
platform chunk Iris generates), and `PackSettings.extension(type)` for what is worked out
|
platform chunk Iris generates), and `PackSettings.extension(type)` for what is worked out
|
||||||
from a pack's settings before any world exists (how far a feature reaches). Each returns an `Optional`, empty by default,
|
from a pack's settings before any world exists (how far a feature reaches). Each returns an `Optional`, empty by default,
|
||||||
so a host offers what it has and a module states what it requires:
|
so a host offers what it has and a module states what it requires:
|
||||||
`world.extension(LegacyStreams.class).orElseThrow()`. Why one door:
|
`world.extension(StructureHost.class).orElseThrow()`. Why one door:
|
||||||
|
|
||||||
- **No thread-locals.** Facades used to be bound to the current thread (`IrisChunk.current()`, `ObjectPlacement.current()`),
|
- **No thread-locals.** Facades used to be bound to the current thread (`IrisChunk.current()`, `ObjectPlacement.current()`),
|
||||||
which only worked while the host's own code had bound them and broke silently on another thread. The context a stage
|
which only worked while the host's own code had bound them and broke silently on another thread. The context a stage
|
||||||
@@ -1331,9 +1339,6 @@ API now: `world.running()`, `world.seed(purpose)`, `TerrainSampler`, `FeatureSet
|
|||||||
- **`MatterMantle`** (invocation). Carve plans its caves as VolmLib matter slices (`MatterCavern`, markers) that Iris and the
|
- **`MatterMantle`** (invocation). Carve plans its caves as VolmLib matter slices (`MatterCavern`, markers) that Iris and the
|
||||||
platform read back as slices. The API mantle has typed layers but no cavern layer; it goes when carve writes a layer the
|
platform read back as slices. The API mantle has typed layers but no cavern layer; it goes when carve writes a layer the
|
||||||
API defines and Iris reads that instead.
|
API defines and Iris reads that instead.
|
||||||
- **`LegacyStreams`** (world). Iris's object chunk random, and the noise of a placement's density style and virtual
|
|
||||||
heightmap, which decide where existing worlds have their objects and which no API noise reproduces value for value. It
|
|
||||||
goes when a world format change lets object placing draw from stage streams and API noise.
|
|
||||||
- **`objects.ObjectRun`** (the input of a placement run, `PlacementRun.input`). The object and the module's own
|
- **`objects.ObjectRun`** (the input of a placement run, `PlacementRun.input`). The object and the module's own
|
||||||
`objects.ObjectPlacement` settings that Iris's built-in placement stages read, and what they report back (the anchor
|
`objects.ObjectPlacement` settings that Iris's built-in placement stages read, and what they report back (the anchor
|
||||||
height, which written blocks are the object's). The placement-level module settings no longer need it: the run carries
|
height, which written blocks are the object's). The placement-level module settings no longer need it: the run carries
|
||||||
@@ -1344,8 +1349,6 @@ API now: `world.running()`, `world.seed(purpose)`, `TerrainSampler`, `FeatureSet
|
|||||||
loot of its pieces. The structure model (structures, pools, pieces) is `iris:structure`'s own resource kinds, which Iris
|
loot of its pieces. The structure model (structures, pools, pieces) is `iris:structure`'s own resource kinds, which Iris
|
||||||
registers with its own modules because its jigsaw studio reads them. Its surface is already API vocabulary; it goes when
|
registers with its own modules because its jigsaw studio reads them. Its surface is already API vocabulary; it goes when
|
||||||
the placer can write through the API.
|
the placer can write through the API.
|
||||||
- **`spawn.SpawnCooldowns`** (world). Spawner cooldowns Iris saves with a world's engine data, so they survive a restart; API
|
|
||||||
per-world state is in memory only. It goes when the API can persist per-world state.
|
|
||||||
- **Random parameters (`RNG`) in these facades and `loot.LootResolver`**. They are the legacy streams existing worlds were
|
- **Random parameters (`RNG`) in these facades and `loot.LootResolver`**. They are the legacy streams existing worlds were
|
||||||
generated from. They go when a world format change lets them be stage streams.
|
generated from. They go when a world format change lets them be stage streams.
|
||||||
|
|
||||||
|
|||||||
@@ -353,6 +353,23 @@ static PlantedChunks planted(PackWorld world) {
|
|||||||
keeps nothing. Use a class of the module as the type.
|
keeps nothing. Use a class of the module as the type.
|
||||||
- A state that is `AutoCloseable` is closed after the world stops, once nothing generates with it.
|
- 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:
|
||||||
|
|
||||||
|
```java
|
||||||
|
private static final SavedKey<LastWaves> WAVES = new SavedKey<>("example:waves/last", LastWaves.class, new LastWavesCodec(), LastWaves::new);
|
||||||
|
|
||||||
|
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
|
||||||
|
```
|
||||||
|
|
||||||
|
- 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`.
|
||||||
|
- The id names the stored file, so its path has no empty, `.` or `..` segment.
|
||||||
|
|
||||||
A module that wants to act when the host loads a pack or starts or stops a world registers a `ModuleLifecycle`. Every
|
A module that wants to act when the host loads a pack or starts or stops a world registers a `ModuleLifecycle`. Every
|
||||||
hook does nothing by default, and a module class may implement it and register itself:
|
hook does nothing by default, and a module class may implement it and register itself:
|
||||||
|
|
||||||
@@ -1099,7 +1116,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.
|
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 views (`ctx.mantle()`, its layers and blocks, a placement's `access().mantle()`) are made once per
|
||||||
invocation, so asking again returns the same view.
|
invocation, so asking again returns the same view.
|
||||||
- The `mantle` package keeps namespaced typed layers, codecs, lifetimes and buffered edits.
|
- The `mantle` package keeps namespaced typed layers, lifetimes and buffered edits; `com.volmit.data.Codec` stores
|
||||||
|
their values, and the values of `RunningWorld.saved`.
|
||||||
- `IrisFeature`, `@Feature`, the config annotations (`@Desc`, `@Required`, `@MinNumber`,
|
- `IrisFeature`, `@Feature`, the config annotations (`@Desc`, `@Required`, `@MinNumber`,
|
||||||
`@MaxNumber`, `@MinItems`, `@Snippet`, `@Ref`) describe settings; the host reads them with `OptionsMetadata`
|
`@MaxNumber`, `@MinItems`, `@Snippet`, `@Ref`) describe settings; the host reads them with `OptionsMetadata`
|
||||||
(`com.volmit.host`).
|
(`com.volmit.host`).
|
||||||
|
|||||||
@@ -42,6 +42,23 @@ public interface RunningWorld {
|
|||||||
*/
|
*/
|
||||||
Optional<PlacementRecord> placementAt(int worldX, int y, int worldZ);
|
Optional<PlacementRecord> placementAt(int worldX, int y, int worldZ);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The value the module keeps with this world across restarts under {@code key}: the host's one instance of it for
|
||||||
|
* the world, read from the world's storage the first time anyone asks (or {@code key.initial()} when none was
|
||||||
|
* stored), and written back when the host saves the world and when it stops. Keep what a spawner last did or a
|
||||||
|
* counter that must outlive the server here, not what can be rebuilt from the pack; per-world caches belong in
|
||||||
|
* {@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
|
||||||
|
* 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
|
||||||
|
*/
|
||||||
|
<T> T saved(SavedKey<T> key);
|
||||||
|
|
||||||
/** The time and weather of the world; empty while the platform has not loaded the world. */
|
/** The time and weather of the world; empty while the platform has not loaded the world. */
|
||||||
Optional<Sky> sky();
|
Optional<Sky> sky();
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package com.volmit.world;
|
||||||
|
|
||||||
|
import com.volmit.data.Codec;
|
||||||
|
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 starts with the owning module's id or its
|
||||||
|
* namespace; the host names its storage after it, so each {@code /} separated segment of the 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 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.substring(id.indexOf(':') + 1).split("/", -1)) {
|
||||||
|
if (segment.isEmpty() || segment.equals(".") || segment.equals("..")) {
|
||||||
|
throw new IllegalArgumentException("A saved ID names files, so its path has no empty, . or .. segment: " + id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
package com.volmit.world;
|
||||||
|
|
||||||
|
import com.volmit.data.Codec;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.io.DataInput;
|
||||||
|
import java.io.DataOutput;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
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<>() {
|
||||||
|
@Override
|
||||||
|
public int version() {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void write(DataOutput output, String value) throws IOException {
|
||||||
|
output.writeUTF(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String read(DataInput input, int storedVersion) throws IOException {
|
||||||
|
return input.readUTF();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void acceptsNamespacedIdsWithNestedPaths() {
|
||||||
|
assertDoesNotThrow(() -> key("example:spawn/cooldowns"));
|
||||||
|
assertDoesNotThrow(() -> key("example:book.v2"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsIdsThatAreNotNamespaced() {
|
||||||
|
for (String id : new String[]{"", "book", ":book", "example:", "Example:book", "a:b:c"}) {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> key(id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsIdsThatCouldLeaveTheWorldsStorage() {
|
||||||
|
for (String id : new String[]{"example:../book", "example:a/../b", "example:./book", "example:/book", "example:book/", "example:a//b"}) {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> key(id), id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@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<>() {
|
||||||
|
@Override
|
||||||
|
public int version() {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void write(DataOutput output, Integer value) throws IOException {
|
||||||
|
output.writeInt(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Integer read(DataInput input, int storedVersion) throws IOException {
|
||||||
|
return input.readInt();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new SavedKey<>("a:b", int.class, number, () -> 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static SavedKey<String> key(String id) {
|
||||||
|
return new SavedKey<>(id, String.class, TEXT, () -> "");
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user