Merge mouths

This commit is contained in:
Brian Fopiano committed 2026-11-04 02:38:37 -05:00
commit 78a521769a
8 files changed
+1173 -5

No files matched your search

@@ -12,6 +12,7 @@ import art.arcane.iris.generation.hydrology.grid.HeightLattice;
import art.arcane.iris.generation.hydrology.grid.HydrologySampleBuffer;
import art.arcane.iris.generation.hydrology.grid.PriorityFlood;
import art.arcane.iris.generation.hydrology.raster.PondChannelSettlement;
import art.arcane.iris.generation.hydrology.raster.NaturalHeights;
import art.arcane.iris.generation.hydrology.raster.TongueGuard;
import art.arcane.iris.generation.hydrology.underground.Grotto;
import art.arcane.iris.generation.hydrology.underground.GrottoPlanner;
@@ -21,6 +22,7 @@ import art.arcane.iris.generation.hydrology.water.PondKind;
import art.arcane.iris.generation.hydrology.water.PondPlanner;
import art.arcane.iris.generation.hydrology.water.Reach;
import art.arcane.iris.generation.hydrology.water.ReachShaper;
import art.arcane.iris.generation.hydrology.water.SeaApproach;
import art.arcane.iris.generation.hydrology.water.ReachStyle;
import art.arcane.iris.generation.hydrology.water.ShapedNetwork;
import art.arcane.iris.generation.hydrology.water.TidalPlanner;
@@ -132,7 +134,7 @@ public final class WindowPlanner {
network = PondChannelSettlement.settle(key, guarded(shaper.shape(key, drainage.surface(), drainage.receivers(),
drainage.accumulation(), drainage.channels(), samples.ocean(), water, fine, settings.seed())), settings.seed(), settings.seaLevel());
}
List<Reach> reaches = network.reaches();
List<Reach> reaches = guarded(new ShapedNetwork(SeaApproach.apply(network.reaches(), network.ponds(), columnHeights(), settings.seaLevel()), network.ponds())).reaches();
List<Pond> windowPonds = windowPonds(network.ponds());
List<Reach> ownedReaches = new ArrayList<>(ownedReaches(key, reaches));
List<Reach> arms = tidal.plan(key, natural, samples, network);
@@ -144,15 +146,19 @@ public final class WindowPlanner {
}
private ShapedNetwork guarded(ShapedNetwork shaped) {
return TongueGuard.guard(shaped, columnHeights(), settings.seed(), settings.seaLevel(), settings.deformation().maxFill());
}
private NaturalHeights columnHeights() {
HydrologySampleBuffer column = new HydrologySampleBuffer(1);
int[] columnX = new int[1];
int[] columnZ = new int[1];
return TongueGuard.guard(shaped, (x, z) -> {
return (x, z) -> {
columnX[0] = x;
columnZ[0] = z;
fine.sampleColumns(columnX, columnZ, column);
return column.height()[0];
}, settings.seed(), settings.seaLevel(), settings.deformation().maxFill());
};
}
public WindowPlan plan(WindowKey key, List<RegionPlan> regions) {
@@ -0,0 +1,219 @@
package art.arcane.iris.generation.hydrology.water;
import art.arcane.iris.generation.hydrology.raster.NaturalHeights;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
public final class SeaApproach {
static final float GENTLE_SLOPE = 0.125f;
static final float STEEPEST_SLOPE = 0.25f;
static final float LENGTH = 128f;
static final float FIRST_STEP = 12f;
static final float COAST_REACH = 64f;
static final int CLIFF_HEIGHT = 16;
static final float CLIFF_BANK_REACH = 16f;
private final Map<Long, List<Reach>> feeders = new HashMap<>();
private final Map<Reach, int[]> lowered = new IdentityHashMap<>();
private final List<Pond> ponds;
private final NaturalHeights natural;
private final int seaLevel;
private int base;
private float slope;
private float firstStep;
private SeaApproach(List<Reach> reaches, List<Pond> ponds, NaturalHeights natural, int seaLevel) {
this.ponds = ponds;
this.natural = natural;
this.seaLevel = seaLevel;
for (Reach reach : reaches) {
if (reach.downstreamId() != 0L) {
feeders.computeIfAbsent(reach.downstreamId(), id -> new ArrayList<>()).add(reach);
}
}
}
public static List<Reach> apply(List<Reach> reaches, List<Pond> ponds, NaturalHeights natural, int seaLevel) {
SeaApproach approach = new SeaApproach(reaches, ponds, natural, seaLevel);
for (Reach reach : reaches) {
int last = reach.style().length - 1;
if (reach.downstreamId() == 0L && reach.style()[last] == ReachStyle.MOUTH) {
approach.lowerToward(reach);
}
}
if (approach.lowered.isEmpty()) {
return reaches;
}
List<Reach> result = new ArrayList<>(reaches.size());
for (Reach reach : reaches) {
int[] grade = approach.lowered.get(reach);
result.add(grade == null ? reach : rebuilt(reach, grade, seaLevel));
}
return result;
}
private void lowerToward(Reach mouth) {
int start = estuaryStart(mouth);
if (highCoast(mouth, start)) {
return;
}
float width = mouth.halfWidth()[start];
base = seaLevel + mouth.tier().stepHeight();
firstStep = Math.max(FIRST_STEP, width);
slope = slope(mouth, start, Math.min(GENTLE_SLOPE, 1f / Math.max(1f, width)));
walk(mouth, start, 0f, mouth.grade()[start]);
}
private static int estuaryStart(Reach mouth) {
int start = mouth.style().length - 1;
while (start > 0 && mouth.style()[start - 1] == ReachStyle.MOUTH) {
start--;
}
return start;
}
private boolean highCoast(Reach mouth, int start) {
Reach reach = mouth;
int point = start - 1;
if (start == 0) {
reach = largestFeeder(mouth);
if (reach == null) {
return false;
}
point = reach.xs().length - 2;
}
if (point < 0) {
return false;
}
int next = Math.min(reach.xs().length - 1, point + 1);
float dx = reach.xs()[next] - reach.xs()[point];
float dz = reach.zs()[next] - reach.zs()[point];
float span = Math.max(1e-3f, (float) Math.hypot(dx, dz));
return bankPeak(reach, point, -dz / span, dx / span) - seaLevel >= CLIFF_HEIGHT
&& bankPeak(reach, point, dz / span, -dx / span) - seaLevel >= CLIFF_HEIGHT;
}
private double bankPeak(Reach reach, int point, float nx, float nz) {
double peak = Double.NEGATIVE_INFINITY;
float half = reach.halfWidth()[point];
for (float out = half + 2f; out <= half + CLIFF_BANK_REACH; out += 2f) {
peak = Math.max(peak, natural.height((int) Math.floor(reach.xs()[point] + nx * out), (int) Math.floor(reach.zs()[point] + nz * out)));
}
return peak;
}
private float slope(Reach mouth, int start, float gentle) {
float rise = Float.POSITIVE_INFINITY;
Reach reach = mouth;
int point = start;
float along = 0f;
int below = mouth.grade()[start];
while (along <= LENGTH) {
if (point == 0) {
reach = largestFeeder(reach);
if (reach == null) {
break;
}
point = reach.xs().length - 1;
continue;
}
along += distance(reach, point - 1, point);
point--;
int level = reach.grade()[point];
if (stops(reach, point, along, level, below)) {
break;
}
if (along > COAST_REACH) {
rise = Math.min(rise, (level - base) / Math.max(1f, along - firstStep));
}
below = level;
}
return rise == Float.POSITIVE_INFINITY ? gentle : Math.clamp(rise, gentle, STEEPEST_SLOPE);
}
private void walk(Reach reach, int from, float start, int firstBelow) {
float along = start;
int below = firstBelow;
for (int point = from - 1; point >= 0; point--) {
along += distance(reach, point, point + 1);
int level = reach.grade()[point];
if (along > LENGTH || stops(reach, point, along, level, below)) {
return;
}
int allowed = base + (int) Math.floor(slope * Math.max(0f, along - firstStep));
if (level > allowed) {
lowered.computeIfAbsent(reach, known -> known.grade().clone())[point] = allowed;
} else if (along > COAST_REACH) {
return;
}
below = level;
}
for (Reach feeder : feeders.getOrDefault(reach.id(), List.of())) {
int end = feeder.grade().length - 1;
int[] grade = lowered.get(reach);
int ceiling = grade == null ? reach.grade()[0] : grade[0];
if (feeder.grade()[end] > ceiling) {
lowered.computeIfAbsent(feeder, known -> known.grade().clone())[end] = ceiling;
}
walk(feeder, end, along, feeder.grade()[end]);
}
}
private boolean stops(Reach reach, int point, float along, int level, int below) {
if (reach.style()[point] == ReachStyle.POND_OUTLET || besidePond(reach, point)) {
return true;
}
if (level - below < reach.tier().waterfallMinimumDrop()) {
return false;
}
return along > COAST_REACH || level - seaLevel >= CLIFF_HEIGHT;
}
private boolean besidePond(Reach reach, int point) {
for (Pond pond : ponds) {
if (ReachShaper.nearLip(pond.mask(), reach.xs()[point], reach.zs()[point], reach.halfWidth()[point])) {
return true;
}
}
return false;
}
private Reach largestFeeder(Reach reach) {
Reach largest = null;
for (Reach feeder : feeders.getOrDefault(reach.id(), List.of())) {
if (largest == null || feeder.catchment() > largest.catchment()) {
largest = feeder;
}
}
return largest;
}
private static float distance(Reach reach, int from, int to) {
return (float) Math.hypot(reach.xs()[to] - reach.xs()[from], reach.zs()[to] - reach.zs()[from]);
}
private static Reach rebuilt(Reach reach, int[] grade, int seaLevel) {
int count = grade.length;
boolean[] ocean = new boolean[count];
boolean[] outlet = new boolean[count];
for (int point = 0; point < count; point++) {
ocean[point] = reach.style()[point] == ReachStyle.MOUTH;
outlet[point] = reach.style()[point] == ReachStyle.POND_OUTLET;
}
ReachStyle[] styled = ReachShaper.styles(grade, ocean, outlet, reach.tier().waterfallMinimumDrop(), seaLevel, reach.tier().stepHeight());
ReachStyle[] style = reach.style().clone();
for (int point = 0; point < count; point++) {
boolean touched = grade[point] != reach.grade()[point] || point > 0 && grade[point - 1] != reach.grade()[point - 1]
|| point + 1 < count && grade[point + 1] != reach.grade()[point + 1];
if (touched) {
style[point] = styled[point];
}
}
return new Reach(reach.id(), reach.tier(), reach.downstreamId(), reach.xs(), reach.zs(), grade, reach.halfWidth(), reach.depth(), style, reach.catchment())
.withStraightFalls(reach.straightFalls());
}
}
@@ -1620,6 +1620,145 @@ public class ReachShaperTest {
assertEquals("a short estuary still meets the seabed", HydrologyTier.MINIMUM_DEPTH, estuary.depth()[last], 0f);
}
@Test
public void riverOnAPlateauComesDownToTheSeaOverAStretch() {
HydrologySettings settings = settings(config -> {
});
Reach reach = coastalRun(settings, 0, (mouth, x) -> SEA_LEVEL + 1D + Math.min(11D, 0.5D * Math.max(0D, mouth - x)));
assertGentleRunToTheSea(reach, settings);
int start = trailingMouth(reach);
assertEquals("the last water above the sea stands one step up", SEA_LEVEL + reach.tier().stepHeight(), reach.grade()[start - 1]);
float run = reach.xs()[start] - reach.xs()[firstPointAbove(reach, start, SEA_LEVEL + 6)];
assertTrue("the river takes " + run + " blocks over its last six", run >= 24f);
}
@Test
public void riverCommittedToRisingBanksStillArrivesInSmallSteps() {
HydrologySettings settings = settings(config -> {
});
assertGentleRunToTheSea(coastalRun(settings, 0, (mouth, x) -> SEA_LEVEL + 1D + 0.2D * Math.max(0D, mouth - x)), settings);
}
@Test
public void shortMouthReachLowersItsFeederToo() {
HydrologySettings settings = settings(config -> {
});
List<Reach> reaches = coastalRuns(settings, 48, (mouth, x) -> SEA_LEVEL + 1D + Math.min(11D, 0.1D * Math.max(0D, mouth - x)));
assertEquals(2, reaches.size());
Reach feeder = reaches.get(0).style()[reaches.get(0).style().length - 1] == ReachStyle.MOUTH ? reaches.get(1) : reaches.get(0);
int last = feeder.grade().length - 1;
int above = last - 1;
assertTrue("the feeder end " + feeder.grade()[above] + " stands a step above the sea", feeder.grade()[above] - SEA_LEVEL <= feeder.tier().stepHeight());
for (int point = 1; point <= last; point++) {
if (feeder.xs()[last] - feeder.xs()[point] > 24f) {
continue;
}
assertTrue("feeder step at " + point + ": " + feeder.grade()[point - 1] + " to " + feeder.grade()[point],
feeder.grade()[point - 1] - feeder.grade()[point] <= feeder.tier().stepHeight());
}
}
@Test
public void highCliffCoastKeepsItsWaterfallIntoTheSea() {
HydrologySettings settings = settings(config -> {
});
Reach reach = coastalRun(settings, 0, (mouth, x) -> x >= mouth - 2D ? SEA_LEVEL - 4D : SEA_LEVEL + 30D);
int start = trailingMouth(reach);
assertTrue("a high cliff stays a fall: " + reach.grade()[start - 1], reach.grade()[start - 1] >= SEA_LEVEL + 16);
assertEquals(ReachStyle.WATERFALL, reach.style()[start - 1]);
}
@Test
public void inlandFallAwayFromTheSeaKeepsItsHeight() {
HydrologySettings settings = settings(config -> {
});
Reach reach = coastalRun(settings, 0, (mouth, x) -> mouth - x > 150D ? SEA_LEVEL + 30D : SEA_LEVEL + 5D);
int drop = 0;
float at = 0f;
for (int point = 1; point < reach.grade().length; point++) {
if (reach.grade()[point - 1] - reach.grade()[point] > drop) {
drop = reach.grade()[point - 1] - reach.grade()[point];
at = reach.xs()[reach.xs().length - 1] - reach.xs()[point];
}
}
assertTrue("the fall stays " + drop + " tall at " + at + " from the mouth", drop >= 20 && at > 128f);
}
@Test
public void seaApproachLeavesOtherReachesAlone() {
HydrologySettings settings = settings(config -> {
});
Reach inland = coastalRun(settings, false);
assertTrue("a reach that does not meet the sea is the same object", inland == SeaApproach.apply(List.of(inland), List.of(), (x, z) -> SEA_LEVEL + 40D, SEA_LEVEL).get(0));
}
@Test
public void seaApproachStopsBesideAPond() {
HydrologySettings settings = settings(config -> {
});
DoubleBinaryOperator plateau = (mouth, x) -> SEA_LEVEL + 1D + Math.min(11D, 0.5D * Math.max(0D, mouth - x));
Reach open = coastalRun(settings, 0, plateau);
Reach plain = plainPlateau(settings, plateau);
int start = trailingMouth(open);
assertTrue("the open plateau lowers", open.grade()[start - 1] < plain.grade()[start - 1]);
float x = plain.xs()[start - 8];
float z = plain.zs()[start - 8];
int offset = Math.round(plain.halfWidth()[start - 8]) + 4;
Pond pond = new Pond(61L, PondKind.NATURAL, plain.grade()[start - 8], plain.grade()[start - 8] - 3, Math.round(x), Math.round(z), plain.grade()[start - 8] + 1f,
disk(Math.round(x), Math.round(z) + offset, 4), 0L, 0, "water", Math.round(x), Math.round(z) + offset);
Reach beside = SeaApproach.apply(List.of(plain), List.of(pond), (px, pz) -> SEA_LEVEL + 1D, SEA_LEVEL).get(0);
assertEquals("water above the pond's reach is left as planned", plain.grade()[0], beside.grade()[0]);
for (int point = 1; point < plain.grade().length; point++) {
assertTrue("no rise at " + point, beside.grade()[point - 1] >= beside.grade()[point]);
}
assertEquals("the water beside the pond keeps its level", plain.grade()[start - 8], beside.grade()[start - 8]);
}
private static Reach plainPlateau(HydrologySettings settings, DoubleBinaryOperator profile) {
int width = 30;
DemGrid surface = new DemGrid(0, 0, CELL, width, 3);
Arrays.fill(surface.values(), 90f);
int[] receivers = new int[width * 3];
Arrays.fill(receivers, -1);
float[] accumulation = new float[width * 3];
BitSet channels = new BitSet(width * 3);
for (int i = 0; i < width; i++) {
int cell = surface.index(i, 1);
receivers[cell] = i + 1 < width ? surface.index(i + 1, 1) : -1;
accumulation[cell] = (i + 1) * 1000f;
if (i + 1 < width) {
channels.set(cell);
}
}
surface.set(width - 1, 1, 30f);
double mouthX = (width - 1) * CELL;
HeightLattice fine = new HeightLattice(new Terrain((x, z) -> profile.applyAsDouble(mouthX, x)), FINE, false, 1 << 16);
return new ReachShaper(settings).shape(WINDOW, surface, receivers, accumulation, channels,
SeaCells.atOrBelow(surface, SEA_LEVEL), List.of(), fine, SEED).reaches().get(0);
}
private static void assertGentleRunToTheSea(Reach reach, HydrologySettings settings) {
int start = trailingMouth(reach);
assertTrue("the reach ends in an estuary", start > 0);
assertTrue("no step of " + (reach.grade()[start - 1] - SEA_LEVEL) + " at the estuary " + Arrays.toString(reach.grade()),
reach.grade()[start - 1] - SEA_LEVEL <= reach.tier().stepHeight());
float mouthX = reach.xs()[reach.xs().length - 1];
for (int point = 1; point <= start; point++) {
if (mouthX - reach.xs()[point] <= 96f) {
assertTrue("step at " + point + ": " + reach.grade()[point - 1] + " to " + reach.grade()[point] + " in " + Arrays.toString(reach.grade()),
reach.grade()[point - 1] - reach.grade()[point] <= reach.tier().stepHeight());
}
}
}
private static int firstPointAbove(Reach reach, int from, int level) {
int point = from;
while (point > 0 && reach.grade()[point] < level) {
point--;
}
return point;
}
@Test
public void estuaryStopsAtAHeldPondLip() {
Reach outlet = coastalOutlet(PondKind.NATURAL);
@@ -2691,6 +2830,36 @@ public class ReachShaperTest {
assertTrue("estuary points over the low land " + inland, inland > 0);
}
private static Reach coastalRun(HydrologySettings settings, int originX, DoubleBinaryOperator profile) {
List<Reach> reaches = coastalRuns(settings, originX, profile);
assertEquals(1, reaches.size());
return reaches.get(0);
}
private static List<Reach> coastalRuns(HydrologySettings settings, int originX, DoubleBinaryOperator profile) {
int width = 30;
DemGrid surface = new DemGrid(originX, 0, CELL, width, 3);
Arrays.fill(surface.values(), 90f);
int[] receivers = new int[width * 3];
Arrays.fill(receivers, -1);
float[] accumulation = new float[width * 3];
BitSet channels = new BitSet(width * 3);
for (int i = 0; i < width; i++) {
int cell = surface.index(i, 1);
receivers[cell] = i + 1 < width ? surface.index(i + 1, 1) : -1;
accumulation[cell] = (i + 1) * 1000f;
if (i + 1 < width) {
channels.set(cell);
}
}
surface.set(width - 1, 1, 30f);
double mouthX = originX + (width - 1) * CELL;
HeightLattice fine = new HeightLattice(new Terrain((x, z) -> profile.applyAsDouble(mouthX, x)), FINE, false, 1 << 16);
List<Reach> shaped = new ReachShaper(settings).shape(WINDOW, surface, receivers, accumulation, channels,
SeaCells.atOrBelow(surface, SEA_LEVEL), List.of(), fine, SEED).reaches();
return SeaApproach.apply(shaped, List.of(), (x, z) -> profile.applyAsDouble(mouthX, x), SEA_LEVEL);
}
private static Reach coastalRun(HydrologySettings settings, boolean ocean) {
return coastalRun(settings, ocean, 0.08D);
}
+20
View File
@@ -442,6 +442,26 @@ tasks.register('grottoProbe', JavaExec) {
}
}
tasks.register('mouthProbe', JavaExec) {
group = 'verification'
description = 'Measures how real pack rivers meet the sea, dumps a mouth, renders real block sections, or lists reach digests.'
mainClass = 'art.arcane.iris.probe.MouthProbe'
classpath = sourceSets.main.runtimeClasspath
jvmArgs('--add-modules', 'jdk.incubator.vector', '-Djava.awt.headless=true')
minHeapSize = '2g'
maxHeapSize = '8g'
dependsOn(':core:compileJava')
doFirst {
Provider<String> windows = providers.gradleProperty('probeWindows')
Provider<String> mode = providers.gradleProperty('probeMode').orElse('metrics')
if (!probePack.isPresent() || !probeDimension.isPresent() || !windows.isPresent() || !probeOutput.isPresent()) {
throw new GradleException('mouthProbe requires probePack, probeDimension, probeWindows=x0..x1,z0..z1 and probeOutput')
}
List<String> extra = (providers.gradleProperty('probeExtra').orElse('').get() as String).tokenize(',')
args([mode.get(), probePack.get(), probeDimension.get(), probeSeed.orElse('1337').get(), windows.get(), probeOutput.get()] + extra)
}
}
tasks.register('transitionProbe', JavaExec) {
group = 'verification'
description = 'Exercises a bounded two-pack Studio cutover, transition routing, receipts and semantics with a vanilla-biome pack.'
@@ -0,0 +1,61 @@
package art.arcane.iris.probe;
import art.arcane.iris.generation.hydrology.raster.WaterHeads;
import art.arcane.iris.generation.hydrology.water.Reach;
import art.arcane.iris.generation.hydrology.water.ReachStyle;
final class MouthMetrics {
static final int APPROACH = 96;
private MouthMetrics() {
}
static boolean seaMouth(Reach reach) {
int last = reach.style().length - 1;
return reach.downstreamId() == 0L && reach.style()[last] == ReachStyle.MOUTH;
}
static double[] along(Reach reach) {
double[] along = new double[reach.xs().length];
for (int point = 1; point < along.length; point++) {
along[point] = along[point - 1] + Math.hypot(reach.xs()[point] - reach.xs()[point - 1], reach.zs()[point] - reach.zs()[point - 1]);
}
return along;
}
static int snapped(Reach reach, int point, int sea) {
return WaterHeads.snap(reach.grade()[point], sea, reach.tier().stepHeight());
}
static int lastAboveSea(Reach reach, int sea) {
for (int point = reach.grade().length - 1; point >= 0; point--) {
if (snapped(reach, point, sea) > sea) {
return point;
}
}
return -1;
}
static int finalDrop(Reach reach, int sea) {
int high = lastAboveSea(reach, sea);
return high < 0 ? 0 : snapped(reach, high, sea) - sea;
}
static double seaRun(Reach reach, int sea) {
double[] along = along(reach);
int high = lastAboveSea(reach, sea);
return along[along.length - 1] - (high < 0 ? 0D : along[high]);
}
static int largestStep(Reach reach, int sea, double within) {
double[] along = along(reach);
double end = along[along.length - 1];
int largest = 0;
for (int point = 1; point < along.length; point++) {
if (end - along[point] <= within) {
largest = Math.max(largest, snapped(reach, point - 1, sea) - snapped(reach, point, sea));
}
}
return largest;
}
}
@@ -0,0 +1,635 @@
package art.arcane.iris.probe;
import art.arcane.iris.generation.concurrent.MultiBurst;
import art.arcane.iris.generation.hydrology.engine.HydrologyBinding;
import art.arcane.iris.generation.hydrology.engine.IrisHydrologyTerrainSource;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.hydrology.plan.WindowKey;
import art.arcane.iris.generation.hydrology.plan.WindowPlan;
import art.arcane.iris.generation.hydrology.raster.WaterRole;
import art.arcane.iris.generation.hydrology.underground.Grotto;
import art.arcane.iris.generation.hydrology.water.Pond;
import art.arcane.iris.generation.hydrology.water.Reach;
import art.arcane.iris.generation.hydrology.water.ReachStyle;
import art.arcane.iris.generation.runtime.Engine;
import art.arcane.iris.generation.terrain.IrisDimension;
import art.arcane.volmlib.nativelib.terrain.NativeBiome;
import art.arcane.volmlib.nativelib.terrain.NativeBlockState;
import art.arcane.volmlib.util.hunk.Hunk;
import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.zip.GZIPOutputStream;
public final class MouthProbe {
private static final String LOG = "[mouth-probe]";
private static final int[][] SIDES = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
private static final int LEVELS = 64;
private static final int BELOW = 16;
private static final int SCALE = 5;
private static final int AIR = 0xc8dcff;
private MouthProbe() {
}
public static void main(String[] arguments) {
int code = 2;
try {
String mode = arguments[0];
HydrologyWindows.Target target = HydrologyWindows.Target.parse(arguments[1], arguments[2], arguments[3], arguments[4], "false");
File out = new File(arguments[5]);
out.mkdirs();
long failures = switch (mode) {
case "metrics" -> metrics(target, out);
case "dump" -> dump(target, out, Integer.parseInt(arguments[6]), Integer.parseInt(arguments[7]));
case "sections" -> sections(target, out, arguments);
case "digest" -> digest(target, out);
case "chunks" -> chunks(target, out);
default -> throw new IllegalArgumentException("Unknown mode " + mode);
};
System.out.println(LOG + " failures=" + failures);
code = failures == 0L ? 0 : 1;
} catch (Throwable failure) {
failure.printStackTrace(System.out);
}
System.exit(code);
}
private static HydrologySettings settings(Engine engine) {
IrisDimension dimension = engine.getDimension();
return HydrologySettings.compile(dimension.getHydrology(), engine.getSeedManager().getBodies(), dimension.getFluidHeight(), 0, engine.getHeight());
}
private static HydrologyPlanHarness.Plans plans(Engine engine, HydrologySettings settings, HydrologyWindows.WindowRange range) {
return new HydrologyPlanHarness.Plans(settings, terrain(engine, settings), terrain(engine, settings)::naturalSurface, range);
}
private static IrisHydrologyTerrainSource terrain(Engine engine, HydrologySettings settings) {
return new IrisHydrologyTerrainSource(engine.getComplex(), engine.getDimension(), settings, MultiBurst.hydrology,
MultiBurst.hydrology.parallelism(), HydrologyBinding.UNBOUND);
}
private static List<Reach> mouths(HydrologyPlanHarness.Plans plans, HydrologyWindows.WindowRange windows) {
List<Reach> mouths = new ArrayList<>();
for (Map.Entry<WindowKey, WindowPlan> entry : plans.windowPlans().entrySet()) {
if (windows.contains(entry.getKey())) {
for (Reach reach : entry.getValue().reaches()) {
if (MouthMetrics.seaMouth(reach) && !TidalReachProbe.tidal(reach)) {
mouths.add(reach);
}
}
}
}
return mouths;
}
private static TidalReachProbe.Columns columns(Engine engine, HydrologySettings settings, HydrologyPlanHarness.Plans plans) {
HydrologyPlanHarness.RasterCache rasters = new HydrologyPlanHarness.RasterCache(1 << 14, plans::rasterize);
return new TidalReachProbe.Columns(rasters, terrain(engine, settings), plans, settings.seaLevel());
}
private static boolean openSea(TidalReachProbe.Columns columns, int x, int z, int sea) {
int head = columns.head(x, z);
return head == sea || head == Integer.MIN_VALUE && columns.ocean(x, z) && columns.height(x, z) < sea;
}
private static int[] rasterEdge(Reach reach, TidalReachProbe.Columns columns, int sea) {
double[] along = MouthMetrics.along(reach);
double end = along[along.length - 1];
int worst = 0;
int worstWidth = 0;
int worstX = 0;
int worstZ = 0;
Set<Long> seen = new TreeSet<>();
for (int point = 0; point < along.length; point++) {
if (end - along[point] > MouthMetrics.APPROACH) {
continue;
}
int reachOut = (int) Math.ceil(reach.halfWidth()[point]) + 2;
int cx = Math.round(reach.xs()[point]);
int cz = Math.round(reach.zs()[point]);
for (int z = cz - reachOut; z <= cz + reachOut; z++) {
for (int x = cx - reachOut; x <= cx + reachOut; x++) {
if (!seen.add(((long) x << 32) ^ (z & 0xffffffffL))) {
continue;
}
int head = columns.head(x, z);
if (head <= sea) {
continue;
}
for (int[] side : SIDES) {
if (openSea(columns, x + side[0], z + side[1], sea)) {
int drop = head - sea;
if (drop > worst) {
worst = drop;
worstX = x;
worstZ = z;
}
if (drop > 2) {
worstWidth++;
}
break;
}
}
}
}
}
return new int[]{worst, worstWidth, worstX, worstZ};
}
private static int[] coast(Reach reach, TidalReachProbe.Columns columns, int sea) {
int high = Math.max(0, MouthMetrics.lastAboveSea(reach, sea));
int next = Math.min(reach.xs().length - 1, high + 1);
int before = Math.max(0, high - 1);
double dx = reach.xs()[next] - reach.xs()[before];
double dz = reach.zs()[next] - reach.zs()[before];
double span = Math.max(1e-3D, Math.hypot(dx, dz));
double nx = -dz / span;
double nz = dx / span;
double half = reach.halfWidth()[high];
int[] peak = new int[2];
for (int side = 0; side < 2; side++) {
double sign = side == 0 ? 1D : -1D;
int top = Integer.MIN_VALUE;
for (double out = half + 2D; out <= half + 32D; out += 1D) {
top = Math.max(top, columns.natural((int) Math.floor(reach.xs()[high] + sign * nx * out), (int) Math.floor(reach.zs()[high] + sign * nz * out)));
}
peak[side] = top - sea;
}
int ground = columns.natural(Math.round(reach.xs()[high]), Math.round(reach.zs()[high])) - sea;
return new int[]{Math.min(peak[0], peak[1]), Math.max(peak[0], peak[1]), ground};
}
private static long metrics(HydrologyWindows.Target target, File out) throws Exception {
try (RealPackProbeSupport.Workspace workspace = RealPackProbeSupport.openWorkspace(target.pack(), target.dimension(), LOG);
RealPackProbeSupport.EngineSession session = workspace.openEngine(target.seed(), false, "metrics");
PrintWriter writer = new PrintWriter(new File(out, "mouths-" + target.seed() + ".tsv"))) {
Engine engine = session.engine();
HydrologySettings settings = settings(engine);
int sea = settings.seaLevel();
HydrologyPlanHarness.Plans plans = plans(engine, settings, target.windows().grown(1));
TidalReachProbe.Columns columns = columns(engine, settings, plans);
writer.println("seed\tid\ttier\tmouthX\tmouthZ\tlength\tfinalDrop\tseaRun\tlargestStep64\tlargestStep32\trasterDrop\trasterDamColumns\tlowBank\thighBank\tground\tfall\thighGrade32\tpond\tworstX\tworstZ\tworstLinked");
int count = 0;
Map<Long, Long> downstream = new HashMap<>();
for (WindowPlan plan : plans.windowPlans().values()) {
for (Reach reach : plan.reaches()) {
downstream.put(reach.id(), reach.downstreamId());
}
}
for (Reach reach : mouths(plans, target.windows())) {
int last = reach.xs().length - 1;
int[] edge = rasterEdge(reach, columns, sea);
int[] coast = coast(reach, columns, sea);
boolean fall = false;
for (ReachStyle style : reach.style()) {
fall |= style == ReachStyle.WATERFALL;
}
double[] along = MouthMetrics.along(reach);
writer.printf(Locale.ROOT, "%d\t%d\t%s\t%.0f\t%.0f\t%.0f\t%d\t%.1f\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%b\t%d\t%b\t%d\t%d\t%b%n", target.seed(), reach.id(), reach.tier().name(),
reach.xs()[last], reach.zs()[last], along[last], MouthMetrics.finalDrop(reach, sea), MouthMetrics.seaRun(reach, sea),
MouthMetrics.largestStep(reach, sea, 64D), MouthMetrics.largestStep(reach, sea, 32D), edge[0], edge[1], coast[0], coast[1], coast[2], fall, highGrade(reach, sea), nearOutlet(reach), edge[2], edge[3], linked(columns.feature(edge[2], edge[3]), reach.id(), downstream));
count++;
}
System.out.println(LOG + " seed " + target.seed() + " mouths " + count + " planFailures " + plans.failures().size());
return plans.failures().size();
}
}
private static boolean linked(long feature, long mouth, Map<Long, Long> downstream) {
long at = feature;
for (int hop = 0; hop < 64 && at != 0L; hop++) {
if (at == mouth) {
return true;
}
at = downstream.getOrDefault(at, 0L);
}
return false;
}
private static int highGrade(Reach reach, int sea) {
double[] along = MouthMetrics.along(reach);
int firstMouth = reach.style().length - 1;
while (firstMouth > 0 && reach.style()[firstMouth - 1] == ReachStyle.MOUTH) {
firstMouth--;
}
int high = 0;
for (int point = firstMouth; point >= 0 && along[firstMouth] - along[point] <= 32D; point--) {
high = Math.max(high, reach.grade()[point] - sea);
}
return high;
}
private static boolean nearOutlet(Reach reach) {
for (ReachStyle style : reach.style()) {
if (style == ReachStyle.POND_OUTLET) {
return true;
}
}
return false;
}
private static Reach nearest(List<Reach> reaches, int x, int z) {
return reaches.stream().min(Comparator.comparingDouble((Reach reach) -> {
int last = reach.xs().length - 1;
return Math.hypot(reach.xs()[last] - x, reach.zs()[last] - z);
})).orElseThrow();
}
private static long dump(HydrologyWindows.Target target, File out, int x, int z) throws Exception {
try (RealPackProbeSupport.Workspace workspace = RealPackProbeSupport.openWorkspace(target.pack(), target.dimension(), LOG);
RealPackProbeSupport.EngineSession session = workspace.openEngine(target.seed(), false, "dump");
PrintWriter writer = new PrintWriter(new File(out, "dump-" + target.seed() + "-" + x + "_" + z + ".txt"))) {
Engine engine = session.engine();
HydrologySettings settings = settings(engine);
int sea = settings.seaLevel();
HydrologyPlanHarness.Plans plans = plans(engine, settings, target.windows().grown(1));
TidalReachProbe.Columns columns = columns(engine, settings, plans);
Reach reach = nearest(mouths(plans, target.windows()), x, z);
double[] along = MouthMetrics.along(reach);
double end = along[along.length - 1];
writer.println("sea " + sea + " reach " + reach.id() + " tier " + reach.tier().name() + " estuary " + reach.tier().estuary() + " points " + along.length + " length " + end + " stepHeight " + reach.tier().stepHeight());
writer.println("toEnd\tx\tz\tgrade\tsnap\thalf\tdepth\tstyle\tnatural\tnaturalL\tnaturalR\toceanIntent\tcolHead\tcolTerrain\trole");
for (int point = 0; point < along.length; point++) {
if (end - along[point] > 256D) {
continue;
}
int cx = (int) Math.floor(reach.xs()[point]);
int cz = (int) Math.floor(reach.zs()[point]);
int before = Math.max(0, point - 1);
int next = Math.min(along.length - 1, point + 1);
double dx = reach.xs()[next] - reach.xs()[before];
double dz = reach.zs()[next] - reach.zs()[before];
double span = Math.max(1e-3D, Math.hypot(dx, dz));
double reachOut = reach.halfWidth()[point] + 3D;
int lx = (int) Math.floor(cx - dz / span * reachOut);
int lz = (int) Math.floor(cz + dx / span * reachOut);
int rx = (int) Math.floor(cx + dz / span * reachOut);
int rz = (int) Math.floor(cz - dx / span * reachOut);
writer.printf(Locale.ROOT, "%.1f\t%.1f\t%.1f\t%d\t%d\t%.1f\t%.1f\t%s\t%d\t%d\t%d\t%b\t%d\t%d\t%s%n", end - along[point], reach.xs()[point], reach.zs()[point],
reach.grade()[point] - sea, MouthMetrics.snapped(reach, point, sea) - sea, reach.halfWidth()[point], reach.depth()[point], reach.style()[point],
columns.natural(cx, cz) - sea, columns.natural(lx, lz) - sea, columns.natural(rx, rz) - sea, columns.ocean(cx, cz),
head(columns, cx, cz, sea), columns.height(cx, cz) - sea, columns.role(cx, cz));
}
writer.println();
for (Map.Entry<WindowKey, WindowPlan> entry : plans.windowPlans().entrySet()) {
for (Reach near : entry.getValue().reaches()) {
double best = Double.POSITIVE_INFINITY;
int at = 0;
for (int point = 0; point < near.xs().length; point++) {
double apart = Math.hypot(near.xs()[point] - x, near.zs()[point] - z);
if (apart < best) {
best = apart;
at = point;
}
}
if (best < 32D) {
int last = near.xs().length - 1;
writer.printf(Locale.ROOT, "near reach %d window %d,%d tier %s down %d start %.0f,%.0f end %.0f,%.0f nearest %.0f grade there +%d style %s endGrade +%d lastStyle %s%n", near.id(), entry.getKey().wx(), entry.getKey().wz(), near.tier().name(), near.downstreamId(),
near.xs()[0], near.zs()[0], near.xs()[last], near.zs()[last], best, near.grade()[at] - sea, near.style()[at], near.grade()[last] - sea, near.style()[last]);
}
}
}
writer.println();
writer.println("heads above sea around " + x + "," + z + " (x right, z down); . dry land, ~ open sea, # dry below sea");
for (int gz = z - 40; gz <= z + 40; gz += 1) {
StringBuilder line = new StringBuilder();
for (int gx = x - 40; gx <= x + 40; gx += 1) {
int head = columns.head(gx, gz);
WaterRole role = columns.role(gx, gz);
if (head != Integer.MIN_VALUE) {
int up = head - sea;
line.append(up == 0 ? (role == WaterRole.MOUTH ? 'm' : '0') : up < 10 ? (char) ('0' + up) : '+');
} else {
boolean ocean = columns.ocean(gx, gz);
int ground = columns.height(gx, gz);
line.append(ground < sea ? (ocean ? '~' : '#') : '.');
}
}
writer.println(line);
}
System.out.println(LOG + " dumped reach " + reach.id());
return 0L;
}
}
private static int head(TidalReachProbe.Columns columns, int x, int z, int sea) {
int head = columns.head(x, z);
return head == Integer.MIN_VALUE ? -999 : head - sea;
}
private static long sections(HydrologyWindows.Target target, File out, String[] arguments) throws Exception {
try (RealPackProbeSupport.Workspace workspace = RealPackProbeSupport.openWorkspace(target.pack(), target.dimension(), LOG);
RealPackProbeSupport.EngineSession session = workspace.openEngine(target.seed(), false, "sections")) {
Engine engine = session.engine();
HydrologySettings settings = settings(engine);
int sea = settings.seaLevel();
HydrologyPlanHarness.Plans plans = plans(engine, settings, target.windows().grown(1));
List<Reach> mouths = mouths(plans, target.windows());
List<Reach> chosen = new ArrayList<>();
for (int index = 6; index + 1 < arguments.length; index += 2) {
chosen.add(nearest(mouths, Integer.parseInt(arguments[index]), Integer.parseInt(arguments[index + 1])));
}
Set<Long> chunks = new TreeSet<>();
for (Reach reach : chosen) {
int last = reach.xs().length - 1;
double[] along = MouthMetrics.along(reach);
for (int point = 0; point <= last; point++) {
if (along[last] - along[point] <= MouthMetrics.APPROACH + 48D) {
for (int dz = -64; dz <= 64; dz += 16) {
for (int dx = -64; dx <= 64; dx += 16) {
chunks.add(TidalReachProbe.key((Math.round(reach.xs()[point]) + dx) >> 4, (Math.round(reach.zs()[point]) + dz) >> 4));
}
}
}
}
}
int height = engine.getTarget().getHeight();
Map<Long, String[]> states = new ConcurrentHashMap<>();
Map<Long, int[]> colors = new ConcurrentHashMap<>();
ExecutorService pool = Executors.newFixedThreadPool(6);
try {
List<Future<?>> futures = new ArrayList<>();
for (long chunk : chunks) {
futures.add(pool.submit(() -> {
int chunkX = (int) (chunk >> 32);
int chunkZ = (int) chunk;
Hunk<NativeBlockState> blocks = Hunk.newArrayHunk(16, height, 16);
Hunk<NativeBiome> biomes = Hunk.newArrayHunk(16, height, 16);
engine.generate(chunkX << 4, chunkZ << 4, blocks, biomes, false);
int[] painted = new int[256 * LEVELS];
for (int lz = 0; lz < 16; lz++) {
for (int lx = 0; lx < 16; lx++) {
for (int level = 0; level < LEVELS; level++) {
NativeBlockState state = blocks.get(lx, sea - BELOW + level, lz);
painted[(lz << 4 | lx) * LEVELS + level] = state == null || state.isAir() ? AIR : TidalReachProbe.blockColor(state);
}
}
}
colors.put(chunk, painted);
return null;
}));
}
for (Future<?> future : futures) {
future.get();
}
} finally {
pool.shutdown();
}
for (Reach reach : chosen) {
int last = reach.xs().length - 1;
String name = target.seed() + "-" + Math.round(reach.xs()[last]) + "_" + Math.round(reach.zs()[last]);
ImageIO.write(sheet(reach, colors, sea), "png", new File(out, "mouth-" + name + ".png"));
System.out.println(LOG + " wrote " + name + " finalDrop " + MouthMetrics.finalDrop(reach, sea));
}
}
return 0L;
}
private static BufferedImage sheet(Reach reach, Map<Long, int[]> colors, int sea) {
List<BufferedImage> parts = new ArrayList<>();
parts.add(topView(reach, colors));
parts.add(longProfile(reach, colors));
double[] along = MouthMetrics.along(reach);
double end = along[along.length - 1];
for (double back : new double[]{0D, 8D, 16D, 32D, 48D, 64D}) {
int point = along.length - 1;
while (point > 1 && end - along[point] < back) {
point--;
}
double dx = reach.xs()[Math.min(along.length - 1, point + 1)] - reach.xs()[point - 1];
double dz = reach.zs()[Math.min(along.length - 1, point + 1)] - reach.zs()[point - 1];
double span = Math.max(1e-3D, Math.hypot(dx, dz));
parts.add(cross(reach.xs()[point], reach.zs()[point], -dz / span, dx / span, Math.round(back) + " back, grade +" + (reach.grade()[point] - sea), colors));
}
int width = 0;
int total = 0;
for (BufferedImage part : parts) {
width = Math.max(width, part.getWidth());
total += part.getHeight() + 4;
}
BufferedImage image = new BufferedImage(width, total, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = image.createGraphics();
int y = 0;
for (BufferedImage part : parts) {
graphics.drawImage(part, 0, y, null);
y += part.getHeight() + 4;
}
graphics.dispose();
return image;
}
private static BufferedImage topView(Reach reach, Map<Long, int[]> colors) {
double[] along = MouthMetrics.along(reach);
int centre = along.length - 1;
while (centre > 0 && along[along.length - 1] - along[centre] < 24D) {
centre--;
}
int cx = Math.round(reach.xs()[centre]);
int cz = Math.round(reach.zs()[centre]);
int half = 72;
int scale = 5;
BufferedImage image = new BufferedImage((2 * half + 1) * scale, (2 * half + 1) * scale, BufferedImage.TYPE_INT_RGB);
for (int z = -half; z <= half; z++) {
for (int x = -half; x <= half; x++) {
int bx = cx + x;
int bz = cz + z;
int[] painted = colors.get(TidalReachProbe.key(bx >> 4, bz >> 4));
int rgb = 0;
if (painted != null) {
int offset = ((bz & 15) << 4 | (bx & 15)) * LEVELS;
for (int level = LEVELS - 1; level >= 0; level--) {
if (painted[offset + level] != AIR) {
double shade = Math.clamp(0.72D + 0.06D * (level - BELOW), 0.35D, 1.25D);
int base = painted[offset + level];
int red = Math.min(255, (int) (((base >> 16) & 255) * shade));
int green = Math.min(255, (int) (((base >> 8) & 255) * shade));
int blue = Math.min(255, (int) ((base & 255) * shade));
rgb = red << 16 | green << 8 | blue;
break;
}
}
}
for (int dz = 0; dz < scale; dz++) {
for (int dx = 0; dx < scale; dx++) {
image.setRGB((x + half) * scale + dx, (z + half) * scale + dz, rgb);
}
}
}
}
Graphics2D graphics = image.createGraphics();
graphics.setColor(Color.WHITE);
graphics.drawString("from above, centre " + cx + "," + cz, 4, 12);
graphics.dispose();
return image;
}
private static BufferedImage longProfile(Reach reach, Map<Long, int[]> colors) {
double[] along = MouthMetrics.along(reach);
double end = along[along.length - 1];
int lastPoint = along.length - 1;
double ox = reach.xs()[lastPoint] - reach.xs()[lastPoint - 1];
double oz = reach.zs()[lastPoint] - reach.zs()[lastPoint - 1];
double span = Math.max(1e-3D, Math.hypot(ox, oz));
ox /= span;
oz /= span;
int width = MouthMetrics.APPROACH + 48 + 1;
int[][] line = new int[width][2];
int point = 0;
for (int across = 0; across < width; across++) {
double distance = end - MouthMetrics.APPROACH + across;
double x;
double z;
if (distance >= end) {
x = reach.xs()[lastPoint] + ox * (distance - end);
z = reach.zs()[lastPoint] + oz * (distance - end);
} else {
while (point < lastPoint - 1 && along[point + 1] < distance) {
point++;
}
double t = Math.clamp((distance - along[point]) / Math.max(1e-3D, along[point + 1] - along[point]), 0D, 1D);
x = reach.xs()[point] + t * (reach.xs()[point + 1] - reach.xs()[point]);
z = reach.zs()[point] + t * (reach.zs()[point + 1] - reach.zs()[point]);
}
line[across][0] = (int) Math.floor(x);
line[across][1] = (int) Math.floor(z);
}
return paint(line, "along the river, last " + MouthMetrics.APPROACH + " and 48 out to sea, " + line[MouthMetrics.APPROACH][0] + "," + line[MouthMetrics.APPROACH][1], colors);
}
private static BufferedImage cross(double x, double z, double nx, double nz, String label, Map<Long, int[]> colors) {
int width = 129;
int[][] line = new int[width][2];
for (int across = 0; across < width; across++) {
line[across][0] = (int) Math.floor(x + nx * (across - 64));
line[across][1] = (int) Math.floor(z + nz * (across - 64));
}
return paint(line, label + " at " + Math.round(x) + "," + Math.round(z), colors);
}
private static BufferedImage paint(int[][] line, String label, Map<Long, int[]> colors) {
BufferedImage image = new BufferedImage(line.length * SCALE, LEVELS * SCALE + 14, BufferedImage.TYPE_INT_RGB);
for (int across = 0; across < line.length; across++) {
int[] painted = colors.get(TidalReachProbe.key(line[across][0] >> 4, line[across][1] >> 4));
for (int level = 0; level < LEVELS; level++) {
int rgb = painted == null ? 0 : painted[((line[across][1] & 15) << 4 | (line[across][0] & 15)) * LEVELS + level];
for (int dx = 0; dx < SCALE; dx++) {
for (int dy = 0; dy < SCALE; dy++) {
image.setRGB(across * SCALE + dx, (LEVELS - 1 - level) * SCALE + dy + 14, rgb);
}
}
}
}
Graphics2D graphics = image.createGraphics();
graphics.setColor(new Color(255, 80, 80));
int seaRow = (LEVELS - 1 - BELOW) * SCALE + 14;
graphics.drawLine(0, seaRow, 6, seaRow);
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, image.getWidth(), 14);
graphics.setColor(Color.BLACK);
graphics.drawString(label, 2, 11);
graphics.dispose();
return image;
}
private static long digest(HydrologyWindows.Target target, File out) throws Exception {
try (RealPackProbeSupport.Workspace workspace = RealPackProbeSupport.openWorkspace(target.pack(), target.dimension(), LOG);
RealPackProbeSupport.EngineSession session = workspace.openEngine(target.seed(), false, "digest");
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(new File(out, "reaches-" + target.seed() + ".tsv.gz"))), StandardCharsets.UTF_8))) {
Engine engine = session.engine();
HydrologySettings settings = settings(engine);
HydrologyPlanHarness.Plans plans = plans(engine, settings, target.windows());
Map<String, Integer> totals = new HashMap<>();
for (Map.Entry<WindowKey, WindowPlan> entry : plans.windowPlans().entrySet()) {
String window = entry.getKey().wx() + "\t" + entry.getKey().wz();
for (Reach reach : entry.getValue().reaches()) {
String kind = TidalReachProbe.tidal(reach) ? "A" : MouthMetrics.seaMouth(reach) ? "M" : "R";
writer.println(kind + "\t" + window + "\t" + reach.id() + "\t" + reach.downstreamId() + "\t" + TidalReachProbe.stable(reach) + "\t" + join(reach.xs()) + "\t" + join(reach.zs()) + "\t" + Arrays.toString(reach.grade()).replace(" ", ""));
totals.merge(kind, 1, Integer::sum);
}
for (Pond pond : entry.getValue().ponds()) {
writer.println("P\t" + window + "\t" + pond.id() + "\t" + pond.outletReachId() + "\t" + pond.level() + "\t" + pond.floorX() + "\t" + pond.floorZ() + "\t" + pond.kind());
totals.merge("P", 1, Integer::sum);
}
for (Grotto grotto : entry.getValue().grottos()) {
writer.println("G\t" + window + "\t" + grotto.id() + "\t" + Arrays.hashCode(grotto.xs()) + "\t" + Arrays.hashCode(grotto.zs()) + "\t" + Arrays.hashCode(grotto.halfWidth())
+ "\t" + Arrays.hashCode(grotto.roof()) + "\t" + Arrays.hashCode(grotto.floor()) + "\t" + Arrays.hashCode(grotto.plugs()));
totals.merge("G", 1, Integer::sum);
}
}
System.out.println(LOG + " seed " + target.seed() + " reaches " + totals + " planFailures " + plans.failures().size());
return plans.failures().size();
}
}
private static String join(float[] values) {
StringBuilder text = new StringBuilder();
for (float value : values) {
if (!text.isEmpty()) {
text.append(',');
}
text.append(Math.round(value * 10f) / 10f);
}
return text.toString();
}
private static long chunks(HydrologyWindows.Target target, File out) throws Exception {
try (RealPackProbeSupport.Workspace workspace = RealPackProbeSupport.openWorkspace(target.pack(), target.dimension(), LOG);
RealPackProbeSupport.EngineSession session = workspace.openEngine(target.seed(), false, "chunks");
PrintWriter writer = new PrintWriter(new File(out, "chunks-" + target.seed() + ".tsv"))) {
Engine engine = session.engine();
int height = engine.getTarget().getHeight();
List<WindowKey> keys = target.windows().keys();
Map<Long, Long> hashes = new ConcurrentHashMap<>();
ExecutorService pool = Executors.newFixedThreadPool(6);
try {
List<Future<?>> futures = new ArrayList<>();
for (WindowKey key : keys) {
for (int dz = 0; dz < HydrologyWindows.CHUNKS; dz++) {
for (int dx = 0; dx < HydrologyWindows.CHUNKS; dx++) {
int chunkX = key.wx() * HydrologyWindows.CHUNKS + dx;
int chunkZ = key.wz() * HydrologyWindows.CHUNKS + dz;
futures.add(pool.submit(() -> {
Hunk<NativeBlockState> blocks = Hunk.newArrayHunk(16, height, 16);
Hunk<NativeBiome> biomes = Hunk.newArrayHunk(16, height, 16);
engine.generate(chunkX << 4, chunkZ << 4, blocks, biomes, false);
hashes.put(TidalReachProbe.key(chunkX, chunkZ), TidalReachProbe.blockHash(blocks, biomes, height));
return null;
}));
}
}
}
for (Future<?> future : futures) {
future.get();
}
} finally {
pool.shutdown();
}
for (Map.Entry<Long, Long> entry : hashes.entrySet()) {
writer.println((int) (entry.getKey() >> 32) + "\t" + entry.getKey().intValue() + "\t" + entry.getValue());
}
System.out.println(LOG + " seed " + target.seed() + " chunks " + hashes.size());
return 0L;
}
}
}
@@ -1089,6 +1089,14 @@ public final class TidalReachProbe {
return 0L;
}
static long blockHash(Hunk<NativeBlockState> blocks, Hunk<NativeBiome> biomes, int height) {
return hash(blocks, biomes, height, true);
}
static int blockColor(NativeBlockState state) {
return Slab.color(state);
}
private static double nearest(Reach arm, int x, int z) {
double best = Double.POSITIVE_INFINITY;
for (int point = 0; point < arm.xs().length; point++) {
@@ -1159,7 +1167,7 @@ public final class TidalReachProbe {
}
}
private static int stable(Reach reach) {
static int stable(Reach reach) {
int hash = 31 * Long.hashCode(reach.id()) + Long.hashCode(reach.downstreamId());
hash = 31 * hash + Float.floatToIntBits(reach.catchment());
hash = 31 * hash + reach.tier().name().hashCode();
@@ -1217,7 +1225,7 @@ public final class TidalReachProbe {
return HexFormat.of().formatHex(sha.digest(), 0, 8);
}
private static long key(int x, int z) {
static long key(int x, int z) {
return ((long) x << 32) | (z & 0xFFFFFFFFL);
}
}
@@ -0,0 +1,50 @@
package art.arcane.iris.probe;
import art.arcane.iris.generation.hydrology.config.IrisHydrology;
import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.hydrology.water.Reach;
import art.arcane.iris.generation.hydrology.water.ReachStyle;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class MouthMetricsTest {
private static final int SEA = 40;
@Test
public void readsTheDropAtTheSeaAndTheLargestStepNearIt() {
Reach reach = reach(0L, new int[]{50, 46, 44, 40, 40}, ReachStyle.MOUTH);
assertTrue(MouthMetrics.seaMouth(reach));
assertEquals(4, MouthMetrics.finalDrop(reach, SEA));
assertEquals(40D, MouthMetrics.seaRun(reach, SEA), 1e-6D);
assertEquals(4, MouthMetrics.largestStep(reach, SEA, 64D));
}
@Test
public void aFeederOrAPondEndIsNotASeaMouth() {
assertFalse(MouthMetrics.seaMouth(reach(7L, new int[]{50, 46, 44, 40, 40}, ReachStyle.MOUTH)));
assertFalse(MouthMetrics.seaMouth(reach(0L, new int[]{50, 46, 44, 44, 44}, ReachStyle.RUN)));
}
private static Reach reach(long downstream, int[] grade, ReachStyle end) {
HydrologySettings settings = HydrologySettings.compile(new IrisHydrology(), 1L, SEA, 0, 256);
int count = grade.length;
float[] xs = new float[count];
float[] zs = new float[count];
float[] half = new float[count];
float[] depth = new float[count];
ReachStyle[] style = new ReachStyle[count];
Arrays.fill(half, 4f);
Arrays.fill(depth, 2f);
Arrays.fill(style, ReachStyle.RUN);
for (int point = 0; point < count; point++) {
xs[point] = 20f * point;
}
style[count - 1] = end;
return new Reach(1L, settings.majorTier(), downstream, xs, zs, grade, half, depth, style, 1000f);
}
}