diff --git a/api/CONTRACTS.md b/api/CONTRACTS.md index 834d1bf3f..d20d1fc34 100644 --- a/api/CONTRACTS.md +++ b/api/CONTRACTS.md @@ -32,7 +32,7 @@ types that carry them and lists what the Iris adapter still owes. | Geometry and mantle registration | `FeatureRegistry`, host `ModuleRegistry`, `FeatureCatalog` | | Block states and palettes | `BlockState`, `BlockRegistry` (`resolve(BlockSpec)`, `find(key)`, `blockEntity`, `hasTrait`, `oreFor`, `rotate(state, BlockTurn)`, `tryRotate(state, BlockTurn)` (empty for a block that cannot face the turn, where `rotate` answers air), `merge`, `withPropertyIfAccepted`, `matches`), `BlockTurn`, `BlockTrait` (with `STORAGE`), `BlockSpec`, `PaletteSpec` and `PaletteSampler` (`BlockRegistry.palette`) | | A pack's objects | `PlaceableObject` (`name`, size, `center`, `geometry`), `PackObjects` (`object`, `sizeOf`, `scaled` with `ScaleMethod`, `smartBored`, `build`), `PackResources.objects()` | -| Placing through the pack's placement graph | `Placements.place(PlacementRun)` (`PackWorld.placements()`), `PlacementRun` (request, name, settings JSON, area, terrain, input, seed), `PlacementTerrain` (`recordPlacement` / `placementAt` with a `PlacementRecord`), `StructureVolumes`, `PlacedMarker`, `PlacementOutcome`; stages read `PlacementContext.placementTerrain()` and `input(type)`; mantle stages get a terrain from `MantleGenerationContext.placementTerrain()`; `RunningWorld.placementAt` reads what a placement recorded; `FeatureRegistry.registerPlacementType` names the type packs write placements as (host `FeatureCatalog.placementType()`, `PackSchema.placementType()`) | +| Placing through the pack's placement graph | `Placements.place(PlacementRun)` (`PackWorld.placements()`), `PlacementRun` (request, name, settings JSON, area, terrain, input, seed), `PlacementTerrain` (`recordPlacement` / `placementAt` with a `PlacementRecord`; `clearBlock` / `clearAttached` take a block, or its block entity, record and markers, back), `StructureVolumes`, `PlacedMarker`, `PlacementOutcome`; stages read `PlacementContext.placementTerrain()` and `input(type)`; mantle stages get a terrain from `MantleGenerationContext.placementTerrain()`; `RunningWorld.placementAt` reads what a placement recorded; `FeatureRegistry.registerPlacementType` names the type packs write placements as (host `FeatureCatalog.placementType()`, `PackSchema.placementType()`) | | Noise from pack-described styles | `NoiseStyle`, `StyledRange`, `PackResources.noise()`, `NoiseFactory`, `NoiseSampler` | | Values in settings | `BlockSpec`, `PaletteSpec`, `NoiseStyle`, `StyledRange`, `Range`, `BlockPosition`, `JigsawOverrides`, `Object` as `ValueKind.AnyKind` | | Decisions over and fit of the platform's own structures | service `VanillaStructures` (`rule`, `starts`, `shift`, `reach`, `beforePieces`, `afterPieces`, `setup`), `VanillaStructureRule`, `VanillaStructureContext`, `VanillaStructureStart`, `VanillaStructureStartContext`, `VanillaStructureSetup`, `PlatformStart`, `StartMemo`, `StartReach`, `StructureFit` (`Start`, `Piece`, `ColumnVisitor`), `DecorationStep`, `TerrainAdaptation`, `PieceKind`, `TemplateCells`, `world.BlockAccess`, host `FeatureCatalog.registrations(service)` | @@ -240,7 +240,8 @@ running Iris is the pack publisher's responsibility. - 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; `highest` 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. + the cave floor markers of a chunk, in heights above the bottom; `carvedAt` is the void the cave carver planned at a + block, empty where none was or when the host cannot read it; `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/api/api/src/main/java/com/volmit/placement/PlacementTerrain.java b/api/api/src/main/java/com/volmit/placement/PlacementTerrain.java index 826886ca9..7f7dd89c7 100644 --- a/api/api/src/main/java/com/volmit/placement/PlacementTerrain.java +++ b/api/api/src/main/java/com/volmit/placement/PlacementTerrain.java @@ -48,6 +48,26 @@ public interface PlacementTerrain { */ void recordPlacement(int x, int y, int z, PlacementRecord placement); + /** + * Takes back the block written at the position, so the terrain shows through there. The block entity, placement + * record and markers kept beside it stay ({@link #clearAttached}). + * + * @throws UnsupportedOperationException when this terrain cannot take blocks back + */ + default void clearBlock(int x, int y, int z) { + throw new UnsupportedOperationException("This terrain cannot take blocks back"); + } + + /** + * Takes back the block entity, placement record and markers the host kept beside the block, whether or not a block + * is still written there. + * + * @throws UnsupportedOperationException when this terrain cannot take them back + */ + default void clearAttached(int x, int y, int z) { + throw new UnsupportedOperationException("This terrain cannot take what is kept beside a block back"); + } + /** The placement recorded at the block ({@link #recordPlacement}); empty when none is. */ Optional placementAt(int x, int y, int z); diff --git a/api/api/src/main/java/com/volmit/vanilla/VanillaStructureContext.java b/api/api/src/main/java/com/volmit/vanilla/VanillaStructureContext.java index ecde18518..391db9cbe 100644 --- a/api/api/src/main/java/com/volmit/vanilla/VanillaStructureContext.java +++ b/api/api/src/main/java/com/volmit/vanilla/VanillaStructureContext.java @@ -2,6 +2,9 @@ package com.volmit.vanilla; import com.volmit.config.PackSettings; import com.volmit.resource.PackResources; +import com.volmit.world.PackWorld; + +import java.util.Optional; /** The world a {@link com.volmit.service.VanillaStructures} provider decides for. Valid only while the provider runs. */ public interface VanillaStructureContext { @@ -10,4 +13,9 @@ public interface VanillaStructureContext { /** The module settings the world's dimension declares: its own, and every region and biome it can reach. */ PackSettings settings(); + + /** The world the provider decides for; empty when it decides before any world exists, such as for the setup of a dimension. */ + default Optional world() { + return Optional.empty(); + } } diff --git a/api/api/src/main/java/com/volmit/world/RunningWorld.java b/api/api/src/main/java/com/volmit/world/RunningWorld.java index 720f9ef35..d5a094f9e 100644 --- a/api/api/src/main/java/com/volmit/world/RunningWorld.java +++ b/api/api/src/main/java/com/volmit/world/RunningWorld.java @@ -3,6 +3,7 @@ package com.volmit.world; import com.volmit.config.FeatureSettings; import com.volmit.data.SavedKey; import com.volmit.geometry.BlockPosition; +import com.volmit.mantle.CarvedVoid; import com.volmit.placement.PlacementRecord; import com.volmit.resource.ResourceId; import java.util.List; @@ -43,6 +44,15 @@ public interface RunningWorld { */ Optional placementAt(int worldX, int y, int worldZ); + /** + * The void the cave carver planned at the block, as the world holds it now; empty where none was, or when the block's + * chunk keeps no generation data any more, and on a platform that cannot read it. Y is the height above the + * dimension's bottom. + */ + default Optional carvedAt(int worldX, int y, int worldZ) { + return Optional.empty(); + } + /** * 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 diff --git a/api/host/src/main/java/com/volmit/host/ModuleWorld.java b/api/host/src/main/java/com/volmit/host/ModuleWorld.java index 30ee2db0f..ea13d72de 100644 --- a/api/host/src/main/java/com/volmit/host/ModuleWorld.java +++ b/api/host/src/main/java/com/volmit/host/ModuleWorld.java @@ -4,6 +4,7 @@ import com.volmit.ModuleLog; import com.volmit.config.PackSettings; import com.volmit.placement.Placements; import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; import com.volmit.world.PackWorld; import com.volmit.world.RunningWorld; import java.util.List; @@ -37,6 +38,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(); diff --git a/api/host/src/test/java/com/volmit/host/ExtensionsTest.java b/api/host/src/test/java/com/volmit/host/ExtensionsTest.java index 29b76af9c..674fdeafa 100644 --- a/api/host/src/test/java/com/volmit/host/ExtensionsTest.java +++ b/api/host/src/test/java/com/volmit/host/ExtensionsTest.java @@ -12,6 +12,7 @@ import com.volmit.hunk.Hunk; import com.volmit.mantle.Mantle; import com.volmit.placement.Placements; 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; @@ -73,6 +74,18 @@ class ExtensionsTest { assertEquals(Optional.of(new WorldOffer("iris")), view.extension(WorldOffer.class)); } + @Test + void aModulesViewOfAWorldAnswersTheSeedPurposesTheHostAnswers() { + var world = new OfferingWorld(new WorldOffer("iris")); + PackWorld view = ModuleWorld.of(world, ModuleLogs.discarding()); + + assertEquals(HOST_SEED, view.seed(HOST_SEED_PURPOSE), "the host decides the seed of a purpose it knows"); + assertEquals(world.seed(ResourceId.parse("test:other")), view.seed(ResourceId.parse("test:other"))); + } + + private static final ResourceId HOST_SEED_PURPOSE = ResourceId.parse("test:host-seed"); + private static final long HOST_SEED = 31337L; + private static final class OfferingWorld implements PackWorld { private final WorldStates states = new WorldStates(); private final WorldOffer offer; @@ -82,6 +95,7 @@ class ExtensionsTest { } public long seed() { return TestContexts.SEED; } + @Override public long seed(ResourceId purpose) { return purpose.equals(HOST_SEED_PURPOSE) ? HOST_SEED : PackWorld.super.seed(purpose); } public PackResources resources() { throw new AssertionError("Unused resources"); } public PackSettings settings() { throw new AssertionError("Unused settings"); } public int minWorldY() { return 0; } diff --git a/core/src/main/java/art/arcane/iris/core/modules/CarvedVoids.java b/core/src/main/java/art/arcane/iris/core/modules/CarvedVoids.java index b6ba9e0de..95f4fc4da 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/CarvedVoids.java +++ b/core/src/main/java/art/arcane/iris/core/modules/CarvedVoids.java @@ -175,6 +175,10 @@ final class CarvedVoids implements MantleLayer { } private CarvedVoid toApi(MatterCavern cavern) { + return toApi(cavern, ids); + } + + static CarvedVoid toApi(MatterCavern cavern, PackResourceIds ids) { CarvedVoid plain = switch (cavern.getLiquid()) { case LIQUID_FLUID -> CarvedVoid.FLUID; case LIQUID_LAVA -> CarvedVoid.LAVA; diff --git a/core/src/main/java/art/arcane/iris/core/modules/FitlessWorld.java b/core/src/main/java/art/arcane/iris/core/modules/FitlessWorld.java new file mode 100644 index 000000000..944f55b4f --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/FitlessWorld.java @@ -0,0 +1,122 @@ +package art.arcane.iris.core.modules; + +import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.config.PackSettings; +import com.volmit.host.ModuleLogs; +import com.volmit.item.ItemRegistry; +import com.volmit.noise.NoiseFactory; +import com.volmit.object.PackObjects; +import com.volmit.placement.Placements; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.resource.ResourceKind; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Function; + +/** + * The world a fit has outside any world: a start fitted with its memo needs nothing of a world but the noise its + * terrain carving draws on, which comes from plain styles. Everything else a fit could ask of a world fails, saying why. + */ +final class FitlessWorld implements PackWorld, PackResources { + private static final String OUTSIDE_A_WORLD = "The built-in modules fit outside a world here: a start needs its memo" + + " and a fit without palettes"; + private static final ResourceId PACK = ResourceId.parse("iris:fitless"); + + private final UUID snapshot = UUID.randomUUID(); + private final NoiseFactory noise = IrisNoiseFactory.standalone(); + + @Override + public long seed() { + throw outsideAWorld(); + } + + @Override + public PackResources resources() { + return this; + } + + @Override + public PackSettings settings() { + throw outsideAWorld(); + } + + @Override + public int minWorldY() { + throw outsideAWorld(); + } + + @Override + public Optional running() { + return Optional.empty(); + } + + @Override + public T state(Class type, Function create) { + throw outsideAWorld(); + } + + @Override + public Placements placements() { + throw outsideAWorld(); + } + + @Override + public ModuleLog log() { + return ModuleLogs.discarding(); + } + + @Override + public List services(Class service) { + throw outsideAWorld(); + } + + @Override + public ResourceId packId() { + return PACK; + } + + @Override + public UUID snapshotId() { + return snapshot; + } + + @Override + public BlockRegistry blocks() { + throw outsideAWorld(); + } + + @Override + public ItemRegistry items() { + throw outsideAWorld(); + } + + @Override + public NoiseFactory noise() { + return noise; + } + + @Override + public PackObjects objects() { + throw outsideAWorld(); + } + + @Override + public Optional find(ResourceKind kind, ResourceId id) { + throw outsideAWorld(); + } + + @Override + public List ids(ResourceKind kind) { + throw outsideAWorld(); + } + + private static IllegalStateException outsideAWorld() { + return new IllegalStateException(OUTSIDE_A_WORLD); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisNoiseFactory.java b/core/src/main/java/art/arcane/iris/core/modules/IrisNoiseFactory.java index 1c7c480df..345fc1905 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisNoiseFactory.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisNoiseFactory.java @@ -49,6 +49,11 @@ final class IrisNoiseFactory implements NoiseFactory { this.resources = resources; } + /** Noise with no pack behind it: the plain styles, but no expressions and no image maps. */ + static IrisNoiseFactory standalone() { + return new IrisNoiseFactory(null, null); + } + @Override public NoiseSampler sampler(NoiseStyle style, long seed) { IrisGeneratorStyle iris = styles.computeIfAbsent(style, unbuilt -> IrisValues.generatorStyle(unbuilt, resources)); diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java b/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java index 47f01651c..12f925fcd 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisPackWorld.java @@ -19,11 +19,13 @@ package art.arcane.iris.core.modules; import art.arcane.iris.builtin.structure.StructureHost; +import art.arcane.iris.builtin.structure.StructureSeeds; import art.arcane.iris.engine.framework.Engine; import com.volmit.ModuleLog; import com.volmit.config.PackSettings; import com.volmit.host.WorldStates; import com.volmit.placement.Placements; +import com.volmit.resource.ResourceId; import com.volmit.world.PackWorld; import com.volmit.world.RunningWorld; import java.util.List; @@ -70,6 +72,14 @@ public final class IrisPackWorld implements PackWorld { return engine.getSeedManager().getSeed(); } + @Override + public long seed(ResourceId purpose) { + if (StructureSeeds.PLACEMENT.equals(purpose)) { + return engine.getSeedManager().getMantle(); + } + return PackWorld.super.seed(purpose); + } + @Override public IrisPackResources resources() { @@ -78,7 +88,7 @@ public final class IrisPackWorld implements PackWorld { @Override public int minWorldY() { - return engine.getWorld().minHeight(); + return engine.getMinHeight(); } @Override diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisRunningWorld.java b/core/src/main/java/art/arcane/iris/core/modules/IrisRunningWorld.java index 23a06abee..f5c77730e 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisRunningWorld.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisRunningWorld.java @@ -24,11 +24,13 @@ import art.arcane.iris.spi.PlatformWorld; import art.arcane.iris.util.common.scheduling.J; import art.arcane.volmlib.util.mantle.runtime.MantleChunk; import art.arcane.volmlib.util.matter.Matter; +import art.arcane.volmlib.util.matter.MatterCavern; import art.arcane.volmlib.util.matter.slices.MarkerMatter; import com.volmit.ModuleLog; import com.volmit.config.FeatureSettings; import com.volmit.data.SavedKey; import com.volmit.geometry.BlockPosition; +import com.volmit.mantle.CarvedVoid; import com.volmit.placement.PlacementRecord; import com.volmit.resource.ResourceId; import com.volmit.world.RunningWorld; @@ -139,6 +141,12 @@ final class IrisRunningWorld implements RunningWorld { } } + @Override + public Optional carvedAt(int worldX, int y, int worldZ) { + MatterCavern cavern = engine.getMantle().getMantle().get(worldX, y, worldZ, MatterCavern.class); + return Optional.ofNullable(cavern).map(carved -> CarvedVoids.toApi(carved, packIds())); + } + @Override public boolean debug() { return engine.isStudio(); diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisStructureHost.java b/core/src/main/java/art/arcane/iris/core/modules/IrisStructureHost.java index 89de8d425..7ca07978a 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisStructureHost.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisStructureHost.java @@ -24,8 +24,8 @@ import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.engine.mantle.components.StructurePlacing; import art.arcane.iris.engine.object.structure.IrisStructure; import com.volmit.ModuleLog; -import com.volmit.generation.InvocationContext; import com.volmit.resource.ResourceId; +import com.volmit.stage.MantleStageContext; import java.util.List; import java.util.Optional; @@ -41,9 +41,8 @@ final class IrisStructureHost implements StructureHost { } @Override - public void placeChunk(InvocationContext context) { - IrisMantleChunk chunk = context.extension(IrisMantleChunk.class).orElseThrow(); - placing().place(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); + public void placeChunk(MantleStageContext context) { + placing().place(context); } @Override @@ -65,6 +64,6 @@ final class IrisStructureHost implements StructureHost { } private StructurePlacing placing() { - return engine.getGeneration().state(StructurePlacing.class, generating -> new StructurePlacing(generating, log)); + return engine.getGeneration().world().state(StructurePlacing.class, generating -> new StructurePlacing(generating, log)); } } diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleStructureFitting.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleStructureFitting.java index 68184f221..f0495fd63 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleStructureFitting.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleStructureFitting.java @@ -96,10 +96,8 @@ public final class ModuleStructureFitting implements NativeStructureFitting { public static NativeStructureFitting builtInModules() { ModuleRegistry registry = new ModuleRegistry(); IrisModuleHost.builtInModules().forEach(module -> ModuleSetups.run(DiscoveredModule.builtIn(module), new StageGraphBuilder(), registry)); - return new ModuleStructureFitting(registry.freeze().registrations(VanillaStructures.class), () -> { - throw new IllegalStateException("The built-in modules fit outside a world here: a start needs its memo" - + " and a fit without palettes"); - }); + FitlessWorld fitless = new FitlessWorld(); + return new ModuleStructureFitting(registry.freeze().registrations(VanillaStructures.class), () -> fitless); } @Override diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleVanillaStructures.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleVanillaStructures.java index 85bd455d9..c0efc8183 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleVanillaStructures.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleVanillaStructures.java @@ -54,6 +54,7 @@ import java.util.OptionalInt; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; +import java.util.function.Supplier; /** * What the pack's modules want for the platform's own structures, asked through their {@link VanillaStructures} @@ -77,7 +78,8 @@ public final class ModuleVanillaStructures { private ModuleVanillaStructures(Engine engine, PackResources snapshot) { this.snapshot = snapshot; this.providers = providersOf(engine.getData()); - this.world = new World(snapshot, new IrisPackSettings(engine)); + this.world = new World(snapshot, new IrisPackSettings(engine), + () -> Optional.of(engine.getGeneration().world())); } /** The combined rule of the pack's modules for the platform structure {@code structureKey} in {@code engine}'s world. */ @@ -139,7 +141,7 @@ public final class ModuleVanillaStructures { /** The combined setup of the pack's modules for {@code dimension} of the pack {@code data} serves, before any world exists. */ public static VanillaStructureSetup setupFor(IrisData data, IrisDimension dimension) { - VanillaStructureContext context = new World(data.getPackResources(), new DimensionSettings(data, dimension)); + VanillaStructureContext context = new World(data.getPackResources(), new DimensionSettings(data, dimension), Optional::empty); VanillaStructureSetup combined = VanillaStructureSetup.UNCHANGED; for (ServiceRegistration registration : providersOf(data)) { combined = combined.and(ask(registration, "setting up the vanilla structures of dimension " + dimension.getLoadKey(), @@ -241,7 +243,12 @@ public final class ModuleVanillaStructures { } /** The world the providers decide for: the engine's pack snapshot and the settings its dimension reaches. */ - private record World(PackResources resources, PackSettings settings) implements VanillaStructureContext { + private record World(PackResources resources, PackSettings settings, Supplier> worldSource) + implements VanillaStructureContext { + @Override + public Optional world() { + return worldSource.get(); + } } private record StartContext(PackWorld world, TerrainSampler terrain) implements VanillaStructureStartContext { diff --git a/core/src/main/java/art/arcane/iris/core/modules/PlacerTerrain.java b/core/src/main/java/art/arcane/iris/core/modules/PlacerTerrain.java index 428601a1b..af9e0dddc 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/PlacerTerrain.java +++ b/core/src/main/java/art/arcane/iris/core/modules/PlacerTerrain.java @@ -120,6 +120,19 @@ final class PlacerTerrain implements PlacementTerrain { } } + @Override + public void clearBlock(int x, int y, int z) { + placer.clearBlock(x, y, z); + if (written != null) { + written.remove(new BlockPosition(x, y, z)); + } + } + + @Override + public void clearAttached(int x, int y, int z) { + placer.clearAttached(x, y, z); + } + @Override public boolean isCarved(int x, int y, int z) { return placer.isCarved(x, y, z); diff --git a/core/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java b/core/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java index c988a7381..49e9c8262 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java @@ -21,26 +21,28 @@ package art.arcane.iris.engine.framework; import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.engine.framework.structure.ColumnHeights; import art.arcane.iris.engine.framework.structure.NativeStartPlanner; +import art.arcane.iris.engine.framework.structure.StructureWorld; import art.arcane.iris.engine.framework.structure.assembly.AssembledPiece; import art.arcane.iris.engine.framework.structure.assembly.Assembly; import art.arcane.iris.engine.framework.structure.assembly.StructureAssembly; import art.arcane.iris.engine.framework.structure.assembly.StructureStamp; import art.arcane.iris.engine.framework.structure.assembly.Viability; -import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.builtin.structure.NativeStructureSource; -import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.builtin.structure.StructureAnchorMode; import art.arcane.iris.builtin.structure.StructureCarveShape; import art.arcane.iris.builtin.structure.StructurePlacement; +import art.arcane.iris.builtin.structure.StructurePlacementSettings; import art.arcane.iris.builtin.structure.StructureTerrain; import art.arcane.iris.builtin.structure.StructureTerrainMode; import art.arcane.iris.builtin.structure.NativeStructureSuppression; import art.arcane.iris.builtin.structure.StructureDistribution; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; +import com.volmit.config.Level; import com.volmit.geometry.BlockPosition; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; import java.util.ArrayList; import java.util.Collections; @@ -86,139 +88,139 @@ public final class IrisStructureLocator { } /** Structure keys referenced by any Iris assembly or native jigsaw placement. */ - public static Set placedKeys(Engine engine) { - if (engine == null) { + public static Set placedKeys(PackWorld world) { + if (world == null) { return Collections.emptySet(); } - return index(engine).loadKeys; + return index(world).loadKeys; } /** * Every key under which a structure the engine's placements place can be found: the placed keys and the platform * structures Iris structures stand in for ({@code vanillaSource}), the latter in lower case. */ - public static Set placedKeysAndAliases(Engine engine) { - if (engine == null) { + public static Set placedKeysAndAliases(PackWorld world) { + if (world == null) { return Collections.emptySet(); } - PlacementIndex placementIndex = index(engine); + PlacementIndex placementIndex = index(world); Set keys = new LinkedHashSet<>(placementIndex.loadKeys); keys.addAll(placementIndex.vanillaAliases); return Collections.unmodifiableSet(keys); } /** The platform structures the engine's placements start natively ({@code nativeStructures}), in lower case. */ - public static Set nativeKeys(Engine engine) { - if (engine == null) { + public static Set nativeKeys(PackWorld world) { + if (world == null) { return Collections.emptySet(); } - return index(engine).nativeKeys; + return index(world).nativeKeys; } - public static boolean isPlaced(Engine engine, String key) { - if (engine == null || key == null || key.isEmpty()) { + public static boolean isPlaced(PackWorld world, String key) { + if (world == null || key == null || key.isEmpty()) { return false; } - PlacementIndex placementIndex = index(engine); + PlacementIndex placementIndex = index(world); String normalizedKey = normalize(key); return placementIndex.normalizedLoadKeys.contains(normalizedKey) || placementIndex.vanillaAliases.contains(normalizedKey); } - public static boolean hasLocatablePlacement(Engine engine, String key) { - if (engine == null || key == null || key.isBlank()) { + public static boolean hasLocatablePlacement(PackWorld world, String key) { + if (world == null || key == null || key.isBlank()) { return false; } - return locatableIndex(engine).normalizedKeys().contains(normalize(key)); + return locatableIndex(world).normalizedKeys().contains(normalize(key)); } - public static boolean hasLocatableEditablePlacement(Engine engine, String key) { - if (engine == null || key == null || key.isBlank()) { + public static boolean hasLocatableEditablePlacement(PackWorld world, String key) { + if (world == null || key == null || key.isBlank()) { return false; } - return locatableIndex(engine).normalizedEditableKeys().contains(normalize(key)); + return locatableIndex(world).normalizedEditableKeys().contains(normalize(key)); } - public static boolean hasLocatableNativePlacement(Engine engine, String key) { - if (engine == null || key == null || key.isBlank()) { + public static boolean hasLocatableNativePlacement(PackWorld world, String key) { + if (world == null || key == null || key.isBlank()) { return false; } - return locatableIndex(engine).normalizedNativeKeys().contains(normalize(key)); + return locatableIndex(world).normalizedNativeKeys().contains(normalize(key)); } - public static Set locatableKeys(Engine engine) { - return locatableIndex(engine).keys(); + public static Set locatableKeys(PackWorld world) { + return locatableIndex(world).keys(); } - public static Set locatableEditableKeys(Engine engine) { - return locatableIndex(engine).editableKeys(); + public static Set locatableEditableKeys(PackWorld world) { + return locatableIndex(world).editableKeys(); } - public static Set locatableNativeKeys(Engine engine) { - return locatableIndex(engine).nativeKeys(); + public static Set locatableNativeKeys(PackWorld world) { + return locatableIndex(world).nativeKeys(); } - public static boolean hasNativePlacement(Engine engine, String key) { - if (engine == null || key == null || key.isBlank()) { + public static boolean hasNativePlacement(PackWorld world, String key) { + if (world == null || key == null || key.isBlank()) { return false; } - return index(engine).nativeKeys.contains(normalize(key)); + return index(world).nativeKeys.contains(normalize(key)); } - public static boolean hasEditablePlacement(Engine engine, String key) { - if (engine == null || key == null || key.isBlank()) { + public static boolean hasEditablePlacement(PackWorld world, String key) { + if (world == null || key == null || key.isBlank()) { return false; } - for (StructurePlacement placement : index(engine).placements) { - if (placement.hasIrisStructures() && matches(placement, key, engine)) { + for (StructurePlacement placement : index(world).placements) { + if (placement.hasIrisStructures() && matches(placement, key, world)) { return true; } } return false; } - public static boolean suppressesVanilla(Engine engine, String vanillaKey) { - if (engine == null || vanillaKey == null || vanillaKey.isEmpty()) { + public static boolean suppressesVanilla(PackWorld world, String vanillaKey) { + if (world == null || vanillaKey == null || vanillaKey.isEmpty()) { return false; } - return index(engine).suppressedVanillaSources.contains(normalize(vanillaKey)); + return index(world).suppressedVanillaSources.contains(normalize(vanillaKey)); } - public static boolean startsInChunk(Engine engine, String key, int cx, int cz) { - if (!isPlaced(engine, key)) { + public static boolean startsInChunk(PackWorld world, String key, int cx, int cz) { + if (!isPlaced(world, key)) { return false; } - return resolveInChunk(engine, key, cx, cz) != null; + return resolveInChunk(world, key, cx, cz) != null; } - public static LocateResult locate(Engine engine, String key, int fromBlockX, int fromBlockZ, int maxRadiusChunks) { - return locate(engine, key, fromBlockX, fromBlockZ, maxRadiusChunks, (chunkX, chunkZ) -> true); + public static LocateResult locate(PackWorld world, String key, int fromBlockX, int fromBlockZ, int maxRadiusChunks) { + return locate(world, key, fromBlockX, fromBlockZ, maxRadiusChunks, (chunkX, chunkZ) -> true); } - public static LocateResult locate(Engine engine, String key, int fromBlockX, int fromBlockZ, + public static LocateResult locate(PackWorld world, String key, int fromBlockX, int fromBlockZ, int maxRadiusChunks, CandidateFilter candidateFilter) { try { - return locateFiltered(engine, key, fromBlockX, fromBlockZ, maxRadiusChunks, candidateFilter); + return locateFiltered(world, key, fromBlockX, fromBlockZ, maxRadiusChunks, candidateFilter); } catch (CandidateSearchLimitException ignored) { return SEARCH_LIMIT_RESULT; } } public static LocateResult locateInPlacementRings( - Engine engine, String key, int fromBlockX, int fromBlockZ, + PackWorld world, String key, int fromBlockX, int fromBlockZ, int maxSearchRadius, CandidateFilter candidateFilter) { try { return locateInPlacementRingsFiltered( - engine, key, fromBlockX, fromBlockZ, maxSearchRadius, candidateFilter); + world, key, fromBlockX, fromBlockZ, maxSearchRadius, candidateFilter); } catch (CandidateSearchLimitException ignored) { return SEARCH_LIMIT_RESULT; } } private static LocateResult locateInPlacementRingsFiltered( - Engine engine, String key, int fromBlockX, int fromBlockZ, + PackWorld world, String key, int fromBlockX, int fromBlockZ, int maxSearchRadius, CandidateFilter candidateFilter) { - if (!isPlaced(engine, key)) { + if (!isPlaced(world, key)) { return NOT_FOUND_RESULT; } CandidateFilter activeFilter = Objects.requireNonNull( @@ -226,26 +228,21 @@ public final class IrisStructureLocator { int maximumRing = Math.max(0, Math.min(maxSearchRadius, 2048)); int centerChunkX = fromBlockX >> 4; int centerChunkZ = fromBlockZ >> 4; - PlacementCatalog catalog = collectPlacementCatalog(engine, key); + PlacementCatalog catalog = collectPlacementCatalog(world, key); if (catalog.randomSpread().isEmpty() && catalog.concentricRings().isEmpty() && !catalog.hasDensity()) { return NOT_FOUND_RESULT; } - SeedManager seedManager = engine.getSeedManager(); - if (seedManager == null) { - throw new IllegalStateException( - "Iris structure locate requires a bound seed manager for '" + key + "'"); - } - long seed = seedManager.getMantle(); + long seed = StructureWorld.placementSeed(world); CandidateBudget candidateBudget = new CandidateBudget(); LocatedCandidate best = nearestConcentricCandidate( - engine, key, fromBlockX, fromBlockZ, seed, catalog, activeFilter, candidateBudget); + world, key, fromBlockX, fromBlockZ, seed, catalog, activeFilter, candidateBudget); for (int ring = 0; ring <= maximumRing; ring++) { boolean foundInRing = false; for (RandomSpreadParameters parameters : catalog.randomSpread()) { LocatedCandidate candidate = firstRandomSpreadCandidateInRing( - engine, key, fromBlockX, fromBlockZ, + world, key, fromBlockX, fromBlockZ, centerChunkX, centerChunkZ, ring, seed, parameters, activeFilter, candidateBudget); if (candidate == null) { @@ -258,7 +255,7 @@ public final class IrisStructureLocator { } if (catalog.hasDensity()) { LocatedCandidate candidate = firstDensityCandidateInRing( - engine, key, fromBlockX, fromBlockZ, + world, key, fromBlockX, fromBlockZ, centerChunkX, centerChunkZ, ring, activeFilter, candidateBudget); if (candidate != null) { @@ -276,7 +273,7 @@ public final class IrisStructureLocator { } private static LocatedCandidate nearestConcentricCandidate( - Engine engine, String key, int fromBlockX, int fromBlockZ, + PackWorld world, String key, int fromBlockX, int fromBlockZ, long seed, PlacementCatalog catalog, CandidateFilter candidateFilter, CandidateBudget candidateBudget) { LocatedCandidate best = null; @@ -290,7 +287,7 @@ public final class IrisStructureLocator { if (candidate == null || !checkedChunks.add(chunkKey(candidate[0], candidate[1]))) { continue; } - ResolvedStart resolved = resolveInChunk(engine, key, candidate[0], candidate[1]); + ResolvedStart resolved = resolveInChunk(world, key, candidate[0], candidate[1]); if (resolved == null || !candidateFilter.accept(candidate[0], candidate[1])) { continue; } @@ -305,7 +302,7 @@ public final class IrisStructureLocator { } private static LocatedCandidate firstRandomSpreadCandidateInRing( - Engine engine, String key, int fromBlockX, int fromBlockZ, + PackWorld world, String key, int fromBlockX, int fromBlockZ, int centerChunkX, int centerChunkZ, int ring, long seed, RandomSpreadParameters parameters, CandidateFilter candidateFilter, CandidateBudget candidateBudget) { @@ -323,7 +320,7 @@ public final class IrisStructureLocator { int[] candidate = StructurePlacementGrid.randomSpreadCellChunk( centerCellX + offsetX, centerCellZ + offsetZ, spacing, parameters.separation(), parameters.salt(), seed); - ResolvedStart resolved = resolveInChunk(engine, key, candidate[0], candidate[1]); + ResolvedStart resolved = resolveInChunk(world, key, candidate[0], candidate[1]); if (resolved != null && candidateFilter.accept(candidate[0], candidate[1])) { return new LocatedCandidate( resolved, blockDistanceSquared(resolved, fromBlockX, fromBlockZ)); @@ -334,7 +331,7 @@ public final class IrisStructureLocator { } private static LocatedCandidate firstDensityCandidateInRing( - Engine engine, String key, int fromBlockX, int fromBlockZ, + PackWorld world, String key, int fromBlockX, int fromBlockZ, int centerChunkX, int centerChunkZ, int ring, CandidateFilter candidateFilter, CandidateBudget candidateBudget) { for (int offsetX = -ring; offsetX <= ring; offsetX++) { @@ -347,7 +344,7 @@ public final class IrisStructureLocator { int chunkX = centerChunkX + offsetX; int chunkZ = centerChunkZ + offsetZ; candidateBudget.claim(); - ResolvedStart resolved = resolveInChunk(engine, key, chunkX, chunkZ); + ResolvedStart resolved = resolveInChunk(world, key, chunkX, chunkZ); if (resolved != null && candidateFilter.accept(chunkX, chunkZ)) { return new LocatedCandidate( resolved, blockDistanceSquared(resolved, fromBlockX, fromBlockZ)); @@ -357,9 +354,9 @@ public final class IrisStructureLocator { return null; } - private static LocateResult locateFiltered(Engine engine, String key, int fromBlockX, int fromBlockZ, + private static LocateResult locateFiltered(PackWorld world, String key, int fromBlockX, int fromBlockZ, int maxRadiusChunks, CandidateFilter candidateFilter) { - if (!isPlaced(engine, key)) { + if (!isPlaced(world, key)) { return NOT_FOUND_RESULT; } CandidateFilter activeFilter = Objects.requireNonNull(candidateFilter, "Structure locate filter must not be null"); @@ -367,15 +364,11 @@ public final class IrisStructureLocator { int pcx = fromBlockX >> 4; int pcz = fromBlockZ >> 4; LocatedCandidate best = null; - PlacementCatalog catalog = collectPlacementCatalog(engine, key); + PlacementCatalog catalog = collectPlacementCatalog(world, key); if (catalog.randomSpread().isEmpty() && catalog.concentricRings().isEmpty() && !catalog.hasDensity()) { return NOT_FOUND_RESULT; } - SeedManager seedManager = engine.getSeedManager(); - if (seedManager == null) { - throw new IllegalStateException("Iris structure locate requires a bound seed manager for '" + key + "'"); - } - long seed = seedManager.getMantle(); + long seed = StructureWorld.placementSeed(world); CandidateBudget candidateBudget = new CandidateBudget(); for (RandomSpreadParameters parameters : catalog.randomSpread) { @@ -406,7 +399,7 @@ public final class IrisStructureLocator { cx, cz, fromBlockX, fromBlockZ) >= best.distanceSquared()) { continue; } - ResolvedStart resolved = resolveInChunk(engine, key, cx, cz); + ResolvedStart resolved = resolveInChunk(world, key, cx, cz); if (resolved != null && activeFilter.accept(cx, cz)) { long distanceSquared = blockDistanceSquared( resolved, fromBlockX, fromBlockZ); @@ -433,7 +426,7 @@ public final class IrisStructureLocator { candidate[0], candidate[1], fromBlockX, fromBlockZ) >= best.distanceSquared()) { continue; } - ResolvedStart resolved = resolveInChunk(engine, key, candidate[0], candidate[1]); + ResolvedStart resolved = resolveInChunk(world, key, candidate[0], candidate[1]); if (resolved != null && activeFilter.accept(candidate[0], candidate[1])) { long distanceSquared = blockDistanceSquared( resolved, fromBlockX, fromBlockZ); @@ -462,7 +455,7 @@ public final class IrisStructureLocator { continue; } candidateBudget.claim(); - ResolvedStart resolved = resolveInChunk(engine, key, cx, cz); + ResolvedStart resolved = resolveInChunk(world, key, cx, cz); if (resolved != null && activeFilter.accept(cx, cz)) { long distanceSquared = blockDistanceSquared( resolved, fromBlockX, fromBlockZ); @@ -487,15 +480,15 @@ public final class IrisStructureLocator { && Math.abs((long) chunkZ - centerChunkZ) <= radius; } - public static ResolvedPlacement resolvePlacement(Engine engine, StructurePlacement placement, int cx, int cz) { - if (engine == null || engine.getData() == null || engine.getSeedManager() == null) { - throw new IllegalStateException("Iris structure placement requires a fully bound engine"); + public static ResolvedPlacement resolvePlacement(PackWorld world, StructurePlacement placement, int cx, int cz) { + if (world == null) { + throw new IllegalStateException("Iris structure placement requires a world"); } NativeStartPlanner.validateBackend(placement); if (!placement.hasIrisStructures()) { throw new IllegalStateException("Iris structure placement is missing its structure list"); } - long seed = engine.getSeedManager().getMantle(); + long seed = StructureWorld.placementSeed(world); if (!StructurePlacementGrid.startsInChunk(placement, cx, cz, seed)) { return null; } @@ -503,7 +496,7 @@ public final class IrisStructureLocator { RNG rng = StructurePlacementGrid.placementRng(placement, cx, cz, seed); int originX = (cx << 4) + rng.nextInt(16); int originZ = (cz << 4) + rng.nextInt(16); - PlacementAnchor anchor = resolveAnchor(engine, placement, cx, cz, originX, originZ, rng); + PlacementAnchor anchor = resolveAnchor(world, placement, cx, cz, originX, originZ, rng); if (anchor == null) { return null; } @@ -515,9 +508,9 @@ public final class IrisStructureLocator { if (selectedKey == null || selectedKey.isBlank()) { throw new IllegalStateException("Iris structure placement selected a blank structure key"); } - PackResources pack = engine.getData().getPackResources(); + PackResources pack = world.resources(); ResourceId structureId = pack.idOf(selectedKey); - StructureAssembly provider = providerOf(engine, structureId); + StructureAssembly provider = providerOf(world, structureId); if (provider == null) { throw new IllegalStateException("Iris structure placement references missing structure '" + selectedKey + "'"); @@ -543,8 +536,8 @@ public final class IrisStructureLocator { } boolean exactY = hasExactY(placement, stamp, pieces); - int worldMin = engine.getMinHeight() + 1; - int worldMax = engine.getMinHeight() + engine.getHeight() - 1; + int worldMin = world.minWorldY() + 1; + int worldMax = world.minWorldY() + StructureWorld.height(world) - 1; if (exactY) { Integer verticalShift = resolveVerticalShift(pieces, placement, baseY, worldMin, worldMax); if (!requirePlacementOutput(placement, selectedKey, cx, cz, verticalShift != null, @@ -558,7 +551,7 @@ public final class IrisStructureLocator { } if (placement.isAnchoredUnderground() && !placement.resolvedAnchor().isCave()) { Integer burialShift = resolveUndergroundBurialShift( - engine, pieces, placement, baseY, worldMin, worldMax); + world, pieces, placement, baseY, worldMin, worldMax); if (!requirePlacementOutput(placement, selectedKey, cx, cz, burialShift != null, "assembled pieces and carving envelope cannot remain fully buried beneath terrain")) { return null; @@ -584,9 +577,9 @@ public final class IrisStructureLocator { * The first provider of {@link StructureAssembly} among the modules of the engine's pack that knows {@code structure}; * null when none does. */ - public static StructureAssembly providerOf(Engine engine, ResourceId structure) { - PackResources pack = engine.getData().getPackResources(); - for (StructureAssembly provider : engine.getGeneration().world().services(StructureAssembly.class)) { + public static StructureAssembly providerOf(PackWorld world, ResourceId structure) { + PackResources pack = world.resources(); + for (StructureAssembly provider : world.services(StructureAssembly.class)) { if (provider.knows(pack, structure)) { return provider; } @@ -595,10 +588,10 @@ public final class IrisStructureLocator { } /** How the pieces of the pack structure {@code key} are stamped; null when no module knows the structure. */ - public static StructureStamp stampOf(Engine engine, String key) { - PackResources pack = engine.getData().getPackResources(); + public static StructureStamp stampOf(PackWorld world, String key) { + PackResources pack = world.resources(); ResourceId structure = pack.idOf(key); - StructureAssembly provider = providerOf(engine, structure); + StructureAssembly provider = providerOf(world, structure); return provider == null ? null : provider.stamp(pack, structure).orElse(null); } @@ -631,24 +624,24 @@ public final class IrisStructureLocator { && fitsHorizontalBounds(bounds, originX, originZ, structureRadius); } - private static ResolvedStart resolveInChunk(Engine engine, String key, int cx, int cz) { + private static ResolvedStart resolveInChunk(PackWorld world, String key, int cx, int cz) { String normalizedKey = normalize(key); - if (hasNativePlacement(engine, key)) { - for (NativeStartPlanner.Plan plan : NativeStartPlanner.plansAt(engine, cx, cz)) { + if (hasNativePlacement(world, key)) { + for (NativeStartPlanner.Plan plan : NativeStartPlanner.plansAt(world, cx, cz)) { if (normalize(plan.source().structure()).equals(normalizedKey)) { return new ResolvedStart(cx << 4, plan.baseY(), cz << 4); } } } - KList placements = StructurePlacementScope.placementsAt(engine, cx, cz); + List placements = StructurePlacementScope.placementsAt(world, cx, cz); for (StructurePlacement placement : placements) { - if (!matches(placement, key, engine)) { + if (!matches(placement, key, world)) { continue; } if (placement.hasNativeStructures()) { continue; } - ResolvedPlacement resolved = resolvePlacement(engine, placement, cx, cz); + ResolvedPlacement resolved = resolvePlacement(world, placement, cx, cz); if (resolved != null && matchesResolved(resolved, key)) { return new ResolvedStart( resolved.originX(), resolved.baseY(), resolved.originZ()); @@ -658,7 +651,7 @@ public final class IrisStructureLocator { } private static PlacementAnchor resolveAnchor( - Engine engine, + PackWorld world, StructurePlacement placement, int chunkX, int chunkZ, @@ -668,25 +661,25 @@ public final class IrisStructureLocator { ) { if (placement.resolvedAnchor().isCave()) { StructureCaveAnchorResolver.Anchor caveAnchor = StructureCaveAnchorResolver.resolve( - engine, placement, chunkX, chunkZ, rng.nextParallelRNG(CAVE_ANCHOR_DOMAIN)); + world, placement, chunkX, chunkZ, rng.nextParallelRNG(CAVE_ANCHOR_DOMAIN)); return caveAnchor == null ? null : new PlacementAnchor(caveAnchor.x(), caveAnchor.y(), caveAnchor.z()); } - Integer baseY = resolveBaseY(engine, placement, originX, originZ, rng); + Integer baseY = resolveBaseY(world, placement, originX, originZ, rng); return baseY == null ? null : new PlacementAnchor(originX, baseY, originZ); } - private static Integer resolveBaseY(Engine engine, StructurePlacement placement, int originX, int originZ, RNG rng) { - int worldMin = engine.getMinHeight() + 1; - int worldMax = engine.getMinHeight() + engine.getHeight() - 1; + private static Integer resolveBaseY(PackWorld world, StructurePlacement placement, int originX, int originZ, RNG rng) { + int worldMin = world.minWorldY() + 1; + int worldMax = world.minWorldY() + StructureWorld.height(world) - 1; if (worldMin > worldMax) { return null; } if (!placement.underwater() - && NativeStartPlanner.isSubmerged(engine, originX, originZ)) { + && NativeStartPlanner.isSubmerged(world, originX, originZ)) { return null; } if (placement.resolvedAnchor() == StructureAnchorMode.SURFACE) { - int surfaceY = engine.getHeight(originX, originZ, true) + engine.getMinHeight(); + int surfaceY = StructureWorld.highest(world, originX, originZ); return surfaceY < placement.minHeight() || surfaceY > placement.maxHeight() ? null : surfaceY; } int bandMin = Math.max(worldMin, Math.min(placement.minHeight(), placement.maxHeight())); @@ -722,11 +715,11 @@ public final class IrisStructureLocator { return 0; } - static Integer resolveUndergroundBurialShift(Engine engine, KList pieces, + static Integer resolveUndergroundBurialShift(PackWorld world, KList pieces, StructurePlacement placement, int baseY, int worldMin, int worldMax) { int[] bounds = computeBounds(pieces); - if (engine == null || bounds == null || placement == null || !placement.isAnchoredUnderground() + if (world == null || bounds == null || placement == null || !placement.isAnchoredUnderground() || placement.resolvedAnchor().isCave()) { return null; } @@ -753,7 +746,7 @@ public final class IrisStructureLocator { ColumnHeights surfaceHeights = new ColumnHeights(Integer.MIN_VALUE); if (bore || forceCarve && carveShape == StructureCarveShape.BOX) { maximumShift = resolveBurialEnvelopeShift( - engine, + world, bounds[0] - sideExtension, bounds[3] + sideExtension, bounds[2] - sideExtension, @@ -768,7 +761,7 @@ public final class IrisStructureLocator { } else { for (AssembledPiece piece : pieces) { maximumShift = resolveBurialEnvelopeShift( - engine, + world, piece.minX() - sideExtension, piece.maxX() + sideExtension, piece.minZ() - sideExtension, @@ -785,7 +778,7 @@ public final class IrisStructureLocator { return minimumShift > maximumShift ? null : maximumShift; } - private static int resolveBurialEnvelopeShift(Engine engine, int minX, int maxX, int minZ, int maxZ, + private static int resolveBurialEnvelopeShift(PackWorld world, int minX, int maxX, int minZ, int maxZ, int envelopeTopY, int maximumShift, ColumnHeights surfaceHeights) { for (int x = minX; x <= maxX; x++) { @@ -796,7 +789,7 @@ public final class IrisStructureLocator { if (surfaceHeights.size() >= MAX_BURIAL_COLUMNS) { return Integer.MIN_VALUE; } - surfaceY = engine.getHeight(x, z, true) + engine.getMinHeight(); + surfaceY = StructureWorld.highest(world, x, z); surfaceHeights.put(columnKey, surfaceY); } int allowedTopY = surfaceY - UNDERGROUND_SURFACE_CLEARANCE; @@ -908,13 +901,13 @@ public final class IrisStructureLocator { return minimum + rng.nextInt((maximum - minimum) + 1); } - private static PlacementCatalog collectPlacementCatalog(Engine engine, String key) { + private static PlacementCatalog collectPlacementCatalog(PackWorld world, String key) { Set randomSpread = new LinkedHashSet<>(); List concentricRings = new ArrayList<>(); boolean hasDensity = false; - for (StructurePlacement placement : index(engine).placements) { - if (!isSearchablePlacement(engine, placement) - || !matches(placement, key, engine)) { + for (StructurePlacement placement : index(world).placements) { + if (!isSearchablePlacement(world, placement) + || !matches(placement, key, world)) { continue; } if (placement.distribution() == StructureDistribution.RANDOM_SPREAD) { @@ -930,22 +923,22 @@ public final class IrisStructureLocator { return new PlacementCatalog(List.copyOf(randomSpread), List.copyOf(concentricRings), hasDensity); } - static boolean isSearchableDensityPlacement(Engine engine, StructurePlacement placement) { + static boolean isSearchableDensityPlacement(PackWorld world, StructurePlacement placement) { return placement != null && placement.distribution() == StructureDistribution.DENSITY - && isSearchablePlacement(engine, placement); + && isSearchablePlacement(world, placement); } - static boolean isSearchablePlacement(Engine engine, StructurePlacement placement) { - if (engine == null || placement == null || engine.getHeight() <= 0) { + static boolean isSearchablePlacement(PackWorld world, StructurePlacement placement) { + if (world == null || placement == null || StructureWorld.height(world) <= 0) { return false; } if (placement.distribution() == StructureDistribution.DENSITY && !(placement.density() > 0.0)) { return false; } - long worldMin = (long) engine.getMinHeight() + (placement.isAnchoredUnderground() ? 1L : 0L); - long worldMax = (long) engine.getMinHeight() + engine.getHeight() + long worldMin = (long) world.minWorldY() + (placement.isAnchoredUnderground() ? 1L : 0L); + long worldMax = (long) world.minWorldY() + StructureWorld.height(world) - (placement.resolvedAnchor().isCave() ? 2L : 1L); if (worldMin > worldMax) { return false; @@ -1033,8 +1026,8 @@ public final class IrisStructureLocator { private record PlacementAnchor(int x, int y, int z) { } - private static boolean matches(StructurePlacement placement, String key, Engine engine) { - if (placement == null || key == null || engine == null || engine.getData() == null) { + private static boolean matches(StructurePlacement placement, String key, PackWorld world) { + if (placement == null || key == null || world == null) { return false; } String normalizedKey = normalize(key); @@ -1047,7 +1040,7 @@ public final class IrisStructureLocator { if (structureKey == null || structureKey.isBlank()) { continue; } - StructureStamp stamp = stampOf(engine, structureKey); + StructureStamp stamp = stampOf(world, structureKey); if (stamp == null) { continue; } @@ -1069,32 +1062,29 @@ public final class IrisStructureLocator { return key == null ? "" : key.toLowerCase(Locale.ROOT); } - private static PlacementIndex index(Engine engine) { - if (engine == null) { + private static PlacementIndex index(PackWorld world) { + if (world == null) { return EMPTY_INDEX; } - if (engine.getData() == null || engine.getDimension() == null) { - throw new IllegalStateException("Iris structure index requires a fully bound engine and dimension"); - } - return engine.getGeneration().state(PlacementIndex.class, IrisStructureLocator::build); + return world.state(PlacementIndex.class, IrisStructureLocator::build); } - private static LocatableIndex locatableIndex(Engine engine) { - if (engine == null) { + private static LocatableIndex locatableIndex(PackWorld world) { + if (world == null) { return EMPTY_LOCATABLE_INDEX; } - return engine.getGeneration().state(LocatableIndex.class, IrisStructureLocator::buildLocatableIndex); + return world.state(LocatableIndex.class, IrisStructureLocator::buildLocatableIndex); } - private static LocatableIndex buildLocatableIndex(Engine engine) { + private static LocatableIndex buildLocatableIndex(PackWorld world) { Set keys = new LinkedHashSet<>(); Set normalizedKeys = new LinkedHashSet<>(); Set editableKeys = new LinkedHashSet<>(); Set normalizedEditableKeys = new LinkedHashSet<>(); Set nativeKeys = new LinkedHashSet<>(); Set normalizedNativeKeys = new LinkedHashSet<>(); - for (StructurePlacement placement : index(engine).placements) { - if (!isSearchablePlacement(engine, placement)) { + for (StructurePlacement placement : index(world).placements) { + if (!isSearchablePlacement(world, placement)) { continue; } if (placement.hasNativeStructures()) { @@ -1105,7 +1095,7 @@ public final class IrisStructureLocator { continue; } for (String structureKey : placement.structures()) { - StructureStamp stamp = stampOf(engine, structureKey); + StructureStamp stamp = stampOf(world, structureKey); if (stamp == null) { throw new IllegalStateException( "Iris structure placement references missing structure '" + structureKey + "'"); @@ -1134,29 +1124,15 @@ public final class IrisStructureLocator { normalizedKeys.add(normalize(trimmedKey)); } - private static PlacementIndex build(Engine engine) { + private static PlacementIndex build(PackWorld world) { Set loadKeys = new LinkedHashSet<>(); Set normalizedLoadKeys = new LinkedHashSet<>(); Set vanillaAliases = new LinkedHashSet<>(); Set suppressedVanillaSources = new LinkedHashSet<>(); List placements = new ArrayList<>(); - collect(StructurePlacementScope.placementsOf(engine.getDimension()), engine, loadKeys, normalizedLoadKeys, vanillaAliases, - suppressedVanillaSources, placements, true); - KList regions = engine.getDimension().getAllRegions(engine); - if (regions != null) { - for (IrisRegion region : regions) { - collect(StructurePlacementScope.placementsOf(region), engine, - loadKeys, normalizedLoadKeys, vanillaAliases, - suppressedVanillaSources, placements, false); - } - } - KList biomes = engine.getDimension().getReachableBiomes(engine); - if (biomes != null) { - for (IrisBiome biome : biomes) { - collect(StructurePlacementScope.placementsOf(biome), engine, - loadKeys, normalizedLoadKeys, vanillaAliases, - suppressedVanillaSources, placements, false); - } + for (var declared : world.settings().declared(StructurePlacementSettings.class)) { + collect(declared.value().placements(), world, loadKeys, normalizedLoadKeys, vanillaAliases, + suppressedVanillaSources, placements, declared.level() == Level.DIMENSION); } return new PlacementIndex( Collections.unmodifiableSet(loadKeys), @@ -1182,7 +1158,7 @@ public final class IrisStructureLocator { return Collections.unmodifiableSet(nativeKeys); } - private static void collect(List source, Engine engine, Set loadKeys, + private static void collect(List source, PackWorld world, Set loadKeys, Set normalizedLoadKeys, Set vanillaAliases, Set suppressedVanillaSources, List placements, boolean allowNativeSuppression) { @@ -1219,7 +1195,7 @@ public final class IrisStructureLocator { ? "REPLACE_SOURCE contains a blank Iris structure reference" : "Iris structure placement contains a blank structure reference"); } - StructureStamp stamp = stampOf(engine, structureKey); + StructureStamp stamp = stampOf(world, structureKey); if (stamp == null) { throw new IllegalStateException((replacesNative ? "REPLACE_SOURCE references missing Iris structure '" @@ -1237,9 +1213,9 @@ public final class IrisStructureLocator { throw new IllegalStateException("REPLACE_SOURCE structure '" + structureKey + "' must declare a valid namespaced vanillaSource"); } - PackResources pack = engine.getData().getPackResources(); + PackResources pack = world.resources(); ResourceId structureId = pack.idOf(structureKey); - if (providerOf(engine, structureId).viability(pack, structureId) != Viability.GUARANTEED) { + if (providerOf(world, structureId).viability(pack, structureId) != Viability.GUARANTEED) { throw new IllegalStateException("REPLACE_SOURCE structure '" + structureKey + "' is not runtime-viable; native generation will not be used as a fallback"); } diff --git a/core/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java b/core/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java index 0f73ff88f..fb0f46a21 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolver.java @@ -1,16 +1,19 @@ package art.arcane.iris.engine.framework; import art.arcane.iris.builtin.carve.CaveLavaHeightSettings; -import art.arcane.iris.engine.object.world.biome.IrisBiome; import art.arcane.iris.builtin.structure.StructureAnchorMode; import art.arcane.iris.builtin.structure.StructurePlacement; +import art.arcane.iris.engine.framework.structure.StructureWorld; import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.matter.MatterCavern; +import com.volmit.mantle.CarvedVoid; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Objects; +import java.util.Optional; import java.util.function.IntPredicate; public final class StructureCaveAnchorResolver { @@ -19,22 +22,21 @@ public final class StructureCaveAnchorResolver { private static final int MAX_SCAN_STEP = 16; private static final int MAX_CLEARANCE = 64; private static final int MAX_GENERIC_CENTER_SEARCH = 4096; - private static final byte LIQUID_FORCED_AIR = 3; private StructureCaveAnchorResolver() { } - public static Anchor resolve(Engine engine, StructurePlacement placement, int chunkX, int chunkZ, RNG rng) { - Objects.requireNonNull(engine, "Cave structure anchor requires an engine"); + public static Anchor resolve(PackWorld world, StructurePlacement placement, int chunkX, int chunkZ, RNG rng) { + Objects.requireNonNull(world, "Cave structure anchor requires a world"); Objects.requireNonNull(placement, "Cave structure anchor requires a placement"); Objects.requireNonNull(rng, "Cave structure anchor requires a random source"); StructureAnchorMode mode = placement.resolvedAnchor(); - if (!mode.isCave() || engine.getMantle() == null || engine.getMantle().getMantle() == null) { + if (!mode.isCave() || world.running().isEmpty()) { return null; } - int worldMin = engine.getMinHeight() + 1; - int worldMax = engine.getMinHeight() + engine.getHeight() - 2; + int worldMin = world.minWorldY() + 1; + int worldMax = world.minWorldY() + StructureWorld.height(world) - 2; int minimumY = Math.max(worldMin, Math.min(placement.minHeight(), placement.maxHeight())); int maximumY = Math.min(worldMax, Math.max(placement.minHeight(), placement.maxHeight())); if (minimumY > maximumY) { @@ -51,7 +53,7 @@ public final class StructureCaveAnchorResolver { int blockX = chunkMinX + (candidateColumn & 15); int blockZ = chunkMinZ + (candidateColumn >>> 4); List anchors = anchorsInColumn( - engine, placement, mode, blockX, blockZ, + world, placement, mode, blockX, blockZ, minimumY, maximumY, scanStep, clearance); if (!anchors.isEmpty()) { return new Anchor(blockX, anchors.get(rng.nextInt(anchors.size())), blockZ); @@ -73,7 +75,7 @@ public final class StructureCaveAnchorResolver { } static List anchorsInColumn( - Engine engine, + PackWorld world, StructurePlacement placement, StructureAnchorMode mode, int blockX, @@ -85,20 +87,20 @@ public final class StructureCaveAnchorResolver { ) { if (mode == StructureAnchorMode.CAVE_CENTER) { return centerAnchorsInColumn( - engine, placement, blockX, blockZ, + world, placement, blockX, blockZ, minimumY, maximumY, scanStep, clearance); } List anchors = new ArrayList<>(); int step = Math.max(1, scanStep); for (int worldY = minimumY; worldY <= maximumY; worldY += step) { - int mantleY = toMantleY(worldY, engine.getMinHeight()); - if (!matchesGeometry(engine, mode, blockX, mantleY, blockZ, clearance)) { + int mantleY = toMantleY(worldY, world.minWorldY()); + if (!matchesGeometry(world, mode, blockX, mantleY, blockZ, clearance)) { continue; } - if (!matchesAnchorFluid(engine, placement, blockX, mantleY, blockZ)) { + if (!matchesAnchorFluid(world, placement, blockX, mantleY, blockZ)) { continue; } - if (!matchesBiome(engine, placement, blockX, mantleY, blockZ)) { + if (!matchesBiome(world, placement, blockX, mantleY, blockZ)) { continue; } anchors.add(worldY); @@ -107,7 +109,7 @@ public final class StructureCaveAnchorResolver { } private static List centerAnchorsInColumn( - Engine engine, + PackWorld world, StructurePlacement placement, int blockX, int blockZ, @@ -118,11 +120,11 @@ public final class StructureCaveAnchorResolver { ) { List anchors = new ArrayList<>(); int step = Math.max(1, scanStep); - int worldOffset = engine.getMinHeight(); + int worldOffset = world.minWorldY(); int minimumMantleY = 0; - int maximumMantleY = engine.getHeight() - 1; + int maximumMantleY = StructureWorld.height(world) - 1; int processedThroughWorldY = Integer.MIN_VALUE; - IntPredicate carved = y -> isCarved(engine, blockX, y, blockZ); + IntPredicate carved = y -> isCarved(world, blockX, y, blockZ); for (int worldY = minimumY; worldY <= maximumY; worldY += step) { if (worldY <= processedThroughWorldY) { continue; @@ -139,12 +141,12 @@ public final class StructureCaveAnchorResolver { } int lowerCenterWorldY = lower + Math.floorDiv(upper - lower, 2) + worldOffset; addCenterAnchor( - anchors, engine, placement, blockX, blockZ, + anchors, world, placement, blockX, blockZ, lowerCenterWorldY, minimumY, maximumY); int upperCenterWorldY = lower + Math.ceilDiv(upper - lower, 2) + worldOffset; if (upperCenterWorldY != lowerCenterWorldY) { addCenterAnchor( - anchors, engine, placement, blockX, blockZ, + anchors, world, placement, blockX, blockZ, upperCenterWorldY, minimumY, maximumY); } } @@ -153,7 +155,7 @@ public final class StructureCaveAnchorResolver { private static void addCenterAnchor( List anchors, - Engine engine, + PackWorld world, StructurePlacement placement, int blockX, int blockZ, @@ -164,25 +166,25 @@ public final class StructureCaveAnchorResolver { if (worldY < minimumY || worldY > maximumY) { return; } - int mantleY = toMantleY(worldY, engine.getMinHeight()); - if (matchesAnchorFluid(engine, placement, blockX, mantleY, blockZ) - && matchesBiome(engine, placement, blockX, mantleY, blockZ)) { + int mantleY = toMantleY(worldY, world.minWorldY()); + if (matchesAnchorFluid(world, placement, blockX, mantleY, blockZ) + && matchesBiome(world, placement, blockX, mantleY, blockZ)) { anchors.add(worldY); } } static boolean matchesGeometry( - Engine engine, + PackWorld world, StructureAnchorMode mode, int blockX, int mantleY, int blockZ, int clearance ) { - IntPredicate carved = y -> isCarved(engine, blockX, y, blockZ); + IntPredicate carved = y -> isCarved(world, blockX, y, blockZ); if (mode == StructureAnchorMode.CAVE_CENTER) { return matchesCenterGeometry( - carved, mantleY, Math.max(1, clearance), 0, engine.getHeight() - 1); + carved, mantleY, Math.max(1, clearance), 0, StructureWorld.height(world) - 1); } return matchesGeometry(carved, mode, mantleY, clearance); } @@ -272,49 +274,49 @@ public final class StructureCaveAnchorResolver { return true; } - private static boolean isCarved(Engine engine, int blockX, int mantleY, int blockZ) { - if (mantleY < 0 || mantleY >= engine.getHeight()) { + private static boolean isCarved(PackWorld world, int blockX, int mantleY, int blockZ) { + if (mantleY < 0 || mantleY >= StructureWorld.height(world)) { return false; } - MatterCavern cavern = cavernAt(engine, blockX, mantleY, blockZ); - return cavern != null && cavern.isCavern(); + return carvedAt(world, blockX, mantleY, blockZ).isPresent(); } private static boolean matchesAnchorFluid( - Engine engine, + PackWorld world, StructurePlacement placement, int blockX, int mantleY, int blockZ ) { - MatterCavern cavern = cavernAt(engine, blockX, mantleY, blockZ); + int lavaHeight = StructureWorld.running(world).settings().at(CaveLavaHeightSettings.class, blockX, blockZ) + .dimension().map(CaveLavaHeightSettings::height).orElse(CaveLavaHeightSettings.DEFAULT_HEIGHT); return acceptsAnchorFluid( placement.underwater(), - cavern, + carvedAt(world, blockX, mantleY, blockZ).orElse(null), mantleY, - engine.getDimension().getModuleSettings().find(CaveLavaHeightSettings.class).map(CaveLavaHeightSettings::height).orElse(CaveLavaHeightSettings.DEFAULT_HEIGHT)); + lavaHeight); } static boolean acceptsAnchorFluid( boolean underwater, - MatterCavern cavern, + CarvedVoid carved, int mantleY, int defaultLavaHeight ) { - if (cavern == null || !cavern.isCavern()) { + if (carved == null) { return false; } if (underwater) { return true; } - if (cavern.getLiquid() == LIQUID_FORCED_AIR) { + if (carved.fill() == CarvedVoid.Fill.AIR) { return true; } - return cavern.isAir() && mantleY > defaultLavaHeight; + return carved.fill() == CarvedVoid.Fill.OPEN && mantleY > defaultLavaHeight; } - private static MatterCavern cavernAt(Engine engine, int blockX, int mantleY, int blockZ) { - return engine.getMantle().getMantle().get(blockX, mantleY, blockZ, MatterCavern.class); + private static Optional carvedAt(PackWorld world, int blockX, int mantleY, int blockZ) { + return StructureWorld.running(world).carvedAt(blockX, mantleY, blockZ); } static int toMantleY(int worldY, int worldMinHeight) { @@ -322,7 +324,7 @@ public final class StructureCaveAnchorResolver { } private static boolean matchesBiome( - Engine engine, + PackWorld world, StructurePlacement placement, int blockX, int mantleY, @@ -331,11 +333,11 @@ public final class StructureCaveAnchorResolver { if (placement.caveBiomes().isEmpty()) { return true; } - IrisBiome biome = engine.getCaveOrMantleBiome(blockX, mantleY, blockZ); - if (biome == null || biome.getLoadKey() == null) { + Optional biome = caveOrCarvedBiome(world, blockX, mantleY, blockZ); + if (biome.isEmpty()) { return false; } - String actual = biome.getLoadKey().toLowerCase(Locale.ROOT); + String actual = StructureWorld.keyOf(world, biome.get()).toLowerCase(Locale.ROOT); for (String allowed : placement.caveBiomes()) { if (matchesBiomeKey(actual, allowed)) { return true; @@ -344,6 +346,15 @@ public final class StructureCaveAnchorResolver { return false; } + /** The biome the carver gave the void at the block, else the cave biome of the column at that height. */ + private static Optional caveOrCarvedBiome(PackWorld world, int blockX, int mantleY, int blockZ) { + Optional carvedBiome = carvedAt(world, blockX, mantleY, blockZ).flatMap(CarvedVoid::biome); + if (carvedBiome.isPresent()) { + return carvedBiome; + } + return StructureWorld.running(world).layout().caveBiome(blockX, mantleY, blockZ); + } + static boolean matchesBiomeKey(String actual, String allowed) { if (actual == null || actual.isBlank() || allowed == null || allowed.isBlank()) { return false; diff --git a/core/src/main/java/art/arcane/iris/engine/framework/StructurePlacementScope.java b/core/src/main/java/art/arcane/iris/engine/framework/StructurePlacementScope.java index bc99627de..b5df5742c 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/StructurePlacementScope.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/StructurePlacementScope.java @@ -2,16 +2,20 @@ package art.arcane.iris.engine.framework; import art.arcane.iris.builtin.structure.StructurePlacement; import art.arcane.iris.builtin.structure.StructurePlacementSettings; -import art.arcane.iris.core.loader.IrisRegistrant; -import art.arcane.iris.engine.IrisComplex; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.volmlib.util.collection.KList; +import art.arcane.iris.engine.framework.structure.StructureWorld; +import com.volmit.config.FeatureSettings; +import com.volmit.config.Level; +import com.volmit.config.SettingsStack; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; +import com.volmit.world.TerrainSampler; +import java.util.ArrayList; import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; -import java.util.Objects; +import java.util.Optional; import java.util.Set; /** @@ -20,79 +24,78 @@ import java.util.Set; * region lookups a pack never needs. */ public final class StructurePlacementScope { + private static final int CHUNK_CENTER_OFFSET_BLOCKS = 8; + private StructurePlacementScope() { } - /** The placements {@code owner} declares in its {@code "structures"} settings; empty for none. */ - public static List placementsOf(IrisRegistrant owner) { - if (owner == null) { - return List.of(); - } - return owner.getModuleSettings().find(StructurePlacementSettings.class) - .map(StructurePlacementSettings::placements) - .orElse(List.of()); + /** The placements {@code settings} declare; empty for none. */ + public static List placementsOf(Optional settings) { + return settings.map(StructurePlacementSettings::placements).orElse(List.of()); } - public static KList placementsAt(Engine engine, int chunkX, int chunkZ) { - Engine activeEngine = Objects.requireNonNull(engine, "Structure placement scope requires an engine"); - IrisComplex complex = activeEngine.getComplex(); - int blockX = (chunkX << 4) + 8; - int blockZ = (chunkZ << 4) + 8; - KList placements = new KList<>(); + public static List placementsAt(PackWorld world, int chunkX, int chunkZ) { + RunningWorld running = StructureWorld.running(world); + int blockX = (chunkX << 4) + CHUNK_CENTER_OFFSET_BLOCKS; + int blockZ = (chunkZ << 4) + CHUNK_CENTER_OFFSET_BLOCKS; + List placements = new ArrayList<>(); Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); - ScopeIndex index = scopeIndex(activeEngine); - if (complex != null) { - if (index.biome()) { - IrisBiome biome = complex.getTrueBiomeStream().get(blockX, blockZ); - addUnique(placements, seen, placementsOf(biome)); - } - if (index.caveBiome()) { - IrisBiome caveBiome = complex.getCaveBiomeStream().get(blockX, blockZ); - addCaveUnique(placements, seen, placementsOf(caveBiome)); - } - if (index.region()) { - IrisRegion region = complex.getRegionStream().get(blockX, blockZ); - addUnique(placements, seen, placementsOf(region)); - } - } - if (index.dimension()) { - addUnique(placements, seen, placementsOf(activeEngine.getDimension())); + ScopeIndex index = world.state(ScopeIndex.class, StructurePlacementScope::buildScopeIndex); + if (index.declaresBelowDimension()) { + addColumnPlacements(placements, seen, running, index, blockX, blockZ); } + addUnique(placements, seen, index.dimensionPlacements()); return placements; } - private static ScopeIndex scopeIndex(Engine engine) { - return engine.getGeneration().state(ScopeIndex.class, StructurePlacementScope::buildScopeIndex); + private static void addColumnPlacements(List placements, Set seen, + RunningWorld running, ScopeIndex index, int blockX, int blockZ) { + SettingsStack declared = running.settings().at(StructurePlacementSettings.class, blockX, blockZ); + if (index.biome()) { + addUnique(placements, seen, placementsOf(declared.level(Level.BIOME))); + } + if (index.caveBiome()) { + addCaveUnique(placements, seen, placementsOf(caveBiomeSettings(running, blockX, blockZ))); + } + if (index.region()) { + addUnique(placements, seen, placementsOf(declared.level(Level.REGION))); + } } - private static ScopeIndex buildScopeIndex(Engine engine) { + private static Optional caveBiomeSettings(RunningWorld running, int blockX, int blockZ) { + TerrainSampler layout = running.layout(); + ResourceId surfaceBiome = layout.surfaceBiome(blockX, blockZ); + Optional caveBiome = layout.caveBiome(blockX, layout.bounds().minY(), blockZ) + .filter(cave -> !cave.equals(surfaceBiome)); + FeatureSettings settings = running.settings(); + return caveBiome.flatMap(cave -> settings.declaredBy(cave, StructurePlacementSettings.class)); + } + + private static ScopeIndex buildScopeIndex(PackWorld world) { boolean biome = false; boolean caveBiome = false; - KList allBiomes = engine.getAllBiomes(); - if (allBiomes == null) { - biome = true; - caveBiome = true; - } else { - for (IrisBiome candidate : allBiomes) { - List structures = placementsOf(candidate); - if (structures.isEmpty()) { - continue; + boolean region = false; + List dimensionPlacements = List.of(); + for (var entry : world.settings().declared(StructurePlacementSettings.class)) { + List placements = entry.value().placements(); + if (placements.isEmpty()) { + continue; + } + switch (entry.level()) { + case BIOME -> { + biome = true; + caveBiome |= placements.stream().anyMatch(placement -> placement.resolvedAnchor().isCave()); + } + case REGION -> region = true; + case DIMENSION -> dimensionPlacements = placements; + default -> { } - biome = true; - caveBiome |= structures.stream().anyMatch(placement -> placement.resolvedAnchor().isCave()); } } - boolean region = false; - if (engine.getDimension() != null) { - KList allRegions = engine.getDimension().getAllRegions(engine); - region = allRegions == null - || allRegions.stream().anyMatch(candidate -> !placementsOf(candidate).isEmpty()); - } - boolean dimension = !placementsOf(engine.getDimension()).isEmpty(); - return new ScopeIndex(biome, caveBiome, region, dimension); + return new ScopeIndex(biome, caveBiome, region, dimensionPlacements); } - private static void addUnique(KList destination, Set seen, + private static void addUnique(List destination, Set seen, List source) { for (StructurePlacement placement : source) { if (placement != null && seen.add(placement)) { @@ -101,7 +104,7 @@ public final class StructurePlacementScope { } } - private static void addCaveUnique(KList destination, Set seen, + private static void addCaveUnique(List destination, Set seen, List source) { for (StructurePlacement placement : source) { if (placement != null && placement.resolvedAnchor().isCave() && seen.add(placement)) { @@ -110,6 +113,9 @@ public final class StructurePlacementScope { } } - private record ScopeIndex(boolean biome, boolean caveBiome, boolean region, boolean dimension) { + record ScopeIndex(boolean biome, boolean caveBiome, boolean region, List dimensionPlacements) { + boolean declaresBelowDimension() { + return biome || caveBiome || region; + } } } diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/NativeStartPlanner.java b/core/src/main/java/art/arcane/iris/engine/framework/structure/NativeStartPlanner.java index c5f273b39..dd3f4d61f 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/NativeStartPlanner.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/structure/NativeStartPlanner.java @@ -18,9 +18,9 @@ package art.arcane.iris.engine.framework.structure; -import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.StructurePlacementGrid; import art.arcane.iris.engine.framework.StructurePlacementScope; +import com.volmit.world.PackWorld; import art.arcane.iris.builtin.structure.StructureAnchorMode; import art.arcane.iris.builtin.structure.StructurePlacement; import art.arcane.iris.builtin.structure.NativeStructureSource; @@ -48,10 +48,10 @@ public final class NativeStartPlanner { public record Plan(StructurePlacement placement, NativeStructureSource source, int chunkX, int chunkZ, int baseY) { } - public static List plansAt(Engine engine, int chunkX, int chunkZ) { + public static List plansAt(PackWorld world, int chunkX, int chunkZ) { Map plansByStructure = new LinkedHashMap<>(); - for (StructurePlacement placement : StructurePlacementScope.placementsAt(engine, chunkX, chunkZ)) { - Plan plan = planAt(engine, placement, chunkX, chunkZ); + for (StructurePlacement placement : StructurePlacementScope.placementsAt(world, chunkX, chunkZ)) { + Plan plan = planAt(world, placement, chunkX, chunkZ); if (plan == null) { continue; } @@ -64,23 +64,20 @@ public final class NativeStartPlanner { return List.copyOf(plansByStructure.values()); } - public static Plan planAt(Engine engine, StructurePlacement placement, int chunkX, int chunkZ) { + public static Plan planAt(PackWorld world, StructurePlacement placement, int chunkX, int chunkZ) { validateBackend(placement); if (!placement.hasNativeStructures()) { return null; } - Engine activeEngine = Objects.requireNonNull(engine, "Native structure planner requires an engine"); - if (activeEngine.getSeedManager() == null) { - throw new IllegalStateException("Native structure planner requires a bound seed manager"); - } - long mantleSeed = activeEngine.getSeedManager().getMantle(); + Objects.requireNonNull(world, "Native structure planner requires a world"); + long mantleSeed = StructureWorld.placementSeed(world); if (!StructurePlacementGrid.startsInChunk(placement, chunkX, chunkZ, mantleSeed)) { return null; } RNG placementRng = StructurePlacementGrid.placementRng( placement, chunkX, chunkZ, mantleSeed).nextParallelRNG(NATIVE_SELECTION_DOMAIN); NativeStructureSource source = selectSource(placement.nativeStructures(), placementRng); - Integer baseY = resolveBaseY(activeEngine, placement, chunkX, chunkZ, placementRng); + Integer baseY = resolveBaseY(world, placement, chunkX, chunkZ, placementRng); if (baseY == null) { return null; } @@ -102,8 +99,8 @@ public final class NativeStartPlanner { } } - public static boolean isSubmerged(Engine engine, int blockX, int blockZ) { - return engine.getHeight(blockX, blockZ, true) < engine.getDimension().getFluidHeight(); + public static boolean isSubmerged(PackWorld world, int blockX, int blockZ) { + return StructureWorld.highestAboveBottom(world, blockX, blockZ) < StructureWorld.fluidHeightAboveBottom(world); } static NativeStructureSource selectSource(List sources, RNG rng) { @@ -133,20 +130,20 @@ public final class NativeStartPlanner { throw new IllegalStateException("Native structure source selection produced no result"); } - private static Integer resolveBaseY(Engine engine, StructurePlacement placement, + private static Integer resolveBaseY(PackWorld world, StructurePlacement placement, int chunkX, int chunkZ, RNG rng) { - int worldMin = engine.getMinHeight() + 1; - int worldMax = engine.getMinHeight() + engine.getHeight() - 1; + int worldMin = world.minWorldY() + 1; + int worldMax = world.minWorldY() + StructureWorld.height(world) - 1; if (worldMin > worldMax) { throw new IllegalStateException("Native structure placement has invalid world height bounds"); } int blockX = (chunkX << 4) + 8; int blockZ = (chunkZ << 4) + 8; - if (!placement.underwater() && isSubmerged(engine, blockX, blockZ)) { + if (!placement.underwater() && isSubmerged(world, blockX, blockZ)) { return null; } if (!placement.underground()) { - int surfaceY = engine.getHeight(blockX, blockZ, true) + engine.getMinHeight(); + int surfaceY = StructureWorld.highest(world, blockX, blockZ); if (surfaceY < placement.minHeight() || surfaceY > placement.maxHeight()) { return null; } diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureLocating.java b/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureLocating.java index a2de3f091..59530d2f6 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureLocating.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureLocating.java @@ -18,7 +18,6 @@ package art.arcane.iris.engine.framework.structure; -import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.IrisStructureLocator; import com.volmit.resource.PackResources; import com.volmit.resource.ResourceId; @@ -52,43 +51,41 @@ public final class StructureLocating implements StructureLocator { @Override public Set locatable(PackWorld world) { - return idsOf(world.resources(), IrisStructureLocator.locatableEditableKeys(engine(world))); + return idsOf(world.resources(), IrisStructureLocator.locatableEditableKeys(world)); } @Override public Set placed(PackWorld world) { - return idsOf(world.resources(), IrisStructureLocator.placedKeysAndAliases(engine(world))); + return idsOf(world.resources(), IrisStructureLocator.placedKeysAndAliases(world)); } @Override public LocateResult locate(PackWorld world, ResourceId structure, int fromX, int fromZ, int maxRadiusChunks) { - Engine engine = engine(world); - String key = keyOf(world.resources(), IrisStructureLocator.placedKeysAndAliases(engine), structure); - return apiResult(engine, IrisStructureLocator.locate(engine, key, fromX, fromZ, maxRadiusChunks)); + String key = keyOf(world.resources(), IrisStructureLocator.placedKeysAndAliases(world), structure); + return apiResult(world, IrisStructureLocator.locate(world, key, fromX, fromZ, maxRadiusChunks)); } @Override public Set startedStructures(PackWorld world) { - return platformIds(IrisStructureLocator.nativeKeys(engine(world))); + return platformIds(IrisStructureLocator.nativeKeys(world)); } @Override public Set locatableStarts(PackWorld world) { - return platformIds(IrisStructureLocator.locatableNativeKeys(engine(world))); + return platformIds(IrisStructureLocator.locatableNativeKeys(world)); } /** Searches the rings of the placements that start {@code structure} natively, as the platform's own locate does. */ @Override public LocateResult locateStart(PackWorld world, ResourceId structure, int fromX, int fromZ, int maxRings, ChunkFilter accepts) { - Engine engine = engine(world); - return apiResult(engine, IrisStructureLocator.locateInPlacementRings( - engine, structure.toString(), fromX, fromZ, maxRings, accepts::accepts)); + return apiResult(world, IrisStructureLocator.locateInPlacementRings( + world, structure.toString(), fromX, fromZ, maxRings, accepts::accepts)); } - private static LocateResult apiResult(Engine engine, IrisStructureLocator.LocateResult result) { + private static LocateResult apiResult(PackWorld world, IrisStructureLocator.LocateResult result) { return switch (result.status()) { - case FOUND -> LocateResult.found(new BlockPosition(result.originX(), result.baseY() - engine.getMinHeight(), result.originZ())); + case FOUND -> LocateResult.found(new BlockPosition(result.originX(), result.baseY() - world.minWorldY(), result.originZ())); case NOT_FOUND -> LocateResult.NOT_FOUND; case SEARCH_LIMIT_REACHED -> LocateResult.SEARCH_LIMIT_REACHED; }; @@ -102,10 +99,6 @@ public final class StructureLocating implements StructureLocator { return ids; } - private static Engine engine(PackWorld world) { - return world.extension(Engine.class).orElseThrow(); - } - private static Set idsOf(PackResources pack, Collection keys) { Set ids = new LinkedHashSet<>(); for (String key : keys) { diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java b/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java index 7ca896b65..57047e8f3 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureVanillaStructures.java @@ -18,7 +18,6 @@ package art.arcane.iris.engine.framework.structure; -import art.arcane.iris.engine.framework.Engine; import art.arcane.iris.engine.framework.IrisStructureLocator; import art.arcane.iris.engine.framework.structure.fit.StartLayouts; import art.arcane.iris.engine.framework.structure.fit.StructureFitting; @@ -56,20 +55,20 @@ public final class StructureVanillaStructures implements VanillaStructures { */ @Override public VanillaStructureRule rule(ResourceId structure, VanillaStructureContext context) { - Engine engine = context.settings().extension(Engine.class).orElseThrow(); + PackWorld world = context.world().orElseThrow(); String key = structure.toString(); - boolean replaced = IrisStructureLocator.suppressesVanilla(engine, key); + boolean replaced = IrisStructureLocator.suppressesVanilla(world, key); boolean blocked = replaced || ImportedStructures.of(context.settings()).disables(key); - boolean placed = replaced || IrisStructureLocator.isPlaced(engine, key); + boolean placed = replaced || IrisStructureLocator.isPlaced(world, key); VanillaStructureRule rule = blocked ? VanillaStructureRule.BLOCK : VanillaStructureRule.GENERATE; return placed ? rule.and(VanillaStructureRule.ALSO_PLACE) : rule; } @Override public List starts(int chunkX, int chunkZ, VanillaStructureStartContext context) { - Engine engine = engine(context.world()); - return NativeStartPlanner.plansAt(engine, chunkX, chunkZ).stream() - .map(plan -> start(plan, engine.getMinHeight())) + PackWorld world = context.world(); + return NativeStartPlanner.plansAt(world, chunkX, chunkZ).stream() + .map(plan -> start(plan, world.minWorldY())) .toList(); } @@ -102,10 +101,6 @@ public final class StructureVanillaStructures implements VanillaStructures { return ImportedStructures.of(context.settings()).setup(); } - private static Engine engine(PackWorld world) { - return world.extension(Engine.class).orElseThrow(); - } - /** {@code plan} as the start the platform generates: heights above the bottom and the placement's fit. */ static VanillaStructureStart start(NativeStartPlanner.Plan plan, int minHeight) { StructurePlacement placement = plan.placement(); diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureWorld.java b/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureWorld.java new file mode 100644 index 000000000..2674dd8cc --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureWorld.java @@ -0,0 +1,50 @@ +package art.arcane.iris.engine.framework.structure; + +import art.arcane.iris.builtin.structure.StructureSeeds; +import com.volmit.resource.ResourceId; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; + +/** + * What structure placement asks a world about its size, its seed and its terrain. Heights here are the world's own + * (absolute) Y unless a method says it is above the dimension's bottom. + */ +public final class StructureWorld { + private StructureWorld() { + } + + public static RunningWorld running(PackWorld world) { + return world.running().orElseThrow(() -> new IllegalStateException("Structure placement requires a running world")); + } + + /** The key the pack's files name {@code id} by: its path in the pack's own namespace, the whole id in another. */ + public static String keyOf(PackWorld world, ResourceId id) { + return id.namespace().equals(world.resources().packId().namespace()) ? id.path() : id.toString(); + } + + /** The seed placements start from. */ + public static long placementSeed(PackWorld world) { + return world.seed(StructureSeeds.PLACEMENT); + } + + /** How many blocks high the world is. */ + public static int height(PackWorld world) { + var bounds = running(world).layout().bounds(); + return bounds.maxY() - bounds.minY(); + } + + /** The highest block of the column, with what objects and structures added, above the dimension's bottom. */ + public static int highestAboveBottom(PackWorld world, int blockX, int blockZ) { + return running(world).highest(blockX, blockZ, true); + } + + /** The highest block of the column in world Y. */ + public static int highest(PackWorld world, int blockX, int blockZ) { + return highestAboveBottom(world, blockX, blockZ) + world.minWorldY(); + } + + /** The height up to which the dimension is filled with fluid, above the dimension's bottom. */ + public static int fluidHeightAboveBottom(PackWorld world) { + return running(world).layout().fluidHeight(); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/fit/StructureFitting.java b/core/src/main/java/art/arcane/iris/engine/framework/structure/fit/StructureFitting.java index 4e38b0211..dd7540875 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/fit/StructureFitting.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/structure/fit/StructureFitting.java @@ -91,7 +91,8 @@ public final class StructureFitting { private void prepare() { vacuumFoundations = SurfaceFitting.prepareSurfaceStructures(blocks, area, starts, surfaceHeight, SurfaceFitting.MAX_SURFACE_TEMPLATE_CELLS, fit.log()); - TerrainIntegration.prepareTerrain(blocks, area, starts, fit.seed(), this::naturalBlock, this::paletteBlock); + TerrainIntegration.prepareTerrain(blocks, area, starts, fit.seed(), fit.world().resources().noise(), + this::naturalBlock, this::paletteBlock); RigidSupport.bridgeRigidPieceSupport(blocks, area, starts); } diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegration.java b/core/src/main/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegration.java index 44ee7f79d..4fa9e60dc 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegration.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegration.java @@ -23,10 +23,11 @@ import art.arcane.iris.builtin.structure.StructureTerrain; import art.arcane.iris.builtin.structure.StructureTerrainMode; import art.arcane.iris.engine.mantle.components.StructureCarveEnvelope; import art.arcane.iris.engine.mantle.components.StructureCarvingFootprint; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.volmlib.util.math.RNG; import com.volmit.block.BlockState; import com.volmit.block.PaletteSpec; +import com.volmit.noise.NoiseFactory; +import com.volmit.noise.NoiseSampler; +import com.volmit.noise.NoiseStyle; import com.volmit.resource.ResourceId; import com.volmit.vanilla.TerrainAdaptation; import com.volmit.geometry.BlockPosition; @@ -49,6 +50,9 @@ final class TerrainIntegration { private static final long CARVE_CEILING_ROLL_SIGNATURE = 0x2A17L; private static final long CARVE_FLOOR_ROLL_SIGNATURE = 0x5B3DL; private static final long CARVE_LOBE_SIGNATURE = 0x7C41L; + private static final NoiseStyle SIGNATURE_NOISE = NoiseStyle.of("IRIS"); + /** The lobes want a plain single octave channel: the fractured signature noise has no usable low frequency band. */ + private static final NoiseStyle SINGLE_OCTAVE_NOISE = NoiseStyle.of("SIMPLEX"); private static final long CARVE_IDENTITY_X = 341873128712L; private static final long CARVE_IDENTITY_Z = 132897987541L; private static final int SOURCE_BURY_HORIZONTAL_RADIUS = 6; @@ -83,14 +87,14 @@ final class TerrainIntegration { * Integrates the terrain of every start, then clears the legacy template air of those that replay their own * adaptation or are encased. The natural material SOURCE fills with is read once for all starts, before any fill. */ - static void prepareTerrain(FitBlocks blocks, Box area, List starts, long seed, + static void prepareTerrain(FitBlocks blocks, Box area, List starts, long seed, NoiseFactory noise, IntFunction naturalBlock, FitPalettes palettes) { if (starts.isEmpty()) { return; } SourceTerrainSnapshot sourceTerrain = captureSourceTerrain(blocks, area, starts); for (FitStart start : starts) { - integrateTerrain(blocks, area, start, seed, naturalBlock, palettes, sourceTerrain); + integrateTerrain(blocks, area, start, seed, noise, naturalBlock, palettes, sourceTerrain); } for (FitStart start : starts) { if (clearsLegacyTemplateAir(start)) { @@ -99,7 +103,7 @@ final class TerrainIntegration { } } - static void integrateTerrain(FitBlocks blocks, Box area, FitStart start, long seed, + static void integrateTerrain(FitBlocks blocks, Box area, FitStart start, long seed, NoiseFactory noise, IntFunction naturalBlock, FitPalettes palettes, SourceTerrainSnapshot sourceTerrain) { StructureTerrain terrain = start.terrain(); @@ -109,11 +113,12 @@ final class TerrainIntegration { case PRESERVE, VACUUM -> { } case ENCASE -> encasePieces(blocks, area, start, terrain, seed, naturalBlock, palettes); - case BORE, FORCE_CARVE -> carve(blocks, area, start, terrain, seed); + case BORE, FORCE_CARVE -> carve(blocks, area, start, terrain, seed, noise); } } - private static void carve(FitBlocks blocks, Box area, FitStart start, StructureTerrain terrain, long seed) { + private static void carve(FitBlocks blocks, Box area, FitStart start, StructureTerrain terrain, long seed, + NoiseFactory noise) { StructureCarveShape shape = terrain.resolvedMode() == StructureTerrainMode.BORE ? StructureCarveShape.BOX : terrain.resolvedShape(); if (shape == StructureCarveShape.BOX) { @@ -122,7 +127,7 @@ final class TerrainIntegration { } carveOrganicColumns(blocks, area, organicCarve( CarveFootprints.of(start, Math.max(0, terrain.horizontalPadding())), - terrain, shape, carveNoiseIdentity(seed, start))); + terrain, shape, carveNoiseIdentity(seed, start), noise)); } static SourceTerrainSnapshot captureSourceTerrain(FitBlocks blocks, Box area, List starts) { @@ -404,22 +409,20 @@ final class TerrainIntegration { } static OrganicCarve organicCarve(StructureCarvingFootprint footprint, StructureTerrain terrain, - StructureCarveShape shape, long identity) { + StructureCarveShape shape, long identity, NoiseFactory noise) { double strength = terrain.resolvedErosionStrength(); double lobeStrength = terrain.resolvedLobeStrength(); - RNG noiseRng = new RNG(identity); - CNG blob = null; - CNG ceilingRoll = null; - CNG floorRoll = null; - CNG lobe = null; + NoiseSampler blob = null; + NoiseSampler ceilingRoll = null; + NoiseSampler floorRoll = null; + NoiseSampler lobe = null; if (shape == StructureCarveShape.ERODED && strength > 0D) { - blob = CNG.signature(noiseRng); - ceilingRoll = CNG.signature(noiseRng.nextParallelRNG(CARVE_CEILING_ROLL_SIGNATURE)); - floorRoll = CNG.signature(noiseRng.nextParallelRNG(CARVE_FLOOR_ROLL_SIGNATURE)); + blob = noise.sampler(SIGNATURE_NOISE, identity); + ceilingRoll = noise.sampler(SIGNATURE_NOISE, identity + CARVE_CEILING_ROLL_SIGNATURE); + floorRoll = noise.sampler(SIGNATURE_NOISE, identity + CARVE_FLOOR_ROLL_SIGNATURE); } if (shape == StructureCarveShape.ERODED && lobeStrength > 0D) { - // A plain single octave channel: the fractured signature noise has no usable low frequency band. - lobe = new CNG(noiseRng.nextParallelRNG(CARVE_LOBE_SIGNATURE), 1D, 1); + lobe = noise.sampler(SINGLE_OCTAVE_NOISE, identity + CARVE_LOBE_SIGNATURE); } return new OrganicCarve(footprint, shape, Math.max(0, terrain.horizontalPadding()), @@ -474,10 +477,10 @@ final class TerrainIntegration { continue; } if (distanceSquared > 0D && eroded) { - double noise = carve.blob().fitDouble(0D, 1D, + double blobSample = carve.blob().sample( x * carve.frequency(), y * carve.frequency(), z * carve.frequency()); if (!StructureCarveEnvelope.shouldCarveOverboreCell( - carve.shape(), distanceSquared, noise, carve.strength())) { + carve.shape(), distanceSquared, blobSample, carve.strength())) { continue; } } @@ -627,7 +630,7 @@ final class TerrainIntegration { record OrganicCarve(StructureCarvingFootprint footprint, StructureCarveShape shape, int horizontalPadding, int ceilingPadding, int floorPadding, - double strength, double frequency, CNG blob, CNG ceilingRoll, CNG floorRoll, - CNG lobe, double lobeFrequency, double lobeStrength) { + double strength, double frequency, NoiseSampler blob, + NoiseSampler ceilingRoll, NoiseSampler floorRoll, NoiseSampler lobe, double lobeFrequency, double lobeStrength) { } } diff --git a/core/src/main/java/art/arcane/iris/engine/mantle/MantleWriter.java b/core/src/main/java/art/arcane/iris/engine/mantle/MantleWriter.java index 66733fb6c..2f65d23bc 100644 --- a/core/src/main/java/art/arcane/iris/engine/mantle/MantleWriter.java +++ b/core/src/main/java/art/arcane/iris/engine/mantle/MantleWriter.java @@ -41,6 +41,8 @@ import art.arcane.volmlib.util.math.RNG; import art.arcane.volmlib.util.matter.Matter; import art.arcane.volmlib.util.matter.MatterCavern; import art.arcane.volmlib.util.matter.MatterSlice; +import art.arcane.volmlib.util.matter.MatterStructurePOI; +import art.arcane.iris.engine.framework.TreeBlockMaterial; import art.arcane.iris.util.project.noise.CNG; import art.arcane.iris.util.common.scheduling.J; import lombok.AccessLevel; @@ -373,6 +375,14 @@ public class MantleWriter implements IObjectPlacer, AutoCloseable { matter.getSlice(type).set(x & 15, y & 15, z & 15, null); } + /** Takes back the placement marker, tree material, block entity and point of interest kept beside the block. */ + public void clearAttached(int x, int y, int z) { + clearData(x, y, z, String.class); + clearData(x, y, z, TreeBlockMaterial.class); + clearData(x, y, z, TileWrapper.class); + clearData(x, y, z, MatterStructurePOI.class); + } + private static void clearDeferredPlacement(Matter matter, int x, int y, int z) { if (matter.hasSlice(Identifier.class)) { matter.getSlice(Identifier.class).set(x & 15, y & 15, z & 15, null); diff --git a/core/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelope.java b/core/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelope.java index a33ed27ec..86127d040 100644 --- a/core/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelope.java +++ b/core/src/main/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelope.java @@ -19,7 +19,7 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.structure.StructureCarveShape; -import art.arcane.iris.util.project.noise.CNG; +import com.volmit.noise.NoiseSampler; /** * Carve envelope math shared by the Iris-assembled structure path and the native (vanilla template) @@ -44,7 +44,7 @@ public final class StructureCarveEnvelope { * stays inside the footprint bounds the carve was sized against and never falls below * {@code horizontalPadding * (1 - lobeStrength)}. */ - public static double lobedSideReach(CNG lobe, double lobeFrequency, double lobeStrength, + public static double lobedSideReach(NoiseSampler lobe, double lobeFrequency, double lobeStrength, int x, int z, int horizontalPadding) { if (horizontalPadding <= 0) { return 0D; @@ -56,7 +56,7 @@ public final class StructureCarveEnvelope { * Ceiling counterpart of {@link #lobedSideReach}, deliberately half as strong so the roof swells * with the same lobes without collapsing onto the pieces. */ - public static double lobedUpReach(CNG lobe, double lobeFrequency, double lobeStrength, + public static double lobedUpReach(NoiseSampler lobe, double lobeFrequency, double lobeStrength, int x, int z, double upReach) { if (upReach <= 0D) { return upReach; @@ -65,19 +65,18 @@ public final class StructureCarveEnvelope { * lobeFactor(lobe, lobeFrequency, lobeStrength * CEILING_LOBE_RATIO, x, z)); } - private static double lobeFactor(CNG lobe, double lobeFrequency, double lobeStrength, + private static double lobeFactor(NoiseSampler lobe, double lobeFrequency, double lobeStrength, int x, int z) { double clampedStrength = Math.max(0D, Math.min(1D, lobeStrength)); if (lobe == null || clampedStrength <= 0D) { return 1D; } double scaledFrequency = lobeFrequency * LOBE_FREQUENCY_SCALE; - double sample = Math.max(0D, Math.min(1D, lobe.fitDouble( - 0D, 1D, x * scaledFrequency, z * scaledFrequency))); + double sample = Math.max(0D, Math.min(1D, lobe.sample(x * scaledFrequency, z * scaledFrequency))); return 1D - clampedStrength * (1D - sample); } - public static double erodedUpReach(CNG roll, double frequency, double strength, int x, int z, int head) { + public static double erodedUpReach(NoiseSampler roll, double frequency, double strength, int x, int z, int head) { if (head <= 0) { return 0D; } @@ -86,8 +85,8 @@ public final class StructureCarveEnvelope { return Math.max(1D, head); } double rollFrequency = frequency * CEILING_ROLL_FREQUENCY_RATIO; - double sample = roll.fitDouble(0D, 1D, x * rollFrequency, z * rollFrequency) * 0.7D - + roll.fitDouble(0D, 1D, x * rollFrequency * 3D, z * rollFrequency * 3D) * 0.3D; + double sample = roll.sample(x * rollFrequency, z * rollFrequency) * 0.7D + + roll.sample(x * rollFrequency * 3D, z * rollFrequency * 3D) * 0.3D; double contrast = Math.max(0D, Math.min(1D, (sample - 0.5D) * 2.6D + 0.5D)); double roundedReach = Math.max(1D, head); double erodedReach = Math.max(1D, head * (0.4D + 1.4D * contrast)); @@ -99,7 +98,7 @@ public final class StructureCarveEnvelope { * never exceeds the configured floor padding, so a padding of zero leaves every column standing on * its own supporting block instead of undermining the structure. */ - public static double erodedDownReach(CNG roll, double frequency, double strength, int x, int z, int floorCut) { + public static double erodedDownReach(NoiseSampler roll, double frequency, double strength, int x, int z, int floorCut) { if (floorCut <= 0) { return 0D; } @@ -108,7 +107,7 @@ public final class StructureCarveEnvelope { return floorCut; } double rollFrequency = frequency * FLOOR_ROLL_FREQUENCY_RATIO; - double sample = roll.fitDouble(0D, 1D, x * rollFrequency, z * rollFrequency); + double sample = roll.sample(x * rollFrequency, z * rollFrequency); return floorCut * (1D - clampedStrength * FLOOR_ROLL_AMPLITUDE * (1D - sample)); } diff --git a/core/src/main/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlanner.java b/core/src/main/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlanner.java index 8c64c6ced..467f51db3 100644 --- a/core/src/main/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlanner.java +++ b/core/src/main/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlanner.java @@ -1,7 +1,9 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.engine.framework.structure.ColumnHeights; -import art.arcane.iris.spi.PlatformBlockState; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; import java.util.function.IntConsumer; import java.util.function.IntPredicate; @@ -13,9 +15,9 @@ final class StructureFoundationPlanner { } static void recordBaseCell(ColumnHeights columns, int x, int y, int z, - PlatformBlockState state, boolean supportNonOccluding) { + BlockState state, BlockRegistry blocks, boolean supportNonOccluding) { if (columns == null || state == null - || !(supportNonOccluding ? state.isSolid() : state.isOccluding())) { + || !blocks.hasTrait(state, supportNonOccluding ? BlockTrait.SOLID : BlockTrait.OCCLUDING)) { return; } long columnKey = pack(x, z); @@ -38,19 +40,20 @@ final class StructureFoundationPlanner { return NO_GROUND; } - static boolean isGroundSolid(PlatformBlockState overlay, boolean carved, int mantleY, int terrainHeight) { + static boolean isGroundSolid(BlockState overlay, BlockRegistry blocks, boolean carved, int mantleY, + int terrainHeight) { if (mantleY <= 0) { return true; } if (overlay != null) { - return overlay.isSolid(); + return blocks.hasTrait(overlay, BlockTrait.SOLID); } return !carved && mantleY <= terrainHeight; } - static boolean isSurfaceSupportBoundary(PlatformBlockState overlay, boolean carved, + static boolean isSurfaceSupportBoundary(BlockState overlay, BlockRegistry blocks, boolean carved, int mantleY, int terrainHeight) { - return carved || isGroundSolid(overlay, false, mantleY, terrainHeight); + return carved || isGroundSolid(overlay, blocks, false, mantleY, terrainHeight); } static int fillSupportColumn(int foundationY, int groundY, IntConsumer supportAtY) { diff --git a/core/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java b/core/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java index d10fe236d..ddf7dc7c3 100644 --- a/core/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java +++ b/core/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java @@ -18,94 +18,100 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.builtin.anchor.PlaceTrait; import art.arcane.iris.builtin.anchor.ObjectPlaceMode; +import art.arcane.iris.builtin.anchor.PlaceTrait; +import art.arcane.iris.builtin.loot.ObjectLoot; +import art.arcane.iris.builtin.objects.ObjectPlacement; +import art.arcane.iris.builtin.objects.ObjectRun; +import art.arcane.iris.builtin.prepare.ObjectRotation; +import art.arcane.iris.builtin.structure.StructureCarveShape; +import art.arcane.iris.builtin.structure.StructurePlacement; +import art.arcane.iris.builtin.structure.StructurePlacementSettings; +import art.arcane.iris.builtin.structure.StructureStilts; +import art.arcane.iris.builtin.structure.StructureTerrain; +import art.arcane.iris.builtin.structure.StructureTerrainMode; +import art.arcane.iris.engine.framework.IrisStructureLocator; +import art.arcane.iris.engine.framework.StructurePlacementScope; import art.arcane.iris.engine.framework.structure.ColumnHeights; +import art.arcane.iris.engine.framework.structure.StructureWorld; import art.arcane.iris.engine.framework.structure.assembly.AssembledPiece; import art.arcane.iris.engine.framework.structure.assembly.PieceTurn; import art.arcane.iris.engine.framework.structure.assembly.StructureAssembly; import art.arcane.iris.engine.framework.structure.assembly.StructureStamp; -import art.arcane.iris.builtin.objects.ObjectPlacement; -import art.arcane.iris.builtin.prepare.ObjectRotation; -import art.arcane.iris.core.IrisSettings; -import art.arcane.iris.core.modules.ModuleObjectPlacement; import art.arcane.volmlib.util.cache.CacheKey; -import art.arcane.iris.engine.framework.IrisStructureLocator; -import art.arcane.iris.engine.framework.StructurePlacementScope; -import art.arcane.iris.core.modules.PlacementMarkers; -import art.arcane.iris.engine.framework.TreeBlockMaterial; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.builtin.loot.ObjectLoot; -import art.arcane.iris.engine.mantle.MantleWriter; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.prefab.IrisObject; -import art.arcane.iris.engine.object.world.region.IrisRegion; -import art.arcane.iris.builtin.structure.StructureCarveShape; -import art.arcane.iris.builtin.structure.StructurePlacement; -import art.arcane.iris.builtin.structure.StructureStilts; +import art.arcane.volmlib.util.collection.KList; +import art.arcane.volmlib.util.documentation.ChunkCoordinates; +import art.arcane.volmlib.util.math.RNG; import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; import com.volmit.block.PaletteSampler; import com.volmit.block.PaletteSpec; -import art.arcane.iris.builtin.structure.StructureTerrain; -import art.arcane.iris.builtin.structure.StructureTerrainMode; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.util.common.data.B; -import art.arcane.volmlib.util.math.IrisBlockVector; -import art.arcane.iris.util.project.matter.TileWrapper; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.iris.util.project.context.ChunkContext; -import art.arcane.volmlib.util.documentation.ChunkCoordinates; -import art.arcane.volmlib.util.mantle.runtime.MantleChunk; -import art.arcane.volmlib.util.matter.Matter; -import art.arcane.volmlib.util.matter.MatterCavern; -import art.arcane.volmlib.util.matter.MatterStructurePOI; -import art.arcane.volmlib.util.math.RNG; +import com.volmit.geometry.BlockBox; import com.volmit.geometry.BlockPosition; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.Mantle; +import com.volmit.noise.NoiseSampler; +import com.volmit.noise.NoiseStyle; +import com.volmit.object.ObjectBlock; +import com.volmit.object.PlaceableObject; +import com.volmit.placement.PlacementOutcome; +import com.volmit.placement.PlacementRecord; +import com.volmit.placement.PlacementTerrain; +import com.volmit.resource.PackResources; +import com.volmit.stage.MantleStageContext; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; /** * Places the Iris structures of the dimension, its regions and biomes into the mantle for * {@link StructureModule}: their pieces, foundations, bores and carves, clearing object trees they - * intersect. One per engine runtime. Its reach is the largest structure any placement can produce. + * intersect. One per world. Its reach is the largest structure any placement can produce. */ public class StructurePlacing { - private static final MatterCavern CARVE_CAVERN = new MatterCavern(true, "", (byte) 3); + private static final CarvedVoid CARVE_VOID = CarvedVoid.AIR; + private static final NoiseStyle CARVE_NOISE = NoiseStyle.of("IRIS"); + private static final long CARVE_ROLL_SIGNATURE = 0x2A17L; + private static final int REJECTED_PIECE = -1; + private static final int SAMPLED_HEIGHT = -1; - private final Engine engine; + private final PackWorld world; private final ModuleLog log; - public StructurePlacing(Engine engine, ModuleLog log) { - this.engine = engine; + public StructurePlacing(PackWorld world, ModuleLog log) { + this.world = world; this.log = log; } - /** Places what originates in the chunk at chunk coordinates {@code x}, {@code z} into {@code writer}. */ + /** Places what originates in the chunk {@code context} generates into its mantle. */ @ChunkCoordinates - public void place(MantleWriter writer, int x, int z, ChunkContext context) { - for (StructurePlacement placement : StructurePlacementScope.placementsAt( - engine, x, z)) { + public void place(MantleStageContext context) { + int x = context.chunkX(); + int z = context.chunkZ(); + for (StructurePlacement placement : StructurePlacementScope.placementsAt(world, x, z)) { if (!placement.hasIrisStructures()) { continue; } - placeFromPlacement(writer, placement, x, z); + placeFromPlacement(context, placement, x, z); } } @ChunkCoordinates - private void placeFromPlacement(MantleWriter writer, StructurePlacement placement, int cx, int cz) { + private void placeFromPlacement(MantleStageContext context, StructurePlacement placement, int cx, int cz) { IrisStructureLocator.ResolvedPlacement resolved = IrisStructureLocator.resolvePlacement( - engine, placement, cx, cz); + world, placement, cx, cz); if (resolved == null) { return; } - boolean trace = IrisSettings.get().getGeneral().isDebug(); + boolean trace = log.debugging(); if (trace) { log.debug("[StructTrace] ORIGIN chunk=" + cx + "," + cz + " structures=" + placement.structures() + " anchor=" + placement.resolvedAnchor() + " band=" + placement.minHeight() + ".." + placement.maxHeight()); @@ -124,21 +130,20 @@ public class StructurePlacing { } if (!placement.isAnchoredUnderground()) { - clearIntersectingObjectTrees(writer, resolved); + clearIntersectingObjectTrees(context, resolved); } StructureTerrain terrain = placement.resolvedTerrain(); StructureTerrainMode terrainMode = terrain.resolvedMode(); if (terrainMode == StructureTerrainMode.FORCE_CARVE) { - forceCarveStructure(writer, pieces, terrain); + forceCarveStructure(context, pieces, terrain); } else if (terrainMode == StructureTerrainMode.BORE) { - boreStructure(writer, pieces, terrain); + boreStructure(context, pieces, terrain); } else if (terrainMode != StructureTerrainMode.PRESERVE && terrainMode != StructureTerrainMode.SOURCE) { throw new IllegalStateException("Iris assembly terrain mode " + terrainMode + " is not implemented for structure '" + key + "'"); } - ObjectPlaceMode mode = stamp.placeMode(); int failedPieces = 0; StructureStilts stilt = placement.stilt().orElse(null); @@ -149,87 +154,88 @@ public class StructurePlacing { ObjectPlaceMode undergroundMode = mode.placeMode().has(PlaceTrait.CAVE_ANCHORED) ? mode : ObjectPlaceMode.STRUCTURE_PIECE; for (AssembledPiece p : pieces) { - if (placeObject(writer, key, stamp, p, undergroundMode, p.y(), rng, - foundationColumns, supportNonOccluding) == -1) { + if (placeObject(context, key, stamp, p, undergroundMode, p.y(), + foundationColumns, supportNonOccluding) == REJECTED_PIECE) { failedPieces++; } } } else if (mode.placeMode().has(PlaceTrait.FREE_HEIGHT)) { for (AssembledPiece p : pieces) { - if (placeObject(writer, key, stamp, p, ObjectPlaceMode.STRUCTURE_PIECE, p.y(), rng, - foundationColumns, supportNonOccluding) == -1) { + if (placeObject(context, key, stamp, p, ObjectPlaceMode.STRUCTURE_PIECE, p.y(), + foundationColumns, supportNonOccluding) == REJECTED_PIECE) { failedPieces++; } } } else if (pieces.size() == 1) { - if (placeObject(writer, key, stamp, pieces.getFirst(), mode, -1, rng, - foundationColumns, supportNonOccluding) == -1) { + if (placeObject(context, key, stamp, pieces.getFirst(), mode, SAMPLED_HEIGHT, + foundationColumns, supportNonOccluding) == REJECTED_PIECE) { failedPieces++; } } else { for (AssembledPiece p : pieces) { - if (placeObject(writer, key, stamp, p, ObjectPlaceMode.STRUCTURE_PIECE, p.y(), rng, - foundationColumns, supportNonOccluding) == -1) { + if (placeObject(context, key, stamp, p, ObjectPlaceMode.STRUCTURE_PIECE, p.y(), + foundationColumns, supportNonOccluding) == REJECTED_PIECE) { failedPieces++; } } } requireAppliedPieces(resolved, cx, cz, failedPieces); if (failedPieces == 0 && stilt != null) { - placeFoundation(writer, foundationColumns, stilt, rng, !placement.isAnchoredUnderground()); + placeFoundation(context, foundationColumns, stilt, rng, !placement.isAnchoredUnderground()); } } - private void placeFoundation(MantleWriter writer, ColumnHeights columns, + private void placeFoundation(MantleStageContext context, ColumnHeights columns, StructureStilts settings, RNG rng, boolean surfaceStructure) { PaletteSpec palette = settings.palette().orElseThrow( () -> new NullPointerException("Structure stilt palette must not be null")); - PaletteSampler picker = engine.getData().getPackResources().blocks().palette(palette, rng.getSeed()); - int mantleOffset = engine.getMinHeight(); + BlockRegistry blocks = world.resources().blocks(); + PaletteSampler picker = blocks.palette(palette, rng.getSeed()); + Mantle mantle = context.mantle(); + PlacementTerrain terrain = context.placementTerrain(); + RunningWorld running = StructureWorld.running(world); + int mantleOffset = world.minWorldY(); int maxDepth = Math.max(1, settings.maxDepth()); columns.forEach((column, foundationY) -> { int worldX = StructureFoundationPlanner.unpackX(column); int worldZ = StructureFoundationPlanner.unpackZ(column); - PlatformBlockState foundationState = writer.getDataIfPresent( - worldX, foundationY, worldZ, PlatformBlockState.class); - if (foundationState == null || !foundationState.isSolid()) { + BlockState foundationState = mantle.blocks().get(worldX, foundationY, worldZ); + if (foundationState == null || !blocks.hasTrait(foundationState, BlockTrait.SOLID)) { return; } - int terrainHeight = engine.getMantle().trueHeight(worldX, worldZ); + int terrainHeight = running.layout().surfaceHeight(worldX, worldZ); int groundY = StructureFoundationPlanner.findGroundY( foundationY, maxDepth, 0, y -> { - PlatformBlockState overlay = writer.getDataIfPresent( - worldX, y, worldZ, PlatformBlockState.class); - boolean carved = writer.getDataIfPresent( - worldX, y, worldZ, MatterCavern.class) != null; + BlockState overlay = mantle.blocks().get(worldX, y, worldZ); + boolean carved = mantle.carved().get(worldX, y, worldZ) != null; return surfaceStructure ? StructureFoundationPlanner.isSurfaceSupportBoundary( - overlay, carved, y, terrainHeight) + overlay, blocks, carved, y, terrainHeight) : StructureFoundationPlanner.isGroundSolid( - overlay, carved, y, terrainHeight); + overlay, blocks, carved, y, terrainHeight); }); if (groundY == StructureFoundationPlanner.NO_GROUND) { return; } StructureFoundationPlanner.fillSupportColumn(foundationY, groundY, y -> { - writeFoundationSupport(writer, picker, worldX, y, worldZ, mantleOffset); + writeFoundationSupport(terrain, mantle, picker, worldX, y, worldZ, mantleOffset); }); }); } /** Writes the stilt palette's block at the column's mantle height, clearing any carve there. */ - static void writeFoundationSupport(MantleWriter writer, PaletteSampler picker, int worldX, int mantleY, int worldZ, - int mantleOffset) { + static void writeFoundationSupport(PlacementTerrain terrain, Mantle mantle, PaletteSampler picker, int worldX, + int mantleY, int worldZ, int mantleOffset) { int worldY = mantleY + mantleOffset; - PlatformBlockState support = B.getState(picker.at(worldX, worldY, worldZ).key()); + BlockState support = picker.at(worldX, worldY, worldZ); if (support == null) { throw new IllegalStateException("Structure stilt palette resolved no block at " + worldX + "," + worldY + "," + worldZ); } - writer.clearData(worldX, mantleY, worldZ, MatterCavern.class); - writer.set(worldX, mantleY, worldZ, support); + mantle.carved().remove(worldX, mantleY, worldZ); + terrain.set(worldX, mantleY, worldZ, support); } static KList resolvedPiecesOrNull( @@ -257,7 +263,7 @@ public class StructurePlacing { + " assembled piece(s)"); } - private void boreStructure(MantleWriter writer, KList pieces, + private void boreStructure(MantleStageContext context, KList pieces, StructureTerrain terrain) { int[] bounds = computePieceBounds(pieces); if (bounds == null) { @@ -270,24 +276,24 @@ public class StructurePlacing { int maxX = bounds[3] + pad; int maxY = bounds[4] + Math.max(0, terrain.ceilingPadding()); int maxZ = bounds[5] + pad; - int worldMin = engine.getMinHeight() + 1; - int worldMax = engine.getMinHeight() + engine.getHeight() - 1; + int worldMin = world.minWorldY() + 1; + int worldMax = world.minWorldY() + StructureWorld.height(world) - 1; minY = Math.max(minY, worldMin); maxY = Math.min(maxY, worldMax); if (maxX < minX || maxY < minY || maxZ < minZ) { return; } - int mantleOffset = engine.getMinHeight(); + int mantleOffset = world.minWorldY(); for (int bx = minX; bx <= maxX; bx++) { for (int by = minY; by <= maxY; by++) { for (int bz = minZ; bz <= maxZ; bz++) { - writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN); + carve(context, bx, by - mantleOffset, bz); } } } } - private void forceCarveStructure(MantleWriter writer, KList pieces, + private void forceCarveStructure(MantleStageContext context, KList pieces, StructureTerrain terrain) { int[] bounds = computePieceBounds(pieces); if (bounds == null) { @@ -298,13 +304,13 @@ public class StructurePlacing { int head = Math.max(0, terrain.ceilingPadding()); int floorCut = Math.max(0, terrain.floorPadding()); double strength = terrain.resolvedErosionStrength(); - int mantleOffset = engine.getMinHeight(); - int worldMin = engine.getMinHeight() + 1; - int worldMax = engine.getMinHeight() + engine.getHeight() - 1; + int mantleOffset = world.minWorldY(); + int worldMin = world.minWorldY() + 1; + int worldMax = world.minWorldY() + StructureWorld.height(world) - 1; int upExtension = shape.maximumCeilingExtension(head, strength); if (shape == StructureCarveShape.BOX) { - carveOverboreBox(writer, bounds, margin, head, floorCut, mantleOffset, worldMin, worldMax); + carveOverboreBox(context, bounds, margin, head, floorCut, mantleOffset, worldMin, worldMax); return; } @@ -317,15 +323,15 @@ public class StructurePlacing { double frequency = terrain.resolvedErosionFrequency(); boolean eroded = shape == StructureCarveShape.ERODED && strength > 0D; - CNG blob = null; - CNG roll = null; + NoiseSampler blob = null; + NoiseSampler roll = null; if (eroded) { - RNG noiseRng = new RNG(engine.getSeedManager().getMantle() + CacheKey.key(bounds[0], bounds[2])); - blob = CNG.signature(noiseRng); - roll = CNG.signature(noiseRng.nextParallelRNG(0x2A17)); + long noiseSeed = StructureWorld.placementSeed(world) + CacheKey.key(bounds[0], bounds[2]); + blob = world.resources().noise().sampler(CARVE_NOISE, noiseSeed); + roll = world.resources().noise().sampler(CARVE_NOISE, noiseSeed + CARVE_ROLL_SIGNATURE); } - if (IrisSettings.get().getGeneral().isDebug()) { + if (log.debugging()) { log.info("Overbore carving structure cavern: shape=" + shape + " pieces=" + pieces.size() + " footprint=" + footprint.width() + "x" + footprint.depth() + " margin=" + margin + " head=" + head + " floorCut=" + floorCut + " work=" + work); @@ -357,28 +363,27 @@ public class StructurePlacing { double distanceSquared = normalizedHorizontalDistanceSquared + normalizedY * normalizedY; if (distanceSquared <= 0D) { - writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN); + carve(context, bx, by - mantleOffset, bz); continue; } if (distanceSquared > 1D) { continue; } if (!eroded) { - writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN); + carve(context, bx, by - mantleOffset, bz); continue; } - double noise = blob.fitDouble( - 0D, 1D, bx * frequency, by * frequency, bz * frequency); + double noise = blob.sample(bx * frequency, by * frequency, bz * frequency); if (StructureCarveEnvelope.shouldCarveOverboreCell( shape, distanceSquared, noise, strength)) { - writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN); + carve(context, bx, by - mantleOffset, bz); } } } } } - private void carveOverboreBox(MantleWriter writer, int[] bounds, int margin, int head, int floorCut, + private void carveOverboreBox(MantleStageContext context, int[] bounds, int margin, int head, int floorCut, int mantleOffset, int worldMin, int worldMax) { int minX = bounds[0] - margin; int minY = Math.max(worldMin, bounds[1] - floorCut); @@ -389,12 +394,18 @@ public class StructurePlacing { for (int bx = minX; bx <= maxX; bx++) { for (int by = minY; by <= maxY; by++) { for (int bz = minZ; bz <= maxZ; bz++) { - writer.setForcedCarve(bx, by - mantleOffset, bz, CARVE_CAVERN); + carve(context, bx, by - mantleOffset, bz); } } } } + /** Carves the block open for good: the void is planned and any block a placement wrote there is taken back. */ + private static void carve(MantleStageContext context, int x, int mantleY, int z) { + context.placementTerrain().clearBlock(x, mantleY, z); + context.mantle().carved().set(x, mantleY, z, CARVE_VOID); + } + private static long overboreCandidateVolume(int[] bounds, int margin, int upExtension, int floorCut) { return inclusiveVolume( @@ -414,96 +425,82 @@ public class StructurePlacing { return width * height * depth; } - private void clearIntersectingObjectTrees(MantleWriter writer, IrisStructureLocator.ResolvedPlacement resolved) { - int mantleOffset = engine.getMinHeight(); - int worldHeight = engine.getHeight(); - Map intersectingObjects = new HashMap<>(); + private void clearIntersectingObjectTrees(MantleStageContext context, IrisStructureLocator.ResolvedPlacement resolved) { + BlockRegistry blocks = world.resources().blocks(); + int mantleOffset = world.minWorldY(); + int worldHeight = StructureWorld.height(world); + Map intersectingObjects = new HashMap<>(); for (AssembledPiece piece : resolved.pieces()) { - IrisObject object = objectOf(piece); - for (IrisBlockVector local : object.getBlocks().keys()) { - PlatformBlockState structureState = object.getBlocks().get(local); - if (!isOccupiedStructureState(structureState)) { + for (ObjectBlock block : objectOf(piece).geometry().blocks()) { + if (!isOccupiedStructureState(block.state(), blocks)) { continue; } - BlockPosition rotated = piece.turn().rotate( - new BlockPosition(local.getBlockX(), local.getBlockY(), local.getBlockZ())); + BlockPosition rotated = piece.turn().rotate(block.position()); int y = piece.y() - mantleOffset + rotated.y(); if (y >= 0 && y < worldHeight) { - collectIntersectingObjectTreeMarker( - writer, piece.x() + rotated.x(), y, + collectIntersectingObjectTree( + context, piece.x() + rotated.x(), y, piece.z() + rotated.z(), intersectingObjects); } } } - for (Map.Entry entry : intersectingObjects.entrySet()) { - clearMarkerOwnedObject(writer, entry.getKey(), entry.getValue(), worldHeight); + for (Map.Entry entry : intersectingObjects.entrySet()) { + clearRecordOwnedObject(context, entry.getKey(), entry.getValue(), worldHeight); } } - static boolean isOccupiedStructureState(PlatformBlockState state) { - return !B.isAir(state); + static boolean isOccupiedStructureState(BlockState state, BlockRegistry blocks) { + return state != null && !blocks.hasTrait(state, BlockTrait.AIR); } - private void collectIntersectingObjectTreeMarker(MantleWriter writer, int x, int y, int z, - Map intersectingObjects) { - PlatformBlockState state = writer.getDataIfPresent(x, y, z, PlatformBlockState.class); - if (state == null || !state.isTreeBlock()) { + private void collectIntersectingObjectTree(MantleStageContext context, int x, int y, int z, + Map intersectingObjects) { + BlockState state = context.mantle().blocks().get(x, y, z); + if (state == null || !isTreeBlock(state)) { return; } - String marker = writer.getDataIfPresent(x, y, z, String.class); - if (isOrdinaryObjectMarker(marker)) { - intersectingObjects.computeIfAbsent(marker, ignored -> new ObjectMarkerBounds()) + Optional record = StructureWorld.running(world).placementAt(x, y, z); + if (isOrdinaryObjectRecord(record)) { + intersectingObjects.computeIfAbsent(record.get(), ignored -> new ObjectMarkerBounds()) .include(x, y, z); } } - private void clearMarkerOwnedObject(MantleWriter writer, String marker, + private boolean isTreeBlock(BlockState state) { + BlockRegistry blocks = world.resources().blocks(); + return blocks.hasTrait(state, BlockTrait.LOG) || blocks.hasTrait(state, BlockTrait.LEAVES); + } + + private void clearRecordOwnedObject(MantleStageContext context, PlacementRecord record, ObjectMarkerBounds intersections, int worldHeight) { - PlacementMarkers.Decoded decoded = PlacementMarkers.decode(marker); - if (decoded == null) { + Optional object = world.resources().objects().object(record.object()); + if (object.isEmpty()) { return; } - IrisObject object = engine.getData().load(IrisObject.class, decoded.objectKey(), false); - if (object == null) { - return; - } - int horizontalSpan = Math.max(1, Math.max(object.getW(), object.getD())); - int verticalSpan = Math.max(1, object.getH()); + int horizontalSpan = Math.max(1, Math.max(object.get().width(), object.get().depth())); + int verticalSpan = Math.max(1, object.get().height()); ObjectMarkerBounds search = intersections.expand(horizontalSpan - 1, verticalSpan - 1, worldHeight); - KList positions = new KList<>(); - int minChunkX = Math.floorDiv(search.minX, 16); - int maxChunkX = Math.floorDiv(search.maxX, 16); - int minChunkZ = Math.floorDiv(search.minZ, 16); - int maxChunkZ = Math.floorDiv(search.maxZ, 16); - for (int chunkX = minChunkX; chunkX <= maxChunkX; chunkX++) { - for (int chunkZ = minChunkZ; chunkZ <= maxChunkZ; chunkZ++) { - MantleChunk chunk = writer.acquireChunk(chunkX, chunkZ); - if (chunk == null) { - continue; - } - int blockX = chunkX << 4; - int blockZ = chunkZ << 4; - chunk.iterate(String.class, (localX, y, localZ, value) -> { - int x = blockX + localX; - int z = blockZ + localZ; - if (marker.equals(value) && search.contains(x, y, z)) { + BlockBox prepared = context.mantle().bounds(); + RunningWorld running = StructureWorld.running(world); + PlacementTerrain terrain = context.placementTerrain(); + List positions = new ArrayList<>(); + for (int x = search.minX; x <= search.maxX; x++) { + for (int y = search.minY; y <= search.maxY; y++) { + for (int z = search.minZ; z <= search.maxZ; z++) { + if (prepared.contains(x, y, z) && running.placementAt(x, y, z).filter(record::equals).isPresent()) { positions.add(new ObjectBlockPosition(x, y, z)); } - }); + } } } for (ObjectBlockPosition position : positions) { - writer.clearBlock(position.x(), position.y(), position.z()); - writer.clearData(position.x(), position.y(), position.z(), String.class); - writer.clearData(position.x(), position.y(), position.z(), TreeBlockMaterial.class); - writer.clearData(position.x(), position.y(), position.z(), TileWrapper.class); - writer.clearData(position.x(), position.y(), position.z(), MatterStructurePOI.class); + terrain.clearBlock(position.x(), position.y(), position.z()); + terrain.clearAttached(position.x(), position.y(), position.z()); } } - static boolean isOrdinaryObjectMarker(String marker) { - PlacementMarkers.Decoded decoded = PlacementMarkers.decode(marker); - return decoded != null && !decoded.structureAware(); + static boolean isOrdinaryObjectRecord(Optional record) { + return record.isPresent() && record.get().structure().isEmpty(); } static ObjectMarkerBounds markerSearchBounds(int minX, int minY, int minZ, @@ -522,25 +519,19 @@ public class StructurePlacing { } private List blocksOf(AssembledPiece piece) { - IrisObject object = objectOf(piece); - if (object == null || object.getBlocks() == null) { - return null; + BlockRegistry blocks = world.resources().blocks(); + List pieceBlocks = new ArrayList<>(); + for (ObjectBlock block : objectOf(piece).geometry().blocks()) { + pieceBlocks.add(new StructurePieceColumns.PieceBlock( + block.position(), blocks.hasTrait(block.state(), BlockTrait.AIR))); } - List blocks = new ArrayList<>(); - for (IrisBlockVector local : object.getBlocks().keys()) { - if (local != null) { - blocks.add(new StructurePieceColumns.PieceBlock( - new BlockPosition(local.getBlockX(), local.getBlockY(), local.getBlockZ()), - B.isAir(object.getBlocks().get(local)))); - } - } - return blocks; + return pieceBlocks; } - /** The object of {@code piece}, loaded from the engine's pack. */ - private IrisObject objectOf(AssembledPiece piece) { - String key = engine.getData().getPackResources().keyOf(piece.object()); - return engine.getData().load(IrisObject.class, key, false); + /** The object of {@code piece}, loaded from the world's pack. */ + private PlaceableObject objectOf(AssembledPiece piece) { + return world.resources().objects().object(piece.object()) + .orElseThrow(() -> new IllegalStateException("Structure piece object " + piece.object() + " is missing")); } private int[] computePieceBounds(KList pieces) { @@ -583,11 +574,11 @@ public class StructurePlacing { return placement.loot(loot); } - private int placeObject(MantleWriter writer, String structureKey, StructureStamp stamp, AssembledPiece p, - ObjectPlaceMode mode, int y, RNG rng, ColumnHeights foundationColumns, + private int placeObject(MantleStageContext context, String structureKey, StructureStamp stamp, AssembledPiece p, + ObjectPlaceMode mode, int y, ColumnHeights foundationColumns, boolean supportNonOccluding) { - IrisObject object = objectOf(p); - String objectKey = object.getLoadKey(); + PlaceableObject object = objectOf(p); + String objectKey = object.name(); ObjectPlacement.Builder builder = lootPlacementBuilder(stamp, objectKey).mode(mode).rotation(moduleRotation(p.turn())); if (!stamp.edits().isEmpty()) { builder.edit(new KList<>(stamp.edits())); @@ -596,16 +587,32 @@ public class StructurePlacing { builder.forcePlace(true); } ObjectPlacement config = builder.build(); - int placeY = (y == -1) ? -1 : y - engine.getMinHeight(); - String marker = structurePlacementMarker(structureKey, p, objectKey); - return ModuleObjectPlacement.place(object, p.x(), placeY, p.z(), writer, config, rng, (position, state) -> { + int placeY = (y == SAMPLED_HEIGHT) ? SAMPLED_HEIGHT : y - world.minWorldY(); + PlacementTerrain terrain = context.placementTerrain(); + ObjectRun run = ObjectRun.of(object, config, p.x(), placeY, p.z()); + PlacementOutcome outcome = run.placeIn(world, terrain); + if (!outcome.isPlaced()) { + return REJECTED_PIECE; + } + recordPieceBlocks(terrain, run, structureKey, p, objectKey, foundationColumns, supportNonOccluding); + return run.anchorY().orElseThrow(() -> new IllegalStateException( + "The placement graph placed " + objectKey + " without anchoring it")); + } + + /** Notes each block the piece wrote as a base cell of the foundation, and marks its storage blocks as the structure's. */ + private void recordPieceBlocks(PlacementTerrain terrain, ObjectRun run, String structureKey, AssembledPiece piece, + String objectKey, ColumnHeights foundationColumns, boolean supportNonOccluding) { + BlockRegistry blocks = world.resources().blocks(); + PlacementRecord record = structurePlacementRecord(structureKey, piece, objectKey); + for (BlockPosition position : run.objectBlocks()) { + BlockState state = terrain.get(position.x(), position.y(), position.z()); StructureFoundationPlanner.recordBaseCell( - foundationColumns, position.getX(), position.getY(), position.getZ(), state, + foundationColumns, position.x(), position.y(), position.z(), state, blocks, supportNonOccluding); - if (marker != null && shouldWriteStructureMarker(state)) { - writer.setData(position.getX(), position.getY(), position.getZ(), marker); + if (record != null && shouldWriteStructureMarker(state, blocks)) { + terrain.recordPlacement(position.x(), position.y(), position.z(), record); } - }, null, engine.getData()).heightOrRejected(); + } } /** The placement rotation that turns a placed piece the way {@code turn} does. */ @@ -613,8 +620,8 @@ public class StructurePlacing { return ObjectRotation.of(0, turn.yDegrees(), 0); } - static boolean shouldWriteStructureMarker(PlatformBlockState state) { - return state != null && state.isStorageChest(); + static boolean shouldWriteStructureMarker(BlockState state, BlockRegistry blocks) { + return state != null && blocks.hasTrait(state, BlockTrait.STORAGE); } static int structurePlacementId(String structureKey, String objectKey, int x, int y, int z) { @@ -627,27 +634,21 @@ public class StructurePlacing { return hash & Integer.MAX_VALUE; } - private static String structurePlacementMarker(String structureKey, AssembledPiece piece, String objectKey) { + private PlacementRecord structurePlacementRecord(String structureKey, AssembledPiece piece, String objectKey) { if (structureKey == null || structureKey.isBlank() || objectKey == null || objectKey.isBlank()) { return null; } + PackResources pack = world.resources(); int placementId = structurePlacementId(structureKey, objectKey, piece.x(), piece.y(), piece.z()); - return PlacementMarkers.encodeStructure(objectKey, placementId, structureKey); + return PlacementRecord.ofPiece(pack.idOf(objectKey), placementId, pack.idOf(structureKey)); } /** How far, in blocks along X and Z, placements may write beyond their chunk. */ public int reach() { - IrisDimension dimension = engine.getDimension(); int maxBlocks = 0; - - for (IrisRegion region : dimension.getAllRegions(engine)) { - maxBlocks = Math.max(maxBlocks, maxBlocksFrom(StructurePlacementScope.placementsOf(region))); + for (var declared : world.settings().declared(StructurePlacementSettings.class)) { + maxBlocks = Math.max(maxBlocks, maxBlocksFrom(declared.value().placements())); } - for (IrisBiome biome : dimension.getReachableBiomes(engine)) { - maxBlocks = Math.max(maxBlocks, maxBlocksFrom(StructurePlacementScope.placementsOf(biome))); - } - maxBlocks = Math.max(maxBlocks, maxBlocksFrom(StructurePlacementScope.placementsOf(dimension))); - return maxBlocks; } @@ -662,9 +663,9 @@ public class StructurePlacing { || terrain.resolvedMode() == StructureTerrainMode.BORE ? Math.max(0, terrain.horizontalPadding()) : 0; for (String key : placement.structures()) { - var pack = engine.getData().getPackResources(); + PackResources pack = world.resources(); var structure = pack.idOf(key); - StructureAssembly provider = IrisStructureLocator.providerOf(engine, structure); + StructureAssembly provider = IrisStructureLocator.providerOf(world, structure); if (provider != null) { max = Math.max(max, Math.max(1, provider.reachChunks(pack, structure).orElse(1)) * 16 + carvePadding); } diff --git a/core/src/main/java/art/arcane/iris/engine/object/placement/IObjectPlacer.java b/core/src/main/java/art/arcane/iris/engine/object/placement/IObjectPlacer.java index 07eefa63e..feffe851d 100644 --- a/core/src/main/java/art/arcane/iris/engine/object/placement/IObjectPlacer.java +++ b/core/src/main/java/art/arcane/iris/engine/object/placement/IObjectPlacer.java @@ -58,4 +58,12 @@ public interface IObjectPlacer { @Nullable T getData(int xx, int yy, int zz, Class t); Engine getEngine(); + + default void clearBlock(int x, int y, int z) { + throw new UnsupportedOperationException("This placer cannot take blocks back"); + } + + default void clearAttached(int x, int y, int z) { + throw new UnsupportedOperationException("This placer cannot take what is kept beside a block back"); + } } diff --git a/core/src/test/java/art/arcane/iris/core/modules/IrisTestNoise.java b/core/src/test/java/art/arcane/iris/core/modules/IrisTestNoise.java new file mode 100644 index 000000000..3e28ec00d --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/modules/IrisTestNoise.java @@ -0,0 +1,22 @@ +package art.arcane.iris.core.modules; + +import art.arcane.iris.core.loader.IrisData; +import com.volmit.noise.NoiseFactory; + +import java.io.File; +import java.util.List; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** Iris's own noise factory over an empty pack, for tests that need the very noise generation reads. */ +public final class IrisTestNoise { + private IrisTestNoise() { + } + + public static NoiseFactory factory() { + IrisData data = mock(IrisData.class); + when(data.getDataFolder()).thenReturn(new File("test-pack")); + return new IrisNoiseFactory(data, new IrisPackResources(data, List::of)); + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/framework/IrisStructureLocatorContractTest.java b/core/src/test/java/art/arcane/iris/engine/framework/IrisStructureLocatorContractTest.java index 8af664cef..ef08b5fa8 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/IrisStructureLocatorContractTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/IrisStructureLocatorContractTest.java @@ -30,13 +30,12 @@ import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.structure.StructureGraphCatalog; import art.arcane.iris.engine.object.structure.jigsaw.JigsawDirection; import com.volmit.geometry.BlockPosition; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; +import art.arcane.iris.engine.framework.structure.JigsawStructureAssembly; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceEntry; import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; import art.arcane.iris.builtin.structure.NativeStructureSource; -import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.engine.object.structure.IrisStructure; import art.arcane.iris.builtin.structure.StructureAnchorMode; import art.arcane.iris.builtin.structure.StructurePlacement; @@ -47,6 +46,9 @@ import art.arcane.volmlib.util.math.RNG; import com.volmit.host.ModuleLogs; import org.junit.Test; +import com.volmit.world.PackWorld; + +import java.util.ArrayList; import java.util.List; import java.util.Set; import art.arcane.iris.engine.framework.structure.assembly.AssembledPiece; @@ -88,16 +90,15 @@ public class IrisStructureLocatorContractTest { @Test public void isPlacedIsFalseForNullOrEmptyKey() { - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - assertFalse(IrisStructureLocator.isPlaced(engine, null)); - assertFalse(IrisStructureLocator.isPlaced(engine, "")); + StructureTestWorld world = new StructureTestWorld(); + assertFalse(IrisStructureLocator.isPlaced(world, null)); + assertFalse(IrisStructureLocator.isPlaced(world, "")); } @Test public void locatablePlacementsExcludeDisabledDensityConfigurations() { - Engine disabled = densityEngine(0.0, false, -64, 384, -2032, 2032); - Engine active = densityEngine(0.01, false, -64, 384, -2032, 2032); + StructureTestWorld disabled = densityWorld(0.0, false, -64, 384, -2032, 2032); + StructureTestWorld active = densityWorld(0.01, false, -64, 384, -2032, 2032); assertTrue(IrisStructureLocator.isPlaced(disabled, "test:density")); assertFalse(IrisStructureLocator.hasLocatablePlacement(disabled, "test:density")); @@ -110,12 +111,10 @@ public class IrisStructureLocatorContractTest { @Test public void locatablePlacementsExcludeEveryDistributionOutsideWorldHeight() { - Engine randomSpread = densityEngine(1.0, false, -64, 384, 400, 500); - TestSettings.with(StructurePlacementScope.placementsOf(randomSpread.getDimension()).get(0), - "distribution", StructureDistribution.RANDOM_SPREAD); - Engine concentricRings = densityEngine(1.0, false, -64, 384, 400, 500); - TestSettings.with(StructurePlacementScope.placementsOf(concentricRings.getDimension()).get(0), - "distribution", StructureDistribution.CONCENTRIC_RINGS); + StructureTestWorld randomSpread = densityWorld(1.0, false, -64, 384, 400, 500); + TestSettings.with(densityPlacement(randomSpread), "distribution", StructureDistribution.RANDOM_SPREAD); + StructureTestWorld concentricRings = densityWorld(1.0, false, -64, 384, 400, 500); + TestSettings.with(densityPlacement(concentricRings), "distribution", StructureDistribution.CONCENTRIC_RINGS); assertFalse(IrisStructureLocator.hasLocatablePlacement(randomSpread, "test:density")); assertFalse(IrisStructureLocator.hasLocatablePlacement(concentricRings, "test:density")); @@ -133,19 +132,7 @@ public class IrisStructureLocatorContractTest { withAdded(editable, "structures", "test:city_definition"); StructurePlacement nativePlacement = new StructurePlacement(); withAdded(nativePlacement, "nativeStructures", nativeSource("source:native_city")); - IrisDimension dimension = mock(IrisDimension.class); - KList placements = new KList<>(); - placements.add(editable); - placements.add(nativePlacement); - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(engine.getData()).thenReturn(data); - when(engine.getDimension()).thenReturn(dimension); - when(engine.getMinHeight()).thenReturn(-64); - when(engine.getHeight()).thenReturn(384); - when(dimension.getModuleSettings()).thenReturn(declaring(placements)); - when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); - when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); + StructureTestWorld engine = jigsawWorld(data).dimension(editable, nativePlacement); assertEquals(Set.of("test:city_definition", "source:city", "source:native_city"), IrisStructureLocator.locatableKeys(engine)); @@ -167,18 +154,9 @@ public class IrisStructureLocatorContractTest { public void nativeStructureReplacementSuppressesOnlyItsRegisteredSource() { IrisData data = mock(IrisData.class); ModuleResourceFixture.serveModules(data, new StructureModelModule(), new StructureModule()); - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - IrisDimension dimension = mock(IrisDimension.class); StructurePlacement placement = placement("nativeSuppression", NativeStructureSuppression.REPLACE_SOURCE); withAdded(placement, "nativeStructures", nativeSource("minecraft:ancient_city")); - KList placements = new KList<>(); - placements.add(placement); - when(engine.getData()).thenReturn(data); - when(engine.getDimension()).thenReturn(dimension); - when(dimension.getModuleSettings()).thenReturn(declaring(placements)); - when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); - when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); + StructureTestWorld engine = jigsawWorld(data).dimension(placement); assertTrue(IrisStructureLocator.isPlaced(engine, "minecraft:ancient_city")); assertTrue(IrisStructureLocator.suppressesVanilla(engine, "minecraft:ancient_city")); @@ -187,10 +165,9 @@ public class IrisStructureLocatorContractTest { @Test public void suppressesVanillaIsFalseForNullOrEmptyKey() { - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - assertFalse(IrisStructureLocator.suppressesVanilla(engine, null)); - assertFalse(IrisStructureLocator.suppressesVanilla(engine, "")); + StructureTestWorld world = new StructureTestWorld(); + assertFalse(IrisStructureLocator.suppressesVanilla(world, null)); + assertFalse(IrisStructureLocator.suppressesVanilla(world, "")); } @Test @@ -204,23 +181,12 @@ public class IrisStructureLocatorContractTest { StructurePlacement placement = new StructurePlacement(); withAdded(placement, "structures", "test:city"); - IrisDimension dimension = mock(IrisDimension.class); - KList placements = new KList<>(); - placements.add(placement); - when(dimension.getModuleSettings()).thenReturn(declaring(placements)); - when(dimension.getAllRegions(any())).thenReturn(new KList<>()); - when(dimension.getReachableBiomes(any())).thenReturn(new KList<>()); - - Engine engine = mock(Engine.class); - - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(engine.getData()).thenReturn(data); - when(engine.getDimension()).thenReturn(dimension); + StructureTestWorld engine = jigsawWorld(data).dimension(placement); assertTrue(IrisStructureLocator.isPlaced(engine, "minecraft:ancient_city")); assertFalse(IrisStructureLocator.suppressesVanilla(engine, "minecraft:ancient_city")); TestSettings.with(placement, "nativeSuppression", NativeStructureSuppression.REPLACE_SOURCE); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); + engine = jigsawWorld(data).dimension(placement); assertTrue(IrisStructureLocator.suppressesVanilla(engine, "minecraft:ancient_city")); } @@ -236,18 +202,7 @@ public class IrisStructureLocatorContractTest { StructurePlacement placement = new StructurePlacement(); withAdded(placement, "structures", "test:city"); TestSettings.with(placement, "nativeSuppression", NativeStructureSuppression.REPLACE_SOURCE); - IrisRegion region = mock(IrisRegion.class); - when(region.getModuleSettings()).thenReturn(declaring(new KList().qadd(placement))); - IrisDimension dimension = mock(IrisDimension.class); - when(dimension.getModuleSettings()).thenReturn(declaring(new KList<>())); - when(dimension.getAllRegions(any())).thenReturn(new KList().qadd(region)); - when(dimension.getReachableBiomes(any())).thenReturn(new KList<>()); - - Engine engine = mock(Engine.class); - - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(engine.getData()).thenReturn(data); - when(engine.getDimension()).thenReturn(dimension); + StructureTestWorld engine = jigsawWorld(data).region(StructureTestWorld.REGION, placement); assertReplacementFailure( () -> IrisStructureLocator.suppressesVanilla(engine, "minecraft:ancient_city"), @@ -293,14 +248,7 @@ public class IrisStructureLocatorContractTest { StructurePlacement placement = placement("nativeSuppression", NativeStructureSuppression.REPLACE_SOURCE); withAdded(placement, "structures", "test:city"); - IrisDimension dimension = mock(IrisDimension.class); - when(dimension.getModuleSettings()).thenReturn(declaring(new KList().qadd(placement))); - when(dimension.getAllRegions(any())).thenReturn(new KList<>()); - when(dimension.getReachableBiomes(any())).thenReturn(new KList<>()); - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(engine.getData()).thenReturn(data); - when(engine.getDimension()).thenReturn(dimension); + StructureTestWorld engine = jigsawWorld(data).dimension(placement); assertReplacementFailure( () -> IrisStructureLocator.suppressesVanilla(engine, "minecraft:ancient_city"), @@ -316,14 +264,7 @@ public class IrisStructureLocatorContractTest { registerSinglePieceGraph(data, structure, "test:city"); StructurePlacement placement = placement("nativeSuppression", NativeStructureSuppression.REPLACE_SOURCE); withAdded(placement, "structures", "test:city"); - IrisDimension dimension = mock(IrisDimension.class); - when(dimension.getModuleSettings()).thenReturn(declaring(new KList().qadd(placement))); - when(dimension.getAllRegions(any())).thenReturn(new KList<>()); - when(dimension.getReachableBiomes(any())).thenReturn(new KList<>()); - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(engine.getData()).thenReturn(data); - when(engine.getDimension()).thenReturn(dimension); + StructureTestWorld engine = jigsawWorld(data).dimension(placement); assertReplacementFailure( () -> IrisStructureLocator.suppressesVanilla(engine, "minecraft:ancient_city"), @@ -337,14 +278,7 @@ public class IrisStructureLocatorContractTest { ModuleResourceFixture.serve(data); StructurePlacement placement = new StructurePlacement(); withAdded(placement, "structures", "test:missing"); - IrisDimension dimension = mock(IrisDimension.class); - when(dimension.getModuleSettings()).thenReturn(declaring(new KList().qadd(placement))); - when(dimension.getAllRegions(any())).thenReturn(new KList<>()); - when(dimension.getReachableBiomes(any())).thenReturn(new KList<>()); - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(engine.getData()).thenReturn(data); - when(engine.getDimension()).thenReturn(dimension); + StructureTestWorld engine = jigsawWorld(data).dimension(placement); assertReplacementFailure( () -> IrisStructureLocator.isPlaced(engine, "test:missing"), @@ -352,10 +286,10 @@ public class IrisStructureLocatorContractTest { } @Test - public void placementResolutionRejectsAnUnboundEngine() { + public void placementResolutionRejectsAMissingWorld() { assertReplacementFailure( () -> IrisStructureLocator.resolvePlacement(null, new StructurePlacement(), 0, 0), - "fully bound engine"); + "requires a world"); } @Test @@ -393,54 +327,53 @@ public class IrisStructureLocatorContractTest { @Test public void locateReturnsNotFoundForNullOrEmptyKey() { - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); + StructureTestWorld world = new StructureTestWorld(); assertEquals(IrisStructureLocator.LocateStatus.NOT_FOUND, - IrisStructureLocator.locate(engine, null, 0, 0, 100).status()); + IrisStructureLocator.locate(world, null, 0, 0, 100).status()); assertEquals(IrisStructureLocator.LocateStatus.NOT_FOUND, - IrisStructureLocator.locate(engine, "", 0, 0, 100).status()); + IrisStructureLocator.locate(world, "", 0, 0, 100).status()); } @Test public void zeroDensityLocateReturnsWithoutScanningPlacementGraphs() { - Engine engine = densityEngine(0.0, false, -64, 384, -2032, 2032); + StructureTestWorld world = densityWorld(0.0, false, -64, 384, -2032, 2032); IrisStructureLocator.LocateResult result = - IrisStructureLocator.locate(engine, "test:density", 0, 0, 100); + IrisStructureLocator.locate(world, "test:density", 0, 0, 100); assertEquals(IrisStructureLocator.LocateStatus.NOT_FOUND, result.status()); - verify(engine, never()).getComplex(); + assertEquals(0, world.placementScans()); } @Test public void impossibleDensityHeightBandReturnsWithoutScanningPlacementGraphs() { - Engine engine = densityEngine(1.0, true, -64, 384, 500, 600); + StructureTestWorld world = densityWorld(1.0, true, -64, 384, 500, 600); IrisStructureLocator.LocateResult result = - IrisStructureLocator.locate(engine, "test:density", 0, 0, 100); + IrisStructureLocator.locate(world, "test:density", 0, 0, 100); assertEquals(IrisStructureLocator.LocateStatus.NOT_FOUND, result.status()); - verify(engine, never()).getComplex(); + assertEquals(0, world.placementScans()); } @Test public void densityLocateReportsSafetyLimitAfterFixedCandidateBudget() { - Engine engine = densityEngine(1.0, false, -64, 384, -2032, 2032); + StructureTestWorld world = densityWorld(1.0, false, -64, 384, -2032, 2032); IrisStructureLocator.LocateResult result = - IrisStructureLocator.locate(engine, "test:density", 0, 0, 2048); + IrisStructureLocator.locate(world, "test:density", 0, 0, 2048); assertEquals(IrisStructureLocator.LocateStatus.SEARCH_LIMIT_REACHED, result.status()); assertFalse(result.found()); - verify(engine, times(4_096)).getComplex(); + assertEquals(4_096, world.placementScans()); } @Test public void densityLocateDoesNotReturnPartialRingWinnerAtSafetyLimit() { - Engine engine = densityEngine(1.0, false, -64, 384, -2032, 2032); + StructureTestWorld world = densityWorld(1.0, false, -64, 384, -2032, 2032); IrisStructureLocator.LocateResult result = IrisStructureLocator.locate( - engine, "test:density", 0, 0, 2048, + world, "test:density", 0, 0, 2048, (chunkX, chunkZ) -> chunkX == 31 && chunkZ == 31 || chunkX == 0 && chunkZ == 32); @@ -450,7 +383,7 @@ public class IrisStructureLocatorContractTest { @Test public void zeroRadiusDoesNotSearchAdjacentDensityChunks() { - Engine engine = densityEngine(1.0, false, -64, 384, -2032, 2032); + StructureTestWorld engine = densityWorld(1.0, false, -64, 384, -2032, 2032); IrisStructureLocator.LocateResult result = IrisStructureLocator.locate( engine, "test:density", 0, 0, 0, @@ -461,10 +394,8 @@ public class IrisStructureLocatorContractTest { @Test public void locateRanksEditableStartsByResolvedBlockOrigin() { - Engine engine = densityEngine(1.0, false, -64, 384, -2032, 2032); - when(engine.getHeight(anyInt(), anyInt(), eq(true))).thenReturn(128); - when(engine.getDimension().getFluidHeight()).thenReturn(63); - StructurePlacement placement = StructurePlacementScope.placementsOf(engine.getDimension()).get(0); + StructureTestWorld engine = densityWorld(1.0, false, -64, 384, -2032, 2032).highest((x, z) -> 128).fluidHeight(63); + StructurePlacement placement = densityPlacement(engine); NearestScenario scenario = nearestEqualChunkDistanceScenario(engine, placement); assertNotNull(scenario); @@ -488,10 +419,7 @@ public class IrisStructureLocatorContractTest { @Test public void searchableDensityRequiresPositiveProbabilityAndWorldHeightOverlap() { - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(engine.getMinHeight()).thenReturn(-64); - when(engine.getHeight()).thenReturn(384); + StructureTestWorld engine = new StructureTestWorld(); StructurePlacement placement = new StructurePlacement(); TestSettings.with(placement, "distribution", StructureDistribution.DENSITY); TestSettings.with(placement, "minHeight", -32); @@ -512,14 +440,14 @@ public class IrisStructureLocatorContractTest { public void placementIndexIsKeptPerWorld() { IrisData sharedData = mock(IrisData.class); ModuleResourceFixture.serveModules(sharedData, new StructureModelModule(), new StructureModule()); - Engine firstEngine = emptyEngine(sharedData); - Engine secondEngine = emptyEngine(sharedData); - Set firstIndex = IrisStructureLocator.placedKeys(firstEngine); - assertSame(firstIndex, IrisStructureLocator.placedKeys(firstEngine)); - assertNotSame(firstIndex, IrisStructureLocator.placedKeys(secondEngine)); + StructureTestWorld firstWorld = emptyWorld(sharedData); + StructureTestWorld secondWorld = emptyWorld(sharedData); + Set firstIndex = IrisStructureLocator.placedKeys(firstWorld); + assertSame(firstIndex, IrisStructureLocator.placedKeys(firstWorld)); + assertNotSame(firstIndex, IrisStructureLocator.placedKeys(secondWorld)); - when(firstEngine.getGeneration()).thenReturn(new EngineGeneration(firstEngine)); - assertNotSame("a new world builds its own index", firstIndex, IrisStructureLocator.placedKeys(firstEngine)); + StructureTestWorld restartedWorld = emptyWorld(sharedData); + assertNotSame("a new world builds its own index", firstIndex, IrisStructureLocator.placedKeys(restartedWorld)); } @Test @@ -609,28 +537,21 @@ public class IrisStructureLocatorContractTest { @Test public void caveSearchabilityReservesVerticalBoundaryCells() { - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(engine.getMinHeight()).thenReturn(-64); - when(engine.getHeight()).thenReturn(384); + StructureTestWorld engine = new StructureTestWorld(); StructurePlacement placement = placement("distribution", StructureDistribution.DENSITY, "density", 1D, "anchor", StructureAnchorMode.CAVE_FLOOR, "minHeight", 319, "maxHeight", 319); assertFalse(IrisStructureLocator.isSearchableDensityPlacement(engine, placement)); TestSettings.with(placement, "minHeight", 318, "maxHeight", 318); assertTrue(IrisStructureLocator.isSearchableDensityPlacement(engine, placement)); - when(engine.getHeight()).thenReturn(2); + engine.height(2); TestSettings.with(placement, "minHeight", -2032, "maxHeight", 2032); assertFalse(IrisStructureLocator.isSearchableDensityPlacement(engine, placement)); } @Test public void undergroundAssemblyIsShiftedBelowEveryTerrainColumn() { - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(engine.getMinHeight()).thenReturn(-64); - when(engine.getHeight(anyInt(), anyInt(), eq(true))) - .thenAnswer(invocation -> invocation.getArgument(0) == 1 ? 140 : 164); + StructureTestWorld engine = new StructureTestWorld().highest((x, z) -> x == 1 ? 140 : 164); StructurePlacement placement = new StructurePlacement(); TestSettings.with(placement, "underground", true); TestSettings.with(placement, "minHeight", -64); @@ -649,10 +570,7 @@ public class IrisStructureLocatorContractTest { @Test public void undergroundBurialIncludesForceCarveCeiling() { - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(engine.getMinHeight()).thenReturn(-64); - when(engine.getHeight(anyInt(), anyInt(), eq(true))).thenReturn(164); + StructureTestWorld engine = new StructureTestWorld().highest((x, z) -> 164); StructurePlacement placement = new StructurePlacement(); TestSettings.with(placement, "underground", true); TestSettings.with(placement, "minHeight", -64); @@ -679,17 +597,18 @@ public class IrisStructureLocatorContractTest { @Test public void zeroForceCarvePaddingDoesNotExpandTheBurialEnvelope() { - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(engine.getMinHeight()).thenReturn(-64); - when(engine.getHeight(anyInt(), anyInt(), eq(true))).thenReturn(164); + List heightReads = new ArrayList<>(); + StructureTestWorld engine = new StructureTestWorld().highest((x, z) -> { + heightReads.add(x + "," + z); + return 164; + }); StructurePlacement placement = placement("underground", true, "minHeight", -64, "maxHeight", 100, "terrain", forceCarve("\"shape\":\"ROUNDED\",\"horizontalPadding\":0,\"ceilingPadding\":0")); KList pieces = new KList<>(); pieces.add(piece(4, 60, 7, 4, 80, 7)); assertEquals(Integer.valueOf(0), IrisStructureLocator.resolveUndergroundBurialShift( engine, pieces, placement, 60, -63, 319)); - verify(engine, times(1)).getHeight(4, 7, true); + assertEquals(List.of("4,7"), heightReads); } @Test @@ -727,7 +646,7 @@ public class IrisStructureLocatorContractTest { } private NearestScenario nearestEqualChunkDistanceScenario( - Engine engine, StructurePlacement placement) { + PackWorld engine, StructurePlacement placement) { int[][] chunks = { {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1} @@ -780,20 +699,23 @@ public class IrisStructureLocatorContractTest { return new StructureStamp(placeMode, List.of(), List.of(), ""); } - private Engine emptyEngine(IrisData data) { - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - IrisDimension dimension = mock(IrisDimension.class); - when(engine.getData()).thenReturn(data); - when(engine.getDimension()).thenReturn(dimension); - when(dimension.getModuleSettings()).thenReturn(declaring(new KList<>())); - when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); - when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); - return engine; + private StructureTestWorld emptyWorld(IrisData data) { + return jigsawWorld(data).dimension(); } - private Engine densityEngine(double density, boolean underground, int worldMin, int worldHeight, - int placementMin, int placementMax) { + /** A world whose pack is {@code data} and whose structures the jigsaw provider assembles. */ + private StructureTestWorld jigsawWorld(IrisData data) { + return new StructureTestWorld() + .resources(data.getPackResources()) + .assembling(new JigsawStructureAssembly(ModuleLogs.discarding())); + } + + private StructurePlacement densityPlacement(StructureTestWorld world) { + return world.dimensionPlacements().get(0); + } + + private StructureTestWorld densityWorld(double density, boolean underground, int worldMin, int worldHeight, + int placementMin, int placementMax) { IrisData data = mock(IrisData.class); ModuleResourceFixture.serveModules(data, new StructureModelModule(), new StructureModule()); IrisStructure structure = new IrisStructure(); @@ -808,21 +730,13 @@ public class IrisStructureLocatorContractTest { TestSettings.with(placement, "minHeight", placementMin); TestSettings.with(placement, "maxHeight", placementMax); - Engine engine = mock(Engine.class); - - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - IrisDimension dimension = mock(IrisDimension.class); - KList placements = new KList<>(); - placements.add(placement); - when(engine.getData()).thenReturn(data); - when(engine.getDimension()).thenReturn(dimension); - when(engine.getSeedManager()).thenReturn(new SeedManager(77L)); - when(engine.getMinHeight()).thenReturn(worldMin); - when(engine.getHeight()).thenReturn(worldHeight); - when(dimension.getModuleSettings()).thenReturn(declaring(placements)); - when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); - when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); - return engine; + return jigsawWorld(data) + .highest((x, z) -> 0) + .fluidHeight(0) + .placementSeed(new SeedManager(77L).getMantle()) + .minY(worldMin) + .height(worldHeight) + .dimension(placement); } private void registerSinglePieceGraph(IrisData data, IrisStructure structure, String prefix) { diff --git a/core/src/test/java/art/arcane/iris/engine/framework/IrisStructurePlacementRingLocatorTest.java b/core/src/test/java/art/arcane/iris/engine/framework/IrisStructurePlacementRingLocatorTest.java index f5c28bbf9..28f019c8a 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/IrisStructurePlacementRingLocatorTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/IrisStructurePlacementRingLocatorTest.java @@ -1,26 +1,17 @@ package art.arcane.iris.engine.framework; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.builtin.structure.NativeStructureSource; import art.arcane.iris.builtin.structure.StructurePlacement; import art.arcane.iris.builtin.structure.StructureDistribution; -import art.arcane.volmlib.util.collection.KList; import org.junit.Test; import java.util.concurrent.atomic.AtomicBoolean; import static art.arcane.iris.engine.framework.StructurePlacementFixtures.placement; import static art.arcane.iris.engine.framework.StructurePlacementFixtures.nativeSource; -import static art.arcane.iris.engine.framework.StructurePlacementFixtures.declaring; import static art.arcane.iris.engine.framework.StructurePlacementFixtures.withAdded; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; public class IrisStructurePlacementRingLocatorTest { private static final String STRUCTURE_KEY = "test:manual_native"; @@ -28,18 +19,18 @@ public class IrisStructurePlacementRingLocatorTest { @Test public void zeroVanillaRingSearchesTheOriginPlacementCell() { StructurePlacement placement = randomPlacement("origin-cell", 24, 6); - Engine engine = engine(placement); - long seed = engine.getSeedManager().getMantle(); + StructureTestWorld world = world(placement); + long seed = world.seed(); int[] expected = StructurePlacementGrid.randomSpreadCellChunk( 0, 0, placement.spacing(), placement.separation(), StructurePlacementGrid.placementSalt(placement), seed); assertTrue(expected[0] != 0 || expected[1] != 0); IrisStructureLocator.LocateResult chunkRadius = IrisStructureLocator.locate( - engine, STRUCTURE_KEY, 0, 0, 0); + world, STRUCTURE_KEY, 0, 0, 0); IrisStructureLocator.LocateResult placementRadius = IrisStructureLocator.locateInPlacementRings( - engine, STRUCTURE_KEY, 0, 0, 0, (chunkX, chunkZ) -> true); + world, STRUCTURE_KEY, 0, 0, 0, (chunkX, chunkZ) -> true); assertEquals(IrisStructureLocator.LocateStatus.NOT_FOUND, chunkRadius.status()); assertEquals(IrisStructureLocator.LocateStatus.FOUND, placementRadius.status()); @@ -51,8 +42,8 @@ public class IrisStructurePlacementRingLocatorTest { public void mixedSpacingPlacementsShareTheSameVanillaRingIndex() { StructurePlacement small = randomPlacement("small-grid", 8, 2); StructurePlacement large = randomPlacement("large-grid", 40, 10); - Engine engine = engine(small, large); - long seed = engine.getSeedManager().getMantle(); + StructureTestWorld world = world(small, large); + long seed = world.seed(); int[] smallRingZero = candidate(small, seed, 0, 0); int[] largeRingZero = candidate(large, seed, 0, 0); int[] smallRingOne = candidate(small, seed, -1, -1); @@ -60,7 +51,7 @@ public class IrisStructurePlacementRingLocatorTest { IrisStructureLocator.LocateResult result = IrisStructureLocator.locateInPlacementRings( - engine, STRUCTURE_KEY, 0, 0, 1, + world, STRUCTURE_KEY, 0, 0, 1, (chunkX, chunkZ) -> { if (chunkX == smallRingOne[0] && chunkZ == smallRingOne[1]) { visitedLaterSmallRing.set(true); @@ -81,11 +72,11 @@ public class IrisStructurePlacementRingLocatorTest { StructurePlacement placement = placement("placementId", "concentric", "distribution", StructureDistribution.CONCENTRIC_RINGS, "ringCount", 1, "ringDistance", 32, "ringSpread", 1); withAdded(placement, "nativeStructures", nativeSource(STRUCTURE_KEY)); - Engine engine = engine(placement); + StructureTestWorld world = world(placement); IrisStructureLocator.LocateResult result = IrisStructureLocator.locateInPlacementRings( - engine, STRUCTURE_KEY, 0, 0, 0, (chunkX, chunkZ) -> true); + world, STRUCTURE_KEY, 0, 0, 0, (chunkX, chunkZ) -> true); assertEquals(IrisStructureLocator.LocateStatus.FOUND, result.status()); long chunkX = result.originX() >> 4; @@ -98,11 +89,11 @@ public class IrisStructurePlacementRingLocatorTest { StructurePlacement placement = placement("placementId", "density", "distribution", StructureDistribution.DENSITY, "density", 1.0); withAdded(placement, "nativeStructures", nativeSource(STRUCTURE_KEY)); - Engine engine = engine(placement); + StructureTestWorld world = world(placement); IrisStructureLocator.LocateResult result = IrisStructureLocator.locateInPlacementRings( - engine, STRUCTURE_KEY, 0, 0, 2048, + world, STRUCTURE_KEY, 0, 0, 2048, (chunkX, chunkZ) -> false); assertEquals(IrisStructureLocator.LocateStatus.SEARCH_LIMIT_REACHED, result.status()); @@ -113,10 +104,10 @@ public class IrisStructurePlacementRingLocatorTest { StructurePlacement placement = placement("placementId", "unbounded-concentric-rings", "distribution", StructureDistribution.CONCENTRIC_RINGS, "ringCount", Integer.MAX_VALUE, "ringDistance", 32, "ringSpread", 1); withAdded(placement, "nativeStructures", nativeSource(STRUCTURE_KEY)); - Engine engine = engine(placement); + StructureTestWorld world = world(placement); IrisStructureLocator.LocateResult result = IrisStructureLocator.locateInPlacementRings( - engine, STRUCTURE_KEY, 0, 0, 2048, (chunkX, chunkZ) -> false); + world, STRUCTURE_KEY, 0, 0, 2048, (chunkX, chunkZ) -> false); assertEquals(IrisStructureLocator.LocateStatus.SEARCH_LIMIT_REACHED, result.status()); } @@ -126,10 +117,10 @@ public class IrisStructurePlacementRingLocatorTest { StructurePlacement placement = placement("placementId", "unbounded-concentric-chunks", "distribution", StructureDistribution.CONCENTRIC_RINGS, "ringCount", Integer.MAX_VALUE, "ringDistance", 32, "ringSpread", 1); withAdded(placement, "nativeStructures", nativeSource(STRUCTURE_KEY)); - Engine engine = engine(placement); + StructureTestWorld world = world(placement); IrisStructureLocator.LocateResult result = IrisStructureLocator.locate( - engine, STRUCTURE_KEY, 0, 0, 2048, (chunkX, chunkZ) -> false); + world, STRUCTURE_KEY, 0, 0, 2048, (chunkX, chunkZ) -> false); assertEquals(IrisStructureLocator.LocateStatus.SEARCH_LIMIT_REACHED, result.status()); } @@ -149,26 +140,10 @@ public class IrisStructurePlacementRingLocatorTest { return placement; } - private static Engine engine(StructurePlacement... placements) { - IrisData data = mock(IrisData.class); - IrisDimension dimension = mock(IrisDimension.class); - Engine engine = mock(Engine.class); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - KList configured = new KList<>(); - for (StructurePlacement placement : placements) { - configured.add(placement); - } - when(engine.getData()).thenReturn(data); - when(engine.getDimension()).thenReturn(dimension); - when(engine.getSeedManager()).thenReturn(new SeedManager(1337L)); - when(engine.getComplex()).thenReturn(null); - when(engine.getMinHeight()).thenReturn(-64); - when(engine.getHeight()).thenReturn(384); - when(engine.getHeight(anyInt(), anyInt(), anyBoolean())).thenReturn(128); - when(dimension.getFluidHeight()).thenReturn(63); - when(dimension.getModuleSettings()).thenReturn(declaring(configured)); - when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); - when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); - return engine; + private static StructureTestWorld world(StructurePlacement... placements) { + return new StructureTestWorld() + .placementSeed(new SeedManager(1337L).getMantle()) + .highest((x, z) -> 128) + .dimension(placements); } } diff --git a/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureStartsTest.java b/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureStartsTest.java index 638381812..e775270c1 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureStartsTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/NativeStructureStartsTest.java @@ -127,7 +127,7 @@ public class NativeStructureStartsTest { for (int chunkX = -GRID_RADIUS_CHUNKS; chunkX <= GRID_RADIUS_CHUNKS; chunkX++) { for (int chunkZ = -GRID_RADIUS_CHUNKS; chunkZ <= GRID_RADIUS_CHUNKS; chunkZ++) { List plans = NativeStructureStarts.plansAt(engine, chunkX, chunkZ); - List modulePlans = NativeStartPlanner.plansAt(engine, chunkX, chunkZ); + List modulePlans = NativeStartPlanner.plansAt(engine.getGeneration().world(), chunkX, chunkZ); assertEquals(modulePlans.size(), plans.size()); for (int index = 0; index < plans.size(); index++) { NativeStructureStartPlan plan = plans.get(index); diff --git a/core/src/test/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolverTest.java b/core/src/test/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolverTest.java index 45f121783..52a8bd00a 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolverTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/StructureCaveAnchorResolverTest.java @@ -1,23 +1,16 @@ package art.arcane.iris.engine.framework; -import art.arcane.iris.builtin.carve.CaveLavaHeightSettings; -import art.arcane.iris.core.modules.BuiltInPack; import art.arcane.iris.builtin.structure.StructureAnchorMode; import art.arcane.iris.builtin.structure.StructurePlacement; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.spi.IrisPlatform; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.spi.PlatformBlockState; -import art.arcane.iris.spi.PlatformRegistries; import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.matter.MatterCavern; -import org.junit.After; -import org.junit.Before; +import com.volmit.mantle.CarvedVoid; import org.junit.Test; import java.util.Arrays; import java.util.HashSet; +import java.util.Optional; import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.IntPredicate; import static art.arcane.iris.engine.framework.StructurePlacementFixtures.placement; @@ -27,31 +20,9 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.RETURNS_DEEP_STUBS; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; public class StructureCaveAnchorResolverTest { - @Before - public void bindPlatform() { - IrisPlatforms.unbind(); - PlatformBlockState block = mock(PlatformBlockState.class); - PlatformRegistries registries = mock(PlatformRegistries.class); - when(registries.block(anyString())).thenReturn(block); - IrisPlatform platform = mock(IrisPlatform.class); - when(platform.registries()).thenReturn(registries); - IrisPlatforms.bind(platform); - } - - @After - public void unbindPlatform() { - IrisPlatforms.unbind(); - } + private final AtomicInteger surfaceReads = new AtomicInteger(); @Test public void floorRequiresSolidBoundaryAndUpwardClearance() { @@ -143,33 +114,33 @@ public class StructureCaveAnchorResolverTest { @Test public void dryCaveUnderSubmergedSurfaceUsesAnchorCavernState() { - Engine engine = engineWithFloorAnchor(new MatterCavern(true, "", (byte) 0), 0); + StructureTestWorld world = worldWithFloorAnchor(CarvedVoid.OPEN, 0); StructureCaveAnchorResolver.Anchor anchor = StructureCaveAnchorResolver.resolve( - engine, floorPlacement(false), 0, 0, new RNG(87234L)); + world, floorPlacement(false), 0, 0, new RNG(87234L)); assertNotNull(anchor); assertEquals(-54, anchor.y()); - verify(engine, never()).getHeight(anyInt(), anyInt(), eq(true)); + assertEquals(0, surfaceReads.get()); } @Test public void wetCaveUnderDrySurfaceIsRejectedAtTheAnchor() { - Engine engine = engineWithFloorAnchor(new MatterCavern(true, "", (byte) 1), 200); + StructureTestWorld world = worldWithFloorAnchor(CarvedVoid.FLUID, 200); StructureCaveAnchorResolver.Anchor anchor = StructureCaveAnchorResolver.resolve( - engine, floorPlacement(false), 0, 0, new RNG(87234L)); + world, floorPlacement(false), 0, 0, new RNG(87234L)); assertNull(anchor); - verify(engine, never()).getHeight(anyInt(), anyInt(), eq(true)); + assertEquals(0, surfaceReads.get()); } @Test public void dryPolicyHonorsExplicitLiquidsAndDefaultLavaHeight() { - MatterCavern air = new MatterCavern(true, "", (byte) 0); - MatterCavern water = new MatterCavern(true, "", (byte) 1); - MatterCavern lava = new MatterCavern(true, "", (byte) 2); - MatterCavern forcedAir = new MatterCavern(true, "", (byte) 3); + CarvedVoid air = CarvedVoid.OPEN; + CarvedVoid water = CarvedVoid.FLUID; + CarvedVoid lava = CarvedVoid.LAVA; + CarvedVoid forcedAir = CarvedVoid.AIR; assertFalse(StructureCaveAnchorResolver.acceptsAnchorFluid(false, air, 8, 8)); assertTrue(StructureCaveAnchorResolver.acceptsAnchorFluid(false, air, 9, 8)); @@ -177,30 +148,22 @@ public class StructureCaveAnchorResolverTest { assertFalse(StructureCaveAnchorResolver.acceptsAnchorFluid(false, lava, 20, 8)); assertTrue(StructureCaveAnchorResolver.acceptsAnchorFluid(false, forcedAir, 0, 8)); assertTrue(StructureCaveAnchorResolver.acceptsAnchorFluid(true, water, 20, 8)); - assertFalse(StructureCaveAnchorResolver.acceptsAnchorFluid( - true, new MatterCavern(false, "", (byte) 0), 20, 8)); + assertFalse(StructureCaveAnchorResolver.acceptsAnchorFluid(true, null, 20, 8)); } - private static Engine engineWithFloorAnchor(MatterCavern anchorCavern, int surfaceHeight) { - Engine engine = mock(Engine.class, RETURNS_DEEP_STUBS); - IrisDimension dimension = mock(IrisDimension.class); - MatterCavern carvedAir = new MatterCavern(true, "", (byte) 0); - when(engine.getMinHeight()).thenReturn(-64); - when(engine.getHeight()).thenReturn(384); - when(engine.getHeight(anyInt(), anyInt(), eq(true))).thenReturn(surfaceHeight); - when(engine.getDimension()).thenReturn(dimension); - when(dimension.getFluidHeight()).thenReturn(127); - when(dimension.getModuleSettings()).thenReturn(BuiltInPack.settings(new CaveLavaHeightSettings(8))); - when(engine.getMantle().getMantle().get( - anyInt(), anyInt(), anyInt(), eq(MatterCavern.class))) - .thenAnswer(invocation -> { - int mantleY = invocation.getArgument(1); + private StructureTestWorld worldWithFloorAnchor(CarvedVoid anchorVoid, int surfaceHeight) { + return new StructureTestWorld() + .fluidHeight(127) + .highest((x, z) -> { + surfaceReads.incrementAndGet(); + return surfaceHeight; + }) + .carved((x, mantleY, z) -> { if (mantleY == 10) { - return anchorCavern; + return Optional.of(anchorVoid); } - return mantleY == 11 || mantleY == 12 ? carvedAir : null; + return mantleY == 11 || mantleY == 12 ? Optional.of(CarvedVoid.OPEN) : Optional.empty(); }); - return engine; } private static StructurePlacement floorPlacement(boolean underwater) { diff --git a/core/src/test/java/art/arcane/iris/engine/framework/StructurePlacementScopeTest.java b/core/src/test/java/art/arcane/iris/engine/framework/StructurePlacementScopeTest.java index 5e4b2a603..c33151786 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/StructurePlacementScopeTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/StructurePlacementScopeTest.java @@ -1,27 +1,22 @@ package art.arcane.iris.engine.framework; -import art.arcane.iris.engine.IrisComplex; -import art.arcane.iris.engine.object.world.biome.IrisBiome; -import art.arcane.iris.engine.object.world.dimension.IrisDimension; -import art.arcane.iris.engine.object.world.region.IrisRegion; import art.arcane.iris.builtin.structure.StructureAnchorMode; import art.arcane.iris.builtin.structure.StructurePlacement; -import art.arcane.volmlib.util.collection.KList; +import com.volmit.resource.ResourceId; +import com.volmit.world.BiomeSample; import org.junit.Test; +import java.util.List; +import java.util.Optional; + import static art.arcane.iris.engine.framework.StructurePlacementFixtures.placement; -import static art.arcane.iris.engine.framework.StructurePlacementFixtures.declare; -import static art.arcane.iris.engine.framework.StructurePlacementFixtures.declaring; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.RETURNS_DEEP_STUBS; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; public class StructurePlacementScopeTest { + private static final ResourceId CAVE_BIOME = ResourceId.parse("test:biome/caves"); + @Test public void caveBiomeContributesOnlyCaveAnchoredPlacements() { StructurePlacement surfacePlacement = new StructurePlacement(); @@ -29,31 +24,15 @@ public class StructurePlacementScopeTest { StructurePlacement invalidCaveScopePlacement = placement("anchor", StructureAnchorMode.SURFACE); StructurePlacement regionPlacement = new StructurePlacement(); StructurePlacement dimensionPlacement = new StructurePlacement(); + StructureTestWorld world = new StructureTestWorld() + .biome(StructureTestWorld.SURFACE_BIOME, surfacePlacement) + .biome(CAVE_BIOME, cavePlacement, invalidCaveScopePlacement) + .region(StructureTestWorld.REGION, regionPlacement) + .dimension(dimensionPlacement, cavePlacement) + .biomes((x, y, z) -> new BiomeSample( + StructureTestWorld.REGION, StructureTestWorld.SURFACE_BIOME, Optional.of(CAVE_BIOME))); - IrisBiome surfaceBiome = declare(new IrisBiome(), surfacePlacement); - IrisBiome caveBiome = declare(new IrisBiome(), cavePlacement, invalidCaveScopePlacement); - IrisRegion region = declare(new IrisRegion(), regionPlacement); - Engine engine = mock(Engine.class, RETURNS_DEEP_STUBS); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - IrisComplex complex = engine.getComplex(); - IrisDimension dimension = mock(IrisDimension.class); - KList dimensionStructures = new KList<>(); - dimensionStructures.add(dimensionPlacement); - dimensionStructures.add(cavePlacement); - KList allRegions = new KList<>(); - allRegions.add(region); - KList allBiomes = new KList<>(); - allBiomes.add(surfaceBiome); - allBiomes.add(caveBiome); - when(engine.getDimension()).thenReturn(dimension); - when(engine.getAllBiomes()).thenReturn(allBiomes); - when(dimension.getModuleSettings()).thenReturn(declaring(dimensionStructures)); - when(dimension.getAllRegions(engine)).thenReturn(allRegions); - when(complex.getTrueBiomeStream().get(8, 8)).thenReturn(surfaceBiome); - when(complex.getCaveBiomeStream().get(8, 8)).thenReturn(caveBiome); - when(complex.getRegionStream().get(8, 8)).thenReturn(region); - - KList placements = StructurePlacementScope.placementsAt(engine, 0, 0); + List placements = StructurePlacementScope.placementsAt(world, 0, 0); assertEquals(4, placements.size()); assertTrue(placements.contains(surfacePlacement)); @@ -66,23 +45,12 @@ public class StructurePlacementScopeTest { @Test public void dimensionOnlyPlacementsDoNotResolveBiomeScopes() { StructurePlacement dimensionPlacement = new StructurePlacement(); - Engine engine = mock(Engine.class, RETURNS_DEEP_STUBS); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - IrisComplex complex = engine.getComplex(); - IrisDimension dimension = mock(IrisDimension.class); - KList dimensionStructures = new KList<>(); - dimensionStructures.add(dimensionPlacement); - when(engine.getDimension()).thenReturn(dimension); - when(engine.getAllBiomes()).thenReturn(new KList<>()); - when(dimension.getModuleSettings()).thenReturn(declaring(dimensionStructures)); - when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); + StructureTestWorld world = new StructureTestWorld().dimension(dimensionPlacement); - KList placements = StructurePlacementScope.placementsAt(engine, 0, 0); + List placements = StructurePlacementScope.placementsAt(world, 0, 0); assertEquals(1, placements.size()); assertTrue(placements.contains(dimensionPlacement)); - verify(complex.getTrueBiomeStream(), never()).get(8, 8); - verify(complex.getCaveBiomeStream(), never()).get(8, 8); - verify(complex.getRegionStream(), never()).get(8, 8); + assertEquals(0, world.columnReads()); } } diff --git a/core/src/test/java/art/arcane/iris/engine/framework/StructureTestWorld.java b/core/src/test/java/art/arcane/iris/engine/framework/StructureTestWorld.java new file mode 100644 index 000000000..966c7d867 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/engine/framework/StructureTestWorld.java @@ -0,0 +1,443 @@ +package art.arcane.iris.engine.framework; + +import art.arcane.iris.builtin.structure.StructurePlacement; +import art.arcane.iris.builtin.structure.StructurePlacementSettings; +import art.arcane.iris.engine.framework.structure.assembly.StructureAssembly; +import com.volmit.IrisFeature; +import com.volmit.ModuleLog; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.config.FeatureSettings; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.Level; +import com.volmit.config.PackSettings; +import com.volmit.config.SettingsStack; +import com.volmit.data.SavedKey; +import com.volmit.geometry.BlockBox; +import com.volmit.geometry.BlockPosition; +import com.volmit.host.ModuleLogs; +import com.volmit.item.ItemRegistry; +import com.volmit.mantle.CarvedVoid; +import com.volmit.noise.NoiseFactory; +import com.volmit.object.PackObjects; +import com.volmit.placement.PlacementRecord; +import com.volmit.placement.Placements; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.resource.ResourceKind; +import com.volmit.world.BiomeKind; +import com.volmit.world.BiomeSample; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; +import com.volmit.world.TerrainSample; +import com.volmit.world.TerrainSampler; +import com.volmit.world.UpperDimension; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.OptionalInt; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; +import java.util.function.IntBinaryOperator; + +/** + * A world as structure placement sees it, for tests: the declarations of the dimension, regions and biomes, the biome of + * each column, its height and the voids carved into it. Everything is set before the first read. + */ +public final class StructureTestWorld implements PackWorld { + public static final ResourceId DIMENSION = ResourceId.parse("test:dimension/overworld"); + public static final ResourceId REGION = ResourceId.parse("test:region/plains"); + public static final ResourceId SURFACE_BIOME = ResourceId.parse("test:biome/plains"); + private static final int WORLD_LIMIT_BLOCKS = 30_000_000; + + private PackResources resources = new FakePack(); + private final List> declarations = new ArrayList<>(); + private final List assemblies = new ArrayList<>(); + private final Map, Object> states = new HashMap<>(); + private final AtomicInteger columnReads = new AtomicInteger(); + private final AtomicInteger placementScans = new AtomicInteger(); + private int minY = -64; + private int height = 384; + private int fluidHeight = 63; + private long placementSeed = 0L; + private Long worldSeed; + private PackWorld host; + private IntBinaryOperator highest = (x, z) -> 64; + private BiomeColumns biomeColumns = (x, y, z) -> new BiomeSample(REGION, SURFACE_BIOME, Optional.empty()); + private CarvedColumns carved = (x, y, z) -> Optional.empty(); + + /** The world that gives this one its pack, its services and the placement stages it runs. */ + public StructureTestWorld hostedBy(PackWorld value) { + host = value; + return this; + } + + /** The world's own seed, when it differs from the one placement starts from. */ + public StructureTestWorld worldSeed(long value) { + worldSeed = value; + return this; + } + + /** The pack the world generates, in place of the empty one. */ + public StructureTestWorld resources(PackResources value) { + resources = value; + return this; + } + + public StructureTestWorld minY(int value) { + minY = value; + return this; + } + + public StructureTestWorld height(int value) { + height = value; + return this; + } + + public StructureTestWorld fluidHeight(int value) { + fluidHeight = value; + return this; + } + + public StructureTestWorld placementSeed(long value) { + placementSeed = value; + return this; + } + + public StructureTestWorld highest(IntBinaryOperator value) { + highest = value; + return this; + } + + public StructureTestWorld biomes(BiomeColumns value) { + biomeColumns = value; + return this; + } + + public StructureTestWorld carved(CarvedColumns value) { + carved = value; + return this; + } + + public StructureTestWorld assembling(StructureAssembly assembly) { + assemblies.add(assembly); + return this; + } + + public StructureTestWorld dimension(StructurePlacement... placements) { + return declare(Level.DIMENSION, DIMENSION, placements); + } + + public StructureTestWorld region(ResourceId region, StructurePlacement... placements) { + return declare(Level.REGION, region, placements); + } + + public StructureTestWorld biome(ResourceId biome, StructurePlacement... placements) { + return declare(Level.BIOME, biome, placements); + } + + private StructureTestWorld declare(Level level, ResourceId source, StructurePlacement[] placements) { + declarations.add(new Entry<>(level, source, StructurePlacementFixtures.placementSettings(List.of(placements)))); + return this; + } + + /** The placements the dimension declares. */ + public List dimensionPlacements() { + return declarations.stream().filter(entry -> entry.level() == Level.DIMENSION) + .flatMap(entry -> entry.value().placements().stream()).toList(); + } + + /** How many times the placements of a chunk were worked out. */ + public int placementScans() { + return placementScans.get(); + } + + /** How many columns placement asked the world's layout about. */ + public int columnReads() { + return columnReads.get(); + } + + @Override + public long seed() { + return worldSeed == null ? placementSeed : worldSeed; + } + + @Override + public long seed(ResourceId purpose) { + return placementSeed; + } + + @Override + public PackResources resources() { + return host == null ? resources : host.resources(); + } + + @Override + public PackSettings settings() { + return new PackSettings() { + @Override + @SuppressWarnings("unchecked") + public SettingsStack declared(Class featureType) { + return featureType == StructurePlacementSettings.class + ? (SettingsStack) SettingsStack.of(declarations) : SettingsStack.empty(); + } + + @Override + public PackResources resources() { + return StructureTestWorld.this.resources(); + } + }; + } + + @Override + public int minWorldY() { + return minY; + } + + @Override + public Optional running() { + return Optional.of(new Running()); + } + + @Override + public T state(Class type, Function create) { + if (type == StructurePlacementScope.ScopeIndex.class) { + placementScans.incrementAndGet(); + } + Object known = states.get(type); + if (known == null) { + known = create.apply(this); + states.put(type, known); + } + return type.cast(known); + } + + @Override + public Placements placements() { + if (host == null) { + throw new UnsupportedOperationException("No placements here"); + } + return host.placements(); + } + + @Override + public ModuleLog log() { + return ModuleLogs.discarding(); + } + + @Override + @SuppressWarnings("unchecked") + public List services(Class service) { + if (host != null) { + return host.services(service); + } + return service == StructureAssembly.class ? (List) List.copyOf(assemblies) : List.of(); + } + + /** The biome of a column at a height. */ + @FunctionalInterface + public interface BiomeColumns { + BiomeSample at(int worldX, int y, int worldZ); + } + + /** The void carved into a block, if any. */ + @FunctionalInterface + public interface CarvedColumns { + Optional at(int worldX, int y, int worldZ); + } + + private final class Running implements RunningWorld { + private final TerrainSampler layout = new Layout(); + + @Override + public TerrainSampler layout() { + return layout; + } + + @Override + public FeatureSettings settings() { + return new FeatureSettings() { + @Override + @SuppressWarnings("unchecked") + public SettingsStack at(Class featureType, int worldX, int worldZ) { + if (featureType != StructurePlacementSettings.class) { + return SettingsStack.empty(); + } + columnReads.incrementAndGet(); + BiomeSample column = biomeColumns.at(worldX, minY, worldZ); + List> here = new ArrayList<>(); + for (Entry declaration : declarations) { + if (declaration.level() == Level.DIMENSION + || declaration.source().equals(column.region()) + || declaration.source().equals(column.surfaceBiome())) { + here.add(declaration); + } + } + return (SettingsStack) SettingsStack.of(here); + } + + @Override + @SuppressWarnings("unchecked") + public Optional declaredBy(ResourceId biome, Class featureType) { + if (featureType != StructurePlacementSettings.class) { + return Optional.empty(); + } + return declarations.stream().filter(entry -> entry.level() == Level.BIOME && entry.source().equals(biome)) + .map(entry -> (F) entry.value()).findFirst(); + } + }; + } + + @Override + public int highest(int worldX, int worldZ, boolean ignoreFluid) { + return highest.applyAsInt(worldX, worldZ); + } + + @Override + public List caveFloors(int chunkX, int chunkZ) { + return List.of(); + } + + @Override + public Optional placementAt(int worldX, int y, int worldZ) { + return Optional.empty(); + } + + @Override + public Optional carvedAt(int worldX, int y, int worldZ) { + return carved.at(worldX, y, worldZ); + } + + @Override + public T saved(SavedKey key) { + throw new UnsupportedOperationException("No saved state here"); + } + + @Override + public Optional sky() { + return Optional.empty(); + } + + @Override + public Set platformLootTables() { + return Set.of(); + } + + @Override + public boolean debug() { + return false; + } + } + + private final class Layout implements TerrainSampler { + @Override + public BlockBox bounds() { + return new BlockBox(-WORLD_LIMIT_BLOCKS, 0, -WORLD_LIMIT_BLOCKS, WORLD_LIMIT_BLOCKS, height, WORLD_LIMIT_BLOCKS); + } + + @Override + public TerrainSample column(int worldX, int worldZ) { + throw new UnsupportedOperationException("No terrain columns here"); + } + + @Override + public double surfaceY(int worldX, int worldZ) { + return highest.applyAsInt(worldX, worldZ); + } + + @Override + public BiomeSample biome(int worldX, int y, int worldZ) { + return biomeColumns.at(worldX, y, worldZ); + } + + @Override + public int fluidHeight() { + return fluidHeight; + } + + @Override + public OptionalInt upperDimensionY(int worldX, int worldZ) { + return OptionalInt.empty(); + } + + @Override + public BiomeKind surfaceKind(int worldX, int worldZ) { + throw new UnsupportedOperationException("No biome kinds here"); + } + + @Override + public Optional surfaceBlock(int worldX, int worldZ) { + return Optional.empty(); + } + + @Override + public double biomeHeight(ResourceId biome, int worldX, int worldZ, long seed) { + throw new UnsupportedOperationException("No biome heights here"); + } + + @Override + public Optional skyBiome(ResourceId biome, int worldX, int worldZ) { + return Optional.empty(); + } + + @Override + public int minWorldY() { + return minY; + } + + @Override + public Optional upperDimension() { + return Optional.empty(); + } + } + + /** A pack with no resources at all: placement only reads its id. */ + private static final class FakePack implements PackResources { + private final UUID snapshot = UUID.randomUUID(); + + @Override + public ResourceId packId() { + return ResourceId.parse("test:pack"); + } + + @Override + public UUID snapshotId() { + return snapshot; + } + + @Override + public BlockRegistry blocks() { + throw new UnsupportedOperationException("No blocks here"); + } + + @Override + public ItemRegistry items() { + throw new UnsupportedOperationException("No items here"); + } + + @Override + public NoiseFactory noise() { + throw new UnsupportedOperationException("No noise here"); + } + + @Override + public PackObjects objects() { + throw new UnsupportedOperationException("No objects here"); + } + + @Override + public Optional find(ResourceKind kind, ResourceId id) { + return Optional.empty(); + } + + @Override + public List ids(ResourceKind kind) { + return List.of(); + } + } +} diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/NativeStartPlannerTest.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/NativeStartPlannerTest.java index 0afe13c15..8de0a6585 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/structure/NativeStartPlannerTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/NativeStartPlannerTest.java @@ -1,10 +1,8 @@ package art.arcane.iris.engine.framework.structure; -import art.arcane.iris.core.loader.IrisData; -import art.arcane.iris.engine.framework.Engine; -import art.arcane.iris.engine.framework.EngineGeneration; import art.arcane.iris.engine.framework.SeedManager; import art.arcane.iris.engine.framework.StructurePlacementGrid; +import art.arcane.iris.engine.framework.StructureTestWorld; import art.arcane.iris.builtin.structure.StructureStilts; import art.arcane.iris.builtin.structure.StructureTerrain; import art.arcane.iris.builtin.structure.StructureTerrainMode; @@ -44,7 +42,7 @@ import static org.mockito.Mockito.when; public class NativeStartPlannerTest { @Test public void undergroundPlanIsDeterministicAndUsesConfiguredBand() { - Engine engine = engine(982374L, -64, 384, 90); + StructureTestWorld engine = engine(982374L, -64, 384, 90); StructurePlacement placement = TestSettings.with(nativePlacement(), "underground", true, "minHeight", -45, "maxHeight", -20); NativeStartPlanner.Plan first = NativeStartPlanner.planAt(engine, placement, 12, -7); @@ -60,7 +58,7 @@ public class NativeStartPlannerTest { @Test public void undergroundBandOutsideWorldBoundsSkipsTheCandidate() { - Engine engine = engine(982374L, -64, 384, 90); + StructureTestWorld engine = engine(982374L, -64, 384, 90); StructurePlacement placement = TestSettings.with(nativePlacement(), "underground", true, "minHeight", 500, "maxHeight", 600); assertNull(NativeStartPlanner.planAt(engine, placement, 12, -7)); @@ -68,7 +66,7 @@ public class NativeStartPlannerTest { @Test public void surfacePlanUsesIrisTerrainAndHonorsHeightGate() { - Engine engine = engine(77L, -64, 384, 150); + StructureTestWorld engine = engine(77L, -64, 384, 150); StructurePlacement placement = TestSettings.with(nativePlacement(), "minHeight", 80, "maxHeight", 90); NativeStartPlanner.Plan plan = NativeStartPlanner.planAt(engine, placement, 0, 0); @@ -107,7 +105,7 @@ public class NativeStartPlannerTest { @Test public void underwaterFlagRejectsSubmergedColumnsForSurfaceAndUndergroundPlans() { - Engine engine = engine(77L, -64, 384, 63); + StructureTestWorld engine = engine(77L, -64, 384, 63); StructurePlacement placement = nativePlacement(); assertNull(NativeStartPlanner.planAt(engine, placement, 0, 0)); @@ -121,7 +119,7 @@ public class NativeStartPlannerTest { @Test public void fluidHeightBoundaryIsShoreForPlannerAndLocator() { - Engine engine = engine(77L, -64, 384, 64); + StructureTestWorld engine = engine(77L, -64, 384, 64); StructurePlacement placement = nativePlacement(); assertTrue(!NativeStartPlanner.isSubmerged(engine, 8, 8)); @@ -133,7 +131,7 @@ public class NativeStartPlannerTest { @Test public void duplicateSelectedStructureUsesOneDeterministicPlan() { - Engine engine = engine(77L, -64, 384, 150); + StructureTestWorld engine = engine(77L, -64, 384, 150); StructurePlacement first = TestSettings.with(nativePlacement(), "placementId", "first"); StructurePlacement second = TestSettings.with(nativePlacement(), "placementId", "second"); bindPlacements(engine, first, second); @@ -189,27 +187,17 @@ public class NativeStartPlannerTest { return placement; } - private Engine engine(long seed, int minHeight, int height, int terrainHeight) { - Engine engine = mock(Engine.class); - when(engine.getSeedManager()).thenReturn(new SeedManager(seed)); - when(engine.getMinHeight()).thenReturn(minHeight); - when(engine.getHeight()).thenReturn(height); - when(engine.getHeight(org.mockito.ArgumentMatchers.anyInt(), - org.mockito.ArgumentMatchers.anyInt(), org.mockito.ArgumentMatchers.eq(true))) - .thenReturn(terrainHeight); - IrisDimension dimension = mock(IrisDimension.class); - when(dimension.getFluidHeight()).thenReturn(64); - when(engine.getDimension()).thenReturn(dimension); - return engine; + private StructureTestWorld engine(long seed, int minHeight, int height, int terrainHeight) { + return new StructureTestWorld() + .placementSeed(new SeedManager(seed).getMantle()) + .minY(minHeight) + .height(height) + .highest((x, z) -> terrainHeight) + .fluidHeight(64); } - private void bindPlacements(Engine engine, StructurePlacement... placements) { - IrisDimension dimension = engine.getDimension(); - when(engine.getData()).thenReturn(mock(IrisData.class)); - when(engine.getGeneration()).thenReturn(new EngineGeneration(engine)); - when(dimension.getModuleSettings()).thenReturn(declaring(placements)); - when(dimension.getAllRegions(engine)).thenReturn(new KList<>()); - when(dimension.getReachableBiomes(engine)).thenReturn(new KList<>()); + private void bindPlacements(StructureTestWorld engine, StructurePlacement... placements) { + engine.dimension(placements); } private void assertInvalid(StructurePlacement placement) { diff --git a/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegrationTest.java b/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegrationTest.java index 1b5c16ded..54155e608 100644 --- a/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegrationTest.java +++ b/core/src/test/java/art/arcane/iris/engine/framework/structure/fit/TerrainIntegrationTest.java @@ -1,12 +1,14 @@ package art.arcane.iris.engine.framework.structure.fit; import art.arcane.iris.builtin.structure.StructureCarveShape; +import art.arcane.iris.core.modules.IrisTestNoise; import art.arcane.iris.builtin.structure.StructureTerrain; import art.arcane.iris.builtin.structure.StructureTerrainMode; import art.arcane.iris.engine.framework.structure.NativeStructureFit; import art.arcane.iris.engine.mantle.components.StructureCarvingFootprint; import com.google.gson.Gson; import com.volmit.block.BlockState; +import com.volmit.noise.NoiseFactory; import com.volmit.vanilla.DecorationStep; import com.volmit.vanilla.PieceKind; import com.volmit.vanilla.StartMemo; @@ -40,6 +42,7 @@ import static org.junit.Assert.assertTrue; public class TerrainIntegrationTest { private static final long SEED = 1234L; private static final long CARVE_SEED = 8675309L; + private static final NoiseFactory NOISE = IrisTestNoise.factory(); private static final int SLAB_DEPTH = 128; private static final int SLAB_MIN_Y = 64; private static final int SLAB_PADDING = 14; @@ -92,7 +95,7 @@ public class TerrainIntegrationTest { FitStart start = start("{\"mode\":\"ENCASE\",\"encasePalette\":{\"palette\":[{\"block\":\"tuff\"}]}}", TerrainAdaptation.BURY, FitFixture.Piece.fixed(PYRAMID)); - TerrainIntegration.integrateTerrain(world.fitBlocks(), PYRAMID, start, SEED, NATURAL, tuff, null); + TerrainIntegration.integrateTerrain(world.fitBlocks(), PYRAMID, start, SEED, NOISE, NATURAL, tuff, null); assertEquals(state("tuff"), world.at(0, 64, 0)); assertEquals(SEED ^ "test:structure".hashCode(), (long) seeds.getFirst()); @@ -415,7 +418,7 @@ public class TerrainIntegrationTest { } private static void integrate(FitFixture.World world, Box area, FitStart start) { - TerrainIntegration.prepareTerrain(world.fitBlocks(), area, List.of(start), SEED, NATURAL, NO_PALETTES); + TerrainIntegration.prepareTerrain(world.fitBlocks(), area, List.of(start), SEED, NOISE, NATURAL, NO_PALETTES); } private static FitStart start(String terrainJson, TerrainAdaptation adaptation, FitFixture.Piece... pieces) { @@ -444,7 +447,7 @@ public class TerrainIntegrationTest { StructureTerrain terrain = erodedTerrain(horizontalPadding, lobeStrength); FitStart start = start(JSON.toJson(terrain), TerrainAdaptation.NONE, FitFixture.Piece.fixed(PYRAMID)); return TerrainIntegration.organicCarve(CarveFootprints.of(start, horizontalPadding), terrain, - StructureCarveShape.ERODED, CARVE_SEED); + StructureCarveShape.ERODED, CARVE_SEED, NOISE); } private static StructureTerrain erodedTerrain(int horizontalPadding, double lobeStrength) { @@ -471,7 +474,7 @@ public class TerrainIntegrationTest { FitFixture.World world = filled(area); TerrainIntegration.carveOrganicColumns(world.fitBlocks(), area, TerrainIntegration.organicCarve( - footprint, erodedTerrain(SLAB_PADDING, lobeStrength), StructureCarveShape.ERODED, CARVE_SEED)); + footprint, erodedTerrain(SLAB_PADDING, lobeStrength), StructureCarveShape.ERODED, CARVE_SEED, NOISE)); int[] depths = new int[SLAB_DEPTH]; for (int z = 0; z < SLAB_DEPTH; z++) { diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisStructureFoundationWriteTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisStructureFoundationWriteTest.java index 79001c814..46e60bf0e 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisStructureFoundationWriteTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/IrisStructureFoundationWriteTest.java @@ -1,14 +1,11 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.engine.UsableBlockPlatform; -import art.arcane.iris.engine.mantle.MantleWriter; -import art.arcane.iris.spi.IrisPlatform; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.spi.PlatformRegistries; -import art.arcane.volmlib.util.matter.MatterCavern; import com.volmit.block.BlockState; import com.volmit.block.PaletteSampler; -import org.junit.After; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.Mantle; +import com.volmit.mantle.MantleLayer; +import com.volmit.placement.PlacementTerrain; import org.junit.Test; import org.mockito.InOrder; @@ -17,51 +14,45 @@ import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; public class IrisStructureFoundationWriteTest { - @After - public void unbindPlatform() { - UsableBlockPlatform.unbind(); - } + private static final BlockState SUPPORT = new BlockState("minecraft:deepslate_bricks"); @Test + @SuppressWarnings("unchecked") public void resolvesWorldCoordinatesThenClearsCavernBeforeWritingSupport() { - UsableBlockPlatform.bind(); - MantleWriter writer = mock(MantleWriter.class); + Mantle mantle = mock(Mantle.class); + MantleLayer carved = mock(MantleLayer.class); + when(mantle.carved()).thenReturn(carved); + PlacementTerrain terrain = mock(PlacementTerrain.class); List asked = new ArrayList<>(); PaletteSampler picker = (x, y, z) -> { asked.add((int) x + "," + (int) y + "," + (int) z); - return new BlockState("minecraft:deepslate_bricks"); + return SUPPORT; }; - StructurePlacing.writeFoundationSupport(writer, picker, 12, 9, -18, -256); + StructurePlacing.writeFoundationSupport(terrain, mantle, picker, 12, 9, -18, -256); assertEquals(List.of("12,-247,-18"), asked); - InOrder order = inOrder(writer); - order.verify(writer).clearData(12, 9, -18, MatterCavern.class); - order.verify(writer).set(eq(12), eq(9), eq(-18), any(art.arcane.iris.spi.PlatformBlockState.class)); + InOrder order = inOrder(carved, terrain); + order.verify(carved).remove(12, 9, -18); + order.verify(terrain).set(12, 9, -18, SUPPORT); } @Test public void unresolvedPaletteFailsBeforeChangingCavernOrBlocks() { - UsableBlockPlatform.unbind(); - IrisPlatform platform = mock(IrisPlatform.class); - when(platform.registries()).thenReturn(mock(PlatformRegistries.class)); - IrisPlatforms.bind(platform); - MantleWriter writer = mock(MantleWriter.class); + Mantle mantle = mock(Mantle.class); + PlacementTerrain terrain = mock(PlacementTerrain.class); try { - StructurePlacing.writeFoundationSupport(writer, (x, y, z) -> new BlockState("test:unknown"), 12, 9, -18, -256); + StructurePlacing.writeFoundationSupport(terrain, mantle, (x, y, z) -> null, 12, 9, -18, -256); } catch (IllegalStateException error) { assertTrue(error.getMessage().contains("12,-247,-18")); - verifyNoInteractions(writer); + verifyNoInteractions(mantle, terrain); return; } throw new AssertionError("Expected an unresolved structure stilt palette to fail"); diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelopeTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelopeTest.java index 1b0e9391e..2f3377f2a 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelopeTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureCarveEnvelopeTest.java @@ -1,8 +1,9 @@ package art.arcane.iris.engine.mantle.components; import art.arcane.iris.builtin.structure.StructureCarveShape; -import art.arcane.iris.util.project.noise.CNG; -import art.arcane.volmlib.util.math.RNG; +import art.arcane.iris.core.modules.IrisTestNoise; +import com.volmit.noise.NoiseSampler; +import com.volmit.noise.NoiseStyle; import org.junit.Test; import static org.junit.Assert.assertEquals; @@ -10,6 +11,16 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class StructureCarveEnvelopeTest { + private static final com.volmit.noise.NoiseFactory NOISE = IrisTestNoise.factory(); + + private static NoiseSampler signature(long seed) { + return NOISE.sampler(NoiseStyle.of("IRIS"), seed); + } + + private static NoiseSampler singleOctave(long seed) { + return NOISE.sampler(NoiseStyle.of("SIMPLEX"), seed); + } + @Test public void exactStructureFootprintAlwaysCarves() { assertTrue(StructureCarveEnvelope.shouldCarveOverboreCell( @@ -65,7 +76,7 @@ public class StructureCarveEnvelopeTest { @Test public void erodedCeilingStaysInsideTheAdvertisedCarveShapeExtension() { - CNG roll = CNG.signature(new RNG(4242L)); + NoiseSampler roll = signature(4242L); for (double strength : new double[]{0.25D, 0.5D, 1D}) { int limit = StructureCarveShape.ERODED.maximumCeilingExtension(10, strength); @@ -81,7 +92,7 @@ public class StructureCarveEnvelopeTest { @Test public void floorModulationNeverCutsPastTheConfiguredPadding() { - CNG roll = CNG.signature(new RNG(9001L)); + NoiseSampler roll = signature(9001L); assertEquals(0D, StructureCarveEnvelope.erodedDownReach(null, 0.05D, 1D, 0, 0, 0), 0D); assertEquals(6D, StructureCarveEnvelope.erodedDownReach(null, 0.05D, 0D, 0, 0, 6), 0D); @@ -99,7 +110,7 @@ public class StructureCarveEnvelopeTest { @Test public void lobedSideReachWandersInsideTheConfiguredPaddingBand() { - CNG lobe = new CNG(new RNG(1337L), 1D, 1); + NoiseSampler lobe = singleOctave(1337L); double lowest = 14D; double highest = 0D; @@ -118,7 +129,7 @@ public class StructureCarveEnvelopeTest { @Test public void zeroLobeStrengthKeepsTheUniformPadding() { - CNG lobe = new CNG(new RNG(1337L), 1D, 1); + NoiseSampler lobe = singleOctave(1337L); for (int x = -64; x <= 64; x++) { for (int z = -64; z <= 64; z++) { @@ -133,7 +144,7 @@ public class StructureCarveEnvelopeTest { @Test public void lobeWavelengthSpansTensOfBlocksAtTheDerivedFrequency() { - CNG lobe = new CNG(new RNG(20250729L), 1D, 1); + NoiseSampler lobe = singleOctave(20250729L); int span = 2048; int crossings = 0; double previous = 0D; @@ -153,7 +164,7 @@ public class StructureCarveEnvelopeTest { @Test public void ceilingLobeIsHalfTheWallLobe() { - CNG lobe = new CNG(new RNG(4242L), 1D, 1); + NoiseSampler lobe = singleOctave(4242L); for (int x = -96; x <= 96; x += 3) { for (int z = -96; z <= 96; z += 3) { @@ -170,7 +181,7 @@ public class StructureCarveEnvelopeTest { @Test public void lobeSamplingIsAPureFunctionOfTheColumn() { - CNG lobe = new CNG(new RNG(77L), 1D, 1); + NoiseSampler lobe = singleOctave(77L); for (int x = -32; x <= 32; x += 7) { for (int z = -32; z <= 32; z += 7) { diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlannerTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlannerTest.java index 4c29a0959..69573b4e2 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlannerTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureFoundationPlannerTest.java @@ -1,7 +1,9 @@ package art.arcane.iris.engine.mantle.components; -import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.engine.framework.structure.ColumnHeights; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; import org.junit.Test; import java.util.ArrayList; @@ -10,29 +12,40 @@ import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class StructureFoundationPlannerTest { + private static final BlockState SOLID = new BlockState("minecraft:stone"); + private static final BlockState NON_OCCLUDING_SOLID = new BlockState("minecraft:glass"); + private static final BlockState DECORATION = new BlockState("minecraft:poppy"); + private static final BlockState FLUID = new BlockState("minecraft:water"); + private static final BlockRegistry BLOCKS = blocks(); + + private static BlockRegistry blocks() { + BlockRegistry registry = mock(BlockRegistry.class); + when(registry.hasTrait(any(), any())).thenAnswer(call -> { + BlockState state = call.getArgument(0); + BlockTrait trait = call.getArgument(1); + if (trait == BlockTrait.SOLID) { + return state.equals(SOLID) || state.equals(NON_OCCLUDING_SOLID); + } + return trait == BlockTrait.OCCLUDING && state.equals(SOLID); + }); + return registry; + } + @Test public void recordsLowestPlacedOccludingCellByDefault() { - PlatformBlockState solid = mock(PlatformBlockState.class); - when(solid.isOccluding()).thenReturn(true); - when(solid.isSolid()).thenReturn(true); - PlatformBlockState nonOccludingSolid = mock(PlatformBlockState.class); - when(nonOccludingSolid.isSolid()).thenReturn(true); - when(nonOccludingSolid.isOccluding()).thenReturn(false); - PlatformBlockState decoration = mock(PlatformBlockState.class); - when(decoration.isOccluding()).thenReturn(false); - ColumnHeights columns = new ColumnHeights(0); - StructureFoundationPlanner.recordBaseCell(columns, 100, 48, 200, decoration, false); - StructureFoundationPlanner.recordBaseCell(columns, 100, 49, 200, solid, false); - StructureFoundationPlanner.recordBaseCell(columns, 100, 50, 200, solid, false); - StructureFoundationPlanner.recordBaseCell(columns, 100, 45, 200, solid, false); - StructureFoundationPlanner.recordBaseCell(columns, -17, 60, -33, solid, false); - StructureFoundationPlanner.recordBaseCell(columns, 12, 41, 44, solid, false); - StructureFoundationPlanner.recordBaseCell(columns, 12, 36, 44, nonOccludingSolid, false); + StructureFoundationPlanner.recordBaseCell(columns, 100, 48, 200, DECORATION, BLOCKS, false); + StructureFoundationPlanner.recordBaseCell(columns, 100, 49, 200, SOLID, BLOCKS, false); + StructureFoundationPlanner.recordBaseCell(columns, 100, 50, 200, SOLID, BLOCKS, false); + StructureFoundationPlanner.recordBaseCell(columns, 100, 45, 200, SOLID, BLOCKS, false); + StructureFoundationPlanner.recordBaseCell(columns, -17, 60, -33, SOLID, BLOCKS, false); + StructureFoundationPlanner.recordBaseCell(columns, 12, 41, 44, SOLID, BLOCKS, false); + StructureFoundationPlanner.recordBaseCell(columns, 12, 36, 44, NON_OCCLUDING_SOLID, BLOCKS, false); assertEquals(3, columns.size()); assertEquals(45, columns.get(StructureFoundationPlanner.pack(100, 200))); @@ -44,18 +57,9 @@ public class StructureFoundationPlannerTest { @Test public void recordsSolidNonOccludingBaseWhenEnabled() { - PlatformBlockState partialStructureBlock = mock(PlatformBlockState.class); - when(partialStructureBlock.isSolid()).thenReturn(true); - when(partialStructureBlock.isOccluding()).thenReturn(false); - PlatformBlockState fullStructureBlock = mock(PlatformBlockState.class); - when(fullStructureBlock.isSolid()).thenReturn(true); - when(fullStructureBlock.isOccluding()).thenReturn(true); - ColumnHeights columns = new ColumnHeights(0); - StructureFoundationPlanner.recordBaseCell( - columns, 12, 41, 44, fullStructureBlock, true); - StructureFoundationPlanner.recordBaseCell( - columns, 12, 36, 44, partialStructureBlock, true); + StructureFoundationPlanner.recordBaseCell(columns, 12, 41, 44, SOLID, BLOCKS, true); + StructureFoundationPlanner.recordBaseCell(columns, 12, 36, 44, NON_OCCLUDING_SOLID, BLOCKS, true); assertEquals(1, columns.size()); assertEquals(36, columns.get(StructureFoundationPlanner.pack(12, 44))); @@ -72,30 +76,20 @@ public class StructureFoundationPlannerTest { @Test public void compositeGroundUsesOverlayThenCarvingThenTerrain() { - PlatformBlockState solid = mock(PlatformBlockState.class); - when(solid.isSolid()).thenReturn(true); - PlatformBlockState fluid = mock(PlatformBlockState.class); - when(fluid.isSolid()).thenReturn(false); - - assertTrue(StructureFoundationPlanner.isGroundSolid(solid, true, 12, 20)); - assertFalse(StructureFoundationPlanner.isGroundSolid(fluid, false, 12, 20)); - assertFalse(StructureFoundationPlanner.isGroundSolid(null, true, 12, 20)); - assertTrue(StructureFoundationPlanner.isGroundSolid(null, false, 12, 20)); - assertFalse(StructureFoundationPlanner.isGroundSolid(null, false, 21, 20)); - assertTrue(StructureFoundationPlanner.isGroundSolid(null, true, 0, -20)); + assertTrue(StructureFoundationPlanner.isGroundSolid(SOLID, BLOCKS, true, 12, 20)); + assertFalse(StructureFoundationPlanner.isGroundSolid(FLUID, BLOCKS, false, 12, 20)); + assertFalse(StructureFoundationPlanner.isGroundSolid(null, BLOCKS, true, 12, 20)); + assertTrue(StructureFoundationPlanner.isGroundSolid(null, BLOCKS, false, 12, 20)); + assertFalse(StructureFoundationPlanner.isGroundSolid(null, BLOCKS, false, 21, 20)); + assertTrue(StructureFoundationPlanner.isGroundSolid(null, BLOCKS, true, 0, -20)); } @Test public void surfaceSupportStopsAtCarvedCaveBoundary() { - PlatformBlockState solid = mock(PlatformBlockState.class); - when(solid.isSolid()).thenReturn(true); - PlatformBlockState air = mock(PlatformBlockState.class); - when(air.isSolid()).thenReturn(false); - - assertTrue(StructureFoundationPlanner.isSurfaceSupportBoundary(null, true, 18, 24)); - assertTrue(StructureFoundationPlanner.isSurfaceSupportBoundary(solid, false, 30, 24)); - assertFalse(StructureFoundationPlanner.isSurfaceSupportBoundary(air, false, 30, 24)); - assertTrue(StructureFoundationPlanner.isSurfaceSupportBoundary(null, false, 24, 24)); + assertTrue(StructureFoundationPlanner.isSurfaceSupportBoundary(null, BLOCKS, true, 18, 24)); + assertTrue(StructureFoundationPlanner.isSurfaceSupportBoundary(SOLID, BLOCKS, false, 30, 24)); + assertFalse(StructureFoundationPlanner.isSurfaceSupportBoundary(FLUID, BLOCKS, false, 30, 24)); + assertTrue(StructureFoundationPlanner.isSurfaceSupportBoundary(null, BLOCKS, false, 24, 24)); } @Test diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureOutputPinTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureOutputPinTest.java index cd8d77a0c..57d98a579 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureOutputPinTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructureOutputPinTest.java @@ -16,8 +16,7 @@ import art.arcane.iris.engine.framework.IrisStructureLocator; import art.arcane.iris.engine.framework.structure.assembly.AssembledPiece; import art.arcane.iris.engine.framework.SeedManager; import art.arcane.iris.engine.framework.StructurePlacementScope; -import art.arcane.iris.engine.mantle.EngineMantle; -import art.arcane.iris.engine.mantle.MantleWriter; +import art.arcane.iris.engine.framework.StructureTestWorld; import art.arcane.iris.engine.object.TestSettings; import art.arcane.iris.engine.object.prefab.IrisObject; import art.arcane.iris.engine.object.structure.IrisStructure; @@ -37,9 +36,40 @@ import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.PlatformBlockState; import art.arcane.iris.spi.PlatformRegistries; import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.mantle.runtime.Mantle; -import art.arcane.volmlib.util.matter.Matter; -import art.arcane.volmlib.util.matter.MatterCavern; +import art.arcane.iris.core.modules.IrisPackResources; +import art.arcane.iris.core.modules.PlacementMarkers; +import com.volmit.IrisFeature; +import com.volmit.block.BlockState; +import com.volmit.config.FeatureSettings; +import com.volmit.config.Level; +import com.volmit.config.PackSettings; +import com.volmit.config.SettingsStack; +import com.volmit.data.SavedKey; +import com.volmit.geometry.BlockBox; +import com.volmit.geometry.BlockPosition; +import com.volmit.mantle.CarvedVoid; +import com.volmit.mantle.Mantle; +import com.volmit.mantle.MantleEdit; +import com.volmit.mantle.MantleLayer; +import com.volmit.mantle.MantleVisitor; +import com.volmit.object.BlockEntityData; +import com.volmit.placement.PlacedMarker; +import com.volmit.placement.PlacementRecord; +import com.volmit.placement.PlacementTerrain; +import com.volmit.placement.Placements; +import com.volmit.placement.StructureVolumes; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.stage.MantleStageContext; +import com.volmit.world.BiomeKind; +import com.volmit.world.BiomeSample; +import com.volmit.world.PackWorld; +import com.volmit.world.RunningWorld; +import com.volmit.world.TerrainSample; +import com.volmit.world.TerrainSampler; +import com.volmit.world.UpperDimension; +import com.volmit.ModuleLog; +import com.volmit.config.FeatureSettings.Entry; import com.google.gson.Gson; import com.volmit.host.LoadedPack; import com.volmit.host.ModuleLogs; @@ -64,6 +94,7 @@ import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -90,6 +121,7 @@ public class StructureOutputPinTest { private static final int WORLD_HEIGHT = 320; private static final int FLUID_HEIGHT = 63; private static final int GRID_RADIUS_CHUNKS = 40; + private static final int GRID_BLOCKS = 1_000_000; private static final int CAVE_FLOOR_MANTLE_Y = 50; private static final int CAVE_CEILING_MANTLE_Y = 78; @@ -130,6 +162,7 @@ public class StructureOutputPinTest { art.arcane.iris.core.loader.ResourceLoader objectLoader = mock(art.arcane.iris.core.loader.ResourceLoader.class); when(objectLoader.getPossibleKeys()).thenAnswer(invocation -> objects.keySet().toArray(String[]::new)); when(objectLoader.findFile(anyString())).thenAnswer(invocation -> objectFile(invocation.getArgument(0))); + when(objectLoader.load(anyString())).thenAnswer(invocation -> objects.get((String) invocation.getArgument(0))); when(data.getObjectLoader()).thenReturn(objectLoader); when(data.load(eq(IrisObject.class), anyString(), anyBoolean())) .thenAnswer(invocation -> objects.get((String) invocation.getArgument(1))); @@ -233,14 +266,23 @@ public class StructureOutputPinTest { private Outcome run(StructurePlacement placement) { Engine engine = engineWith(placement); - WriterLog log = new WriterLog(); - MantleWriter writer = recordingWriter(log, engine); + StructureTestWorld world = new StructureTestWorld() + .hostedBy(engine.getGeneration().world()) + .worldSeed(WORLD_SEED) + .placementSeed(new SeedManager(WORLD_SEED).getMantle()) + .minY(MIN_HEIGHT) + .height(WORLD_HEIGHT) + .fluidHeight(FLUID_HEIGHT) + .highest(StructureOutputPinTest::terrainHeight) + .carved((x, mantleY, z) -> caveAt(mantleY)) + .dimension(placement); + WriterLog log = new WriterLog(world); Outcome outcome = new Outcome(); - StructurePlacing placing = new StructurePlacing(engine, ModuleLogs.discarding()); + StructurePlacing placing = new StructurePlacing(world, ModuleLogs.discarding()); for (int chunkX = -GRID_RADIUS_CHUNKS; chunkX < GRID_RADIUS_CHUNKS; chunkX++) { for (int chunkZ = -GRID_RADIUS_CHUNKS; chunkZ < GRID_RADIUS_CHUNKS; chunkZ++) { - for (StructurePlacement scoped : StructurePlacementScope.placementsAt(engine, chunkX, chunkZ)) { - IrisStructureLocator.ResolvedPlacement resolved = IrisStructureLocator.resolvePlacement(engine, scoped, chunkX, chunkZ); + for (StructurePlacement scoped : StructurePlacementScope.placementsAt(world, chunkX, chunkZ)) { + IrisStructureLocator.ResolvedPlacement resolved = IrisStructureLocator.resolvePlacement(world, scoped, chunkX, chunkZ); if (resolved == null) { continue; } @@ -251,7 +293,7 @@ public class StructureOutputPinTest { outcome.pieces.add(describe(piece)); } } - placing.place(writer, chunkX, chunkZ, null); + placing.place(log.contextOf(chunkX, chunkZ)); } } outcome.writes.addAll(log.lines); @@ -268,10 +310,12 @@ public class StructureOutputPinTest { private Engine engineWith(StructurePlacement placement) { Engine engine = mock(Engine.class, withSettings().stubOnly()); IrisDimension dimension = mock(IrisDimension.class, withSettings().stubOnly()); - EngineMantle engineMantle = mock(EngineMantle.class, withSettings().stubOnly()); + art.arcane.iris.engine.mantle.EngineMantle engineMantle = mock(art.arcane.iris.engine.mantle.EngineMantle.class, withSettings().stubOnly()); @SuppressWarnings("unchecked") - Mantle mantle = mock(Mantle.class, withSettings().stubOnly()); - when(mantle.get(anyInt(), anyInt(), anyInt(), eq(MatterCavern.class))).thenAnswer(invocation -> caveAt(invocation.getArgument(1))); + art.arcane.volmlib.util.mantle.runtime.Mantle mantle = + mock(art.arcane.volmlib.util.mantle.runtime.Mantle.class, withSettings().stubOnly()); + when(mantle.get(anyInt(), anyInt(), anyInt(), eq(art.arcane.volmlib.util.matter.MatterCavern.class))) + .thenAnswer(invocation -> caveAt(invocation.getArgument(1)).map(ignored -> new art.arcane.volmlib.util.matter.MatterCavern(true, "", (byte) 3)).orElse(null)); when(engineMantle.getMantle()).thenReturn(mantle); when(engineMantle.trueHeight(anyInt(), anyInt())).thenAnswer(invocation -> terrainHeight(invocation.getArgument(0), invocation.getArgument(1))); when(engine.getMantle()).thenReturn(engineMantle); @@ -299,95 +343,293 @@ public class StructureOutputPinTest { return 128 + Math.floorMod(x * 3 + z * 5, 9) + Math.floorMod(x / 7 - z / 5, 4); } - private static MatterCavern caveAt(int mantleY) { - return mantleY >= CAVE_FLOOR_MANTLE_Y && mantleY <= CAVE_CEILING_MANTLE_Y ? new MatterCavern(true, "", (byte) 3) : null; - } - - private static MantleWriter recordingWriter(WriterLog log, Engine engine) { - return mock(MantleWriter.class, withSettings().stubOnly().defaultAnswer(invocation -> log.answer(invocation, engine))); + private static Optional caveAt(int mantleY) { + return mantleY >= CAVE_FLOOR_MANTLE_Y && mantleY <= CAVE_CEILING_MANTLE_Y ? Optional.of(CarvedVoid.AIR) : Optional.empty(); } + /** + * The mantle placement writes into, as the api shows it: it records every write as one line, in the order the writes + * come, and reads back what was written. + */ private final class WriterLog { - private final Map written = new HashMap<>(); + private final Map written = new HashMap<>(); private final List lines = new ArrayList<>(); - private final ReturnsEmptyValues empty = new ReturnsEmptyValues(); + private final StructureTestWorld world; + private final PlacementTerrain terrain = new RecordingTerrain(); + private final Mantle mantle = new RecordingMantle(); + private final MutableContext context = new MutableContext(); - Object answer(InvocationOnMock invocation, Engine engine) throws Throwable { - Object[] arguments = invocation.getArguments(); - switch (invocation.getMethod().getName()) { - case "getEngine": - return engine; - case "getHighest": - return terrainHeight((Integer) arguments[0], (Integer) arguments[1]); - case "get": - return stateAt((Integer) arguments[0], (Integer) arguments[1], (Integer) arguments[2]); - case "set": - return set(arguments); - case "setData": - lines.add("D " + position(arguments) + "=" + describeData(arguments[3])); - return null; - case "setTile": - lines.add("T " + position(arguments)); - return null; - case "setForcedCarve": - lines.add("C " + position(arguments)); - written.remove(position(arguments)); - return null; - case "clearBlock": - lines.add("X " + position(arguments)); - written.remove(position(arguments)); - return null; - case "clearData": - lines.add("R " + position(arguments) + "=" + ((Class) arguments[3]).getSimpleName()); - return null; - case "getDataIfPresent": - case "getData": - return dataAt(arguments); - case "isSolid": - return stateAt((Integer) arguments[0], (Integer) arguments[1], (Integer) arguments[2]).isSolid(); - case "isSurfaceSolid": - return true; - case "getFluidHeight": - return FLUID_HEIGHT - MIN_HEIGHT; - case "acquireChunk": - return null; - default: - return empty.answer(invocation); - } + WriterLog(StructureTestWorld world) { + this.world = world; } - private Object set(Object[] arguments) { - if (arguments.length != 4 || !(arguments[3] instanceof PlatformBlockState state)) { - return null; - } - lines.add("S " + position(arguments) + "=" + state.key()); - written.put(position(arguments), state); - return null; + MantleStageContext contextOf(int chunkX, int chunkZ) { + context.chunkX = chunkX; + context.chunkZ = chunkZ; + return context; } - private Object dataAt(Object[] arguments) { - Class type = (Class) arguments[3]; - if (type == PlatformBlockState.class) { - return written.get(position(arguments)); - } - return null; - } - - private PlatformBlockState stateAt(int x, int y, int z) { - PlatformBlockState state = written.get(x + "," + y + "," + z); + private BlockState stateAt(int x, int y, int z) { + BlockState state = written.get(position(x, y, z)); if (state != null) { return state; } - boolean ground = y <= terrainHeight(x, z) && (caveAt(y) == null); - return registryState(ground ? "minecraft:stone" : "minecraft:air"); + boolean ground = y <= terrainHeight(x, z) && caveAt(y).isEmpty(); + return new BlockState(ground ? "minecraft:stone" : "minecraft:air"); } - private static String position(Object[] arguments) { - return arguments[0] + "," + arguments[1] + "," + arguments[2]; + private static String position(int x, int y, int z) { + return x + "," + y + "," + z; } - private static String describeData(Object value) { - return value instanceof String text ? "String:" + text : value == null ? "null" : value.getClass().getSimpleName(); + private final class MutableContext implements MantleStageContext { + private int chunkX; + private int chunkZ; + + @Override + public int chunkX() { + return chunkX; + } + + @Override + public int chunkZ() { + return chunkZ; + } + + @Override + public int originX() { + return chunkX << 4; + } + + @Override + public int originZ() { + return chunkZ << 4; + } + + @Override + public PackWorld world() { + return world; + } + + @Override + public TerrainSampler terrain() { + return world.running().orElseThrow().layout(); + } + + @Override + public FeatureSettings settings() { + return world.running().orElseThrow().settings(); + } + + @Override + public Mantle mantle() { + return mantle; + } + + @Override + public PlacementTerrain placementTerrain() { + return terrain; + } + + @Override + public com.volmit.random.WorldRandom random() { + throw new UnsupportedOperationException("No random here"); + } + + @Override + public O output(com.volmit.stage.Stage stage) { + throw new UnsupportedOperationException("No stage outputs here"); + } + + @Override + public SettingsStack configured(Class settingsType) { + throw new UnsupportedOperationException("No stage settings here"); + } + } + + private final class RecordingTerrain implements PlacementTerrain { + @Override + public int highest(int x, int z, boolean ignoreFluid) { + return terrainHeight(x, z); + } + + @Override + public BlockState get(int x, int y, int z) { + return stateAt(x, y, z); + } + + @Override + public void set(int x, int y, int z, BlockState state) { + lines.add("S " + position(x, y, z) + "=" + state.key()); + written.put(position(x, y, z), state); + } + + @Override + public void set(int x, int y, int z, BlockState state, BlockEntityData blockEntity) { + set(x, y, z, state); + lines.add("T " + position(x, y, z)); + } + + @Override + public void clearBlock(int x, int y, int z) { + written.remove(position(x, y, z)); + } + + @Override + public void clearAttached(int x, int y, int z) { + } + + @Override + public boolean isCarved(int x, int y, int z) { + return false; + } + + @Override + public boolean isSurfaceSolid(int x, int y, int z) { + return true; + } + + @Override + public boolean isUnderwater(int x, int z) { + return false; + } + + @Override + public int fluidHeight() { + return FLUID_HEIGHT - MIN_HEIGHT; + } + + @Override + public boolean preventsDecay() { + return false; + } + + @Override + public void recordPlacement(int x, int y, int z, PlacementRecord placement) { + IrisPackResources resources = (IrisPackResources) world.resources(); + lines.add("D " + position(x, y, z) + "=String:" + PlacementMarkers.encode(placement, resources)); + } + + @Override + public Optional placementAt(int x, int y, int z) { + return Optional.empty(); + } + + @Override + public StructureVolumes structureVolumes(int minX, int minZ, int maxX, int maxZ) { + return new StructureVolumes() { + @Override + public boolean isEmpty() { + return true; + } + + @Override + public boolean intersects(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { + return false; + } + + @Override + public boolean containsWithin(int x, int y, int z, int margin) { + return false; + } + }; + } + + @Override + public void mark(PlacedMarker marker) { + BlockPosition at = marker.position(); + String kind = switch (marker) { + case PlacedMarker.TreeMaterial ignored -> "TreeBlockMaterial"; + case PlacedMarker.BuriedTreasure ignored -> "MatterStructurePOI"; + case PlacedMarker.PackMarker ignored -> "MatterMarker"; + }; + lines.add("D " + position(at.x(), at.y(), at.z()) + "=" + kind); + } + } + + private final class RecordingMantle implements Mantle { + private final MantleLayer blocks = new MantleLayer<>() { + @Override + public BlockState get(int x, int y, int z) { + return written.get(position(x, y, z)); + } + + @Override + public void set(int x, int y, int z, BlockState value) { + throw new UnsupportedOperationException("Blocks are written through placements"); + } + + @Override + public void remove(int x, int y, int z) { + throw new UnsupportedOperationException("Blocks are written through placements"); + } + + @Override + public void visit(BlockBox area, MantleVisitor visitor) { + throw new UnsupportedOperationException("No visits here"); + } + + @Override + public void clear(BlockBox area) { + throw new UnsupportedOperationException("No clears here"); + } + }; + private final MantleLayer carved = new MantleLayer<>() { + @Override + public CarvedVoid get(int x, int y, int z) { + return null; + } + + @Override + public void set(int x, int y, int z, CarvedVoid value) { + lines.add("C " + position(x, y, z)); + } + + @Override + public void remove(int x, int y, int z) { + lines.add("R " + position(x, y, z) + "=MatterCavern"); + } + + @Override + public void visit(BlockBox area, MantleVisitor visitor) { + throw new UnsupportedOperationException("No visits here"); + } + + @Override + public void clear(BlockBox area) { + throw new UnsupportedOperationException("No clears here"); + } + }; + + @Override + public BlockBox bounds() { + return new BlockBox(-GRID_BLOCKS, 0, -GRID_BLOCKS, GRID_BLOCKS, WORLD_HEIGHT, GRID_BLOCKS); + } + + @Override + public MantleLayer layer(com.volmit.mantle.MantleKey key) { + throw new UnsupportedOperationException("No module layers here"); + } + + @Override + public MantleLayer blocks() { + return blocks; + } + + @Override + public MantleLayer carved() { + return carved; + } + + @Override + public void setPlatformBiome(int x, int y, int z, ResourceId biome) { + throw new UnsupportedOperationException("No biomes here"); + } + + @Override + public MantleEdit edit() { + throw new UnsupportedOperationException("No edits here"); + } } } diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructurePlacingMarkerTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructurePlacingMarkerTest.java index a19372c7d..376059ca0 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructurePlacingMarkerTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructurePlacingMarkerTest.java @@ -9,9 +9,11 @@ import com.volmit.resource.ResourceId; import java.util.List; import art.arcane.iris.builtin.structure.StructurePlacement; import art.arcane.iris.builtin.structure.NativeStructureSuppression; -import art.arcane.iris.spi.PlatformBlockState; import art.arcane.volmlib.util.collection.KList; import art.arcane.volmlib.util.math.RNG; +import com.volmit.block.BlockRegistry; +import com.volmit.block.BlockState; +import com.volmit.block.BlockTrait; import org.junit.Test; import static art.arcane.iris.engine.framework.StructurePlacementFixtures.placement; @@ -27,14 +29,13 @@ import static org.mockito.Mockito.when; public class StructurePlacingMarkerTest { @Test public void markerFilterAcceptsOnlyStorageContainers() { - PlatformBlockState storage = mock(PlatformBlockState.class); - PlatformBlockState solid = mock(PlatformBlockState.class); - when(storage.isStorageChest()).thenReturn(true); - when(solid.isStorageChest()).thenReturn(false); + BlockState storage = new BlockState("minecraft:chest"); + BlockState solid = new BlockState("minecraft:stone"); + BlockRegistry blocks = blocksWith(BlockTrait.STORAGE, storage); - assertTrue(StructurePlacing.shouldWriteStructureMarker(storage)); - assertFalse(StructurePlacing.shouldWriteStructureMarker(solid)); - assertFalse(StructurePlacing.shouldWriteStructureMarker(null)); + assertTrue(StructurePlacing.shouldWriteStructureMarker(storage, blocks)); + assertFalse(StructurePlacing.shouldWriteStructureMarker(solid, blocks)); + assertFalse(StructurePlacing.shouldWriteStructureMarker(null, blocks)); } @Test @@ -49,14 +50,21 @@ public class StructurePlacingMarkerTest { @Test public void treeCollisionUsesOnlyNonAirStructureBlocks() { - PlatformBlockState solid = mock(PlatformBlockState.class); - PlatformBlockState air = mock(PlatformBlockState.class); - when(solid.isAir()).thenReturn(false); - when(air.isAir()).thenReturn(true); + BlockState solid = new BlockState("minecraft:stone"); + BlockState air = new BlockState("minecraft:air"); + BlockRegistry blocks = blocksWith(BlockTrait.AIR, air); - assertTrue(StructurePlacing.isOccupiedStructureState(solid)); - assertFalse(StructurePlacing.isOccupiedStructureState(air)); - assertFalse(StructurePlacing.isOccupiedStructureState(null)); + assertTrue(StructurePlacing.isOccupiedStructureState(solid, blocks)); + assertFalse(StructurePlacing.isOccupiedStructureState(air, blocks)); + assertFalse(StructurePlacing.isOccupiedStructureState(null, blocks)); + } + + private static BlockRegistry blocksWith(BlockTrait trait, BlockState... having) { + BlockRegistry blocks = mock(BlockRegistry.class); + for (BlockState state : having) { + when(blocks.hasTrait(state, trait)).thenReturn(true); + } + return blocks; } @Test diff --git a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructurePlacingOverboreTest.java b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructurePlacingOverboreTest.java index b84ff804d..36e415a91 100644 --- a/core/src/test/java/art/arcane/iris/engine/mantle/components/StructurePlacingOverboreTest.java +++ b/core/src/test/java/art/arcane/iris/engine/mantle/components/StructurePlacingOverboreTest.java @@ -1,7 +1,11 @@ package art.arcane.iris.engine.mantle.components; +import com.volmit.placement.PlacementRecord; +import com.volmit.resource.ResourceId; import org.junit.Test; +import java.util.Optional; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -9,10 +13,11 @@ import static org.junit.Assert.assertTrue; public class StructurePlacingOverboreTest { @Test public void ordinaryMarkersAreSeparatedFromStructureMarkers() { - assertTrue(StructurePlacing.isOrdinaryObjectMarker("trees/oak@42")); - assertFalse(StructurePlacing.isOrdinaryObjectMarker( - "@iris-structure:v1:dHJlZXMvb2Fr:42:bWluZWNyYWZ0Om1hbnNpb24")); - assertFalse(StructurePlacing.isOrdinaryObjectMarker("not-a-marker")); + ResourceId oak = new ResourceId("test", "trees/oak"); + assertTrue(StructurePlacing.isOrdinaryObjectRecord(Optional.of(PlacementRecord.of(oak, 42)))); + assertFalse(StructurePlacing.isOrdinaryObjectRecord( + Optional.of(PlacementRecord.ofPiece(oak, 42, new ResourceId("minecraft", "mansion"))))); + assertFalse(StructurePlacing.isOrdinaryObjectRecord(Optional.empty())); } @Test diff --git a/module/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java b/module/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java index 5703e7117..7c3888ccb 100644 --- a/module/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java +++ b/module/src/main/java/art/arcane/iris/builtin/structure/StructureHost.java @@ -17,7 +17,7 @@ */ package art.arcane.iris.builtin.structure; -import com.volmit.generation.InvocationContext; +import com.volmit.stage.MantleStageContext; import com.volmit.resource.ResourceId; import java.util.List; @@ -31,7 +31,7 @@ import java.util.Optional; */ public interface StructureHost { /** Places the structures that start in the chunk whose mantle the mantle invocation {@code context} generates. */ - void placeChunk(InvocationContext context); + void placeChunk(MantleStageContext context); /** How far, in blocks along X and Z, a structure may write beyond the chunk it starts in. */ int reach(); diff --git a/module/src/main/java/art/arcane/iris/builtin/structure/StructureSeeds.java b/module/src/main/java/art/arcane/iris/builtin/structure/StructureSeeds.java new file mode 100644 index 000000000..78fc4c0cd --- /dev/null +++ b/module/src/main/java/art/arcane/iris/builtin/structure/StructureSeeds.java @@ -0,0 +1,15 @@ +package art.arcane.iris.builtin.structure; + +import com.volmit.resource.ResourceId; + +/** The seed purposes of structure placement, for {@link com.volmit.world.PackWorld#seed(ResourceId)}. */ +public final class StructureSeeds { + /** + * The seed placements start from: where structures start, their anchors and their pieces. Iris keeps the seed it has + * always used for it, so the structures of existing worlds stay where they are. + */ + public static final ResourceId PLACEMENT = ResourceId.parse("iris:structure/placement"); + + private StructureSeeds() { + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/objects/ForwardingTerrain.java b/module/src/main/java/art/arcane/iris/modules/objects/ForwardingTerrain.java index b3b5866ab..9ff2023ce 100644 --- a/module/src/main/java/art/arcane/iris/modules/objects/ForwardingTerrain.java +++ b/module/src/main/java/art/arcane/iris/modules/objects/ForwardingTerrain.java @@ -90,6 +90,16 @@ public abstract class ForwardingTerrain implements PlacementTerrain { delegate.recordPlacement(x, y, z, placement); } + @Override + public void clearBlock(int x, int y, int z) { + delegate.clearBlock(x, y, z); + } + + @Override + public void clearAttached(int x, int y, int z) { + delegate.clearAttached(x, y, z); + } + @Override public Optional placementAt(int x, int y, int z) { return delegate.placementAt(x, y, z);