diff --git a/CONTRACTS.md b/CONTRACTS.md index 5dfb1b399..24ab32818 100644 --- a/CONTRACTS.md +++ b/CONTRACTS.md @@ -208,6 +208,12 @@ running Iris is the pack publisher's responsibility. (`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. +- Answer `PackWorld.seed(purpose)` with `WorldRandom.purposeSeed(seed(), purpose)`, except for ids of your own built-ins + whose existing worlds depend on other seeds; the same world and purpose always get the same seed. +- Answer `PackWorld.running()` for a world the host runs, empty for a tool's world. Its `layout()` covers every column of + the world (not one chunk), with the same values chunk stages read; its `settings()` are the settings at a column and a + biome's declarations as chunk stages see them; `highestBlock` is the platform's highest block now; `caveFloors` are + the cave floor markers of a chunk, in heights above the bottom; `sky()` is empty until the platform has the world. - 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 6f843facd..e984c364b 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -1068,6 +1068,18 @@ each world a state store and tells modules when worlds start and stop. 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. +- **Purpose seeds.** `PackWorld.seed(purpose)` is the seed a world gives a purpose id, specified as + `WorldRandom.purposeSeed(seed(), purpose)` (FNV-1a of the id, SplitMix64-mixed with the world seed) and pinned. Modules + mixed `seed()` with salts by hand, and Iris's built-ins asked a facade (`IrisSeeds`) for its per-feature seeds; one + method serves both, because a host may answer its own built-ins' ids (`iris:seed/terrain`, `iris:seed/carve`) with the + seeds its existing worlds were generated with, and every other id by the specification. +- **The running world.** `PackWorld.running()` is the world as it runs now, for services and lifecycle hooks, which have + no chunk to ask: the layout over every column as a `TerrainSampler`, the settings at a column and of a biome as + `FeatureSettings`, the highest block now, the cave floors the mantle marked, the sky (time and weather), the platform's + loot tables and whether it is a debug world. It reuses the chunk vocabulary instead of a second one: Iris's built-ins + read the same through a facade (`LiveWorld`, with its own `Level`, `BiomeKind` and `Sky`), now deleted. Empty for a + tool's world, which nothing runs. Which biome a block "is in" (cave below the surface, else surface) stays a module + rule, not API: hosts and modules disagree on it, and the layout already answers both biomes. - **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 @@ -1216,16 +1228,16 @@ A module jar sees three things besides the JDK and its own pack's jars, and noth 2. **Packages the host exposes**: libraries it shares (VolmLib, Gson) and the public face of its built-in modules (`art.arcane.iris.builtin`: stage constants, settings and output types packs may read). 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 Iris's per-feature world seeds (`IrisSeeds`), which 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 + features need from its internals, such as the legacy random streams Iris's object placement draws from, which + 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. **The extension point.** A built-in reaches its facade through one door: `PackWorld.extension(type)` for what belongs to -a world (seeds, the world at a block), `InvocationContext.extension(type)` for what belongs to one invocation (the +a world (the object system, spawner cooldowns Iris persists), `InvocationContext.extension(type)` for what belongs to one invocation (the platform chunk Iris generates, the placement being attempted), 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, so a host offers what it has and a module states what it requires: -`world.extension(IrisSeeds.class).orElseThrow()`. Why one door: +`world.extension(ObjectHost.class).orElseThrow()`. Why one door: - **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 diff --git a/README.md b/README.md index d70fa926e..e5f53e86a 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,12 @@ JDK may change, so use `pick` and `shuffle` instead of `Collections.shuffle`. Bo unbiased, `nextDouble` never returns its bound, and invalid bounds throw. It is not thread-safe: a stage uses its own stream within one invocation and must not share or keep it. +A module's own world-wide randoms and noise take `world.seed(purpose)`, the seed the world gives a purpose id such as +`example:moss/patches`: the same for the same world and purpose, independent across purposes, so two modules never +mix the world seed into the same value by hand. Hosts answer `WorldRandom.purposeSeed(world.seed(), purpose)`, pinned +like every other `WorldRandom` value; Iris answers its built-ins' `iris:seed/*` purposes with the seeds its worlds +always had. + ## The mantle pipeline and reach A chunk stage writes only its own chunk: the host may already have generated its neighbors. Work that @@ -291,7 +297,7 @@ static PlantedChunks planted(PackWorld world) { } ``` -- `ctx.world()` is the `PackWorld` an invocation generates: its seed, the pack snapshot's resources, the settings of +- `ctx.world()` is the `PackWorld` an invocation generates: its seed and purpose seeds, 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 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. @@ -382,6 +388,11 @@ final class RuinsObjects implements ObjectsAt { carries out on the right thread. - Services name pack resources by `ResourceId` (`world.resources().idOf(key)` for a key the pack wrote), and absent values in what they return are `Optional`s. +- A service that answers about the world as it runs, outside any chunk, reads `world.running()`: the layout over every + column (`layout()`, a `TerrainSampler`), the settings at a column and what a biome declares (`settings()`), the + highest block now, the cave floors the mantle marked, the time and weather (`sky()`, empty until the platform has + the world), the platform's loot tables and whether the world is a debug (studio) world. It is empty for a tool's + world, which nothing runs. - Each service says how several providers combine, with `@Service(Providers.X)`: `ALL` (the host asks every provider and combines the answers), `FIRST` (the host asks in order until one answers) or `ONE` (at most one provider per pack; a second fails the pack load, naming both modules). Providers are in module id order, each module's in @@ -611,12 +622,12 @@ public final class VeinSettings implements IrisFeature { // in a stage var resources = ctx.world().resources(); -NoiseSampler density = resources.noise().sampler(veins.density(), ctx.world().seed() ^ VEIN_SALT); +NoiseSampler density = resources.noise().sampler(veins.density(), ctx.world().seed(VEIN_DENSITY)); // ResourceId example:veins/density 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 `world().seed()`, so the noise +expression or image map of the pack, and the host builds the noise. Seed it from a world seed (`world().seed(purpose)`), 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 diff --git a/api/src/main/java/com/volmit/random/WorldRandom.java b/api/src/main/java/com/volmit/random/WorldRandom.java index 17cbbfa78..1c111fc83 100644 --- a/api/src/main/java/com/volmit/random/WorldRandom.java +++ b/api/src/main/java/com/volmit/random/WorldRandom.java @@ -1,5 +1,7 @@ package com.volmit.random; +import com.volmit.resource.ResourceId; +import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; import java.util.ListIterator; @@ -46,6 +48,8 @@ import java.util.RandomAccess; */ public final class WorldRandom { private static final long GOLDEN_GAMMA = 0x9e3779b97f4a7c15L; + private static final long FNV_OFFSET_BASIS = 0xcbf29ce484222325L; + private static final long FNV_PRIME = 0x100000001b3L; private static final int INT_BITS = 32; private static final long UNSIGNED_INT_MASK = 0xffff_ffffL; private static final long INT_RANGE = 1L << INT_BITS; @@ -60,6 +64,20 @@ public final class WorldRandom { state = seed; } + /** + * The seed for {@code purpose} of a world whose seed is {@code worldSeed}: {@code mix(worldSeed ^ mix(h))}, where + * {@code mix} is the finalizer above and {@code h} the 64-bit FNV-1a hash (offset basis {@code 0xcbf29ce484222325}, + * prime {@code 0x100000001b3}) of the UTF-8 bytes of {@code purpose.toString()}. Different purposes give independent + * seeds; see {@link com.volmit.world.PackWorld#seed(ResourceId)}. + */ + public static long purposeSeed(long worldSeed, ResourceId purpose) { + long hash = FNV_OFFSET_BASIS; + for (byte octet : purpose.toString().getBytes(StandardCharsets.UTF_8)) { + hash = (hash ^ (octet & 0xff)) * FNV_PRIME; + } + return mix(worldSeed ^ mix(hash)); + } + /** A uniformly distributed {@code long}: the next SplitMix64 output. */ public long nextLong() { state += GOLDEN_GAMMA; diff --git a/api/src/main/java/com/volmit/world/PackWorld.java b/api/src/main/java/com/volmit/world/PackWorld.java index cf7af027f..d5c53999e 100644 --- a/api/src/main/java/com/volmit/world/PackWorld.java +++ b/api/src/main/java/com/volmit/world/PackWorld.java @@ -3,6 +3,7 @@ package com.volmit.world; import com.volmit.ModuleLog; import com.volmit.config.PackSettings; import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import java.util.Optional; import java.util.function.Function; @@ -25,6 +26,15 @@ import java.util.function.Function; public interface PackWorld { long seed(); + /** + * The seed this world gives {@code purpose}, such as {@code example:moss/patches}: the same for the same world and + * purpose, independent across purposes. Seed a module's own randoms and noise with it instead of mixing + * {@link #seed()} by hand. A host answers {@link com.volmit.random.WorldRandom#purposeSeed} of the world's seed, + * except for purposes of its own modules whose worlds already depend on other seeds: Iris answers the ids of + * {@code iris:} purposes its built-in modules use with the seeds its worlds always had. + */ + long seed(ResourceId purpose); + /** The pack snapshot this world generates with. */ PackResources resources(); @@ -38,6 +48,9 @@ public interface PackWorld { */ int minWorldY(); + /** The world as it runs now, for services and lifecycle hooks; empty for a tool's world, which nothing runs. */ + Optional running(); + /** * The world's one {@code type} instance, created by {@code create} the first time anyone asks for it. Modules keep * their caches and per-world workers here instead of in fields, since stage bodies and services are shared by every diff --git a/api/src/main/java/com/volmit/world/RunningWorld.java b/api/src/main/java/com/volmit/world/RunningWorld.java new file mode 100644 index 000000000..b9b669c38 --- /dev/null +++ b/api/src/main/java/com/volmit/world/RunningWorld.java @@ -0,0 +1,54 @@ +package com.volmit.world; + +import com.volmit.config.FeatureSettings; +import com.volmit.geometry.BlockPosition; +import com.volmit.resource.ResourceId; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +/** A world the host is running, as it is now, for services and lifecycle hooks: they have no chunk, so they ask the + * world's layout, settings and platform state here instead of through an invocation. A chunk stage uses its + * invocation's views, which may differ while the chunk generates. + * + *

X and Z are world coordinates; Y is the height above the dimension's bottom, as everywhere in the API. The views + * live as long as the world and are safe to use from any thread. + */ +public interface RunningWorld { + /** The world's terrain and biomes as generation lays them out, before anything was placed: its bounds are every + * column of the world at full height. The same answers a chunk stage's {@link TerrainSampler} gives for its columns. + */ + TerrainSampler layout(); + + /** The settings at a world column, as a chunk stage's {@link FeatureSettings} gives them: the dimension's, the + * column's region's and its surface biome's; a cave biome's through {@link FeatureSettings#declaredBy}. + */ + FeatureSettings settings(); + + /** The height of the highest block in the column now: the terrain with what objects and structures added. + * {@code ignoreFluid} skips fluid blocks, so it answers the ground under a sea. + */ + int highestBlock(int worldX, int worldZ, boolean ignoreFluid); + + /** The floors of the caves generation marked in the chunk, as positions of the floor blocks; none on a platform that + * cannot read them. + */ + List caveFloors(int chunkX, int chunkZ); + + /** The time and weather of the world; empty while the platform has not loaded the world. */ + Optional sky(); + + /** The ids of the loot tables the platform has, such as {@code minecraft:chests/simple_dungeon}. They do not change + * while the world runs. + */ + Set platformLootTables(); + + /** Whether the world is one a pack author is working on (Iris: a studio world): the host then shows where generated + * things came from, such as the sources of items ({@link com.volmit.item.ItemDrop#source()}). + */ + boolean debug(); + + /** The world's time of day in ticks, whether it storms and whether it thunders. */ + record Sky(long time, boolean storming, boolean thundering) { + } +} diff --git a/api/src/test/java/com/volmit/random/WorldRandomTest.java b/api/src/test/java/com/volmit/random/WorldRandomTest.java index 42f366919..f852b58cd 100644 --- a/api/src/test/java/com/volmit/random/WorldRandomTest.java +++ b/api/src/test/java/com/volmit/random/WorldRandomTest.java @@ -1,5 +1,6 @@ package com.volmit.random; +import com.volmit.resource.ResourceId; import org.junit.jupiter.api.Test; import java.lang.reflect.Method; import java.lang.reflect.Modifier; @@ -35,6 +36,13 @@ class WorldRandomTest { 6349198060258255764L, 701532786141963250L, -2430762948046562554L), draws(6, WorldRandom::nextLong)); } + @Test + void purposeSeedsFollowTheirSpecification() { + assertEquals(4999169706209116627L, WorldRandom.purposeSeed(42, ResourceId.parse("example:moss/patches"))); + assertEquals(1770219120571522516L, WorldRandom.purposeSeed(42, ResourceId.parse("example:moss/caves"))); + assertEquals(1140829150526819945L, WorldRandom.purposeSeed(-7, ResourceId.parse("example:moss/patches"))); + } + @Test void intsAreTheHighHalfOfALong() { assertEquals(List.of(-1109970394, 686809907, 1196582743, 1478287871, 163338330, -565956102), @@ -251,7 +259,7 @@ class WorldRandomTest { assertEquals(Set.of("nextLong()", "nextLong(long)", "nextLong(long,long)", "nextInt()", "nextInt(int)", "nextInt(int,int)", "nextBoolean()", "nextFloat()", "nextDouble()", "nextDouble(double)", "nextDouble(double,double)", "nextGaussian()", "chance(double)", "pick(java.util.List)", - "shuffle(java.util.List)"), methods); + "shuffle(java.util.List)", "purposeSeed(long,com.volmit.resource.ResourceId)"), methods); } private static List shuffled(int size) { diff --git a/api/src/test/reference/world_random.py b/api/src/test/reference/world_random.py index c35edb6d2..22b0caaa4 100644 --- a/api/src/test/reference/world_random.py +++ b/api/src/test/reference/world_random.py @@ -37,6 +37,10 @@ def stream_seed(invocation_seed, stage_id): return mix(mix(invocation_seed & MASK64) ^ fnv1a64(stage_id)) +def purpose_seed(world_seed, purpose): + return mix((world_seed & MASK64) ^ mix(fnv1a64(purpose))) + + # fdlibm __ieee754_log (e_log.c), the algorithm StrictMath.log specifies. LN2_HI = 6.93147180369123816490e-01 LN2_LO = 1.90821492927058770002e-10 @@ -210,6 +214,8 @@ def draws(label, method, count=6, seed=42): if __name__ == "__main__": print(f"fnv1a64(iris:stilt/fill) = {signed64(fnv1a64('iris:stilt/fill'))}") print(f"streamSeed(42, iris:stilt/fill) = {signed64(stream_seed(42, 'iris:stilt/fill'))}") + for seed, purpose in [(42, "example:moss/patches"), (42, "example:moss/caves"), (-7, "example:moss/patches")]: + print(f"purposeSeed({seed}, {purpose}) = {signed64(purpose_seed(seed, purpose))}") stage = WorldRandom(stream_seed(42, "iris:stilt/fill")) print(f"stage stream nextLong, nextInt, nextInt(1000000): " f"{stage.next_long()}, {stage.next_int()}, {stage.next_int_bound(1_000_000)}") diff --git a/host/src/main/java/com/volmit/host/ModuleWorld.java b/host/src/main/java/com/volmit/host/ModuleWorld.java index fcc82bf51..0d94c9a1e 100644 --- a/host/src/main/java/com/volmit/host/ModuleWorld.java +++ b/host/src/main/java/com/volmit/host/ModuleWorld.java @@ -3,7 +3,9 @@ package com.volmit.host; import com.volmit.ModuleLog; import com.volmit.config.PackSettings; import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; import java.util.Objects; import java.util.Optional; import java.util.function.Function; @@ -34,6 +36,11 @@ final class ModuleWorld implements PackWorld { return world.seed(); } + @Override + public long seed(ResourceId purpose) { + return world.seed(purpose); + } + @Override public PackResources resources() { return world.resources(); @@ -49,6 +56,11 @@ final class ModuleWorld implements PackWorld { return world.minWorldY(); } + @Override + public Optional running() { + return world.running(); + } + @Override public T state(Class type, Function create) { Objects.requireNonNull(create, "create"); diff --git a/host/src/test/java/com/volmit/host/ExtensionsTest.java b/host/src/test/java/com/volmit/host/ExtensionsTest.java index 3e038867a..9c4109402 100644 --- a/host/src/test/java/com/volmit/host/ExtensionsTest.java +++ b/host/src/test/java/com/volmit/host/ExtensionsTest.java @@ -10,12 +10,15 @@ import com.volmit.config.PackSettings; 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.resource.ResourceId; import com.volmit.stage.Pipeline; import com.volmit.stage.Stage; import com.volmit.support.TestContexts; import com.volmit.support.TestSetups; import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; import com.volmit.world.TerrainSampler; import java.util.ArrayList; import java.util.List; @@ -80,9 +83,11 @@ class ExtensionsTest { } public long seed() { return TestContexts.SEED; } + public long seed(ResourceId purpose) { return WorldRandom.purposeSeed(seed(), purpose); } public PackResources resources() { throw new AssertionError("Unused resources"); } public PackSettings settings() { throw new AssertionError("Unused settings"); } public int minWorldY() { return 0; } + public Optional running() { return Optional.empty(); } public T state(Class type, Function create) { return states.state(type, () -> create.apply(this)); } public ModuleLog log() { return ModuleLogs.discarding(); } diff --git a/host/src/test/java/com/volmit/support/TestWorld.java b/host/src/test/java/com/volmit/support/TestWorld.java index af6f63cf5..c64771024 100644 --- a/host/src/test/java/com/volmit/support/TestWorld.java +++ b/host/src/test/java/com/volmit/support/TestWorld.java @@ -6,8 +6,12 @@ import com.volmit.config.PackSettings; import com.volmit.config.SettingsStack; import com.volmit.host.ModuleLogs; import com.volmit.host.WorldStates; +import com.volmit.random.WorldRandom; import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; +import java.util.Optional; import java.util.function.Function; /** A world for tests: the test seed, no resources, no declared settings, and a real state store. */ @@ -29,6 +33,11 @@ public final class TestWorld implements PackWorld, AutoCloseable { return TestContexts.SEED; } + @Override + public long seed(ResourceId purpose) { + return WorldRandom.purposeSeed(seed(), purpose); + } + @Override public PackResources resources() { throw new AssertionError("Unused resources"); @@ -48,6 +57,11 @@ public final class TestWorld implements PackWorld, AutoCloseable { return 0; } + @Override + public Optional running() { + return Optional.empty(); + } + @Override public T state(Class type, Function create) { return states.state(type, () -> create.apply(this));