Merge underground lava

- Deep lava pools, cave springs and the cave fluid probe from hydro/f3
- Recaptured the settings fingerprint and schema digest for the combined code
This commit is contained in:
Brian Fopiano committed 2026-11-03 14:01:25 -05:00
commit b0747d7483
31 files changed
+1608 -40

No files matched your search

@@ -4,5 +4,6 @@ public enum HydrologyCaveAction {
WET_SOURCE,
DRY_AIR,
SEAL_GUARD,
POOL_SOURCE
POOL_SOURCE,
SPRING_SOURCE
}
@@ -20,7 +20,7 @@ public final class HydrologyCaveCell {
}
this.fluidProfileKey = fluidProfileKey.trim();
this.cavern = switch (action) {
case WET_SOURCE, POOL_SOURCE -> new MatterCavern(true, "", LIQUID_FLUID);
case WET_SOURCE, POOL_SOURCE, SPRING_SOURCE -> new MatterCavern(true, "", LIQUID_FLUID);
case DRY_AIR -> new MatterCavern(true, "", LIQUID_FORCED_AIR);
case SEAL_GUARD -> null;
};
@@ -31,7 +31,7 @@ public final class HydrologyCaveCell {
}
public boolean isWet() {
return action == HydrologyCaveAction.WET_SOURCE || action == HydrologyCaveAction.POOL_SOURCE;
return action == HydrologyCaveAction.WET_SOURCE || action == HydrologyCaveAction.POOL_SOURCE || action == HydrologyCaveAction.SPRING_SOURCE;
}
public MatterCavern asCavern() {
@@ -50,4 +50,12 @@ public class IrisCavePools {
@Required
@Description("Name of the fluid profile that fills cave pools. The hydrology policy fluid of the cave biome at the pool replaces it, then that of its region, then that of the dimension. A surface biome's policy never fills cave pools.")
private String fluid = "water";
@Description("Name of the fluid profile that fills pools at or below deepFluidMaxY. Unset keeps the same fluid at every depth. A hydrology policy that names a fluid still replaces it.")
private String deepFluid;
@MinNumber(-2032)
@MaxNumber(2031)
@Description("Highest world Y that deepFluid fills. No pool crosses this height: a pool rising from below stops at it.")
private int deepFluidMaxY = -128;
}
@@ -0,0 +1,32 @@
package art.arcane.iris.generation.hydrology.config;
import art.arcane.iris.pack.schema.annotation.MaxNumber;
import art.arcane.iris.pack.schema.annotation.MinNumber;
import art.arcane.iris.pack.schema.annotation.Required;
import art.arcane.volmlib.util.documentation.Description;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Accessors(chain = true)
@NoArgsConstructor
@Description("Seep points in carved cave walls. Each holds one source block that the game's fluid physics spreads once the chunk is loaded.")
@Data
public class IrisCaveSprings {
@Description("Places springs in cave walls.")
private boolean enabled = false;
@MinNumber(0)
@MaxNumber(2)
@Description("Candidate spring sites per chunk.")
private double density = 0.05D;
@Required
@Description("Name of the fluid profile a spring runs with. The hydrology policy fluid of the cave biome at the seep replaces it, then that of its region, then that of the dimension.")
private String fluid = "lava";
@MinNumber(0)
@MaxNumber(256)
@Description("Fewest blocks of ground kept between the surface and a spring, its opening and the cave it runs into.")
private int minDepthBelowSurface = 16;
}
@@ -7,7 +7,7 @@ import lombok.experimental.Accessors;
@Accessors(chain = true)
@NoArgsConstructor
@Description("Water below the surface: flooded passages that run inland from the sea, and pools on cave floors.")
@Description("Water below the surface: flooded passages that run inland from the sea, pools on cave floors, and springs in cave walls.")
@Data
public class IrisHydrologyUnderground {
@Description("Flooded passages at sea level that run inland from coastal cliffs.")
@@ -15,4 +15,7 @@ public class IrisHydrologyUnderground {
@Description("Standing water on the floors of carved caves.")
private IrisCavePools cavePools = new IrisCavePools();
@Description("Seep points in cave walls with one source block that the game's fluid physics spreads.")
private IrisCaveSprings caveSprings = new IrisCaveSprings();
}
@@ -156,7 +156,7 @@ public final class HydrologyRuntime {
engine.getHeight());
requireBiomeFluids(dimension.getReachableBiomes(engine), settings);
boolean caveFluidPolicies = requireCaveFluids(dimension, dimension.getAllRegions(engine), dimension.getReachableCaveBiomes(engine), settings)
&& settings.underground().cavePools().enabled();
&& (settings.underground().cavePools().enabled() || settings.underground().caveSprings().enabled());
if (settings.density() == 0D) {
return DISABLED;
}
@@ -4,6 +4,7 @@ import art.arcane.iris.generation.block.IrisBlockData;
import art.arcane.iris.generation.decoration.IrisDecorationPart;
import art.arcane.iris.generation.decoration.IrisDecorator;
import art.arcane.iris.generation.hydrology.config.IrisCavePools;
import art.arcane.iris.generation.hydrology.config.IrisCaveSprings;
import art.arcane.iris.generation.hydrology.config.IrisFluidProfile;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyClimate;
import art.arcane.iris.generation.hydrology.config.IrisHydrology;
@@ -62,6 +63,10 @@ public final class HydrologySettings {
public static final int MAX_CAVE_POOL_RADIUS = 15;
private static final int CAVE_POOL_SPAN = 2 * MAX_CAVE_POOL_RADIUS + 1;
private static final int MAX_CAVE_POOL_AREA = CAVE_POOL_SPAN * CAVE_POOL_SPAN;
private static final int MIN_DEEP_FLUID_Y = -2032;
private static final int MAX_DEEP_FLUID_Y = 2031;
private static final double MAX_SPRING_DENSITY = 2D;
private static final int MAX_SPRING_DEPTH = 256;
private static final int MAX_LAKE_AREA = LakeCandidate.MAX_EXTENT * LakeCandidate.MAX_EXTENT;
private static final int MAX_PREFETCH_RINGS = 4;
private static final int MAX_SEEDED_DENSITY = 64;
@@ -356,7 +361,7 @@ public final class HydrologySettings {
}
private Underground underground(IrisHydrologyUnderground config) {
return new Underground(seaInlets(config.getSeaInlets()), cavePools(config.getCavePools()));
return new Underground(seaInlets(config.getSeaInlets()), cavePools(config.getCavePools()), caveSprings(config.getCaveSprings()));
}
private SeaInlets seaInlets(IrisSeaInlets config) {
@@ -411,7 +416,22 @@ public final class HydrologySettings {
return new CavePools(config.isEnabled(), (float) config.getDensity(), config.getMinArea(), config.getMaxArea(),
config.getMaxDepth(), config.getRadius(),
intRange(config.getFreeboard(), "underground.cavePools.freeboard", RangeFloor.NON_NEGATIVE),
config.getFluid());
config.getFluid(), blankToNull(config.getDeepFluid()), config.getDeepFluidMaxY());
}
private static CaveSprings caveSprings(IrisCaveSprings config) {
if (config.isEnabled()) {
if (!(Double.isFinite(config.getDensity()) && config.getDensity() >= 0D && config.getDensity() <= MAX_SPRING_DENSITY)) {
throw new IllegalArgumentException("Hydrology underground.caveSprings.density must stay within 0.." + MAX_SPRING_DENSITY
+ ", got " + config.getDensity());
}
requireWithin(config.getMinDepthBelowSurface(), 0, MAX_SPRING_DEPTH, "underground.caveSprings.minDepthBelowSurface");
}
return new CaveSprings(config.isEnabled(), (float) config.getDensity(), config.getFluid(), config.getMinDepthBelowSurface());
}
private static String blankToNull(String value) {
return value == null || value.isBlank() ? null : value;
}
private static Map<String, IrisMaterialPalette> fluids(List<IrisFluidProfile> profiles) {
@@ -610,6 +630,9 @@ public final class HydrologySettings {
if (!pools.enabled()) {
return;
}
if (pools.deepFluid() != null) {
requireWithin(pools.deepFluidMaxY(), MIN_DEEP_FLUID_Y, MAX_DEEP_FLUID_Y, "underground.cavePools.deepFluidMaxY");
}
if (pools.freeboard().max() >= pools.maxDepth()) {
throw new IllegalArgumentException("Hydrology underground.cavePools.freeboard max " + pools.freeboard().max()
+ " must stay below maxDepth " + pools.maxDepth());
@@ -657,6 +680,12 @@ public final class HydrologySettings {
}
requireFillingFluid(ponds.fluid(), "ponds.fluid");
requireFillingFluid(underground.cavePools().fluid(), "underground.cavePools.fluid");
if (underground.cavePools().deepFluid() != null) {
requireFillingFluid(underground.cavePools().deepFluid(), "underground.cavePools.deepFluid");
}
if (underground.caveSprings().enabled()) {
requireFillingFluid(underground.caveSprings().fluid(), "underground.caveSprings.fluid");
}
}
public void requireFillingFluid(String name, String field) {
@@ -731,11 +760,14 @@ public final class HydrologySettings {
private void addUnderground(Fingerprint hash) {
SeaInlets inlets = underground.seaInlets();
CavePools pools = underground.cavePools();
CaveSprings springs = underground.caveSprings();
hash.add(inlets.enabled()).add(inlets.spacing()).add(inlets.minimumCliffHeight()).add(inlets.length())
.add(inlets.halfWidth()).add(inlets.depth()).add(inlets.headroom()).add(inlets.roofClearance())
.add(inlets.chamberRadius())
.add(pools.enabled()).add(pools.density()).add(pools.minArea()).add(pools.maxArea())
.add(pools.maxDepth()).add(pools.radius()).add(pools.freeboard()).add(pools.fluid());
.add(pools.maxDepth()).add(pools.radius()).add(pools.freeboard()).add(pools.fluid())
.add(pools.deepFluid()).add(pools.deepFluidMaxY())
.add(springs.enabled()).add(springs.density()).add(springs.fluid()).add(springs.minDepthBelowSurface());
}
private void addFluids(Fingerprint hash) {
@@ -801,10 +833,13 @@ public final class HydrologySettings {
}
public record CavePools(boolean enabled, float density, int minArea, int maxArea, int maxDepth, int radius,
IntRange freeboard, String fluid) {
IntRange freeboard, String fluid, String deepFluid, int deepFluidMaxY) {
}
public record Underground(SeaInlets seaInlets, CavePools cavePools) {
public record CaveSprings(boolean enabled, float density, String fluid, int minDepthBelowSurface) {
}
public record Underground(SeaInlets seaInlets, CavePools cavePools, CaveSprings caveSprings) {
}
private enum RangeFloor {
@@ -6,4 +6,6 @@ public interface CarvedTerrain {
int surface(int x, int z);
String caveFluid(int x, int y, int z);
boolean structureNear(int x, int y, int z);
}
@@ -5,6 +5,7 @@ import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell;
import art.arcane.iris.generation.hydrology.grid.CellHash;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.mantle.MantleWriter;
import art.arcane.volmlib.util.matter.slices.UpdateMatter;
import it.unimi.dsi.fastutil.longs.LongArrayFIFOQueue;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
@@ -33,11 +34,18 @@ public final class CavePoolFiller {
private final HydrologySettings.CavePools pools;
private final Set<String> fluids;
private final float density;
private final int deepLine;
public CavePoolFiller(HydrologySettings settings) {
public CavePoolFiller(HydrologySettings settings, int worldMinimumY) {
this.pools = settings.underground().cavePools();
this.fluids = settings.fluids().keySet();
this.density = settings.density();
this.deepLine = pools.deepFluidMaxY() - worldMinimumY;
int height = settings.maxY() - settings.minY();
if (pools.enabled() && pools.deepFluid() != null && (deepLine < 0 || deepLine >= height)) {
throw new IllegalStateException("Hydrology underground.cavePools.deepFluidMaxY " + pools.deepFluidMaxY()
+ " is outside this world, which spans Y " + worldMinimumY + " to " + (worldMinimumY + height - 1));
}
}
public void fill(int chunkX, int chunkZ, Supplier<? extends CarvedTerrain> terrain, MantleWriter writer, long seed) {
@@ -167,9 +175,13 @@ public final class CavePoolFiller {
}
int y = unpackY(cell);
HydrologyCaveCell existing = writer.getDataIfPresent(x, y, z, HydrologyCaveCell.class);
if (existing == null || replacesSharedWall(existing, value)) {
boolean spring = existing != null && existing.action() == HydrologyCaveAction.SPRING_SOURCE;
if (existing == null || spring || replacesSharedWall(existing, value)) {
writer.setData(x, y, z, value);
}
if (spring) {
writer.setData(x, y, z, UpdateMatter.OFF);
}
}
}
@@ -180,7 +192,10 @@ public final class CavePoolFiller {
private String fluid(CarvedTerrain carved, int x, int y, int z) {
String policy = carved.caveFluid(x, y, z);
return policy != null ? policy : pools.fluid();
if (policy != null) {
return policy;
}
return pools.deepFluid() != null && y <= deepLine ? pools.deepFluid() : pools.fluid();
}
private String siteFluid(CarvedTerrain carved, int x, int y, int z) {
@@ -0,0 +1,182 @@
package art.arcane.iris.generation.hydrology.underground;
import art.arcane.iris.generation.hydrology.cave.HydrologyCaveAction;
import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell;
import art.arcane.iris.generation.hydrology.grid.CellHash;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.mantle.MantleWriter;
import art.arcane.volmlib.util.matter.slices.UpdateMatter;
import it.unimi.dsi.fastutil.longs.LongArrayFIFOQueue;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import java.util.Set;
import java.util.function.Supplier;
public final class CaveSpringPlacer {
private static final int FLOW_REACH = HydrologySettings.MAX_CAVE_POOL_RADIUS;
private static final int FLOW_LIMIT = 4096;
private static final long SALT_SITES = 0x535052495445L;
private static final long SALT_DENSITY = 0x535052444e53L;
private static final long SALT_COLUMN = 0x535052434f4cL;
private static final long SALT_SEEP = 0x5350525345L << 20;
private static final int[] SIDE_X = {1, -1, 0, 0};
private static final int[] SIDE_Z = {0, 0, 1, -1};
private final HydrologySettings.CaveSprings springs;
private final Set<String> fluids;
private final float density;
public CaveSpringPlacer(HydrologySettings settings) {
this.springs = settings.underground().caveSprings();
this.fluids = settings.fluids().keySet();
this.density = settings.density();
}
public void place(int chunkX, int chunkZ, Supplier<? extends CarvedTerrain> terrain, MantleWriter writer, long seed) {
if (!springs.enabled() || springs.density() == 0f || density == 0f) {
return;
}
int attempts = attempts(seed, chunkX, chunkZ);
for (int attempt = 0; attempt < attempts; attempt++) {
if (density < 1f && CellHash.unit(CellHash.mix(seed, SALT_DENSITY + attempt, chunkX, chunkZ)) >= density) {
continue;
}
CarvedTerrain carved = terrain.get();
long column = CellHash.mix(seed, SALT_COLUMN + attempt, chunkX, chunkZ);
int x = (chunkX << 4) + (int) (column & 15);
int z = (chunkZ << 4) + (int) ((column >>> 4) & 15);
int y = seep(carved, x, z, seed);
if (y >= 0 && contained(carved, x, y, z) && !carved.structureNear(x, y, z)) {
write(chunkX, chunkZ, x, y, z, new HydrologyCaveCell(HydrologyCaveAction.SPRING_SOURCE, fluid(carved, x, y, z)), writer);
}
}
}
private int attempts(long seed, int chunkX, int chunkZ) {
double sites = springs.density();
int whole = (int) sites;
return whole + (CellHash.unit(CellHash.mix(seed, SALT_SITES, chunkX, chunkZ)) < sites - whole ? 1 : 0);
}
private int seep(CarvedTerrain carved, int x, int z, long seed) {
int top = carved.surface(x, z) - springs.minDepthBelowSurface();
int chosen = -1;
long chosenHash = Long.MAX_VALUE;
CaveVoxel below = carved.voxel(x, 1, z);
CaveVoxel voxel = carved.voxel(x, 2, z);
for (int y = 2; y <= top; y++) {
CaveVoxel above = carved.voxel(x, y + 1, z);
if (below == CaveVoxel.SOLID && voxel == CaveVoxel.SOLID && above == CaveVoxel.SOLID && opens(carved, x, y, z)) {
long hash = CellHash.mix(seed, SALT_SEEP + y, x, z);
if (hash < chosenHash) {
chosenHash = hash;
chosen = y;
}
}
below = voxel;
voxel = above;
}
return chosen;
}
private static boolean opens(CarvedTerrain carved, int x, int y, int z) {
for (int side = 0; side < 4; side++) {
int sideX = x + SIDE_X[side];
int sideZ = z + SIDE_Z[side];
if (carved.voxel(sideX, y, sideZ) == CaveVoxel.AIR && carved.voxel(sideX, y - 1, sideZ) == CaveVoxel.AIR) {
return true;
}
}
return false;
}
private boolean contained(CarvedTerrain carved, int seepX, int seepY, int seepZ) {
LongOpenHashSet visited = new LongOpenHashSet();
LongArrayFIFOQueue queue = new LongArrayFIFOQueue();
for (int side = 0; side < 4; side++) {
int sideX = seepX + SIDE_X[side];
int sideZ = seepZ + SIDE_Z[side];
CaveVoxel voxel = carved.voxel(sideX, seepY, sideZ);
if (voxel == CaveVoxel.FOREIGN) {
return false;
}
if (voxel == CaveVoxel.AIR) {
if (!roofed(carved, sideX, seepY, sideZ)) {
return false;
}
long cell = pack(sideX, seepY, sideZ);
visited.add(cell);
queue.enqueue(cell);
}
}
while (!queue.isEmpty() && visited.size() <= FLOW_LIMIT) {
long cell = queue.dequeueLong();
int x = unpackX(cell);
int y = unpackY(cell);
int z = unpackZ(cell);
if (y > carved.surface(x, z) - springs.minDepthBelowSurface()) {
return false;
}
for (int next = 0; next < 5; next++) {
int nextX = next < 4 ? x + SIDE_X[next] : x;
int nextY = next < 4 ? y : y - 1;
int nextZ = next < 4 ? z + SIDE_Z[next] : z;
if (Math.abs(nextX - seepX) > FLOW_REACH || Math.abs(nextZ - seepZ) > FLOW_REACH) {
continue;
}
CaveVoxel voxel = carved.voxel(nextX, nextY, nextZ);
if (voxel == CaveVoxel.FOREIGN) {
return false;
}
if (voxel == CaveVoxel.AIR && visited.add(pack(nextX, nextY, nextZ))) {
queue.enqueue(pack(nextX, nextY, nextZ));
}
}
}
return true;
}
private static boolean roofed(CarvedTerrain carved, int x, int startY, int z) {
int y = startY + 1;
CaveVoxel voxel = carved.voxel(x, y, z);
while (voxel == CaveVoxel.AIR) {
voxel = carved.voxel(x, ++y, z);
}
return voxel == CaveVoxel.SOLID;
}
private String fluid(CarvedTerrain carved, int x, int y, int z) {
String policy = carved.caveFluid(x, y, z);
String fluid = policy != null ? policy : springs.fluid();
if (!fluids.contains(fluid)) {
throw new IllegalStateException("Cave spring at " + x + "," + y + "," + z + " names fluid '" + fluid
+ "', which is not one of the hydrology fluids " + fluids);
}
return fluid;
}
private static void write(int chunkX, int chunkZ, int x, int y, int z, HydrologyCaveCell source, MantleWriter writer) {
writer.withChunkFence(chunkX, chunkZ, () -> {
if (writer.getDataIfPresent(x, y, z, HydrologyCaveCell.class) == null) {
writer.setData(x, y, z, source);
writer.setData(x, y, z, UpdateMatter.ON);
}
});
}
private static long pack(int x, int y, int z) {
return ((long) (x + (1 << 25)) << 38) | ((long) (z + (1 << 25)) << 12) | y;
}
private static int unpackX(long cell) {
return (int) (cell >>> 38) - (1 << 25);
}
private static int unpackZ(long cell) {
return (int) ((cell >>> 12) & ((1L << 26) - 1)) - (1 << 25);
}
private static int unpackY(long cell) {
return (int) (cell & 4095);
}
}
@@ -15,6 +15,8 @@ import art.arcane.iris.generation.subterrain.SubterrainPlanner;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.generation.terrain.Terrain3DColumn;
import art.arcane.iris.structure.placement.StructurePlacementScope;
import art.arcane.volmlib.nativelib.terrain.structure.NativeStructureVolume;
import art.arcane.volmlib.util.mantle.flag.MantleFlag;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.matter.Matter;
@@ -29,6 +31,8 @@ import java.util.Map;
final class MantleCarvedTerrain implements CarvedTerrain {
private static final int SPAN = 48;
private static final int UNKNOWN = Integer.MIN_VALUE;
private static final int STRUCTURE_REACH_CHUNKS = 8;
private static final int IMPORTED_STRUCTURE_REACH = 32;
private final MantleWriter writer;
private final IrisComplex complex;
@@ -120,6 +124,31 @@ final class MantleCarvedTerrain implements CarvedTerrain {
return IrisHydrologyPolicy.inherited(biome == null ? List.of() : List.of(biome), region, dimension, IrisHydrologyPolicy::getFluid);
}
@Override
public boolean structureNear(int x, int y, int z) {
if (dimension.getTerrainTransform() != null) {
return true;
}
long revision = ProvisionalSampling.revision();
boolean near = importedStructureNear(x, y, z) || StructurePlacementScope.startsNear(engine, chunkX, chunkZ, STRUCTURE_REACH_CHUNKS);
requireFinal(revision, chunkX << 4, chunkZ << 4);
return near;
}
private boolean importedStructureNear(int x, int y, int z) {
int minX = x - IMPORTED_STRUCTURE_REACH;
int minZ = z - IMPORTED_STRUCTURE_REACH;
int maxX = x + IMPORTED_STRUCTURE_REACH;
int maxZ = z + IMPORTED_STRUCTURE_REACH;
int maxY = y + minimumY + 1;
for (NativeStructureVolume volume : engine.getNativeStructureVolumes(minX, minZ, maxX, maxZ)) {
if (volume.intersects(minX, minimumY, minZ, maxX, maxY, maxZ)) {
return true;
}
}
return false;
}
private static Collection<SeaInlet> inlets(HydrologyRuntime runtime, int chunkX, int chunkZ) {
Map<Long, SeaInlet> inlets = new LinkedHashMap<>();
for (int offsetZ = -1; offsetZ <= 1; offsetZ++) {
@@ -4,11 +4,14 @@ import art.arcane.iris.generation.context.ChunkContext;
import art.arcane.iris.generation.decoration.IrisProceduralBlocks;
import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell;
import art.arcane.iris.generation.hydrology.config.IrisHydrology;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyUnderground;
import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
import art.arcane.iris.generation.hydrology.raster.FluidSeams;
import art.arcane.iris.generation.hydrology.underground.CarvedTerrain;
import art.arcane.iris.generation.hydrology.underground.CavePoolFiller;
import art.arcane.iris.generation.hydrology.underground.CaveSpringPlacer;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.underground.SeaInletRasterizer;
import art.arcane.iris.generation.runtime.Engine;
@@ -23,6 +26,7 @@ import art.arcane.volmlib.util.matter.slices.UpdateMatter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
@ComponentFlag(ReservedFlag.RIVER_HYDROLOGY)
public final class MantleHydrologyComponent extends IrisMantleComponent {
@@ -44,12 +48,12 @@ public final class MantleHydrologyComponent extends IrisMantleComponent {
@Override
protected int computeRadius() {
return poolsActive() ? CavePoolFiller.REACH : 0;
return caveWaterActive() ? CavePoolFiller.REACH : 0;
}
@Override
public int getInputRadius() {
return poolsActive() ? CavePoolFiller.REACH : 0;
return caveWaterActive() ? CavePoolFiller.REACH : 0;
}
public static boolean isEnabledFor(IrisDimension dimension) {
@@ -58,15 +62,18 @@ public final class MantleHydrologyComponent extends IrisMantleComponent {
&& !dimension.getDisabledComponents().contains(ReservedFlag.RIVER_HYDROLOGY);
}
private static boolean poolsEnabledFor(IrisDimension dimension) {
return isEnabledFor(dimension) && dimension.isCarvingEnabled() && !dimension.getDisabledComponents().contains(ReservedFlag.CARVED)
&& dimension.getHydrology().getUnderground().getCavePools().isEnabled();
private static boolean caveWaterEnabledFor(IrisDimension dimension) {
if (!isEnabledFor(dimension) || !dimension.isCarvingEnabled() || dimension.getDisabledComponents().contains(ReservedFlag.CARVED)) {
return false;
}
IrisHydrologyUnderground underground = dimension.getHydrology().getUnderground();
return underground.getCavePools().isEnabled() || underground.getCaveSprings().isEnabled();
}
private boolean poolsActive() {
private boolean caveWaterActive() {
EngineMantle mantle = getEngineMantle();
Engine engine = mantle == null ? null : mantle.getEngine();
return engine != null && engine.getDimension() != null && poolsEnabledFor(engine.getDimension());
return engine != null && engine.getDimension() != null && caveWaterEnabledFor(engine.getDimension());
}
@Override
@@ -85,11 +92,18 @@ public final class MantleHydrologyComponent extends IrisMantleComponent {
}
}
generateFalls(writer, complex, runtime, own, chunkX, chunkZ);
if (poolsActive()) {
if (caveWaterActive()) {
HydrologySettings settings = runtime.settings();
Engine engine = getEngineMantle().getEngine();
new CavePoolFiller(settings).fill(chunkX, chunkZ, () -> new MantleCarvedTerrain(writer, complex, engine, chunkX, chunkZ), writer,
settings.seed());
CarvedTerrain[] opened = new CarvedTerrain[1];
Supplier<CarvedTerrain> carved = () -> {
if (opened[0] == null) {
opened[0] = new MantleCarvedTerrain(writer, complex, engine, chunkX, chunkZ);
}
return opened[0];
};
new CavePoolFiller(settings, engine.getWorld().minHeight()).fill(chunkX, chunkZ, carved, writer, settings.seed());
new CaveSpringPlacer(settings).place(chunkX, chunkZ, carved, writer, settings.seed());
}
}
@@ -418,7 +418,7 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
return null;
}
return switch (hydrology.action()) {
case WET_SOURCE, POOL_SOURCE -> fluid;
case WET_SOURCE, POOL_SOURCE, SPRING_SOURCE -> fluid;
case DRY_AIR -> air;
case SEAL_GUARD -> normalizeWaterlogging(current, null);
};
@@ -8,6 +8,7 @@ import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyTier;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyWetness;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.hydrology.underground.CavePoolFiller;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.generation.terrain.ShoreBiomeLineages;
@@ -111,8 +112,9 @@ final class PackHydrologyValidator {
private static boolean validateCompile(String path, IrisDimension dimension, List<String> errors) {
try {
HydrologySettings.compile(dimension.getHydrology(), 0L, dimension.getFluidHeight(), 0,
HydrologySettings settings = HydrologySettings.compile(dimension.getHydrology(), 0L, dimension.getFluidHeight(), 0,
dimension.getMaxHeight() - dimension.getMinHeight());
new CavePoolFiller(settings, dimension.getMinHeight());
return true;
} catch (RuntimeException failure) {
errors.add(path + " does not compile: " + reason(failure));
@@ -49,6 +49,20 @@ public final class StructurePlacementScope {
return placements;
}
public static boolean startsNear(Engine engine, int chunkX, int chunkZ, int reachChunks) {
long seed = engine.getSeedManager().getMantle();
for (int startZ = chunkZ - reachChunks; startZ <= chunkZ + reachChunks; startZ++) {
for (int startX = chunkX - reachChunks; startX <= chunkX + reachChunks; startX++) {
for (IrisStructurePlacement placement : placementsAt(engine, startX, startZ)) {
if (placement.getDistribution() != null && StructurePlacementGrid.startsInChunk(placement, startX, startZ, seed)) {
return true;
}
}
}
}
return false;
}
private static ScopeIndex scopeIndex(Engine engine) {
int revision = engine.getCacheID();
synchronized (SCOPE_INDEXES) {
@@ -46,6 +46,7 @@ public final class HydrologyCaveMatter extends RawMatter<HydrologyCaveCell> {
case DRY_AIR -> 3;
case SEAL_GUARD -> 4;
case POOL_SOURCE -> 5;
case SPRING_SOURCE -> 6;
};
}
@@ -55,6 +56,7 @@ public final class HydrologyCaveMatter extends RawMatter<HydrologyCaveCell> {
case 3 -> HydrologyCaveAction.DRY_AIR;
case 4 -> HydrologyCaveAction.SEAL_GUARD;
case 5 -> HydrologyCaveAction.POOL_SOURCE;
case 6 -> HydrologyCaveAction.SPRING_SOURCE;
default -> throw new IOException("Unknown hydrology cave action code " + code);
};
}
@@ -950,6 +950,31 @@ public class HydrologyRuntimeTest {
assertDisabled(HydrologyRuntime.create(engine, complex));
}
@Test(timeout = 180_000L)
public void policyFluidsReachSpringsWithCavePoolsOff() throws Exception {
try (EngineFixture.Environment ignored = EngineFixture.environment();
EngineFixture fixture = new EngineFixture(EngineFixture.pack(temporaryFolder.newFolder().toPath(), false))) {
IrisHydrology config = new IrisHydrology().setEnabled(true).setPrefetchRings(0);
config.getUnderground().getCavePools().setEnabled(false);
config.getUnderground().getCaveSprings().setFluid("water");
fixture.dimension.setHydrology(config);
fixture.dimension.setHydrologyPolicy(new IrisHydrologyPolicy().setFluid("water"));
assertFalse(caveFluidPolicies(fixture));
config.getUnderground().getCaveSprings().setEnabled(true);
assertTrue(caveFluidPolicies(fixture));
}
}
private static boolean caveFluidPolicies(EngineFixture fixture) {
HydrologyRuntime runtime = HydrologyRuntime.create(fixture.engine, fixture.complex);
try {
return runtime.caveFluidPolicies();
} finally {
runtime.close();
}
}
@Test
public void zeroDensitySkipsRuntimePlanningAfterValidatingSettings() throws Exception {
Engine engine = mock(Engine.class);
@@ -35,7 +35,7 @@ public class HydrologySettingsTest {
private static final int SEA_LEVEL = 62;
private static final int MIN_Y = -64;
private static final int MAX_Y = 320;
private static final long DEFAULT_FINGERPRINT = -2376958294785826560L;
private static final long DEFAULT_FINGERPRINT = -2359553697125315860L;
@Test
public void densityIsBoundedAndChangesThePlanIdentity() {
@@ -35,12 +35,13 @@ import static org.mockito.Mockito.when;
public class CavePoolFillerTest {
private static final long SEED = 1337L;
private static final int FLOOR = 50;
private static final int WORLD_MIN = -256;
@Test
public void globalDensityThinsCandidateColumnsBeforeSamplingCaves() {
IrisHydrology config = new IrisHydrology().setDensity(0.5D);
config.getUnderground().getCavePools().setDensity(8D);
CavePoolFiller filler = new CavePoolFiller(HydrologySettings.compile(config, SEED, 63, 0, 384));
CavePoolFiller filler = new CavePoolFiller(HydrologySettings.compile(config, SEED, 63, 0, 384), 0);
CarvedTerrain carved = mock(CarvedTerrain.class);
MantleWriter writer = mock(MantleWriter.class);
Set<Long> columns = new HashSet<>();
@@ -67,7 +68,7 @@ public class CavePoolFillerTest {
public void chunksWithoutAPoolSiteNeverOpenTheirCaves() {
IrisHydrology config = new IrisHydrology().setDensity(0.5D);
config.getUnderground().getCavePools().setDensity(0.05D);
CavePoolFiller filler = new CavePoolFiller(HydrologySettings.compile(config, SEED, 63, 0, 384));
CavePoolFiller filler = new CavePoolFiller(HydrologySettings.compile(config, SEED, 63, 0, 384), 0);
CarvedTerrain carved = mock(CarvedTerrain.class);
MantleWriter writer = mock(MantleWriter.class);
AtomicInteger opened = new AtomicInteger();
@@ -86,7 +87,7 @@ public class CavePoolFillerTest {
public void zeroGlobalDensityDoesNotReadCaves() {
IrisHydrology config = new IrisHydrology().setDensity(0D);
config.getUnderground().getCavePools().setDensity(8D);
CavePoolFiller filler = new CavePoolFiller(HydrologySettings.compile(config, SEED, 63, 0, 384));
CavePoolFiller filler = new CavePoolFiller(HydrologySettings.compile(config, SEED, 63, 0, 384), 0);
CarvedTerrain carved = mock(CarvedTerrain.class);
MantleWriter writer = mock(MantleWriter.class);
filler.fill(0, 0, () -> carved, writer, SEED);
@@ -163,10 +164,10 @@ public class CavePoolFillerTest {
MantleWriter forwardWriter = writer(forward);
MantleWriter reverseWriter = writer(reverse);
for (int index = 0; index < 9; index++) {
new CavePoolFiller(settings).fill(index % 3 - 1, index / 3 - 1, () -> world, forwardWriter, SEED);
new CavePoolFiller(settings, 0).fill(index % 3 - 1, index / 3 - 1, () -> world, forwardWriter, SEED);
}
for (int index = 8; index >= 0; index--) {
new CavePoolFiller(settings).fill(index % 3 - 1, index / 3 - 1, () -> world, reverseWriter, SEED);
new CavePoolFiller(settings, 0).fill(index % 3 - 1, index / 3 - 1, () -> world, reverseWriter, SEED);
}
assertFalse(forward.isEmpty());
@@ -197,10 +198,10 @@ public class CavePoolFillerTest {
Map<Long, HydrologyCaveCell> forward = new HashMap<>();
Map<Long, HydrologyCaveCell> reverse = new HashMap<>();
new CavePoolFiller(settings).fill(0, 0, () -> world, writer(forward), SEED);
new CavePoolFiller(settings).fill(1, 0, () -> world, writer(forward), SEED);
new CavePoolFiller(settings).fill(1, 0, () -> world, writer(reverse), SEED);
new CavePoolFiller(settings).fill(0, 0, () -> world, writer(reverse), SEED);
new CavePoolFiller(settings, 0).fill(0, 0, () -> world, writer(forward), SEED);
new CavePoolFiller(settings, 0).fill(1, 0, () -> world, writer(forward), SEED);
new CavePoolFiller(settings, 0).fill(1, 0, () -> world, writer(reverse), SEED);
new CavePoolFiller(settings, 0).fill(0, 0, () -> world, writer(reverse), SEED);
assertFalse(wetCells(forward, "water").isEmpty());
assertFalse(wetCells(forward, "lava").isEmpty());
@@ -269,6 +270,72 @@ public class CavePoolFillerTest {
}), unknown, 0, 0));
}
@Test
public void deepFluidFillsPoolsAtOrBelowTheLineInWorldHeight() {
HydrologySettings below = deepSettings(52 + WORLD_MIN);
Map<Long, HydrologyCaveCell> deep = fillAt(below, room(0, 15, 0, 15, FLOOR, 52), 0, 0);
assertEquals(roomCells(FLOOR, 52), wetCells(deep, "lava"));
assertTrue(wetCells(deep, "water").isEmpty());
HydrologySettings above = deepSettings(FLOOR - 1 + WORLD_MIN);
Map<Long, HydrologyCaveCell> shallow = fillAt(above, room(0, 15, 0, 15, FLOOR, 52), 0, 0);
assertEquals(roomCells(FLOOR, 52), wetCells(shallow, "water"));
assertTrue(wetCells(shallow, "lava").isEmpty());
}
@Test
public void poolReachingTheLineStopsAtItAndNeverStraddles() {
HydrologySettings settings = deepSettings(51 + WORLD_MIN);
Map<Long, HydrologyCaveCell> written = fillAt(settings, roomWithSill(), 0, 0);
assertEquals(roomCells(FLOOR, 51), wetCells(written, "lava"));
assertTrue(wetCells(written, "water").isEmpty());
}
@Test
public void unsetDeepFluidKeepsThePoolFluidAtAnyDepth() {
Map<Long, HydrologyCaveCell> written = fillAt(settings(pools -> pools.setFreeboard(new KList<>(0, 0)).setDeepFluidMaxY(300)),
roomWithSill(), 0, 0);
assertEquals(roomCells(FLOOR, 52), wetCells(written, "water"));
}
@Test
public void cavePolicyWinsOverTheDeepFluid() {
VoxelWorld world = roomWithSill();
world.policyFluid(x -> "water");
Map<Long, HydrologyCaveCell> written = fillAt(deepSettings(52 + WORLD_MIN), world, 0, 0);
assertEquals(roomCells(FLOOR, 52), wetCells(written, "water"));
assertTrue(wetCells(written, "lava").isEmpty());
}
@Test
public void deepAndShallowPoolsOverOneAnotherShareOnlyRockWhateverTheChunkOrder() {
VoxelWorld world = room(0, 15, 0, 15, FLOOR, 52);
world.carve(0, 15, 0, 15, 54, 57);
world.carve(16, 16, 8, 8, 57, 58);
HydrologySettings settings = HydrologySettings.compile(deepConfig(52 + WORLD_MIN, 8D), SEED, 63, 0, 512);
Map<Long, HydrologyCaveCell> forward = new HashMap<>();
Map<Long, HydrologyCaveCell> reverse = new HashMap<>();
new CavePoolFiller(settings, WORLD_MIN).fill(0, 0, () -> world, writer(forward), SEED);
new CavePoolFiller(settings, WORLD_MIN).fill(1, 0, () -> world, writer(forward), SEED);
new CavePoolFiller(settings, WORLD_MIN).fill(1, 0, () -> world, writer(reverse), SEED);
new CavePoolFiller(settings, WORLD_MIN).fill(0, 0, () -> world, writer(reverse), SEED);
assertFalse(wetCells(forward, "lava").isEmpty());
assertFalse(wetCells(forward, "water").isEmpty());
assertGuard(forward, 8, 53, 8);
assertEquals(forward, reverse);
assertNoMixedBodies(forward);
}
@Test
public void deepFluidLineOutsideTheWorldFailsClosed() {
HydrologySettings below = deepSettings(WORLD_MIN - 1);
assertThrows(IllegalStateException.class, () -> new CavePoolFiller(below, WORLD_MIN));
HydrologySettings above = deepSettings(WORLD_MIN + 512);
assertThrows(IllegalStateException.class, () -> new CavePoolFiller(above, WORLD_MIN));
new CavePoolFiller(deepSettings(WORLD_MIN + 511), WORLD_MIN);
}
@Test
public void foreignCellsAndDisabledPoolsWriteNothing() {
VoxelWorld feature = roomWithSill();
@@ -324,7 +391,7 @@ public class CavePoolFillerTest {
private static Map<Long, HydrologyCaveCell> fill(HydrologySettings settings, VoxelWorld world, int chunkX, int chunkZ) {
Map<Long, HydrologyCaveCell> written = new HashMap<>();
new CavePoolFiller(settings).fill(chunkX, chunkZ, () -> world, writer(written), SEED);
new CavePoolFiller(settings, 0).fill(chunkX, chunkZ, () -> world, writer(written), SEED);
return written;
}
@@ -350,6 +417,23 @@ public class CavePoolFillerTest {
return HydrologySettings.compile(config, SEED, 63, 0, 384);
}
private static IrisHydrology deepConfig(int deepFluidMaxY, double density) {
IrisHydrology config = new IrisHydrology().setEnabled(true);
config.getFluids().add(new IrisFluidProfile().setName("lava").setPalette(new IrisMaterialPalette().qclear().qadd("minecraft:lava")));
config.getUnderground().getCavePools().setDensity(density).setFreeboard(new KList<>(0, 0)).setDeepFluid("lava").setDeepFluidMaxY(deepFluidMaxY);
return config;
}
private static HydrologySettings deepSettings(int deepFluidMaxY) {
return HydrologySettings.compile(deepConfig(deepFluidMaxY, 1D), SEED, 63, 0, 512);
}
private static Map<Long, HydrologyCaveCell> fillAt(HydrologySettings settings, VoxelWorld world, int chunkX, int chunkZ) {
Map<Long, HydrologyCaveCell> written = new HashMap<>();
new CavePoolFiller(settings, WORLD_MIN).fill(chunkX, chunkZ, () -> world, writer(written), SEED);
return written;
}
private static Set<Long> wetCells(Map<Long, HydrologyCaveCell> written, String fluid) {
Set<Long> cells = new HashSet<>();
for (Map.Entry<Long, HydrologyCaveCell> entry : written.entrySet()) {
@@ -430,5 +514,10 @@ public class CavePoolFillerTest {
public String caveFluid(int x, int y, int z) {
return policyFluid.apply(x);
}
@Override
public boolean structureNear(int x, int y, int z) {
return false;
}
}
}
@@ -0,0 +1,518 @@
package art.arcane.iris.generation.hydrology.underground;
import art.arcane.iris.generation.hydrology.cave.HydrologyCaveAction;
import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell;
import art.arcane.iris.generation.hydrology.config.IrisCaveSprings;
import art.arcane.iris.generation.hydrology.config.IrisFluidProfile;
import art.arcane.iris.generation.hydrology.config.IrisHydrology;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.mantle.MantleWriter;
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.matter.MatterUpdate;
import art.arcane.volmlib.util.matter.slices.UpdateMatter;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.IntFunction;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
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.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
public class CaveSpringPlacerTest {
private static final long SEED = 1337L;
private static final long[] SEEDS = {1337L, 42L, 7L, 99L, 2048L, -5L, 31337L, 88L};
private static final int FLOOR = 50;
private static final int CEILING = 70;
private static final int[][] SIDES = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
@Test
public void placesOneSourceInARockWallAboveAnOpeningAndAsksForAnUpdate() {
World world = pillars();
Recorder recorder = new Recorder();
for (long seed : SEEDS) {
placer(springs -> {
}).place(0, 0, () -> world, recorder.writer, seed);
}
assertFalse(recorder.cells.isEmpty());
for (Map.Entry<Long, HydrologyCaveCell> entry : recorder.cells.entrySet()) {
int x = x(entry.getKey());
int y = y(entry.getKey());
int z = z(entry.getKey());
assertEquals(HydrologyCaveAction.SPRING_SOURCE, entry.getValue().action());
assertEquals("lava", entry.getValue().fluidProfileKey());
assertEquals(0, x >> 4);
assertEquals(0, z >> 4);
assertEquals(CaveVoxel.SOLID, world.voxel(x, y, z));
assertEquals(CaveVoxel.SOLID, world.voxel(x, y + 1, z));
assertEquals(CaveVoxel.SOLID, world.voxel(x, y - 1, z));
boolean opening = false;
for (int[] side : SIDES) {
opening |= world.voxel(x + side[0], y, z + side[1]) == CaveVoxel.AIR
&& world.voxel(x + side[0], y - 1, z + side[1]) == CaveVoxel.AIR;
}
assertTrue("seep at " + x + "," + y + "," + z + " opens over a drop", opening);
assertSame(UpdateMatter.ON, recorder.updates.get(entry.getKey()));
}
assertEquals(recorder.cells.keySet(), recorder.updates.keySet());
}
@Test
public void disabledSpringsAndZeroDensityNeverOpenTheCaves() {
CarvedTerrain carved = mock(CarvedTerrain.class);
MantleWriter writer = mock(MantleWriter.class);
new CaveSpringPlacer(compile(new IrisHydrology())).place(0, 0, () -> carved, writer, SEED);
placer(springs -> springs.setDensity(0D)).place(0, 0, () -> carved, writer, SEED);
IrisHydrology thinned = config(springs -> springs.setDensity(2D)).setDensity(0D);
new CaveSpringPlacer(compile(thinned)).place(0, 0, () -> carved, writer, SEED);
verifyNoInteractions(carved, writer);
}
@Test
public void densityIsSitesPerChunk() {
World world = pillars();
CaveSpringPlacer placer = placer(springs -> springs.setDensity(0.05D));
int[] counter = new int[1];
for (int chunkX = 0; chunkX < 2048; chunkX++) {
placer.place(chunkX, 0, () -> {
counter[0]++;
return world;
}, new Recorder().writer, SEED);
}
int opened = counter[0];
assertTrue("0.05 sites a chunk open about 102 of 2048 chunks, opened " + opened, opened > 60 && opened < 150);
}
@Test
public void policyFluidReplacesTheSpringFluidAndAnUnknownOneFails() {
World policy = pillars();
policy.policyFluid = x -> "water";
Recorder recorder = new Recorder();
placer(springs -> {
}).place(0, 0, () -> policy, recorder.writer, SEED);
assertFalse(recorder.cells.isEmpty());
for (HydrologyCaveCell cell : recorder.cells.values()) {
assertEquals("water", cell.fluidProfileKey());
}
World unknown = pillars();
unknown.policyFluid = x -> "magma";
assertThrows(IllegalStateException.class, () -> placer(springs -> {
}).place(0, 0, () -> unknown, new Recorder().writer, SEED));
}
@Test
public void chunkOrderDoesNotMatter() {
World world = pillars();
CaveSpringPlacer placer = placer(springs -> {
});
List<int[]> chunks = new ArrayList<>();
for (int chunkX = -2; chunkX <= 2; chunkX++) {
for (int chunkZ = -2; chunkZ <= 2; chunkZ++) {
chunks.add(new int[]{chunkX, chunkZ});
}
}
for (long seed : SEEDS) {
Recorder forward = new Recorder();
for (int[] chunk : chunks) {
placer.place(chunk[0], chunk[1], () -> world, forward.writer, seed);
}
Collections.shuffle(chunks, new Random(seed));
Recorder shuffled = new Recorder();
for (int[] chunk : chunks) {
placer.place(chunk[0], chunk[1], () -> world, shuffled.writer, seed);
}
assertFalse(forward.cells.isEmpty());
assertEquals(forward.cells, shuffled.cells);
assertEquals(forward.updates.keySet(), shuffled.updates.keySet());
}
}
@Test
public void staysMinDepthBelowTheSurfaceAlongTheSeepAndItsFlow() {
World shallow = pillars();
shallow.surface = CEILING + 3;
assertTrue(place(shallow, springs -> springs.setMinDepthBelowSurface(CEILING + 3 - FLOOR)).isEmpty());
World deep = pillars();
Map<Long, HydrologyCaveCell> written = place(deep, springs -> springs.setMinDepthBelowSurface(deep.surface - 58));
assertFalse(written.isEmpty());
for (long cell : written.keySet()) {
assertTrue(y(cell) <= 58);
}
World sloped = pillars();
sloped.surfaceAt = (x, z) -> x >= 8 ? FLOOR + 8 : 200;
assertTrue("the flow reaches ground too close to the surface",
place(sloped, springs -> springs.setMinDepthBelowSurface(16)).isEmpty());
}
@Test
public void theFlowKeepsMinDepthOnGroundThatStaysAboveIt() {
World lowGround = pillars();
lowGround.surfaceAt = (x, z) -> x >= 8 ? 60 : 200;
assertFalse("the floor at 51 lies 9 under the low ground",
place(lowGround, springs -> springs.setMinDepthBelowSurface(9)).isEmpty());
assertTrue("the same floor is too shallow for 10",
place(lowGround, springs -> springs.setMinDepthBelowSurface(10)).isEmpty());
}
@Test
public void aForeignCellBesideTheSeepDropsItEvenWithAnotherSideOpen() {
World walled = pillars();
for (int x = -16; x < 32; x++) {
for (int z = -16; z < 32; z++) {
if (Math.floorMod(x + z, 2) == 1 && Math.floorMod(z, 2) == 1) {
for (int y = FLOOR + 2; y <= CEILING; y++) {
walled.foreign(x, y, z);
}
}
}
}
assertTrue(place(walled, springs -> {
}).isEmpty());
}
@Test
public void anOpeningWithNoDropHoldsNoSeep() {
World slit = new World();
World drop = new World();
for (int x = -16; x < 32; x++) {
for (int z = -16; z < 32; z++) {
if (Math.floorMod(x + z, 2) == 1) {
slit.carve(x, x, z, z, 60, 60);
drop.carve(x, x, z, z, 59, 60);
}
}
}
assertTrue(place(slit, springs -> {
}).isEmpty());
assertFalse(place(drop, springs -> {
}).isEmpty());
}
@Test
public void aSeepNeedsRockDirectlyAboveAndBelow() {
World layered = pillars();
for (int x = -16; x < 32; x++) {
for (int z = -16; z < 32; z++) {
if (Math.floorMod(x + z, 2) == 0) {
for (int y = FLOOR + 4; y <= CEILING; y += 3) {
layered.carve(x, x, z, z, y, y);
}
}
}
}
assertTrue("every wall block has air directly above or below it", place(layered, springs -> {
}).isEmpty());
}
@Test
public void seepsCoverEveryColumnOfTheirChunk() {
World world = pillars();
CaveSpringPlacer placer = placer(springs -> {
});
Recorder recorder = new Recorder();
for (long seed = 0L; seed < 128L; seed++) {
placer.place(0, 0, () -> world, recorder.writer, seed);
}
Set<Integer> xs = new HashSet<>();
Set<Integer> zs = new HashSet<>();
for (long cell : recorder.cells.keySet()) {
xs.add(x(cell));
zs.add(z(cell));
}
Set<Integer> chunk = new HashSet<>();
for (int column = 0; column < 16; column++) {
chunk.add(column);
}
assertEquals(chunk, xs);
assertEquals(chunk, zs);
}
@Test
public void theFlowIsFollowedFifteenBlocksAndNoFurther() {
Consumer<IrisCaveSprings> one = springs -> springs.setDensity(1D);
int checked = 0;
for (long seed : SEEDS) {
Map<Long, HydrologyCaveCell> clean = placeAt(pillars(), seed, one);
for (long cell : clean.keySet()) {
for (int[] side : SIDES) {
World inside = pillars();
inside.foreign(x(cell) + side[0] * 15, FLOOR, z(cell) + side[1] * 15);
assertTrue(placeAt(inside, seed, one).isEmpty());
World outside = pillars();
outside.foreign(x(cell) + side[0] * 16, FLOOR, z(cell) + side[1] * 16);
assertEquals(clean, placeAt(outside, seed, one));
checked++;
}
}
}
assertTrue(checked > 0);
}
@Test
public void aSeepThatWouldOpenOntoTheSurfaceIsDropped() {
World open = pillars();
open.carveOpenings(CEILING + 1, open.surface);
assertTrue(place(open, springs -> {
}).isEmpty());
}
@Test
public void foreignCellsInTheFlowAndHistoricChunksDropTheSpring() {
World bottom = pillars();
for (int x = -16; x < 32; x++) {
for (int z = -16; z < 32; z++) {
bottom.foreign(x, FLOOR, z);
}
}
assertTrue("cave lava, an aquifer or a room under the flow", place(bottom, springs -> {
}).isEmpty());
World historic = pillars();
historic.historicMinX = 8;
assertTrue("the flow reaches a chunk generated earlier", place(historic, springs -> {
}).isEmpty());
World own = pillars();
own.historicMinX = -64;
assertTrue("own chunk generated earlier", place(own, springs -> {
}).isEmpty());
}
@Test
public void structuresNearbyDropTheSpring() {
World world = pillars();
world.structures = (x, y, z) -> true;
assertTrue(place(world, springs -> {
}).isEmpty());
}
@Test
public void theStructureCheckIsAskedAboutTheSeepItself() {
Consumer<IrisCaveSprings> one = springs -> springs.setDensity(1D);
int checked = 0;
for (long seed : SEEDS) {
for (long cell : placeAt(pillars(), seed, one).keySet()) {
World world = pillars();
world.structures = (x, y, z) -> key(x, y, z) == cell;
assertTrue(placeAt(world, seed, one).isEmpty());
checked++;
}
}
assertTrue(checked > 0);
}
@Test
public void poolWallsWinOverSpringsWhicheverChunkWritesFirst() {
World world = new World();
carvePillars(world, 0, 15);
HydrologySettings settings = compile(config(springs -> {
}));
CaveSpringPlacer placer = new CaveSpringPlacer(settings);
CavePoolFiller filler = new CavePoolFiller(settings, 0);
Recorder springsFirst = new Recorder();
placer.place(0, 0, () -> world, springsFirst.writer, SEED);
Map<Long, HydrologyCaveCell> placed = new HashMap<>(springsFirst.cells);
filler.fill(0, 0, () -> world, springsFirst.writer, SEED);
Recorder poolsFirst = new Recorder();
filler.fill(0, 0, () -> world, poolsFirst.writer, SEED);
placer.place(0, 0, () -> world, poolsFirst.writer, SEED);
assertEquals(springsFirst.cells, poolsFirst.cells);
assertEquals("a replaced spring asks for no block update", liveUpdates(poolsFirst), liveUpdates(springsFirst));
Set<Long> replaced = new HashSet<>();
for (long cell : placed.keySet()) {
if (springsFirst.cells.get(cell).action() == HydrologyCaveAction.SEAL_GUARD) {
replaced.add(cell);
}
}
assertFalse("the scene puts a spring in a pool wall", replaced.isEmpty());
}
private static CaveSpringPlacer placer(Consumer<IrisCaveSprings> springs) {
return new CaveSpringPlacer(compile(config(springs)));
}
private static Map<Long, HydrologyCaveCell> place(World world, Consumer<IrisCaveSprings> springs) {
Map<Long, HydrologyCaveCell> written = new HashMap<>();
for (long seed : SEEDS) {
written.putAll(placeAt(world, seed, springs));
}
return written;
}
private static Map<Long, HydrologyCaveCell> placeAt(World world, long seed, Consumer<IrisCaveSprings> springs) {
Recorder recorder = new Recorder();
placer(springs).place(0, 0, () -> world, recorder.writer, seed);
return recorder.cells;
}
private static Set<Long> liveUpdates(Recorder recorder) {
Set<Long> live = new HashSet<>();
for (Map.Entry<Long, MatterUpdate> update : recorder.updates.entrySet()) {
if (update.getValue().isUpdate()) {
live.add(update.getKey());
}
}
return live;
}
private static IrisHydrology config(Consumer<IrisCaveSprings> springs) {
IrisHydrology config = new IrisHydrology().setEnabled(true);
config.getFluids().add(new IrisFluidProfile().setName("lava").setPalette(new IrisMaterialPalette().qclear().qadd("minecraft:lava")));
config.getUnderground().getCavePools().setDensity(8D).setMaxDepth(16).setMaxArea(961).setFreeboard(new KList<>(0, 0));
springs.accept(config.getUnderground().getCaveSprings().setEnabled(true).setDensity(2D));
return config;
}
private static HydrologySettings compile(IrisHydrology config) {
return HydrologySettings.compile(config, SEED, 63, 0, 384);
}
private static World pillars() {
World world = new World();
carvePillars(world, -16, 31);
return world;
}
private static void carvePillars(World world, int min, int max) {
world.carve(min, max, min, max, FLOOR, FLOOR + 1);
for (int x = min; x <= max; x++) {
for (int z = min; z <= max; z++) {
if (Math.floorMod(x + z, 2) == 1) {
world.carve(x, x, z, z, FLOOR, CEILING);
}
}
}
}
private static long key(int x, int y, int z) {
return ((long) (x + 4096) << 40) | ((long) y << 20) | (z + 4096);
}
private static int x(long key) {
return (int) (key >>> 40) - 4096;
}
private static int z(long key) {
return (int) (key & 0xFFFFF) - 4096;
}
private static int y(long key) {
return (int) ((key >>> 20) & 0xFFFFF);
}
private interface SurfaceAt {
int at(int x, int z);
}
private interface StructureAt {
boolean at(int x, int y, int z);
}
private static final class Recorder {
private final Map<Long, HydrologyCaveCell> cells = new HashMap<>();
private final Map<Long, MatterUpdate> updates = new HashMap<>();
private final MantleWriter writer = mock(MantleWriter.class);
private Recorder() {
doAnswer(invocation -> {
long key = key(invocation.getArgument(0), invocation.getArgument(1), invocation.getArgument(2));
Object value = invocation.getArgument(3);
if (value instanceof HydrologyCaveCell cell) {
cells.put(key, cell);
} else {
updates.put(key, (MatterUpdate) value);
}
return null;
}).when(writer).setData(anyInt(), anyInt(), anyInt(), any());
when(writer.getDataIfPresent(anyInt(), anyInt(), anyInt(), eq(HydrologyCaveCell.class))).thenAnswer(invocation ->
cells.get(key(invocation.getArgument(0), invocation.getArgument(1), invocation.getArgument(2))));
doAnswer(invocation -> {
invocation.<Runnable>getArgument(2).run();
return null;
}).when(writer).withChunkFence(anyInt(), anyInt(), any(Runnable.class));
}
}
private static final class World implements CarvedTerrain {
private final Set<Long> air = new HashSet<>();
private final Set<Long> foreign = new HashSet<>();
private int surface = 200;
private SurfaceAt surfaceAt;
private IntFunction<String> policyFluid = x -> null;
private int historicMinX = Integer.MAX_VALUE;
private StructureAt structures = (x, y, z) -> false;
void carve(int minX, int maxX, int minZ, int maxZ, int minY, int maxY) {
for (int x = minX; x <= maxX; x++) {
for (int z = minZ; z <= maxZ; z++) {
for (int y = minY; y <= maxY; y++) {
air.add(key(x, y, z));
}
}
}
}
void carveOpenings(int minY, int maxY) {
for (int x = -16; x < 32; x++) {
for (int z = -16; z < 32; z++) {
if (Math.floorMod(x + z, 2) == 1) {
carve(x, x, z, z, minY, maxY);
}
}
}
}
void foreign(int x, int y, int z) {
foreign.add(key(x, y, z));
}
@Override
public CaveVoxel voxel(int x, int y, int z) {
long key = key(x, y, z);
if (y <= 0 || y > surface(x, z) || x >= historicMinX || foreign.contains(key)) {
return CaveVoxel.FOREIGN;
}
return air.contains(key) ? CaveVoxel.AIR : CaveVoxel.SOLID;
}
@Override
public int surface(int x, int z) {
return surfaceAt == null ? surface : surfaceAt.at(x, z);
}
@Override
public String caveFluid(int x, int y, int z) {
return policyFluid.apply(x);
}
@Override
public boolean structureNear(int x, int y, int z) {
return structures.at(x, y, z);
}
}
}
@@ -1,5 +1,6 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.terrain.transform.IrisTerrainTransform;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.hydrology.cave.HydrologyCaveAction;
import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell;
@@ -15,6 +16,7 @@ import art.arcane.iris.generation.hydrology.underground.SeaInletRasterizer;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.EnginePlatformHooks;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.runtime.SeedManager;
import art.arcane.iris.generation.stream.ProvisionalSampling;
import art.arcane.iris.generation.subterrain.SubterrainCell;
import art.arcane.iris.generation.subterrain.SubterrainPlan;
@@ -23,10 +25,13 @@ import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.generation.terrain.Terrain3DColumn;
import art.arcane.iris.structure.placement.IrisStructurePlacement;
import art.arcane.iris.structure.placement.StructureDistribution;
import art.arcane.iris.world.IrisWorld;
import art.arcane.iris.world.storage.matter.IrisMatterSupport;
import art.arcane.iris.world.storage.matter.PreObjectMatterCell;
import art.arcane.iris.world.storage.matter.PreObjectMatterTest;
import art.arcane.volmlib.nativelib.terrain.structure.NativeStructureVolume;
import art.arcane.volmlib.util.collection.KList;
import art.arcane.volmlib.util.mantle.flag.MantleFlag;
import art.arcane.volmlib.util.mantle.runtime.Mantle;
@@ -59,6 +64,8 @@ import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
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 MantleCarvedTerrainTest {
@@ -268,6 +275,68 @@ public class MantleCarvedTerrainTest {
poolFluids(poolRoom(new Underground(volcanic, magma, region("temperate", null), new IrisDimension())).generate(0)));
}
@Test
public void importedStructuresWithinTheFlowsReachAndBelowTheSeepTopAreNear() {
assertFalse(nearSeep());
assertTrue("on the seep", nearSeep(volume(8, -34, 8, 8, -34, 8)));
assertTrue("at the bottom of the world", nearSeep(volume(8, -64, 8, 8, -64, 8)));
assertTrue("one block above the seep", nearSeep(volume(8, -33, 8, 8, -20, 8)));
assertFalse("above that", nearSeep(volume(8, -32, 8, 8, -20, 8)));
assertTrue(nearSeep(volume(40, -60, 8, 50, -50, 8)));
assertFalse(nearSeep(volume(41, -60, 8, 50, -50, 8)));
assertTrue(nearSeep(volume(-30, -60, 8, -24, -50, 8)));
assertFalse(nearSeep(volume(-30, -60, 8, -25, -50, 8)));
assertTrue(nearSeep(volume(8, -60, 40, 8, -50, 50)));
assertFalse(nearSeep(volume(8, -60, 41, 8, -50, 50)));
assertTrue(nearSeep(volume(8, -60, -30, 8, -50, -24)));
assertFalse(nearSeep(volume(8, -60, -30, 8, -50, -25)));
}
@Test
public void placementsThatCanStartNearbyAreNear() {
Scene scene = structureScene();
assertFalse(scene.carved().structureNear(8, 30, 8));
Scene dense = structureScene();
dense.engine.getDimension().setStructures(new KList<>(new IrisStructurePlacement().setDistribution(StructureDistribution.DENSITY).setDensity(1D)));
assertTrue(dense.carved().structureNear(8, 30, 8));
}
@Test
public void terrainTransformDimensionsNeverQueryStructuresDuringTerrain() {
Scene scene = structureScene();
scene.engine.getDimension().setTerrainTransform(new IrisTerrainTransform());
assertTrue(scene.carved().structureNear(8, 30, 8));
verify(scene.engine, never()).getNativeStructureVolumes(anyInt(), anyInt(), anyInt(), anyInt());
}
private static boolean nearSeep(NativeStructureVolume... volumes) {
return structureScene(volumes).carved().structureNear(8, 30, 8);
}
private static NativeStructureVolume volume(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) {
return new NativeStructureVolume("minecraft:mineshaft", minX, minY, minZ, maxX, maxY, maxZ, null);
}
private static Scene structureScene(NativeStructureVolume... volumes) {
Scene scene = new Scene();
IrisWorld world = mock(IrisWorld.class);
when(world.minHeight()).thenReturn(-64);
when(scene.engine.getWorld()).thenReturn(world);
when(scene.engine.getSeedManager()).thenReturn(new SeedManager(SEED));
when(scene.engine.getAllBiomes()).thenReturn(new KList<>());
when(scene.engine.getNativeStructureVolumes(anyInt(), anyInt(), anyInt(), anyInt())).thenAnswer(invocation -> {
KList<NativeStructureVolume> matches = new KList<>();
for (NativeStructureVolume volume : volumes) {
if (volume.intersectsInfluenceRect(invocation.getArgument(0), invocation.getArgument(1), invocation.getArgument(2), invocation.getArgument(3))) {
matches.add(volume);
}
}
return matches;
});
return scene;
}
private static Scene poolRoom(Underground underground) {
Scene scene = new Scene(underground);
Matter[] room = scene.chunk(0, 0);
@@ -456,7 +525,7 @@ public class MantleCarvedTerrainTest {
rasterizer.write(inlet, 0, chunkZ, writer, HydrologyCaveCell.SEA_FLUID, SeaInletRasterizer.SubterrainFluid.NOWHERE,
SeaInletRasterizer.HistoricalChunks.NONE);
}
new CavePoolFiller(settings).fill(0, chunkZ, () -> new MantleCarvedTerrain(writer, complex, engine, 0, chunkZ), writer, SEED);
new CavePoolFiller(settings, 0).fill(0, chunkZ, () -> new MantleCarvedTerrain(writer, complex, engine, 0, chunkZ), writer, SEED);
}
return cells;
}
@@ -8,6 +8,7 @@ import art.arcane.iris.generation.hydrology.config.IrisHydrology;
import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
import art.arcane.iris.generation.hydrology.underground.CavePoolFiller;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisComplex;
@@ -84,6 +85,24 @@ public class MantleHydrologyComponentTest {
assertFalse(MantleHydrologyComponent.isEnabledFor(dimension));
}
@Test
public void springsAloneKeepTheCaveWaterReach() {
IrisDimension dimension = new IrisDimension();
IrisHydrology hydrology = new IrisHydrology().setEnabled(true);
hydrology.getUnderground().getCavePools().setEnabled(false);
dimension.setHydrology(hydrology);
Engine engine = mock(Engine.class);
when(engine.getDimension()).thenReturn(dimension);
EngineMantle mantle = mock(EngineMantle.class);
when(mantle.getEngine()).thenReturn(engine);
MantleHydrologyComponent component = new MantleHydrologyComponent(mantle);
assertEquals(0, component.getInputRadius());
hydrology.getUnderground().getCaveSprings().setEnabled(true);
assertEquals(CavePoolFiller.REACH, component.getInputRadius());
assertEquals(CavePoolFiller.REACH, component.computeRadius());
}
@Test
public void everyDropBetweenWetColumnsFallsFromTheHigherHead() {
MantleHydrologyComponent.Falls falls = MantleHydrologyComponent.plan(0, 0, WORLD_HEIGHT,
@@ -116,6 +116,8 @@ public class IrisCarveModifierHydrologyTest {
new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, "water"), current, source, air));
assertSame(source, IrisCarveModifier.resolveHydrologyState(
new HydrologyCaveCell(HydrologyCaveAction.POOL_SOURCE, "water"), current, source, air));
assertSame(source, IrisCarveModifier.resolveHydrologyState(
new HydrologyCaveCell(HydrologyCaveAction.SPRING_SOURCE, "lava"), current, source, air));
assertSame(air, IrisCarveModifier.resolveHydrologyState(
new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, "water"), current, source, air));
}
@@ -306,7 +308,7 @@ public class IrisCarveModifierHydrologyTest {
IrisHydrology config = new IrisHydrology().setEnabled(true);
config.getUnderground().getCavePools().setDensity(1D).setFreeboard(new KList<>(0, 0));
Map<Long, HydrologyCaveCell> written = new HashMap<>();
new CavePoolFiller(HydrologySettings.compile(config, SEED, 63, 0, 384))
new CavePoolFiller(HydrologySettings.compile(config, SEED, 63, 0, 384), 0)
.fill(0, 0, SealedRoom::new, recordingWriter(written), SEED);
Matter[] sections = new Matter[SECTIONS];
Set<String> wallFluids = new HashSet<>();
@@ -442,5 +444,10 @@ public class IrisCarveModifierHydrologyTest {
public String caveFluid(int x, int y, int z) {
return null;
}
@Override
public boolean structureNear(int x, int y, int z) {
return false;
}
}
}
@@ -155,6 +155,23 @@ public class PackHydrologyValidatorTest {
assertEquals(errors.toString(), 3, errors.size());
}
@Test
public void rejectsADeepFluidLineOutsideTheWorld() throws Exception {
String hydrology = """
{
"enabled": true,
"underground": {"cavePools": {"deepFluid": "lava", "deepFluidMaxY": %d}},
"fluids": [
{"name": "water"},
{"name": "lava", "palette": {"palette": [{"block": "minecraft:lava"}]}}
]
}
""";
assertTrue(validate(pack(dimension(hydrology.formatted(-64), ""))).errors().isEmpty());
PackHydrologyValidator.Validation outside = validate(pack(dimension(hydrology.formatted(-2000), "")));
assertTrue(outside.errors().toString(), outside.errors().toString().contains("deepFluidMaxY"));
}
@Test
public void rejectsFluidReferencesTheFluidProfilesDoNotDefine() throws Exception {
File pack = pack(dimension("""
@@ -84,7 +84,7 @@ public class SchemaBuilderIdentityTest {
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
private static final String EXPECTED_SCHEMA_DIGEST = "d35dfc4ec63cf5cb8f8782177f9b2feac9771c85fdc315d6f3cac5b89cb30924";
private static final String EXPECTED_SCHEMA_DIGEST = "3ed821f505deefbe3bdd3a105ece18893e4778e4cfc902591c43a18e1fceb2c1";
private static final List<Class<?>> SCHEMA_ROOTS = List.of(
IrisDimension.class,
@@ -10,10 +10,12 @@ import art.arcane.iris.generation.runtime.IrisEngine;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.terrain.IrisDimensionCarvingResolver;
import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.testsupport.BukkitTestServer;
import art.arcane.iris.world.IrisWorld;
import art.arcane.volmlib.nativelib.terrain.NativeBiomeRegistry;
import art.arcane.volmlib.nativelib.terrain.NativeBiomeSourcePolicy;
import art.arcane.volmlib.util.collection.KList;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.Field;
@@ -29,6 +31,11 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class BukkitBiomeVisibleResolverTest {
@BeforeClass
public static void initializeBukkit() {
BukkitTestServer.initializeRegistries();
}
@Test
public void chunkResolverMatchesThePerQuartResolution() throws Exception {
IrisBiome surface = customBiome("surface", "meadow");
@@ -0,0 +1,75 @@
package art.arcane.iris.structure.placement;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.iris.generation.runtime.SeedManager;
import art.arcane.volmlib.util.collection.KList;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class StructurePlacementScopeStartsNearTest {
private static final long MANTLE_SEED = 1337L;
@Test
public void reportsAStartWithinTheReachAndNothingOutsideIt() {
IrisStructurePlacement dense = new IrisStructurePlacement().setDistribution(StructureDistribution.DENSITY).setDensity(1D);
assertTrue(StructurePlacementScope.startsNear(engine(new KList<>(dense)), 3, -2, 1));
IrisStructurePlacement never = new IrisStructurePlacement().setDistribution(StructureDistribution.DENSITY).setDensity(0D);
assertFalse(StructurePlacementScope.startsNear(engine(new KList<>(never)), 3, -2, 8));
assertFalse(StructurePlacementScope.startsNear(engine(new KList<>()), 3, -2, 8));
}
@Test
public void aStartCountsExactlyUpToTheReachOnEverySide() {
IrisStructurePlacement sparse = new IrisStructurePlacement().setDistribution(StructureDistribution.DENSITY).setDensity(0.0005D);
Engine engine = engine(new KList<>(sparse));
int[] start = loneStart(sparse);
for (int reach : new int[]{1, 3, 8}) {
for (int[] side : new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {-1, -1}}) {
int chunkX = start[0] + side[0] * reach;
int chunkZ = start[1] + side[1] * reach;
assertTrue(StructurePlacementScope.startsNear(engine, chunkX, chunkZ, reach));
assertFalse(StructurePlacementScope.startsNear(engine, chunkX, chunkZ, reach - 1));
}
}
}
private static int[] loneStart(IrisStructurePlacement placement) {
for (int x = 0; x < 4096; x++) {
for (int z = 0; z < 4096; z++) {
if (StructurePlacementGrid.startsInChunk(placement, x, z, MANTLE_SEED) && alone(placement, x, z)) {
return new int[]{x, z};
}
}
}
throw new AssertionError("No lone start in the searched chunks");
}
private static boolean alone(IrisStructurePlacement placement, int startX, int startZ) {
for (int x = startX - 16; x <= startX + 16; x++) {
for (int z = startZ - 16; z <= startZ + 16; z++) {
if ((x != startX || z != startZ) && StructurePlacementGrid.startsInChunk(placement, x, z, MANTLE_SEED)) {
return false;
}
}
}
return true;
}
private static Engine engine(KList<IrisStructurePlacement> placements) {
Engine engine = mock(Engine.class);
SeedManager seeds = mock(SeedManager.class);
when(seeds.getMantle()).thenReturn(MANTLE_SEED);
when(engine.getSeedManager()).thenReturn(seeds);
IrisDimension dimension = new IrisDimension();
dimension.setStructures(placements);
when(engine.getDimension()).thenReturn(dimension);
when(engine.getAllBiomes()).thenReturn(new KList<>());
return engine;
}
}
@@ -64,6 +64,7 @@ public class HydrologyCaveMatterTest {
codes.put(HydrologyCaveAction.DRY_AIR, 3);
codes.put(HydrologyCaveAction.SEAL_GUARD, 4);
codes.put(HydrologyCaveAction.POOL_SOURCE, 5);
codes.put(HydrologyCaveAction.SPRING_SOURCE, 6);
assertEquals(List.copyOf(codes.keySet()), List.of(HydrologyCaveAction.values()));
for (Map.Entry<HydrologyCaveAction, Integer> entry : codes.entrySet()) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
@@ -76,6 +77,10 @@ public class HydrologyCaveMatterTest {
assertTrue(pool.isWet());
assertTrue(pool.carves());
assertTrue(pool.asCavern().isWater());
HydrologyCaveCell spring = new HydrologyCaveCell(HydrologyCaveAction.SPRING_SOURCE, "lava");
assertTrue(spring.isWet());
assertTrue(spring.carves());
assertEquals(spring, matter.readNode(new DataInputStream(new ByteArrayInputStream(new byte[]{6, 0, 4, 'l', 'a', 'v', 'a', 0, 0}))));
}
@Test
+28 -1
View File
@@ -326,6 +326,33 @@ tasks.register('generationOrderProbe', JavaExec) {
}
}
tasks.register('caveFluidProbe', JavaExec) {
group = 'verification'
description = 'Generates spaced patches of real pack chunks and reports pools, lava bodies, long bodies and springs per 1000 chunks by depth band.'
mainClass = 'art.arcane.iris.probe.CaveFluidProbe'
classpath = sourceSets.main.runtimeClasspath
jvmArgs('--add-modules', 'jdk.incubator.vector')
minHeapSize = '2g'
maxHeapSize = '8g'
dependsOn(':core:compileJava')
doFirst {
Provider<String> threads = providers.gradleProperty('probeThreads').orElse('4')
Provider<String> patches = providers.gradleProperty('probePatches').orElse('6')
Provider<String> work = providers.gradleProperty('probeWork').orElse(System.getProperty('java.io.tmpdir'))
Map<String, Provider<String>> required = [
probePack: probePack,
probeDimension: probeDimension,
probeSeed: probeSeed
]
required.each { String name, Provider<String> value ->
if (!value.isPresent() || value.get().isBlank()) {
throw new GradleException("caveFluidProbe requires -P${name}=<value>")
}
}
args(probePack.get(), probeDimension.get(), probeSeed.get(), patches.get(), threads.get(), work.get())
}
}
tasks.register('cavePoolProbe', JavaExec) {
group = 'verification'
description = 'Generates real pack chunks with cave pools and reports containment, pool sizes and generation-order hashes.'
@@ -406,7 +433,7 @@ tasks.register('transitionProbe', JavaExec) {
}
['transitionProbe', 'hydrologyProbe', 'genProbe', 'generationOrderProbe', 'riverTransectProbe', 'terrain3DProbe',
'hydrologyBlockProbe', 'cavePoolProbe', 'seaInletProbe'].each { String taskName ->
'hydrologyBlockProbe', 'cavePoolProbe', 'caveFluidProbe', 'seaInletProbe'].each { String taskName ->
tasks.named(taskName, JavaExec).configure { JavaExec task ->
classpath += configurations.studioProbeApi
doFirst {
@@ -0,0 +1,325 @@
package art.arcane.iris.probe;
import art.arcane.iris.generation.decoration.IrisProceduralBlocks;
import art.arcane.iris.generation.hydrology.cave.HydrologyCaveAction;
import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell;
import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.volmlib.nativelib.terrain.NativeBiome;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.volmlib.util.hunk.Hunk;
import art.arcane.volmlib.util.mantle.runtime.MantleChunk;
import art.arcane.volmlib.util.matter.Matter;
import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public final class CaveFluidProbe {
static final int PATCH_CHUNKS = 8;
static final int PATCH_SPACING = 64;
static final int LONG_EXTENT = 32;
static final int[] BAND_FLOORS = {50, 0, -64, -128, -192};
static final String[] BAND_NAMES = {"y>=50", "0..50", "-64..0", "-128..-64", "-192..-128", "y<-192"};
private static final String LOG_PREFIX = "[cave-fluid-probe]";
private static final byte NONE = 0;
private static final byte WATER = 1;
private static final byte LAVA = 2;
private static final int[] DX = {1, -1, 0, 0, 0, 0};
private static final int[] DY = {0, 0, 1, -1, 0, 0};
private static final int[] DZ = {0, 0, 0, 0, 1, -1};
private CaveFluidProbe() {
}
record Configuration(File pack, String dimension, long seed, int patchesPerSide, int threads, Path work) {
static Configuration parse(String[] arguments) {
if (arguments.length != 6) {
throw new IllegalArgumentException("Expected: <pack> <dimension> <seed> <patchesPerSide> <threads> <workParent>");
}
return new Configuration(new File(arguments[0]), arguments[1], Long.parseLong(arguments[2]), Integer.parseInt(arguments[3]),
Integer.parseInt(arguments[4]), Path.of(arguments[5]));
}
}
static final class Grid {
final int span;
final int height;
final byte[] kinds;
final byte[] pools;
final int[] roofs;
Grid(int span, int height) {
this.span = span;
this.height = height;
this.kinds = new byte[span * span * height];
this.pools = new byte[span * span * height];
this.roofs = new int[span * span];
}
int index(int x, int y, int z) {
return (y * span + z) * span + x;
}
}
record Body(byte kind, boolean pool, int lowestY, int extent, int cells) {
}
static final class Tally {
final int[] pools = new int[BAND_NAMES.length];
final int[] lavaPools = new int[BAND_NAMES.length];
final int[] lavaBodies = new int[BAND_NAMES.length];
final int[] longLavaBodies = new int[BAND_NAMES.length];
final int[] longWaterBodies = new int[BAND_NAMES.length];
final int[] springs = new int[BAND_NAMES.length];
int lavaSprings;
int waterSprings;
int unplacedSprings;
int longestLava;
int floorLavaBodies;
int chunks;
}
static List<Body> bodies(Grid grid) {
List<Body> bodies = new ArrayList<>();
boolean[] seen = new boolean[grid.kinds.length];
int[] stack = new int[1024];
for (int start = 0; start < grid.kinds.length; start++) {
byte kind = grid.kinds[start];
if (kind == NONE || seen[start]) {
continue;
}
int top = 0;
stack[top++] = start;
seen[start] = true;
int minX = Integer.MAX_VALUE;
int minZ = Integer.MAX_VALUE;
int maxX = Integer.MIN_VALUE;
int maxZ = Integer.MIN_VALUE;
int lowest = Integer.MAX_VALUE;
int cells = 0;
boolean pool = false;
while (top > 0) {
int cell = stack[--top];
int column = cell % (grid.span * grid.span);
int x = column % grid.span;
int z = column / grid.span;
int y = cell / (grid.span * grid.span);
minX = Math.min(minX, x);
maxX = Math.max(maxX, x);
minZ = Math.min(minZ, z);
maxZ = Math.max(maxZ, z);
lowest = Math.min(lowest, y);
cells++;
pool |= grid.pools[cell] != 0;
for (int direction = 0; direction < 6; direction++) {
int nextX = x + DX[direction];
int nextY = y + DY[direction];
int nextZ = z + DZ[direction];
if (nextX < 0 || nextZ < 0 || nextY < 0 || nextX >= grid.span || nextZ >= grid.span || nextY >= grid.height) {
continue;
}
int next = grid.index(nextX, nextY, nextZ);
if (!seen[next] && grid.kinds[next] == kind) {
seen[next] = true;
if (top == stack.length) {
stack = Arrays.copyOf(stack, stack.length * 2);
}
stack[top++] = next;
}
}
}
bodies.add(new Body(kind, pool, lowest, Math.max(maxX - minX, maxZ - minZ) + 1, cells));
}
return bodies;
}
static int band(int worldY) {
for (int band = 0; band < BAND_FLOORS.length; band++) {
if (worldY >= BAND_FLOORS[band]) {
return band;
}
}
return BAND_FLOORS.length;
}
static void add(Tally tally, List<Body> bodies, int minimumY, int caveLavaHeight) {
for (Body body : bodies) {
int band = band(body.lowestY() + minimumY);
if (body.pool()) {
tally.pools[band]++;
if (body.kind() == LAVA) {
tally.lavaPools[band]++;
}
}
if (body.kind() == LAVA) {
if (!body.pool() && body.lowestY() <= caveLavaHeight) {
tally.floorLavaBodies++;
continue;
}
tally.lavaBodies[band]++;
tally.longestLava = Math.max(tally.longestLava, body.extent());
if (body.extent() >= LONG_EXTENT) {
tally.longLavaBodies[band]++;
}
} else if (body.extent() >= LONG_EXTENT) {
tally.longWaterBodies[band]++;
}
}
}
public static void main(String[] arguments) {
int exitCode = 1;
try {
scan(Configuration.parse(arguments));
exitCode = 0;
} catch (Throwable failure) {
System.out.println(LOG_PREFIX + " FAIL");
failure.printStackTrace(System.out);
}
System.exit(exitCode);
}
private static void scan(Configuration configuration) throws Exception {
try (RealPackProbeSupport.Workspace workspace = RealPackProbeSupport.openWorkspace(new RealPackProbeSupport.WorkspaceOptions(
configuration.pack(), configuration.dimension(), LOG_PREFIX, null, configuration.work()));
RealPackProbeSupport.EngineSession session = workspace.openEngine(configuration.seed(), false, "survey")) {
Engine engine = session.engine();
Tally tally = new Tally();
ExecutorService workers = Executors.newFixedThreadPool(configuration.threads());
try {
int side = configuration.patchesPerSide();
for (int patchZ = 0; patchZ < side; patchZ++) {
for (int patchX = 0; patchX < side; patchX++) {
patch(engine, (patchX - side / 2) * PATCH_SPACING, (patchZ - side / 2) * PATCH_SPACING, workers, tally);
}
System.out.println(LOG_PREFIX + " row " + (patchZ + 1) + "/" + side);
}
} finally {
workers.shutdown();
workers.awaitTermination(60L, TimeUnit.SECONDS);
}
List<Throwable> reports = RealPackProbeSupport.settleAndDrain(engine);
if (!reports.isEmpty()) {
RealPackProbeSupport.printReports(LOG_PREFIX, "survey", reports);
throw new IllegalStateException("Generation reported " + reports.size() + " error(s)");
}
report(configuration.seed(), tally);
}
}
private static void patch(Engine engine, int minX, int minZ, ExecutorService workers, Tally tally) throws Exception {
HydrologyRuntime hydrology = engine.getComplex().getHydrologyRuntime();
if (hydrology != null && hydrology.enabled()) {
hydrology.prepareWindowsAround(minX, minZ, minX + PATCH_CHUNKS - 1, minZ + PATCH_CHUNKS - 1, 1).get();
}
int height = engine.getTarget().getHeight();
int minimumY = engine.getWorld().minHeight();
Grid grid = new Grid(PATCH_CHUNKS * 16, height);
List<Future<?>> futures = new ArrayList<>();
for (int offsetZ = 0; offsetZ < PATCH_CHUNKS; offsetZ++) {
for (int offsetX = 0; offsetX < PATCH_CHUNKS; offsetX++) {
int chunkX = minX + offsetX;
int chunkZ = minZ + offsetZ;
int originX = offsetX * 16;
int originZ = offsetZ * 16;
futures.add(workers.submit(() -> {
chunk(engine, chunkX, chunkZ, originX, originZ, grid, minimumY, tally);
return null;
}));
}
}
for (Future<?> future : futures) {
try {
future.get();
} catch (ExecutionException failure) {
throw new IllegalStateException("Patch at chunk " + minX + "," + minZ + " failed", failure.getCause());
}
}
tally.chunks += PATCH_CHUNKS * PATCH_CHUNKS;
add(tally, bodies(grid), minimumY, engine.getDimension().getCaveLavaHeight());
}
private static void chunk(Engine engine, int chunkX, int chunkZ, int originX, int originZ, Grid grid, int minimumY, Tally tally) {
int height = grid.height;
Hunk<NativeBlockState> blocks = Hunk.newArrayHunk(16, height, 16);
Hunk<NativeBiome> biomes = Hunk.newArrayHunk(16, height, 16);
try {
engine.generate(chunkX << 4, chunkZ << 4, blocks, biomes, false);
} catch (Exception failure) {
throw new IllegalStateException("Failed to generate " + chunkX + "," + chunkZ, failure);
}
for (int z = 0; z < 16; z++) {
for (int x = 0; x < 16; x++) {
int roof = -1;
for (int y = height - 1; y >= 0; y--) {
NativeBlockState state = blocks.get(x, y, z);
byte kind = kind(state);
if (roof < 0 && kind == NONE && state != null && !state.isAir() && state.isSolid()) {
roof = y;
}
if (kind != NONE && y < roof) {
grid.kinds[grid.index(originX + x, y, originZ + z)] = kind;
}
}
}
}
MantleChunk<Matter> mantle = engine.getMantle().getMantle().useChunk(chunkX, chunkZ);
try {
mantle.iterate(HydrologyCaveCell.class, (x, y, z, cell) -> {
if (cell == null) {
return;
}
if (cell.action() == HydrologyCaveAction.POOL_SOURCE) {
grid.pools[grid.index(originX + x, y, originZ + z)] = 1;
} else if (cell.action() == HydrologyCaveAction.SPRING_SOURCE) {
int index = grid.index(originX + x, y, originZ + z);
byte kind = kind(blocks.get(x, y, z));
grid.kinds[index] = NONE;
synchronized (tally) {
tally.springs[band(y + minimumY)]++;
if (kind == LAVA) {
tally.lavaSprings++;
} else if (kind == WATER) {
tally.waterSprings++;
} else {
tally.unplacedSprings++;
}
}
}
});
} finally {
mantle.release();
}
}
private static byte kind(NativeBlockState state) {
if (state == null || state.isAir()) {
return NONE;
}
String material = IrisProceduralBlocks.materialKey(state);
if (material.endsWith("lava")) {
return LAVA;
}
return material.endsWith("water") ? WATER : NONE;
}
private static void report(long seed, Tally tally) {
double per = 1000D / tally.chunks;
System.out.printf(Locale.ROOT, "CAVE_FLUID seed=%d chunks=%d lava_springs=%d water_springs=%d unplaced_springs=%d floor_lava_bodies=%d longest_lava=%d%n",
seed, tally.chunks, tally.lavaSprings, tally.waterSprings, tally.unplacedSprings, tally.floorLavaBodies, tally.longestLava);
for (int band = 0; band < BAND_NAMES.length; band++) {
System.out.printf(Locale.ROOT, "CAVE_FLUID_BAND seed=%d band=%s pools=%.1f lava_pools=%.1f lava_bodies=%.1f lava_long=%.1f water_long=%.1f springs=%.1f%n",
seed, BAND_NAMES[band], tally.pools[band] * per, tally.lavaPools[band] * per, tally.lavaBodies[band] * per,
tally.longLavaBodies[band] * per, tally.longWaterBodies[band] * per, tally.springs[band] * per);
}
}
}
@@ -0,0 +1,46 @@
package art.arcane.iris.probe;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class CaveFluidProbeTest {
private static final int HEIGHT = 32;
@Test
public void bodiesConnectThroughFacesAndMeasureTheirWidestSide() {
CaveFluidProbe.Grid grid = new CaveFluidProbe.Grid(64, HEIGHT);
for (int x = 2; x < 42; x++) {
grid.kinds[grid.index(x, 5, 7)] = 2;
}
grid.kinds[grid.index(50, 6, 7)] = 1;
grid.pools[grid.index(50, 6, 7)] = 1;
grid.kinds[grid.index(51, 7, 7)] = 1;
List<CaveFluidProbe.Body> bodies = CaveFluidProbe.bodies(grid);
assertEquals(3, bodies.size());
assertEquals(new CaveFluidProbe.Body((byte) 2, false, 5, 40, 40), bodies.get(0));
}
@Test
public void tallySortsBodiesIntoBandsAndSetsFloorLavaApart() {
CaveFluidProbe.Tally tally = new CaveFluidProbe.Tally();
CaveFluidProbe.add(tally, List.of(
new CaveFluidProbe.Body((byte) 2, false, 8, 3, 9),
new CaveFluidProbe.Body((byte) 2, true, 8, 3, 9),
new CaveFluidProbe.Body((byte) 2, false, 70, 40, 200),
new CaveFluidProbe.Body((byte) 1, true, 300, 33, 9)), -256, 8);
assertEquals(1, tally.floorLavaBodies);
assertEquals(1, tally.lavaPools[5]);
assertEquals(1, tally.pools[5]);
assertEquals(1, tally.lavaBodies[5]);
assertEquals(1, tally.longLavaBodies[4]);
assertEquals(1, tally.pools[1]);
assertEquals(1, tally.longWaterBodies[1]);
assertEquals(40, tally.longestLava);
}
}