Merge tidal inlets

- Sea inlets become tidal reaches on the river pipeline
- Recaptures the schema digest for the merged lane
This commit is contained in:
Brian Fopiano committed 2026-11-03 20:46:08 -05:00
commit 5df42fc49e
82 files changed
+3370 -4647

No files matched your search

@@ -56,7 +56,7 @@ public class IrisHydrology {
@Description("How the ground around water is reshaped.")
private IrisHydrologyDeformation deformation = new IrisHydrologyDeformation();
@Description("Water below the surface: flooded sea inlets and cave pools.")
@Description("Sea inlets on the coast, and pools and springs in caves.")
private IrisHydrologyUnderground underground = new IrisHydrologyUnderground();
@ArrayType(type = IrisFluidProfile.class, min = 1)
@@ -7,10 +7,10 @@ import lombok.experimental.Accessors;
@Accessors(chain = true)
@NoArgsConstructor
@Description("Water below the surface: flooded passages that run inland from the sea, pools on cave floors, and springs in cave walls.")
@Description("Sea inlets on the coast, and water below the surface: 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.")
@Description("Tidal arms of the sea that wind inland from low coasts at sea level.")
private IrisSeaInlets seaInlets = new IrisSeaInlets();
@Description("Standing water on the floors of carved caves.")
@@ -11,44 +11,58 @@ import lombok.experimental.Accessors;
@Accessors(chain = true)
@NoArgsConstructor
@Description("Flooded passages that open in coastal cliffs and run inland, up the valleys where the drainage allows and onward under higher ground, with the water held at sea level the whole way, ending in a pool chamber. An inlet, its chamber and its seal stay within 512 blocks of the coast.")
@Description("Tidal arms of the sea: winding water courses open to the sky, flat at sea level and filled with sea water, wide at the coast and narrowing inland between shaped banks. They form on low coasts and keep clear of rivers, ponds and lakes.")
@Data
public class IrisSeaInlets {
@Description("Cuts sea inlets into coastal cliffs.")
@Description("Cuts sea inlets into low coasts.")
private boolean enabled = true;
@MinNumber(32)
@MaxNumber(4096)
@Description("Size in blocks of the square cells of the site grid. Each cell holds at most one inlet; inlets in neighbouring cells can lie closer than this.")
private int spacing = 192;
@MinNumber(1)
@MaxNumber(128)
@Description("Height in blocks the coastal land must rise above sea level to be a site. The passage also needs ground at least headroom min + roofClearance + 2 blocks above sea level within about 16 blocks of the coast, so gentle coasts hold no inlets.")
private int minimumCliffHeight = 8;
private int spacing = 160;
@ArrayType(type = Integer.class, min = 2)
@Description("Length of an inlet in blocks, written as [min, max]. The max plus 12, plus the larger of halfWidth max and chamberRadius max, plus 3 must not exceed 512.")
@Description("Length of an inlet in blocks along its centre line, written as [min, max]. An arm that cannot reach the min is left out. The max, plus the meander, plus mouthHalfWidth max, plus bankBand must not exceed 512.")
private KList<Integer> length = new KList<>(64, 256);
@MinNumber(2)
@MaxNumber(128)
@Description("Highest ground in blocks above sea level an inlet may cut through. An arm also stays under the height its bank band can grade back without a sheer wall, about 1.7 times bankBand. It routes around or stops short of higher ground, so lower values keep inlets out of hills.")
private int maximumBankHeight = 44;
@ArrayType(type = Double.class, min = 2)
@Description("Half-width of the passage in blocks, written as [min, max], each from 1 to 16. The passage narrows toward its inland end.")
private KList<Double> halfWidth = new KList<>(2D, 5D);
@Description("Half-width of the water at the sea in blocks, written as [min, max], each from 2 to 32. The min must not be below headHalfWidth max.")
private KList<Double> mouthHalfWidth = new KList<>(13D, 15D);
@ArrayType(type = Integer.class, min = 2)
@Description("Water depth below sea level in blocks, written as [min, max], each from 2 to 16. Two blocks keep liquid water under an open slot's top sea layer.")
private KList<Integer> depth = new KList<>(2, 5);
@ArrayType(type = Double.class, min = 2)
@Description("Half-width of the water at the inland end in blocks, written as [min, max], each from 1 to 8.")
private KList<Double> headHalfWidth = new KList<>(2.5D, 3D);
@ArrayType(type = Integer.class, min = 2)
@Description("Air space above the water in blocks, written as [min, max], each from 0 to 32. It varies smoothly along the passage and shrinks where the ground above is thin.")
private KList<Integer> headroom = new KList<>(4, 10);
@MinNumber(0.5)
@MaxNumber(4)
@Description("How the width falls from mouth to head. 1 narrows evenly; above 1 stays narrow further from the head and widens late near the sea; below 1 widens early.")
private double taper = 1.4D;
@MinNumber(0)
@MaxNumber(0.5)
@Description("Slow change in width along the arm, as a fraction of the width at that point.")
private double widthVariation = 0.18D;
@MinNumber(1)
@MaxNumber(64)
@Description("Least solid ground in blocks kept between the passage roof and the surface.")
private int roofClearance = 6;
@MaxNumber(16)
@Description("Half-width in blocks that sets the size of the bends, as a river of that half-width would meander. Larger values give longer, wider bends.")
private double meanderWidth = 4D;
@ArrayType(type = Integer.class, min = 2)
@Description("Radius in blocks of the pool chamber at the inland end, written as [min, max], each from 1 to 32.")
private KList<Integer> chamberRadius = new KList<>(6, 12);
@Description("Water depth at the middle of the arm in blocks, written as [min, max], each from 2 to 16. The depth runs from min at the head to max toward the sea, and shoals to 1 at both ends.")
private KList<Integer> depth = new KList<>(2, 5);
@MinNumber(4)
@MaxNumber(64)
@Description("Width in blocks of the band of ground beside the water that is shaped into banks.")
private int bankBand = 32;
@Description("Profile of the banks across bankBand.")
private IrisBankStyle bankStyle = IrisBankStyle.SMOOTH;
}
@@ -11,7 +11,6 @@ import art.arcane.iris.generation.hydrology.query.HydrologyFeatureQuery;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.hydrology.query.HydrologySearchTimeoutException;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.water.HydrologyTier;
import art.arcane.iris.generation.hydrology.water.Pond;
import art.arcane.iris.generation.hydrology.water.PondKind;
@@ -41,6 +40,8 @@ final class HydrologyFeatureSearch {
private static final Set<HydrologyFeatureType> WINDOW_TYPES = EnumSet.of(HydrologyFeatureType.STREAM, HydrologyFeatureType.RIVER,
HydrologyFeatureType.MAJOR_RIVER, HydrologyFeatureType.CASCADE, HydrologyFeatureType.WATERFALL, HydrologyFeatureType.MOUTH,
HydrologyFeatureType.POND, HydrologyFeatureType.DAM, HydrologyFeatureType.SEA_INLET);
private static final double TIDAL_LANDING_FROM = 0.5D;
private static final double TIDAL_LANDING_TO = 0.9D;
private static final long POLL_NANOS = TimeUnit.MILLISECONDS.toNanos(50L);
static final String OFF = "hydrology is off";
private static final String PONDS_OFF = "hydrology.ponds.natural and hydrology.ponds.seeded are disabled";
@@ -219,18 +220,6 @@ final class HydrologyFeatureSearch {
pond(pond, type);
}
}
if (types.contains(HydrologyFeatureType.SEA_INLET)) {
for (SeaInlet inlet : plan.inlets()) {
inlet(inlet);
}
}
}
private void inlet(SeaInlet inlet) {
for (int station = 0; station < inlet.stations(); station++) {
offer(inlet.id(), HydrologyFeatureType.SEA_INLET, (int) Math.floor(inlet.xs()[station]), inlet.waterLevel(),
(int) Math.floor(inlet.zs()[station]));
}
}
private HydrologyFeatureType pondType(Pond pond) {
@@ -244,6 +233,12 @@ final class HydrologyFeatureSearch {
}
private void reach(Reach reach) {
if (reach.style()[0] == ReachStyle.TIDAL) {
if (types.contains(HydrologyFeatureType.SEA_INLET)) {
tidal(reach);
}
return;
}
HydrologyFeatureType channel = channelType(settings, reach.tier());
boolean whole = types.contains(channel);
float[] xs = reach.xs();
@@ -257,6 +252,21 @@ final class HydrologyFeatureSearch {
}
}
private void tidal(Reach reach) {
float[] xs = reach.xs();
float[] zs = reach.zs();
double[] along = new double[xs.length];
for (int index = 1; index < xs.length; index++) {
along[index] = along[index - 1] + Math.hypot(xs[index] - xs[index - 1], zs[index] - zs[index - 1]);
}
double total = along[xs.length - 1];
for (int index = 0; index < xs.length; index++) {
if (along[index] >= TIDAL_LANDING_FROM * total && along[index] <= TIDAL_LANDING_TO * total) {
offer(reach.id(), HydrologyFeatureType.SEA_INLET, (int) Math.floor(xs[index]), reach.grade()[index], (int) Math.floor(zs[index]));
}
}
}
private void pond(Pond pond, HydrologyFeatureType type) {
PondMask mask = pond.mask();
for (int j = 0; j < mask.depth(); j++) {
@@ -306,7 +316,7 @@ final class HydrologyFeatureSearch {
case CASCADE -> HydrologyFeatureType.CASCADE;
case WATERFALL -> HydrologyFeatureType.WATERFALL;
case MOUTH -> HydrologyFeatureType.MOUTH;
case RUN, RIFFLE, POND_OUTLET -> null;
case RUN, RIFFLE, POND_OUTLET, TIDAL -> null;
};
}
@@ -1,20 +1,18 @@
package art.arcane.iris.generation.hydrology.engine;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.water.Pond;
import art.arcane.iris.generation.hydrology.water.Reach;
import java.util.List;
import java.util.Objects;
public record HydrologyPlanPreview(List<Reach> reaches, List<Pond> ponds, List<Pond> lakes, List<SeaInlet> inlets, boolean complete) {
public static final HydrologyPlanPreview EMPTY = new HydrologyPlanPreview(List.of(), List.of(), List.of(), List.of(), true);
public static final HydrologyPlanPreview PENDING = new HydrologyPlanPreview(List.of(), List.of(), List.of(), List.of(), false);
public record HydrologyPlanPreview(List<Reach> reaches, List<Pond> ponds, List<Pond> lakes, boolean complete) {
public static final HydrologyPlanPreview EMPTY = new HydrologyPlanPreview(List.of(), List.of(), List.of(), true);
public static final HydrologyPlanPreview PENDING = new HydrologyPlanPreview(List.of(), List.of(), List.of(), false);
public HydrologyPlanPreview {
reaches = List.copyOf(Objects.requireNonNull(reaches, "reaches"));
ponds = List.copyOf(Objects.requireNonNull(ponds, "ponds"));
lakes = List.copyOf(Objects.requireNonNull(lakes, "lakes"));
inlets = List.copyOf(Objects.requireNonNull(inlets, "inlets"));
}
}
@@ -19,8 +19,6 @@ import art.arcane.iris.generation.hydrology.raster.ChannelFluids;
import art.arcane.iris.generation.hydrology.raster.ChunkRasterizer;
import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
import art.arcane.iris.generation.hydrology.raster.NaturalHeights;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.underground.SeaInletRasterizer;
import art.arcane.iris.generation.hydrology.water.HydrologyTier;
import art.arcane.iris.generation.hydrology.water.Pond;
import art.arcane.iris.generation.hydrology.water.Reach;
@@ -307,7 +305,6 @@ public final class HydrologyRuntime {
boolean complete = true;
List<Reach> reaches = new ArrayList<>();
List<Pond> ponds = new ArrayList<>();
List<SeaInlet> inlets = new ArrayList<>();
for (int wz = min.wz() - 1; wz <= max.wz() + 1; wz++) {
for (int wx = min.wx() - 1; wx <= max.wx() + 1; wx++) {
WindowKey window = new WindowKey(wx, wz);
@@ -315,7 +312,6 @@ public final class HydrologyRuntime {
if (plan.isPresent()) {
reaches.addAll(plan.get().plan().reaches());
ponds.addAll(plan.get().plan().ponds());
inlets.addAll(plan.get().plan().inlets());
} else {
complete = false;
requestPreview(window, windowPreviewFailures, key(wx, wz), "window " + wx + "," + wz, () -> cache.previewWindow(window));
@@ -335,7 +331,7 @@ public final class HydrologyRuntime {
() -> cache.previewRegion(region));
}
}
return new HydrologyPlanPreview(reaches, ponds, List.copyOf(lakes.values()), inlets, complete);
return new HydrologyPlanPreview(reaches, ponds, List.copyOf(lakes.values()), complete);
}
public ChunkWaterRaster rasterAt(int blockX, int blockZ) {
@@ -441,28 +437,6 @@ public final class HydrologyRuntime {
return HydrologyFeatureSearch.channelType(settings, tier);
}
public List<SeaInlet> inlets(int chunkX, int chunkZ) {
if (cache == null) {
return List.of();
}
requireOpen();
boolean main = mainThread.getAsBoolean();
List<SeaInlet> touching = new ArrayList<>();
for (CompletableFuture<IndexedWindow> plan : plans(neighbourhood(chunkX, chunkZ), List.of(), PlanMode.DEMAND).windowFutures()) {
if (main && !plan.isDone()) {
throw new IllegalStateException("The hydrology windows around chunk " + chunkX + "," + chunkZ
+ " are not planned yet, so its sea inlets cannot be generated on the main thread.");
}
IndexedWindow window = main ? plan.join() : cache.awaitPlan(plan);
for (SeaInlet inlet : window.plan().inlets()) {
if (SeaInletRasterizer.touches(inlet, chunkX, chunkZ)) {
touching.add(inlet);
}
}
}
return touching;
}
public Set<HydrologyFeatureType> standingWaterTypes(int chunkX, int chunkZ, long featureId) {
if (cache == null) {
throw new IllegalStateException("Hydrology is disabled, so it has no standing water.");
@@ -1,6 +1,5 @@
package art.arcane.iris.generation.hydrology.plan;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.water.HydrologyTier;
import art.arcane.iris.generation.hydrology.water.Pond;
import art.arcane.iris.generation.hydrology.water.PondKind;
@@ -26,31 +25,27 @@ public final class HydrologyPlanCodec {
private static final int POINT_BYTES = 5 * Integer.BYTES + 1;
private static final int REACH_BYTES = 2 * Long.BYTES + 4 * Integer.BYTES + 2 * POINT_BYTES;
private static final int POND_BYTES = 2 * Long.BYTES + 1 + 15 * Integer.BYTES;
private static final int STATION_BYTES = 5 * Integer.BYTES;
private static final int INLET_BYTES = Long.BYTES + 5 * Integer.BYTES + 2 * STATION_BYTES;
private HydrologyPlanCodec() {
}
public static byte[] encode(HydrologySettings settings, WindowPlan plan) {
return encode(settings, WINDOW, plan.key().wx(), plan.key().wz(), plan.reaches(), plan.ponds(), plan.inlets());
return encode(settings, WINDOW, plan.key().wx(), plan.key().wz(), plan.reaches(), plan.ponds());
}
public static byte[] encode(HydrologySettings settings, RegionPlan plan) {
return encode(settings, REGION, plan.key().rx(), plan.key().rz(), plan.majorReaches(), plan.lakes(), List.of());
return encode(settings, REGION, plan.key().rx(), plan.key().rz(), plan.majorReaches(), plan.lakes());
}
public static Optional<WindowPlan> decodeWindow(HydrologySettings settings, byte[] data) {
return decode(settings, WINDOW, data).map(body -> new WindowPlan(new WindowKey(body.x(), body.z()), body.reaches(), body.ponds(),
body.inlets()));
return decode(settings, WINDOW, data).map(body -> new WindowPlan(new WindowKey(body.x(), body.z()), body.reaches(), body.ponds()));
}
public static Optional<RegionPlan> decodeRegion(HydrologySettings settings, byte[] data) {
return decode(settings, REGION, data).map(body -> new RegionPlan(new RegionKey(body.x(), body.z()), body.reaches(), body.ponds()));
}
private static byte[] encode(HydrologySettings settings, byte kind, int x, int z, List<Reach> reaches, List<Pond> ponds,
List<SeaInlet> inlets) {
private static byte[] encode(HydrologySettings settings, byte kind, int x, int z, List<Reach> reaches, List<Pond> ponds) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (DataOutputStream out = new DataOutputStream(bytes)) {
out.writeInt(MAGIC);
@@ -66,12 +61,6 @@ public final class HydrologyPlanCodec {
for (Pond pond : ponds) {
writePond(out, pond);
}
if (kind == WINDOW) {
out.writeInt(inlets.size());
for (SeaInlet inlet : inlets) {
writeInlet(out, inlet);
}
}
} catch (IOException failure) {
throw new UncheckedIOException(failure);
}
@@ -79,6 +68,9 @@ public final class HydrologyPlanCodec {
}
private static int tierIndex(HydrologySettings settings, Reach reach) {
if (reach.tier().equals(settings.tidalTier())) {
return settings.tiers().size();
}
int index = settings.tiers().indexOf(reach.tier());
if (index < 0) {
throw new IllegalArgumentException("Reach " + reach.id() + " uses tier " + reach.tier().name() + ", which is not in the settings.");
@@ -139,24 +131,6 @@ public final class HydrologyPlanCodec {
out.writeInt(pond.floorZ());
}
private static void writeInlet(DataOutputStream out, SeaInlet inlet) throws IOException {
out.writeLong(inlet.id());
out.writeInt(inlet.waterLevel());
out.writeInt(inlet.chamberX());
out.writeInt(inlet.chamberZ());
out.writeInt(inlet.chamberRadius());
out.writeInt(inlet.stations());
writeFloats(out, inlet.xs());
writeFloats(out, inlet.zs());
writeFloats(out, inlet.halfWidth());
for (int floor : inlet.floor()) {
out.writeInt(floor);
}
for (int ceiling : inlet.ceiling()) {
out.writeInt(ceiling);
}
}
private static void writeFloats(DataOutputStream out, float[] values) throws IOException {
for (float value : values) {
out.writeInt(Float.floatToRawIntBits(value));
@@ -174,33 +148,28 @@ public final class HydrologyPlanCodec {
int reachCount = count(in, REACH_BYTES);
List<Reach> reaches = new ArrayList<>(reachCount);
for (int index = 0; index < reachCount; index++) {
reaches.add(readReach(in, settings.tiers()));
reaches.add(readReach(in, settings));
}
int pondCount = count(in, POND_BYTES);
List<Pond> ponds = new ArrayList<>(pondCount);
for (int index = 0; index < pondCount; index++) {
ponds.add(readPond(in));
}
List<SeaInlet> inlets = new ArrayList<>();
if (kind == WINDOW) {
int inletCount = count(in, INLET_BYTES);
for (int index = 0; index < inletCount; index++) {
inlets.add(readInlet(in));
}
}
if (in.hasRemaining()) {
return Optional.empty();
}
return Optional.of(new Body(x, z, reaches, ponds, inlets));
return Optional.of(new Body(x, z, reaches, ponds));
} catch (BufferUnderflowException | IllegalArgumentException | IllegalStateException malformed) {
return Optional.empty();
}
}
private static Reach readReach(ByteBuffer in, List<HydrologyTier> tiers) {
private static Reach readReach(ByteBuffer in, HydrologySettings settings) {
long id = in.getLong();
long downstreamId = in.getLong();
HydrologyTier tier = tiers.get(index(in.getInt(), tiers.size()));
List<HydrologyTier> tiers = settings.tiers();
int tierIndex = index(in.getInt(), tiers.size() + 1);
HydrologyTier tier = tierIndex == tiers.size() ? settings.tidalTier() : tiers.get(tierIndex);
float catchment = Float.intBitsToFloat(in.getInt());
int points = count(in, POINT_BYTES);
float[] xs = readFloats(in, points);
@@ -246,27 +215,6 @@ public final class HydrologyPlanCodec {
return new Pond(id, kind, level, floor, spillX, spillZ, spillHeight, mask, outletReachId, damRaise, fluid, in.getInt(), in.getInt());
}
private static SeaInlet readInlet(ByteBuffer in) {
long id = in.getLong();
int waterLevel = in.getInt();
int chamberX = in.getInt();
int chamberZ = in.getInt();
int chamberRadius = in.getInt();
int stations = count(in, STATION_BYTES);
float[] xs = readFloats(in, stations);
float[] zs = readFloats(in, stations);
float[] halfWidth = readFloats(in, stations);
int[] floor = new int[stations];
for (int station = 0; station < stations; station++) {
floor[station] = in.getInt();
}
int[] ceiling = new int[stations];
for (int station = 0; station < stations; station++) {
ceiling[station] = in.getInt();
}
return new SeaInlet(id, xs, zs, halfWidth, waterLevel, floor, ceiling, chamberX, chamberZ, chamberRadius);
}
private static String readString(ByteBuffer in) {
int length = in.getInt();
if (length == -1) {
@@ -303,6 +251,6 @@ public final class HydrologyPlanCodec {
return value;
}
private record Body(int x, int z, List<Reach> reaches, List<Pond> ponds, List<SeaInlet> inlets) {
private record Body(int x, int z, List<Reach> reaches, List<Pond> ponds) {
}
}
@@ -21,9 +21,8 @@ import art.arcane.iris.generation.hydrology.config.IrisPondDams;
import art.arcane.iris.generation.hydrology.config.IrisPondNatural;
import art.arcane.iris.generation.hydrology.config.IrisPondSeeded;
import art.arcane.iris.generation.hydrology.config.IrisPondShore;
import art.arcane.iris.generation.hydrology.config.IrisBankStyle;
import art.arcane.iris.generation.hydrology.config.IrisSeaInlets;
import art.arcane.iris.generation.hydrology.underground.SeaInletPlanner;
import art.arcane.iris.generation.hydrology.underground.SeaInletRasterizer;
import art.arcane.iris.generation.hydrology.raster.WaterHeads;
import art.arcane.iris.generation.hydrology.water.HydrologyTier;
import art.arcane.iris.generation.hydrology.water.LakeCandidate;
@@ -52,14 +51,26 @@ public final class HydrologySettings {
private static final int MAX_DELTA_LENGTH = 384;
public static final float MAX_HALF_WIDTH = 64f;
public static final int DELTA_STEP = 2;
private static final double MIN_INLET_HALF_WIDTH = 1D;
private static final double MAX_INLET_HALF_WIDTH = 16D;
private static final int TIDAL_BASE_TIER = 1;
private static final String TIDAL_TIER_NAME = "tidal";
private static final double MIN_INLET_MOUTH = 2D;
private static final double MAX_INLET_MOUTH = 32D;
private static final double MIN_INLET_HEAD = 1D;
private static final double MAX_INLET_HEAD = 8D;
private static final int MIN_INLET_DEPTH = 2;
private static final int MAX_INLET_DEPTH = 16;
private static final int MAX_INLET_HEADROOM = 32;
private static final int MAX_INLET_CHAMBER = 32;
private static final int MIN_INLET_BANK_HEIGHT = 2;
private static final int MAX_INLET_BANK_HEIGHT = 128;
private static final double MIN_INLET_TAPER = 0.5D;
private static final double MAX_INLET_TAPER = 4D;
private static final double MAX_INLET_WIDTH_VARIATION = 0.5D;
private static final double MIN_INLET_MEANDER_WIDTH = 1D;
private static final double MAX_INLET_MEANDER_WIDTH = 16D;
private static final int MIN_INLET_BANK_BAND = 4;
private static final int MAX_INLET_BANK_BAND = 64;
private static final int INLET_LAST_STEP = (int) Math.ceil(WindowPlanner.CELL * Math.sqrt(2D));
private static final int INLET_SHELL = SeaInletRasterizer.SHELL;
private static final double INLET_MEANDER_SCALE = 2.5D;
private static final double INLET_MEANDER_MAX = 16D;
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;
@@ -85,6 +96,7 @@ public final class HydrologySettings {
private final Lakes lakes;
private final Deformation deformation;
private final Underground underground;
private final HydrologyTier tidalTier;
private final Map<String, IrisMaterialPalette> fluids;
private final Map<String, String> seams;
private final int prefetchRings;
@@ -108,6 +120,7 @@ public final class HydrologySettings {
this.lakes = lakes(config.getLakes());
this.deformation = deformation(config.getDeformation());
this.underground = underground(config.getUnderground());
this.tidalTier = tidalTier(tiers.get(Math.min(TIDAL_BASE_TIER, tiers.size() - 1)), underground.seaInlets());
this.fluids = fluids(config.getFluids());
this.seams = seams(config.getFluids());
this.prefetchRings = config.getPrefetchRings();
@@ -129,6 +142,10 @@ public final class HydrologySettings {
return tiers;
}
public HydrologyTier tidalTier() {
return tidalTier;
}
public HydrologyTier majorTier() {
return tiers.get(tiers.size() - 1);
}
@@ -207,6 +224,12 @@ public final class HydrologySettings {
return persist;
}
private static HydrologyTier tidalTier(HydrologyTier base, SeaInlets inlets) {
return new HydrologyTier(TIDAL_TIER_NAME, base.minCatchment(), inlets.meanderWidth(), inlets.meanderWidth(), 0f, base.depthRatio(), 0, false,
base.waterfallMinimumDrop(), base.stepHeight(), inlets.bankBand(), inlets.bankStyle(), new HydrologyTier.Estuary(0, 1f),
new HydrologyTier.Delta(0, 0f, 0), base.materials(), base.fluid(), base.decorators());
}
private static Climate climate(IrisHydrologyClimate config) {
Objects.requireNonNull(config, "Hydrology climate is missing");
IrisGeneratorStyle style = Objects.requireNonNull(config.getStyle(), "Hydrology climate.style is missing");
@@ -365,39 +388,49 @@ public final class HydrologySettings {
}
private SeaInlets seaInlets(IrisSeaInlets config) {
SeaInlets inlets = new SeaInlets(config.isEnabled(), config.getSpacing(), config.getMinimumCliffHeight(),
SeaInlets inlets = new SeaInlets(config.isEnabled(), config.getSpacing(),
intRange(config.getLength(), "underground.seaInlets.length", RangeFloor.POSITIVE),
floatRange(config.getHalfWidth(), "underground.seaInlets.halfWidth", RangeFloor.POSITIVE),
config.getMaximumBankHeight(),
floatRange(config.getMouthHalfWidth(), "underground.seaInlets.mouthHalfWidth", RangeFloor.POSITIVE),
floatRange(config.getHeadHalfWidth(), "underground.seaInlets.headHalfWidth", RangeFloor.POSITIVE),
(float) config.getTaper(), (float) config.getWidthVariation(), (float) config.getMeanderWidth(),
intRange(config.getDepth(), "underground.seaInlets.depth", RangeFloor.POSITIVE),
intRange(config.getHeadroom(), "underground.seaInlets.headroom", RangeFloor.NON_NEGATIVE),
config.getRoofClearance(),
intRange(config.getChamberRadius(), "underground.seaInlets.chamberRadius", RangeFloor.POSITIVE));
requireWithin(inlets.halfWidth().min(), MIN_INLET_HALF_WIDTH, MAX_INLET_HALF_WIDTH, "underground.seaInlets.halfWidth", config.getHalfWidth());
requireWithin(inlets.halfWidth().max(), MIN_INLET_HALF_WIDTH, MAX_INLET_HALF_WIDTH, "underground.seaInlets.halfWidth", config.getHalfWidth());
config.getBankBand(), Objects.requireNonNull(config.getBankStyle(), "Hydrology underground.seaInlets.bankStyle is missing"));
requireWithin(inlets.mouthHalfWidth().min(), MIN_INLET_MOUTH, MAX_INLET_MOUTH, "underground.seaInlets.mouthHalfWidth", config.getMouthHalfWidth());
requireWithin(inlets.mouthHalfWidth().max(), MIN_INLET_MOUTH, MAX_INLET_MOUTH, "underground.seaInlets.mouthHalfWidth", config.getMouthHalfWidth());
requireWithin(inlets.headHalfWidth().min(), MIN_INLET_HEAD, MAX_INLET_HEAD, "underground.seaInlets.headHalfWidth", config.getHeadHalfWidth());
requireWithin(inlets.headHalfWidth().max(), MIN_INLET_HEAD, MAX_INLET_HEAD, "underground.seaInlets.headHalfWidth", config.getHeadHalfWidth());
requireWithin(inlets.depth().min(), MIN_INLET_DEPTH, MAX_INLET_DEPTH, "underground.seaInlets.depth", config.getDepth());
requireWithin(inlets.depth().max(), MIN_INLET_DEPTH, MAX_INLET_DEPTH, "underground.seaInlets.depth", config.getDepth());
requireWithin(inlets.headroom().max(), 0, MAX_INLET_HEADROOM, "underground.seaInlets.headroom", config.getHeadroom());
requireWithin(inlets.chamberRadius().max(), 1, MAX_INLET_CHAMBER, "underground.seaInlets.chamberRadius", config.getChamberRadius());
if (inlets.enabled() && seaLevel > minY && seaLevel - inlets.depth().max() - INLET_SHELL - 1 <= minY) {
throw new IllegalArgumentException("Hydrology underground.seaInlets.depth max " + inlets.depth().max()
+ " puts the inlet floor and its seal below the world bottom " + minY + " (sea level " + seaLevel + ")");
requireWithin(inlets.maximumBankHeight(), MIN_INLET_BANK_HEIGHT, MAX_INLET_BANK_HEIGHT, "underground.seaInlets.maximumBankHeight");
requireScalarWithin(config.getTaper(), MIN_INLET_TAPER, MAX_INLET_TAPER, "underground.seaInlets.taper");
requireScalarWithin(config.getWidthVariation(), 0D, MAX_INLET_WIDTH_VARIATION, "underground.seaInlets.widthVariation");
requireScalarWithin(config.getMeanderWidth(), MIN_INLET_MEANDER_WIDTH, MAX_INLET_MEANDER_WIDTH, "underground.seaInlets.meanderWidth");
requireWithin(inlets.bankBand(), MIN_INLET_BANK_BAND, MAX_INLET_BANK_BAND, "underground.seaInlets.bankBand");
if (inlets.mouthHalfWidth().min() < inlets.headHalfWidth().max()) {
throw new IllegalArgumentException("Hydrology underground.seaInlets.mouthHalfWidth min " + inlets.mouthHalfWidth().min()
+ " must not be below headHalfWidth max " + inlets.headHalfWidth().max() + ": an inlet narrows inland");
}
long extent = (long) inlets.length().max() + INLET_LAST_STEP + Math.max((long) Math.ceil(inlets.halfWidth().max()),
inlets.chamberRadius().max()) + 1L + INLET_SHELL;
if (inlets.enabled() && seaLevel > minY && seaLevel - inlets.depth().max() - 1 <= minY) {
throw new IllegalArgumentException("Hydrology underground.seaInlets.depth max " + inlets.depth().max()
+ " puts the inlet floor below the world bottom " + minY + " (sea level " + seaLevel + ")");
}
long meander = (long) Math.ceil(Math.min(INLET_MEANDER_MAX, INLET_MEANDER_SCALE * (inlets.meanderWidth() + 1f)));
long extent = (long) inlets.length().max() + INLET_LAST_STEP + meander + (long) Math.ceil(inlets.mouthHalfWidth().max()) + inlets.bankBand();
if (extent > WindowKey.SIZE) {
throw new IllegalArgumentException("Hydrology underground.seaInlets reach " + extent + " blocks from the coast (length max "
+ inlets.length().max() + " + " + INLET_LAST_STEP + " for the last step + the wider of halfWidth max and chamberRadius max"
+ " + " + (1 + INLET_SHELL) + " for the seal); an inlet must stay within " + WindowKey.SIZE + " blocks");
}
long lookups = SeaInletPlanner.lookupReach(inlets.length().max(), inlets.chamberRadius().max());
if (lookups > WindowKey.SIZE) {
throw new IllegalArgumentException("Hydrology underground.seaInlets planning looks " + lookups
+ " blocks from the coast (length max " + inlets.length().max() + ", chamberRadius max " + inlets.chamberRadius().max()
+ "); it must stay within " + WindowKey.SIZE + " blocks");
+ inlets.length().max() + " + " + INLET_LAST_STEP + " for the last step + " + meander + " for the meander + mouthHalfWidth max "
+ inlets.mouthHalfWidth().max() + " + bankBand " + inlets.bankBand() + "); an inlet must stay within " + WindowKey.SIZE + " blocks");
}
return inlets;
}
private static void requireScalarWithin(double value, double min, double max, String field) {
if (!Double.isFinite(value) || value < min || value > max) {
throw new IllegalArgumentException("Hydrology " + field + " must stay within " + min + ".." + max + ", got " + value);
}
}
private static void requireWithin(double value, double min, double max, String field, List<? extends Number> written) {
if (value < min || value > max) {
throw new IllegalArgumentException("Hydrology range " + field + " must stay within " + min + ".." + max + ", got " + written);
@@ -761,9 +794,9 @@ public final class HydrologySettings {
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())
hash.add(inlets.enabled()).add(inlets.spacing()).add(inlets.length()).add(inlets.maximumBankHeight())
.add(inlets.mouthHalfWidth()).add(inlets.headHalfWidth()).add(inlets.taper()).add(inlets.widthVariation())
.add(inlets.meanderWidth()).add(inlets.depth()).add(inlets.bankBand()).add(inlets.bankStyle())
.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.deepFluid()).add(pools.deepFluidMaxY())
@@ -828,8 +861,9 @@ public final class HydrologySettings {
public record Deformation(int maxFill, float bankSlope, float bankSteepFactor, float bankNoise, boolean caveMask) {
}
public record SeaInlets(boolean enabled, int spacing, int minimumCliffHeight, IntRange length, FloatRange halfWidth,
IntRange depth, IntRange headroom, int roofClearance, IntRange chamberRadius) {
public record SeaInlets(boolean enabled, int spacing, IntRange length, int maximumBankHeight, FloatRange mouthHalfWidth,
FloatRange headHalfWidth, float taper, float widthVariation, float meanderWidth, IntRange depth, int bankBand,
IrisBankStyle bankStyle) {
}
public record CavePools(boolean enabled, float density, int minArea, int maxArea, int maxDepth, int radius,
@@ -1,17 +1,15 @@
package art.arcane.iris.generation.hydrology.plan;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.water.Pond;
import art.arcane.iris.generation.hydrology.water.Reach;
import java.util.List;
import java.util.Objects;
public record WindowPlan(WindowKey key, List<Reach> reaches, List<Pond> ponds, List<SeaInlet> inlets) {
public record WindowPlan(WindowKey key, List<Reach> reaches, List<Pond> ponds) {
public WindowPlan {
Objects.requireNonNull(key, "key");
reaches = List.copyOf(reaches);
ponds = List.copyOf(ponds);
inlets = List.copyOf(inlets);
}
}
@@ -13,8 +13,6 @@ import art.arcane.iris.generation.hydrology.grid.HydrologySampleBuffer;
import art.arcane.iris.generation.hydrology.grid.PriorityFlood;
import art.arcane.iris.generation.hydrology.raster.PondChannelSettlement;
import art.arcane.iris.generation.hydrology.raster.TongueGuard;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.underground.SeaInletPlanner;
import art.arcane.iris.generation.hydrology.water.CupSet;
import art.arcane.iris.generation.hydrology.water.Pond;
import art.arcane.iris.generation.hydrology.water.PondKind;
@@ -23,6 +21,7 @@ import art.arcane.iris.generation.hydrology.water.Reach;
import art.arcane.iris.generation.hydrology.water.ReachShaper;
import art.arcane.iris.generation.hydrology.water.ReachStyle;
import art.arcane.iris.generation.hydrology.water.ShapedNetwork;
import art.arcane.iris.generation.hydrology.water.TidalPlanner;
import java.util.ArrayList;
import java.util.BitSet;
@@ -49,14 +48,14 @@ public final class WindowPlanner {
private final HeightLattice fine;
private final PondPlanner ponds;
private final ReachShaper shaper;
private final SeaInletPlanner inlets;
private final TidalPlanner tidal;
public WindowPlanner(HydrologySettings settings, HeightLattice fine, PondPlanner ponds, ReachShaper shaper) {
this.settings = Objects.requireNonNull(settings, "settings");
this.fine = Objects.requireNonNull(fine, "fine");
this.ponds = Objects.requireNonNull(ponds, "ponds");
this.shaper = Objects.requireNonNull(shaper, "shaper");
this.inlets = new SeaInletPlanner(settings);
this.tidal = new TidalPlanner(settings, fine);
if (fine.cell() != FINE_CELL) {
throw new IllegalArgumentException("Window fine lattice cell " + fine.cell() + " must be " + FINE_CELL);
}
@@ -131,8 +130,9 @@ public final class WindowPlanner {
}
List<Reach> reaches = network.reaches();
List<Pond> windowPonds = windowPonds(network.ponds());
List<SeaInlet> planned = inlets.plan(key, raw, samples, drainage.receivers(), drainage.accumulation(), network, settings.seed());
WindowPlan owned = new WindowPlan(key, ownedReaches(key, reaches), ownedPonds(key, windowPonds), ownedInlets(key, planned));
List<Reach> ownedReaches = new ArrayList<>(ownedReaches(key, reaches));
ownedReaches.addAll(tidal.plan(key, natural, samples, network));
WindowPlan owned = new WindowPlan(key, ownedReaches, ownedPonds(key, windowPonds));
requireSeaConnectedHeads(owned, settings.seaLevel());
return new WindowComputation(owned, reaches, windowPonds);
}
@@ -356,24 +356,11 @@ public final class WindowPlanner {
return owned;
}
private static List<SeaInlet> ownedInlets(WindowKey key, List<SeaInlet> planned) {
List<SeaInlet> owned = new ArrayList<>();
for (SeaInlet inlet : planned) {
if (key.equals(WindowKey.containing((int) Math.floor(inlet.xs()[1]), (int) Math.floor(inlet.zs()[1])))) {
owned.add(inlet);
}
}
return owned;
}
private static void requireSeaConnectedHeads(WindowPlan plan, int seaLevel) {
for (SeaInlet inlet : plan.inlets()) {
if (inlet.waterLevel() != seaLevel) {
throw new IllegalStateException("Window " + plan.key() + " sea inlet " + inlet.id() + " holds water at " + inlet.waterLevel()
+ ", not at sea level " + seaLevel);
}
}
static void requireSeaConnectedHeads(WindowPlan plan, int seaLevel) {
for (Reach reach : plan.reaches()) {
if (requireTidal(plan.key(), reach, seaLevel)) {
continue;
}
int mouth = reach.grade().length;
while (mouth > 0 && reach.style()[mouth - 1] == ReachStyle.MOUTH) {
mouth--;
@@ -401,6 +388,30 @@ public final class WindowPlanner {
}
}
private static boolean requireTidal(WindowKey key, Reach reach, int seaLevel) {
boolean any = false;
boolean all = true;
for (ReachStyle style : reach.style()) {
any |= style == ReachStyle.TIDAL;
all &= style == ReachStyle.TIDAL;
}
if (!any) {
return false;
}
if (!all) {
throw new IllegalStateException("Window " + key + " sea inlet " + reach.id() + " mixes tidal water with other water styles");
}
if (reach.downstreamId() != 0L) {
throw offSea(key, reach, reach.grade().length - 1, ", but a sea inlet drains into reach " + reach.downstreamId() + " instead of the sea");
}
for (int point = 0; point < reach.grade().length; point++) {
if (reach.grade()[point] != seaLevel) {
throw offSea(key, reach, point, ", but a sea inlet stands at sea level " + seaLevel);
}
}
return true;
}
private static IllegalStateException offSea(WindowKey key, Reach reach, int point, String rule) {
return new IllegalStateException("Window " + key + " reach " + reach.id() + " " + reach.style()[point] + " point " + point + " at "
+ reach.xs()[point] + "," + reach.zs()[point] + " is graded " + reach.grade()[point] + rule);
@@ -5,8 +5,6 @@ import art.arcane.iris.generation.hydrology.plan.IndexedWindow;
import art.arcane.iris.generation.hydrology.plan.RegionKey;
import art.arcane.iris.generation.hydrology.plan.RegionPlan;
import art.arcane.iris.generation.hydrology.plan.WindowKey;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.underground.SeaInletRasterizer;
import art.arcane.iris.generation.hydrology.water.ConfluenceGrader;
import art.arcane.iris.generation.hydrology.water.Pond;
import art.arcane.iris.generation.hydrology.water.PondMask;
@@ -14,7 +12,6 @@ import art.arcane.iris.generation.hydrology.water.Reach;
import art.arcane.iris.generation.hydrology.water.ReachStyle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
@@ -31,8 +28,6 @@ final class ChunkFeatures {
private final List<Reach> reaches;
private final List<Pond> ponds;
private final List<Pond> lakes;
private final List<SeaInlet> inlets;
private final int[] inletBoxes;
private final int[] lakeBoxes;
private final ReachSegments segments = new ReachSegments(SEGMENT_CAPACITY);
private final ReachGeometry.Lookup brinks;
@@ -41,14 +36,11 @@ final class ChunkFeatures {
private final MaskEdges lakeReach = new MaskEdges(MaskEdges.Kind.GROWN_WATER);
private boolean inert;
private ChunkFeatures(HydrologySettings settings, List<Reach> reaches, Map<Reach, Reach> plans, List<Pond> ponds, List<Pond> lakes,
List<SeaInlet> inlets, int[] inletBoxes) {
private ChunkFeatures(HydrologySettings settings, List<Reach> reaches, Map<Reach, Reach> plans, List<Pond> ponds, List<Pond> lakes) {
this.brinks = new ReachGeometry.Lookup(settings.seed(), settings.seaLevel(), plans);
this.reaches = reaches;
this.ponds = ponds;
this.lakes = lakes;
this.inlets = inlets;
this.inletBoxes = inletBoxes;
this.lakeBoxes = new int[4 * lakes.size()];
}
@@ -58,19 +50,7 @@ final class ChunkFeatures {
List<Reach> reaches = new ArrayList<>();
Map<Reach, Reach> plans = new IdentityHashMap<>();
List<Pond> ponds = new ArrayList<>();
List<SeaInlet> inlets = new ArrayList<>();
int[] inletBoxes = new int[0];
for (IndexedWindow window : windows) {
for (SeaInlet inlet : window.plan().inlets()) {
int[] bounds = SeaInletRasterizer.bounds(inlet);
int padding = RiffleProfile.RADIUS + 1;
if (bounds[0] <= chunkX * CHUNK + CHUNK - 1 + padding && bounds[2] >= chunkX * CHUNK - padding
&& bounds[1] <= chunkZ * CHUNK + CHUNK - 1 + padding && bounds[3] >= chunkZ * CHUNK - padding) {
inletBoxes = Arrays.copyOf(inletBoxes, inletBoxes.length + 4);
System.arraycopy(bounds, 0, inletBoxes, 4 * inlets.size(), 4);
inlets.add(inlet);
}
}
int before = reaches.size();
window.index().candidates(chunkX, chunkZ, halo, reaches, ponds);
for (int index = before; index < reaches.size(); index++) {
@@ -81,7 +61,7 @@ final class ChunkFeatures {
}
}
List<Pond> lakes = lakes(chunkX, chunkZ, halo, lakeRegionPlans, lakeRegions);
ChunkFeatures features = new ChunkFeatures(settings, reaches, plans, ponds, lakes, inlets, inletBoxes);
ChunkFeatures features = new ChunkFeatures(settings, reaches, plans, ponds, lakes);
features.index(settings, chunkX, chunkZ);
return features;
}
@@ -90,20 +70,6 @@ final class ChunkFeatures {
return inert;
}
SeaInlet openInletAt(int x, int z, int[] column) {
for (int index = 0; index < inlets.size(); index++) {
int box = 4 * index;
if (x < inletBoxes[box] || z < inletBoxes[box + 1] || x > inletBoxes[box + 2] || z > inletBoxes[box + 3]) {
continue;
}
SeaInlet inlet = inlets.get(index);
if (SeaInletRasterizer.column(inlet, x, z, column) && column[1] == SeaInlet.OPEN) {
return inlet;
}
}
return null;
}
ReachGeometry.Lookup brinks() {
return brinks;
}
@@ -123,11 +89,6 @@ final class ChunkFeatures {
return false;
}
}
for (SeaInlet inlet : inlets) {
if (WaterHeads.standing(inlet.waterLevel(), seaLevel) != head) {
return false;
}
}
return segments.hasOnlyLevel(head, seaLevel);
}
@@ -220,20 +181,11 @@ final class ChunkFeatures {
lakeReach.collect(mask, minX - shoreReach, minZ - shoreReach, maxX + shoreReach, maxZ + shoreReach);
System.arraycopy(grownBox(mask), 0, lakeBoxes, 4 * index, 4);
}
inert = segments.isEmpty() && !inletsTouch(minX - 1, minZ - 1, maxX + 1, maxZ + 1)
inert = segments.isEmpty()
&& !pondsTouch(minX - 1 - reach, minZ - 1 - reach, maxX + 1 + reach, maxZ + 1 + reach)
&& !lakesTouch(minX - 2 - shoreReach, minZ - 2 - shoreReach, maxX + 2 + shoreReach, maxZ + 2 + shoreReach);
}
private boolean inletsTouch(int minX, int minZ, int maxX, int maxZ) {
for (int box = 0; box < inletBoxes.length; box += 4) {
if (inletBoxes[box] <= maxX && inletBoxes[box + 2] >= minX && inletBoxes[box + 1] <= maxZ && inletBoxes[box + 3] >= minZ) {
return true;
}
}
return false;
}
private boolean pondsTouch(int minX, int minZ, int maxX, int maxZ) {
for (Pond pond : ponds) {
PondMask mask = pond.mask();
@@ -20,7 +20,7 @@ public final class ChunkRasterizer {
public ChunkRasterizer(HydrologySettings settings, ChannelFluids channelFluids) {
this.settings = Objects.requireNonNull(settings, "settings");
this.channelFluids = Objects.requireNonNull(channelFluids, "channelFluids");
float widest = 0f;
float widest = settings.underground().seaInlets().mouthHalfWidth().max();
for (HydrologyTier tier : settings.tiers()) {
widest = Math.max(widest, tier.maxHalfWidth());
}
@@ -3,7 +3,6 @@ package art.arcane.iris.generation.hydrology.raster;
import art.arcane.iris.generation.hydrology.config.IrisBankStyle;
import art.arcane.iris.generation.hydrology.cave.HydrologyCaveCell;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.water.HydrologyTier;
import art.arcane.iris.generation.hydrology.water.Pond;
import art.arcane.iris.generation.hydrology.water.Reach;
@@ -44,7 +43,7 @@ final class RasterComposer {
private final HydrologyTier[] nearTier = new HydrologyTier[CELLS];
private final ReachGeometry.Lookup brinks;
private final ReachCursor cursor;
private final int[] inletColumn = new int[2];
private final ReachCursor.Choice other = new ReachCursor.Choice();
private final Map<Long, String> reachFluids = new HashMap<>();
private NaturalHeights naturalHeight;
@@ -89,15 +88,6 @@ final class RasterComposer {
int x = originX + cell % GRID;
int z = originZ + cell / GRID;
int ground = natural[cell];
SeaInlet inlet = features.openInletAt(x, z, inletColumn);
if (inlet != null) {
head[cell] = WaterHeads.standing(inlet.waterLevel(), settings.seaLevel());
terrain[cell] = Math.min(Math.min(ground, inletColumn[0]), head[cell] - 1);
role[cell] = WaterRole.INLET;
feature[cell] = inlet.id();
fluid[cell] = HydrologyCaveCell.SEA_FLUID;
return;
}
int lake = features.lakeAt(x, z, ground);
int pondIndex = lake >= 0 ? -1 : features.pondAt(x, z);
boolean shore = interior(cell) && lake < 0 && pondIndex < 0;
@@ -149,7 +139,7 @@ final class RasterComposer {
role[cell] = role(reach.style()[point]);
feature[cell] = reach.id();
tier[cell] = reach.tier();
fluid[cell] = role[cell] == WaterRole.MOUTH ? HydrologyCaveCell.SEA_FLUID : reachFluid(reach);
fluid[cell] = role[cell] == WaterRole.MOUTH || role[cell] == WaterRole.INLET ? HydrologyCaveCell.SEA_FLUID : reachFluid(reach);
}
private String reachFluid(Reach reach) {
@@ -176,25 +166,6 @@ final class RasterComposer {
}
private void dry(int cell, int x, int z, int ground, double variation) {
int cut = ground;
int raise = Integer.MIN_VALUE;
double bankEdge = Double.POSITIVE_INFINITY;
ReachCursor.Choice bank = cursor.bank;
if (bank.reach != null) {
HydrologyTier bankTier = bank.reach.tier();
int surface = brinks.head(bank);
bankEdge = bank.distance - bank.halfWidth();
double u = bankEdge / bankTier.bankBand();
if (bankTier.bankStyle() != IrisBankStyle.CLIFF && bankTier.bankStyle() != IrisBankStyle.TERRACED) {
u = BedProfile.position(u, -variation);
}
if (ground >= surface) {
double cone = coneSlope(steepestToWater(x, z, bank, bankEdge)) * u * bankTier.bankBand();
cut = BankProfile.cut(bankTier.bankStyle(), surface, ground, u, cone, noise(x, z));
} else if (ground >= settings.seaLevel()) {
raise = BankProfile.levee(bankTier.bankStyle(), surface, ground, u, noise(x, z), settings.deformation().maxFill());
}
}
int nearPond = -1;
double pondEdge = Double.POSITIVE_INFINITY;
for (int index = 0; index < features.ponds(); index++) {
@@ -204,6 +175,29 @@ final class RasterComposer {
nearPond = index;
}
}
int cut = ground;
int raise = Integer.MIN_VALUE;
double bankEdge = Double.POSITIVE_INFINITY;
ReachCursor.Choice bank = cursor.bank;
if (bank.reach != null) {
bankEdge = bank.distance - bank.halfWidth();
if (bank.reach.style()[0] == ReachStyle.TIDAL) {
cut = tidalBank(bank, x, z, ground, variation, bankEdge, pondEdge);
} else {
HydrologyTier bankTier = bank.reach.tier();
int surface = brinks.head(bank);
double u = bankEdge / bankTier.bankBand();
if (bankTier.bankStyle() != IrisBankStyle.CLIFF && bankTier.bankStyle() != IrisBankStyle.TERRACED) {
u = BedProfile.position(u, -variation);
}
if (ground >= surface) {
double cone = coneSlope(steepestToWater(x, z, bank, bankEdge)) * u * bankTier.bankBand();
cut = BankProfile.cut(bankTier.bankStyle(), surface, ground, u, cone, noise(x, z));
} else if (ground >= settings.seaLevel()) {
raise = BankProfile.levee(bankTier.bankStyle(), surface, ground, u, noise(x, z), settings.deformation().maxFill());
}
}
}
int taper = settings.ponds().shore().taper();
boolean tapered = nearPond >= 0 && pondEdge <= taper;
if (tapered && ground > WaterHeads.standing(features.pond(nearPond).level(), settings.seaLevel())) {
@@ -218,6 +212,47 @@ final class RasterComposer {
nearestWater(cell, nearPond, pondEdge);
}
private int tidalBank(ReachCursor.Choice bank, int x, int z, int ground, double variation, double bankEdge, double pondEdge) {
HydrologyTier tidal = bank.reach.tier();
int surface = brinks.head(bank);
if (ground < surface) {
return ground;
}
double band = tidal.bankBand();
features.segments().nearestOther(x, z, bank.reach.id(), band, other);
double otherEdge = other.reach == null ? Double.POSITIVE_INFINITY : other.distance - other.halfWidth();
int meet = ground;
if (other.reach != null && otherEdge <= other.reach.tier().bankBand()) {
meet = Math.min(meet, otherBank(x, z, ground, variation, otherEdge));
}
double nearest = Math.min(otherEdge, pondEdge);
double reach = nearest == Double.POSITIVE_INFINITY ? band : Math.min(band, 0.5D * (bankEdge + nearest));
if (bankEdge >= reach) {
return Math.max(surface, meet);
}
double u = bankEdge / reach;
if (tidal.bankStyle() != IrisBankStyle.CLIFF && tidal.bankStyle() != IrisBankStyle.TERRACED) {
u = BedProfile.position(u, -variation);
}
double cone = settings.deformation().bankSlope() * u * reach;
return Math.min(ground, BankProfile.cut(tidal.bankStyle(), surface, Math.max(surface, meet), u, cone, noise(x, z)));
}
private int otherBank(int x, int z, int ground, double variation, double otherEdge) {
HydrologyTier otherTier = other.reach.tier();
int surface = brinks.head(other);
double u = otherEdge / otherTier.bankBand();
if (otherTier.bankStyle() != IrisBankStyle.CLIFF && otherTier.bankStyle() != IrisBankStyle.TERRACED) {
u = BedProfile.position(u, -variation);
}
if (ground < surface) {
return ground;
}
boolean tidal = other.reach.style()[0] == ReachStyle.TIDAL;
double slope = tidal ? settings.deformation().bankSlope() : coneSlope(steepestToWater(x, z, other, otherEdge));
return BankProfile.cut(otherTier.bankStyle(), surface, ground, u, slope * u * otherTier.bankBand(), noise(x, z));
}
private void nearestWater(int cell, int nearPond, double pondEdge) {
double best = Double.POSITIVE_INFINITY;
if (cursor.edge.reach != null) {
@@ -334,11 +369,6 @@ final class RasterComposer {
sample.set(head[cell], feature[cell], role[cell]);
return;
}
SeaInlet inlet = features.openInletAt(x, z, inletColumn);
if (inlet != null) {
sample.set(WaterHeads.standing(inlet.waterLevel(), settings.seaLevel()), inlet.id(), WaterRole.INLET);
return;
}
int lake = features.lakeCovers(x, z) ? features.lakeAt(x, z, naturalAt(x, z)) : -1;
if (lake >= 0) {
sample.set(WaterHeads.standing(features.lake(lake).level(), settings.seaLevel()), features.lake(lake).id(), WaterRole.POND);
@@ -524,6 +554,7 @@ final class RasterComposer {
case CASCADE -> WaterRole.CASCADE;
case WATERFALL -> WaterRole.WATERFALL;
case MOUTH -> WaterRole.MOUTH;
case TIDAL -> WaterRole.INLET;
case RUN, RIFFLE, POND_OUTLET -> WaterRole.CHANNEL;
};
}
@@ -141,6 +141,33 @@ final class ReachSegments {
cursor.resolveChannel();
}
void nearestOther(double x, double z, long excluded, double reach, ReachCursor.Choice out) {
if (!sealed) {
seal();
}
out.reset();
double best = Double.POSITIVE_INFINITY;
for (int index = 0; index < size; index++) {
if (reaches[index].id() == excluded || beyond(x, z, Math.min(startX[index], endX[index]), Math.min(startZ[index], endZ[index]),
Math.max(startX[index], endX[index]), Math.max(startZ[index], endZ[index]), radius[index] + reach)) {
continue;
}
double ax = startX[index];
double az = startZ[index];
double dx = endX[index] - ax;
double dz = endZ[index] - az;
double length = dx * dx + dz * dz;
double t = length == 0D ? 0D : Math.clamp(((x - ax) * dx + (z - az) * dz) / length, 0D, 1D);
double distance = Math.hypot(x - (ax + t * dx), z - (az + t * dz));
double edge = distance - (startWidth[index] + t * (endWidth[index] - startWidth[index]));
if (edge < best && edge <= reach) {
best = edge;
out.reset();
out.offer(reaches[index], segments[index], index, t, distance);
}
}
}
private int coveredCell(double x, double z) {
if (coverStarts == null) {
return -1;
@@ -1,61 +0,0 @@
package art.arcane.iris.generation.hydrology.underground;
import java.util.Arrays;
public record SeaInlet(long id, float[] xs, float[] zs, float[] halfWidth, int waterLevel, int[] floor, int[] ceiling, int chamberX,
int chamberZ, int chamberRadius) {
public static final int OPEN = Integer.MAX_VALUE;
public SeaInlet {
int stations = xs.length;
if (stations < 2 || zs.length != stations || halfWidth.length != stations || floor.length != stations || ceiling.length != stations) {
throw new IllegalArgumentException("Sea inlet " + id + " needs at least two stations and matching arrays: xs=" + xs.length
+ " zs=" + zs.length + " halfWidth=" + halfWidth.length + " floor=" + floor.length + " ceiling=" + ceiling.length);
}
if (chamberRadius <= 0) {
throw new IllegalArgumentException("Sea inlet " + id + " needs a positive chamber radius, got " + chamberRadius);
}
for (int station = 0; station < stations; station++) {
if (!(halfWidth[station] > 0f) || floor[station] >= waterLevel || ceiling[station] < waterLevel) {
throw new IllegalArgumentException("Sea inlet " + id + " station " + station + " has half-width " + halfWidth[station]
+ ", floor " + floor[station] + " and ceiling " + ceiling[station] + " around water level " + waterLevel);
}
}
}
public int stations() {
return xs.length;
}
public boolean open(int station) {
return ceiling[station] == OPEN;
}
@Override
public boolean equals(Object other) {
return other instanceof SeaInlet inlet && id == inlet.id && waterLevel == inlet.waterLevel && chamberX == inlet.chamberX
&& chamberZ == inlet.chamberZ && chamberRadius == inlet.chamberRadius && Arrays.equals(xs, inlet.xs)
&& Arrays.equals(zs, inlet.zs) && Arrays.equals(halfWidth, inlet.halfWidth) && Arrays.equals(floor, inlet.floor)
&& Arrays.equals(ceiling, inlet.ceiling);
}
@Override
public int hashCode() {
int hash = 31 * Long.hashCode(id) + waterLevel;
hash = 31 * hash + chamberX;
hash = 31 * hash + chamberZ;
hash = 31 * hash + chamberRadius;
hash = 31 * hash + Arrays.hashCode(xs);
hash = 31 * hash + Arrays.hashCode(zs);
hash = 31 * hash + Arrays.hashCode(halfWidth);
hash = 31 * hash + Arrays.hashCode(floor);
return 31 * hash + Arrays.hashCode(ceiling);
}
@Override
public String toString() {
int last = xs.length - 1;
return "SeaInlet[id=" + id + ", stations=" + xs.length + ", mouth=" + xs[0] + "," + zs[0] + ", end=" + xs[last] + "," + zs[last]
+ ", waterLevel=" + waterLevel + ", chamber=" + chamberX + "," + chamberZ + " r" + chamberRadius + "]";
}
}
@@ -1,72 +0,0 @@
package art.arcane.iris.generation.hydrology.underground;
final class SeaInletFootprint {
private static final byte OPEN = 1;
private static final byte COVERED = 2;
private static final int SHELL = SeaInletRasterizer.SHELL;
private final int minX;
private final int minZ;
private final int maxX;
private final int maxZ;
private final byte[] kinds;
private SeaInletFootprint(SeaInlet inlet) {
int[] bounds = SeaInletRasterizer.bounds(inlet);
this.minX = bounds[0];
this.minZ = bounds[1];
this.maxX = bounds[2];
this.maxZ = bounds[3];
this.kinds = new byte[(maxX - minX + 1) * (maxZ - minZ + 1)];
int[] column = new int[2];
for (int z = minZ; z <= maxZ; z++) {
for (int x = minX; x <= maxX; x++) {
if (SeaInletRasterizer.column(inlet, x, z, column)) {
kinds[index(x, z)] = column[1] == SeaInlet.OPEN ? OPEN : COVERED;
}
}
}
}
static SeaInletFootprint of(SeaInlet inlet) {
return new SeaInletFootprint(inlet);
}
boolean conflicts(SeaInletFootprint other) {
return opensBeside(this, other) || opensBeside(other, this);
}
private static boolean opensBeside(SeaInletFootprint open, SeaInletFootprint covered) {
int fromX = Math.max(open.minX, covered.minX - SHELL);
int toX = Math.min(open.maxX, covered.maxX + SHELL);
int fromZ = Math.max(open.minZ, covered.minZ - SHELL);
int toZ = Math.min(open.maxZ, covered.maxZ + SHELL);
for (int z = fromZ; z <= toZ; z++) {
for (int x = fromX; x <= toX; x++) {
if (open.kind(x, z) == OPEN && covered.coveredNear(x, z)) {
return true;
}
}
}
return false;
}
private boolean coveredNear(int x, int z) {
for (int dz = -SHELL; dz <= SHELL; dz++) {
for (int dx = -SHELL; dx <= SHELL; dx++) {
if (kind(x + dx, z + dz) == COVERED) {
return true;
}
}
}
return false;
}
private byte kind(int x, int z) {
return x < minX || x > maxX || z < minZ || z > maxZ ? 0 : kinds[index(x, z)];
}
private int index(int x, int z) {
return (z - minZ) * (maxX - minX + 1) + x - minX;
}
}
@@ -1,583 +0,0 @@
package art.arcane.iris.generation.hydrology.underground;
import art.arcane.iris.generation.hydrology.grid.CellHash;
import art.arcane.iris.generation.hydrology.grid.DemGrid;
import art.arcane.iris.generation.hydrology.grid.HydrologySampleBuffer;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.hydrology.plan.WindowKey;
import art.arcane.iris.generation.hydrology.plan.WindowPlanner;
import art.arcane.iris.generation.hydrology.water.Pond;
import art.arcane.iris.generation.hydrology.water.PondMask;
import art.arcane.iris.generation.hydrology.water.Reach;
import art.arcane.iris.generation.hydrology.water.ShapedNetwork;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
public final class SeaInletPlanner {
private static final int ROOF_MARGIN = 2;
private static final int OPEN_LAND_STATIONS = 2;
private static final int STEP_LOOKUP_CELLS = 2;
private static final float NOISE_STEP = 32f;
private static final int CONTAINMENT = 2;
private static final float WET_SLACK = CONTAINMENT + 1 + 6f;
private static final int[] SIDE_I = {1, -1, 0, 0};
private static final int[] SIDE_J = {0, 0, 1, -1};
private static final long SALT_ID = 0x5345414e4c4554L;
private static final long SALT_SITE_X = 0x53454153495458L;
private static final long SALT_SITE_Z = 0x5345415349545aL;
private static final long SALT_LENGTH = 0x5345414c454e47L;
private static final long SALT_RADIUS = 0x53454152414449L;
private static final long SALT_HEADROOM = 0x53454148454144L;
private static final long SALT_DEPTH = 0x53454144455054L;
private static final long SALT_DENSITY = 0x53454144454e53L;
private static final double SQUARED_MARGIN = 1e-9D;
private final HydrologySettings settings;
public SeaInletPlanner(HydrologySettings settings) {
this.settings = Objects.requireNonNull(settings, "settings");
}
public static long lookupReach(int lengthMax, int chamberRadiusMax) {
int cell = WindowPlanner.CELL;
long farthestStation = cell * (long) Math.floor((lengthMax + cell * Math.sqrt(2D) - cell) / cell);
return farthestStation + (long) cell * Math.max(STEP_LOOKUP_CELLS, chamberRing(chamberRadiusMax, cell));
}
public List<SeaInlet> plan(WindowKey window, DemGrid raw, HydrologySampleBuffer samples, int[] receivers, float[] accumulation,
ShapedNetwork network, long seed) {
Objects.requireNonNull(window, "window");
HydrologySettings.SeaInlets config = settings.underground().seaInlets();
if (!config.enabled() || settings.density() == 0f) {
return List.of();
}
int count = raw.values().length;
if (samples.height().length < count || receivers.length != count || accumulation.length != count) {
throw new IllegalArgumentException("Sea inlet planning needs " + count + " cells, got samples=" + samples.height().length
+ " receivers=" + receivers.length + " accumulation=" + accumulation.length);
}
Terrain terrain = new Terrain(raw, samples, receivers, accumulation, cover(raw, samples.height(), network), seed);
List<Traced> traced = new ArrayList<>();
for (Map.Entry<Long, List<Integer>> site : sites(terrain, config).entrySet()) {
SeaInlet inlet = site(terrain, config, site.getKey(), site.getValue());
if (inlet == null) {
continue;
}
if (terrain.clipped && window.equals(owner(inlet))) {
throw new IllegalStateException("Sea inlet " + inlet.id() + " of window " + window
+ " reaches the edge of the window's planning span");
}
traced.add(new Traced(inlet, !terrain.clipped));
}
traced.sort(Comparator.comparingLong((Traced entry) -> entry.inlet().id()).thenComparingDouble(entry -> entry.inlet().xs()[0])
.thenComparingDouble(entry -> entry.inlet().zs()[0]));
return separated(traced);
}
private static List<SeaInlet> separated(List<Traced> traced) {
List<SeaInletFootprint> footprints = new ArrayList<>(traced.size());
for (Traced entry : traced) {
footprints.add(SeaInletFootprint.of(entry.inlet()));
}
List<SeaInlet> kept = new ArrayList<>(traced.size());
for (int index = 0; index < traced.size(); index++) {
boolean yields = false;
for (int earlier = 0; earlier < index && !yields; earlier++) {
yields = footprints.get(earlier).conflicts(footprints.get(index));
}
if (!yields && traced.get(index).whole()) {
kept.add(traced.get(index).inlet());
}
}
return List.copyOf(kept);
}
private Map<Long, List<Integer>> sites(Terrain terrain, HydrologySettings.SeaInlets config) {
Map<Long, List<Integer>> sites = new TreeMap<>();
DemGrid grid = terrain.grid;
float cliff = settings.seaLevel() + config.minimumCliffHeight();
for (int j = 1; j < grid.depth() - 1; j++) {
for (int i = 1; i < grid.width() - 1; i++) {
int cell = grid.index(i, j);
if (terrain.ocean(cell) || terrain.natural(cell) < cliff || mouth(terrain, cell) < 0) {
continue;
}
long key = siteKey(Math.floorDiv(grid.blockX(cell), config.spacing()), Math.floorDiv(grid.blockZ(cell), config.spacing()));
sites.computeIfAbsent(key, ignored -> new ArrayList<>()).add(cell);
}
}
return sites;
}
private SeaInlet site(Terrain terrain, HydrologySettings.SeaInlets config, long key, List<Integer> candidates) {
int siteX = (int) (key >> 32);
int siteZ = (int) key;
if (settings.density() < 1f && CellHash.unit(CellHash.mix(terrain.seed, SALT_DENSITY, siteX, siteZ)) >= settings.density()) {
return null;
}
double targetX = (siteX + CellHash.unit(CellHash.mix(terrain.seed, SALT_SITE_X, siteX, siteZ))) * config.spacing();
double targetZ = (siteZ + CellHash.unit(CellHash.mix(terrain.seed, SALT_SITE_Z, siteX, siteZ))) * config.spacing();
DemGrid grid = terrain.grid;
WindowKey owner = WindowKey.containing((int) Math.floor(targetX), (int) Math.floor(targetZ));
terrain.clipped = siteTouchesBorder(terrain, config, siteX, siteZ, owner);
List<Integer> ordered = new ArrayList<>(candidates.size());
for (int candidate : candidates) {
if (owner.equals(WindowKey.containing(grid.blockX(candidate), grid.blockZ(candidate)))) {
ordered.add(candidate);
}
}
ordered.sort(Comparator.comparingDouble((Integer cell) -> distanceSquared(grid, cell, targetX, targetZ)).thenComparingInt(cell -> cell));
for (int candidate : ordered) {
SeaInlet inlet = trace(terrain, config, candidate);
if (inlet != null) {
return inlet;
}
}
return null;
}
private SeaInlet trace(Terrain terrain, HydrologySettings.SeaInlets config, int land) {
DemGrid grid = terrain.grid;
int mouth = mouth(terrain, land);
if (!openable(terrain, mouth)) {
return null;
}
float target = lerp(config.length().min(), config.length().max(), unit(terrain, SALT_LENGTH, land));
List<Integer> path = new ArrayList<>();
List<Boolean> open = new ArrayList<>();
path.add(mouth);
open.add(true);
int current = land;
float length = 0f;
int openStations = 0;
boolean covered = false;
while (current >= 0 && length < target) {
if (canCover(terrain, config, current)) {
covered = true;
} else if (covered || openStations >= OPEN_LAND_STATIONS || !openable(terrain, current)) {
break;
} else {
openStations++;
}
length += step(grid, path.get(path.size() - 1), current);
path.add(current);
open.add(!covered);
int next = upstream(terrain, mouth, current, path);
current = next >= 0 ? next : inland(terrain, config, mouth, current, path);
}
while (covered && path.size() > 2 && !open.get(path.size() - 1)) {
if (pathLength(grid, path) < config.length().min()) {
return null;
}
SeaInlet inlet = build(terrain, config, path, open);
if (inlet != null) {
return inlet;
}
path.remove(path.size() - 1);
open.remove(open.size() - 1);
}
return null;
}
private SeaInlet build(Terrain terrain, HydrologySettings.SeaInlets config, List<Integer> path, List<Boolean> open) {
DemGrid grid = terrain.grid;
int stations = path.size();
int mouth = path.get(0);
int land = path.get(1);
int end = path.get(stations - 1);
int water = settings.seaLevel();
float chamberCapacity = Float.NaN;
int radius = 0;
int preferred = Math.round(lerp(config.chamberRadius().min(), config.chamberRadius().max(), unit(terrain, SALT_RADIUS, end)));
for (int candidate : new int[]{preferred, config.chamberRadius().min()}) {
float capacity = capacity(terrain, config, end, chamberRing(candidate, grid.cell()));
if (capacity - water >= config.headroom().min()) {
radius = candidate;
chamberCapacity = capacity;
break;
}
}
if (radius == 0) {
return null;
}
float[] capacity = new float[stations];
for (int station = 0; station < stations; station++) {
capacity[station] = open.get(station) ? Float.POSITIVE_INFINITY
: station == stations - 1 ? chamberCapacity : capacity(terrain, config, path.get(station), 1);
}
float total = pathLength(grid, path);
float[] xs = new float[stations];
float[] zs = new float[stations];
float[] halfWidth = new float[stations];
int[] floor = new int[stations];
int[] ceiling = new int[stations];
float travelled = 0f;
HydrologySettings.FloatRange widths = config.halfWidth();
for (int station = 0; station < stations; station++) {
int cell = path.get(station);
if (station > 0) {
travelled += step(grid, path.get(station - 1), cell);
}
xs[station] = grid.blockX(cell);
zs[station] = grid.blockZ(cell);
halfWidth[station] = widths.max() - (widths.max() - widths.min()) * (travelled / total);
floor[station] = water - Math.round(lerp(config.depth().min(), config.depth().max(), smooth(terrain, SALT_DEPTH, land, travelled)));
if (open.get(station)) {
ceiling[station] = SeaInlet.OPEN;
continue;
}
float room = capacity[station];
if (station > 0) {
room = Math.min(room, capacity[station - 1]);
}
if (station + 1 < stations) {
room = Math.min(room, capacity[station + 1]);
}
float headroom = lerp(config.headroom().min(), config.headroom().max(), smooth(terrain, SALT_HEADROOM, land, travelled));
ceiling[station] = water + (int) Math.floor(Math.min(headroom, room - water));
}
long id = CellHash.mix(CellHash.mix(terrain.seed, SALT_ID, grid.blockX(mouth), grid.blockZ(mouth)), SALT_ID, grid.blockX(land),
grid.blockZ(land));
return new SeaInlet(id, xs, zs, halfWidth, water, floor, ceiling, grid.blockX(end), grid.blockZ(end), radius);
}
private static double smooth(Terrain terrain, long salt, int land, float distance) {
float position = distance / NOISE_STEP;
int knot = (int) Math.floor(position);
double fraction = position - knot;
double eased = fraction * fraction * (3D - 2D * fraction);
long base = CellHash.mix(terrain.seed, salt, terrain.grid.blockX(land), terrain.grid.blockZ(land));
double from = CellHash.unit(CellHash.mix(base, salt, knot, 0));
double to = CellHash.unit(CellHash.mix(base, salt, knot + 1, 0));
return from + (to - from) * eased;
}
private boolean canCover(Terrain terrain, HydrologySettings.SeaInlets config, int cell) {
return capacity(terrain, config, cell, 1) - settings.seaLevel() >= config.headroom().min();
}
private static float capacity(Terrain terrain, HydrologySettings.SeaInlets config, int cell, int ring) {
DemGrid grid = terrain.grid;
int i = cell % grid.width();
int j = cell / grid.width();
float lowest = Float.POSITIVE_INFINITY;
boolean outside = false;
for (int dj = -ring; dj <= ring; dj++) {
for (int di = -ring; di <= ring; di++) {
int ni = i + di;
int nj = j + dj;
if (ni < 0 || nj < 0 || ni >= grid.width() || nj >= grid.depth()) {
outside = true;
continue;
}
int neighbour = grid.index(ni, nj);
if (terrain.ocean(neighbour)) {
return Float.NEGATIVE_INFINITY;
}
lowest = Math.min(lowest, terrain.cover[neighbour]);
}
}
if (outside) {
terrain.clipped = true;
return Float.NEGATIVE_INFINITY;
}
return lowest - config.roofClearance() - ROOF_MARGIN;
}
private static boolean openable(Terrain terrain, int cell) {
DemGrid grid = terrain.grid;
int i = cell % grid.width();
int j = cell / grid.width();
boolean outside = false;
for (int dj = -1; dj <= 1; dj++) {
for (int di = -1; di <= 1; di++) {
int ni = i + di;
int nj = j + dj;
if (ni < 0 || nj < 0 || ni >= grid.width() || nj >= grid.depth()) {
outside = true;
} else if (terrain.wet(grid.index(ni, nj))) {
return false;
}
}
}
terrain.clipped |= outside;
return !outside;
}
private static int mouth(Terrain terrain, int land) {
int receiver = terrain.receivers[land];
if (receiver >= 0 && terrain.ocean(receiver)) {
return receiver;
}
DemGrid grid = terrain.grid;
int i = land % grid.width();
int j = land / grid.width();
for (int side = 0; side < SIDE_I.length; side++) {
int ni = i + SIDE_I[side];
int nj = j + SIDE_J[side];
if (ni >= 0 && nj >= 0 && ni < grid.width() && nj < grid.depth() && terrain.ocean(grid.index(ni, nj))) {
return grid.index(ni, nj);
}
}
return -1;
}
private static int upstream(Terrain terrain, int mouth, int cell, List<Integer> path) {
DemGrid grid = terrain.grid;
int i = cell % grid.width();
int j = cell / grid.width();
double away = distanceSquared(grid, cell, grid.blockX(mouth), grid.blockZ(mouth));
int best = -1;
for (int dj = -1; dj <= 1; dj++) {
for (int di = -1; di <= 1; di++) {
int neighbour = onward(terrain, mouth, i + di, j + dj, away, path);
if (neighbour < 0 || terrain.receivers[neighbour] != cell) {
continue;
}
if (best < 0 || terrain.accumulation[neighbour] > terrain.accumulation[best]
|| terrain.accumulation[neighbour] == terrain.accumulation[best] && neighbour < best) {
best = neighbour;
}
}
}
return best;
}
private int inland(Terrain terrain, HydrologySettings.SeaInlets config, int mouth, int cell, List<Integer> path) {
DemGrid grid = terrain.grid;
int i = cell % grid.width();
int j = cell / grid.width();
double away = distanceSquared(grid, cell, grid.blockX(mouth), grid.blockZ(mouth));
int best = -1;
boolean bestCovers = false;
double bestAway = 0D;
for (int dj = -1; dj <= 1; dj++) {
for (int di = -1; di <= 1; di++) {
int neighbour = onward(terrain, mouth, i + di, j + dj, away, path);
if (neighbour < 0) {
continue;
}
double distance = distanceSquared(grid, neighbour, grid.blockX(mouth), grid.blockZ(mouth));
boolean covers = canCover(terrain, config, neighbour);
if (best < 0 || covers && !bestCovers || covers == bestCovers && (distance > bestAway
|| distance == bestAway && terrain.cover[neighbour] > terrain.cover[best])) {
best = neighbour;
bestCovers = covers;
bestAway = distance;
}
}
}
return best;
}
private Cover cover(DemGrid grid, float[] natural, ShapedNetwork network) {
int count = grid.values().length;
float[] cover = new float[count];
System.arraycopy(natural, 0, cover, 0, count);
boolean[] wet = new boolean[count];
for (Reach reach : network.reaches()) {
int band = reach.tier().bankBand() + CONTAINMENT + grid.cell();
for (int point = 0; point + 1 < reach.xs().length; point++) {
float bed = Math.min(reach.grade()[point] - reach.depth()[point], reach.grade()[point + 1] - reach.depth()[point + 1]) - 1f;
float water = Math.max(reach.halfWidth()[point], reach.halfWidth()[point + 1]);
splat(grid, cover, wet, reach.xs()[point], reach.zs()[point], reach.xs()[point + 1], reach.zs()[point + 1], water + band,
water + WET_SLACK, bed);
}
}
HydrologySettings.PondShore shore = settings.ponds().shore();
for (Pond pond : network.ponds()) {
PondMask mask = pond.mask();
float bed = Math.min(pond.floor(), pond.level() - shore.maxDepth()) - 1f;
float radius = 2f * mask.step() + shore.taper() + CONTAINMENT + grid.cell();
float water = 1.5f * mask.step() + WET_SLACK;
for (int nj = 0; nj < mask.depth(); nj++) {
for (int ni = 0; ni < mask.width(); ni++) {
if (mask.node(ni, nj)) {
float x = mask.originX() + ni * mask.step();
float z = mask.originZ() + nj * mask.step();
splat(grid, cover, wet, x, z, x, z, radius, water, bed);
}
}
}
}
return new Cover(cover, wet);
}
private static void splat(DemGrid grid, float[] cover, boolean[] wet, float ax, float az, float bx, float bz, float radius, float wetRadius,
float bed) {
int cell = grid.cell();
int minI = Math.max(0, (int) Math.floor((Math.min(ax, bx) - radius - grid.originX()) / cell));
int maxI = Math.min(grid.width() - 1, (int) Math.ceil((Math.max(ax, bx) + radius - grid.originX()) / cell));
int minJ = Math.max(0, (int) Math.floor((Math.min(az, bz) - radius - grid.originZ()) / cell));
int maxJ = Math.min(grid.depth() - 1, (int) Math.ceil((Math.max(az, bz) + radius - grid.originZ()) / cell));
double dx = bx - ax;
double dz = bz - az;
double span = dx * dx + dz * dz;
double outside = radius > 0f ? squaredAbove(radius) : Double.POSITIVE_INFINITY;
double inside = radius > 0f ? squaredBelow(radius) : Double.NEGATIVE_INFINITY;
double wetOutside = wetRadius > 0f ? squaredAbove(wetRadius) : Double.POSITIVE_INFINITY;
double wetInside = wetRadius > 0f ? squaredBelow(wetRadius) : Double.NEGATIVE_INFINITY;
for (int j = minJ; j <= maxJ; j++) {
double pz = grid.originZ() + (double) j * cell;
for (int i = minI; i <= maxI; i++) {
double px = grid.originX() + (double) i * cell;
double t = span <= 0D ? 0D : Math.clamp(((px - ax) * dx + (pz - az) * dz) / span, 0D, 1D);
double ex = px - (ax + t * dx);
double ez = pz - (az + t * dz);
double squared = ex * ex + ez * ez;
if (squared > outside || !(squared < inside) && Math.hypot(ex, ez) > radius) {
continue;
}
int index = j * grid.width() + i;
cover[index] = Math.min(cover[index], bed);
wet[index] |= squared < wetInside || !(squared > wetOutside) && Math.hypot(ex, ez) <= wetRadius;
}
}
}
private static int onward(Terrain terrain, int mouth, int ni, int nj, double away, List<Integer> path) {
DemGrid grid = terrain.grid;
if (ni < 0 || nj < 0 || ni >= grid.width() || nj >= grid.depth()) {
terrain.clipped = true;
return -1;
}
int neighbour = grid.index(ni, nj);
if (terrain.ocean(neighbour) || path.contains(neighbour)
|| distanceSquared(grid, neighbour, grid.blockX(mouth), grid.blockZ(mouth)) <= away) {
return -1;
}
if (ni == 0 || nj == 0 || ni == grid.width() - 1 || nj == grid.depth() - 1) {
terrain.clipped = true;
return -1;
}
return neighbour;
}
private boolean siteTouchesBorder(Terrain terrain, HydrologySettings.SeaInlets config, int siteX, int siteZ, WindowKey owner) {
DemGrid grid = terrain.grid;
CellRange columns = siteCells(siteX, config.spacing(), owner.wx(), grid.originX(), grid.cell());
CellRange rows = siteCells(siteZ, config.spacing(), owner.wz(), grid.originZ(), grid.cell());
int lastColumn = grid.width() - 1;
int lastRow = grid.depth() - 1;
if (columns.first() < 0L || rows.first() < 0L || columns.last() > lastColumn || rows.last() > lastRow) {
return true;
}
float cliff = settings.seaLevel() + config.minimumCliffHeight();
for (int i = (int) columns.first(); i <= columns.last(); i++) {
if (rows.first() == 0L && cliffLand(terrain, i, 0, cliff) || rows.last() == lastRow && cliffLand(terrain, i, lastRow, cliff)) {
return true;
}
}
for (int j = (int) rows.first(); j <= rows.last(); j++) {
if (columns.first() == 0L && cliffLand(terrain, 0, j, cliff)
|| columns.last() == lastColumn && cliffLand(terrain, lastColumn, j, cliff)) {
return true;
}
}
return false;
}
private static CellRange siteCells(int site, int spacing, int window, int origin, int cell) {
long from = Math.max((long) site * spacing, (long) window * WindowKey.SIZE);
long to = Math.min(((long) site + 1L) * spacing, ((long) window + 1L) * WindowKey.SIZE);
return new CellRange(Math.ceilDiv(from - origin, cell), Math.ceilDiv(to - origin, cell) - 1L);
}
private static boolean cliffLand(Terrain terrain, int i, int j, float cliff) {
int cell = terrain.grid.index(i, j);
return !terrain.ocean(cell) && terrain.natural(cell) >= cliff;
}
private static int chamberRing(int radius, int cell) {
return (radius + cell - 1) / cell + 1;
}
private static WindowKey owner(SeaInlet inlet) {
return WindowKey.containing((int) Math.floor(inlet.xs()[1]), (int) Math.floor(inlet.zs()[1]));
}
private static double squaredAbove(float radius) {
return (double) radius * radius * (1D + SQUARED_MARGIN);
}
private static double squaredBelow(float radius) {
return (double) radius * radius * (1D - SQUARED_MARGIN);
}
private static float pathLength(DemGrid grid, List<Integer> path) {
float length = 0f;
for (int station = 1; station < path.size(); station++) {
length += step(grid, path.get(station - 1), path.get(station));
}
return length;
}
private static float step(DemGrid grid, int from, int to) {
return (float) Math.hypot(grid.blockX(to) - grid.blockX(from), grid.blockZ(to) - grid.blockZ(from));
}
private static double distanceSquared(DemGrid grid, int cell, double x, double z) {
double dx = grid.blockX(cell) - x;
double dz = grid.blockZ(cell) - z;
return dx * dx + dz * dz;
}
private static double unit(Terrain terrain, long salt, int cell) {
return CellHash.unit(CellHash.mix(terrain.seed, salt, terrain.grid.blockX(cell), terrain.grid.blockZ(cell)));
}
private static float lerp(float min, float max, double unit) {
return (float) (min + (max - min) * unit);
}
private static long siteKey(int siteX, int siteZ) {
return ((long) siteX << 32) | (siteZ & 0xFFFFFFFFL);
}
private record Cover(float[] cover, boolean[] wet) {
}
private record Traced(SeaInlet inlet, boolean whole) {
}
private record CellRange(long first, long last) {
}
private static final class Terrain {
private final DemGrid grid;
private final HydrologySampleBuffer samples;
private final int[] receivers;
private final float[] accumulation;
private final float[] cover;
private final boolean[] wet;
private final long seed;
private boolean clipped;
private Terrain(DemGrid grid, HydrologySampleBuffer samples, int[] receivers, float[] accumulation, Cover cover, long seed) {
this.grid = grid;
this.samples = samples;
this.receivers = receivers;
this.accumulation = accumulation;
this.cover = cover.cover();
this.wet = cover.wet();
this.seed = seed;
}
private boolean ocean(int cell) {
return samples.ocean()[cell];
}
private float natural(int cell) {
return samples.height()[cell];
}
private boolean wet(int cell) {
return wet[cell];
}
}
}
@@ -1,232 +0,0 @@
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.mantle.MantleWriter;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import java.util.Arrays;
public final class SeaInletRasterizer {
public static final int SHELL = 2;
private static final int CHUNK = 16;
private static final int GRID = CHUNK + 2 * SHELL;
static final int NONE = Integer.MIN_VALUE;
public void write(SeaInlet inlet, int chunkX, int chunkZ, MantleWriter writer, String fluid, SubterrainFluid subterrain,
HistoricalChunks historical) {
if (!touches(inlet, chunkX, chunkZ)) {
return;
}
int[] floors = new int[GRID * GRID];
int[] ceilings = new int[GRID * GRID];
if (!shape(inlet, (chunkX << 4) - SHELL, (chunkZ << 4) - SHELL, GRID, floors, ceilings)) {
return;
}
HydrologyCaveCell wet = new HydrologyCaveCell(HydrologyCaveAction.WET_SOURCE, fluid);
HydrologyCaveCell dry = new HydrologyCaveCell(HydrologyCaveAction.DRY_AIR, fluid);
HydrologyCaveCell guard = new HydrologyCaveCell(HydrologyCaveAction.SEAL_GUARD, fluid);
int water = inlet.waterLevel();
boolean[] historicalAround = historicalAround(chunkX, chunkZ, historical);
for (int lz = 0; lz < CHUNK; lz++) {
for (int lx = 0; lx < CHUNK; lx++) {
int cell = (lz + SHELL) * GRID + lx + SHELL;
int x = (chunkX << 4) + lx;
int z = (chunkZ << 4) + lz;
int low = nearby(floors, GRID, cell, true);
if (low == NONE) {
continue;
}
int floor = floors[cell];
if (floor == NONE) {
guard(writer, x, low - SHELL, water, z, guard);
} else if (ceilings[cell] == SeaInlet.OPEN) {
guard(writer, x, low - SHELL, floor - 1, z, guard);
} else if (historicalAround != null && besideHistorical(historicalAround, lx, lz)) {
guard(writer, x, low - SHELL, ceilings[cell], z, guard);
} else {
for (int y = floor + 1; y <= water; y++) {
writer.setData(x, y, z, wet);
writer.clearData(x, y, z, NativeBlockState.class);
}
for (int y = water + 1; y <= ceilings[cell]; y++) {
writer.setData(x, y, z, dry);
}
guard(writer, x, low - SHELL, floor, z, guard);
}
int roof = nearbyRoof(ceilings, cell, water);
for (int y = water + 1; y <= roof + SHELL; y++) {
if (subterrain.at(x, y, z)) {
guard(writer, x, y, y, z, guard);
}
}
}
}
}
public interface SubterrainFluid {
SubterrainFluid NOWHERE = (x, y, z) -> false;
boolean at(int x, int y, int z);
}
public interface HistoricalChunks {
HistoricalChunks NONE = (chunkX, chunkZ) -> false;
boolean at(int chunkX, int chunkZ);
}
public static boolean touches(SeaInlet inlet, int chunkX, int chunkZ) {
int[] bounds = bounds(inlet);
int minX = chunkX << 4;
int minZ = chunkZ << 4;
return bounds[0] <= minX + CHUNK - 1 + SHELL && bounds[2] >= minX - SHELL && bounds[1] <= minZ + CHUNK - 1 + SHELL
&& bounds[3] >= minZ - SHELL;
}
public static int[] bounds(SeaInlet inlet) {
float minX = inlet.chamberX() - inlet.chamberRadius();
float minZ = inlet.chamberZ() - inlet.chamberRadius();
float maxX = inlet.chamberX() + inlet.chamberRadius() + 1;
float maxZ = inlet.chamberZ() + inlet.chamberRadius() + 1;
for (int station = 0; station < inlet.stations(); station++) {
float reach = inlet.halfWidth()[station] + 1f;
minX = Math.min(minX, inlet.xs()[station] - reach);
minZ = Math.min(minZ, inlet.zs()[station] - reach);
maxX = Math.max(maxX, inlet.xs()[station] + reach);
maxZ = Math.max(maxZ, inlet.zs()[station] + reach);
}
return new int[]{(int) Math.floor(minX), (int) Math.floor(minZ), (int) Math.ceil(maxX), (int) Math.ceil(maxZ)};
}
public static boolean column(SeaInlet inlet, int x, int z, int[] out) {
double px = x + 0.5D;
double pz = z + 0.5D;
int floor = Integer.MAX_VALUE;
int ceiling = NONE;
float[] xs = inlet.xs();
float[] zs = inlet.zs();
for (int station = 0; station + 1 < xs.length; station++) {
double ax = xs[station];
double az = zs[station];
double dx = xs[station + 1] - ax;
double dz = zs[station + 1] - az;
double span = dx * dx + dz * dz;
double t = span <= 0D ? 0D : Math.clamp(((px - ax) * dx + (pz - az) * dz) / span, 0D, 1D);
double distance = Math.hypot(px - (ax + t * dx), pz - (az + t * dz));
double half = inlet.halfWidth()[station] + t * (inlet.halfWidth()[station + 1] - inlet.halfWidth()[station]);
if (distance > half) {
continue;
}
floor = Math.min(floor, (int) Math.round(inlet.floor()[station] + t * (inlet.floor()[station + 1] - inlet.floor()[station])));
ceiling = Math.max(ceiling, ceiling(inlet, station, t));
}
double radius = inlet.chamberRadius();
double fromCentre = Math.hypot(px - inlet.chamberX(), pz - inlet.chamberZ());
if (fromCentre <= radius) {
int last = xs.length - 1;
double dome = Math.sqrt(1D - (fromCentre / radius) * (fromCentre / radius));
int water = inlet.waterLevel();
floor = Math.min(floor, water - (int) Math.max(1L, Math.round((water - inlet.floor()[last]) * dome)));
ceiling = Math.max(ceiling, water + (int) Math.round((inlet.ceiling()[last] - water) * dome));
}
if (ceiling == NONE) {
return false;
}
out[0] = floor;
out[1] = ceiling;
return true;
}
private static int ceiling(SeaInlet inlet, int station, double t) {
if (inlet.open(station) || inlet.open(station + 1)) {
return t <= 0.5D ? inlet.ceiling()[station] : inlet.ceiling()[station + 1];
}
return (int) Math.round(inlet.ceiling()[station] + t * (inlet.ceiling()[station + 1] - inlet.ceiling()[station]));
}
static boolean shape(SeaInlet inlet, int originX, int originZ, int size, int[] floors, int[] ceilings) {
Arrays.fill(floors, NONE);
Arrays.fill(ceilings, NONE);
boolean any = false;
int[] column = new int[2];
for (int gz = 0; gz < size; gz++) {
for (int gx = 0; gx < size; gx++) {
if (column(inlet, originX + gx, originZ + gz, column)) {
floors[gz * size + gx] = column[0];
ceilings[gz * size + gx] = column[1];
any = true;
}
}
}
return any;
}
static int nearby(int[] values, int size, int cell, boolean lowest) {
int found = NONE;
int gx = cell % size;
int gz = cell / size;
for (int dz = -SHELL; dz <= SHELL; dz++) {
for (int dx = -SHELL; dx <= SHELL; dx++) {
int value = values[(gz + dz) * size + gx + dx];
if (value != NONE && (found == NONE || (lowest ? value < found : value > found))) {
found = value;
}
}
}
return found;
}
private static int nearbyRoof(int[] ceilings, int cell, int water) {
int roof = water - SHELL;
int gx = cell % GRID;
int gz = cell / GRID;
for (int dz = -SHELL; dz <= SHELL; dz++) {
for (int dx = -SHELL; dx <= SHELL; dx++) {
int ceiling = ceilings[(gz + dz) * GRID + gx + dx];
if (ceiling != SeaInlet.OPEN && ceiling > water && ceiling > roof) {
roof = ceiling;
}
}
}
return roof;
}
private static boolean[] historicalAround(int chunkX, int chunkZ, HistoricalChunks historical) {
boolean[] around = null;
for (int dz = -1; dz <= 1; dz++) {
for (int dx = -1; dx <= 1; dx++) {
if ((dx != 0 || dz != 0) && historical.at(chunkX + dx, chunkZ + dz)) {
if (around == null) {
around = new boolean[9];
}
around[(dz + 1) * 3 + dx + 1] = true;
}
}
}
return around;
}
private static boolean besideHistorical(boolean[] historicalAround, int lx, int lz) {
int fromX = lx < SHELL ? -1 : 0;
int toX = lx >= CHUNK - SHELL ? 1 : 0;
int fromZ = lz < SHELL ? -1 : 0;
int toZ = lz >= CHUNK - SHELL ? 1 : 0;
for (int dz = fromZ; dz <= toZ; dz++) {
for (int dx = fromX; dx <= toX; dx++) {
if (historicalAround[(dz + 1) * 3 + dx + 1]) {
return true;
}
}
}
return false;
}
private static void guard(MantleWriter writer, int x, int fromY, int toY, int z, HydrologyCaveCell guard) {
for (int y = fromY; y <= toY; y++) {
if (writer.getDataIfPresent(x, y, z, HydrologyCaveCell.class) == null) {
writer.setData(x, y, z, guard);
}
}
}
}
@@ -1,63 +0,0 @@
package art.arcane.iris.generation.hydrology.underground;
import java.util.Arrays;
import java.util.Collection;
public final class SeaInletSpace {
private static final int SHELL = SeaInletRasterizer.SHELL;
private static final int NONE = SeaInletRasterizer.NONE;
private final int originX;
private final int originZ;
private final int size;
private final int[] lows;
private final int[] highs;
private SeaInletSpace(int originX, int originZ, int size, int[] lows, int[] highs) {
this.originX = originX;
this.originZ = originZ;
this.size = size;
this.lows = lows;
this.highs = highs;
}
public static SeaInletSpace of(Collection<SeaInlet> inlets, int originX, int originZ, int size) {
int[] lows = new int[size * size];
int[] highs = new int[size * size];
Arrays.fill(lows, NONE);
Arrays.fill(highs, NONE);
int grid = size + 2 * SHELL;
int[] floors = new int[grid * grid];
int[] ceilings = new int[grid * grid];
for (SeaInlet inlet : inlets) {
if (!SeaInletRasterizer.shape(inlet, originX - SHELL, originZ - SHELL, grid, floors, ceilings)) {
continue;
}
for (int z = 0; z < size; z++) {
for (int x = 0; x < size; x++) {
int cell = (z + SHELL) * grid + x + SHELL;
int low = SeaInletRasterizer.nearby(floors, grid, cell, true);
if (low == NONE) {
continue;
}
int column = z * size + x;
int bottom = low - SHELL;
int top = Math.max(inlet.waterLevel(), SeaInletRasterizer.nearby(ceilings, grid, cell, false));
lows[column] = lows[column] == NONE ? bottom : Math.min(lows[column], bottom);
highs[column] = Math.max(highs[column], top);
}
}
}
return new SeaInletSpace(originX, originZ, size, lows, highs);
}
public boolean contains(int x, int y, int z) {
int localX = x - originX;
int localZ = z - originZ;
if (localX < 0 || localX >= size || localZ < 0 || localZ >= size) {
return false;
}
int column = localZ * size + localX;
return lows[column] != NONE && y >= lows[column] && y <= highs[column];
}
}
@@ -44,10 +44,14 @@ final class ReachFitter {
}
Fitted fit(DemGrid grid, int[] cells, float[] cellCatchment, HydrologyTier tier, long shapeSeed, boolean drainsToTheSea) {
return fit(grid, cells, cellCatchment, tier, shapeSeed, drainsToTheSea, tier.halfWidth(cellCatchment[cellCatchment.length - 1]), MEANDER_WIDTH_SCALE, true);
}
Fitted fit(DemGrid grid, int[] cells, float[] cellCatchment, HydrologyTier tier, long shapeSeed, boolean drainsToTheSea, float meanderWidth, double amplitudeScale, boolean dampOnSlopes) {
float halfWidth = tier.halfWidth(cellCatchment[cellCatchment.length - 1]);
Line line = relax(resample(grid, cells, cellCatchment));
Tangents tangents = tangents(line.xs(), line.zs());
meander(line, tangents, shapeSeed, halfWidth);
meander(line, tangents, shapeSeed, meanderWidth, amplitudeScale, dampOnSlopes);
int reach = Math.max(2, (int) Math.ceil(Math.max(VALLEY_SNAP, halfWidth + 2f) / SPACING));
Reads reads = read(line, tangents, reach);
Fitted fitted = place(line, tangents, reads, soften(viterbi(reads, line.xs().length, reach), reads, reach), tier);
@@ -159,7 +163,7 @@ final class ReachFitter {
return spaced;
}
private void meander(Line line, Tangents tangents, long shapeSeed, float halfWidth) {
private void meander(Line line, Tangents tangents, long shapeSeed, float halfWidth, double amplitudeScale, boolean dampOnSlopes) {
int count = line.xs().length;
if (count < 3) {
return;
@@ -168,11 +172,11 @@ final class ReachFitter {
for (int wave = 0; wave < phase.length; wave++) {
phase[wave] = 2D * Math.PI * CellHash.unit(CellHash.mix(shapeSeed, SALT_MEANDER, wave, 0));
}
double amplitude = Math.clamp(MEANDER_WIDTH_SCALE * (halfWidth + 1f), MEANDER_MIN, MEANDER_MAX);
double amplitude = Math.clamp(amplitudeScale * (halfWidth + 1f), MEANDER_MIN, MEANDER_MAX);
double wavelength = Math.clamp(MEANDER_WAVELENGTH_WIDTHS * 2D * (halfWidth + 1f), MEANDER_WAVELENGTH_MIN, MEANDER_WAVELENGTH_MAX);
double ramp = Math.min(line.length() / 2D, wavelength / 2D);
float[] open = awayFromPonds(line, tangents, (float) amplitude + halfWidth + SHORE_MARGIN);
double[] damping = slopeDamping(line);
double[] damping = dampOnSlopes ? slopeDamping(line) : null;
float[] offsets = new float[count];
for (int point = 1; point < count - 1; point++) {
double s = line.distance()[point];
@@ -181,7 +185,7 @@ final class ReachFitter {
wave += MEANDER_WAVE_WEIGHTS[index] * StrictMath.sin(2D * Math.PI * s / (wavelength * MEANDER_WAVE_SCALES[index]) + phase[index]);
}
double envelope = smoothstep(s / ramp) * smoothstep((line.length() - s) / ramp);
offsets[point] = (float) (amplitude * envelope * damping[point] * wave * open[point]);
offsets[point] = (float) (amplitude * envelope * (damping == null ? 1D : damping[point]) * wave * open[point]);
}
for (int point = 1; point < count - 1; point++) {
line.xs()[point] -= offsets[point] * tangents.z()[point];
@@ -370,10 +370,7 @@ public final class ReachShaper {
for (int point = 0; point < distance.length; point++) {
draft.outletZone[point] = draft.outlet && distance[point] <= OUTLET_LENGTH;
}
for (int pass = 0; pass < SMOOTHING_PASSES; pass++) {
chaikin(draft);
}
unfold(draft);
smooth(draft);
float upstream = 0f;
float feederEnd = 0f;
for (int index : draft.incoming) {
@@ -385,6 +382,13 @@ public final class ReachShaper {
widths(draft, upstream, feederEnd);
}
static void smooth(ReachDraft draft) {
for (int pass = 0; pass < SMOOTHING_PASSES; pass++) {
chaikin(draft);
}
unfold(draft);
}
private static void restyle(ReachDraft draft, int seaLevel) {
draft.style = styles(draft.grade, draft.ocean, draft.fixed(), draft.tier.waterfallMinimumDrop(), seaLevel, draft.tier.stepHeight());
}
@@ -8,7 +8,8 @@ public enum ReachStyle {
CASCADE(2),
WATERFALL(3),
POND_OUTLET(4),
MOUTH(5);
MOUTH(5),
TIDAL(6);
private static final PersistedCodes<ReachStyle> CODES = PersistedCodes.of(ReachStyle.class, ReachStyle::code);
@@ -0,0 +1,793 @@
package art.arcane.iris.generation.hydrology.water;
import art.arcane.iris.generation.hydrology.grid.CellHash;
import art.arcane.iris.generation.hydrology.grid.DemGrid;
import art.arcane.iris.generation.hydrology.grid.HeightLattice;
import art.arcane.iris.generation.hydrology.grid.HydrologySampleBuffer;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.hydrology.plan.WindowKey;
import art.arcane.iris.generation.hydrology.plan.WindowPlanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.PriorityQueue;
public final class TidalPlanner {
private static final int CELL = WindowPlanner.CELL;
private static final int[] SIDE_I = {1, -1, 0, 0};
private static final int[] SIDE_J = {0, 0, 1, -1};
private static final int MEMO_SITES = 4096;
private static final int BUILD_ATTEMPTS = 24;
private static final int TRIM_PASSES = 8;
private static final float MOUTH_ZONE = 32f;
private static final float END_SHARE = 0.4f;
private static final float DIAGONAL = 1.41421356f;
private static final float BESIDE_SEA_MARGIN = 10f;
private static final float BESIDE_SEA_SHARE = 0.4f;
private static final float TIP_LENGTH = 12f;
private static final float TIP_HALF_WIDTH = 1.5f;
private static final float SHOAL_LENGTH = 16f;
private static final float DEEP_SHARE = 0.5f;
private static final float SCAN_STEP = 8f;
private static final float HEAD_WOBBLE = 0.4f;
private static final float WOBBLE_LONG = 57f;
private static final float WOBBLE_SHORT = 23f;
private static final float BESIDE_NEAR = 1f;
private static final float CLEARANCE_MARGIN = 4f;
private static final int CLEARANCE_BAND = 24;
private static final int LOW_RIVER = 2;
private static final float LOW_RIVER_BAND = 4f;
private static final float WALK_WIDTH = 4f;
private static final float MAX_BANK_SLOPE = 2.5f;
private static final float SMOOTH_STEEPEST = 1.5f;
private static final float BANK_FIELD_SHARE = 0.125f;
private static final float FAR_BANK_SHARE = 1.5f;
private static final float HEAD_LOOK_BACK = 16f;
private static final float TERRITORY_MARGIN = 8f;
private static final int PROFILE_STEP = 4;
private static final float CLIFF_RISE = 14f;
private static final float WANDER = 12f;
private static final float WANDER_CELLS = 5f;
private static final float WAVES_PER_LENGTH = 0.5f;
private static final float WAVELENGTH_WIDTHS = 24f;
private static final double MEANDER_SCALE = 4.5D;
private static final long SALT_WANDER = 0x5449444c574eL;
private static final long SALT_ID = 0x5449444c4944L;
private static final long SALT_SITE = 0x5449444c53L;
private static final long SALT_DENSITY = 0x5449444c444eL;
private static final long SALT_TARGET_X = 0x5449444c5458L;
private static final long SALT_TARGET_Z = 0x5449444c545aL;
private static final long SALT_LENGTH = 0x5449444c4c4eL;
private static final long SALT_SHAPE = 0x5449444c5348L;
private static final long SALT_MOUTH = 0x5449444c4d4fL;
private static final long SALT_HEAD = 0x5449444c4845L;
private static final long SALT_DEPTH = 0x5449444c4450L;
private static final long SALT_WOBBLE = 0x5449444c5742L;
private final HydrologySettings settings;
private final HydrologySettings.SeaInlets config;
private final HeightLattice fine;
private final int stride;
private final long seed;
private final float gradedHeight;
private final float territory;
private final Map<Long, Anchor> anchors = new LinkedHashMap<>(MEMO_SITES, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<Long, Anchor> eldest) {
return size() > MEMO_SITES;
}
};
public TidalPlanner(HydrologySettings settings, HeightLattice fine) {
this.settings = Objects.requireNonNull(settings, "settings");
this.config = settings.underground().seaInlets();
this.fine = Objects.requireNonNull(fine, "fine");
this.stride = CELL / fine.cell();
this.seed = settings.seed();
this.gradedHeight = Math.min(config.maximumBankHeight(), MAX_BANK_SLOPE * config.bankBand() / SMOOTH_STEEPEST);
this.territory = config.mouthHalfWidth().max() + config.headHalfWidth().max() + TERRITORY_MARGIN;
}
public List<Reach> plan(WindowKey window, DemGrid natural, HydrologySampleBuffer samples, ShapedNetwork network) {
Objects.requireNonNull(window, "window");
Objects.requireNonNull(network, "network");
if (!config.enabled() || settings.density() <= 0f) {
return List.of();
}
List<Anchor> own = own(window);
if (own.isEmpty()) {
return List.of();
}
Land land = new Land(natural, samples);
float[] coast = coastDistance(land);
boolean[] wet = wet(natural, network);
banked(natural, samples, wet);
ReachFitter fitter = new ReachFitter(fine, new PondLookup(network.ponds()));
List<Reach> planned = new ArrayList<>();
for (Anchor anchor : own) {
List<Anchor> rivals = rivals(anchor);
Reach reach = site(window, land, coast, wet, anchor, rivals, fitter, network);
if (reach != null) {
requireWithinReach(window, reach);
planned.add(reach);
}
}
planned.sort(Comparator.comparingLong(Reach::id));
return List.copyOf(planned);
}
private List<Anchor> own(WindowKey window) {
int spacing = config.spacing();
int minSiteX = Math.floorDiv(window.wx() * WindowKey.SIZE, spacing);
int maxSiteX = Math.floorDiv((window.wx() + 1) * WindowKey.SIZE - 1, spacing);
int minSiteZ = Math.floorDiv(window.wz() * WindowKey.SIZE, spacing);
int maxSiteZ = Math.floorDiv((window.wz() + 1) * WindowKey.SIZE - 1, spacing);
List<Anchor> own = new ArrayList<>();
for (int siteZ = minSiteZ; siteZ <= maxSiteZ; siteZ++) {
for (int siteX = minSiteX; siteX <= maxSiteX; siteX++) {
Anchor anchor = anchor(siteX, siteZ);
if (anchor.active() && anchor.owner().equals(window)) {
own.add(anchor);
}
}
}
return own;
}
private Anchor anchor(int siteX, int siteZ) {
long key = ((long) siteX << 32) | (siteZ & 0xFFFFFFFFL);
synchronized (anchors) {
Anchor known = anchors.get(key);
if (known != null) {
return known;
}
}
Anchor anchor = locate(siteX, siteZ);
synchronized (anchors) {
anchors.put(key, anchor);
}
return anchor;
}
private Anchor locate(int siteX, int siteZ) {
int spacing = config.spacing();
double targetX = (siteX + CellHash.unit(CellHash.mix(seed, SALT_TARGET_X, siteX, siteZ))) * spacing;
double targetZ = (siteZ + CellHash.unit(CellHash.mix(seed, SALT_TARGET_Z, siteX, siteZ))) * spacing;
WindowKey owner = WindowKey.containing((int) Math.floor(targetX), (int) Math.floor(targetZ));
if (settings.density() < 1f && CellHash.unit(CellHash.mix(seed, SALT_DENSITY, siteX, siteZ)) >= settings.density()) {
return new Anchor(siteX, siteZ, owner, targetX, targetZ, false, 0, 0);
}
int firstX = Math.ceilDiv(siteX * spacing, CELL) * CELL;
int firstZ = Math.ceilDiv(siteZ * spacing, CELL) * CELL;
int cellsX = Math.ceilDiv((siteX + 1) * spacing - firstX, CELL);
int cellsZ = Math.ceilDiv((siteZ + 1) * spacing - firstZ, CELL);
Land land = land(firstX - CELL, firstZ - CELL, cellsX + 2, cellsZ + 2);
DemGrid grid = land.grid();
int bestX = 0;
int bestZ = 0;
double best = Double.POSITIVE_INFINITY;
for (int j = 1; j <= cellsZ; j++) {
for (int i = 1; i <= cellsX; i++) {
int cell = grid.index(i, j);
int mouth = open(land, cell) ? mouth(land, cell) : -1;
if (mouth < 0 || !owner.equals(WindowKey.containing(grid.blockX(mouth), grid.blockZ(mouth)))) {
continue;
}
double distance = Math.hypot(grid.blockX(cell) - targetX, grid.blockZ(cell) - targetZ);
if (distance < best) {
best = distance;
bestX = grid.blockX(cell);
bestZ = grid.blockZ(cell);
}
}
}
return new Anchor(siteX, siteZ, owner, targetX, targetZ, best != Double.POSITIVE_INFINITY, bestX, bestZ);
}
private List<Anchor> rivals(Anchor anchor) {
double reach = 2D * (config.length().max() + 2 * CELL) + territory;
int spacing = config.spacing();
int minSiteX = Math.floorDiv((int) Math.floor(anchor.x() - reach), spacing);
int maxSiteX = Math.floorDiv((int) Math.ceil(anchor.x() + reach), spacing);
int minSiteZ = Math.floorDiv((int) Math.floor(anchor.z() - reach), spacing);
int maxSiteZ = Math.floorDiv((int) Math.ceil(anchor.z() + reach), spacing);
List<Anchor> rivals = new ArrayList<>();
for (int siteZ = minSiteZ; siteZ <= maxSiteZ; siteZ++) {
for (int siteX = minSiteX; siteX <= maxSiteX; siteX++) {
Anchor other = anchor(siteX, siteZ);
if (other.active() && (other.siteX() != anchor.siteX() || other.siteZ() != anchor.siteZ())) {
rivals.add(other);
}
}
}
return rivals;
}
private boolean inTerritory(Anchor anchor, List<Anchor> rivals, double x, double z) {
double own = Math.hypot(x - anchor.x(), z - anchor.z());
for (Anchor rival : rivals) {
if (own + territory > Math.hypot(x - rival.x(), z - rival.z())) {
return false;
}
}
return true;
}
private Reach site(WindowKey window, Land land, float[] coast, boolean[] wet, Anchor anchor, List<Anchor> rivals, ReachFitter fitter, ShapedNetwork network) {
DemGrid grid = land.grid();
int spacing = config.spacing();
List<Integer> candidates = new ArrayList<>();
int firstI = Math.ceilDiv(anchor.siteX() * spacing - grid.originX(), CELL);
int firstJ = Math.ceilDiv(anchor.siteZ() * spacing - grid.originZ(), CELL);
int lastI = Math.ceilDiv((anchor.siteX() + 1) * spacing - grid.originX(), CELL) - 1;
int lastJ = Math.ceilDiv((anchor.siteZ() + 1) * spacing - grid.originZ(), CELL) - 1;
for (int j = Math.max(1, firstJ); j <= Math.min(grid.depth() - 2, lastJ); j++) {
for (int i = Math.max(1, firstI); i <= Math.min(grid.width() - 2, lastI); i++) {
int cell = grid.index(i, j);
int mouth = open(land, cell) && !wet[cell] ? mouth(land, cell) : -1;
if (mouth >= 0 && window.equals(WindowKey.containing(grid.blockX(mouth), grid.blockZ(mouth)))
&& inTerritory(anchor, rivals, grid.blockX(cell), grid.blockZ(cell))) {
candidates.add(cell);
}
}
}
candidates.sort(Comparator.comparingDouble((Integer cell) -> Math.hypot(grid.blockX(cell) - anchor.targetX(), grid.blockZ(cell) - anchor.targetZ())).thenComparingInt(cell -> cell));
int attempts = 0;
for (int cell : candidates) {
int[] cells = trace(land, coast, wet, anchor, rivals, cell);
if (cells == null) {
continue;
}
Reach reach = shape(land, cells, anchor, rivals, fitter, network);
if (reach != null) {
return reach;
}
if (++attempts >= BUILD_ATTEMPTS) {
return null;
}
}
return null;
}
private boolean[] wet(DemGrid grid, ShapedNetwork network) {
boolean[] wet = new boolean[grid.values().length];
for (Reach river : network.reaches()) {
float band = Math.min(river.tier().bankBand(), CLEARANCE_BAND) + CLEARANCE_MARGIN + WALK_WIDTH;
for (int point = 0; point < river.xs().length; point += 2) {
float apart = river.grade()[point] - settings.seaLevel() <= LOW_RIVER ? CLEARANCE_MARGIN + LOW_RIVER_BAND : band;
mark(grid, wet, river.xs()[point], river.zs()[point], river.halfWidth()[point] + apart);
}
}
for (Pond pond : network.ponds()) {
PondMask mask = pond.mask();
float radius = 1.5f * mask.step() + Math.max(settings.ponds().shore().taper(), CLEARANCE_BAND) + CLEARANCE_MARGIN;
for (int j = 0; j < mask.depth(); j++) {
for (int i = 0; i < mask.width(); i++) {
if (mask.node(i, j)) {
mark(grid, wet, mask.originX() + i * mask.step(), mask.originZ() + j * mask.step(), radius);
}
}
}
}
return wet;
}
private void banked(DemGrid grid, HydrologySampleBuffer samples, boolean[] wet) {
int radius = (int) Math.ceil(BANK_FIELD_SHARE * config.bankBand() / CELL);
int width = grid.width();
int depth = grid.depth();
float limit = settings.seaLevel() + gradedHeight;
boolean[] high = new boolean[width * depth];
for (int cell = 0; cell < high.length; cell++) {
high[cell] = !samples.ocean()[cell] && samples.height()[cell] > limit;
}
boolean[] across = new boolean[high.length];
for (int j = 0; j < depth; j++) {
int last = Integer.MIN_VALUE / 2;
for (int i = 0; i < width; i++) {
last = high[j * width + i] ? i : last;
across[j * width + i] = i - last <= radius;
}
last = Integer.MAX_VALUE / 2;
for (int i = width - 1; i >= 0; i--) {
last = high[j * width + i] ? i : last;
across[j * width + i] |= last - i <= radius;
}
}
for (int i = 0; i < width; i++) {
int last = Integer.MIN_VALUE / 2;
for (int j = 0; j < depth; j++) {
last = across[j * width + i] ? j : last;
wet[j * width + i] |= j - last <= radius;
}
last = Integer.MAX_VALUE / 2;
for (int j = depth - 1; j >= 0; j--) {
last = across[j * width + i] ? j : last;
wet[j * width + i] |= last - j <= radius;
}
}
}
private static void mark(DemGrid grid, boolean[] wet, float x, float z, float radius) {
int cell = grid.cell();
int minI = Math.max(0, (int) Math.floor((x - radius - grid.originX()) / cell));
int maxI = Math.min(grid.width() - 1, (int) Math.ceil((x + radius - grid.originX()) / cell));
int minJ = Math.max(0, (int) Math.floor((z - radius - grid.originZ()) / cell));
int maxJ = Math.min(grid.depth() - 1, (int) Math.ceil((z + radius - grid.originZ()) / cell));
float squared = radius * radius;
for (int j = minJ; j <= maxJ; j++) {
float dz = grid.originZ() + j * cell - z;
for (int i = minI; i <= maxI; i++) {
float dx = grid.originX() + i * cell - x;
if (dx * dx + dz * dz <= squared) {
wet[j * grid.width() + i] = true;
}
}
}
}
private Land land(int originX, int originZ, int width, int depth) {
HydrologySampleBuffer samples = new HydrologySampleBuffer(width * depth);
fine.fill(Math.floorDiv(originX, fine.cell()), Math.floorDiv(originZ, fine.cell()), width, depth, stride, samples);
DemGrid grid = new DemGrid(originX, originZ, CELL, width, depth);
System.arraycopy(samples.height(), 0, grid.values(), 0, width * depth);
return new Land(grid, samples);
}
private boolean open(Land land, int cell) {
HydrologySampleBuffer samples = land.samples();
float height = samples.height()[cell];
return !samples.ocean()[cell] && height >= settings.seaLevel() + 1 && height <= settings.seaLevel() + gradedHeight
&& (samples.permission()[cell] & HydrologySampleBuffer.ALLOW_STREAMS) != 0;
}
private static int mouth(Land land, int cell) {
DemGrid grid = land.grid();
int i = cell % grid.width();
int j = cell / grid.width();
for (int side = 0; side < SIDE_I.length; side++) {
int ni = i + SIDE_I[side];
int nj = j + SIDE_J[side];
if (ni >= 0 && nj >= 0 && ni < grid.width() && nj < grid.depth() && land.samples().ocean()[grid.index(ni, nj)]) {
return grid.index(ni, nj);
}
}
return -1;
}
private static float[] coastDistance(Land land) {
DemGrid grid = land.grid();
boolean[] ocean = land.samples().ocean();
int width = grid.width();
int depth = grid.depth();
float[] distance = new float[width * depth];
Arrays.fill(distance, Float.POSITIVE_INFINITY);
for (int cell = 0; cell < distance.length; cell++) {
if (ocean[cell]) {
distance[cell] = 0f;
}
}
float straight = CELL;
float diagonal = CELL * DIAGONAL;
for (int pass = 0; pass < 2; pass++) {
int step = pass == 0 ? -1 : 1;
for (int b = 0; b < depth; b++) {
int j = pass == 0 ? b : depth - 1 - b;
for (int a = 0; a < width; a++) {
int i = pass == 0 ? a : width - 1 - a;
int cell = grid.index(i, j);
float best = distance[cell];
if (i + step >= 0 && i + step < width) {
best = Math.min(best, distance[grid.index(i + step, j)] + straight);
}
if (j + step >= 0 && j + step < depth) {
best = Math.min(best, distance[grid.index(i, j + step)] + straight);
if (i + step >= 0 && i + step < width) {
best = Math.min(best, distance[grid.index(i + step, j + step)] + diagonal);
}
if (i - step >= 0 && i - step < width) {
best = Math.min(best, distance[grid.index(i - step, j + step)] + diagonal);
}
}
distance[cell] = best;
}
}
}
return distance;
}
private int[] trace(Land land, float[] coast, boolean[] wet, Anchor anchor, List<Anchor> rivals, int start) {
DemGrid grid = land.grid();
int mouth = mouth(land, start);
double unit = CellHash.unit(CellHash.mix(seed, SALT_LENGTH, grid.blockX(start), grid.blockZ(start)));
float target = (float) (config.length().min() + (config.length().max() - config.length().min()) * unit);
float[] height = land.samples().height();
Map<Integer, Step> reached = new HashMap<>();
reached.put(start, new Step(-1, 0f, CELL));
PriorityQueue<Integer> frontier = new PriorityQueue<>(Comparator.comparingDouble((Integer cell) -> coast[cell]).thenComparingInt(cell -> cell));
frontier.add(start);
int chosen = start;
float chosenCost = Float.POSITIVE_INFINITY;
float longest = CELL;
while (!frontier.isEmpty()) {
int current = frontier.poll();
Step step = reached.get(current);
if (step.length() >= target) {
float cost = step.cost() / step.length();
if (longest < target || cost < chosenCost) {
chosen = current;
chosenCost = cost;
longest = step.length();
}
continue;
}
if (longest < target && step.length() > longest) {
longest = step.length();
chosen = current;
}
int i = current % grid.width();
int j = current / grid.width();
for (int dj = -1; dj <= 1; dj++) {
for (int di = -1; di <= 1; di++) {
int ni = i + di;
int nj = j + dj;
if (di == 0 && dj == 0 || ni < 1 || nj < 1 || ni >= grid.width() - 1 || nj >= grid.depth() - 1) {
continue;
}
int next = grid.index(ni, nj);
if (coast[next] <= coast[current] || wet[next] || !open(land, next) || !inTerritory(anchor, rivals, grid.blockX(next), grid.blockZ(next))) {
continue;
}
float span = di != 0 && dj != 0 ? CELL * DIAGONAL : CELL;
float cost = step.cost() + span * (height[next] - settings.seaLevel() + wander(grid.blockX(next), grid.blockZ(next)));
Step known = reached.get(next);
if (known == null) {
frontier.add(next);
}
if (known == null || cost < known.cost()) {
reached.put(next, new Step(current, cost, step.length() + span));
}
}
}
}
float length = reached.get(chosen).length();
if (length < config.length().min() || coast[chosen] < END_SHARE * length) {
return null;
}
List<Integer> path = new ArrayList<>();
for (int cell = chosen; cell >= 0; cell = reached.get(cell).from()) {
path.add(cell);
}
int[] cells = new int[path.size() + 1];
for (int index = 0; index < path.size(); index++) {
cells[index] = path.get(index);
}
cells[path.size()] = mouth;
return cells;
}
private float wander(int x, int z) {
float size = WANDER_CELLS * CELL;
int ix = (int) Math.floor(x / size);
int iz = (int) Math.floor(z / size);
float u = x / size - ix;
float v = z / size - iz;
float a = (float) CellHash.unit(CellHash.mix(seed, SALT_WANDER, ix, iz));
float b = (float) CellHash.unit(CellHash.mix(seed, SALT_WANDER, ix + 1, iz));
float c = (float) CellHash.unit(CellHash.mix(seed, SALT_WANDER, ix, iz + 1));
float d = (float) CellHash.unit(CellHash.mix(seed, SALT_WANDER, ix + 1, iz + 1));
return WANDER * ((a + (b - a) * u) * (1f - v) + (c + (d - c) * u) * v);
}
private Reach shape(Land land, int[] cells, Anchor anchor, List<Anchor> rivals, ReachFitter fitter, ShapedNetwork network) {
DemGrid grid = land.grid();
int last = cells.length - 1;
int mouthX = grid.blockX(cells[last]);
int mouthZ = grid.blockZ(cells[last]);
int startX = grid.blockX(cells[last - 1]);
int startZ = grid.blockZ(cells[last - 1]);
long id = CellHash.mix(CellHash.mix(seed, SALT_ID, mouthX, mouthZ), SALT_SITE, startX, startZ);
long shape = CellHash.mix(id, SALT_SHAPE, 0, 0);
HydrologyTier tier = settings.tidalTier();
float walked = 0f;
for (int index = 1; index < cells.length; index++) {
walked += (float) Math.hypot(grid.blockX(cells[index]) - grid.blockX(cells[index - 1]), grid.blockZ(cells[index]) - grid.blockZ(cells[index - 1]));
}
float meanderWidth = Math.clamp(walked * WAVES_PER_LENGTH / WAVELENGTH_WIDTHS - 1f, 1f, config.meanderWidth());
ReachFitter.Fitted fitted = fitter.fit(grid, cells, new float[cells.length], tier, shape, true, meanderWidth, MEANDER_SCALE, false);
ReachDraft draft = new ReachDraft(new ReachTracer.Chain(cells, ReachTracer.End.OCEAN, -1), id, tier, 0f, Integer.MIN_VALUE, fitted);
draft.grade = new int[draft.xs.length];
Arrays.fill(draft.grade, settings.seaLevel());
draft.outletZone = new boolean[draft.xs.length];
ReachShaper.smooth(draft);
float[] xs = draft.xs;
float[] zs = draft.zs;
for (int pass = 0; pass < TRIM_PASSES; pass++) {
int grounded = groundedHead(xs, zs, id, shape);
if (grounded < 0) {
return null;
}
int head = Math.max(grounded, Math.max(territoryHead(xs, zs, shape, anchor, rivals), clearHead(xs, zs, shape, network)));
float[] distance = ReachShaper.distances(xs, zs);
if (distance[distance.length - 1] - distance[head] < config.length().min()) {
return null;
}
if (head == 0) {
Reach reach = reach(id, shape, xs, zs);
if (besideSea(reach)) {
return null;
}
return reach;
}
xs = Arrays.copyOfRange(xs, head, xs.length);
zs = Arrays.copyOfRange(zs, head, zs.length);
}
return null;
}
private int territoryHead(float[] xs, float[] zs, long shape, Anchor anchor, List<Anchor> rivals) {
float[] distance = ReachShaper.distances(xs, zs);
for (int point = xs.length - 1; point >= 0; point--) {
if (!inTerritory(anchor, rivals, xs[point], zs[point])) {
float keep = distance[point] + SCAN_STEP;
int head = point;
while (head < xs.length - 1 && distance[head] < keep) {
head++;
}
return head;
}
}
return 0;
}
private int clearHead(float[] xs, float[] zs, long shape, ShapedNetwork network) {
float[] distance = ReachShaper.distances(xs, zs);
float[] widths = widths(shape, distance);
float keep = 0f;
for (Reach river : network.reaches()) {
float band = Math.min(river.tier().bankBand(), CLEARANCE_BAND) + CLEARANCE_MARGIN;
for (int segment = 0; segment < river.xs().length; segment++) {
float apart = river.grade()[segment] - settings.seaLevel() <= LOW_RIVER ? CLEARANCE_MARGIN + LOW_RIVER_BAND : band;
keep = Math.max(keep, blocked(xs, zs, widths, distance, river.xs()[segment], river.zs()[segment], river.halfWidth()[segment] + apart));
}
}
for (Pond pond : network.ponds()) {
PondMask mask = pond.mask();
float radius = 1.5f * mask.step() + Math.max(settings.ponds().shore().taper(), CLEARANCE_BAND) + CLEARANCE_MARGIN;
for (int j = 0; j < mask.depth(); j++) {
for (int i = 0; i < mask.width(); i++) {
if (mask.node(i, j)) {
keep = Math.max(keep, blocked(xs, zs, widths, distance, mask.originX() + i * mask.step(), mask.originZ() + j * mask.step(), radius));
}
}
}
}
if (keep <= 0f) {
return 0;
}
int head = 0;
while (head < distance.length - 1 && distance[head] < keep) {
head++;
}
return head;
}
private static float blocked(float[] xs, float[] zs, float[] widths, float[] distance, float x, float z, float radius) {
for (int point = xs.length - 1; point >= 0; point--) {
float gap = widths[point] + radius;
float dx = xs[point] - x;
float dz = zs[point] - z;
if (dx * dx + dz * dz < gap * gap) {
return distance[point] + radius + widths[point];
}
}
return 0f;
}
private Reach reach(long id, long shape, float[] xs, float[] zs) {
float[] distance = ReachShaper.distances(xs, zs);
float[] halfWidth = widths(shape, distance);
float[] depth = depths(shape, distance);
int[] grade = new int[xs.length];
Arrays.fill(grade, settings.seaLevel());
ReachStyle[] style = new ReachStyle[xs.length];
Arrays.fill(style, ReachStyle.TIDAL);
return new Reach(id, settings.tidalTier(), 0L, xs, zs, grade, halfWidth, depth, style, 0f);
}
private float[] widths(long shape, float[] distance) {
float total = distance[distance.length - 1];
HydrologySettings.FloatRange mouths = config.mouthHalfWidth();
HydrologySettings.FloatRange heads = config.headHalfWidth();
float mouth = mouths.min() + (mouths.max() - mouths.min()) * (float) CellHash.unit(CellHash.mix(shape, SALT_MOUTH, 0, 0));
float head = heads.min() + (heads.max() - heads.min()) * (float) CellHash.unit(CellHash.mix(shape, SALT_HEAD, 0, 0));
double phaseLong = CellHash.unit(CellHash.mix(shape, SALT_WOBBLE, 0, 0));
double phaseShort = CellHash.unit(CellHash.mix(shape, SALT_WOBBLE, 1, 0));
float[] widths = new float[distance.length];
for (int point = 0; point < distance.length; point++) {
float s = distance[point];
float t = s / total;
double funnel = head + (mouth - head) * Math.pow(t, config.taper());
double wobble = 0.65D * StrictMath.sin(2D * Math.PI * (s / WOBBLE_LONG + phaseLong)) + 0.35D * StrictMath.sin(2D * Math.PI * (s / WOBBLE_SHORT + phaseShort));
double ends = Math.min(1f, Math.min(s, total - s) / TIP_LENGTH);
double shaped = funnel * (1D + config.widthVariation() * ends * (HEAD_WOBBLE + (1f - HEAD_WOBBLE) * t) * wobble);
double tip = TIP_HALF_WIDTH + (shaped - TIP_HALF_WIDTH) * Math.min(1f, s / TIP_LENGTH);
widths[point] = (float) Math.max(TIP_HALF_WIDTH, point == distance.length - 1 ? mouth : tip);
}
return widths;
}
private float[] depths(long shape, float[] distance) {
float total = distance[distance.length - 1];
HydrologySettings.IntRange range = config.depth();
float deepest = range.min() + (range.max() - range.min()) * (float) CellHash.unit(CellHash.mix(shape, SALT_DEPTH, 0, 0));
float[] depth = new float[distance.length];
for (int point = 0; point < distance.length; point++) {
float s = distance[point];
float along = range.min() + (deepest - range.min()) * Math.min(1f, s / total / DEEP_SHARE);
float shoal = Math.min(1f, s / SHOAL_LENGTH) * Math.min(1f, (total - s) / SHOAL_LENGTH);
depth[point] = 1f + (along - 1f) * shoal;
}
return depth;
}
private int groundedHead(float[] xs, float[] zs, long id, long shape) {
float[] distance = ReachShaper.distances(xs, zs);
float total = distance[distance.length - 1];
float[] widths = widths(shape, distance);
int band = config.bankBand();
float limit = settings.seaLevel() + gradedHeight;
float farLimit = settings.seaLevel() + FAR_BANK_SHARE * gradedHeight;
int rings = band / PROFILE_STEP + 1;
int[] columnX = new int[2 * rings + 1];
int[] columnZ = new int[2 * rings + 1];
HydrologySampleBuffer samples = new HydrologySampleBuffer(columnX.length);
int stops = (int) Math.ceil(total / SCAN_STEP);
int point = xs.length - 1;
for (int stop = 0; stop <= stops; stop++) {
float wanted = total - stop * SCAN_STEP;
while (point > 0 && distance[point] > wanted) {
point--;
}
int before = Math.max(0, point - 1);
int after = Math.min(xs.length - 1, point + 1);
double length = Math.max(1e-3D, Math.hypot(xs[after] - xs[before], zs[after] - zs[before]));
double nx = -(zs[after] - zs[before]) / length;
double nz = (xs[after] - xs[before]) / length;
for (int ring = 0; ring < rings; ring++) {
double out = widths[point] + BESIDE_NEAR + ring * PROFILE_STEP;
columnX[2 * ring] = (int) Math.floor(xs[point] + out * nx);
columnZ[2 * ring] = (int) Math.floor(zs[point] + out * nz);
columnX[2 * ring + 1] = (int) Math.floor(xs[point] - out * nx);
columnZ[2 * ring + 1] = (int) Math.floor(zs[point] - out * nz);
}
columnX[2 * rings] = (int) Math.floor(xs[point]);
columnZ[2 * rings] = (int) Math.floor(zs[point]);
fine.sampleColumns(columnX, columnZ, samples);
boolean inland = total - distance[point] > MOUTH_ZONE;
boolean bad = !samples.ocean()[2 * rings] && samples.height()[2 * rings] > limit;
for (int ring = 0; ring < rings && !bad; ring++) {
for (int side = 0; side < 2 && !bad; side++) {
int index = 2 * ring + side;
if (samples.ocean()[index]) {
continue;
}
float height = samples.height()[index];
bad = height > (ring >= rings / 2 ? farLimit : limit) || inland && ring < 2 && height < settings.seaLevel();
if (!bad && ring > 0 && !samples.ocean()[index - 2]) {
bad = height - samples.height()[index - 2] >= CLIFF_RISE;
}
}
}
if (bad) {
float keep = distance[point] + band + widths[point];
int head = point;
while (head < xs.length - 1 && distance[head] < keep) {
head++;
}
return total - distance[head] >= config.length().min() ? head : -1;
}
}
return headFacesHighGround(xs, zs, widths, distance, limit) ? headBack(distance, total) : 0;
}
private boolean headFacesHighGround(float[] xs, float[] zs, float[] widths, float[] distance, float limit) {
int ahead = 0;
while (ahead < xs.length - 1 && distance[ahead] < SCAN_STEP) {
ahead++;
}
double length = Math.max(1e-3D, Math.hypot(xs[0] - xs[ahead], zs[0] - zs[ahead]));
double tx = (xs[0] - xs[ahead]) / length;
double tz = (zs[0] - zs[ahead]) / length;
int rays = 7;
int rings = config.bankBand() / PROFILE_STEP;
int[] columnX = new int[rays * rings];
int[] columnZ = new int[rays * rings];
for (int ray = 0; ray < rays; ray++) {
double angle = Math.toRadians(-90D + 30D * ray);
double dx = tx * Math.cos(angle) - tz * Math.sin(angle);
double dz = tx * Math.sin(angle) + tz * Math.cos(angle);
for (int ring = 0; ring < rings; ring++) {
float out = widths[0] + (ring + 1) * PROFILE_STEP;
columnX[ray * rings + ring] = (int) Math.floor(xs[0] + out * dx);
columnZ[ray * rings + ring] = (int) Math.floor(zs[0] + out * dz);
}
}
HydrologySampleBuffer samples = new HydrologySampleBuffer(columnX.length);
fine.sampleColumns(columnX, columnZ, samples);
for (int index = 0; index < columnX.length; index++) {
if (samples.ocean()[index]) {
continue;
}
if (samples.height()[index] > limit || index % rings > 0 && !samples.ocean()[index - 1] && samples.height()[index] - samples.height()[index - 1] >= CLIFF_RISE) {
return true;
}
}
return false;
}
private int headBack(float[] distance, float total) {
int head = 0;
while (head < distance.length - 1 && distance[head] < HEAD_LOOK_BACK) {
head++;
}
return total - distance[head] >= config.length().min() ? head : -1;
}
private boolean besideSea(Reach reach) {
float[] distance = ReachShaper.distances(reach.xs(), reach.zs());
float total = distance[distance.length - 1];
int stops = 0;
int beside = 0;
int point = 0;
int directions = 8;
int[] columnX = new int[directions];
int[] columnZ = new int[directions];
HydrologySampleBuffer samples = new HydrologySampleBuffer(directions);
for (float s = 0f; s <= total; s += SCAN_STEP) {
while (point < distance.length - 1 && distance[point] < s) {
point++;
}
float radius = reach.halfWidth()[point] + BESIDE_SEA_MARGIN;
for (int direction = 0; direction < directions; direction++) {
double angle = 2D * Math.PI * direction / directions;
columnX[direction] = (int) Math.floor(reach.xs()[point] + radius * Math.cos(angle));
columnZ[direction] = (int) Math.floor(reach.zs()[point] + radius * Math.sin(angle));
}
fine.sampleColumns(columnX, columnZ, samples);
boolean sea = false;
for (int direction = 0; direction < directions; direction++) {
sea |= samples.ocean()[direction];
}
stops++;
beside += sea ? 1 : 0;
}
return beside > BESIDE_SEA_SHARE * stops;
}
private void requireWithinReach(WindowKey window, Reach reach) {
int band = config.bankBand();
for (int point = 0; point < reach.xs().length; point++) {
float out = reach.halfWidth()[point] + band;
if (reach.xs()[point] - out < (window.wx() - 1) * WindowKey.SIZE || reach.xs()[point] + out >= (window.wx() + 2) * WindowKey.SIZE
|| reach.zs()[point] - out < (window.wz() - 1) * WindowKey.SIZE || reach.zs()[point] + out >= (window.wz() + 2) * WindowKey.SIZE) {
throw new IllegalStateException("Sea inlet " + reach.id() + " of window " + window + " reaches past the next window at point " + point);
}
}
}
private record Step(int from, float cost, float length) {
}
private record Land(DemGrid grid, HydrologySampleBuffer samples) {
}
private record Anchor(int siteX, int siteZ, WindowKey owner, double targetX, double targetZ, boolean active, int x, int z) {
}
}
@@ -1,13 +1,8 @@
package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime;
import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.underground.SeaInletRasterizer;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
import java.util.Arrays;
import java.util.List;
public final class CaveCeilingMask {
static final int CONTAINMENT = 2;
@@ -59,69 +54,6 @@ public final class CaveCeilingMask {
return masked;
}
public static long[] headroom(int chunkX, int chunkZ, HydrologyRuntime runtime, long[] bands) {
List<SeaInlet> inlets = runtime.inlets(chunkX, chunkZ);
if (inlets.isEmpty()) {
return null;
}
int roofClearance = runtime.settings().underground().seaInlets().roofClearance();
return fillHeadroom(chunkX, chunkZ, inlets, roofClearance, bands) ? bands : null;
}
static boolean fillHeadroom(int chunkX, int chunkZ, List<SeaInlet> inlets, int roofClearance, long[] bands) {
if (inlets.isEmpty()) {
return false;
}
int originX = (chunkX << 4) - CONTAINMENT;
int originZ = (chunkZ << 4) - CONTAINMENT;
int[] bottoms = new int[FIELD * FIELD];
int[] tops = new int[FIELD * FIELD];
Arrays.fill(bottoms, Integer.MAX_VALUE);
Arrays.fill(tops, Integer.MIN_VALUE);
int[] column = new int[2];
boolean roofed = false;
for (SeaInlet inlet : inlets) {
int[] bounds = SeaInletRasterizer.bounds(inlet);
int fromX = Math.max(originX, bounds[0]);
int toX = Math.min(originX + FIELD - 1, bounds[2]);
int toZ = Math.min(originZ + FIELD - 1, bounds[3]);
for (int z = Math.max(originZ, bounds[1]); z <= toZ; z++) {
for (int x = fromX; x <= toX; x++) {
if (!SeaInletRasterizer.column(inlet, x, z, column) || column[1] == SeaInlet.OPEN) {
continue;
}
int index = (z - originZ) * FIELD + x - originX;
bottoms[index] = Math.min(bottoms[index], inlet.waterLevel() + 1);
tops[index] = Math.max(tops[index], column[1] + roofClearance);
roofed = true;
}
}
}
if (!roofed) {
return false;
}
boolean masked = false;
for (int lz = 0; lz < CHUNK; lz++) {
for (int lx = 0; lx < CHUNK; lx++) {
int bottom = Integer.MAX_VALUE;
int top = Integer.MIN_VALUE;
for (int fz = lz; fz <= lz + CONTAINMENT * 2; fz++) {
for (int fx = lx; fx <= lx + CONTAINMENT * 2; fx++) {
bottom = Math.min(bottom, bottoms[fz * FIELD + fx]);
top = Math.max(top, tops[fz * FIELD + fx]);
}
}
bands[PowerOfTwoCoordinates.packLocal16(lx, lz)] = SurfaceFluidBoundaryPlan.boundary(bottom, top);
masked |= bottom <= top;
}
}
return masked;
}
public static boolean masked(int[] ceilings, long[] headroom, int column, int y) {
return ceilings != null && y > ceilings[column] || SurfaceFluidBoundaryPlan.protects(headroom, column, y);
}
public static ChunkWaterRaster ready(ChunkWaterRaster raster, int chunkX, int chunkZ) {
if (raster.provisional()) {
throw new IllegalStateException("The water raster for chunk " + chunkX + "," + chunkZ
@@ -5,8 +5,6 @@ import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy;
import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime;
import art.arcane.iris.generation.hydrology.underground.CarvedTerrain;
import art.arcane.iris.generation.hydrology.underground.CaveVoxel;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.underground.SeaInletSpace;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.stream.ProvisionalSampling;
@@ -23,10 +21,7 @@ import art.arcane.volmlib.util.matter.Matter;
import art.arcane.volmlib.util.matter.MatterCavern;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
final class MantleCarvedTerrain implements CarvedTerrain {
private static final int SPAN = 48;
@@ -49,7 +44,6 @@ final class MantleCarvedTerrain implements CarvedTerrain {
private final SubterrainPlanner planner;
private final List<SubterrainPlan> features;
private final boolean terrain3D;
private final SeaInletSpace inlets;
private final MantleChunk<Matter>[] chunks;
private final boolean[] existing;
private final int[] surfaces = new int[SPAN * SPAN];
@@ -71,7 +65,6 @@ final class MantleCarvedTerrain implements CarvedTerrain {
this.minimumY = engine.getWorld().minHeight();
HydrologyRuntime runtime = complex.getHydrologyRuntime();
this.caveFluids = runtime.caveFluidPolicies();
this.inlets = SeaInletSpace.of(inlets(runtime, chunkX, chunkZ), originX, originZ, SPAN);
SubterrainPlanner subterrain = complex.getSubterrainPlanner();
List<SubterrainPlan> plans = subterrain == null || subterrain.isEmpty() ? List.of()
: subterrain.plansForBounds(originX, originZ, originX + SPAN - 1, originZ + SPAN - 1);
@@ -88,7 +81,7 @@ final class MantleCarvedTerrain implements CarvedTerrain {
@Override
public CaveVoxel voxel(int x, int y, int z) {
int column = column(x, z);
if (y <= 0 || y >= height || existing(x, z) || y > surface(x, z, column) || inlets.contains(x, y, z)) {
if (y <= 0 || y >= height || existing(x, z) || y > surface(x, z, column)) {
return CaveVoxel.FOREIGN;
}
if (planner != null && planner.sample(features, x, y + minimumY, z).owned()) {
@@ -149,18 +142,6 @@ final class MantleCarvedTerrain implements CarvedTerrain {
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++) {
for (int offsetX = -1; offsetX <= 1; offsetX++) {
for (SeaInlet inlet : runtime.inlets(chunkX + offsetX, chunkZ + offsetZ)) {
inlets.putIfAbsent(inlet.id(), inlet);
}
}
}
return inlets.values();
}
private int surface(int x, int z, int column) {
int known = surfaces[column];
if (known == UNKNOWN) {
@@ -169,10 +169,6 @@ public class MantleCarvingComponent extends IrisMantleComponent {
);
int[] caveCeilings = CaveCeilingMask.fill(x, z, complex.getHydrologyRuntime()::raster,
blendScratch.caveCeilingField, blendScratch.caveCeilings) ? blendScratch.caveCeilings : null;
long[] inletHeadroom = CaveCeilingMask.headroom(x, z, complex.getHydrologyRuntime(), blendScratch.inletHeadroom);
if (inletHeadroom != null) {
SurfaceFluidBoundaryPlan.join(surfaceFluidBoundaries, inletHeadroom);
}
CaveFluidSupportPlan fluidSupportPlan = new CaveFluidSupportPlan();
for (WeightedProfile weightedProfile : weightedProfiles) {
carveProfile(weightedProfile, writer, x, z, chunkSurfaceHeights, surfaceFluidBoundaries, caveCeilings, fluidSupportPlan);
@@ -194,10 +190,10 @@ public class MantleCarvingComponent extends IrisMantleComponent {
caveCeilings
);
}
rasterizeSubterrain(writer, x, z, complex, caveCeilings, inletHeadroom);
rasterizeSubterrain(writer, x, z, complex, caveCeilings);
}
private void rasterizeSubterrain(MantleWriter writer, int chunkX, int chunkZ, IrisComplex complex, int[] caveCeilings, long[] inletHeadroom) {
private void rasterizeSubterrain(MantleWriter writer, int chunkX, int chunkZ, IrisComplex complex, int[] caveCeilings) {
SubterrainPlanner planner = complex.getSubterrainPlanner();
if (planner == null || planner.isEmpty()) {
return;
@@ -211,7 +207,7 @@ public class MantleCarvingComponent extends IrisMantleComponent {
if (cell.solid() && !cell.room().reservedSolid()) {
return;
}
if (!cell.solid() && CaveCeilingMask.masked(caveCeilings, inletHeadroom, PowerOfTwoCoordinates.packLocal16(x & 15, z & 15), y)) {
if (!cell.solid() && caveCeilings != null && y > caveCeilings[PowerOfTwoCoordinates.packLocal16(x & 15, z & 15)]) {
return;
}
if (cell.solid()) {
@@ -767,7 +763,6 @@ public class MantleCarvingComponent extends IrisMantleComponent {
private final double[] chunkSurfaceHeightSamples = new double[CHUNK_AREA];
private final int[] caveCeilingField = new int[CaveCeilingMask.FIELD * CaveCeilingMask.FIELD];
private final int[] caveCeilings = new int[CHUNK_AREA];
private final long[] inletHeadroom = new long[CHUNK_AREA];
private final double[][] neighbourHeights = new double[NEIGHBOURS][CHUNK_AREA];
private final Object[][] neighbourObjects = new Object[NEIGHBOURS][CHUNK_AREA];
private final long[][] neighbourSubmerged = new long[NEIGHBOURS][4];
@@ -12,8 +12,6 @@ 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;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.subterrain.SubterrainPlan;
@@ -35,7 +33,6 @@ public final class MantleHydrologyComponent extends IrisMantleComponent {
private static final int CHUNK = 16;
private static final int GRID = CHUNK + 2;
private static final int[] SIDES = {1, -1, GRID, -GRID};
private static final SeaInletRasterizer INLETS = new SeaInletRasterizer();
public MantleHydrologyComponent(EngineMantle engineMantle) {
super(engineMantle, ReservedFlag.RIVER_HYDROLOGY, PRIORITY);
@@ -84,13 +81,6 @@ public final class MantleHydrologyComponent extends IrisMantleComponent {
}
HydrologyRuntime runtime = complex.getHydrologyRuntime();
ChunkWaterRaster own = CaveCeilingMask.ready(runtime.raster(chunkX, chunkZ), chunkX, chunkZ);
List<SeaInlet> inlets = runtime.inlets(chunkX, chunkZ);
if (!inlets.isEmpty()) {
SeaInletRasterizer.SubterrainFluid subterrain = subterrainFluid(writer, complex, chunkX, chunkZ);
for (SeaInlet inlet : inlets) {
INLETS.write(inlet, chunkX, chunkZ, writer, HydrologyCaveCell.SEA_FLUID, subterrain, complex::isHistoricalChunk);
}
}
generateFalls(writer, complex, runtime, own, chunkX, chunkZ);
if (caveWaterActive()) {
HydrologySettings settings = runtime.settings();
@@ -107,19 +97,6 @@ public final class MantleHydrologyComponent extends IrisMantleComponent {
}
}
private static SeaInletRasterizer.SubterrainFluid subterrainFluid(MantleWriter writer, IrisComplex complex, int chunkX, int chunkZ) {
SubterrainPlanner planner = complex.getSubterrainPlanner();
if (planner == null || planner.isEmpty()) {
return SeaInletRasterizer.SubterrainFluid.NOWHERE;
}
List<SubterrainPlan> plans = planner.plansForBounds(chunkX << 4, chunkZ << 4, (chunkX << 4) + 15, (chunkZ << 4) + 15);
if (plans.isEmpty()) {
return SeaInletRasterizer.SubterrainFluid.NOWHERE;
}
int minimumY = writer.getEngine().getWorld().minHeight();
return (x, y, z) -> planner.sample(plans, x, y + minimumY, z).fluid();
}
private void generateFalls(MantleWriter writer, IrisComplex complex, HydrologyRuntime runtime, ChunkWaterRaster own, int chunkX,
int chunkZ) {
if (!holdsWater(own)) {
@@ -73,17 +73,6 @@ final class SurfaceFluidBoundaryPlan {
}
}
static void join(long[] boundaries, long[] bands) {
for (int columnIndex = 0; columnIndex < CHUNK_AREA; columnIndex++) {
long band = bands[columnIndex];
if (startY(band) > endY(band)) {
continue;
}
long boundary = boundaries[columnIndex];
boundaries[columnIndex] = boundary(Math.min(startY(boundary), startY(band)), Math.max(endY(boundary), endY(band)));
}
}
static boolean protects(long[] boundaries, int columnIndex, int y) {
if (boundaries == null || columnIndex < 0 || columnIndex >= boundaries.length) {
return false;
@@ -42,6 +42,7 @@ final class HydrologyVegetationSource {
for (HydrologyTier tier : settings.tiers()) {
tiers.put(tier, HydrologyVegetation.Decorators.compile(tier.decorators(), data, "Hydrology tier '" + tier.name() + "' decorators"));
}
tiers.put(settings.tidalTier(), tiers.get(settings.tiers().get(Math.min(1, settings.tiers().size() - 1))));
HydrologyVegetationSource source = new HydrologyVegetationSource(data, dimension, tiers,
HydrologyVegetation.Decorators.compile(settings.ponds().decorators(), data, "Hydrology ponds.decorators"));
source.planted = !source.ponds.empty();
@@ -1405,6 +1405,11 @@ public class IrisComplex implements DataProvider {
return tier == null ? pondMaterials : tier.materials();
}
public boolean isTidalBank(int x, int z) {
WaterRole role = resolveWaterRole(x, z);
return (role == WaterRole.BANK || role == WaterRole.SHORE) && chunkRasterAt(x, z).tier(x & 15, z & 15) == hydrologyRuntime.settings().tidalTier();
}
public HydrologyVegetation.Decorators resolveWaterDecorators(int x, int z) {
if (!waterVegetation.planted()) {
return HydrologyVegetation.Decorators.EMPTY;
@@ -164,8 +164,7 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
getEngine().getWorld().minHeight(),
resolverState.complex,
subterrainPlanner == null ? null : subterrainPlanner.chunkSampler(x, z),
subterrain ? caveCeilings(resolverState.complex, x, z) : null,
subterrain ? inletHeadroom(resolverState.complex, x, z) : null
subterrain ? caveCeilings(resolverState.complex, x, z) : null
);
CarveResolver carveResolver = new CarveResolver(resolutionContext);
terrain.forEachCell(carveResolver::apply);
@@ -263,17 +262,16 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
int minimumY = getEngine().getWorld().minHeight();
SubterrainSurfaceMaterials materials = subterrainMaterials(planner, blockX >> 4, blockZ >> 4);
int[] caveCeilings = caveCeilings(getComplex(), blockX >> 4, blockZ >> 4);
long[] inletHeadroom = inletHeadroom(getComplex(), blockX >> 4, blockZ >> 4);
MantleChunk<Matter> chunk = getEngine().getMantle().getMantle().useChunk(blockX >> 4, blockZ >> 4);
try {
preserveSubterrain(planner, materials, caveCeilings, inletHeadroom, minimumY, blockX, blockZ, output,
preserveSubterrain(planner, materials, caveCeilings, minimumY, blockX, blockZ, output,
(worldX, y, worldZ) -> HydrologyCaveStorage.getIfPresent(chunk, worldX, y, worldZ));
} finally {
chunk.release();
}
}
private void preserveSubterrain(SubterrainPlanner planner, SubterrainSurfaceMaterials materials, int[] caveCeilings, long[] inletHeadroom,
private void preserveSubterrain(SubterrainPlanner planner, SubterrainSurfaceMaterials materials, int[] caveCeilings,
int minimumY, int blockX, int blockZ, Hunk<NativeBlockState> output, HydrologyCells hydrology) {
SubterrainRasterizer.rasterize(planner, blockX >> 4, blockZ >> 4, (worldX, worldY, worldZ, cell) -> {
int y = worldY - minimumY;
@@ -282,7 +280,7 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
}
int x = worldX & 15;
int z = worldZ & 15;
if (!cell.solid() && CaveCeilingMask.masked(caveCeilings, inletHeadroom, PowerOfTwoCoordinates.packLocal16(x, z), y)) {
if (!cell.solid() && caveCeilings != null && y > caveCeilings[PowerOfTwoCoordinates.packLocal16(x, z)]) {
return;
}
if (hydrology.at(worldX, y, worldZ) != null) {
@@ -310,10 +308,6 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
new int[CaveCeilingMask.FIELD * CaveCeilingMask.FIELD], ceilings) ? ceilings : null;
}
private static long[] inletHeadroom(IrisComplex complex, int chunkX, int chunkZ) {
return CaveCeilingMask.headroom(chunkX, chunkZ, complex.getHydrologyRuntime(), new long[256]);
}
private void restoreSubterrainSolids(Hunk<NativeBlockState> output, int chunkX, int chunkZ, boolean preserveFloorSupports,
HydrologyCells hydrology) {
SubterrainPlanner planner = getComplex().getSubterrainPlanner();
@@ -476,7 +470,7 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
CarveOwnership.Owner owner = carveOwner(hydrology, feature,
context.terrainColumns() == null ? null : context.terrainColumns()[columnIndex], y);
if (owner == CarveOwnership.Owner.SUBTERRAIN) {
if (!feature.solid() && CaveCeilingMask.masked(context.caveCeilings(), context.inletHeadroom(), columnIndex, y)) {
if (!feature.solid() && context.caveCeilings() != null && y > context.caveCeilings()[columnIndex]) {
return;
}
context.output().setRaw(localX, y, localZ, SubterrainRasterizer.state(feature));
@@ -566,8 +560,7 @@ public class IrisCarveModifier extends EngineAssignedModifier<NativeBlockState>
int minimumY,
IrisComplex complex,
SubterrainPlanner.ChunkSampler subterrainSampler,
int[] caveCeilings,
long[] inletHeadroom
int[] caveCeilings
) {
}
@@ -50,7 +50,8 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator<NativeBloc
private static final BoundBlockState AIR = BoundBlockState.of("AIR");
private static final BoundBlockState DIRT = BoundBlockState.of("minecraft:dirt");
private static final BoundBlockState NETHERRACK = BoundBlockState.of("minecraft:netherrack");
private static final int SLOT_SEA_LAYERS = 1;
private static final int INLET_SEA_LAYERS = 1;
private static final int TIDAL_BANK_SHALLOW_CUT = 16;
@Getter
private final RNG rng;
@@ -291,7 +292,7 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator<NativeBloc
if (i > he && i <= hf) {
int fdepth = hf - i;
if (seaFloor && fblocks == null) {
fblocks = biome.generateSeaLayers(realX, realZ, rng, role == WaterRole.INLET ? SLOT_SEA_LAYERS : hf - he, data);
fblocks = biome.generateSeaLayers(realX, realZ, rng, role == WaterRole.INLET ? INLET_SEA_LAYERS : hf - he, data);
}
put(i, HydrologyFluidLayerSelector.select(
fblocks,
@@ -316,6 +317,9 @@ public class IrisTerrainNormalActuator extends EngineAssignedActuator<NativeBloc
}
blocks = biome.generateLayers(dimension, realX, realZ, rng,
layerSurfaceY + cut + 1 - bedrockFloor, layerSurfaceY + cut, data, complex);
if (exposeStrata && cut <= TIDAL_BANK_SHALLOW_CUT && complex.isTidalBank(realX, realZ)) {
cut = 0;
}
}
int deepFloor = Math.max(bedrockFloor, layerCeilingY > 0 ? layerCeilingY + 2 : 0);
@@ -40,15 +40,14 @@ final class PackHydrologyValidator {
new RangeField("ponds.seeded.depth", Floor.POSITIVE, true),
new RangeField("ponds.seeded.channelSpacing", Floor.POSITIVE, true),
new RangeField("underground.seaInlets.length", Floor.POSITIVE, true),
new RangeField("underground.seaInlets.halfWidth", Floor.POSITIVE, false),
new RangeField("underground.seaInlets.mouthHalfWidth", Floor.POSITIVE, false),
new RangeField("underground.seaInlets.headHalfWidth", Floor.POSITIVE, false),
new RangeField("underground.seaInlets.depth", Floor.POSITIVE, true),
new RangeField("underground.seaInlets.headroom", Floor.NON_NEGATIVE, true),
new RangeField("underground.seaInlets.chamberRadius", Floor.POSITIVE, true),
new RangeField("underground.cavePools.freeboard", Floor.NON_NEGATIVE, true)
);
private static final List<String> FLUID_REFERENCES = List.of("ponds.fluid", "underground.cavePools.fluid");
private static final IrisHydrologyTier DEFAULT_TIER = new IrisHydrologyTier();
private static final String MANTLE_WATER = "the falling water at waterfalls and cascades, sea inlets and cave pools";
private static final String MANTLE_WATER = "the falling water at waterfalls and cascades and cave pools";
private PackHydrologyValidator() {
}
@@ -68,7 +68,7 @@ final class RiverLimits {
private void inspectUnderground() {
if (settings.underground().seaInlets().enabled()) {
add(ExportLimit.SEA_INLET, hydrology, "", "Sea inlets are not exported: coastal cliffs have no flooded passages");
add(ExportLimit.SEA_INLET, hydrology, "", "Sea inlets are not exported: low coasts have no tidal arms");
}
if (settings.underground().cavePools().enabled() && settings.underground().cavePools().density() > 0.0F) {
add(ExportLimit.CAVE_POOL, hydrology, "", "Cave pools are not exported: cave floors hold no standing water of their own");
@@ -44,8 +44,8 @@ public final class IrisStructureWater implements StructureWater {
static boolean river(WaterRole role) {
return switch (role) {
case CHANNEL, POND, CASCADE, WATERFALL -> true;
case NONE, BANK, SHORE, POND_SHORE, DAM, MOUTH, INLET -> false;
case CHANNEL, POND, CASCADE, WATERFALL, INLET -> true;
case NONE, BANK, SHORE, POND_SHORE, DAM, MOUTH -> false;
};
}
}
@@ -4,11 +4,11 @@ import art.arcane.iris.generation.hydrology.engine.HydrologyPlanPreview;
import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.water.HydrologyTier;
import art.arcane.iris.generation.hydrology.water.Pond;
import art.arcane.iris.generation.hydrology.water.PondMask;
import art.arcane.iris.generation.hydrology.water.Reach;
import art.arcane.iris.generation.hydrology.water.ReachStyle;
import art.arcane.iris.world.history.ChunkGenerationSemantics;
import java.util.Arrays;
@@ -193,36 +193,20 @@ final class WaterMap {
for (Pond lake : plans.lakes()) {
drawMask(lake.mask(), HydrologyFeatureType.LAKE);
}
for (SeaInlet inlet : plans.inlets()) {
checkCancelled();
drawInlet(inlet);
}
}
private void drawInlet(SeaInlet inlet) {
float[] xs = inlet.xs();
float[] zs = inlet.zs();
float[] halfWidth = inlet.halfWidth();
for (int station = 0; station + 1 < xs.length; station++) {
double radius = Math.max(halfWidth[station], halfWidth[station + 1]) + step / 2D;
drawSegment(xs[station], zs[station], xs[station + 1], zs[station + 1], radius, HydrologyFeatureType.SEA_INLET);
}
drawSegment(inlet.chamberX(), inlet.chamberZ(), inlet.chamberX(), inlet.chamberZ(), inlet.chamberRadius() + step / 2D,
HydrologyFeatureType.SEA_INLET);
}
private void drawReach(Reach reach) {
float[] xs = reach.xs();
float[] zs = reach.zs();
float[] halfWidth = reach.halfWidth();
HydrologyFeatureType channel = channel(reach.tier());
HydrologyFeatureType channel = reach.style()[0] == ReachStyle.TIDAL ? HydrologyFeatureType.SEA_INLET : channel(reach.tier());
for (int point = 0; point < xs.length; point++) {
int next = Math.min(point + 1, xs.length - 1);
HydrologyFeatureType type = switch (reach.style()[point]) {
case CASCADE -> HydrologyFeatureType.CASCADE;
case WATERFALL -> HydrologyFeatureType.WATERFALL;
case MOUTH -> HydrologyFeatureType.MOUTH;
case RUN, RIFFLE, POND_OUTLET -> channel;
case RUN, RIFFLE, POND_OUTLET, TIDAL -> channel;
};
double radius = Math.max(halfWidth[point], halfWidth[next]) + step / 2D;
drawSegment(xs[point], zs[point], xs[next], zs[next], radius, type);
@@ -18,8 +18,6 @@ import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
import art.arcane.iris.generation.hydrology.raster.WaterRole;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.underground.SeaInletRasterizer;
import art.arcane.iris.generation.hydrology.water.HydrologyTier;
import art.arcane.iris.generation.biome.IrisBiome;
import art.arcane.iris.generation.terrain.IrisRegion;
@@ -46,6 +44,7 @@ import java.util.Set;
public final class GenerationSemanticCapture {
private static final int CHUNK_SIZE = 16;
private static final String INLET_PROFILE = HydrologyFeatureType.SEA_INLET.key();
private static final Set<HydrologyFeatureType> INLET_TYPES = Set.of(HydrologyFeatureType.SEA_INLET);
private static final long CAVE_POOL_SALT = 0x43415645504f4f4cL;
private GenerationSemanticCapture() {
@@ -160,7 +159,6 @@ public final class GenerationSemanticCapture {
int minimumX = Math.multiplyExact(chunkX, CHUNK_SIZE);
int minimumZ = Math.multiplyExact(chunkZ, CHUNK_SIZE);
int minimumY = engine.getDimension().getMinHeight();
captureInlets(complex, runtime.inlets(chunkX, chunkZ), minimumX, minimumZ, minimumY, semantics);
if (raster.empty()) {
return;
}
@@ -175,14 +173,16 @@ public final class GenerationSemanticCapture {
continue;
}
WaterRole role = complex.getWaterRoleStream().get(blockX, blockZ);
if (!role.wet() || role == WaterRole.INLET) {
if (!role.wet()) {
continue;
}
long id = raster.featureId(localX, localZ);
Set<HydrologyFeatureType> types = role == WaterRole.POND
? standing.computeIfAbsent(id, feature -> runtime.standingWaterTypes(chunkX, chunkZ, feature))
: flowingTypes(runtime, role, raster.tier(localX, localZ));
String fluid = role == WaterRole.MOUTH
Set<HydrologyFeatureType> types = switch (role) {
case POND -> standing.computeIfAbsent(id, feature -> runtime.standingWaterTypes(chunkX, chunkZ, feature));
case INLET -> INLET_TYPES;
default -> flowingTypes(runtime, role, raster.tier(localX, localZ));
};
String fluid = role == WaterRole.INLET ? INLET_PROFILE : role == WaterRole.MOUTH
? reachFluids.computeIfAbsent(id, reach -> runtime.channelFluid(chunkX, chunkZ, reach))
: Objects.requireNonNull(raster.fluid(localX, localZ), "Water column " + blockX + "," + blockZ + " has no fluid profile");
int y = Math.addExact((int) Math.round(complex.getWaterHeadStream().getDouble(blockX, blockZ)), minimumY);
@@ -195,29 +195,6 @@ public final class GenerationSemanticCapture {
}
}
private static void captureInlets(IrisComplex complex, List<SeaInlet> inlets, int minimumX, int minimumZ, int minimumY,
ChunkGenerationSemantics.Builder semantics) {
for (SeaInlet inlet : inlets) {
captureInlet(complex, inlet, minimumX, minimumZ, minimumY, semantics);
}
}
private static void captureInlet(IrisComplex complex, SeaInlet inlet, int minimumX, int minimumZ, int minimumY,
ChunkGenerationSemantics.Builder semantics) {
int[] column = new int[2];
for (int localX = 0; localX < CHUNK_SIZE; localX++) {
for (int localZ = 0; localZ < CHUNK_SIZE; localZ++) {
int blockX = minimumX + localX;
int blockZ = minimumZ + localZ;
if (SeaInletRasterizer.column(inlet, blockX, blockZ, column) && hasFullHydrologyWeight(complex, blockX, blockZ)) {
semantics.addRiverFeature(INLET_PROFILE, HydrologyFeatureType.SEA_INLET, inlet.id(), blockX,
Math.addExact(inlet.waterLevel(), minimumY), blockZ);
return;
}
}
}
}
private static Set<HydrologyFeatureType> flowingTypes(HydrologyRuntime runtime, WaterRole role, HydrologyTier tier) {
return switch (role) {
case CHANNEL -> Set.of(runtime.channelType(tier));
@@ -37,7 +37,8 @@ public class PersistedCodesTest {
ReachStyle.CASCADE, 2,
ReachStyle.WATERFALL, 3,
ReachStyle.POND_OUTLET, 4,
ReachStyle.MOUTH, 5);
ReachStyle.MOUTH, 5,
ReachStyle.TIDAL, 6);
private static final Map<PondKind, Integer> POND_KIND_CODES = Map.of(
PondKind.NATURAL, 0,
PondKind.SEEDED, 1,
@@ -33,7 +33,7 @@ public class IrisHydrologyDefaultsTest {
"lakes": { "enabled": true, "minArea": 65536, "maxArea": 4194304 },
"deformation": { "maxFill": 6, "bankSlope": 0.2, "bankSteepFactor": 3.5, "bankNoise": 0.2, "caveMask": true },
"underground": {
"seaInlets": { "enabled": true, "spacing": 192, "minimumCliffHeight": 8, "length": [64, 256], "halfWidth": [2, 5], "depth": [2, 5], "headroom": [4, 10], "roofClearance": 6, "chamberRadius": [6, 12] },
"seaInlets": { "enabled": true, "spacing": 160, "length": [64, 256], "maximumBankHeight": 44, "mouthHalfWidth": [13, 15], "headHalfWidth": [2.5, 3], "taper": 1.4, "widthVariation": 0.18, "meanderWidth": 4, "depth": [2, 5], "bankBand": 32, "bankStyle": "SMOOTH" },
"cavePools": { "enabled": true, "density": 0.15, "minArea": 6, "maxArea": 400, "maxDepth": 4, "radius": 15, "freeboard": [0, 1], "fluid": "water" }
},
"fluids": [ { "name": "water", "palette": { "palette": [ { "block": "minecraft:water" } ] } } ],
@@ -222,12 +222,12 @@ public class HydrologyFeatureSearchTest {
WindowPlan window(WindowKey key, List<RegionPlan> plans) {
calls.incrementAndGet();
if (channelTier != null && key.equals(new WindowKey(0, 0))) {
return new WindowPlan(key, List.of(channel(channelTier)), List.of(), List.of());
return new WindowPlan(key, List.of(channel(channelTier)), List.of());
}
if (Math.max(Math.abs(key.wx()), Math.abs(key.wz())) > openRing) {
hold();
}
return new WindowPlan(key, List.of(), List.of(), List.of());
return new WindowPlan(key, List.of(), List.of());
}
private void hold() {
@@ -16,8 +16,6 @@ import art.arcane.iris.generation.hydrology.query.HydrologyFeatureRef;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
import art.arcane.iris.generation.hydrology.raster.WaterRole;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.underground.SeaInletRasterizer;
import art.arcane.iris.generation.hydrology.water.Pond;
import art.arcane.iris.generation.hydrology.water.PondKind;
import art.arcane.iris.generation.hydrology.water.PondMask;
@@ -331,48 +329,23 @@ public class HydrologyRuntimeTest {
}
@Test(timeout = 180_000L)
public void seaInletsReachChunksPastTheirOwnerAndFailClosedOnTheMainThread() throws Exception {
AtomicBoolean main = new AtomicBoolean(true);
public void seaInletsAreSearchedAndPreviewedAsTidalReaches() throws Exception {
FakePlanners planners = new FakePlanners(settings());
HydrologyRuntime runtime = runtime(planners, main::get);
CountDownLatch gate = new CountDownLatch(1);
planners.gate = gate;
assertThrows(IllegalStateException.class, () -> runtime.inlets(68, 25));
gate.countDown();
main.set(false);
List<SeaInlet> tail = runtime.inlets(68, 25);
assertEquals(List.of(FakePlanners.inlet()), tail);
assertEquals(new WindowKey(2, 0), WindowKey.containing(68 << 4, 25 << 4));
assertEquals(tail, runtime.inlets(62, 25));
assertEquals(List.of(), runtime.inlets(75, 25));
assertEquals(List.of(), runtime.inlets(68, 30));
assertEquals(List.of(), runtime.inlets(0, 0));
main.set(true);
assertEquals(tail, runtime.inlets(68, 25));
main.set(false);
Map<Long, HydrologyCaveCell> written = new ConcurrentHashMap<>();
MantleWriter writer = mock(MantleWriter.class);
doAnswer(call -> {
HydrologyCaveCell cell = call.getArgument(3);
int x = call.getArgument(0);
assertEquals(68, x >> 4);
written.put(((long) x << 40) ^ ((long) (int) call.getArgument(2) << 20) ^ (int) call.getArgument(1), cell);
return null;
}).when(writer).setData(anyInt(), anyInt(), anyInt(), any(HydrologyCaveCell.class));
new SeaInletRasterizer().write(tail.getFirst(), 68, 25, writer, HydrologyCaveCell.SEA_FLUID, SeaInletRasterizer.SubterrainFluid.NOWHERE,
SeaInletRasterizer.HistoricalChunks.NONE);
assertTrue("the chunk past the owner window writes inlet water",
written.values().stream().anyMatch(cell -> cell.action() == HydrologyCaveAction.WET_SOURCE));
HydrologyRuntime runtime = runtime(planners, () -> false);
HydrologyFeatureRef nearest = runtime.nearestFeature(1050, 405, HydrologyFeatureQuery.of(HydrologyFeatureType.SEA_INLET), 512, ANY,
RUNNING).orElseThrow();
assertEquals(new HydrologyFeatureRef(INLET, HydrologyFeatureType.SEA_INLET, 1048, 40, 400), nearest);
HydrologyFeatureRef fromInland = runtime.nearestFeature(960, 400, HydrologyFeatureQuery.of(HydrologyFeatureType.SEA_INLET), 512, ANY,
RUNNING).orElseThrow();
assertEquals("a search lands in the half of the arm toward the sea", new HydrologyFeatureRef(INLET, HydrologyFeatureType.SEA_INLET, 1040, 40, 400), fromInland);
HydrologyFeatureRef fromTheSea = runtime.nearestFeature(1200, 400, HydrologyFeatureQuery.of(HydrologyFeatureType.SEA_INLET), 512, ANY,
RUNNING).orElseThrow();
assertEquals("a search lands short of the open sea", new HydrologyFeatureRef(INLET, HydrologyFeatureType.SEA_INLET, 1072, 40, 400), fromTheSea);
assertEquals("a tidal reach is not a river mouth", Optional.empty(),
runtime.nearestFeature(1050, 405, HydrologyFeatureQuery.of(HydrologyFeatureType.MOUTH), 128, ANY, RUNNING));
assertEquals(Optional.empty(),
runtime.nearestFeature(0, 0, HydrologyFeatureQuery.of(HydrologyFeatureType.SEA_INLET), 64, ANY, RUNNING));
assertEquals(List.of(FakePlanners.inlet()), runtime.planPreview(900, 300, 1100, 500).inlets());
assertEquals(List.of(), FakeHydrology.disabled().inlets(0, 0));
assertEquals(List.of(INLET), runtime.planPreview(900, 300, 1100, 500).reaches().stream().map(Reach::id).filter(id -> id == INLET).toList());
}
@Test(timeout = 180_000L)
@@ -548,7 +521,7 @@ public class HydrologyRuntimeTest {
}
assertTrue("a released cap admits new previews", preview.complete());
assertEquals(2, preview.ponds().size());
assertEquals(1, preview.reaches().size());
assertEquals(2, preview.reaches().size());
}
@Test(timeout = 180_000L)
@@ -1306,15 +1279,15 @@ public class HydrologyRuntimeTest {
throw new IllegalStateException("window planner exploded");
}
return new WindowPlan(key, List.of(river()), List.of(pond(POND, PondKind.NATURAL, 70, 2, 2, 8),
pond(POND + 1, PondKind.SEEDED, 70, 296, 296, 3)), List.of());
pond(POND + 1, PondKind.SEEDED, 70, 296, 296, 3)));
}
if (key.equals(new WindowKey(1, 0))) {
return new WindowPlan(key, List.of(), List.of(), List.of(inlet()));
return new WindowPlan(key, List.of(tidal()), List.of());
}
if (key.equals(new WindowKey(3, 0))) {
return new WindowPlan(key, List.of(), List.of(pond(FAR_POND, PondKind.NATURAL, 75, 1700, 100, 3)), List.of());
return new WindowPlan(key, List.of(), List.of(pond(FAR_POND, PondKind.NATURAL, 75, 1700, 100, 3)));
}
return new WindowPlan(key, List.of(), List.of(), List.of());
return new WindowPlan(key, List.of(), List.of());
}
private void pass() {
@@ -1335,21 +1308,23 @@ public class HydrologyRuntimeTest {
}
}
private static SeaInlet inlet() {
int stations = 13;
float[] xs = new float[stations];
float[] zs = new float[stations];
float[] halfWidth = new float[stations];
int[] floor = new int[stations];
int[] ceiling = new int[stations];
for (int station = 0; station < stations; station++) {
xs[station] = 992f + station * 8f;
zs[station] = 400f;
halfWidth[station] = 3f;
floor[station] = 37;
ceiling[station] = 45;
private Reach tidal() {
int points = 13;
float[] xs = new float[points];
float[] zs = new float[points];
int[] grade = new int[points];
float[] halfWidth = new float[points];
float[] depth = new float[points];
ReachStyle[] style = new ReachStyle[points];
for (int point = 0; point < points; point++) {
xs[point] = 992f + point * 8f;
zs[point] = 400f;
grade[point] = 40;
halfWidth[point] = 3f;
depth[point] = 3f;
style[point] = ReachStyle.TIDAL;
}
return new SeaInlet(INLET, xs, zs, halfWidth, 40, floor, ceiling, 1088, 400, 6);
return new Reach(INLET, settings.tidalTier(), 0L, xs, zs, grade, halfWidth, depth, style, 0f);
}
private Reach river() {
@@ -317,7 +317,7 @@ public class HydrologyPlanCacheTest {
WindowKey key = new WindowKey(5, -3);
HydrologyPlanCache cache = new HydrologyPlanCache(planners.settings, planners::region, (window, regions) -> {
Reach reach = planners.window(window, regions).reaches().get(0);
return new WindowPlan(window, List.of(reach, reach), List.of(), List.of());
return new WindowPlan(window, List.of(reach, reach), List.of());
}, pool(1), () -> false);
caches.add(cache);
Throwable failure = failureOf(() -> cache.window(key));
@@ -1174,7 +1174,7 @@ public class HydrologyPlanCacheTest {
throw new AssertionError("Window " + key + " got region plans " + given + ", needs " + needed);
}
hook.accept(key);
return new WindowPlan(key, List.of(reach(key)), List.of(), List.of());
return new WindowPlan(key, List.of(reach(key)), List.of());
}
private Reach reach(WindowKey key) {
@@ -4,7 +4,6 @@ import art.arcane.iris.generation.hydrology.config.IrisBankStyle;
import art.arcane.iris.generation.hydrology.config.IrisHydrology;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyMaterials;
import art.arcane.iris.generation.hydrology.grid.HeightLattice;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.water.HydrologyTier;
import art.arcane.iris.generation.hydrology.water.Pond;
import art.arcane.iris.generation.hydrology.water.PondKind;
@@ -47,7 +46,7 @@ public class HydrologyPlanCodecTest {
0577617465720000001c000000060000000000000007020000004400000040ffffffec0000001042898000fffffffc00
00000800000004000000000000000000000000000000000000002900000002000000046c617661ffffffea0000000e00
0000000000000803000000500000003c00000040ffffffc042a10000fffffffc00000008000000040000000000000000
00000000ffffffffffffffff00000000ffffffff0000003cffffffc400000000
00000000ffffffffffffffff00000000ffffffff0000003cffffffc4
""";
@Test
@@ -60,7 +59,7 @@ public class HydrologyPlanCodecTest {
new int[]{Integer.MIN_VALUE, -64, 0, 63, 319, Integer.MAX_VALUE},
new float[]{0.5f, 1f, 2.75f, NAN_PAYLOAD, 12f, 0f},
new float[]{1f, Float.POSITIVE_INFINITY, 0.4f, 1e-42f, -0f, 3f},
ReachStyle.values(), NEGATIVE_NAN);
Arrays.copyOf(ReachStyle.values(), 6), NEGATIVE_NAN);
Reach plain = new Reach(77L, tiers.get(0), -9_000_000_000L, new float[]{10f, 11.5f}, new float[]{-3f, -2.5f}, new int[]{70, 69},
new float[]{0.5f, 0.75f}, new float[]{1f, 1f}, new ReachStyle[]{ReachStyle.RUN, ReachStyle.MOUTH}, 1501.25f).withStraightFalls(new int[]{0});
List<Pond> ponds = new ArrayList<>();
@@ -70,12 +69,7 @@ public class HydrologyPlanCodecTest {
index == 0 ? NAN_PAYLOAD : 61.5f + index, mask(index), index == 1 ? -1L : 77L, index * 2, fluid(index),
-650 + index, 880 + index));
}
SeaInlet oddInlet = new SeaInlet(-5_000_000_000L, new float[]{-0f, NAN_PAYLOAD, 1e-40f}, new float[]{NEGATIVE_NAN, 3.5f, -0f},
new float[]{Float.MIN_VALUE, 5f, 2.25f}, 63, new int[]{Integer.MIN_VALUE, 60, 62}, new int[]{63, Integer.MAX_VALUE, 70},
-12, 40, 9);
SeaInlet plainInlet = new SeaInlet(91L, new float[]{8f, 16f}, new float[]{-24f, -16f}, new float[]{5f, 4f}, 306,
new int[]{303, 302}, new int[]{340, 312}, 16, -16, 6);
WindowPlan window = new WindowPlan(new WindowKey(-3, 7), List.of(odd, plain), ponds, List.of(oddInlet, plainInlet));
WindowPlan window = new WindowPlan(new WindowKey(-3, 7), List.of(odd, plain), ponds);
WindowPlan decodedWindow = HydrologyPlanCodec.decodeWindow(settings, HydrologyPlanCodec.encode(settings, window)).orElseThrow();
assertBitExact(window, decodedWindow, tiers);
@@ -85,7 +79,7 @@ public class HydrologyPlanCodecTest {
assertReachesBitExact(region.majorReaches(), decodedRegion.majorReaches(), tiers);
assertPondsBitExact(region.lakes(), decodedRegion.lakes());
WindowPlan empty = new WindowPlan(new WindowKey(Integer.MIN_VALUE, Integer.MAX_VALUE), List.of(), List.of(), List.of());
WindowPlan empty = new WindowPlan(new WindowKey(Integer.MIN_VALUE, Integer.MAX_VALUE), List.of(), List.of());
assertEquals(empty, HydrologyPlanCodec.decodeWindow(settings, HydrologyPlanCodec.encode(settings, empty)).orElseThrow());
SyntheticTerrain terrain = SyntheticTerrain.openFractal(SEED);
@@ -105,6 +99,18 @@ public class HydrologyPlanCodecTest {
assertBitExact(planned, HydrologyPlanCodec.decodeWindow(settings, HydrologyPlanCodec.encode(settings, planned)).orElseThrow(), tiers);
}
@Test
public void tidalReachesRoundTripOnTheTidalTier() {
HydrologySettings settings = settings(new IrisHydrology());
int sea = settings.seaLevel();
Reach tidal = new Reach(404L, settings.tidalTier(), 0L, new float[]{0f, 8f, 16f}, new float[]{0f, 4f, 2f}, new int[]{sea, sea, sea},
new float[]{2f, 6f, 12f}, new float[]{1f, 4f, 1f}, new ReachStyle[]{ReachStyle.TIDAL, ReachStyle.TIDAL, ReachStyle.TIDAL}, 0f);
WindowPlan window = new WindowPlan(new WindowKey(0, 0), List.of(tidal), List.of());
WindowPlan decoded = HydrologyPlanCodec.decodeWindow(settings, HydrologyPlanCodec.encode(settings, window)).orElseThrow();
assertEquals(window, decoded);
assertSame(settings.tidalTier(), decoded.reaches().get(0).tier());
}
@Test
public void codecDecodesMismatchedOrCorruptDataAsEmpty() {
HydrologySettings settings = settings(new IrisHydrology());
@@ -112,9 +118,7 @@ public class HydrologyPlanCodecTest {
Reach reach = new Reach(5L, tier, -1L, new float[]{1f, 2f, 3f}, new float[]{4f, 5f, 6f}, new int[]{70, 69, 68},
new float[]{1f, 1f, 1.5f}, new float[]{1f, 1f, 1f}, new ReachStyle[]{ReachStyle.RUN, ReachStyle.RIFFLE, ReachStyle.MOUTH}, 2000f);
Pond pond = new Pond(9L, PondKind.SEEDED, 66, 62, 10, 12, 66.5f, mask(3), 5L, 0, "water", 11, 13);
SeaInlet inlet = new SeaInlet(12L, new float[]{8f, 16f, 24f}, new float[]{0f, 0f, 8f}, new float[]{5f, 4f, 3f}, 63,
new int[]{60, 61, 59}, new int[]{90, 68, 70}, 24, 8, 7);
WindowPlan window = new WindowPlan(new WindowKey(1, 2), List.of(reach), List.of(pond), List.of(inlet));
WindowPlan window = new WindowPlan(new WindowKey(1, 2), List.of(reach), List.of(pond));
byte[] encoded = HydrologyPlanCodec.encode(settings, window);
HydrologySettings reseeded = HydrologySettings.compile(new IrisHydrology(), SEED + 1L, SyntheticTerrain.SEA_LEVEL,
@@ -147,7 +151,7 @@ public class HydrologyPlanCodecTest {
Reach stray = new Reach(6L, foreign, -1L, new float[]{1f, 2f}, new float[]{1f, 2f}, new int[]{1, 1}, new float[]{1f, 1f},
new float[]{1f, 1f}, new ReachStyle[]{ReachStyle.RUN, ReachStyle.RUN}, 1f);
try {
HydrologyPlanCodec.encode(settings, new WindowPlan(new WindowKey(0, 0), List.of(stray), List.of(), List.of()));
HydrologyPlanCodec.encode(settings, new WindowPlan(new WindowKey(0, 0), List.of(stray), List.of()));
fail("a tier outside the settings has no index");
} catch (IllegalArgumentException expected) {
assertTrue(expected.getMessage(), expected.getMessage().contains("foreign"));
@@ -174,21 +178,13 @@ public class HydrologyPlanCodecTest {
new Pond(6L, PondKind.SEEDED, 74, 71, 30, 8, 74.25f, mask(2), -1L, 1, "water", 28, 6),
new Pond(7L, PondKind.CHAINED, 68, 64, -20, 16, 68.75f, mask(0), 41L, 2, "lava", -22, 14),
new Pond(8L, PondKind.LAKE, 80, 60, 64, -64, 80.5f, mask(0), -1L, 0, null, 60, -60));
return new WindowPlan(new WindowKey(2, -3), List.of(reach), ponds, List.of());
return new WindowPlan(new WindowKey(2, -3), List.of(reach), ponds);
}
private static void assertBitExact(WindowPlan expected, WindowPlan actual, List<HydrologyTier> tiers) {
assertEquals(expected, actual);
assertReachesBitExact(expected.reaches(), actual.reaches(), tiers);
assertPondsBitExact(expected.ponds(), actual.ponds());
assertEquals(expected.inlets().size(), actual.inlets().size());
for (int index = 0; index < expected.inlets().size(); index++) {
SeaInlet want = expected.inlets().get(index);
SeaInlet got = actual.inlets().get(index);
assertArrayEquals(rawBits(want.xs()), rawBits(got.xs()));
assertArrayEquals(rawBits(want.zs()), rawBits(got.zs()));
assertArrayEquals(rawBits(want.halfWidth()), rawBits(got.halfWidth()));
}
}
private static void assertReachesBitExact(List<Reach> expected, List<Reach> actual, List<HydrologyTier> tiers) {
@@ -225,7 +225,7 @@ public class HydrologyPlanStoreTest {
new ReachStyle[]{ReachStyle.RUN, ReachStyle.CASCADE, ReachStyle.RUN}, 1600f);
Pond pond = new Pond(key.wz() * 17L - key.wx(), PondKind.NATURAL, 72, 68, (int) x, (int) z, 72.25f,
new PondMask((int) x, (int) z, 4, 3, 2, new long[]{0b101101L}), reach.id(), 0, "water", (int) x + 4, (int) z);
return new WindowPlan(key, List.of(reach), List.of(pond), List.of());
return new WindowPlan(key, List.of(reach), List.of(pond));
}
private static HydrologySettings settings(long seed) {
@@ -4,9 +4,11 @@ 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.IrisFluidProfile;
import art.arcane.iris.generation.hydrology.config.IrisBankStyle;
import art.arcane.iris.generation.hydrology.config.IrisHydrology;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyTier;
import art.arcane.iris.generation.hydrology.config.IrisHydrologyMaterials;
import art.arcane.iris.generation.hydrology.config.IrisSeaInlets;
import art.arcane.iris.generation.hydrology.water.HydrologyTier;
import art.arcane.iris.generation.terrain.IrisMaterialPalette;
import art.arcane.iris.pack.loading.IrisData;
@@ -21,6 +23,7 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -35,7 +38,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 = -2359553697125315860L;
private static final long DEFAULT_FINGERPRINT = 8483795183515434045L;
@Test
public void densityIsBoundedAndChangesThePlanIdentity() {
@@ -708,22 +711,71 @@ public class HydrologySettingsTest {
assertTrue(failure.getMessage(), failure.getMessage().contains(field));
}
@Test
public void seaInletDefaultsDescribeAFunnelReachingInland() {
HydrologySettings.SeaInlets inlets = compile(new IrisHydrology()).underground().seaInlets();
assertTrue(inlets.enabled());
assertEquals(160, inlets.spacing());
assertEquals(new HydrologySettings.IntRange(64, 256), inlets.length());
assertEquals(44, inlets.maximumBankHeight());
assertEquals(new HydrologySettings.FloatRange(13f, 15f), inlets.mouthHalfWidth());
assertEquals(new HydrologySettings.FloatRange(2.5f, 3f), inlets.headHalfWidth());
assertEquals(1.4f, inlets.taper(), 0f);
assertEquals(0.18f, inlets.widthVariation(), 1e-6f);
assertEquals(4f, inlets.meanderWidth(), 0f);
assertEquals(new HydrologySettings.IntRange(2, 5), inlets.depth());
assertEquals(32, inlets.bankBand());
assertEquals(IrisBankStyle.SMOOTH, inlets.bankStyle());
}
@Test
public void seaInletRangesAreBounded() {
compile(inlets(new KList<>(1D, 16D), new KList<>(2, 16)));
for (IrisHydrology rejected : List.of(inlets(new KList<>(0.5D, 5D), new KList<>(2, 5)), inlets(new KList<>(2D, 17D), new KList<>(2, 5)),
inlets(new KList<>(2D, 5D), new KList<>(2, 17)), inlets(new KList<>(2D, 5D), new KList<>(1, 5)))) {
IllegalArgumentException failure = assertThrows(IllegalArgumentException.class, () -> compile(rejected));
compile(inlets(config -> config.setMouthHalfWidth(new KList<>(8D, 32D)).setHeadHalfWidth(new KList<>(1D, 8D)).setDepth(new KList<>(2, 16))));
List<IrisHydrology> rejected = List.of(
inlets(config -> config.setMouthHalfWidth(new KList<>(1.5D, 14D)).setHeadHalfWidth(new KList<>(1D, 1.5D))),
inlets(config -> config.setMouthHalfWidth(new KList<>(10D, 33D))),
inlets(config -> config.setHeadHalfWidth(new KList<>(0.5D, 3D))),
inlets(config -> config.setHeadHalfWidth(new KList<>(2D, 9D))),
inlets(config -> config.setDepth(new KList<>(2, 17))),
inlets(config -> config.setDepth(new KList<>(1, 5))),
inlets(config -> config.setMaximumBankHeight(1)),
inlets(config -> config.setMaximumBankHeight(129)),
inlets(config -> config.setTaper(0.4D)),
inlets(config -> config.setTaper(4.1D)),
inlets(config -> config.setWidthVariation(-0.1D)),
inlets(config -> config.setWidthVariation(0.6D)),
inlets(config -> config.setMeanderWidth(0.5D)),
inlets(config -> config.setMeanderWidth(17D)),
inlets(config -> config.setBankBand(3)),
inlets(config -> config.setBankBand(65)));
for (IrisHydrology config : rejected) {
IllegalArgumentException failure = assertThrows(IllegalArgumentException.class, () -> compile(config));
assertTrue(failure.getMessage(), failure.getMessage().contains("underground.seaInlets"));
}
IllegalArgumentException belowWorld = assertThrows(IllegalArgumentException.class,
() -> HydrologySettings.compile(inlets(new KList<>(2D, 5D), new KList<>(2, 16)), SEED, MIN_Y + 18, MIN_Y, MAX_Y));
() -> HydrologySettings.compile(inlets(config -> config.setDepth(new KList<>(2, 16))), SEED, MIN_Y + 16, MIN_Y, MAX_Y));
assertTrue(belowWorld.getMessage(), belowWorld.getMessage().contains("world bottom"));
}
private static IrisHydrology inlets(KList<Double> halfWidth, KList<Integer> depth) {
@Test
public void seaInletMouthMustBeWiderThanItsHead() {
IllegalArgumentException failure = assertThrows(IllegalArgumentException.class,
() -> compile(inlets(config -> config.setMouthHalfWidth(new KList<>(4D, 14D)).setHeadHalfWidth(new KList<>(2D, 5D)))));
assertTrue(failure.getMessage(), failure.getMessage().contains("mouthHalfWidth"));
}
@Test
public void overLongSeaInletsFailAtCompile() {
compile(inlets(config -> config.setLength(new KList<>(64, 447)).setMouthHalfWidth(new KList<>(11D, 16D)).setBankBand(24)));
IllegalArgumentException failure = assertThrows(IllegalArgumentException.class,
() -> compile(inlets(config -> config.setLength(new KList<>(64, 512)))));
assertTrue(failure.getMessage(), failure.getMessage().contains("underground.seaInlets"));
assertTrue(failure.getMessage(), failure.getMessage().contains(Integer.toString(WindowKey.SIZE)));
}
private static IrisHydrology inlets(Consumer<IrisSeaInlets> tweak) {
IrisHydrology config = new IrisHydrology();
config.getUnderground().getSeaInlets().setHalfWidth(halfWidth).setDepth(depth);
tweak.accept(config.getUnderground().getSeaInlets());
return config;
}
@@ -8,7 +8,6 @@ import art.arcane.iris.generation.hydrology.raster.ChunkRasterizer;
import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
import art.arcane.iris.generation.hydrology.raster.ReachIndex;
import art.arcane.iris.generation.hydrology.raster.WaterRole;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.water.Pond;
import art.arcane.iris.generation.hydrology.water.PondPlanner;
import art.arcane.iris.generation.hydrology.water.Reach;
@@ -33,7 +32,6 @@ final class PlannedScene {
private final Function<RegionKey, RegionPlan> regions;
private final List<Reach> reaches;
private final List<Pond> ponds;
private final List<SeaInlet> inlets;
private final ChunkRasterizer rasterizer;
private final Map<WindowKey, IndexedWindow> windows = new HashMap<>();
private final Map<Long, ChunkWaterRaster> rasters = new HashMap<>();
@@ -49,15 +47,12 @@ final class PlannedScene {
this.rasterizer = new ChunkRasterizer(settings, ChannelFluids.TIER);
List<Reach> ownedReaches = new ArrayList<>();
List<Pond> ownedPonds = new ArrayList<>();
List<SeaInlet> ownedInlets = new ArrayList<>();
for (WindowPlan plan : plans.values()) {
ownedReaches.addAll(plan.reaches());
ownedPonds.addAll(plan.ponds());
ownedInlets.addAll(plan.inlets());
}
this.reaches = List.copyOf(ownedReaches);
this.ponds = List.copyOf(ownedPonds);
this.inlets = List.copyOf(ownedInlets);
}
static PlannedScene plan(SyntheticTerrain terrain, HydrologySettings settings, int windowsX, int windowsZ) {
@@ -87,7 +82,7 @@ final class PlannedScene {
requireOrigin(origin, WindowKey.containing(pond.floorX(), pond.floorZ()), pond);
}
Map<WindowKey, WindowPlan> plans = new LinkedHashMap<>();
plans.put(origin, new WindowPlan(origin, reaches, ponds, List.of()));
plans.put(origin, new WindowPlan(origin, reaches, ponds));
return new PlannedScene(terrain, settings, 1, 1, plans, key -> new RegionPlan(key, List.of(), List.of()));
}
@@ -123,10 +118,6 @@ final class PlannedScene {
return ponds;
}
List<SeaInlet> inlets() {
return inlets;
}
int minX() {
return 0;
}
@@ -184,7 +175,7 @@ final class PlannedScene {
private IndexedWindow window(WindowKey key) {
return windows.computeIfAbsent(key, ignored -> {
WindowPlan plan = plans.getOrDefault(key, new WindowPlan(key, List.of(), List.of(), List.of()));
WindowPlan plan = plans.getOrDefault(key, new WindowPlan(key, List.of(), List.of()));
return new IndexedWindow(plan, ReachIndex.build(key, plan.reaches(), plan.ponds()));
});
}
@@ -58,6 +58,16 @@ final class SyntheticTerrain implements HydrologyTerrainSource {
return new SyntheticTerrain(natural, rainfall, streamsBlocked, area, land);
}
SyntheticTerrain rising(double fromX, double slope) {
DoubleBinaryOperator inner = natural;
return new SyntheticTerrain((x, z) -> inner.applyAsDouble(x, z) + Math.max(0D, x - fromX) * slope, rainfall, streamsBlocked, pondsBlocked, land);
}
SyntheticTerrain steppedAbove(double fromZ, double rise) {
DoubleBinaryOperator inner = natural;
return new SyntheticTerrain((x, z) -> inner.applyAsDouble(x, z) + (z >= fromZ ? rise : 0D), rainfall, streamsBlocked, pondsBlocked, land);
}
SyntheticTerrain lowered(double depth) {
DoubleBinaryOperator inner = natural;
return new SyntheticTerrain((x, z) -> inner.applyAsDouble(x, z) - depth, rainfall, streamsBlocked, pondsBlocked, land);
@@ -278,6 +288,20 @@ final class SyntheticTerrain implements HydrologyTerrainSource {
return new SyntheticTerrain((x, z) -> x < coastX ? OCEAN_FLOOR : SEA_LEVEL + 30D + 0.05D * (x - coastX) + 3D * Math.sin(z / 40D));
}
static SyntheticTerrain lowCoast(double coastX) {
return new SyntheticTerrain((x, z) -> {
double inland = x - coastX;
return inland < 0D ? OCEAN_FLOOR : SEA_LEVEL + 2D + 0.06D * inland + 2.5D * Math.sin(z / 37D) * Math.min(1D, inland / 32D);
});
}
static SyntheticTerrain lowIsland(double centreX, double centreZ, double coastRadius, double peakAboveSea) {
return new SyntheticTerrain((x, z) -> {
double radius = Math.hypot(x - centreX, z - centreZ);
return radius > coastRadius ? OCEAN_FLOOR : SEA_LEVEL + 1D + peakAboveSea * (1D - radius / coastRadius);
});
}
static SyntheticTerrain seaStrip(double stripMinX, double stripWidth) {
return new SyntheticTerrain((x, z) -> x >= stripMinX && x < stripMinX + stripWidth ? SEA_LEVEL - 2D : valleySlope(x, z));
}
@@ -0,0 +1,414 @@
package art.arcane.iris.generation.hydrology.plan;
import art.arcane.iris.generation.hydrology.config.IrisHydrology;
import art.arcane.iris.generation.hydrology.grid.DemGrid;
import art.arcane.iris.generation.hydrology.grid.HeightLattice;
import art.arcane.iris.generation.hydrology.grid.HydrologySampleBuffer;
import art.arcane.iris.generation.hydrology.water.Pond;
import art.arcane.iris.generation.hydrology.water.PondKind;
import art.arcane.iris.generation.hydrology.water.PondMask;
import art.arcane.iris.generation.hydrology.water.Reach;
import art.arcane.iris.generation.hydrology.water.ReachStyle;
import art.arcane.iris.generation.hydrology.water.ShapedNetwork;
import art.arcane.iris.generation.hydrology.water.TidalPlanner;
import art.arcane.volmlib.util.collection.KList;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class TidalPlannerTest {
private static final long SEED = 1337L;
private static final int SEA = SyntheticTerrain.SEA_LEVEL;
private static final double COAST_X = 300D;
private static final ShapedNetwork NOTHING = new ShapedNetwork(List.of(), List.of());
private static final List<WindowKey> COAST_WINDOWS = List.of(new WindowKey(0, 0), new WindowKey(0, 1), new WindowKey(0, -1), new WindowKey(1, 0));
private static HydrologySettings settings() {
return settings(new IrisHydrology());
}
private static HydrologySettings settings(IrisHydrology config) {
return HydrologySettings.compile(config, SEED, SEA, SyntheticTerrain.MIN_Y, SyntheticTerrain.MAX_Y);
}
private static Fixture planner(HydrologySettings settings, SyntheticTerrain terrain) {
return new Fixture(settings, new HeightLattice(terrain, WindowPlanner.FINE_CELL, false, 1 << 21));
}
private static List<Reach> arms(Fixture planner) {
return arms2(planner, COAST_WINDOWS.toArray(new WindowKey[0]));
}
private record Fixture(TidalPlanner tidal, HeightLattice fine) {
Fixture(HydrologySettings settings, HeightLattice fine) {
this(new TidalPlanner(settings, fine), fine);
}
List<Reach> plan(WindowKey window, ShapedNetwork network) {
int span = 3 * WindowKey.SIZE / WindowPlanner.CELL;
int originX = (window.wx() - 1) * WindowKey.SIZE;
int originZ = (window.wz() - 1) * WindowKey.SIZE;
HydrologySampleBuffer samples = new HydrologySampleBuffer(span * span);
fine.fill(originX / WindowPlanner.FINE_CELL, originZ / WindowPlanner.FINE_CELL, span, span, WindowPlanner.CELL / WindowPlanner.FINE_CELL, samples);
DemGrid natural = new DemGrid(originX, originZ, WindowPlanner.CELL, span, span);
System.arraycopy(samples.height(), 0, natural.values(), 0, span * span);
return tidal.plan(window, natural, samples, network);
}
}
private static float length(Reach reach) {
float length = 0f;
for (int point = 1; point < reach.xs().length; point++) {
length += (float) Math.hypot(reach.xs()[point] - reach.xs()[point - 1], reach.zs()[point] - reach.zs()[point - 1]);
}
return length;
}
private static int last(Reach reach) {
return reach.xs().length - 1;
}
@Test
public void lowCoastHoldsWholeTidalReachesAtSeaLevelThatDrainToTheSea() {
HydrologySettings settings = settings();
List<Reach> arms = arms(planner(settings, SyntheticTerrain.lowCoast(COAST_X)));
assertTrue("arms on the low coast " + arms.size(), arms.size() >= 3);
for (Reach arm : arms) {
assertEquals(settings.tidalTier(), arm.tier());
assertEquals(0L, arm.downstreamId());
for (int point = 0; point < arm.xs().length; point++) {
assertEquals(arm + " point " + point, ReachStyle.TIDAL, arm.style()[point]);
assertEquals(arm + " point " + point, SEA, arm.grade()[point]);
}
assertTrue(arm + " starts inland of the coast", arm.xs()[0] > COAST_X + 16f);
assertTrue(arm + " ends in the sea", arm.xs()[last(arm)] < COAST_X);
assertTrue(arm + " length " + length(arm), length(arm) >= settings.underground().seaInlets().length().min());
WindowPlanner.requireSeaConnectedHeads(new WindowPlan(WindowKey.containing((int) Math.floor(arm.xs()[last(arm)]), (int) Math.floor(arm.zs()[last(arm)])),
List.of(arm), List.of()), SEA);
}
}
@Test
public void armsBelongToTheWindowOfTheirMouth() {
Fixture planner = planner(settings(), SyntheticTerrain.lowCoast(COAST_X));
for (WindowKey window : COAST_WINDOWS) {
for (Reach arm : planner.plan(window, NOTHING)) {
assertEquals(window, WindowKey.containing((int) Math.floor(arm.xs()[last(arm)]), (int) Math.floor(arm.zs()[last(arm)])));
}
}
}
@Test
public void tallCoastsHoldNoArms() {
assertTrue(arms(planner(settings(), SyntheticTerrain.cliffCoast(COAST_X).lowered(-30D))).isEmpty());
}
@Test
public void disabledAndZeroDensityPlanNoArms() {
IrisHydrology disabled = new IrisHydrology();
disabled.getUnderground().getSeaInlets().setEnabled(false);
assertTrue(arms(planner(settings(disabled), SyntheticTerrain.lowCoast(COAST_X))).isEmpty());
assertTrue(arms(planner(settings(new IrisHydrology().setDensity(0D)), SyntheticTerrain.lowCoast(COAST_X))).isEmpty());
}
@Test
public void densityThinsSites() {
List<Reach> full = arms(planner(settings(), SyntheticTerrain.lowCoast(COAST_X)));
List<Reach> half = arms(planner(settings(new IrisHydrology().setDensity(0.5D)), SyntheticTerrain.lowCoast(COAST_X)));
assertFalse(half.isEmpty());
assertTrue(half.size() < full.size());
}
@Test
public void streamBlockedGroundHoldsNoArms() {
SyntheticTerrain blocked = SyntheticTerrain.lowCoast(COAST_X).withStreamsBlocked((x, z) -> true);
assertTrue(arms(planner(settings(), blocked)).isEmpty());
}
@Test
public void armsWalkAwayFromTheSeaOnAPeninsulaInsteadOfAlongTheShore() {
SyntheticTerrain island = SyntheticTerrain.lowIsland(800D, 800D, 420D, 24D);
for (Reach arm : arms2(planner(settings(), island), new WindowKey(0, 0), new WindowKey(1, 0), new WindowKey(0, 1), new WindowKey(1, 1))) {
double mouthRadius = Math.hypot(arm.xs()[last(arm)] - 800D, arm.zs()[last(arm)] - 800D);
double headRadius = Math.hypot(arm.xs()[0] - 800D, arm.zs()[0] - 800D);
assertTrue(arm + " runs inland by at least half its length: " + (mouthRadius - headRadius) + " of " + length(arm),
mouthRadius - headRadius >= 0.5D * length(arm));
}
}
private static List<Reach> arms2(Fixture planner, WindowKey... windows) {
List<Reach> arms = new ArrayList<>();
for (WindowKey window : windows) {
arms.addAll(planner.plan(window, NOTHING));
}
return arms;
}
@Test
public void headsNarrowToAtLeastAThirdOfTheMouth() {
for (Reach arm : arms(planner(settings(), SyntheticTerrain.lowCoast(COAST_X)))) {
float[] widths = arm.halfWidth();
int points = widths.length;
float head = widths[points / 8];
float mouth = widths[points - 1];
assertTrue(arm + " mouth " + mouth + " head " + head, mouth / Math.max(head, 2f) >= 3f);
}
}
@Test
public void armsStopBeforeGroundAboveTheBankLimit() {
SyntheticTerrain ramp = SyntheticTerrain.lowCoast(COAST_X);
HydrologySettings settings = settings();
int limit = settings.underground().seaInlets().maximumBankHeight();
for (Reach arm : arms(planner(settings, ramp))) {
for (int point = 0; point < arm.xs().length; point++) {
assertTrue(arm + " runs through ground " + ramp.natural(arm.xs()[point], arm.zs()[point]),
ramp.natural(arm.xs()[point], arm.zs()[point]) <= SEA + limit);
}
}
}
@Test
public void armsNeverGradeBanksThroughGroundTooTallForTheBand() {
HydrologySettings settings = settings();
double wallX = COAST_X + 150D;
SyntheticTerrain hill = SyntheticTerrain.lowCoast(COAST_X).rising(wallX, 2D);
double graded = 1.5D * settings.underground().seaInlets().maximumBankHeight();
List<Reach> arms = arms(planner(settings, hill));
assertFalse("a low strip still holds arms", arms.isEmpty());
for (Reach arm : arms) {
for (int point = 0; point < arm.xs().length; point++) {
double side = arm.halfWidth()[point] + settings.underground().seaInlets().bankBand();
assertTrue(arm + " grades through " + hill.natural(arm.xs()[point] + side, arm.zs()[point]),
hill.natural(arm.xs()[point] + side, arm.zs()[point]) <= SEA + graded + 1D);
}
double ahead = arm.halfWidth()[0] + settings.underground().seaInlets().bankBand();
assertTrue(arm + " ends against a wall", hill.natural(arm.xs()[0] + ahead, arm.zs()[0]) <= SEA + graded + 1D);
}
}
@Test
public void armsTooShortToStopBeforeAWallAreLeftOut() {
SyntheticTerrain wall = SyntheticTerrain.lowCoast(COAST_X).rising(COAST_X + 60D, 8D);
for (Reach arm : arms(planner(settings(), wall))) {
assertTrue(arm + " ends against the wall", arm.xs()[0] + arm.halfWidth()[0] + 16f <= COAST_X + 60D);
}
}
@Test
public void armsLeaveTheBandOfACliffRunningBesideThem() {
HydrologySettings settings = settings();
SyntheticTerrain coast = SyntheticTerrain.lowCoast(COAST_X);
Reach free = arms(planner(settings, coast)).get(0);
float middleZ = free.zs()[free.zs().length / 2];
float cliffZ = middleZ + 16f;
for (Reach arm : arms(planner(settings, coast.steppedAbove(cliffZ, 20D)))) {
for (int point = 0; point < arm.xs().length; point++) {
float apart = Math.abs(cliffZ - arm.zs()[point]) - arm.halfWidth()[point];
assertTrue(arm + " runs " + apart + " from the cliff at point " + point + ", x " + arm.xs()[point],
arm.xs()[point] < COAST_X + 8f || apart >= settings.underground().seaInlets().bankBand() / 2f);
}
}
}
@Test
public void territoriesKeepCloseMouthsApart() {
IrisHydrology dense = new IrisHydrology();
dense.getUnderground().getSeaInlets().setSpacing(48).setMouthHalfWidth(new KList<>(3D, 4D)).setHeadHalfWidth(new KList<>(1D, 1.5D)).setMeanderWidth(1D);
HydrologySettings settings = settings(dense);
List<Reach> arms = arms(planner(settings, SyntheticTerrain.lowCoast(COAST_X)));
assertFalse(arms.isEmpty());
for (int a = 0; a < arms.size(); a++) {
for (int b = a + 1; b < arms.size(); b++) {
double apart = Math.hypot(arms.get(a).zs()[last(arms.get(a))] - arms.get(b).zs()[last(arms.get(b))], arms.get(a).xs()[last(arms.get(a))] - arms.get(b).xs()[last(arms.get(b))]);
assertTrue("mouths " + apart + " apart", apart >= 13D);
}
}
}
@Test
public void groundBelowTheSeaBesideAnArmCutsTheArmOffAtIt() {
SyntheticTerrain plain = SyntheticTerrain.lowCoast(COAST_X);
List<Reach> clean = arms(planner(settings(), plain));
assertFalse(clean.isEmpty());
Reach longest = clean.get(0);
for (Reach arm : clean) {
longest = length(arm) > length(longest) ? arm : longest;
}
double hollowX = longest.xs()[0] - 12D;
double hollowZ = longest.zs()[0];
SyntheticTerrain hollow = plain.withPit(hollowX, hollowZ, 10D, 40D).withLand((x, z) -> x > COAST_X);
for (Reach arm : arms(planner(settings(), hollow))) {
for (int point = 0; point < arm.xs().length; point++) {
double beside = Math.hypot(arm.xs()[point] - hollowX, arm.zs()[point] - hollowZ);
assertTrue(arm + " passes the hollow at " + beside, beside > arm.halfWidth()[point] + 4D);
}
}
}
@Test
public void armsKeepClearOfRivers() {
SyntheticTerrain coast = SyntheticTerrain.lowCoast(COAST_X);
HydrologySettings settings = settings();
Fixture planner = planner(settings, coast);
List<Reach> free = arms(planner);
assertFalse(free.isEmpty());
Reach blocked = free.get(0);
float z = blocked.zs()[blocked.xs().length / 2];
int points = 40;
float[] xs = new float[points];
float[] zs = new float[points];
int[] grade = new int[points];
float[] halfWidth = new float[points];
float[] depth = new float[points];
ReachStyle[] style = new ReachStyle[points];
for (int point = 0; point < points; point++) {
xs[point] = 700f - point * 10f;
zs[point] = z;
grade[point] = SEA + 2;
halfWidth[point] = 3f;
depth[point] = 1f;
style[point] = ReachStyle.RUN;
}
Reach river = new Reach(9L, settings.tiers().get(1), 0L, xs, zs, grade, halfWidth, depth, style, 30000f);
ShapedNetwork network = new ShapedNetwork(List.of(river), List.of());
WindowKey owner = WindowKey.containing((int) Math.floor(blocked.xs()[last(blocked)]), (int) Math.floor(blocked.zs()[last(blocked)]));
for (Reach arm : planner.plan(owner, network)) {
for (int point = 0; point < arm.xs().length; point++) {
for (int other = 0; other < points; other++) {
double apart = Math.hypot(arm.xs()[point] - xs[other], arm.zs()[point] - zs[other]);
assertTrue(arm + " nears the river: " + apart, apart > arm.halfWidth()[point] + 3f);
}
}
}
}
@Test
public void armsKeepClearOfPonds() {
SyntheticTerrain coast = SyntheticTerrain.lowCoast(COAST_X);
Fixture planner = planner(settings(), coast);
Reach blocked = arms(planner).get(0);
int pondX = (int) blocked.xs()[blocked.xs().length / 2];
int pondZ = (int) blocked.zs()[blocked.xs().length / 2];
long[] bits = new long[1];
Arrays.fill(bits, -1L);
PondMask mask = new PondMask(pondX - 16, pondZ - 16, 8, 5, 5, bits);
Pond pond = new Pond(3L, PondKind.NATURAL, SEA + 8, SEA + 4, pondX, pondZ, SEA + 8.5f, mask, 0L, 0, null, pondX, pondZ);
WindowKey owner = WindowKey.containing((int) Math.floor(blocked.xs()[last(blocked)]), (int) Math.floor(blocked.zs()[last(blocked)]));
for (Reach arm : planner.plan(owner, new ShapedNetwork(List.of(), List.of(pond)))) {
for (int point = 0; point < arm.xs().length; point++) {
assertFalse(arm + " enters the pond", mask.grownContains((int) arm.xs()[point], (int) arm.zs()[point]));
}
}
}
@Test
public void armsNeverCrowdEachOtherAcrossWindowLines() {
HydrologySettings settings = settings();
List<Reach> arms = arms(planner(settings, SyntheticTerrain.lowCoast(COAST_X)));
for (int a = 0; a < arms.size(); a++) {
for (int b = a + 1; b < arms.size(); b++) {
Reach first = arms.get(a);
Reach second = arms.get(b);
for (int p = 0; p < first.xs().length; p += 2) {
for (int q = 0; q < second.xs().length; q += 2) {
double apart = Math.hypot(first.xs()[p] - second.xs()[q], first.zs()[p] - second.zs()[q]);
assertTrue(first + " and " + second + " come within " + apart,
apart >= first.halfWidth()[p] + second.halfWidth()[q]);
}
}
}
}
}
@Test
public void armsAreIdenticalInAnyPlanningOrderAndAcrossThreads() throws Exception {
HydrologySettings settings = settings();
SyntheticTerrain coast = SyntheticTerrain.lowCoast(COAST_X);
Map<WindowKey, List<Reach>> forward = new HashMap<>();
Fixture first = planner(settings, coast);
for (WindowKey window : COAST_WINDOWS) {
forward.put(window, first.plan(window, NOTHING));
}
Map<WindowKey, List<Reach>> backward = new HashMap<>();
Fixture second = planner(settings, coast);
for (int index = COAST_WINDOWS.size() - 1; index >= 0; index--) {
backward.put(COAST_WINDOWS.get(index), second.plan(COAST_WINDOWS.get(index), NOTHING));
}
assertEquals(forward, backward);
Fixture third = planner(settings, coast);
ExecutorService pool = Executors.newFixedThreadPool(4);
try {
Map<WindowKey, Future<List<Reach>>> futures = new HashMap<>();
for (WindowKey window : COAST_WINDOWS) {
futures.put(window, pool.submit(() -> third.plan(window, NOTHING)));
}
for (WindowKey window : COAST_WINDOWS) {
assertEquals(forward.get(window), futures.get(window).get());
}
} finally {
pool.shutdownNow();
}
}
@Test
public void everyArmIsPlannedOnlyByTheWindowOfItsMouth() {
Fixture planner = planner(settings(), SyntheticTerrain.lowCoast(COAST_X));
Map<Long, WindowKey> owners = new HashMap<>();
for (int wz = -2; wz <= 2; wz++) {
for (int wx = -1; wx <= 2; wx++) {
WindowKey window = new WindowKey(wx, wz);
for (Reach arm : planner.plan(window, NOTHING)) {
assertEquals(arm + " planned twice", null, owners.put(arm.id(), window));
}
}
}
assertFalse(owners.isEmpty());
}
@Test
public void territoriesKeepArmsApartWithoutKnowingWhatTheirNeighboursPlanned() {
HydrologySettings settings = settings();
SyntheticTerrain coast = SyntheticTerrain.lowCoast(COAST_X);
Fixture planner = planner(settings, coast);
WindowKey first = new WindowKey(0, 0);
WindowKey second = new WindowKey(0, 1);
List<Reach> alone = planner.plan(second, NOTHING);
planner.plan(first, NOTHING);
assertEquals("planning the neighbour first changes nothing", alone, planner(settings, coast).plan(second, NOTHING));
}
@Test
public void armsFollowTheFunnelKnobs() {
IrisHydrology wide = new IrisHydrology();
wide.getUnderground().getSeaInlets().setMouthHalfWidth(new KList<>(20D, 20D))
.setWidthVariation(0D);
for (Reach arm : arms(planner(settings(wide), SyntheticTerrain.lowCoast(COAST_X)))) {
assertEquals(arm.toString(), 20f, arm.halfWidth()[last(arm)], 0.01f);
}
}
@Test
public void depthShoalsToOneBlockAtBothEnds() {
for (Reach arm : arms(planner(settings(), SyntheticTerrain.lowCoast(COAST_X)))) {
assertEquals(1f, arm.depth()[0], 0.01f);
assertEquals(1f, arm.depth()[last(arm)], 0.01f);
float deepest = 0f;
for (float depth : arm.depth()) {
deepest = Math.max(deepest, depth);
}
assertTrue(arm + " deepest " + deepest, deepest >= 2f && deepest <= 5f);
}
}
}
@@ -8,7 +8,6 @@ import art.arcane.iris.generation.hydrology.grid.HeightLattice;
import art.arcane.iris.generation.hydrology.raster.TongueGuard;
import art.arcane.iris.generation.hydrology.raster.WaterHeads;
import art.arcane.iris.generation.hydrology.raster.WaterRole;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.water.HydrologyTier;
import art.arcane.iris.generation.hydrology.water.CupSet;
import art.arcane.iris.generation.hydrology.water.Pond;
@@ -804,45 +803,22 @@ public class WindowPlannerTest {
}
@Test
public void seaInletsBelongToTheWindowOfTheirFirstLandStationInAnyPlanningOrder() {
public void seaConnectedHeadsAcceptWholeTidalReachesAtSeaLevelOnly() {
HydrologySettings settings = settings(new IrisHydrology());
SyntheticTerrain terrain = SyntheticTerrain.cliffCoast(1400D);
List<WindowKey> keys = List.of(new WindowKey(2, 0), new WindowKey(3, 0), new WindowKey(2, 1), new WindowKey(3, 1));
Map<WindowKey, WindowPlan> forward = new HashMap<>();
WindowPlanner first = planner(settings, terrain);
for (WindowKey key : keys) {
forward.put(key, first.plan(key, noRegions(key)));
}
Map<WindowKey, WindowPlan> backward = new HashMap<>();
WindowPlanner second = planner(settings, terrain);
for (int index = keys.size() - 1; index >= 0; index--) {
backward.put(keys.get(index), second.plan(keys.get(index), noRegions(keys.get(index))));
}
assertEquals(forward, backward);
int spacing = settings.underground().seaInlets().spacing();
Set<Long> sites = new HashSet<>();
int inlets = 0;
int crossing = 0;
for (Map.Entry<WindowKey, WindowPlan> entry : forward.entrySet()) {
for (SeaInlet inlet : entry.getValue().inlets()) {
inlets++;
int landX = (int) Math.floor(inlet.xs()[1]);
int landZ = (int) Math.floor(inlet.zs()[1]);
assertEquals(inlet + " belongs to the window of its first land station", WindowKey.containing(landX, landZ), entry.getKey());
assertTrue(inlet + " is the only inlet of its site", sites.add(((long) Math.floorDiv(landX, spacing) << 32)
| (Math.floorDiv(landZ, spacing) & 0xFFFFFFFFL)));
boolean leaves = false;
for (int station = 0; station < inlet.stations(); station++) {
leaves |= !WindowKey.containing((int) Math.floor(inlet.xs()[station]), (int) Math.floor(inlet.zs()[station])).equals(entry.getKey());
}
crossing += leaves ? 1 : 0;
}
}
assertTrue("sea inlets on the cliff coast " + inlets, inlets >= 2);
assertTrue("inlets running into the next window " + crossing, crossing > 0);
for (WindowKey key : List.of(new WindowKey(3, 0), new WindowKey(3, 1))) {
assertTrue("the inland window owns none of the coast's inlets", forward.get(key).inlets().isEmpty());
}
WindowKey key = new WindowKey(0, 0);
int sea = settings.seaLevel();
WindowPlanner.requireSeaConnectedHeads(new WindowPlan(key, List.of(tidal(settings, sea, 0L, ReachStyle.TIDAL)), List.of()), sea);
assertThrows(IllegalStateException.class,
() -> WindowPlanner.requireSeaConnectedHeads(new WindowPlan(key, List.of(tidal(settings, sea + 2, 0L, ReachStyle.TIDAL)), List.of()), sea));
assertThrows(IllegalStateException.class,
() -> WindowPlanner.requireSeaConnectedHeads(new WindowPlan(key, List.of(tidal(settings, sea, 9L, ReachStyle.TIDAL)), List.of()), sea));
assertThrows(IllegalStateException.class,
() -> WindowPlanner.requireSeaConnectedHeads(new WindowPlan(key, List.of(tidal(settings, sea, 0L, ReachStyle.RUN)), List.of()), sea));
}
private static Reach tidal(HydrologySettings settings, int grade, long downstream, ReachStyle last) {
return new Reach(5L, settings.tidalTier(), downstream, new float[]{0f, 8f}, new float[]{0f, 0f}, new int[]{grade, grade},
new float[]{2f, 4f}, new float[]{1f, 1f}, new ReachStyle[]{ReachStyle.TIDAL, last}, 0f);
}
@Test
@@ -855,8 +831,6 @@ public class WindowPlannerTest {
assertTrue("mouth vertices on the coastal fractal " + fractalColumns.vertices(), fractalColumns.vertices() >= 100);
assertTrue("mouth columns on the coastal fractal " + fractalColumns.mouths(), fractalColumns.mouths() >= 1000);
assertTrue("mouth columns on the cliff coast " + cliffColumns.mouths(), cliffColumns.mouths() >= 1000);
assertTrue("sea inlets on the cliff coast " + cliff.inlets().size(), cliff.inlets().size() >= 2);
assertTrue("inlet columns on the cliff coast " + cliffColumns.inlets(), cliffColumns.inlets() >= 500);
}
@Test
@@ -1193,6 +1167,7 @@ public class WindowPlannerTest {
config.getLakes().setEnabled(false);
config.getPonds().getSeeded().setAlongChannels(false);
config.getTiers().get(0).setMinCatchment(LINE_STREAM_CATCHMENT);
config.getUnderground().getSeaInlets().setEnabled(false);
HydrologySettings settings = settings(config);
int line = LAND.wx() * WindowKey.SIZE;
double axis = LAND.wz() * WindowKey.SIZE + SEAM_DISTANCE;
@@ -1323,9 +1298,6 @@ public class WindowPlannerTest {
}
private static SeaColumns assertSeaConnectedHeads(String name, PlannedScene scene) {
for (SeaInlet inlet : scene.inlets()) {
assertEquals(name + " " + inlet, SEA_LEVEL, inlet.waterLevel());
}
int vertices = 0;
for (Reach reach : scene.reaches()) {
for (int point = 0; point < reach.grade().length; point++) {
@@ -11,8 +11,6 @@ import art.arcane.iris.generation.hydrology.plan.RegionKey;
import art.arcane.iris.generation.hydrology.plan.RegionPlan;
import art.arcane.iris.generation.hydrology.plan.WindowKey;
import art.arcane.iris.generation.hydrology.plan.WindowPlan;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.underground.SeaInletRasterizer;
import art.arcane.iris.generation.hydrology.water.ConfluenceGrader;
import art.arcane.iris.generation.hydrology.water.HydrologyTier;
import art.arcane.iris.generation.hydrology.water.Pond;
@@ -416,49 +414,129 @@ public class ChunkWaterRasterTest {
}
}
@Test
public void openSeaInletSlotColumnsTakeTheInletRoleAtSeaLevel() {
HydrologySettings settings = settings(new IrisHydrology());
int stations = 10;
float[] xs = new float[stations];
float[] zs = new float[stations];
float[] halfWidth = new float[stations];
int[] floor = new int[stations];
int[] ceiling = new int[stations];
for (int station = 0; station < stations; station++) {
xs[station] = -8f + station * 8f;
zs[station] = 8f;
halfWidth[station] = 4f;
floor[station] = SEA_LEVEL - 3;
ceiling[station] = station < 2 ? SeaInlet.OPEN : SEA_LEVEL + 5;
private static Reach straight(long id, HydrologyTier tier, float z, int head, ReachStyle style) {
int points = 9;
float[] xs = new float[points];
float[] zs = new float[points];
int[] grade = new int[points];
float[] halfWidth = new float[points];
float[] depth = new float[points];
ReachStyle[] styles = new ReachStyle[points];
for (int point = 0; point < points; point++) {
xs[point] = -16f + point * 8f;
zs[point] = z;
grade[point] = head;
halfWidth[point] = 3f;
depth[point] = 2f;
styles[point] = style;
}
SeaInlet inlet = new SeaInlet(71L, xs, zs, halfWidth, SEA_LEVEL, floor, ceiling, 64, 8, 6);
return new Reach(id, tier, 0L, xs, zs, grade, halfWidth, depth, styles, 30000f);
}
private static ChunkWaterRaster rasterOf(HydrologySettings settings, List<Reach> reaches, int ground) {
WindowKey key = new WindowKey(0, 0);
IndexedWindow own = new IndexedWindow(new WindowPlan(key, List.of(), List.of(), List.of(inlet)), ReachIndex.build(key, List.of(), List.of()));
ChunkRasterizer rasterizer = new ChunkRasterizer(settings, ChannelFluids.TIER);
ChunkWaterRaster mouth = rasterizer.rasterize(0, 0, (x, z) -> 70, List.of(own), regions(0, 0, List.of()));
int[] column = new int[2];
int open = 0;
for (int lz = 0; lz < 16; lz++) {
for (int lx = 0; lx < 16; lx++) {
boolean slot = SeaInletRasterizer.column(inlet, lx, lz, column) && column[1] == SeaInlet.OPEN;
if (slot) {
open++;
assertEquals(WaterRole.INLET, mouth.role(lx, lz));
assertEquals(SEA_LEVEL, mouth.waterHead(lx, lz));
assertEquals(SEA_LEVEL - 3, mouth.terrainHeight(lx, lz));
assertEquals(SEA_LEVEL - 4, mouth.caveCeiling(lx, lz));
assertEquals(71L, mouth.featureId(lx, lz));
assertEquals(HydrologyCaveCell.SEA_FLUID, mouth.fluid(lx, lz));
} else {
assertEquals(WaterRole.NONE, mouth.role(lx, lz));
assertEquals(70, mouth.terrainHeight(lx, lz));
IndexedWindow own = new IndexedWindow(new WindowPlan(key, reaches, List.of()), ReachIndex.build(key, reaches, List.of()));
return new ChunkRasterizer(settings, ChannelFluids.TIER).rasterize(0, 0, (x, z) -> ground, List.of(own), regions(0, 0, List.of()));
}
@Test
public void tidalBanksMeetANeighbouringRiverBankWithoutACliff() {
HydrologySettings settings = settings(new IrisHydrology());
int ground = SEA_LEVEL + 32;
Reach arm = straight(71L, settings.tidalTier(), -6f, SEA_LEVEL, ReachStyle.TIDAL);
for (int riverHead : new int[]{SEA_LEVEL, SEA_LEVEL + 24}) {
for (HydrologyTier tier : settings.tiers()) {
Reach river = straight(72L, tier, 22f, riverHead, ReachStyle.RUN);
ChunkWaterRaster raster = rasterOf(settings, List.of(arm, river), ground);
ChunkWaterRaster alone = rasterOf(settings, List.of(river), ground);
for (int lx = 0; lx < 16; lx++) {
for (int lz = 0; lz < 15; lz++) {
int step = Math.abs(raster.terrainHeight(lx, lz + 1) - raster.terrainHeight(lx, lz));
assertTrue(tier.name() + " head " + riverHead + " steps " + step + " at " + lx + "," + lz, step <= 8);
}
for (int lz = 9; lz < 16; lz++) {
assertEquals("the river side is the river's own bank at " + lx + "," + lz, alone.terrainHeight(lx, lz), raster.terrainHeight(lx, lz));
}
}
}
}
assertTrue("open slot columns " + open, open > 20);
assertTrue("a covered passage leaves the surface alone",
rasterizer.rasterize(2, 0, (x, z) -> 70, List.of(own), regions(2, 0, List.of())).empty());
}
@Test
public void tidalBanksFollowTheBandInsteadOfCuttingRaysToSteepGround() {
HydrologySettings settings = settings(new IrisHydrology());
int points = 9;
float[] xs = new float[points];
float[] zs = new float[points];
int[] grade = new int[points];
float[] halfWidth = new float[points];
float[] depth = new float[points];
ReachStyle[] style = new ReachStyle[points];
for (int point = 0; point < points; point++) {
xs[point] = -16f + point * 8f;
zs[point] = -8f;
grade[point] = SEA_LEVEL;
halfWidth[point] = 3f;
depth[point] = 3f;
style[point] = ReachStyle.TIDAL;
}
Reach reach = new Reach(71L, settings.tidalTier(), 0L, xs, zs, grade, halfWidth, depth, style, 0f);
WindowKey key = new WindowKey(0, 0);
IndexedWindow own = new IndexedWindow(new WindowPlan(key, List.of(reach), List.of()), ReachIndex.build(key, List.of(reach), List.of()));
ChunkRasterizer rasterizer = new ChunkRasterizer(settings, ChannelFluids.TIER);
ChunkWaterRaster ridged = rasterizer.rasterize(0, 0, (x, z) -> SEA_LEVEL + 20 + (Math.floorMod(x, 8) < 2 ? 8 : 0), List.of(own), regions(0, 0, List.of()));
ChunkWaterRaster plain = rasterizer.rasterize(0, 0, (x, z) -> SEA_LEVEL + 28, List.of(own), regions(0, 0, List.of()));
for (int lz = 0; lz < 16; lz++) {
for (int lx = 0; lx < 16; lx++) {
assertTrue("a ridge reaches no higher than the same band over plain ground at " + lx + "," + lz + ": "
+ ridged.terrainHeight(lx, lz) + " over " + plain.terrainHeight(lx, lz), ridged.terrainHeight(lx, lz) <= plain.terrainHeight(lx, lz));
}
}
}
@Test
public void tidalReachColumnsTakeTheInletRoleAtSeaLevelBetweenBanks() {
HydrologySettings settings = settings(new IrisHydrology());
int points = 9;
float[] xs = new float[points];
float[] zs = new float[points];
int[] grade = new int[points];
float[] halfWidth = new float[points];
float[] depth = new float[points];
ReachStyle[] style = new ReachStyle[points];
for (int point = 0; point < points; point++) {
xs[point] = -16f + point * 8f;
zs[point] = 8f;
grade[point] = SEA_LEVEL;
halfWidth[point] = 3f;
depth[point] = 3f;
style[point] = ReachStyle.TIDAL;
}
Reach reach = new Reach(71L, settings.tidalTier(), 0L, xs, zs, grade, halfWidth, depth, style, 0f);
WindowKey key = new WindowKey(0, 0);
IndexedWindow own = new IndexedWindow(new WindowPlan(key, List.of(reach), List.of()), ReachIndex.build(key, List.of(reach), List.of()));
ChunkRasterizer rasterizer = new ChunkRasterizer(settings, ChannelFluids.TIER);
ChunkWaterRaster raster = rasterizer.rasterize(0, 0, (x, z) -> SEA_LEVEL + 12, List.of(own), regions(0, 0, List.of()));
int wet = 0;
int bank = 0;
for (int lz = 0; lz < 16; lz++) {
for (int lx = 0; lx < 16; lx++) {
if (Math.abs(lz - 8) <= 2) {
wet++;
assertEquals(WaterRole.INLET, raster.role(lx, lz));
assertEquals(SEA_LEVEL, raster.waterHead(lx, lz));
assertTrue(raster.terrainHeight(lx, lz) < SEA_LEVEL);
assertEquals(71L, raster.featureId(lx, lz));
assertEquals(HydrologyCaveCell.SEA_FLUID, raster.fluid(lx, lz));
} else if (raster.waterHead(lx, lz) == Integer.MIN_VALUE) {
bank++;
assertTrue("shaped ground stays above the water at " + lx + "," + lz, raster.terrainHeight(lx, lz) >= SEA_LEVEL);
assertTrue("the band cuts the bank below the natural ground at " + lx + "," + lz, raster.terrainHeight(lx, lz) < SEA_LEVEL + 12);
}
}
}
assertTrue("water columns " + wet, wet > 60);
assertTrue("bank columns " + bank, bank > 60);
}
@Test
@@ -466,7 +544,7 @@ public class ChunkWaterRasterTest {
HydrologySettings settings = settings(new IrisHydrology());
Reach far = line(61L, tier("stream", 1.5f, 0.5f, 0, IrisBankStyle.SMOOTH), 0L, 400f, 400f, 480f, 400f, (x, z) -> 69);
WindowKey key = new WindowKey(0, 0);
IndexedWindow own = new IndexedWindow(new WindowPlan(key, List.of(far), List.of(), List.of()), ReachIndex.build(key, List.of(far), List.of()));
IndexedWindow own = new IndexedWindow(new WindowPlan(key, List.of(far), List.of()), ReachIndex.build(key, List.of(far), List.of()));
AtomicInteger samples = new AtomicInteger();
IntBinaryOperator natural = (x, z) -> {
samples.incrementAndGet();
@@ -503,7 +581,7 @@ public class ChunkWaterRasterTest {
Reach outflow = line(61L, stream, 0L, 400f, 403f, 480f, 403f, (x, z) -> 69);
Reach inflow = line(62L, stream, 0L, 480f, 412f, 400f, 412f, (x, z) -> 69);
WindowKey key = new WindowKey(0, 0);
IndexedWindow own = new IndexedWindow(new WindowPlan(key, List.of(outflow, inflow), List.of(), List.of()),
IndexedWindow own = new IndexedWindow(new WindowPlan(key, List.of(outflow, inflow), List.of()),
ReachIndex.build(key, List.of(outflow, inflow), List.of()));
ChannelFluids volcanic = (x, z) -> x < 440 ? "lava" : null;
ChunkWaterRaster raster = new ChunkRasterizer(settings, volcanic).rasterize(27, 25, (x, z) -> 70, List.of(own), regions(27, 25, List.of()));
@@ -531,7 +609,7 @@ public class ChunkWaterRasterTest {
HydrologySettings settings = settings(new IrisHydrology());
Reach river = line(81L, tier("river", 3f, 0.5f, 32, IrisBankStyle.SMOOTH), 0L, 96f, 256f, 416f, 256f, (x, z) -> 69);
WindowKey key = new WindowKey(0, 0);
IndexedWindow own = new IndexedWindow(new WindowPlan(key, List.of(river), List.of(), List.of()), ReachIndex.build(key, List.of(river), List.of()));
IndexedWindow own = new IndexedWindow(new WindowPlan(key, List.of(river), List.of()), ReachIndex.build(key, List.of(river), List.of()));
NaturalHeights natural = (x, z) -> {
double away = Math.abs(z - 256);
if (x < 256) {
@@ -1016,7 +1094,7 @@ public class ChunkWaterRasterTest {
WindowKey key = new WindowKey(dx, dz);
List<Reach> owned = key.equals(new WindowKey(0, 0)) ? List.of(feeder)
: key.equals(new WindowKey(1, 0)) || key.equals(new WindowKey(1, -1)) ? List.of(downstream) : List.of();
windows.add(new IndexedWindow(new WindowPlan(key, owned, List.of(), List.of()), ReachIndex.build(key, owned, List.of())));
windows.add(new IndexedWindow(new WindowPlan(key, owned, List.of()), ReachIndex.build(key, owned, List.of())));
}
}
ChunkRasterizer rasterizer = new ChunkRasterizer(settings(new IrisHydrology()), ChannelFluids.TIER);
@@ -2644,7 +2722,7 @@ public class ChunkWaterRasterTest {
ownedPonds.add(pond);
}
}
return new IndexedWindow(new WindowPlan(key, owned, ownedPonds, List.of()), ReachIndex.build(key, owned, ownedPonds));
return new IndexedWindow(new WindowPlan(key, owned, ownedPonds), ReachIndex.build(key, owned, ownedPonds));
});
}
@@ -114,7 +114,7 @@ public class PondChannelSettlementTest {
for (long seed = 1L; seed <= 24L; seed++) {
HydrologySettings settings = HydrologySettings.compile(new IrisHydrology(), seed, SEA_LEVEL, -64, 320);
ChunkRasterizer rasterizer = new ChunkRasterizer(settings, ChannelFluids.TIER);
IndexedWindow window = new IndexedWindow(new WindowPlan(WINDOW, List.of(river), List.of(), List.of()), ReachIndex.build(WINDOW, List.of(river), List.of()));
IndexedWindow window = new IndexedWindow(new WindowPlan(WINDOW, List.of(river), List.of()), ReachIndex.build(WINDOW, List.of(river), List.of()));
for (int z = 124; z <= 132; z++) {
Pond pond = pond(1L, PondKind.NATURAL, 94, circle(504, z, 0));
int lowest = Math.min(94, Math.min(rasterHead(rasterizer, window, 504, z), Math.min(rasterHead(rasterizer, window, 505, z),
@@ -163,7 +163,7 @@ public class PondChannelSettlementTest {
private static int assertSettlementMatchesTheRaster(long seed, Reach river, int minX, int maxX, int minZ, int maxZ, int stride) {
HydrologySettings settings = HydrologySettings.compile(new IrisHydrology(), seed, SEA_LEVEL, -64, 320);
ChunkRasterizer rasterizer = new ChunkRasterizer(settings, ChannelFluids.TIER);
IndexedWindow window = new IndexedWindow(new WindowPlan(WINDOW, List.of(river), List.of(), List.of()), ReachIndex.build(WINDOW, List.of(river), List.of()));
IndexedWindow window = new IndexedWindow(new WindowPlan(WINDOW, List.of(river), List.of()), ReachIndex.build(WINDOW, List.of(river), List.of()));
Map<Long, ChunkWaterRaster> rasters = new HashMap<>();
int lowered = 0;
for (int x = minX; x <= maxX; x += stride) {
@@ -1,224 +0,0 @@
package art.arcane.iris.generation.hydrology.underground;
import art.arcane.iris.generation.hydrology.config.IrisHydrology;
import art.arcane.iris.generation.hydrology.grid.D8Router;
import art.arcane.iris.generation.hydrology.grid.DemGrid;
import art.arcane.iris.generation.hydrology.grid.FlowAccumulator;
import art.arcane.iris.generation.hydrology.grid.HydrologySampleBuffer;
import art.arcane.iris.generation.hydrology.grid.PriorityFlood;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.hydrology.plan.WindowKey;
import art.arcane.iris.generation.hydrology.water.Reach;
import art.arcane.iris.generation.hydrology.water.ReachStyle;
import art.arcane.iris.generation.hydrology.water.ShapedNetwork;
import java.util.BitSet;
import java.util.List;
import java.util.function.DoubleBinaryOperator;
final class InletTerrain {
static final long SEED = 1337L;
static final int SEA = 40;
static final int MIN_Y = -64;
static final int MAX_Y = 320;
static final int COAST_X = 160;
static final int CELL = 8;
static final int WIDTH = 96;
static final int DEPTH = 64;
static final int SPAN = 3 * WindowKey.SIZE / CELL;
final DoubleBinaryOperator natural;
final WindowKey window;
final DemGrid grid;
final HydrologySampleBuffer samples;
final int[] receivers;
final float[] accumulation;
private InletTerrain(DoubleBinaryOperator natural) {
this(natural, new WindowKey(0, 0));
}
private InletTerrain(DoubleBinaryOperator natural, WindowKey window) {
this(natural, window, (window.wx() - 1) * WindowKey.SIZE, (window.wz() - 1) * WindowKey.SIZE, SPAN, SPAN);
}
private InletTerrain(DoubleBinaryOperator natural, WindowKey window, int originX, int originZ, int width, int depth) {
this.natural = natural;
this.window = window;
this.grid = new DemGrid(originX, originZ, CELL, width, depth);
int count = width * depth;
this.samples = new HydrologySampleBuffer(count);
BitSet seeds = new BitSet(count);
for (int cell = 0; cell < count; cell++) {
int x = grid.blockX(cell);
int z = grid.blockZ(cell);
float height = (float) natural.applyAsDouble(x, z);
grid.values()[cell] = height;
samples.height()[cell] = height;
samples.ocean()[cell] = Math.round(height) < SEA;
int i = cell % width;
int j = cell / width;
if (samples.ocean()[cell] || i == 0 || j == 0 || i == width - 1 || j == depth - 1) {
seeds.set(cell);
}
}
float[] filled = PriorityFlood.fill(grid, seeds, 0.001f);
DemGrid surface = new DemGrid(originX, originZ, CELL, width, depth);
System.arraycopy(filled, 0, surface.values(), 0, count);
this.receivers = D8Router.receivers(surface, filled, SEED);
float[] weights = new float[count];
for (int cell = 0; cell < count; cell++) {
if (samples.ocean()[cell]) {
receivers[cell] = -1;
}
weights[cell] = CELL * CELL;
}
this.accumulation = FlowAccumulator.accumulate(receivers, filled, weights, 4194304f);
}
static InletTerrain cliff(double cliffHeight) {
return new InletTerrain((x, z) -> x < COAST_X ? SEA - 20D : SEA + cliffHeight + 0.08D * (x - COAST_X));
}
InletTerrain wide(WindowKey window, int windows) {
int cells = (2 * windows + 1) * WindowKey.SIZE / CELL;
int originX = (window.wx() - windows) * WindowKey.SIZE;
int originZ = (window.wz() - windows) * WindowKey.SIZE;
return new InletTerrain(natural, window, originX, originZ, cells, cells);
}
static InletTerrain bay(int westX, int eastX, int bayZ) {
return new InletTerrain((x, z) -> {
if (z > bayZ - CELL / 2D) {
return Math.abs(z - bayZ) < CELL / 2D && x > westX - CELL / 2D && x < eastX + CELL / 2D ? SEA - 20D : SEA + 5D;
}
return SEA + 30D + 0.08D * (bayZ - z);
});
}
static InletTerrain eastEdgeCoast() {
double coast = WindowKey.SIZE - CELL;
return new InletTerrain((x, z) -> x < coast - CELL / 2D ? SEA - 20D : SEA + 30D + 0.08D * (x - coast));
}
static InletTerrain openCoast() {
return new InletTerrain((x, z) -> {
double coast = 768D + 120D * Math.sin(z / 180D) + 40D * Math.sin(z / 53D);
return x < coast ? SEA - 20D : SEA + 30D + 0.08D * (x - coast);
});
}
static InletTerrain cliffWithTrough(double cliffHeight, double troughFrom, double troughTo, double troughHeight) {
return new InletTerrain((x, z) -> {
if (x < COAST_X) {
return SEA - 20D;
}
if (x >= troughFrom && x <= troughTo) {
return troughHeight;
}
return SEA + cliffHeight + 0.08D * (x - COAST_X);
});
}
static InletTerrain coastalRidge(double crestDistance) {
return new InletTerrain((x, z) -> {
if (x < COAST_X) {
return SEA - 20D;
}
double crest = SEA + 30D + 0.3D * crestDistance;
return x < COAST_X + crestDistance ? SEA + 30D + 0.3D * (x - COAST_X) : crest - 0.02D * (x - COAST_X - crestDistance);
});
}
static InletTerrain southCoast(double coastZ) {
return new InletTerrain((x, z) -> z < coastZ ? SEA - 20D : SEA + 30D + 0.08D * (z - coastZ));
}
static InletTerrain steppedCoast(double stepX) {
return new InletTerrain((x, z) -> x < COAST_X ? SEA - 20D : x < stepX ? SEA + 9D : SEA + 40D + 0.05D * (x - stepX));
}
static InletTerrain pocket(int pocketX, int pocketZ) {
return new InletTerrain((x, z) -> Math.abs(x - pocketX) < CELL / 2D && Math.abs(z - pocketZ) < CELL / 2D ? SEA - 20D
: SEA + 30D + 0.08D * Math.hypot(x - pocketX, z - pocketZ));
}
static float length(SeaInlet inlet) {
float length = 0f;
for (int station = 1; station < inlet.stations(); station++) {
length += (float) Math.hypot(inlet.xs()[station] - inlet.xs()[station - 1], inlet.zs()[station] - inlet.zs()[station - 1]);
}
return length;
}
static HydrologySettings settings() {
return settings(new IrisHydrology());
}
static HydrologySettings settings(IrisHydrology config) {
return HydrologySettings.compile(config, SEED, SEA, MIN_Y, MAX_Y);
}
InletTerrain span(WindowKey window) {
return new InletTerrain(natural, window);
}
InletTerrain narrow(int originX, int originZ) {
return new InletTerrain(natural, WindowKey.containing(originX, originZ), originX, originZ, WIDTH, DEPTH);
}
List<SeaInlet> plan(HydrologySettings settings, ShapedNetwork network) {
return new SeaInletPlanner(settings).plan(window, grid, samples, receivers, accumulation, network, SEED);
}
List<SeaInlet> plan(HydrologySettings settings) {
return plan(settings, new ShapedNetwork(List.of(), List.of()));
}
boolean ocean(float x, float z) {
int cell = grid.index(Math.round((x - grid.originX()) / CELL), Math.round((z - grid.originZ()) / CELL));
return samples.ocean()[cell];
}
int naturalAt(int x, int z) {
return (int) Math.round(natural.applyAsDouble(x, z));
}
static Reach eastWestReach(HydrologySettings settings, float fromX, float toX, float z, int grade) {
int points = Math.max(2, (int) Math.ceil((toX - fromX) / 8f) + 1);
float[] xs = new float[points];
float[] zs = new float[points];
int[] grades = new int[points];
float[] widths = new float[points];
float[] depths = new float[points];
ReachStyle[] styles = new ReachStyle[points];
for (int point = 0; point < points; point++) {
xs[point] = fromX + (toX - fromX) * point / (points - 1);
zs[point] = z;
grades[point] = grade;
widths[point] = 2f;
depths[point] = 1.5f;
styles[point] = ReachStyle.RUN;
}
return new Reach(78L, settings.tiers().get(0), 0L, xs, zs, grades, widths, depths, styles, 2000f);
}
static Reach northSouthReach(HydrologySettings settings, float x, int grade, float halfWidth, float depth) {
int points = 25;
float[] xs = new float[points];
float[] zs = new float[points];
int[] grades = new int[points];
float[] widths = new float[points];
float[] depths = new float[points];
ReachStyle[] styles = new ReachStyle[points];
for (int point = 0; point < points; point++) {
xs[point] = x;
zs[point] = point * 64f - WindowKey.SIZE;
grades[point] = grade;
widths[point] = halfWidth;
depths[point] = depth;
styles[point] = ReachStyle.RUN;
}
return new Reach(77L, settings.tiers().get(0), 0L, xs, zs, grades, widths, depths, styles, 2000f);
}
}
@@ -1,562 +0,0 @@
package art.arcane.iris.generation.hydrology.underground;
import art.arcane.iris.generation.hydrology.config.IrisHydrology;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.hydrology.plan.WindowKey;
import art.arcane.iris.generation.hydrology.water.Reach;
import art.arcane.iris.generation.hydrology.water.ReachStyle;
import art.arcane.iris.generation.hydrology.water.ShapedNetwork;
import art.arcane.volmlib.util.collection.KList;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class SeaInletPlannerTest {
private static final int SEA = InletTerrain.SEA;
@Test
public void globalDensityThinsInletSitesWithoutChangingTheirGeometry() {
InletTerrain terrain = InletTerrain.cliff(30D);
IrisHydrology full = new IrisHydrology();
IrisHydrology half = new IrisHydrology().setDensity(0.5D);
full.getUnderground().getSeaInlets().setSpacing(256);
half.getUnderground().getSeaInlets().setSpacing(256);
int baseline = 0;
int retained = 0;
for (int offset = 0; offset < 32; offset++) {
InletTerrain view = terrain.span(new WindowKey(0, offset));
List<SeaInlet> all = view.plan(InletTerrain.settings(full));
List<SeaInlet> reduced = view.plan(InletTerrain.settings(half));
baseline += all.size();
retained += reduced.size();
for (SeaInlet inlet : reduced) {
assertTrue("retained inlets keep the same full passage", all.contains(inlet));
}
assertEquals(reduced, view.plan(InletTerrain.settings(half)));
}
assertTrue("cliff provides enough candidates", baseline >= 32);
assertTrue("half density retains approximately half the sites", retained > baseline * 0.3 && retained < baseline * 0.7);
assertTrue(terrain.plan(InletTerrain.settings(new IrisHydrology().setDensity(0D))).isEmpty());
}
@Test
public void inletStartsAtOceanCell() {
InletTerrain terrain = InletTerrain.cliff(30D);
List<SeaInlet> inlets = terrain.plan(InletTerrain.settings());
assertFalse("a straight cliff coast holds inlets", inlets.isEmpty());
for (SeaInlet inlet : inlets) {
assertTrue(inlet + " opens from an ocean cell", terrain.ocean(inlet.xs()[0], inlet.zs()[0]));
assertFalse(inlet + " runs inland", terrain.ocean(inlet.xs()[1], inlet.zs()[1]));
for (int station = 1; station < inlet.stations(); station++) {
assertTrue(inlet + " climbs away from the sea", inlet.xs()[station] > inlet.xs()[station - 1]);
}
}
}
@Test
public void waterLevelIsSeaLevelEverywhere() {
InletTerrain terrain = InletTerrain.cliff(30D);
HydrologySettings settings = InletTerrain.settings();
HydrologySettings.SeaInlets config = settings.underground().seaInlets();
List<SeaInlet> inlets = terrain.plan(settings);
assertFalse(inlets.isEmpty());
for (SeaInlet inlet : inlets) {
assertEquals(SEA, inlet.waterLevel());
for (int station = 0; station < inlet.stations(); station++) {
int depth = SEA - inlet.floor()[station];
assertTrue(inlet + " depth " + depth, depth >= config.depth().min() && depth <= config.depth().max());
assertTrue(inlet + " keeps air or an open mouth above the water", inlet.ceiling()[station] >= SEA);
}
}
}
@Test
public void roofClearanceHeld() {
HydrologySettings settings = InletTerrain.settings();
int clearance = settings.underground().seaInlets().roofClearance();
double troughFrom = 300D;
InletTerrain terrain = InletTerrain.cliffWithTrough(30D, troughFrom, 340D, SEA + 9D);
List<SeaInlet> inlets = terrain.plan(settings);
assertFalse(inlets.isEmpty());
int covered = 0;
int[] column = new int[2];
for (SeaInlet inlet : inlets) {
int[] bounds = SeaInletRasterizer.bounds(inlet);
for (int z = bounds[1]; z <= bounds[3]; z++) {
for (int x = bounds[0]; x <= bounds[2]; x++) {
if (!SeaInletRasterizer.column(inlet, x, z, column)) {
continue;
}
int ground = terrain.naturalAt(x, z);
assertTrue(inlet + " at " + x + "," + z + " stays clear of the trough", x < troughFrom - clearance);
if (column[1] == SeaInlet.OPEN) {
assertTrue(inlet + " open slot at " + x + "," + z + " stays at the coast", x < InletTerrain.COAST_X + 3 * InletTerrain.CELL);
} else {
covered++;
assertTrue(inlet + " roof at " + x + "," + z + " is " + (ground - column[1]), ground - column[1] >= clearance);
}
}
}
}
assertTrue("covered columns " + covered, covered > 200);
}
@Test
public void openSlotHoldsAtMostTwoLandStationsFromTheSea() {
for (InletTerrain terrain : List.of(InletTerrain.cliff(30D), InletTerrain.cliff(9D), InletTerrain.pocket(152, 256))) {
for (SeaInlet inlet : terrain.plan(InletTerrain.settings())) {
assertTrue(inlet + " opens at the sea", inlet.open(0));
int open = 1;
while (open < inlet.stations() && inlet.open(open)) {
open++;
}
assertTrue(inlet + " open land stations " + (open - 1), open - 1 <= 2);
for (int station = open; station < inlet.stations(); station++) {
assertFalse(inlet + " stays covered after the slot at station " + station, inlet.open(station));
}
}
}
}
@Test
public void slotsNeedingAThirdOpenLandStationAreRejected() {
List<SeaInlet> twoOpen = InletTerrain.steppedCoast(164D).plan(InletTerrain.settings());
assertFalse("a cliff that holds a roof two stations in keeps its inlets", twoOpen.isEmpty());
for (SeaInlet inlet : twoOpen) {
assertTrue(inlet.open(1) && inlet.open(2) && !inlet.open(3));
}
assertTrue("a slot three land stations long is refused", InletTerrain.steppedCoast(172D).plan(InletTerrain.settings()).isEmpty());
}
@Test
public void ceilingFollowsSmoothNoiseAlongThePath() {
HydrologySettings settings = InletTerrain.settings();
int distinct = 0;
for (SeaInlet inlet : InletTerrain.cliff(30D).plan(settings)) {
Set<Integer> heights = new HashSet<>();
for (int station = 1; station < inlet.stations(); station++) {
if (inlet.open(station) || inlet.open(station - 1)) {
continue;
}
heights.add(inlet.ceiling()[station]);
int step = Math.abs(inlet.ceiling()[station] - inlet.ceiling()[station - 1]);
assertTrue(inlet + " ceiling steps " + step + " at station " + station, step <= 3);
}
distinct += heights.size() > 1 ? 1 : 0;
}
assertTrue("ceilings vary along the passage", distinct > 0);
}
@Test
public void inletsSharingAnOceanMouthKeepDistinctIds() {
IrisHydrology config = new IrisHydrology();
config.getUnderground().getSeaInlets().setSpacing(32);
List<SeaInlet> inlets = InletTerrain.pocket(152, 256).plan(InletTerrain.settings(config));
long shared = inlets.stream().filter(inlet -> inlet.xs()[0] == 152f && inlet.zs()[0] == 256f).count();
assertTrue("inlets opening from the one-cell pocket " + shared, shared >= 2);
assertEquals(inlets.size(), inlets.stream().mapToLong(SeaInlet::id).distinct().count());
}
@Test
public void noInletRunsCoveredUnderOrBesideAnotherInletsOpenSlot() {
IrisHydrology dense = new IrisHydrology();
dense.getUnderground().getSeaInlets().setSpacing(32);
int pairs = 0;
for (InletTerrain terrain : List.of(InletTerrain.pocket(152, 256), InletTerrain.cliff(30D), InletTerrain.steppedCoast(164))) {
List<SeaInlet> inlets = terrain.plan(InletTerrain.settings(dense));
for (int first = 0; first < inlets.size(); first++) {
for (int second = first + 1; second < inlets.size(); second++) {
pairs++;
assertFalse(inlets.get(first) + " and " + inlets.get(second) + " cross a covered passage with an open slot",
coveredMeetsOpen(inlets.get(first), inlets.get(second)) || coveredMeetsOpen(inlets.get(second), inlets.get(first)));
}
}
}
assertTrue("inlet pairs " + pairs, pairs > 10);
}
@Test
public void competingInletsResolveTheSameWayInEveryGridThatSeesBoth() {
IrisHydrology dense = new IrisHydrology();
dense.getUnderground().getSeaInlets().setSpacing(32);
HydrologySettings settings = InletTerrain.settings(dense);
InletTerrain pocket = InletTerrain.pocket(512, 256);
List<SeaInlet> here = fromPocket(pocket.span(new WindowKey(0, 0)).plan(settings), 512, 256);
assertTrue("inlets opening from the pocket " + here, here.size() >= 2);
assertEquals("another grid holding every competitor well inside decides the same", here,
fromPocket(pocket.span(new WindowKey(1, 0)).plan(settings), 512, 256));
for (int first = 0; first < here.size(); first++) {
for (int second = first + 1; second < here.size(); second++) {
assertFalse(here.get(first) + " and " + here.get(second) + " cross a covered passage with an open slot",
coveredMeetsOpen(here.get(first), here.get(second)) || coveredMeetsOpen(here.get(second), here.get(first)));
}
}
}
private static List<SeaInlet> fromPocket(List<SeaInlet> inlets, float pocketX, float pocketZ) {
return inlets.stream().filter(inlet -> inlet.xs()[0] == pocketX && inlet.zs()[0] == pocketZ).toList();
}
private static boolean coveredMeetsOpen(SeaInlet covered, SeaInlet open) {
int[] bounds = SeaInletRasterizer.bounds(open);
int[] column = new int[2];
int[] near = new int[2];
for (int z = bounds[1]; z <= bounds[3]; z++) {
for (int x = bounds[0]; x <= bounds[2]; x++) {
if (!SeaInletRasterizer.column(open, x, z, column) || column[1] != SeaInlet.OPEN) {
continue;
}
for (int dz = -SeaInletRasterizer.SHELL; dz <= SeaInletRasterizer.SHELL; dz++) {
for (int dx = -SeaInletRasterizer.SHELL; dx <= SeaInletRasterizer.SHELL; dx++) {
if (SeaInletRasterizer.column(covered, x + dx, z + dz, near) && near[1] != SeaInlet.OPEN) {
return true;
}
}
}
}
}
return false;
}
@Test
public void siteOnAWindowEdgeIsPlannedOnlyFromItsTargetWindow() {
HydrologySettings settings = InletTerrain.settings();
int spacing = settings.underground().seaInlets().spacing();
int site = Math.floorDiv(WindowKey.SIZE, spacing);
assertTrue("the site straddles the window edge", site * spacing < WindowKey.SIZE && (site + 1) * spacing > WindowKey.SIZE);
double coastZ = 160D;
InletTerrain terrain = InletTerrain.southCoast(coastZ);
List<SeaInlet> open = inSite(terrain.plan(settings), spacing, site);
assertEquals("the straddling site holds one inlet", 1, open.size());
WindowKey owner = WindowKey.containing((int) open.getFirst().xs()[1], (int) open.getFirst().zs()[1]);
float fromX = owner.wx() == 0 ? site * spacing - 16f : WindowKey.SIZE - 16f;
float toX = owner.wx() == 0 ? WindowKey.SIZE + 16f : (site + 1) * spacing + 16f;
Reach blocking = InletTerrain.eastWestReach(settings, fromX, toX, (float) coastZ + 4f, InletTerrain.SEA + 28);
List<SeaInlet> blocked = inSite(terrain.plan(settings, new ShapedNetwork(List.of(blocking), List.of())), spacing, site);
int doubled = 0;
for (SeaInlet inlet : blocked) {
doubled += WindowKey.containing((int) inlet.xs()[1], (int) inlet.zs()[1]).equals(owner) ? 0 : 1;
}
assertEquals("a window that cannot use the target window's coast plans nothing for the site", 0, doubled);
}
private static List<SeaInlet> inSite(List<SeaInlet> inlets, int spacing, int site) {
return inlets.stream().filter(inlet -> Math.floorDiv((int) inlet.xs()[1], spacing) == site).toList();
}
@Test
public void staysUnderSurfaceWaterBeds() {
HydrologySettings settings = InletTerrain.settings();
int clearance = settings.underground().seaInlets().roofClearance();
InletTerrain terrain = InletTerrain.cliff(30D);
Reach deep = InletTerrain.northSouthReach(settings, 232f, SEA + 26, 2f, 1.5f);
List<SeaInlet> under = terrain.plan(settings, new ShapedNetwork(List.of(deep), List.of()));
assertFalse(under.isEmpty());
int[] column = new int[2];
int crossings = 0;
for (SeaInlet inlet : under) {
for (int z = SeaInletRasterizer.bounds(inlet)[1]; z <= SeaInletRasterizer.bounds(inlet)[3]; z++) {
if (SeaInletRasterizer.column(inlet, 232, z, column)) {
crossings++;
assertTrue(inlet + " roof under the river bed", (SEA + 26 - 1.5f) - column[1] >= clearance);
}
}
}
assertTrue("inlets pass under the deep river", crossings > 0);
Reach shallow = InletTerrain.northSouthReach(settings, 232f, SEA + 12, 2f, 1.5f);
for (SeaInlet inlet : terrain.plan(settings, new ShapedNetwork(List.of(shallow), List.of()))) {
int[] bounds = SeaInletRasterizer.bounds(inlet);
assertTrue(inlet + " stops before the low river at x=232", bounds[2] < 232 - settings.tiers().get(0).bankBand());
}
}
@Test
public void inletsKeepClearOfSeaLevelDeltaChannels() {
HydrologySettings settings = InletTerrain.settings();
InletTerrain terrain = InletTerrain.cliff(30D);
List<SeaInlet> open = terrain.plan(settings);
assertFalse(open.isEmpty());
SeaInlet first = open.get(0);
Reach channel = deltaChannel(settings, first.xs()[1] + 16f, first.zs()[1], InletTerrain.COAST_X - 12f, first.zs()[0]);
assertTrue("the channel runs through the inlet's opening", crosses(first, channel));
List<SeaInlet> planned = terrain.plan(settings, new ShapedNetwork(List.of(channel), List.of()));
for (SeaInlet inlet : planned) {
assertFalse(inlet + " crosses the delta channel", crosses(inlet, channel));
}
}
private static Reach deltaChannel(HydrologySettings settings, float fromX, float fromZ, float toX, float toZ) {
int points = Math.max(2, (int) Math.ceil(Math.hypot(toX - fromX, toZ - fromZ) / 2D) + 1);
float[] xs = new float[points];
float[] zs = new float[points];
int[] grades = new int[points];
float[] widths = new float[points];
float[] depths = new float[points];
ReachStyle[] styles = new ReachStyle[points];
for (int point = 0; point < points; point++) {
xs[point] = fromX + (toX - fromX) * point / (points - 1);
zs[point] = fromZ + (toZ - fromZ) * point / (points - 1);
grades[point] = SEA;
widths[point] = 3.5f;
depths[point] = 1.5f;
styles[point] = ReachStyle.MOUTH;
}
return new Reach(79L, settings.tiers().get(2), 0L, xs, zs, grades, widths, depths, styles, 150000f);
}
private static boolean crosses(SeaInlet inlet, Reach channel) {
int[] bounds = SeaInletRasterizer.bounds(inlet);
int[] column = new int[2];
for (int z = bounds[1]; z <= bounds[3]; z++) {
for (int x = bounds[0]; x <= bounds[2]; x++) {
if (SeaInletRasterizer.column(inlet, x, z, column) && inWater(channel, x, z)) {
return true;
}
}
}
return false;
}
private static boolean inWater(Reach reach, int x, int z) {
for (int segment = 0; segment + 1 < reach.xs().length; segment++) {
double ax = reach.xs()[segment];
double az = reach.zs()[segment];
double dx = reach.xs()[segment + 1] - ax;
double dz = reach.zs()[segment + 1] - az;
double length = dx * dx + dz * dz;
double t = length == 0D ? 0D : Math.clamp(((x - ax) * dx + (z - az) * dz) / length, 0D, 1D);
if (Math.hypot(x - (ax + t * dx), z - (az + t * dz)) <= reach.halfWidth()[segment]) {
return true;
}
}
return false;
}
@Test
public void endsInChamber() {
HydrologySettings settings = InletTerrain.settings();
HydrologySettings.SeaInlets config = settings.underground().seaInlets();
InletTerrain terrain = InletTerrain.cliff(30D);
int[] column = new int[2];
List<SeaInlet> inlets = terrain.plan(settings);
assertFalse(inlets.isEmpty());
for (SeaInlet inlet : inlets) {
int last = inlet.stations() - 1;
assertEquals(inlet.xs()[last], inlet.chamberX(), 0f);
assertEquals(inlet.zs()[last], inlet.chamberZ(), 0f);
assertTrue(inlet + " chamber radius", inlet.chamberRadius() >= config.chamberRadius().min()
&& inlet.chamberRadius() <= config.chamberRadius().max());
int reach = inlet.chamberRadius() - 1;
for (int dz = -reach; dz <= reach; dz++) {
for (int dx = -reach; dx <= reach; dx++) {
if (dx * dx + dz * dz > reach * reach) {
continue;
}
assertTrue(inlet + " chamber column " + dx + "," + dz,
SeaInletRasterizer.column(inlet, inlet.chamberX() + dx, inlet.chamberZ() + dz, column));
assertTrue(column[0] < SEA);
}
}
float length = InletTerrain.length(inlet);
assertTrue(inlet + " length " + length, length >= config.length().min() && length <= config.length().max() + InletTerrain.CELL * 1.5f);
}
}
@Test
public void continuesInlandPastTheHeadOfTheCoastalCatchment() {
double crest = 40D;
InletTerrain terrain = InletTerrain.coastalRidge(crest);
List<SeaInlet> inlets = terrain.plan(InletTerrain.settings());
assertFalse("a short coastal catchment still holds inlets", inlets.isEmpty());
for (SeaInlet inlet : inlets) {
assertTrue(inlet + " passes under the ridge crest", inlet.xs()[inlet.stations() - 1] > InletTerrain.COAST_X + crest + InletTerrain.CELL);
assertTrue(inlet + " length", InletTerrain.length(inlet) >= InletTerrain.settings().underground().seaInlets().length().min());
}
}
@Test
public void noInletWithoutCliff() {
assertTrue(InletTerrain.cliff(4D).plan(InletTerrain.settings()).isEmpty());
IrisHydrology disabled = new IrisHydrology();
disabled.getUnderground().getSeaInlets().setEnabled(false);
assertTrue(InletTerrain.cliff(30D).plan(InletTerrain.settings(disabled)).isEmpty());
}
@Test
public void deterministic() {
HydrologySettings settings = InletTerrain.settings();
List<SeaInlet> first = InletTerrain.cliff(30D).plan(settings);
List<SeaInlet> second = InletTerrain.cliff(30D).plan(InletTerrain.settings());
assertEquals(first, second);
assertEquals(first.size(), first.stream().mapToLong(SeaInlet::id).distinct().count());
InletTerrain terrain = InletTerrain.cliff(30D);
List<SeaInlet> otherSeed = new SeaInletPlanner(HydrologySettings.compile(new IrisHydrology(), 99L, SEA, InletTerrain.MIN_Y,
InletTerrain.MAX_Y)).plan(terrain.window, terrain.grid, terrain.samples, terrain.receivers, terrain.accumulation,
new ShapedNetwork(List.of(), List.of()), 99L);
assertNotEquals(first, otherSeed);
}
@Test
public void inletsAgreeAcrossWindowsOnOpenCoast() {
IrisHydrology dense = new IrisHydrology();
dense.getUnderground().getSeaInlets().setSpacing(64);
HydrologySettings settings = InletTerrain.settings(dense);
InletTerrain coast = InletTerrain.openCoast();
List<WindowKey> windows = new ArrayList<>(9);
for (int wz = 0; wz <= 2; wz++) {
for (int wx = 0; wx <= 2; wx++) {
windows.add(new WindowKey(wx, wz));
}
}
Map<WindowKey, List<SeaInlet>> views = views(coast, settings, windows);
assertEquals("planning the windows in reverse order changes nothing", views, views(coast, settings, windows.reversed()));
List<String> disagreements = new ArrayList<>();
int owned = 0;
int crossing = 0;
int seen = 0;
for (WindowKey owner : windows) {
for (SeaInlet inlet : views.get(owner)) {
if (!owner.equals(owner(inlet))) {
continue;
}
owned++;
crossing += leavesWindow(inlet, owner) ? 1 : 0;
for (WindowKey view : windows) {
if (view.equals(owner)) {
continue;
}
for (SeaInlet other : views.get(view)) {
if (other.id() != inlet.id()) {
continue;
}
seen++;
if (!other.equals(inlet)) {
disagreements.add(inlet + " of " + owner + " is " + other + " in " + view);
}
}
}
}
}
assertTrue(disagreements.size() + " views disagree with the owner: " + disagreements, disagreements.isEmpty());
assertTrue("owned inlets " + owned, owned >= 20);
assertTrue("owned inlets that neighbouring windows also plan " + seen, seen >= 60);
assertTrue("owned inlets crossing a window line " + crossing, crossing > 0);
}
private static Map<WindowKey, List<SeaInlet>> views(InletTerrain coast, HydrologySettings settings, List<WindowKey> order) {
Map<WindowKey, List<SeaInlet>> views = new LinkedHashMap<>();
for (WindowKey window : order) {
views.put(window, coast.span(window).plan(settings));
}
return views;
}
private static WindowKey owner(SeaInlet inlet) {
return WindowKey.containing((int) Math.floor(inlet.xs()[1]), (int) Math.floor(inlet.zs()[1]));
}
private static boolean leavesWindow(SeaInlet inlet, WindowKey owner) {
int[] bounds = SeaInletRasterizer.bounds(inlet);
return !WindowKey.containing(bounds[0], bounds[1]).equals(owner) || !WindowKey.containing(bounds[2], bounds[3]).equals(owner);
}
@Test
public void ownedInletsNeverConflictAcrossAWindowLine() {
IrisHydrology config = new IrisHydrology();
config.getUnderground().getSeaInlets().setSpacing(WindowKey.SIZE);
config.getUnderground().getSeaInlets().setLength(new KList<>(256, 400));
config.getUnderground().getSeaInlets().setHalfWidth(new KList<>(12D, 12D));
HydrologySettings settings = InletTerrain.settings(config);
int bayZ = 904;
WindowKey west = new WindowKey(1, 1);
WindowKey east = new WindowKey(2, 1);
single(InletTerrain.bay(1008, 1008, bayZ).wide(west, 3).plan(settings), west);
single(InletTerrain.bay(1032, 1032, bayZ).wide(east, 3).plan(settings), east);
InletTerrain bay = InletTerrain.bay(1016, 1024, bayZ);
List<SeaInlet> reference = bay.wide(west, 3).plan(settings);
List<SeaInlet> union = new ArrayList<>();
for (int wz = 0; wz <= 2; wz++) {
for (int wx = 0; wx <= 2; wx++) {
WindowKey window = new WindowKey(wx, wz);
List<SeaInlet> own = bay.span(window).plan(settings).stream().filter(inlet -> owner(inlet).equals(window)).toList();
assertEquals(window + " owns what the full-context plan gives it", reference.stream()
.filter(inlet -> owner(inlet).equals(window)).toList(), own);
union.addAll(own);
}
}
assertEquals("the two windows beside the bay keep one inlet between them: " + union, 1, union.size());
for (int first = 0; first < union.size(); first++) {
for (int second = first + 1; second < union.size(); second++) {
assertFalse(union.get(first) + " and " + union.get(second) + " cross a covered passage with an open slot",
coveredMeetsOpen(union.get(first), union.get(second)) || coveredMeetsOpen(union.get(second), union.get(first)));
}
}
}
private static SeaInlet single(List<SeaInlet> inlets, WindowKey window) {
List<SeaInlet> own = inlets.stream().filter(inlet -> owner(inlet).equals(window)).toList();
assertEquals(window + " owns one bay inlet: " + own, 1, own.size());
return own.getFirst();
}
@Test
public void extentGuardKeepsEveryPlannerLookupInsideTheOwnersSpan() {
for (double halfWidth : new double[]{1D, 16D}) {
for (int chamber = 1; chamber <= 32; chamber++) {
int length = WindowKey.SIZE - 12 - Math.max((int) Math.ceil(halfWidth), chamber) - 3;
IrisHydrology config = new IrisHydrology();
config.getUnderground().getSeaInlets().setLength(new KList<>(64, length));
config.getUnderground().getSeaInlets().setHalfWidth(new KList<>(1D, halfWidth));
config.getUnderground().getSeaInlets().setChamberRadius(new KList<>(1, chamber));
InletTerrain.settings(config);
long reach = SeaInletPlanner.lookupReach(length, chamber);
assertTrue("length " + length + " chamber " + chamber + " looks " + reach + " blocks out", reach <= WindowKey.SIZE);
}
}
}
@Test
public void longestInletAtTheFarEdgeOfItsWindowStaysInsideItsSpan() {
IrisHydrology config = new IrisHydrology();
config.getUnderground().getSeaInlets().setLength(new KList<>(465, 465));
config.getUnderground().getSeaInlets().setChamberRadius(new KList<>(32, 32));
HydrologySettings settings = InletTerrain.settings(config);
WindowKey window = new WindowKey(0, 0);
List<SeaInlet> owned = InletTerrain.eastEdgeCoast().plan(settings).stream().filter(inlet -> owner(inlet).equals(window)).toList();
assertFalse("inlets start on the window's last column", owned.isEmpty());
for (SeaInlet inlet : owned) {
assertEquals(inlet + " starts on the window's last column", WindowKey.SIZE - InletTerrain.CELL, inlet.xs()[1], 0f);
assertTrue(inlet + " runs the full length toward the span edge", inlet.chamberX() >= WindowKey.SIZE + 448);
}
}
@Test
public void ownInletCutOffByTheGridEdgeFailsClosed() {
InletTerrain narrow = InletTerrain.cliff(30D).narrow(0, 0);
IllegalStateException failure = assertThrows(IllegalStateException.class, () -> narrow.plan(InletTerrain.settings()));
assertTrue(failure.getMessage(),
failure.getMessage().matches("Sea inlet -?\\d+ of window WindowKey\\[wx=0, wz=0\\] reaches the edge of .*"));
}
@Test
public void inletsReachingPastTheNextWindowAreRejected() {
IrisHydrology fits = new IrisHydrology();
fits.getUnderground().getSeaInlets().setLength(new KList<>(64, 485));
InletTerrain.settings(fits);
IrisHydrology last = new IrisHydrology();
last.getUnderground().getSeaInlets().setLength(new KList<>(64, 486));
IllegalArgumentException failure = assertThrows(IllegalArgumentException.class, () -> InletTerrain.settings(last));
assertTrue(failure.getMessage(), failure.getMessage().contains("last step"));
}
}
@@ -1,451 +0,0 @@
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.mantle.MantleWriter;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import static org.junit.Assert.assertEquals;
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.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.when;
public class SeaInletRasterizerTest {
private static final int SEA = 40;
private static final String FLUID = HydrologyCaveCell.SEA_FLUID;
private static final int CAVE_CLEARANCE = 2;
@Test
public void waterLevelIsSeaLevelEverywhere() {
Map<Long, HydrologyCaveCell> cells = rasterize(List.of(inlet(1L, 15f)), order(false));
int wetColumns = 0;
Map<Long, Integer> tops = new TreeMap<>();
for (Map.Entry<Long, HydrologyCaveCell> entry : cells.entrySet()) {
int y = y(entry.getKey());
HydrologyCaveAction action = entry.getValue().action();
if (action == HydrologyCaveAction.WET_SOURCE) {
assertTrue("water at " + y, y <= SEA);
tops.merge(column(entry.getKey()), y, Math::max);
} else if (action == HydrologyCaveAction.DRY_AIR) {
assertTrue("air at " + y, y > SEA);
}
assertEquals(FLUID, entry.getValue().fluidProfileKey());
}
for (int top : tops.values()) {
assertEquals(SEA, top);
wetColumns++;
}
assertTrue("wet columns " + wetColumns, wetColumns > 300);
}
@Test
public void everyWaterCellIsHeldBySealedOrWetNeighbours() {
List<SeaInlet> inlets = List.of(inlet(1L, 15f), inlet(2L, 30f));
Map<Long, HydrologyCaveCell> cells = rasterize(inlets, order(false));
int checked = 0;
for (Map.Entry<Long, HydrologyCaveCell> entry : cells.entrySet()) {
if (entry.getValue().action() != HydrologyCaveAction.WET_SOURCE) {
continue;
}
int x = x(entry.getKey());
int y = y(entry.getKey());
int z = z(entry.getKey());
for (int[] side : new int[][]{{1, 0, 0}, {-1, 0, 0}, {0, 0, 1}, {0, 0, -1}, {0, -1, 0}}) {
if (paintedSlot(inlets, x + side[0], y + side[1], z + side[2])) {
continue;
}
HydrologyCaveCell neighbour = cells.get(key(x + side[0], y + side[1], z + side[2]));
assertNotNull("water at " + x + "," + y + "," + z + " has an open side " + side[0] + "," + side[1] + "," + side[2], neighbour);
assertTrue(neighbour.action() == HydrologyCaveAction.WET_SOURCE || neighbour.action() == HydrologyCaveAction.SEAL_GUARD);
}
checked++;
}
assertTrue(checked > 1000);
}
@Test
public void sealKeepsCavesTwoBlocksFromTheWater() {
List<SeaInlet> inlets = List.of(inlet(1L, 15f));
Map<Long, HydrologyCaveCell> cells = rasterize(inlets, order(false));
int checked = 0;
for (Map.Entry<Long, HydrologyCaveCell> entry : cells.entrySet()) {
if (entry.getValue().action() != HydrologyCaveAction.WET_SOURCE) {
continue;
}
int x = x(entry.getKey());
int y = y(entry.getKey());
int z = z(entry.getKey());
for (int below = 0; below <= CAVE_CLEARANCE; below++) {
for (int dz = -CAVE_CLEARANCE; dz <= CAVE_CLEARANCE; dz++) {
for (int dx = -CAVE_CLEARANCE; dx <= CAVE_CLEARANCE; dx++) {
if (paintedSlot(inlets, x + dx, y - below, z + dz)) {
continue;
}
HydrologyCaveCell held = cells.get(key(x + dx, y - below, z + dz));
assertNotNull("no seal at " + (x + dx) + "," + (y - below) + "," + (z + dz) + " near water at " + x + "," + y + "," + z,
held);
assertTrue(held.action() == HydrologyCaveAction.WET_SOURCE || held.action() == HydrologyCaveAction.SEAL_GUARD);
}
}
}
if (cells.get(key(x, y - 1, z)).action() == HydrologyCaveAction.SEAL_GUARD) {
for (int under = 1; under <= CAVE_CLEARANCE + 1; under++) {
assertEquals("bed and two blocks under the water at " + x + "," + y + "," + z, HydrologyCaveAction.SEAL_GUARD,
cells.get(key(x, y - under, z)).action());
}
}
checked++;
}
assertTrue(checked > 1000);
}
@Test
public void openSlotColumnsLeaveTheirWaterToThePainter() {
SeaInlet inlet = inlet(1L, 15f);
Map<Long, HydrologyCaveCell> cells = rasterize(List.of(inlet), order(false));
int[] column = new int[2];
int sealed = 0;
for (Map.Entry<Long, HydrologyCaveCell> entry : cells.entrySet()) {
int x = x(entry.getKey());
int z = z(entry.getKey());
if (!SeaInletRasterizer.column(inlet, x, z, column) || column[1] != SeaInlet.OPEN) {
continue;
}
assertEquals("open slot column " + x + "," + z + " holds only its seal", HydrologyCaveAction.SEAL_GUARD, entry.getValue().action());
assertTrue(y(entry.getKey()) <= column[0]);
sealed++;
}
assertTrue("open slot seal cells " + sealed, sealed > 100);
assertTrue(cells.values().stream().anyMatch(cell -> cell.action() == HydrologyCaveAction.DRY_AIR));
assertTrue(cells.values().stream().anyMatch(cell -> cell.action() == HydrologyCaveAction.WET_SOURCE));
}
@Test
public void openSlotBedsKeepTheirSeaFloorOnTwoSealedBlocks() {
SeaInlet inlet = inlet(1L, 15f);
Map<Long, HydrologyCaveCell> cells = rasterize(List.of(inlet), order(false));
int[] column = new int[2];
int beds = 0;
int covered = 0;
for (int z = -16; z <= 63; z++) {
for (int x = -32; x <= 79; x++) {
if (!SeaInletRasterizer.column(inlet, x, z, column)) {
continue;
}
int floor = column[0];
if (column[1] == SeaInlet.OPEN) {
assertNull("the open slot bed at " + x + "," + floor + "," + z + " keeps the painted sea floor", cells.get(key(x, floor, z)));
for (int under = 1; under <= SeaInletRasterizer.SHELL; under++) {
HydrologyCaveCell sealed = cells.get(key(x, floor - under, z));
assertNotNull("rock under the open slot bed at " + x + "," + (floor - under) + "," + z, sealed);
assertEquals(HydrologyCaveAction.SEAL_GUARD, sealed.action());
}
beds++;
} else {
assertEquals("covered bed at " + x + "," + floor + "," + z, HydrologyCaveAction.SEAL_GUARD, cells.get(key(x, floor, z)).action());
covered++;
}
}
}
assertTrue("open slot beds " + beds, beds > 20);
assertTrue("covered beds " + covered, covered > 100);
}
@Test
public void subterrainFluidWithinTwoBlocksOfInletAirAboveSeaLevelIsSealed() {
SeaInlet inlet = inlet(1L, 15f);
SeaInletRasterizer.SubterrainFluid flooded = (x, y, z) -> Math.floorMod(x + 2 * z + y, 5) != 0;
Map<Long, HydrologyCaveCell> plain = rasterize(List.of(inlet), order(false));
for (Map.Entry<Long, HydrologyCaveCell> entry : plain.entrySet()) {
assertTrue("without subterrain fluid nothing above sea level is sealed",
y(entry.getKey()) <= SEA || entry.getValue().action() == HydrologyCaveAction.DRY_AIR);
}
Map<Long, HydrologyCaveCell> cells = rasterize(List.of(inlet), order(false), flooded);
int checked = 0;
for (Map.Entry<Long, HydrologyCaveCell> entry : cells.entrySet()) {
if (entry.getValue().action() != HydrologyCaveAction.DRY_AIR) {
continue;
}
int x = x(entry.getKey());
int y = y(entry.getKey());
int z = z(entry.getKey());
for (int dy = -2; dy <= 2; dy++) {
for (int dz = -2; dz <= 2; dz++) {
for (int dx = -2; dx <= 2; dx++) {
if (y + dy <= SEA || !flooded.at(x + dx, y + dy, z + dz)) {
continue;
}
HydrologyCaveCell held = cells.get(key(x + dx, y + dy, z + dz));
assertNotNull("subterrain fluid at " + (x + dx) + "," + (y + dy) + "," + (z + dz) + " beside inlet air at " + x + "," + y
+ "," + z, held);
assertTrue(held.action() == HydrologyCaveAction.DRY_AIR || held.action() == HydrologyCaveAction.SEAL_GUARD);
checked++;
}
}
}
}
int sealed = 0;
for (Map.Entry<Long, HydrologyCaveCell> entry : cells.entrySet()) {
int x = x(entry.getKey());
int y = y(entry.getKey());
int z = z(entry.getKey());
if (y <= SEA || entry.getValue().action() != HydrologyCaveAction.SEAL_GUARD) {
continue;
}
assertTrue("only subterrain fluid is sealed above sea level, not " + x + "," + y + "," + z, flooded.at(x, y, z));
assertTrue("the seal at " + x + "," + y + "," + z + " lies within two blocks of inlet air", nearAir(cells, x, y, z));
sealed++;
}
assertTrue("checked " + checked, checked > 1000);
assertTrue("sealed " + sealed, sealed > 200);
assertEquals(cells, rasterize(List.of(inlet), order(true), flooded));
}
private static boolean nearAir(Map<Long, HydrologyCaveCell> cells, int x, int y, int z) {
for (int dy = -2; dy <= 2; dy++) {
for (int dz = -2; dz <= 2; dz++) {
for (int dx = -2; dx <= 2; dx++) {
HydrologyCaveCell cell = cells.get(key(x + dx, y + dy, z + dz));
if (cell != null && cell.action() == HydrologyCaveAction.DRY_AIR) {
return true;
}
}
}
}
return false;
}
private static boolean paintedSlot(List<SeaInlet> inlets, int x, int y, int z) {
int[] column = new int[2];
for (SeaInlet inlet : inlets) {
if (SeaInletRasterizer.column(inlet, x, z, column) && column[1] == SeaInlet.OPEN && y >= column[0] && y <= inlet.waterLevel()) {
return true;
}
}
return false;
}
@Test(timeout = 20_000L)
public void thinDiagonalPassagesSealTheirBedWithoutRunningAway() {
float[] xs = {0f, 8f, 16f, 24f, 32f};
float[] zs = {0f, 8f, 16f, 24f, 32f};
float[] halfWidth = {0.6f, 0.6f, 0.6f, 0.6f, 0.6f};
int[] floor = {SEA - 3, SEA - 3, SEA - 3, SEA - 3, SEA - 3};
int[] ceiling = {SEA + 4, SEA + 4, SEA + 4, SEA + 4, SEA + 4};
SeaInlet thin = new SeaInlet(9L, xs, zs, halfWidth, SEA, floor, ceiling, 32, 32, 2);
Map<Long, HydrologyCaveCell> cells = rasterize(List.of(thin), order(false));
int wet = 0;
for (Map.Entry<Long, HydrologyCaveCell> entry : cells.entrySet()) {
assertTrue("no cell runs away below the shell", y(entry.getKey()) >= SEA - 3 - CAVE_CLEARANCE - 1);
if (entry.getValue().action() == HydrologyCaveAction.WET_SOURCE) {
wet++;
assertEquals(HydrologyCaveAction.SEAL_GUARD, cells.get(key(x(entry.getKey()), SEA - 3, z(entry.getKey()))).action());
}
}
assertTrue(wet > 10);
}
@Test
public void passageEndingAtAnOldChunkIsSealed() {
SeaInlet inlet = inlet(1L, 15f);
SeaInletRasterizer.HistoricalChunks old = (chunkX, chunkZ) -> chunkX == 2;
Map<Long, HydrologyCaveCell> open = rasterize(List.of(inlet), order(false), SeaInletRasterizer.SubterrainFluid.NOWHERE,
SeaInletRasterizer.HistoricalChunks.NONE);
Map<Long, HydrologyCaveCell> cells = rasterize(List.of(inlet), newChunks(order(false), old), SeaInletRasterizer.SubterrainFluid.NOWHERE,
old);
int[] column = new int[2];
int seamColumns = 0;
for (int z = -16; z <= 63; z++) {
for (int x = -32; x <= 79; x++) {
if (old.at(x >> 4, z >> 4) || !nearOldChunk(old, x, z)) {
continue;
}
if (!SeaInletRasterizer.column(inlet, x, z, column) || column[1] == SeaInlet.OPEN) {
continue;
}
assertEquals("without old chunks the seam column " + x + "," + z + " holds water", HydrologyCaveAction.WET_SOURCE,
open.get(key(x, inlet.waterLevel(), z)).action());
for (int y = column[0] - SeaInletRasterizer.SHELL; y <= column[1]; y++) {
HydrologyCaveCell sealed = cells.get(key(x, y, z));
assertNotNull("no seal at " + x + "," + y + "," + z + " beside the old chunk", sealed);
assertEquals("seal at " + x + "," + y + "," + z + " beside the old chunk", HydrologyCaveAction.SEAL_GUARD, sealed.action());
}
seamColumns++;
}
}
int wet = 0;
for (Map.Entry<Long, HydrologyCaveCell> entry : cells.entrySet()) {
int x = x(entry.getKey());
int y = y(entry.getKey());
int z = z(entry.getKey());
assertFalse("old chunk " + (x >> 4) + "," + (z >> 4) + " was written", old.at(x >> 4, z >> 4));
HydrologyCaveAction action = entry.getValue().action();
if (action == HydrologyCaveAction.SEAL_GUARD) {
continue;
}
assertFalse(action + " at " + x + "," + y + "," + z + " lies within two blocks of an old chunk", nearOldChunk(old, x, z));
if (action != HydrologyCaveAction.WET_SOURCE) {
continue;
}
for (int[] side : new int[][]{{1, 0, 0}, {-1, 0, 0}, {0, 0, 1}, {0, 0, -1}, {0, -1, 0}}) {
if (paintedSlot(List.of(inlet), x + side[0], y + side[1], z + side[2])) {
continue;
}
HydrologyCaveCell neighbour = cells.get(key(x + side[0], y + side[1], z + side[2]));
assertNotNull("water at " + x + "," + y + "," + z + " has an open side " + side[0] + "," + side[1] + "," + side[2], neighbour);
assertTrue(neighbour.action() == HydrologyCaveAction.WET_SOURCE || neighbour.action() == HydrologyCaveAction.SEAL_GUARD);
}
wet++;
}
assertTrue("covered seam columns " + seamColumns, seamColumns > 10);
assertTrue("water cells away from the old chunks " + wet, wet > 300);
assertEquals(cells, rasterize(List.of(inlet), newChunks(order(true), old), SeaInletRasterizer.SubterrainFluid.NOWHERE, old));
}
private static boolean nearOldChunk(SeaInletRasterizer.HistoricalChunks old, int x, int z) {
for (int dz = -SeaInletRasterizer.SHELL; dz <= SeaInletRasterizer.SHELL; dz++) {
for (int dx = -SeaInletRasterizer.SHELL; dx <= SeaInletRasterizer.SHELL; dx++) {
if (old.at((x + dx) >> 4, (z + dz) >> 4)) {
return true;
}
}
}
return false;
}
private static List<int[]> newChunks(List<int[]> chunks, SeaInletRasterizer.HistoricalChunks old) {
List<int[]> fresh = new ArrayList<>();
for (int[] chunk : chunks) {
if (!old.at(chunk[0], chunk[1])) {
fresh.add(chunk);
}
}
return fresh;
}
@Test
public void chunkOrderAndInletOrderDoNotChangeTheCells() {
List<SeaInlet> inlets = List.of(inlet(1L, 15f), inlet(2L, 22f));
Map<Long, HydrologyCaveCell> forward = rasterize(inlets, order(false));
Map<Long, HydrologyCaveCell> reverse = rasterize(List.of(inlets.get(1), inlets.get(0)), order(true));
assertEquals(forward, reverse);
assertFalse(forward.isEmpty());
}
@Test
public void chunksWriteOnlyTheirOwnColumns() {
SeaInlet inlet = inlet(1L, 15f);
Map<Long, HydrologyCaveCell> cells = new TreeMap<>();
MantleWriter writer = writer(cells, 1, 0);
new SeaInletRasterizer().write(inlet, 1, 0, writer, FLUID, SeaInletRasterizer.SubterrainFluid.NOWHERE,
SeaInletRasterizer.HistoricalChunks.NONE);
assertFalse(cells.isEmpty());
for (long key : cells.keySet()) {
assertEquals(1, x(key) >> 4);
assertEquals(0, z(key) >> 4);
}
Map<Long, HydrologyCaveCell> far = new TreeMap<>();
new SeaInletRasterizer().write(inlet, 20, 20, writer(far, 20, 20), FLUID, SeaInletRasterizer.SubterrainFluid.NOWHERE,
SeaInletRasterizer.HistoricalChunks.NONE);
assertTrue(far.isEmpty());
assertFalse(SeaInletRasterizer.touches(inlet, 20, 20));
}
private static SeaInlet inlet(long id, float z) {
float[] xs = {-8f, 0f, 8f, 16f, 24f, 32f, 40f, 48f};
float[] zs = new float[xs.length];
float[] halfWidth = new float[xs.length];
int[] floor = new int[xs.length];
int[] ceiling = new int[xs.length];
for (int station = 0; station < xs.length; station++) {
zs[station] = z + (station % 2 == 0 ? 0f : 3f);
halfWidth[station] = 5f - station * 0.4f;
floor[station] = SEA - 2 - station % 3;
ceiling[station] = station < 2 ? SeaInlet.OPEN : SEA + 4 + station % 4;
}
return new SeaInlet(id, xs, zs, halfWidth, SEA, floor, ceiling, 48, (int) z, 7);
}
private static List<int[]> order(boolean reverse) {
List<int[]> chunks = new ArrayList<>();
for (int chunkZ = -1; chunkZ <= 3; chunkZ++) {
for (int chunkX = -2; chunkX <= 4; chunkX++) {
chunks.add(new int[]{chunkX, chunkZ});
}
}
if (reverse) {
Collections.reverse(chunks);
}
return chunks;
}
private static Map<Long, HydrologyCaveCell> rasterize(List<SeaInlet> inlets, List<int[]> chunks) {
return rasterize(inlets, chunks, SeaInletRasterizer.SubterrainFluid.NOWHERE);
}
private static Map<Long, HydrologyCaveCell> rasterize(List<SeaInlet> inlets, List<int[]> chunks, SeaInletRasterizer.SubterrainFluid subterrain) {
return rasterize(inlets, chunks, subterrain, SeaInletRasterizer.HistoricalChunks.NONE);
}
private static Map<Long, HydrologyCaveCell> rasterize(List<SeaInlet> inlets, List<int[]> chunks, SeaInletRasterizer.SubterrainFluid subterrain,
SeaInletRasterizer.HistoricalChunks old) {
Map<Long, HydrologyCaveCell> cells = new TreeMap<>();
SeaInletRasterizer rasterizer = new SeaInletRasterizer();
for (int[] chunk : chunks) {
MantleWriter writer = writer(cells, chunk[0], chunk[1]);
for (SeaInlet inlet : inlets) {
rasterizer.write(inlet, chunk[0], chunk[1], writer, FLUID, subterrain, old);
}
}
return cells;
}
private static MantleWriter writer(Map<Long, HydrologyCaveCell> cells, int chunkX, int chunkZ) {
MantleWriter writer = mock(MantleWriter.class);
doAnswer(call -> {
int x = call.getArgument(0);
int z = call.getArgument(2);
if (x >> 4 != chunkX || z >> 4 != chunkZ) {
throw new AssertionError("chunk " + chunkX + "," + chunkZ + " wrote " + x + "," + z);
}
cells.put(key(x, call.getArgument(1), z), call.getArgument(3));
return null;
}).when(writer).setData(anyInt(), anyInt(), anyInt(), any(HydrologyCaveCell.class));
when(writer.getDataIfPresent(anyInt(), anyInt(), anyInt(), eq(HydrologyCaveCell.class)))
.thenAnswer(call -> cells.get(key(call.getArgument(0), call.getArgument(1), call.getArgument(2))));
return writer;
}
private static long key(int x, int y, int z) {
return ((long) (x + 4096) << 40) | ((long) (z + 4096) << 20) | (y + 4096);
}
private static long column(long key) {
return key >>> 20;
}
private static int x(long key) {
return (int) (key >>> 40) - 4096;
}
private static int z(long key) {
return (int) ((key >>> 20) & 0xFFFFF) - 4096;
}
private static int y(long key) {
return (int) (key & 0xFFFFF) - 4096;
}
}
@@ -837,7 +837,7 @@ public class PondPlannerTest {
long key = ((long) (x >> 4) << 32) | ((z >> 4) & 0xFFFFFFFFL);
ChunkWaterRaster raster = rasters.get(key);
if (raster == null) {
WindowPlan window = new WindowPlan(WindowKey.containing(x, z), List.of(), List.of(pond), List.of());
WindowPlan window = new WindowPlan(WindowKey.containing(x, z), List.of(), List.of(pond));
IndexedWindow indexed = new IndexedWindow(window, ReachIndex.build(window.key(), List.of(), List.of(pond)));
List<RegionPlan> regions = new ArrayList<>();
for (RegionKey region : ChunkRasterizer.lakeRegions(x >> 4, z >> 4)) {
@@ -2,8 +2,6 @@ package art.arcane.iris.generation.mantle;
import art.arcane.iris.generation.hydrology.config.IrisHydrology;
import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.underground.SeaInletRasterizer;
import art.arcane.iris.testsupport.WaterScene;
import art.arcane.volmlib.util.math.PowerOfTwoCoordinates;
import org.junit.Test;
@@ -101,99 +99,6 @@ public class CaveCeilingMaskTest {
}
}
@Test
public void cavesStayOutOfInletHeadroom() {
SeaInlet inlet = inlet();
int[] bounds = SeaInletRasterizer.bounds(inlet);
long[] bands = new long[256];
int[] column = new int[2];
int covered = 0;
int around = 0;
for (int chunkZ = (bounds[1] >> 4) - 1; chunkZ <= (bounds[3] >> 4) + 1; chunkZ++) {
for (int chunkX = (bounds[0] >> 4) - 1; chunkX <= (bounds[2] >> 4) + 1; chunkX++) {
boolean masked = CaveCeilingMask.fillHeadroom(chunkX, chunkZ, List.of(inlet), ROOF_CLEARANCE, bands);
long[] headroom = masked ? bands : null;
boolean expectedMasked = false;
for (int lz = 0; lz < 16; lz++) {
for (int lx = 0; lx < 16; lx++) {
int x = (chunkX << 4) + lx;
int z = (chunkZ << 4) + lz;
int index = PowerOfTwoCoordinates.packLocal16(lx, lz);
int top = highestRoofWithinTwo(inlet, x, z);
if (top == NO_ROOF) {
for (int y = 0; y <= SEA + 64; y++) {
assertFalse("caves stay possible at " + x + "," + y + "," + z + " away from the inlet",
CaveCeilingMask.masked(null, headroom, index, y));
}
continue;
}
expectedMasked = true;
for (int y = inlet.waterLevel() + 1; y <= top; y++) {
assertTrue("caves stay out of the inlet headroom and roof at " + x + "," + y + "," + z,
CaveCeilingMask.masked(null, headroom, index, y));
}
assertFalse("the seal holds caves at the water level " + x + "," + z,
CaveCeilingMask.masked(null, headroom, index, inlet.waterLevel()));
assertFalse("caves stay possible above the inlet roof at " + x + "," + z,
CaveCeilingMask.masked(null, headroom, index, top + 1));
if (SeaInletRasterizer.column(inlet, x, z, column) && column[1] != SeaInlet.OPEN) {
covered++;
} else {
around++;
}
}
}
assertEquals("headroom flag for chunk " + chunkX + "," + chunkZ, expectedMasked, masked);
}
}
assertTrue("covered columns " + covered, covered > 300);
assertTrue("columns around the passage " + around, around > 100);
assertFalse(CaveCeilingMask.fillHeadroom(0, 0, List.of(), ROOF_CLEARANCE, bands));
}
@Test
public void headroomJoinsTheWaterCeilings() {
int[] ceilings = new int[256];
Arrays.fill(ceilings, UNMASKED);
ceilings[3] = 40;
long[] bands = new long[256];
assertTrue(CaveCeilingMask.fillHeadroom(0, 0, List.of(inlet()), ROOF_CLEARANCE, bands));
int index = PowerOfTwoCoordinates.packLocal16(12, 6);
assertTrue(CaveCeilingMask.masked(ceilings, null, 3, 41));
assertFalse(CaveCeilingMask.masked(ceilings, null, 3, 40));
assertFalse(CaveCeilingMask.masked(ceilings, bands, index, SEA));
assertTrue(CaveCeilingMask.masked(ceilings, bands, index, SEA + 1));
assertFalse(CaveCeilingMask.masked(null, null, index, SEA + 1));
}
private static SeaInlet inlet() {
float[] xs = {-8f, 0f, 8f, 16f, 24f, 32f, 40f, 48f};
float[] zs = new float[xs.length];
float[] halfWidth = new float[xs.length];
int[] floor = new int[xs.length];
int[] ceiling = new int[xs.length];
for (int station = 0; station < xs.length; station++) {
zs[station] = 6f + (station % 2 == 0 ? 0f : 3f);
halfWidth[station] = 5f - station * 0.4f;
floor[station] = SEA - 2 - station % 3;
ceiling[station] = station < 2 ? SeaInlet.OPEN : SEA + 4 + station % 4;
}
return new SeaInlet(1L, xs, zs, halfWidth, SEA, floor, ceiling, 48, 6, 7);
}
private static int highestRoofWithinTwo(SeaInlet inlet, int x, int z) {
int top = NO_ROOF;
int[] column = new int[2];
for (int dz = -CaveCeilingMask.CONTAINMENT; dz <= CaveCeilingMask.CONTAINMENT; dz++) {
for (int dx = -CaveCeilingMask.CONTAINMENT; dx <= CaveCeilingMask.CONTAINMENT; dx++) {
if (SeaInletRasterizer.column(inlet, x + dx, z + dz, column) && column[1] != SeaInlet.OPEN) {
top = Math.max(top, column[1] + ROOF_CLEARANCE);
}
}
}
return top;
}
static WaterScene scene(IrisHydrology config) {
IntBinaryOperator natural = (x, z) -> 80;
return new WaterScene(config, natural)
@@ -11,8 +11,6 @@ import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.hydrology.underground.CavePoolFiller;
import art.arcane.iris.generation.hydrology.underground.CaveVoxel;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
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;
@@ -188,48 +186,6 @@ public class MantleCarvedTerrainTest {
assertThrows(IllegalStateException.class, () -> carved.voxel(1, 20, 1));
}
@Test
public void inletSpaceFromEveryNeighbourChunkReadsAsForeignAndPoolsBesideItStayOutInEitherChunkOrder() {
Scene probe = inletScene();
MantleCarvedTerrain carved = probe.carved();
assertEquals("passage water", CaveVoxel.FOREIGN, carved.voxel(7, 28, 21));
assertEquals("passage air", CaveVoxel.FOREIGN, carved.voxel(10, 33, 21));
assertEquals("seal under the passage", CaveVoxel.FOREIGN, carved.voxel(10, 24, 21));
assertEquals("seal beside the passage", CaveVoxel.FOREIGN, carved.voxel(7, 25, 18));
assertEquals(CaveVoxel.SOLID, carved.voxel(7, 23, 18));
assertEquals(CaveVoxel.AIR, carved.voxel(7, 25, 17));
assertEquals(CaveVoxel.SOLID, carved.voxel(10, 34, 21));
assertEquals(CaveVoxel.SOLID, carved.voxel(10, 25, 26));
Map<Long, HydrologyCaveCell> forward = inletScene().generate(0, 1);
Map<Long, HydrologyCaveCell> reverse = inletScene().generate(1, 0);
assertEquals(forward, reverse);
int top = Integer.MIN_VALUE;
for (Map.Entry<Long, HydrologyCaveCell> entry : forward.entrySet()) {
if (entry.getValue().action() != HydrologyCaveAction.POOL_SOURCE) {
continue;
}
long cell = entry.getKey();
top = Math.max(top, cellY(cell));
for (int[] face : FACES) {
HydrologyCaveCell neighbour = forward.get(cell(cellX(cell) + face[0], cellY(cell) + face[1], cellZ(cell) + face[2]));
assertFalse("pool water at " + cellX(cell) + "," + cellY(cell) + "," + cellZ(cell) + " touches the inlet",
neighbour != null && HydrologyCaveCell.SEA_FLUID.equals(neighbour.fluidProfileKey()));
}
}
assertEquals("the pool stops one level below the inlet seal its next level would reach", 24, top);
for (int y = 24; y <= 30; y++) {
assertInlet(forward, 7, y, 19, HydrologyCaveAction.SEAL_GUARD);
}
for (int y = 27; y <= 30; y++) {
assertInlet(forward, 7, y, 21, HydrologyCaveAction.WET_SOURCE);
}
for (int y = 31; y <= 33; y++) {
assertInlet(forward, 7, y, 21, HydrologyCaveAction.DRY_AIR);
}
}
@Test
public void shallowPoolsUnderVolcanicSurfacesStayWater() {
IrisBiome volcanoes = biome("tropical/volcanoes", 0, "lava");
@@ -378,35 +334,6 @@ public class MantleCarvedTerrainTest {
return region;
}
private static Scene inletScene() {
Scene scene = new Scene();
Matter[] room = scene.chunk(0, 0);
for (int x = 2; x <= 13; x++) {
for (int z = 4; z <= 15; z++) {
for (int y = 22; y <= 36; y++) {
cavern(room, x, y, z, (byte) 0);
}
}
}
Matter[] channel = scene.chunk(0, 1);
for (int x = 6; x <= 8; x++) {
for (int z = 16; z <= 19; z++) {
for (int y = 25; y <= 30; y++) {
cavern(channel, x, y, z, (byte) 0);
}
}
}
scene.inlets.add(new SeaInlet(77L, new float[]{40f, -8f}, new float[]{22f, 22f}, new float[]{2f, 2f}, 30, new int[]{26, 26},
new int[]{33, 33}, -8, 22, 2));
return scene;
}
private static void assertInlet(Map<Long, HydrologyCaveCell> written, int x, int y, int z, HydrologyCaveAction action) {
HydrologyCaveCell cell = written.get(cell(x, y, z));
assertTrue("inlet " + action + " at " + x + "," + y + "," + z + " but found " + cell,
cell != null && cell.action() == action && HydrologyCaveCell.SEA_FLUID.equals(cell.fluidProfileKey()));
}
private static long cell(int x, int y, int z) {
return ((long) (x + 4096) << 40) | ((long) y << 20) | (z + 4096);
}
@@ -450,7 +377,6 @@ public class MantleCarvedTerrainTest {
private final MantleWriter writer = mock(MantleWriter.class);
private final IrisComplex complex = mock(IrisComplex.class);
private final Engine engine;
private final List<SeaInlet> inlets = new ArrayList<>();
private final Map<Long, HydrologyCaveCell> cells = new HashMap<>();
private Scene() {
@@ -486,7 +412,6 @@ public class MantleCarvedTerrainTest {
when(complex.allowsMantleChunkWrite(anyInt(), anyInt())).thenReturn(true);
HydrologyRuntime runtime = mock(HydrologyRuntime.class);
when(runtime.caveFluidPolicies()).thenReturn(true);
when(runtime.inlets(anyInt(), anyInt())).thenAnswer(invocation -> touching(invocation.getArgument(0), invocation.getArgument(1)));
doAnswer(invocation -> {
cells.put(cell(invocation.getArgument(0), invocation.getArgument(1), invocation.getArgument(2)), invocation.getArgument(3));
return null;
@@ -504,27 +429,12 @@ public class MantleCarvedTerrainTest {
return new MantleCarvedTerrain(writer, complex, engine, 0, 0);
}
private List<SeaInlet> touching(int chunkX, int chunkZ) {
List<SeaInlet> touching = new ArrayList<>();
for (SeaInlet inlet : inlets) {
if (SeaInletRasterizer.touches(inlet, chunkX, chunkZ)) {
touching.add(inlet);
}
}
return touching;
}
private Map<Long, HydrologyCaveCell> generate(int... chunkZs) {
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).setFreeboard(new KList<>(0, 0));
HydrologySettings settings = HydrologySettings.compile(config, SEED, 63, 0, 384);
SeaInletRasterizer rasterizer = new SeaInletRasterizer();
for (int chunkZ : chunkZs) {
for (SeaInlet inlet : complex.getHydrologyRuntime().inlets(0, chunkZ)) {
rasterizer.write(inlet, 0, chunkZ, writer, HydrologyCaveCell.SEA_FLUID, SeaInletRasterizer.SubterrainFluid.NOWHERE,
SeaInletRasterizer.HistoricalChunks.NONE);
}
new CavePoolFiller(settings, 0).fill(0, chunkZ, () -> new MantleCarvedTerrain(writer, complex, engine, 0, chunkZ), writer, SEED);
}
return cells;
@@ -8,8 +8,6 @@ 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.SeaInlet;
import art.arcane.iris.generation.hydrology.underground.SeaInletRasterizer;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.EngineMetrics;
import art.arcane.iris.generation.runtime.IrisComplex;
@@ -148,90 +146,6 @@ public class MantleCarvingComponentWaterMaskTest {
}
}
@Test
public void inletHeadroomJoinsTheProfilePassProtection() throws Exception {
SeaInlet inlet = coveredInlet(32, 40, 40);
installInlet(inlet);
IrisCaveCarver3D carver = installProfile();
List<long[]> boundaries = new ArrayList<>();
doAnswer(call -> {
boundaries.add(((long[]) call.getArgument(8)).clone());
return 0;
}).when(carver).carve(any(), anyInt(), anyInt(), any(), anyDouble(), anyDouble(), any(), any(), any(), any(), any(), any());
component.generateLayer(writer, 2, 2, context);
assertEquals(1, boundaries.size());
int[] column = new int[2];
int covered = 0;
for (int lz = 0; lz < 16; lz++) {
for (int lx = 0; lx < 16; lx++) {
int index = PowerOfTwoCoordinates.packLocal16(lx, lz);
if (!SeaInletRasterizer.column(inlet, 32 + lx, 32 + lz, column)) {
continue;
}
for (int y = inlet.waterLevel() + 1; y <= column[1] + ROOF_CLEARANCE; y++) {
assertTrue("the carver keeps out of the inlet headroom at " + (32 + lx) + "," + y + "," + (32 + lz),
SurfaceFluidBoundaryPlan.protects(boundaries.getFirst(), index, y));
}
assertFalse(SurfaceFluidBoundaryPlan.protects(boundaries.getFirst(), index, inlet.waterLevel()));
covered++;
}
}
assertTrue("covered columns " + covered, covered > 80);
}
@Test
public void subterrainFeaturesStayOutOfInletHeadroom() {
IrisSubterrainFeature feature = new IrisSubterrainFeature().setId("room").setFamily(IrisSubterrainFamily.CENOTE)
.setProbability(1).setLength(64).setRadius(12).setHeight(24).setPillarSpacing(0).setFormationFraction(0)
.setWorldYRange(new IrisRange(-48, 60));
SubterrainPlanner planner = new SubterrainPlanner(new SubterrainPlanner.Options(List.of(feature), 83L, -64, 128, (x, z) -> "region"));
SubterrainPlan plan = planner.plansForBounds(-512, -512, 512, 512).getFirst();
int chunkX = plan.centerX() >> 4;
int chunkZ = plan.centerZ() >> 4;
when(complex.getSubterrainPlanner()).thenReturn(planner);
try (MockedStatic<B> blocks = mockStatic(B.class)) {
blocks.when(() -> B.getState(anyString())).thenReturn(mock(NativeBlockState.class));
List<int[]> open = openedCells(chunkX, chunkZ);
int[] heights = open.stream().mapToInt(cell -> cell[1]).sorted().toArray();
int water = heights[heights.length / 4];
SeaInlet inlet = coveredInlet(chunkX << 4, (chunkZ << 4) + 8, water);
int[] column = new int[2];
int inside = 0;
for (int[] cell : open) {
if (SeaInletRasterizer.column(inlet, cell[0], cell[2], column) && cell[1] > water && cell[1] <= column[1] + ROOF_CLEARANCE) {
inside++;
}
}
assertTrue("subterrain cells in the headroom before the inlet " + inside, inside > 20);
installInlet(inlet);
List<int[]> sealed = openedCells(chunkX, chunkZ);
assertTrue(sealed.size() > 0);
for (int[] cell : sealed) {
boolean headroom = SeaInletRasterizer.column(inlet, cell[0], cell[2], column) && cell[1] > water
&& cell[1] <= column[1] + ROOF_CLEARANCE;
assertFalse("subterrain opened " + cell[0] + "," + cell[1] + "," + cell[2] + " in the inlet headroom", headroom);
}
}
}
private void installInlet(SeaInlet inlet) {
when(hydrology.inlets(anyInt(), anyInt())).thenAnswer(call -> SeaInletRasterizer.touches(inlet, call.getArgument(0), call.getArgument(1))
? List.of(inlet) : List.of());
when(hydrology.settings()).thenReturn(HydrologySettings.compile(new IrisHydrology().setEnabled(true), 1L, 63, 0, 128));
}
private static SeaInlet coveredInlet(int startX, int z, int water) {
float[] xs = {startX - 4f, startX + 4f, startX + 12f, startX + 20f};
float[] zs = {z, z, z, z};
float[] halfWidth = {4f, 4f, 3.5f, 3f};
int[] floor = {water - 3, water - 3, water - 3, water - 3};
int[] ceiling = {water + 5, water + 5, water + 4, water + 4};
return new SeaInlet(5L, xs, zs, halfWidth, water, floor, ceiling, startX + 20, z, 3);
}
private List<int[]> openedCells(int chunkX, int chunkZ) {
List<int[]> opened = new ArrayList<>();
Mantle<Matter> storage = writer.getMantle();
@@ -9,7 +9,6 @@ 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;
import art.arcane.iris.generation.subterrain.SubterrainCell;
@@ -262,75 +261,6 @@ public class MantleHydrologyComponentTest {
verifyNoInteractions(closed.writer, closed.runtime);
}
@Test
public void seaInletsAreWrittenEvenWhereNoSurfaceWaterFlows() {
Fixture dry = new Fixture(ChunkWaterRaster.EMPTY, (x, z) -> 99);
SeaInlet inlet = new SeaInlet(5L, new float[]{-8f, 8f, 24f}, new float[]{8f, 8f, 8f}, new float[]{4f, 4f, 3f}, 63,
new int[]{60, 60, 59}, new int[]{90, 68, 67}, 24, 8, 6);
when(dry.runtime.inlets(0, 0)).thenReturn(List.of(inlet));
List<HydrologyCaveCell> written = new ArrayList<>();
List<Integer> heights = new ArrayList<>();
doAnswer(call -> {
written.add(call.getArgument(3));
heights.add(call.getArgument(1));
return null;
}).when(dry.writer).setData(anyInt(), anyInt(), anyInt(), any(HydrologyCaveCell.class));
dry.generate();
verify(dry.complex, never()).effectiveWaterHeads(anyInt(), anyInt(), any(), any());
int wet = 0;
for (int index = 0; index < written.size(); index++) {
HydrologyCaveCell cell = written.get(index);
assertEquals(HydrologyCaveCell.SEA_FLUID, cell.fluidProfileKey());
if (cell.action() == HydrologyCaveAction.WET_SOURCE) {
wet++;
assertTrue(heights.get(index) <= 63);
}
}
assertTrue("wet inlet cells " + wet, wet > 100);
}
@Test
public void subterrainFluidBesideSeaInletAirIsSealedAboveSeaLevel() {
Fixture dry = new Fixture(ChunkWaterRaster.EMPTY, (x, z) -> 99);
SeaInlet inlet = new SeaInlet(5L, new float[]{-8f, 8f, 24f}, new float[]{8f, 8f, 8f}, new float[]{4f, 4f, 3f}, 63,
new int[]{60, 60, 59}, new int[]{90, 68, 67}, 24, 8, 6);
when(dry.runtime.inlets(0, 0)).thenReturn(List.of(inlet));
SubterrainPlanner planner = mock(SubterrainPlanner.class);
List<SubterrainPlan> plans = List.of(mock(SubterrainPlan.class));
SubterrainCell water = new SubterrainCell(SubterrainCell.Kind.WATER, "", null);
when(planner.isEmpty()).thenReturn(false);
when(planner.plansForBounds(0, 0, 15, 15)).thenReturn(plans);
when(planner.sample(eq(plans), anyInt(), anyInt(), anyInt())).thenAnswer(call ->
(int) call.getArgument(2) == 69 + MINIMUM_Y ? water : SubterrainCell.OUTSIDE);
when(dry.complex.getSubterrainPlanner()).thenReturn(planner);
Engine engine = mock(Engine.class);
IrisWorld world = mock(IrisWorld.class);
when(dry.writer.getEngine()).thenReturn(engine);
when(engine.getWorld()).thenReturn(world);
when(world.minHeight()).thenReturn(MINIMUM_Y);
Map<Long, HydrologyCaveCell> cells = new HashMap<>();
doAnswer(call -> {
cells.put(cell(call.getArgument(0), call.getArgument(1), call.getArgument(2)), call.getArgument(3));
return null;
}).when(dry.writer).setData(anyInt(), anyInt(), anyInt(), any(HydrologyCaveCell.class));
when(dry.writer.getDataIfPresent(anyInt(), anyInt(), anyInt(), eq(HydrologyCaveCell.class))).thenAnswer(call ->
cells.get(cell(call.getArgument(0), call.getArgument(1), call.getArgument(2))));
dry.generate();
assertEquals("inlet air keeps its cell", HydrologyCaveAction.DRY_AIR, cells.get(cell(4, 69, 8)).action());
assertEquals("subterrain water beside the passage", HydrologyCaveAction.SEAL_GUARD, cells.get(cell(8, 69, 13)).action());
assertEquals("subterrain water over the passage roof", HydrologyCaveAction.SEAL_GUARD, cells.get(cell(12, 69, 8)).action());
assertNull("subterrain water three blocks from the passage", cells.get(cell(8, 69, 15)));
assertNull("rock beside the passage above sea level", cells.get(cell(8, 70, 13)));
for (Map.Entry<Long, HydrologyCaveCell> entry : cells.entrySet()) {
int y = (int) ((entry.getKey() >>> 20) & 0xFFFFF);
if (y > 63 && entry.getValue().action() == HydrologyCaveAction.SEAL_GUARD) {
assertEquals(69, y);
}
}
}
@Test
public void provisionalRastersFailTheChunk() {
Fixture own = new Fixture(ChunkWaterRaster.PROVISIONAL, (x, z) -> 99);
@@ -16,32 +16,6 @@ public class SurfaceFluidBoundaryPlanTest {
private static final int PADDING = 3;
private static final int FLUID_HEIGHT = 64;
@Test
public void joinedBandsWidenTheProtectionToCoverBoth() {
long none = SurfaceFluidBoundaryPlan.boundary(SurfaceFluidBoundaryPlan.NO_BOUNDARY, Integer.MIN_VALUE);
long[] boundaries = new long[CHUNK_SIZE * CHUNK_SIZE];
long[] bands = new long[CHUNK_SIZE * CHUNK_SIZE];
Arrays.fill(boundaries, none);
Arrays.fill(bands, none);
boundaries[0] = SurfaceFluidBoundaryPlan.boundary(60, 64);
bands[0] = SurfaceFluidBoundaryPlan.boundary(65, 80);
bands[1] = SurfaceFluidBoundaryPlan.boundary(70, 75);
boundaries[2] = SurfaceFluidBoundaryPlan.boundary(60, 64);
SurfaceFluidBoundaryPlan.join(boundaries, bands);
assertFalse(SurfaceFluidBoundaryPlan.protects(boundaries, 0, 59));
assertTrue(SurfaceFluidBoundaryPlan.protects(boundaries, 0, 60));
assertTrue(SurfaceFluidBoundaryPlan.protects(boundaries, 0, 80));
assertFalse(SurfaceFluidBoundaryPlan.protects(boundaries, 0, 81));
assertFalse(SurfaceFluidBoundaryPlan.protects(boundaries, 1, 69));
assertTrue(SurfaceFluidBoundaryPlan.protects(boundaries, 1, 70));
assertTrue(SurfaceFluidBoundaryPlan.protects(boundaries, 1, 75));
assertFalse(SurfaceFluidBoundaryPlan.protects(boundaries, 1, 76));
assertEquals(SurfaceFluidBoundaryPlan.boundary(60, 64), boundaries[2]);
assertEquals(none, boundaries[3]);
}
@Test
public void submergedColumnProtectsItsSeabedWithoutBlockingTheCaveBelow() {
Fixture fixture = new Fixture();
@@ -7,8 +7,6 @@ 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.SeaInlet;
import art.arcane.iris.generation.hydrology.underground.SeaInletRasterizer;
import art.arcane.iris.generation.mantle.EngineMantle;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisComplex;
@@ -86,56 +84,6 @@ public class IrisCarveModifierSubterrainMaskTest {
}
}
@Test
public void preservedSubterrainStaysOutOfInletHeadroom() {
IrisSubterrainFeature feature = new IrisSubterrainFeature().setId("room").setFamily(IrisSubterrainFamily.CENOTE)
.setProbability(1).setLength(64).setRadius(12).setHeight(24).setPillarSpacing(0).setFormationFraction(0)
.setWorldYRange(new IrisRange(-48, 60));
SubterrainPlanner planner = new SubterrainPlanner(new SubterrainPlanner.Options(List.of(feature), 83L, MINIMUM_Y, 128, (x, z) -> "region"));
SubterrainPlan plan = planner.plansForBounds(-512, -512, 512, 512).getFirst();
int blockX = plan.centerX() >> 4 << 4;
int blockZ = plan.centerZ() >> 4 << 4;
HydrologyRuntime hydrology = mock(HydrologyRuntime.class);
when(hydrology.raster(anyInt(), anyInt())).thenReturn(ChunkWaterRaster.EMPTY);
IrisCarveModifier modifier = modifier(planner, hydrology);
try (MockedStatic<B> blocks = mockStatic(B.class)) {
blocks.when(() -> B.getState(anyString())).thenReturn(mock(NativeBlockState.class));
List<int[]> open = reopenedCells(modifier, planner, blockX, blockZ);
int[] heights = open.stream().mapToInt(cell -> cell[1]).sorted().toArray();
int water = heights[heights.length / 4];
SeaInlet inlet = coveredInlet(blockX, blockZ + 8, water);
assertTrue("subterrain cells in the headroom before the inlet " + inHeadroom(inlet, open).size(), inHeadroom(inlet, open).size() > 20);
when(hydrology.inlets(anyInt(), anyInt())).thenAnswer(call -> SeaInletRasterizer.touches(inlet, call.getArgument(0),
call.getArgument(1)) ? List.of(inlet) : List.of());
when(hydrology.settings()).thenReturn(HydrologySettings.compile(new IrisHydrology().setEnabled(true), 1L, 63, 0, 128));
List<int[]> sealed = reopenedCells(modifier, planner, blockX, blockZ);
assertTrue(sealed.size() > 0);
assertEquals("subterrain reopened cells in the inlet headroom", List.of(), inHeadroom(inlet, sealed));
}
}
private static List<String> inHeadroom(SeaInlet inlet, List<int[]> cells) {
List<String> inside = new ArrayList<>();
int[] column = new int[2];
for (int[] cell : cells) {
if (SeaInletRasterizer.column(inlet, cell[0], cell[2], column) && cell[1] > inlet.waterLevel()
&& cell[1] <= column[1] + ROOF_CLEARANCE) {
inside.add(cell[0] + "," + cell[1] + "," + cell[2]);
}
}
return inside;
}
private static SeaInlet coveredInlet(int startX, int z, int water) {
float[] xs = {startX - 4f, startX + 4f, startX + 12f, startX + 20f};
float[] zs = {z, z, z, z};
float[] halfWidth = {4f, 4f, 3.5f, 3f};
int[] floor = {water - 3, water - 3, water - 3, water - 3};
int[] ceiling = {water + 5, water + 5, water + 4, water + 4};
return new SeaInlet(5L, xs, zs, halfWidth, water, floor, ceiling, startX + 20, z, 3);
}
@SuppressWarnings("unchecked")
private static List<int[]> reopenedCells(IrisCarveModifier modifier, SubterrainPlanner planner, int blockX, int blockZ) {
List<int[]> open = new ArrayList<>();
@@ -155,7 +103,7 @@ public class IrisCarveModifierSubterrainMaskTest {
}
@Test
public void preservedSubterrainLeavesEveryInletCellAlone() {
public void preservedSubterrainLeavesEveryPassageCellAlone() {
IrisSubterrainFeature feature = new IrisSubterrainFeature().setId("room").setFamily(IrisSubterrainFamily.CENOTE)
.setProbability(1).setLength(64).setRadius(12).setHeight(24).setPillarSpacing(0).setFormationFraction(0)
.setWorldYRange(new IrisRange(-48, 60));
@@ -165,8 +113,8 @@ public class IrisCarveModifierSubterrainMaskTest {
int blockZ = plan.centerZ() >> 4 << 4;
HydrologyRuntime hydrology = mock(HydrologyRuntime.class);
when(hydrology.raster(anyInt(), anyInt())).thenReturn(ChunkWaterRaster.EMPTY);
Map<Long, HydrologyCaveCell> inlet = new HashMap<>();
IrisCarveModifier modifier = modifier(planner, hydrology, inlet);
Map<Long, HydrologyCaveCell> passage = new HashMap<>();
IrisCarveModifier modifier = modifier(planner, hydrology, passage);
try (MockedStatic<B> blocks = mockStatic(B.class)) {
blocks.when(() -> B.getState(anyString())).thenReturn(mock(NativeBlockState.class));
Set<Long> room = written(modifier, blockX, blockZ);
@@ -178,14 +126,14 @@ public class IrisCarveModifierSubterrainMaskTest {
if (y <= water + 2 && y >= water - 3) {
HydrologyCaveAction action = y > water ? HydrologyCaveAction.DRY_AIR
: y == water - 3 ? HydrologyCaveAction.SEAL_GUARD : HydrologyCaveAction.WET_SOURCE;
inlet.put(cell, new HydrologyCaveCell(action, HydrologyCaveCell.SEA_FLUID));
passage.put(cell, new HydrologyCaveCell(action, HydrologyCaveCell.SEA_FLUID));
}
}
assertTrue("inlet cells crossing the room " + inlet.size(), inlet.size() > 20);
assertTrue("passage cells crossing the room " + passage.size(), passage.size() > 20);
Set<Long> crossed = written(modifier, blockX, blockZ);
assertTrue("the room still opens away from the inlet", crossed.size() > 0);
for (long cell : inlet.keySet()) {
assertFalse("the room reopened inlet cell at y " + SubterrainMaskKeys.y(cell), crossed.contains(cell));
assertTrue("the room still opens away from the passage", crossed.size() > 0);
for (long cell : passage.keySet()) {
assertFalse("the room reopened passage cell at y " + SubterrainMaskKeys.y(cell), crossed.contains(cell));
}
}
}
@@ -195,7 +143,7 @@ public class IrisCarveModifierSubterrainMaskTest {
}
@SuppressWarnings("unchecked")
private static IrisCarveModifier modifier(SubterrainPlanner planner, HydrologyRuntime hydrology, Map<Long, HydrologyCaveCell> inlet) {
private static IrisCarveModifier modifier(SubterrainPlanner planner, HydrologyRuntime hydrology, Map<Long, HydrologyCaveCell> passage) {
Engine engine = mock(Engine.class);
EngineMantle engineMantle = mock(EngineMantle.class);
Mantle<Matter> mantle = mock(Mantle.class);
@@ -204,7 +152,7 @@ public class IrisCarveModifierSubterrainMaskTest {
when(engineMantle.getMantle()).thenReturn(mantle);
when(mantle.useChunk(anyInt(), anyInt())).thenReturn(chunk);
when(chunk.exists(anyInt())).thenReturn(true);
when(chunk.get(anyInt())).thenAnswer(call -> section(call.getArgument(0), inlet));
when(chunk.get(anyInt())).thenAnswer(call -> section(call.getArgument(0), passage));
IrisComplex complex = mock(IrisComplex.class);
when(engine.getWorld()).thenReturn(IrisWorld.builder().minHeight(MINIMUM_Y).maxHeight(64).build());
when(engine.getComplex()).thenReturn(complex);
@@ -218,12 +166,12 @@ public class IrisCarveModifierSubterrainMaskTest {
}
@SuppressWarnings("unchecked")
private static Matter section(int section, Map<Long, HydrologyCaveCell> inlet) {
private static Matter section(int section, Map<Long, HydrologyCaveCell> passage) {
Matter matter = mock(Matter.class);
MatterSlice<HydrologyCaveCell> slice = mock(MatterSlice.class);
when(matter.hasSlice(HydrologyCaveCell.class)).thenReturn(true);
when(matter.getSlice(HydrologyCaveCell.class)).thenReturn(slice);
when(slice.get(anyInt(), anyInt(), anyInt())).thenAnswer(call -> inlet.get(SubterrainMaskKeys.key(call.getArgument(0),
when(slice.get(anyInt(), anyInt(), anyInt())).thenAnswer(call -> passage.get(SubterrainMaskKeys.key(call.getArgument(0),
section * 16 + (int) call.getArgument(1), call.getArgument(2))));
return matter;
}
@@ -140,6 +140,22 @@ public class IrisTerrainNormalActuatorHydrologyTest {
assertSame("a slot cut through the cliff shows the strata below the old surface", cliff.dirt, cliff.paint().get(0, GROUND, 0));
}
@Test
public void shallowTidalBankCutsKeepTheBiomeSurfaceLayer() {
Painter cut = new Painter(WaterRole.BANK, 0);
when(cut.complex.naturalTrueHeight(11, -4)).thenReturn(GROUND + 3);
NativeBlockState stripped = cut.paint().get(0, GROUND, 0);
Painter tidal = new Painter(WaterRole.BANK, 0);
when(tidal.complex.naturalTrueHeight(11, -4)).thenReturn(GROUND + 3);
when(tidal.complex.isTidalBank(11, -4)).thenReturn(true);
assertSame("the shallow tidal cut is resurfaced", tidal.grass, tidal.paint().get(0, GROUND, 0));
assertSame("a river bank keeps its strata", cut.dirt, stripped);
Painter deep = new Painter(WaterRole.BANK, 0);
when(deep.complex.naturalTrueHeight(11, -4)).thenReturn(GROUND + 20);
when(deep.complex.isTidalBank(11, -4)).thenReturn(true);
assertSame("a deep tidal cut shows the strata", deep.dirt, deep.paint().get(0, GROUND, 0));
}
@Test
public void openInletSlotsKeepLiquidWaterUnderOnlyTheTopSeaLayer() {
Painter slot = new Painter(WaterRole.INLET, HEAD);
@@ -40,8 +40,7 @@ public class PackHydrologyValidatorTest {
"ponds": {"freeboard": [0, 2], "fluid": "lava",
"seeded": {"radius": [4, 12], "depth": [2, 8], "channelSpacing": [48, 160]}},
"underground": {
"seaInlets": {"length": [24, 96], "halfWidth": [2, 5.5], "depth": [3, 6], "headroom": [0, 3],
"chamberRadius": [4, 9]},
"seaInlets": {"length": [24, 96], "mouthHalfWidth": [8, 12.5], "headHalfWidth": [2, 3.5], "depth": [3, 6]},
"cavePools": {"freeboard": [0, 1], "fluid": "water"}
},
"fluids": [
@@ -82,7 +81,7 @@ public class PackHydrologyValidatorTest {
"enabled": true,
"tiers": [{"name": "stream", "halfWidth": [0, 2]}, {"name": "river", "minCatchment": 9, "halfWidth": [2, 65]}],
"ponds": {"freeboard": [-1, 2], "seeded": {"channelSpacing": [0, 160]}},
"underground": {"seaInlets": {"headroom": [0, 3], "chamberRadius": [-2, 9]}, "cavePools": {"freeboard": [-1, 0]}}
"underground": {"seaInlets": {"mouthHalfWidth": [-2, 9]}, "cavePools": {"freeboard": [-1, 0]}}
}
""", "")));
@@ -90,7 +89,7 @@ public class PackHydrologyValidatorTest {
assertContains(validation.errors(), "tiers[1].halfWidth must not go above 64.");
assertContains(validation.errors(), "ponds.freeboard must not go below 0.");
assertContains(validation.errors(), "ponds.seeded.channelSpacing must stay above 0.");
assertContains(validation.errors(), "underground.seaInlets.chamberRadius must stay above 0.");
assertContains(validation.errors(), "underground.seaInlets.mouthHalfWidth must stay above 0.");
assertContains(validation.errors(), "underground.cavePools.freeboard must not go below 0.");
assertEquals(validation.errors().toString(), 6, validation.errors().size());
}
@@ -655,10 +654,10 @@ public class PackHydrologyValidatorTest {
assertTrue(validation.errors().toString(), validation.errors().isEmpty());
assertEquals(List.of(
"Dimension 'main' sets useMantle to false while hydrology is enabled, so the falling water at waterfalls and cascades,"
+ " sea inlets and cave pools are not generated.",
"Dimension 'main' sets useMantle to false while hydrology is enabled, so the falling water at waterfalls and cascades"
+ " and cave pools are not generated.",
"Dimension 'other' disables the RIVER_HYDROLOGY component while hydrology is enabled, so the falling water at waterfalls"
+ " and cascades, sea inlets and cave pools are not generated."), validation.warnings());
+ " and cascades and cave pools are not generated."), validation.warnings());
}
@Test
@@ -84,7 +84,7 @@ public class SchemaBuilderIdentityTest {
@ClassRule
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
private static final String EXPECTED_SCHEMA_DIGEST = "050cf892aa20a9b8796dd8bb0299cb39a92cdabc46569fdf165db6dc960ecf4b";
private static final String EXPECTED_SCHEMA_DIGEST = "07bb61c7034a6aadae8d03c9c0fe8a31326113f7ad515c99512ded2ab9be686c";
private static final List<Class<?>> SCHEMA_ROOTS = List.of(
IrisDimension.class,
@@ -178,15 +178,23 @@ public class NativeStructurePlacementPlannerTest {
StructureWaterRules.admitsStart(plan, stageWater, VILLAGE));
roles.clear();
WaterRole[] dry = {WaterRole.MOUTH, WaterRole.INLET, WaterRole.SHORE, WaterRole.POND_SHORE, WaterRole.BANK, WaterRole.DAM};
WaterRole[] dry = {WaterRole.MOUTH, WaterRole.SHORE, WaterRole.POND_SHORE, WaterRole.BANK, WaterRole.DAM};
int column = 0;
for (int x = 0; x <= 39; x++) {
for (int z = 0; z < 16; z++) {
roles.put(columnKey(x, z), dry[column++ % dry.length]);
}
}
assertTrue("mouths, inlets, shores, banks and dams do not count as river water",
assertTrue("mouths, shores, banks and dams do not count as river water",
StructureWaterRules.admitsStart(plan, stageWater, VILLAGE));
roles.clear();
for (int x = 0; x <= 39; x++) {
for (int z = 0; z < 16; z++) {
roles.put(columnKey(x, z), x % 2 == 0 ? WaterRole.INLET : WaterRole.BANK);
}
}
assertFalse("a sea inlet under the pieces counts as river water", StructureWaterRules.admitsStart(plan, stageWater, VILLAGE));
}
@Test
@@ -7,6 +7,7 @@ import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
import art.arcane.iris.generation.hydrology.water.Pond;
import art.arcane.iris.generation.hydrology.water.Reach;
import art.arcane.iris.generation.hydrology.water.ReachStyle;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.runtime.IrisComplex;
import art.arcane.iris.generation.runtime.IrisEngine;
@@ -14,7 +15,6 @@ import art.arcane.iris.world.history.ChunkGenerationSemantics;
import art.arcane.iris.world.history.GenerationHistory;
import art.arcane.iris.world.history.GenerationHistoryRuntimeRouter;
import art.arcane.iris.generation.stream.ProvisionalSampling;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.testsupport.FakeHydrology;
import art.arcane.iris.testsupport.WaterScene;
import org.junit.Test;
@@ -100,7 +100,7 @@ public class IrisRendererRiverTest {
Pond pond = WaterScene.pond(32L, 62, 16, 16, 10);
when(runtime.enabled()).thenReturn(true);
when(runtime.planPreview(anyInt(), anyInt(), anyInt(), anyInt()))
.thenReturn(new HydrologyPlanPreview(List.of(), List.of(pond), List.of(), List.of(), true));
.thenReturn(new HydrologyPlanPreview(List.of(), List.of(pond), List.of(), true));
when(runtime.rasterPreview(anyInt(), anyInt())).thenReturn(ChunkWaterRaster.PROVISIONAL);
IrisRenderer renderer = new IrisRenderer(engine(runtime));
@@ -166,23 +166,24 @@ public class IrisRendererRiverTest {
}
@Test
public void planModeDrawsSeaInletPathsUnderground() throws Exception {
int stations = 26;
float[] xs = new float[stations];
float[] zs = new float[stations];
float[] halfWidth = new float[stations];
int[] floor = new int[stations];
int[] ceiling = new int[stations];
for (int station = 0; station < stations; station++) {
xs[station] = 100f + station * 8f;
zs[station] = 200f;
halfWidth[station] = 4f;
floor[station] = SEA_LEVEL - 3;
ceiling[station] = SEA_LEVEL + 5;
public void planModeDrawsTidalReachesAsSeaInlets() throws Exception {
int points = 26;
float[] xs = new float[points];
float[] zs = new float[points];
int[] grade = new int[points];
float[] halfWidth = new float[points];
float[] depth = new float[points];
ReachStyle[] style = new ReachStyle[points];
for (int point = 0; point < points; point++) {
xs[point] = 100f + point * 8f;
zs[point] = 200f;
grade[point] = SEA_LEVEL;
halfWidth[point] = 4f;
depth[point] = 3f;
style[point] = ReachStyle.TIDAL;
}
SeaInlet inlet = new SeaInlet(51L, xs, zs, halfWidth, SEA_LEVEL, floor, ceiling, 300, 200, 8);
try (FakeHydrology hydrology = new FakeHydrology(() -> false, (x, z) -> 90, SEA_LEVEL, List.of(), List.of(), List.of(),
List.of(inlet))) {
Reach tidal = new Reach(51L, FakeHydrology.settings(SEA_LEVEL).tidalTier(), 0L, xs, zs, grade, halfWidth, depth, style, 0f);
try (FakeHydrology hydrology = new FakeHydrology(() -> false, (x, z) -> 90, SEA_LEVEL, List.of(tidal), List.of())) {
HydrologyRuntime runtime = spy(hydrology.runtime);
int[] plan = settled(engine(runtime), 16D * PIXELS, PIXELS);
assertEquals(water(HydrologyFeatureType.SEA_INLET), at(plan, PIXELS, 200 / 16, 200 / 16));
@@ -31,7 +31,7 @@ public class WaterMapProgressTest {
HydrologyRuntime runtime = mock(HydrologyRuntime.class);
Reach reach = mock(Reach.class);
when(runtime.planPreview(anyInt(), anyInt(), anyInt(), anyInt()))
.thenReturn(new HydrologyPlanPreview(List.of(reach), List.of(), List.of(), List.of(), true));
.thenReturn(new HydrologyPlanPreview(List.of(reach), List.of(), List.of(), true));
when(runtime.rasterPreview(anyInt(), anyInt())).thenReturn(ChunkWaterRaster.EMPTY);
WaterMap map = new WaterMap(runtime, 32, 0D, 0D, 1D);
@@ -53,7 +53,7 @@ public class WaterMapTest {
private static WaterMap draw(List<Reach> reaches, List<Pond> ponds, List<Pond> lakes) {
HydrologyRuntime runtime = mock(HydrologyRuntime.class);
when(runtime.planPreview(anyInt(), anyInt(), anyInt(), anyInt()))
.thenReturn(new HydrologyPlanPreview(reaches, ponds, lakes, List.of(), true));
.thenReturn(new HydrologyPlanPreview(reaches, ponds, lakes, true));
when(runtime.channelType(any(HydrologyTier.class))).thenReturn(HydrologyFeatureType.STREAM);
WaterMap map = new WaterMap(runtime, PIXELS, 0D, 0D, MID_STEP);
map.advance(() -> false);
@@ -9,7 +9,6 @@ import art.arcane.iris.generation.hydrology.plan.RegionPlan;
import art.arcane.iris.generation.hydrology.plan.WindowKey;
import art.arcane.iris.generation.hydrology.plan.WindowPlan;
import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.water.Pond;
import art.arcane.iris.generation.hydrology.water.PondKind;
import art.arcane.iris.generation.hydrology.water.PondMask;
@@ -46,35 +45,28 @@ public final class FakeHydrology implements AutoCloseable {
private final List<Reach> reaches;
private final List<Pond> ponds;
private final List<Pond> lakes;
private final List<SeaInlet> inlets;
private final ExecutorService pool;
private volatile CountDownLatch gate;
public FakeHydrology(BooleanSupplier mainThread, IntBinaryOperator naturalHeight, int seaLevel, int pondLevel) {
this(mainThread, naturalHeight, seaLevel, pondLevel, List.of(), null, List.of(), List.of());
this(mainThread, naturalHeight, seaLevel, pondLevel, List.of(), null, List.of());
}
public FakeHydrology(BooleanSupplier mainThread, IntBinaryOperator naturalHeight, int seaLevel, List<Reach> reaches, List<Pond> ponds) {
this(mainThread, naturalHeight, seaLevel, 0, reaches, ponds, List.of(), List.of());
this(mainThread, naturalHeight, seaLevel, 0, reaches, ponds, List.of());
}
public FakeHydrology(BooleanSupplier mainThread, IntBinaryOperator naturalHeight, int seaLevel, List<Reach> reaches, List<Pond> ponds,
List<Pond> lakes) {
this(mainThread, naturalHeight, seaLevel, 0, reaches, ponds, lakes, List.of());
}
public FakeHydrology(BooleanSupplier mainThread, IntBinaryOperator naturalHeight, int seaLevel, List<Reach> reaches, List<Pond> ponds,
List<Pond> lakes, List<SeaInlet> inlets) {
this(mainThread, naturalHeight, seaLevel, 0, reaches, ponds, lakes, inlets);
this(mainThread, naturalHeight, seaLevel, 0, reaches, ponds, lakes);
}
private FakeHydrology(BooleanSupplier mainThread, IntBinaryOperator naturalHeight, int seaLevel, int pondLevel, List<Reach> reaches,
List<Pond> ponds, List<Pond> lakes, List<SeaInlet> inlets) {
List<Pond> ponds, List<Pond> lakes) {
this.pondLevel = pondLevel;
this.reaches = List.copyOf(reaches);
this.ponds = ponds == null ? List.of(pond()) : List.copyOf(ponds);
this.lakes = List.copyOf(lakes);
this.inlets = List.copyOf(inlets);
AtomicInteger threads = new AtomicInteger();
this.pool = Executors.newFixedThreadPool(4, runnable -> {
Thread thread = new Thread(runnable, "fake-hydrology-" + threads.incrementAndGet());
@@ -135,12 +127,12 @@ public final class FakeHydrology implements AutoCloseable {
windowCalls.incrementAndGet();
await(gate);
if (!key.equals(new WindowKey(0, 0))) {
return new WindowPlan(key, List.of(), List.of(), List.of());
return new WindowPlan(key, List.of(), List.of());
}
if (failing.get()) {
throw new IllegalStateException(FAILURE);
}
return new WindowPlan(key, reaches, ponds, inlets);
return new WindowPlan(key, reaches, ponds);
}
private Pond pond() {
@@ -156,7 +156,7 @@ public final class WaterScene {
ownedPonds.add(pond);
}
}
return new IndexedWindow(new WindowPlan(key, owned, ownedPonds, List.of()), ReachIndex.build(key, owned, ownedPonds));
return new IndexedWindow(new WindowPlan(key, owned, ownedPonds), ReachIndex.build(key, owned, ownedPonds));
});
}
@@ -24,7 +24,6 @@ import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType;
import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster;
import art.arcane.iris.generation.hydrology.raster.WaterRole;
import art.arcane.iris.generation.hydrology.underground.SeaInlet;
import art.arcane.iris.generation.hydrology.water.Pond;
import art.arcane.iris.generation.hydrology.water.PondKind;
import art.arcane.iris.generation.hydrology.water.Reach;
@@ -514,23 +513,24 @@ public final class GenerationSemanticCaptureTest {
}
@Test
public void recordsSeaInletsInEveryChunkTheyPassUnderWithTheirOwnProfile() {
int stations = 8;
float[] xs = new float[stations];
float[] zs = new float[stations];
float[] halfWidth = new float[stations];
int[] floor = new int[stations];
int[] ceiling = new int[stations];
for (int station = 0; station < stations; station++) {
xs[station] = 4f + station * 8f;
zs[station] = 24f;
halfWidth[station] = 3f;
floor[station] = WATER_SEA_LEVEL - 3;
ceiling[station] = WATER_SEA_LEVEL + 5;
public void recordsTidalReachesInEveryChunkTheyCrossWithTheirOwnProfile() {
int points = 8;
float[] xs = new float[points];
float[] zs = new float[points];
int[] grade = new int[points];
float[] halfWidth = new float[points];
float[] depth = new float[points];
ReachStyle[] style = new ReachStyle[points];
for (int point = 0; point < points; point++) {
xs[point] = 4f + point * 8f;
zs[point] = 24f;
grade[point] = WATER_SEA_LEVEL;
halfWidth[point] = 3f;
depth[point] = 3f;
style[point] = ReachStyle.TIDAL;
}
SeaInlet inlet = new SeaInlet(41L, xs, zs, halfWidth, WATER_SEA_LEVEL, floor, ceiling, 60, 24, 4);
try (FakeHydrology hydrology = new FakeHydrology(() -> false, (x, z) -> 90, WATER_SEA_LEVEL, List.of(), List.of(), List.of(),
List.of(inlet))) {
Reach tidal = new Reach(41L, FakeHydrology.settings(WATER_SEA_LEVEL).tidalTier(), 0L, xs, zs, grade, halfWidth, depth, style, 0f);
try (FakeHydrology hydrology = new FakeHydrology(() -> false, (x, z) -> 90, WATER_SEA_LEVEL, List.of(tidal), List.of())) {
Fixture fixture = new Fixture();
fixture.water(hydrology.runtime);
+9 -13
View File
@@ -401,27 +401,23 @@ tasks.register('cavePoolProbe', JavaExec) {
}
}
tasks.register('seaInletProbe', JavaExec) {
tasks.register('tidalReachProbe', JavaExec) {
group = 'verification'
description = 'Plans and generates real pack chunks with and without sea inlets and reports containment, seal, roof, sea level, ocean connection and order determinism.'
mainClass = 'art.arcane.iris.probe.SeaInletProbe'
description = 'Plans real pack sea inlets and reports their shape, or generates their chunks and checks containment and chunk order, or compares plan digests.'
mainClass = 'art.arcane.iris.probe.TidalReachProbe'
classpath = sourceSets.main.runtimeClasspath
jvmArgs('--add-modules', 'jdk.incubator.vector', '-Djava.awt.headless=true')
minHeapSize = '2g'
maxHeapSize = '8g'
dependsOn(':core:compileJava')
doFirst {
Provider<String> packOff = providers.gradleProperty('probePackOff')
Provider<String> windows = providers.gradleProperty('probeWindows')
Provider<String> mode = providers.gradleProperty('probeMode').orElse('gate')
if (!probePack.isPresent() || !packOff.isPresent() || !probeDimension.isPresent() || !windows.isPresent() || !probeOutput.isPresent()) {
throw new GradleException('seaInletProbe requires probePack, probePackOff, probeDimension, probeWindows=x0..x1,z0..z1 and probeOutput')
Provider<String> mode = providers.gradleProperty('probeMode').orElse('metrics')
if (!probePack.isPresent() || !probeDimension.isPresent() || !windows.isPresent() || !probeOutput.isPresent()) {
throw new GradleException('tidalReachProbe requires probePack, probeDimension, probeWindows=x0..x1,z0..z1 and probeOutput')
}
String[] axes = windows.get().split(',')
String[] xs = axes[0].split('\\.\\.')
String[] zs = axes[1].split('\\.\\.')
args(probePack.get(), packOff.get(), probeDimension.get(), probeSeed.orElse('1337').get(), xs[0], xs[1], zs[0], zs[1], mode.get(),
probeOutput.get(), providers.gradleProperty('probeThreads').orElse('6').get())
args(mode.get(), probePack.get(), probeDimension.get(), probeSeed.orElse('1337').get(), windows.get(), probeOutput.get(),
providers.gradleProperty('probeThreads').orElse('6').get())
}
}
@@ -450,7 +446,7 @@ tasks.register('transitionProbe', JavaExec) {
}
['transitionProbe', 'hydrologyProbe', 'genProbe', 'generationOrderProbe', 'riverTransectProbe', 'terrain3DProbe',
'hydrologyBlockProbe', 'cavePoolProbe', 'caveFluidProbe', 'seaInletProbe'].each { String taskName ->
'hydrologyBlockProbe', 'cavePoolProbe', 'caveFluidProbe', 'tidalReachProbe'].each { String taskName ->
tasks.named(taskName, JavaExec).configure { JavaExec task ->
classpath += configurations.studioProbeApi
doFirst {
@@ -227,6 +227,16 @@ final class HydrologyPlanHarness {
HydrologySettings settings() {
return settings;
}
boolean ocean(int x, int z) {
HydrologySampleBuffer sample = new HydrologySampleBuffer(1);
planners.fineLattice().sampleColumns(new int[]{x}, new int[]{z}, sample);
return sample.ocean()[0];
}
HydrologyPlanners planners() {
return planners;
}
}
static final class CountingTerrain implements HydrologyTerrainSource {
@@ -2,6 +2,8 @@ package art.arcane.iris.probe;
import art.arcane.iris.generation.hydrology.plan.WindowKey;
import art.arcane.iris.generation.hydrology.plan.WindowPlan;
import art.arcane.iris.generation.hydrology.water.Reach;
import art.arcane.iris.generation.hydrology.water.ReachStyle;
import art.arcane.iris.generation.runtime.Engine;
import java.util.ArrayList;
@@ -21,21 +23,25 @@ final class HydrologyUnderground {
static final Counts NONE = new Counts(0, 0L, 0, 0L, List.of());
}
private static int tidal(WindowPlan plan) {
int arms = 0;
for (Reach reach : plan.reaches()) {
arms += reach.style()[0] == ReachStyle.TIDAL ? 1 : 0;
}
return arms;
}
static Source generated(Engine engine, ExecutorService workers) {
return (key, plan) -> {
SeaInletProbe.Checks inlets = SeaInletProbe.check(engine, plan.inlets(), workers);
int minChunkX = key.wx() * HydrologyWindows.CHUNKS;
int minChunkZ = key.wz() * HydrologyWindows.CHUNKS;
CavePoolProbe.Counts pools = CavePoolProbe.check(engine, new CavePoolProbe.Area(minChunkX, minChunkX + HydrologyWindows.CHUNKS - 1,
minChunkZ, minChunkZ + HydrologyWindows.CHUNKS - 1), workers);
List<String> examples = new ArrayList<>();
for (String example : inlets.examples()) {
examples.add("inlet " + example);
}
for (String example : pools.examples()) {
examples.add("pool " + example);
}
return new Counts(inlets.inlets(), inlets.failures(), pools.pools(), pools.failures(), examples);
return new Counts(tidal(plan), 0L, pools.pools(), pools.failures(), examples);
};
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,120 @@
package art.arcane.iris.probe;
import java.util.Arrays;
final class TidalReachMetrics {
private static final double STEP = 4D;
private static final double STRAIGHT_DEGREES = 10D;
private TidalReachMetrics() {
}
static double length(float[] xs, float[] zs) {
double length = 0D;
for (int point = 1; point < xs.length; point++) {
length += Math.hypot(xs[point] - xs[point - 1], zs[point] - zs[point - 1]);
}
return length;
}
static double sinuosity(float[] xs, float[] zs) {
int last = xs.length - 1;
double chord = Math.hypot(xs[last] - xs[0], zs[last] - zs[0]);
return chord <= 0D ? 1D : length(xs, zs) / chord;
}
static double[][] resample(float[] xs, float[] zs) {
double total = length(xs, zs);
int steps = Math.max(1, (int) Math.floor(total / STEP));
double[] rx = new double[steps + 1];
double[] rz = new double[steps + 1];
int segment = 0;
double along = 0D;
for (int index = 0; index <= steps; index++) {
double wanted = index * STEP;
while (segment < xs.length - 2 && along + Math.hypot(xs[segment + 1] - xs[segment], zs[segment + 1] - zs[segment]) < wanted) {
along += Math.hypot(xs[segment + 1] - xs[segment], zs[segment + 1] - zs[segment]);
segment++;
}
double span = Math.hypot(xs[segment + 1] - xs[segment], zs[segment + 1] - zs[segment]);
double t = span <= 0D ? 0D : Math.clamp((wanted - along) / span, 0D, 1D);
rx[index] = xs[segment] + t * (xs[segment + 1] - xs[segment]);
rz[index] = zs[segment] + t * (zs[segment + 1] - zs[segment]);
}
return new double[][]{rx, rz};
}
static double straightRun(float[] xs, float[] zs) {
double[][] line = resample(xs, zs);
int segments = line[0].length - 1;
double[] heading = headings(line);
double longest = 0D;
int start = 0;
for (int segment = 0; segment < segments; segment++) {
while (start < segment && turn(heading[start], heading[segment]) > STRAIGHT_DEGREES) {
start++;
}
longest = Math.max(longest, (segment - start + 1) * STEP);
}
return longest;
}
static double sharpestTurn(float[] xs, float[] zs) {
double[][] line = resample(xs, zs);
double[] heading = headings(line);
double sharpest = 0D;
for (int segment = 1; segment < heading.length; segment++) {
sharpest = Math.max(sharpest, turn(heading[segment - 1], heading[segment]));
}
return sharpest;
}
private static double[] headings(double[][] line) {
double[] heading = new double[line[0].length - 1];
for (int segment = 0; segment < heading.length; segment++) {
heading[segment] = Math.toDegrees(Math.atan2(line[1][segment + 1] - line[1][segment], line[0][segment + 1] - line[0][segment]));
}
return heading;
}
private static double turn(double from, double to) {
double difference = Math.abs(to - from) % 360D;
return difference > 180D ? 360D - difference : difference;
}
static double longestSlotRun(double[] left, double[] right, double rise, double step) {
double longest = 0D;
double run = 0D;
for (int station = 0; station < left.length; station++) {
run = left[station] >= rise && right[station] >= rise ? run + step : 0D;
longest = Math.max(longest, run);
}
return longest;
}
static double steepestRise(int[] heights, int span) {
double steepest = 0D;
for (int from = 0; from + span < heights.length; from++) {
steepest = Math.max(steepest, heights[from + span] - heights[from]);
}
return steepest;
}
static boolean adjacentRaysAtLeast(int[] rises, int rise) {
for (int ray = 0; ray + 1 < rises.length; ray++) {
if (rises[ray] >= rise && rises[ray + 1] >= rise) {
return true;
}
}
return false;
}
static double percentile(double[] values, double share) {
if (values.length == 0) {
return 0D;
}
double[] sorted = values.clone();
Arrays.sort(sorted);
return sorted[Math.min(sorted.length - 1, (int) Math.floor(share * sorted.length))];
}
}
File diff suppressed because it is too large. Load diff
@@ -373,7 +373,7 @@ public class HydrologyMetricsTest {
}
private static WindowPlan plan(WindowKey key, List<Reach> reaches, List<Pond> ponds) {
return new WindowPlan(key, reaches, ponds, List.of());
return new WindowPlan(key, reaches, ponds);
}
private static Reach reach(long id, HydrologyTier tier, long downstream, float catchment, int[] grade, float... coordinates) {
@@ -57,7 +57,7 @@ public class RiverTransectProbeTest {
RiverTransectProbe.Section section = RiverTransectProbe.section(reach, 5,
(x, z) -> new RiverTransectProbe.Column(70, 66, Math.abs(z - 100) <= 2 ? 68 : RiverTransectProbe.NO_WATER, WaterRole.CHANNEL));
List<String> summary = RiverTransectProbe.summary(new WindowKey(0, 0),
new WindowPlan(new WindowKey(0, 0), List.of(reach), List.of(), List.of()), List.of(),
new WindowPlan(new WindowKey(0, 0), List.of(reach), List.of()), List.of(),
List.of(section), settings);
assertEquals("window 0,0 reaches=1 ponds=0 lakes=0 sections=1", summary.get(0));
assertTrue(summary.get(1), summary.get(1).startsWith("reach 7 tier=stream length=40 from=0,100@70 to=40,100@60"));
@@ -1,76 +0,0 @@
package art.arcane.iris.probe;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import org.junit.Test;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class SeaInletChecksTest {
@Test
public void roofBreachesFailWithTheContainmentSealAndRoofChecks() {
SeaInletProbe.Checks breached = new SeaInletProbe.Checks(3, 0L, 0L, 0L, 0L, 1939L, 0L, 0L, 0L, 0L, 0L, List.of());
assertEquals(1939L, breached.failures());
SeaInletProbe.Checks failing = new SeaInletProbe.Checks(3, 1L, 2L, 3L, 4L, 9L, 5L, 6L, 7L, 8L, 0L, List.of());
assertEquals(45L, failing.failures());
}
@Test
public void looseBedsAreReportedButDoNotFail() {
SeaInletProbe.Checks reported = new SeaInletProbe.Checks(3, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 952L, List.of());
assertEquals(0L, reported.failures());
}
@Test
public void theGateFailsOnEveryCheckIncludingOrderSeaLevelAndAddedLeaks() {
SeaInletProbe.Checks clean = new SeaInletProbe.Checks(3, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 952L, List.of());
SeaInletProbe.Gate passing = new SeaInletProbe.Gate(clean, 0, 0, 0);
assertEquals(0L, passing.failures());
assertTrue(passing.line(), passing.line().startsWith("SEA_INLET_GATE status=PASS failures=0 "));
assertEquals(2L, new SeaInletProbe.Gate(clean, 0, 0, 2).failures());
assertEquals(1L, new SeaInletProbe.Gate(clean, 1, 0, 0).failures());
assertEquals(1L, new SeaInletProbe.Gate(clean, 0, 1, 0).failures());
SeaInletProbe.Checks breached = new SeaInletProbe.Checks(3, 0L, 0L, 0L, 0L, 4L, 0L, 0L, 0L, 0L, 0L, List.of());
SeaInletProbe.Gate failing = new SeaInletProbe.Gate(breached, 0, 0, 0);
assertEquals(4L, failing.failures());
assertTrue(failing.line(), failing.line().startsWith("SEA_INLET_GATE status=FAIL failures=4 "));
}
@Test
public void addedLeaksAreTheLeaksMissingWithoutInlets() {
long kept = SeaInletProbe.cellKey(10, 300, -20);
long removed = SeaInletProbe.cellKey(11, 300, -20);
long added = SeaInletProbe.cellKey(10, 301, -20);
assertEquals(0, SeaInletProbe.addedLeaks(Set.of(kept), Set.of(kept)));
assertEquals("inlets that remove natural leaks do not fail", 0, SeaInletProbe.addedLeaks(Set.of(kept), Set.of(kept, removed)));
assertEquals("a leak the inlets move counts although the totals match", 1, SeaInletProbe.addedLeaks(Set.of(kept, added),
Set.of(kept, removed)));
assertEquals(2, SeaInletProbe.addedLeaks(Set.of(added, removed), Set.of()));
assertNotEquals(SeaInletProbe.cellKey(-1, 300, 0), SeaInletProbe.cellKey(0, 300, -1));
assertNotEquals(SeaInletProbe.cellKey(5, 0, 5), SeaInletProbe.cellKey(5, 4095, 5));
}
@Test
public void inletCellsAreClassifiedAgainstTheDimensionSeaFluid() {
assertEquals(SeaInletProbe.classify(state("minecraft:water"), "minecraft:water"), SeaInletProbe.classify(state("minecraft:lava"),
"minecraft:lava"));
assertEquals(SeaInletProbe.classify(state("minecraft:water[level=8]"), "minecraft:water"),
SeaInletProbe.classify(state("minecraft:lava[level=8]"), "minecraft:lava"));
assertEquals(SeaInletProbe.classify(state("minecraft:lava"), "minecraft:water"), SeaInletProbe.classify(state("minecraft:water"),
"minecraft:lava"));
assertNotEquals(SeaInletProbe.classify(state("minecraft:lava"), "minecraft:lava"), SeaInletProbe.classify(state("minecraft:lava"),
"minecraft:water"));
}
private static NativeBlockState state(String key) {
NativeBlockState state = mock(NativeBlockState.class);
when(state.key()).thenReturn(key);
return state;
}
}
@@ -45,7 +45,7 @@ final class SyntheticHydrology implements AutoCloseable {
}
HydrologyProbe.Inputs inputs(UnaryOperator<HydrologyVoxels.ChunkBlocks> edit) {
return inputs(edit, (key, plan) -> new HydrologyUnderground.Counts(plan.inlets().size(), 0L, 0, 0L, List.of()));
return inputs(edit, (key, plan) -> new HydrologyUnderground.Counts(0, 0L, 0, 0L, List.of()));
}
HydrologyProbe.Inputs inputs(UnaryOperator<HydrologyVoxels.ChunkBlocks> edit, HydrologyUnderground.Source underground) {
@@ -0,0 +1,68 @@
package art.arcane.iris.probe;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class TidalReachMetricsTest {
private static float[] line(int points, float step) {
float[] values = new float[points];
for (int point = 0; point < points; point++) {
values[point] = point * step;
}
return values;
}
@Test
public void straightLineRunsItsWholeLengthWithoutTurning() {
float[] xs = line(25, 4f);
float[] zs = new float[25];
assertEquals(1D, TidalReachMetrics.sinuosity(xs, zs), 1e-9D);
assertEquals(96D, TidalReachMetrics.straightRun(xs, zs), 1e-9D);
assertEquals(0D, TidalReachMetrics.sharpestTurn(xs, zs), 1e-9D);
}
@Test
public void rightAngleShowsAsASharpTurn() {
float[] xs = {0f, 40f, 40f};
float[] zs = {0f, 0f, 40f};
assertEquals(80D / Math.hypot(40D, 40D), TidalReachMetrics.sinuosity(xs, zs), 1e-6D);
assertTrue(TidalReachMetrics.sharpestTurn(xs, zs) >= 45D);
assertEquals(40D, TidalReachMetrics.straightRun(xs, zs), 4.01D);
}
@Test
public void wavyLineHasShortStraightRunsAndAboveOneSinuosity() {
int points = 200;
float[] xs = new float[points];
float[] zs = new float[points];
for (int point = 0; point < points; point++) {
xs[point] = point;
zs[point] = (float) (6D * Math.sin(point / 8D));
}
assertTrue(TidalReachMetrics.sinuosity(xs, zs) > 1.1D);
assertTrue(TidalReachMetrics.straightRun(xs, zs) < 24D);
assertEquals(1D, TidalReachMetrics.percentile(new double[]{0D, 1D, 2D}, 0.5D), 0D);
}
@Test
public void slotRunFindsWallsOnBothSidesAtOnce() {
double[] left = {30D, 30D, 30D, 30D, 2D, 30D};
double[] right = {30D, 30D, 30D, 30D, 30D, 2D};
assertEquals(8D, TidalReachMetrics.longestSlotRun(left, right, 16D, 2D), 0D);
assertEquals(0D, TidalReachMetrics.longestSlotRun(new double[]{30D, 2D}, new double[]{2D, 30D}, 16D, 2D), 0D);
}
@Test
public void steepestRiseSeesASheerWallNotAGradedBank() {
assertEquals(30D, TidalReachMetrics.steepestRise(new int[]{0, 0, 30, 30, 30, 30, 30}, 4), 0D);
assertEquals(4D, TidalReachMetrics.steepestRise(new int[]{0, 1, 2, 3, 4, 5, 6}, 4), 0D);
}
@Test
public void headWallNeedsTwoAdjacentRays() {
assertTrue(TidalReachMetrics.adjacentRaysAtLeast(new int[]{0, 16, 20, 0}, 16));
assertTrue(!TidalReachMetrics.adjacentRaysAtLeast(new int[]{16, 0, 20, 0}, 16));
}
}