Tidal reach planner

- Replace SeaInletPlanner with TidalPlanner, planned only in the owner window
- Walk up a distance-from-coast field and keep clear of rivers, ponds and lakes
- Decide conflicts from hashed site anchors and territories, not from drainage
- Trim or reject arms on tall banks, inland low ground and shores beside the sea
- Share the river fit and smoothing through ReachShaper.smooth
This commit is contained in:
Brian Fopiano committed 2026-11-03 14:50:26 -05:00
1 parent 5d127baac9
commit 79a566cf07
9 files changed
+1051 -1270

No files matched your search

@@ -278,6 +278,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,356 @@
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))).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 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] + settings.underground().seaInlets().bankBand());
}
}
}
}
}
@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);
}
}
}
@@ -1167,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;
@@ -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,451 +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 = SeaInletPlanner.ROOF_CLEARANCE;
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 = SeaInletPlanner.ROOF_CLEARANCE;
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 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 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 .*"));
}
}