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

@@ -21,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;
@@ -47,12 +48,14 @@ public final class WindowPlanner {
private final HeightLattice fine;
private final PondPlanner ponds;
private final ReachShaper shaper;
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.tidal = new TidalPlanner(settings, fine);
if (fine.cell() != FINE_CELL) {
throw new IllegalArgumentException("Window fine lattice cell " + fine.cell() + " must be " + FINE_CELL);
}
@@ -127,7 +130,9 @@ public final class WindowPlanner {
}
List<Reach> reaches = network.reaches();
List<Pond> windowPonds = windowPonds(network.ponds());
WindowPlan owned = new WindowPlan(key, ownedReaches(key, reaches), ownedPonds(key, windowPonds));
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);
}
@@ -1,590 +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 static final int MINIMUM_CLIFF_HEIGHT = 8;
private static final float HALF_WIDTH_MIN = 2f;
private static final float HALF_WIDTH_MAX = 5f;
private static final int HEADROOM_MIN = 4;
private static final int HEADROOM_MAX = 10;
static final int ROOF_CLEARANCE = 6;
private static final int CHAMBER_MIN = 6;
private static final int CHAMBER_MAX = 12;
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() + MINIMUM_CLIFF_HEIGHT;
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(CHAMBER_MIN, CHAMBER_MAX, unit(terrain, SALT_RADIUS, end)));
for (int candidate : new int[]{preferred, CHAMBER_MIN}) {
float capacity = capacity(terrain, config, end, chamberRing(candidate, grid.cell()));
if (capacity - water >= 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;
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] = HALF_WIDTH_MAX - (HALF_WIDTH_MAX - HALF_WIDTH_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(HEADROOM_MIN, 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() >= 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 - ROOF_CLEARANCE - 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() + MINIMUM_CLIFF_HEIGHT;
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];
}
}
}
@@ -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());
}
@@ -0,0 +1,666 @@
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.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
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 = 8;
private static final int TRIM_PASSES = 3;
private static final float MOUTH_ZONE = 32f;
private static final float END_SHARE = 0.5f;
private static final float DIAGONAL = 1.41421356f;
private static final float VALLEY_WEIGHT = 0.5f;
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 WOBBLE_LONG = 57f;
private static final float WOBBLE_SHORT = 23f;
private static final float BESIDE_NEAR = 1f;
private static final float BESIDE_FAR = 4f;
private static final float CLEARANCE_MARGIN = 4f;
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 long SALT_RANK = 0x5449444c524bL;
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 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.territory = 2f * config.mouthHalfWidth().max() + config.bankBand();
}
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);
ReachFitter fitter = new ReachFitter(fine, new PondLookup(network.ponds()));
List<Reach> planned = new ArrayList<>();
for (Anchor anchor : own) {
List<Anchor> rivals = rivals(anchor);
if (suppressed(anchor, rivals)) {
continue;
}
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, 0L);
}
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, CellHash.mix(seed, SALT_RANK, siteX, siteZ));
}
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 suppressed(Anchor anchor, List<Anchor> rivals) {
for (Anchor rival : rivals) {
if (rival.rank() < anchor.rank() && Math.hypot(rival.x() - anchor.x(), rival.z() - anchor.z()) < territory) {
return true;
}
}
return false;
}
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(), config.bankBand()) + 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(), config.bankBand()) + 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 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() + config.maximumBankHeight()
&& (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);
List<Integer> path = new ArrayList<>();
path.add(mouth);
path.add(start);
int current = start;
float length = CELL;
float[] height = land.samples().height();
while (length < target) {
int i = current % grid.width();
int j = current / grid.width();
int best = -1;
float bestScore = Float.POSITIVE_INFINITY;
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 score = height[next] - VALLEY_WEIGHT * (coast[next] - coast[current]);
if (score < bestScore || score == bestScore && next < best) {
bestScore = score;
best = next;
}
}
}
if (best < 0) {
break;
}
length += (float) Math.hypot(grid.blockX(best) - grid.blockX(current), grid.blockZ(best) - grid.blockZ(current));
path.add(best);
current = best;
}
if (length < config.length().min() || coast[current] < END_SHARE * length) {
return null;
}
int[] cells = new int[path.size()];
for (int index = 0; index < cells.length; index++) {
cells[index] = path.get(cells.length - 1 - index);
}
return cells;
}
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();
ReachFitter.Fitted fitted = fitter.fit(grid, cells, new float[cells.length], tier, shape, true);
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 head = Math.max(groundedHead(xs, zs, id, shape), Math.max(territoryHead(xs, zs, shape, anchor, rivals), clearHead(xs, zs, shape, network)));
if (head < 0) {
return null;
}
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(), config.bankBand()) + 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(), config.bankBand()) + 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 * 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() + config.maximumBankHeight();
int sea = settings.seaLevel();
float[] offsets = new float[8];
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--;
}
float half = widths[point];
offsets[0] = half + BESIDE_NEAR;
offsets[1] = -offsets[0];
offsets[2] = half + BESIDE_FAR;
offsets[3] = -offsets[2];
offsets[4] = half + 0.5f * band;
offsets[5] = -offsets[4];
offsets[6] = half + band;
offsets[7] = -offsets[6];
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 tx = (xs[after] - xs[before]) / length;
double tz = (zs[after] - zs[before]) / length;
int[] columnX = new int[offsets.length + 1];
int[] columnZ = new int[offsets.length + 1];
for (int index = 0; index < offsets.length; index++) {
columnX[index] = (int) Math.floor(xs[point] - offsets[index] * tz);
columnZ[index] = (int) Math.floor(zs[point] + offsets[index] * tx);
}
columnX[offsets.length] = (int) Math.floor(xs[point]);
columnZ[offsets.length] = (int) Math.floor(zs[point]);
HydrologySampleBuffer samples = new HydrologySampleBuffer(columnX.length);
fine.sampleColumns(columnX, columnZ, samples);
boolean bad = false;
for (int index = 0; index < columnX.length && !bad; index++) {
boolean ocean = samples.ocean()[index];
boolean near = index < 4 || index == offsets.length;
boolean far = index >= 4 && index < offsets.length;
float allowed = far ? limit + 0.5f * band : limit;
bad = !ocean && (samples.height()[index] > allowed || near && total - distance[point] > MOUTH_ZONE && samples.height()[index] < sea);
}
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 0;
}
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 Land(DemGrid grid, HydrologySampleBuffer samples) {
}
private record Anchor(int siteX, int siteZ, WindowKey owner, double targetX, double targetZ, boolean active, int x, int z, long rank) {
}
}
@@ -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 .*"));
}
}