From 0dabc54e8882fcbd0699cbf63c46fc76f6e7ca6c Mon Sep 17 00:00:00 2001 From: Brian Neumann-Fopiano Date: Sun, 1 Nov 2026 17:15:27 -0500 Subject: [PATCH] Outlets start on the shore - Hold the leading outlet points near the pond at the pond level in ReachGrader, and keep spread from lowering them - Prepend a lead-in from the nearest pond mask node to each non-lake outlet, unless the anchor would fold the reach back on itself - Give held outlet points at least a one-block half-width and carry the held flags through chaikin and unfold - Add PondMask.Cell and PondMask.nearest - Link led-in outlets to their feeders at the junction vertex in ChunkFeatures, falling back to the first vertex's window - Count equal-head water inside the outlet footprint as outlet water in WaterInvariants.detachedOutlets - Add tests for the lip outlet, the tributary junction, the fallback exit, the swallowed outlet and the cross-window led-in feeder - Assert connected outlets on openFractal seeds 1-7 and in the planned scene, and tighten the settled-pond shore check - Check outlet exits at the junction vertex in ReachShaperTest --- .../hydrology/raster/ChunkFeatures.java | 30 ++- .../generation/hydrology/water/PondMask.java | 29 +++ .../hydrology/water/ReachDraft.java | 1 + .../hydrology/water/ReachGrader.java | 10 +- .../hydrology/water/ReachShaper.java | 117 ++++++++-- .../hydrology/plan/PlannedSceneTest.java | 27 ++- .../hydrology/plan/WaterInvariants.java | 15 +- .../hydrology/plan/WindowPlannerTest.java | 114 +++++++++- .../raster/ChunkWaterRasterTest.java | 42 ++++ .../hydrology/water/ReachShaperTest.java | 204 +++++++++++++++++- 10 files changed, 551 insertions(+), 38 deletions(-) diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/raster/ChunkFeatures.java b/core/src/main/java/art/arcane/iris/generation/hydrology/raster/ChunkFeatures.java index 74b9301f8..ea2b0df08 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/raster/ChunkFeatures.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/raster/ChunkFeatures.java @@ -330,9 +330,13 @@ final class ChunkFeatures { } private Reach feederLink(Reach downstream, WindowKey owner) { - WindowKey link = WindowKey.containing((int) Math.floor(downstream.xs()[0]), (int) Math.floor(downstream.zs()[0])); - IndexedWindow upstream = windows.get(link); - List owned = upstream == null ? List.of() : upstream.index().feeders(downstream.id()); + int junction = junction(downstream); + WindowKey link = windowAt(downstream, junction); + List owned = feeders(link, downstream.id()); + if (owned.isEmpty() && junction > 0) { + link = windowAt(downstream, 0); + owned = feeders(link, downstream.id()); + } if (owned.isEmpty()) { return downstream; } @@ -344,11 +348,25 @@ final class ChunkFeatures { return link.equals(owner) ? LinkBlend.clamp(downstream, feeders) : LinkBlend.blend(downstream, feeders); } - private static long cornerBlock(Reach reach) { + private List feeders(WindowKey key, long downstreamId) { + IndexedWindow window = windows.get(key); + return window == null ? List.of() : window.index().feeders(downstreamId); + } + + private int junction(Reach reach) { + return reach.xs().length > 1 && outletLevels.containsKey(reach.id()) ? 1 : 0; + } + + private long cornerBlock(Reach reach) { + int junction = junction(reach); int half = WindowKey.SIZE >> 1; - long cornerX = Math.floorDiv((int) Math.floor(reach.xs()[0]) + half, WindowKey.SIZE); - long cornerZ = Math.floorDiv((int) Math.floor(reach.zs()[0]) + half, WindowKey.SIZE); + long cornerX = Math.floorDiv((int) Math.floor(reach.xs()[junction]) + half, WindowKey.SIZE); + long cornerZ = Math.floorDiv((int) Math.floor(reach.zs()[junction]) + half, WindowKey.SIZE); return (cornerX << 32) | (cornerZ & 0xffffffffL); } + + private static WindowKey windowAt(Reach reach, int point) { + return WindowKey.containing((int) Math.floor(reach.xs()[point]), (int) Math.floor(reach.zs()[point])); + } } } diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/water/PondMask.java b/core/src/main/java/art/arcane/iris/generation/hydrology/water/PondMask.java index a853cc71f..d9805eb5e 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/water/PondMask.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/water/PondMask.java @@ -40,6 +40,32 @@ public record PondMask(int originX, int originZ, int step, int width, int depth, return grownNode(Math.floorDiv(x - originX + (step >> 1), step), Math.floorDiv(z - originZ + (step >> 1), step)); } + public Cell nearest(float x, float z, float radius) { + int minI = Math.max(0, (int) Math.floor((x - radius - originX) / step)); + int maxI = Math.min(width - 1, (int) Math.ceil((x + radius - originX) / step)); + int minJ = Math.max(0, (int) Math.floor((z - radius - originZ) / step)); + int maxJ = Math.min(depth - 1, (int) Math.ceil((z + radius - originZ) / step)); + double best = (double) radius * radius; + int bestI = -1; + int bestJ = -1; + for (int j = minJ; j <= maxJ; j++) { + for (int i = minI; i <= maxI; i++) { + if (!node(i, j)) { + continue; + } + double dx = originX + i * step - x; + double dz = originZ + j * step - z; + double distance = dx * dx + dz * dz; + if (distance < best || bestI < 0 && distance == best) { + best = distance; + bestI = i; + bestJ = j; + } + } + } + return bestI < 0 ? null : new Cell(originX + bestI * step, originZ + bestJ * step); + } + public boolean overlaps(PondMask other) { int half = step >> 1; int otherHalf = other.step >> 1; @@ -69,4 +95,7 @@ public record PondMask(int originX, int originZ, int step, int width, int depth, public int hashCode() { return 31 * (31 * (31 * (31 * (31 * originX + originZ) + step) + width) + depth) + Arrays.hashCode(bits); } + + public record Cell(int x, int z) { + } } diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachDraft.java b/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachDraft.java index 93c6ef0c9..e9ae13ad2 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachDraft.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachDraft.java @@ -12,6 +12,7 @@ final class ReachDraft { float[] catchments; boolean[] ocean; boolean[] outletZone; + boolean[] held; int[] target; int[] grade; float[] halfWidth; diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachGrader.java b/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachGrader.java index 1330f48cf..76236dd62 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachGrader.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachGrader.java @@ -58,6 +58,10 @@ final class ReachGrader { } int[] grade = profile(drafts, draft); for (int point = 0; point < grade.length; point++) { + if (draft.held != null && draft.held[point]) { + grade[point] = level; + continue; + } int cap = draft.ocean[point] ? seaLevel : draft.target[point] + MAX_POOL; int floor = lakeFloor[index] ? draft.floor : Math.max(seaLevel, Math.min(draft.floor, (int) Math.floor(draft.bank[point]) + maxFill)); level = Math.min(level, Math.max(floor, Math.min(grade[point], cap))); @@ -73,7 +77,7 @@ final class ReachGrader { for (int position = upstreamFirst.length - 1; position >= 0; position--) { ReachDraft draft = drafts.get(upstreamFirst[position]); if (!draft.tier.cascades()) { - spread(draft.grade, draft.tier.waterfallMinimumDrop(), startLimit(drafts, draft)); + spread(draft.grade, draft.tier.waterfallMinimumDrop(), startLimit(drafts, draft), draft.held); } lowerIncomingEnds(drafts, draft); } @@ -183,10 +187,10 @@ final class ReachGrader { return sorted[Math.max(0, (int) Math.ceil(POOL_QUANTILE * sorted.length) - 1)]; } - private static void spread(int[] grade, int waterfallMinimumDrop, int startLimit) { + private static void spread(int[] grade, int waterfallMinimumDrop, int startLimit, boolean[] held) { for (int point = grade.length - 2; point >= 0; point--) { int drop = grade[point] - grade[point + 1]; - if (drop >= 2 && drop < waterfallMinimumDrop) { + if (drop >= 2 && drop < waterfallMinimumDrop && (held == null || !held[point])) { int limit = point == 0 ? startLimit : carryLimit(grade, point, waterfallMinimumDrop); grade[point] = Math.max(grade[point + 1] + 1, limit); } diff --git a/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachShaper.java b/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachShaper.java index 13fa6e7fa..2d6635a3a 100644 --- a/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachShaper.java +++ b/core/src/main/java/art/arcane/iris/generation/hydrology/water/ReachShaper.java @@ -16,6 +16,9 @@ public final class ReachShaper { private static final float TAPER_LENGTH = 24f; private static final float WAIST = 0.5f; private static final float OUTLET_LENGTH = 8f; + private static final float LIP_MARGIN = 4f; + private static final int LEAD_IN_REACH = 16; + private static final float LIP_HALF_WIDTH = 1f; private static final long SALT_START = 0x52454143485354L; private static final long SALT_END = 0x524541434845L; private static final long SALT_COARSE_START = 0x434f4152534553L; @@ -58,12 +61,22 @@ public final class ReachShaper { drafts.get(outlet).outlet = true; } } + for (int pond = 0; pond < outletDrafts.length; pond++) { + if (leavesThroughALip(ponds.get(pond), outletDrafts[pond])) { + hold(drafts.get(outletDrafts[pond]), ponds.get(pond).mask()); + } + } ReachGrader.PondChain chain = pondChain(drafts, ponds, outletDrafts); int[] order = upstreamFirst(drafts, chain); int[] levels = ReachGrader.grade(drafts, order, settings.seaLevel(), settings.deformation().maxFill(), chain); for (int index : order) { finish(drafts, drafts.get(index)); } + for (int pond = 0; pond < outletDrafts.length; pond++) { + if (leavesThroughALip(ponds.get(pond), outletDrafts[pond])) { + leadIn(drafts.get(outletDrafts[pond]), ponds.get(pond).mask()); + } + } List linked = new ArrayList<>(ponds.size()); for (int pond = 0; pond < ponds.size(); pond++) { Pond settled = lowered(ponds.get(pond), levels[pond]); @@ -260,6 +273,79 @@ public final class ReachShaper { throw new IllegalStateException("Reach and pond links loop through " + (count - size) + " of " + count + " reaches"); } + private static boolean leavesThroughALip(Pond pond, int outletDraft) { + return outletDraft >= 0 && pond.kind() != PondKind.LAKE; + } + + private static void hold(ReachDraft draft, PondMask mask) { + draft.held = new boolean[draft.xs.length]; + draft.held[0] = true; + for (int point = 1; point < draft.xs.length; point++) { + float radius = draft.tier.halfWidth(draft.catchments[point]) + 1f + LIP_MARGIN; + if (mask.nearest(draft.xs[point], draft.zs[point], radius) == null) { + return; + } + draft.held[point] = true; + } + } + + private static void leadIn(ReachDraft draft, PondMask mask) { + if (mask.contains(Math.round(draft.xs[0]), Math.round(draft.zs[0]))) { + return; + } + PondMask.Cell anchor = mask.nearest(draft.xs[0], draft.zs[0], LEAD_IN_REACH); + if (anchor == null || foldsBack(draft, anchor)) { + return; + } + draft.xs = prepend(draft.xs, anchor.x()); + draft.zs = prepend(draft.zs, anchor.z()); + draft.catchments = prepend(draft.catchments, draft.catchments[0]); + draft.halfWidth = prepend(draft.halfWidth, draft.halfWidth[0]); + draft.depth = prepend(draft.depth, draft.depth[0]); + draft.grade = prepend(draft.grade, draft.grade[0]); + draft.ocean = prepend(draft.ocean, false); + draft.outletZone = prepend(draft.outletZone, true); + draft.held = prepend(draft.held, true); + ReachStyle[] style = new ReachStyle[draft.style.length + 1]; + style[0] = draft.style[0]; + System.arraycopy(draft.style, 0, style, 1, draft.style.length); + draft.style = style; + } + + private static boolean foldsBack(ReachDraft draft, PondMask.Cell anchor) { + float along = (float) Math.hypot(draft.xs[0] - anchor.x(), draft.zs[0] - anchor.z()); + for (int point = 1; point < draft.xs.length; point++) { + along += (float) Math.hypot(draft.xs[point] - draft.xs[point - 1], draft.zs[point] - draft.zs[point - 1]); + float gap = 2f * (draft.halfWidth[point] + 1f); + float apart = (float) Math.hypot(draft.xs[point] - anchor.x(), draft.zs[point] - anchor.z()); + if (apart < gap && along >= apart + gap) { + return true; + } + } + return false; + } + + private static float[] prepend(float[] values, float first) { + float[] result = new float[values.length + 1]; + result[0] = first; + System.arraycopy(values, 0, result, 1, values.length); + return result; + } + + private static int[] prepend(int[] values, int first) { + int[] result = new int[values.length + 1]; + result[0] = first; + System.arraycopy(values, 0, result, 1, values.length); + return result; + } + + private static boolean[] prepend(boolean[] values, boolean first) { + boolean[] result = new boolean[values.length + 1]; + result[0] = first; + System.arraycopy(values, 0, result, 1, values.length); + return result; + } + private static void finish(List drafts, ReachDraft draft) { draft.outletZone = new boolean[draft.xs.length]; float[] distance = distances(draft.xs, draft.zs); @@ -287,6 +373,7 @@ public final class ReachShaper { int[] grade = new int[size]; boolean[] ocean = new boolean[size]; boolean[] outletZone = new boolean[size]; + boolean[] held = draft.held == null ? null : new boolean[size]; for (int segment = 0; segment < count - 1; segment++) { int near = 1 + 2 * segment; int far = near + 1; @@ -296,23 +383,24 @@ public final class ReachShaper { zs[far] = 0.25f * draft.zs[segment] + 0.75f * draft.zs[segment + 1]; catchments[near] = 0.75f * draft.catchments[segment] + 0.25f * draft.catchments[segment + 1]; catchments[far] = 0.25f * draft.catchments[segment] + 0.75f * draft.catchments[segment + 1]; - carryStep(draft, segment, near, grade, ocean, outletZone); - carryStep(draft, segment + 1, far, grade, ocean, outletZone); + carryStep(draft, segment, near, grade, ocean, outletZone, held); + carryStep(draft, segment + 1, far, grade, ocean, outletZone, held); } xs[0] = draft.xs[0]; zs[0] = draft.zs[0]; catchments[0] = draft.catchments[0]; - carryStep(draft, 0, 0, grade, ocean, outletZone); + carryStep(draft, 0, 0, grade, ocean, outletZone, held); xs[size - 1] = draft.xs[count - 1]; zs[size - 1] = draft.zs[count - 1]; catchments[size - 1] = draft.catchments[count - 1]; - carryStep(draft, count - 1, size - 1, grade, ocean, outletZone); + carryStep(draft, count - 1, size - 1, grade, ocean, outletZone, held); draft.xs = xs; draft.zs = zs; draft.catchments = catchments; draft.grade = grade; draft.ocean = ocean; draft.outletZone = outletZone; + draft.held = held; } private static void unfold(ReachDraft draft) { @@ -355,14 +443,12 @@ public final class ReachShaper { int[] grade = new int[size]; boolean[] ocean = new boolean[size]; boolean[] outletZone = new boolean[size]; + boolean[] held = draft.held == null ? null : new boolean[size]; for (int index = 0; index < size; index++) { - int point = kept[index]; - xs[index] = draft.xs[point]; - zs[index] = draft.zs[point]; - catchments[index] = draft.catchments[point]; - grade[index] = draft.grade[point]; - ocean[index] = draft.ocean[point]; - outletZone[index] = draft.outletZone[point]; + carryStep(draft, kept[index], index, grade, ocean, outletZone, held); + xs[index] = draft.xs[kept[index]]; + zs[index] = draft.zs[kept[index]]; + catchments[index] = draft.catchments[kept[index]]; } draft.xs = xs; draft.zs = zs; @@ -370,12 +456,16 @@ public final class ReachShaper { draft.grade = grade; draft.ocean = ocean; draft.outletZone = outletZone; + draft.held = held; } - private static void carryStep(ReachDraft draft, int from, int to, int[] grade, boolean[] ocean, boolean[] outletZone) { + private static void carryStep(ReachDraft draft, int from, int to, int[] grade, boolean[] ocean, boolean[] outletZone, boolean[] held) { grade[to] = draft.grade[from]; ocean[to] = draft.ocean[from]; outletZone[to] = draft.outletZone[from]; + if (held != null) { + held[to] = draft.held[from]; + } } private static void widths(ReachDraft draft, float upstream) { @@ -390,7 +480,8 @@ public final class ReachShaper { if (taper) { law *= Math.min(1f, distance[point] / TAPER_LENGTH); } - draft.halfWidth[point] = Math.max(law, WAIST * running); + float lip = draft.held != null && draft.held[point] ? LIP_HALF_WIDTH : 0f; + draft.halfWidth[point] = Math.max(Math.max(law, WAIST * running), lip); running = Math.max(running, draft.halfWidth[point]); draft.depth[point] = draft.tier.depth(draft.halfWidth[point]); } diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/plan/PlannedSceneTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/plan/PlannedSceneTest.java index 0ff76c46b..529555f47 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/plan/PlannedSceneTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/plan/PlannedSceneTest.java @@ -13,7 +13,6 @@ import java.util.List; import java.util.function.IntBinaryOperator; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; public class PlannedSceneTest { private static final long SEED = 1337L; @@ -28,9 +27,9 @@ public class PlannedSceneTest { } @Test - public void reproducesTodaysOutletGap() { - assertFalse("detached outlets on openFractal(1) with rainfall " + RAINFALL + " over 2x2 windows", - WaterInvariants.detachedOutlets(openFractal()).isEmpty()); + public void outletsAreConnected() { + assertEquals("detached outlets on openFractal(1) with rainfall " + RAINFALL + " over 2x2 windows", List.of(), + WaterInvariants.detachedOutlets(openFractal())); } @Test @@ -49,6 +48,26 @@ public class PlannedSceneTest { } } + @Test + public void outletOwnedByAWiderReceivingReachAtThePondLevelIsConnected() { + HydrologySettings settings = PlannedScene.packSettings(SEED); + for (int receivingGrade : new int[]{100, 98}) { + Reach receiving = straight(52L, settings.tiers().get(2), 0L, 18f, new int[]{150, 128}, new int[]{300, 128}, (x, z) -> receivingGrade); + Reach outlet = straight(51L, settings.tiers().get(0), receiving.id(), 2f, new int[]{133, 128}, new int[]{150, 128}, (x, z) -> 100); + Pond pond = pond(21L, 100, disk(128, 128, 8), outlet.id()); + PlannedScene scene = PlannedScene.of(SyntheticTerrain.flat(104D), settings, List.of(outlet, receiving), List.of(pond)); + int outletColumns = 0; + for (int z = 120; z <= 136; z++) { + for (int x = 120; x <= 160; x++) { + outletColumns += scene.feature(x, z) == outlet.id() ? 1 : 0; + } + } + assertEquals("outlet columns owned by the receiving reach at " + receivingGrade, 0, outletColumns); + assertEquals("receiving reach at " + receivingGrade, receivingGrade == 100 ? List.of() : List.of(outlet.id()), + WaterInvariants.detachedOutlets(scene)); + } + } + @Test public void confluenceHasNoTongueAtEitherTributaryLevel() { HydrologySettings settings = PlannedScene.packSettings(SEED); diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/plan/WaterInvariants.java b/core/src/test/java/art/arcane/iris/generation/hydrology/plan/WaterInvariants.java index 5e77837af..daa9e7bfe 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/plan/WaterInvariants.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/plan/WaterInvariants.java @@ -91,10 +91,11 @@ final class WaterInvariants { int x = cell[0] + DX[side]; int z = cell[1] + DZ[side]; long feature = scene.feature(x, z); - if ((feature != pond.id() && feature != outlet.id()) || scene.head(x, z) != head || !seen.add(pack(x, z))) { + boolean outletWater = feature == outlet.id() || feature != pond.id() && covers(outlet, x, z); + if ((feature != pond.id() && !outletWater) || scene.head(x, z) != head || !seen.add(pack(x, z))) { continue; } - if (feature == outlet.id()) { + if (outletWater) { return true; } queue.add(new int[]{x, z}); @@ -208,6 +209,16 @@ final class WaterInvariants { return grade; } + private static boolean covers(Reach reach, int x, int z) { + for (int segment = 0; segment + 1 < reach.xs().length; segment++) { + double t = along(reach, segment, x, z); + if (offset(reach, segment, t, x, z) <= width(reach, segment, t)) { + return true; + } + } + return false; + } + private static double along(Reach reach, int segment, double x, double z) { double ax = reach.xs()[segment]; double az = reach.zs()[segment]; diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/plan/WindowPlannerTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/plan/WindowPlannerTest.java index b1a8b44ef..f81b9633c 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/plan/WindowPlannerTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/plan/WindowPlannerTest.java @@ -2,6 +2,7 @@ package art.arcane.iris.generation.hydrology.plan; import art.arcane.iris.generation.hydrology.config.IrisHydrology; import art.arcane.iris.generation.hydrology.grid.HeightLattice; +import art.arcane.iris.generation.hydrology.raster.WaterHeads; import art.arcane.iris.generation.hydrology.underground.SeaInlet; import art.arcane.iris.generation.hydrology.water.HydrologyTier; import art.arcane.iris.generation.hydrology.water.CupSet; @@ -13,6 +14,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 org.junit.AfterClass; import org.junit.Test; import java.util.ArrayList; @@ -44,6 +46,12 @@ public class WindowPlannerTest { private static final WindowKey ORIGIN = new WindowKey(0, 0); private static final WindowKey LAND = new WindowKey(4, 4); private static final int SEAM_DISTANCE = 256; + private static final Map OPEN_SCENES = new HashMap<>(); + + @AfterClass + public static void dropScenes() { + OPEN_SCENES.clear(); + } @Test public void zeroDensityRemovesLocalChannelsAndPonds() { @@ -558,8 +566,7 @@ public class WindowPlannerTest { continue; } outlets++; - assertTrue(pond + " outlet starts off its shore at " + outlet.xs()[0] + "," + outlet.zs()[0], - nearMask(pond.mask(), outlet.xs()[0], outlet.zs()[0], WindowPlanner.CELL)); + assertOutletLeavesAtThePondHead(pond, outlet); assertTrue(pond + " outlet " + outlet + " starts above it", outlet.grade()[0] <= pond.level()); } } @@ -620,6 +627,109 @@ public class WindowPlannerTest { return offset < WindowPlanner.CELL || offset >= WindowKey.SIZE - WindowPlanner.CELL; } + @Test + public void everyPondOutletLeavesThroughConnectedWater() { + int outlets = 0; + for (long seed = 1L; seed <= 7L; seed++) { + PlannedScene scene = openScene(seed); + assertEquals("detached outlets on openFractal(" + seed + ")", List.of(), WaterInvariants.detachedOutlets(scene)); + Map byId = byId(scene.reaches()); + for (Pond pond : scene.ponds()) { + outlets += pond.kind() != PondKind.LAKE && byId.containsKey(pond.outletReachId()) ? 1 : 0; + } + } + assertTrue("pond outlets checked " + outlets, outlets >= 50); + } + + private static synchronized PlannedScene openScene(long seed) { + return OPEN_SCENES.computeIfAbsent(seed, key -> PlannedScene.plan(SyntheticTerrain.openFractal(key), PlannedScene.packSettings(SEED), 1, 1)); + } + + private static void assertOutletLeavesAtThePondHead(Pond pond, Reach outlet) { + PondMask mask = pond.mask(); + int leading = 0; + while (leading + 1 < outlet.xs().length && touchesShore(mask, outlet, leading)) { + leading++; + } + assertTrue(pond + " outlet " + outlet.id() + " starts off its shore at " + outlet.xs()[0] + "," + outlet.zs()[0], leading > 0); + int head = WaterHeads.snap(pond.level(), SEA_LEVEL); + for (int segment = 0; segment < leading; segment++) { + int[] box = segmentBox(outlet, segment); + for (int z = box[1]; z <= box[3]; z++) { + for (int x = box[0]; x <= box[2]; x++) { + int[] covering = nearestCovering(outlet, x, z); + if (covering[0] == segment && onShore(mask, x, z)) { + assertEquals(pond + " outlet " + outlet.id() + " water at " + x + "," + z, head, + WaterHeads.snap(outlet.grade()[covering[1]], SEA_LEVEL)); + } + } + } + } + } + + private static boolean touchesShore(PondMask mask, Reach outlet, int segment) { + int[] box = segmentBox(outlet, segment); + for (int z = box[1]; z <= box[3]; z++) { + for (int x = box[0]; x <= box[2]; x++) { + if (onShore(mask, x, z) && covers(outlet, segment, x, z)) { + return true; + } + } + } + return false; + } + + private static boolean onShore(PondMask mask, int x, int z) { + return mask.contains(x, z) || mask.contains(x + 1, z) || mask.contains(x - 1, z) || mask.contains(x, z + 1) || mask.contains(x, z - 1); + } + + private static int[] segmentBox(Reach reach, int segment) { + float radius = Math.max(reach.halfWidth()[segment], reach.halfWidth()[segment + 1]); + return new int[]{(int) Math.floor(Math.min(reach.xs()[segment], reach.xs()[segment + 1]) - radius), + (int) Math.floor(Math.min(reach.zs()[segment], reach.zs()[segment + 1]) - radius), + (int) Math.ceil(Math.max(reach.xs()[segment], reach.xs()[segment + 1]) + radius), + (int) Math.ceil(Math.max(reach.zs()[segment], reach.zs()[segment + 1]) + radius)}; + } + + private static int[] nearestCovering(Reach reach, int x, int z) { + double nearest = Double.POSITIVE_INFINITY; + int[] found = {-1, -1}; + for (int segment = 0; segment + 1 < reach.xs().length; segment++) { + double t = along(reach, segment, x, z); + double distance = offset(reach, segment, t, x, z); + if (distance <= width(reach, segment, t) && distance < nearest) { + nearest = distance; + found[0] = segment; + found[1] = t < 0.5D ? segment : segment + 1; + } + } + return found; + } + + private static boolean covers(Reach reach, int segment, int x, int z) { + double t = along(reach, segment, x, z); + return offset(reach, segment, t, x, z) <= width(reach, segment, t); + } + + private static double along(Reach reach, int segment, double x, double z) { + 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; + return length == 0D ? 0D : Math.clamp(((x - ax) * dx + (z - az) * dz) / length, 0D, 1D); + } + + private static double offset(Reach reach, int segment, double t, double x, double z) { + double px = reach.xs()[segment] + t * (reach.xs()[segment + 1] - reach.xs()[segment]); + double pz = reach.zs()[segment] + t * (reach.zs()[segment + 1] - reach.zs()[segment]); + return Math.hypot(x - px, z - pz); + } + + private static double width(Reach reach, int segment, double t) { + return reach.halfWidth()[segment] + t * (reach.halfWidth()[segment + 1] - reach.halfWidth()[segment]); + } + private static boolean nearMask(PondMask mask, float x, float z, int distance) { for (int dz = -distance; dz <= distance; dz++) { for (int dx = -distance; dx <= distance; dx++) { diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/raster/ChunkWaterRasterTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/raster/ChunkWaterRasterTest.java index 519c4c44a..1841f55c2 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/raster/ChunkWaterRasterTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/raster/ChunkWaterRasterTest.java @@ -657,6 +657,25 @@ public class ChunkWaterRasterTest { } } + @Test + public void ledInOutletMeetsItsFeedersAcrossAWindowLine() { + HydrologyTier river = tier("river", 2f, 0.5f, 4, IrisBankStyle.SMOOTH); + Reach outlet = ledIn(line(191L, river, 0L, 516f, 200f, 600f, 200f, (x, z) -> Math.max(60, 68 - (int) ((x - 516f) / 10f))), 503f, 200f); + Reach feeder = line(192L, river, outlet.id(), 516f, 120f, 516f, 200f, (x, z) -> z < 160f ? 70 : 66); + Pond pond = new Pond(190L, PondKind.NATURAL, 68, 60, 504, 200, 69.5f, circle(488, 200, 16, 1), outlet.id(), 0, "water", 488, 200); + assertTrue("the lead-in starts in the pond", pond.mask().contains(503, 200)); + assertEquals(new WindowKey(0, 0), WindowKey.containing(503, 200)); + assertEquals(new WindowKey(1, 0), WindowKey.containing(516, 200)); + int feederEnd = feeder.grade()[feeder.grade().length - 1]; + assertTrue("the outlet owner starts above its feeder's end", outlet.grade()[1] > feederEnd); + Scene scene = new Scene(settings(new IrisHydrology()), (x, z) -> 75).reach(outlet).reach(feeder).pond(pond); + for (int x = 516; x <= 600; x++) { + int head = scene.head(x, 200); + assertNotEquals("centre line is water at x=" + x, Integer.MIN_VALUE, head); + assertTrue("outlet water at " + head + " above its feeder's end " + feederEnd + " at x=" + x, head <= feederEnd); + } + } + @Test public void everyBankStyleRasterizes() { IrisHydrology config = new IrisHydrology(); @@ -875,6 +894,29 @@ public class ChunkWaterRasterTest { return new Reach(id, tier, downstreamId, xs, zs, grades, halfWidth, depth, style, 1000f); } + private static Reach ledIn(Reach reach, float x, float z) { + int count = reach.xs().length + 1; + float[] xs = new float[count]; + float[] zs = new float[count]; + int[] grade = new int[count]; + float[] halfWidth = new float[count]; + float[] depth = new float[count]; + ReachStyle[] style = new ReachStyle[count]; + System.arraycopy(reach.xs(), 0, xs, 1, count - 1); + System.arraycopy(reach.zs(), 0, zs, 1, count - 1); + System.arraycopy(reach.grade(), 0, grade, 1, count - 1); + System.arraycopy(reach.halfWidth(), 0, halfWidth, 1, count - 1); + System.arraycopy(reach.depth(), 0, depth, 1, count - 1); + System.arraycopy(reach.style(), 0, style, 1, count - 1); + xs[0] = x; + zs[0] = z; + grade[0] = grade[1]; + halfWidth[0] = halfWidth[1]; + depth[0] = depth[1]; + style[0] = style[1]; + return new Reach(reach.id(), reach.tier(), reach.downstreamId(), xs, zs, grade, halfWidth, depth, style, reach.catchment()); + } + private static Pond pond(long id, PondKind kind, int level, PondMask mask, int floorX, int floorZ, int damRaise) { return new Pond(id, kind, level, level - 8, floorX, floorZ, level + 1.5f, mask, 0L, damRaise, "water", floorX, floorZ); } diff --git a/core/src/test/java/art/arcane/iris/generation/hydrology/water/ReachShaperTest.java b/core/src/test/java/art/arcane/iris/generation/hydrology/water/ReachShaperTest.java index ed71a950d..d633f385a 100644 --- a/core/src/test/java/art/arcane/iris/generation/hydrology/water/ReachShaperTest.java +++ b/core/src/test/java/art/arcane/iris/generation/hydrology/water/ReachShaperTest.java @@ -14,6 +14,7 @@ import art.arcane.iris.generation.hydrology.grid.HydrologySampleBuffer; import art.arcane.iris.generation.hydrology.grid.HydrologyTerrainSource; import art.arcane.iris.generation.hydrology.grid.PriorityFlood; import art.arcane.iris.generation.hydrology.plan.HydrologySettings; +import art.arcane.iris.generation.hydrology.raster.PondChannelSettlement; import art.arcane.volmlib.util.collection.KList; import org.junit.Test; @@ -295,8 +296,10 @@ public class ReachShaperTest { assertNotNull(outlet); assertTrue(outlet.grade()[0] <= upper.level()); assertEquals(ReachStyle.POND_OUTLET, outlet.style()[0]); - assertTrue("outlet starts " + outlet.xs()[0] + "," + outlet.zs()[0] + " spill " + upper.spillX() + "," + upper.spillZ(), - Math.hypot(outlet.xs()[0] - upper.spillX(), outlet.zs()[0] - upper.spillZ()) <= 1.5D * CELL); + assertTrue("outlet leads in from " + outlet.xs()[0] + "," + outlet.zs()[0], + upper.mask().contains(Math.round(outlet.xs()[0]), Math.round(outlet.zs()[0]))); + assertTrue("outlet exits " + outlet.xs()[1] + "," + outlet.zs()[1] + " spill " + upper.spillX() + "," + upper.spillZ(), + Math.hypot(outlet.xs()[1] - upper.spillX(), outlet.zs()[1] - upper.spillZ()) <= 1.5D * CELL); Reach reach = outlet; for (int hops = 0; reach.downstreamId() != 0L && hops < 64; hops++) { reach = byId.get(reach.downstreamId()); @@ -308,6 +311,109 @@ public class ReachShaperTest { assertEquals(original.withOutletReachId(upper.outletReachId()), upper); } + @Test + public void pondOutletWaterReachesItsPondAtThePondLevel() { + HydrologySettings settings = settings(config -> { + }); + DemGrid flat = outletGrid(); + int[] receivers = new int[flat.values().length]; + float[] accumulation = new float[receivers.length]; + BitSet channels = new BitSet(receivers.length); + outletRow(flat, receivers, accumulation, channels); + Pond pond = new Pond(31L, PondKind.NATURAL, 99, 94, 104, 64, 100f, disk(96, 64, 5), 0L, 0, "water", 96, 64); + HeightLattice fine = new HeightLattice(new Terrain((x, z) -> Math.hypot(x - 96D, z - 64D) <= 5D ? 94D + : x <= 104D ? 100D : 100D - 0.5D * (x - 104D)), FINE, false, 1 << 16); + ShapedNetwork shaped = new ReachShaper(settings).shape(flat, receivers, accumulation, channels, List.of(pond), fine, SEED); + Pond shapedPond = shaped.ponds().get(0); + assertEquals(99, shapedPond.level()); + assertOutletLeavesAtThePondLevel("lip outlet", shapedPond, byId(shaped.reaches()).get(shapedPond.outletReachId())); + assertEquals(99, PondChannelSettlement.settle(shaped, SEA_LEVEL).ponds().get(0).level()); + } + + @Test + public void pondOutletAtAJunctionLowersOnceAndStaysConnected() { + HydrologySettings settings = settings(config -> { + }); + DemGrid flat = outletGrid(); + int[] receivers = new int[flat.values().length]; + float[] accumulation = new float[receivers.length]; + BitSet channels = new BitSet(receivers.length); + outletRow(flat, receivers, accumulation, channels); + for (int j = flat.depth() - 1; j > 8; j--) { + flow(flat, receivers, accumulation, channels, 13, j, 13, j - 1, 1500f + 10f * (flat.depth() - j)); + } + HeightLattice fine = new HeightLattice(new Terrain((x, z) -> { + double radius = Math.hypot(x - 96D, z - 64D); + if (radius <= 8D) { + return 93D + radius; + } + if (Math.abs(x - 104D) <= 3D && z >= 68D) { + return 95D; + } + return x <= 104D ? 100D : 100D - 0.5D * (x - 104D); + }), FINE, false, 1 << 16); + PondPlanner planner = new PondPlanner(settings); + ReachShaper shaper = new ReachShaper(settings); + List water = List.of(new Pond(41L, PondKind.NATURAL, 99, 93, 104, 64, 100f, disk(96, 64, 5), 0L, 0, "water", 96, 64)); + ShapedNetwork network = PondChannelSettlement.settle(shaper.shape(flat, receivers, accumulation, channels, water, fine, SEED), SEA_LEVEL); + int lowerings = 0; + while (network.ponds().get(0).level() < water.get(0).level()) { + lowerings++; + assertTrue("pond still lowering after " + lowerings + " passes", lowerings <= 2); + Pond reflooded = planner.reflood(flat, fine, CupSet.EMPTY, network.ponds().get(0)); + assertNotNull("reflooded pond at " + network.ponds().get(0).level(), reflooded); + water = List.of(reflooded.withOutletReachId(0L)); + network = PondChannelSettlement.settle(shaper.shape(flat, receivers, accumulation, channels, water, fine, SEED), SEA_LEVEL); + } + Pond settled = network.ponds().get(0); + Map byId = byId(network.reaches()); + Reach outlet = byId.get(settled.outletReachId()); + assertOutletLeavesAtThePondLevel("junction outlet", settled, outlet); + Reach tributary = null; + for (Reach reach : network.reaches()) { + if (reach.downstreamId() == outlet.id()) { + tributary = reach; + } + } + assertNotNull("tributary joining the outlet", tributary); + assertEquals("settlements down to the tributary", 1, lowerings); + assertEquals(tributary.grade()[tributary.grade().length - 1], settled.level()); + } + + @Test + public void fallbackOutletRunningTowardItsPondKeepsItsStartAndHoldsThePondLevel() { + HydrologySettings settings = settings(config -> { + }); + DemGrid flat = outletGrid(); + int[] receivers = new int[flat.values().length]; + Arrays.fill(receivers, -1); + float[] accumulation = new float[receivers.length]; + BitSet channels = new BitSet(receivers.length); + flow(flat, receivers, accumulation, channels, 4, 4, 4, 5, 1600f); + for (int i = 0; i < 4; i++) { + flow(flat, receivers, accumulation, channels, i, 5, i + 1, 5, 1500f + 10f * i); + } + for (int i = 4; i < flat.width(); i++) { + flow(flat, receivers, accumulation, channels, i, 5, i + 1 < flat.width() ? i + 1 : -1, 5, 3200f + 10f * i); + } + PondMask mask = disk(32, 43, 2); + assertFalse("no DEM node inside the pond", mask.contains(32, 40) || mask.contains(32, 48)); + Pond pond = new Pond(51L, PondKind.NATURAL, 99, 94, 32, 34, 100f, mask, 0L, 0, "water", 32, 43); + HeightLattice fine = new HeightLattice(new Terrain((x, z) -> 100D), FINE, false, 1 << 16); + ShapedNetwork shaped = new ReachShaper(settings).shape(flat, receivers, accumulation, channels, List.of(pond), fine, SEED); + Pond shapedPond = shaped.ponds().get(0); + Reach outlet = byId(shaped.reaches()).get(shapedPond.outletReachId()); + assertNotNull(outlet); + assertNoFold("fallback outlet", outlet); + assertEquals("the outlet keeps the fallback exit as its start", 32f, outlet.xs()[0], 0f); + assertEquals(32f, outlet.zs()[0], 0f); + for (int point = 0; point < outlet.grade().length; point++) { + assertEquals("held grade at " + point, shapedPond.level(), outlet.grade()[point]); + } + assertOutletTouchesAtThePondLevel("fallback outlet", shapedPond, outlet); + assertEquals(99, PondChannelSettlement.settle(shaped, SEA_LEVEL).ponds().get(0).level()); + } + @Test public void gorgeCutWhenRidgeMissedByGrid() { HydrologySettings settings = settings(config -> { @@ -554,8 +660,9 @@ public class ReachShaperTest { ShapedNetwork shaped = new ReachShaper(settings).shape(flat, receivers, accumulation, channels, List.of(pond), fine, SEED); Reach outlet = byId(shaped.reaches()).get(shaped.ponds().get(0).outletReachId()); assertNotNull(outlet); - assertEquals(120f, outlet.xs()[0], 0f); - assertEquals(64f, outlet.zs()[0], 0f); + assertTrue(pond.mask().contains(Math.round(outlet.xs()[0]), Math.round(outlet.zs()[0]))); + assertEquals(120f, outlet.xs()[1], 0f); + assertEquals(64f, outlet.zs()[1], 0f); } @Test @@ -728,8 +835,9 @@ public class ReachShaperTest { Map byId = byId(shaped.reaches()); Reach outlet = byId.get(shaped.ponds().get(0).outletReachId()); assertNotNull(outlet); - assertEquals(344f, outlet.xs()[0], 0f); - assertEquals((float) VALLEY_Z, outlet.zs()[0], 0f); + assertTrue(drained.mask().contains(Math.round(outlet.xs()[0]), Math.round(outlet.zs()[0]))); + assertEquals(344f, outlet.xs()[1], 0f); + assertEquals((float) VALLEY_Z, outlet.zs()[1], 0f); assertEquals(ReachStyle.POND_OUTLET, outlet.style()[0]); assertFalse(endsIn(outlet, drained)); for (Reach reach : shaped.reaches()) { @@ -737,8 +845,9 @@ public class ReachShaperTest { } Reach fallback = byId.get(shaped.ponds().get(1).outletReachId()); assertNotNull(fallback); - assertEquals(424f, fallback.xs()[0], 0f); - assertEquals((float) VALLEY_Z, fallback.zs()[0], 0f); + assertTrue(beside.mask().contains(Math.round(fallback.xs()[0]), Math.round(fallback.zs()[0]))); + assertEquals(424f, fallback.xs()[1], 0f); + assertEquals((float) VALLEY_Z, fallback.zs()[1], 0f); } @Test @@ -1098,6 +1207,85 @@ public class ReachShaperTest { channels.set(cell); } + private static DemGrid outletGrid() { + DemGrid flat = new DemGrid(0, 0, CELL, 32, 16); + Arrays.fill(flat.values(), 100f); + return flat; + } + + private static void outletRow(DemGrid grid, int[] receivers, float[] accumulation, BitSet channels) { + Arrays.fill(receivers, -1); + for (int i = 0; i < grid.width(); i++) { + flow(grid, receivers, accumulation, channels, i, 8, i + 1 < grid.width() ? i + 1 : -1, 8, 1600f + 10f * i); + } + } + + private static void assertOutletLeavesAtThePondLevel(String label, Pond pond, Reach outlet) { + assertNotNull(label, outlet); + assertTrue(label + " starts off the shore at " + outlet.xs()[0] + "," + outlet.zs()[0], + pond.mask().contains(Math.round(outlet.xs()[0]), Math.round(outlet.zs()[0]))); + assertOutletTouchesAtThePondLevel(label, pond, outlet); + } + + private static void assertOutletTouchesAtThePondLevel(String label, Pond pond, Reach outlet) { + PondMask mask = pond.mask(); + int touched = 0; + for (int j = 0; j < mask.depth(); j++) { + for (int i = 0; i < mask.width(); i++) { + if (!mask.node(i, j)) { + continue; + } + int x = mask.originX() + i * mask.step(); + int z = mask.originZ() + j * mask.step(); + int[][] cells = {{x, z}, {x + 1, z}, {x - 1, z}, {x, z + 1}, {x, z - 1}}; + for (int[] cell : cells) { + int point = coveringPoint(outlet, cell[0], cell[1]); + if (point >= 0) { + touched++; + assertEquals(label + " water at " + cell[0] + "," + cell[1], pond.level(), outlet.grade()[point]); + } + } + } + } + assertTrue(label + " water touches the pond", touched > 0); + } + + private static int coveringPoint(Reach reach, int x, int z) { + double nearest = Double.POSITIVE_INFINITY; + int point = -1; + 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); + double distance = Math.hypot(x - (ax + t * dx), z - (az + t * dz)); + double width = reach.halfWidth()[segment] + t * (reach.halfWidth()[segment + 1] - reach.halfWidth()[segment]); + if (distance <= width && distance < nearest) { + nearest = distance; + point = t < 0.5D ? segment : segment + 1; + } + } + return point; + } + + private static PondMask disk(int centreX, int centreZ, int radius) { + int originX = centreX - radius - 1; + int originZ = centreZ - radius - 1; + int size = 2 * radius + 3; + long[] bits = new long[(size * size + 63) >>> 6]; + for (int j = 0; j < size; j++) { + for (int i = 0; i < size; i++) { + if (Math.hypot(originX + i - centreX, originZ + j - centreZ) <= radius) { + int index = j * size + i; + bits[index >>> 6] |= 1L << index; + } + } + } + return new PondMask(originX, originZ, 1, size, size, bits); + } + private static PondMask rectangle(int originX, int originZ, int width, int depth) { long[] bits = new long[(width * depth + 63) >>> 6]; for (int index = 0; index < width * depth; index++) {