Scale rivers and lakes to realistic size

Replace the reference-sheet water paint with a drainage-based hydrology
pass (BowlValleyHydrology.cs). Rivers are skeletonised into a graph,
oriented downhill, and sized by upstream drainage: creeks 2-5 m, main
rivers 40-50 m, mouths about 100 m. They meander and step down in level
to their lakes or the sea. Lakes keep their shapes but shrink to
realistic areas on flattened basin floors.

Water surfaces are now per-tile meshes: soft-edged river ribbons and
flat lake grids, built after the terrain (also via the new "Rebuild
Bowl Valley Water Surfaces" menu). The water shader gains an optional
vertex-alpha edge fade. The player is moved to the shrunken north-east
tarn's east shore.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Netherwarlord
2026-11-25 11:43:44 -05:00
co-authored by Claude Opus 5.5
parent 8579ec537f
commit bb5c70bd92
143 changed files with 10642 additions and 10369 deletions
+9550 -9823
View File
File diff suppressed because it is too large Load Diff
+3 -1
View File
@@ -242,7 +242,7 @@ GameObject:
m_Layer: 2
m_Name: Player
m_TagString: Untagged
m_Icon: {fileID: 0}
m_Icon: {fileID: 3936346786652291628, guid: 0000000000000000d000000000000000, type: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
@@ -313,6 +313,8 @@ MonoBehaviour:
jumpHeight: 1.1
gravity: 20
groundSnapDistance: 0.6
jumpBufferTime: 0.15
coyoteTime: 0.1
cameraPivot: {fileID: 7989328392886976939}
bodyVisual: {fileID: 6393905552424145001}
lookSensitivity: 0.1
@@ -0,0 +1,809 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace TravelersQuest.World.Editor
{
// Realistic-scale hydrology for the Bowl Valley world.
// The reference sheet paints rivers 2-5 px wide (1-3 km at ~535 m per pixel). Here the painted water is thinned to
// centre lines and turned into a river network: every river's width comes from how much channel drains through it
// (creeks 2-5 m, streams 8-20 m, main rivers 30-80 m, ~120 m at the biggest mouths). Every lake keeps its position
// and shape but is scaled down to a believable area. Water levels are fitted to the dry terrain, never above it.
public static partial class BowlValleyTerrainBuilder
{
public class Lake
{
public int id;
public Vector2 c; // world centroid
public float s; // linear scale applied to the reference shape
public float area0, area1; // km², reference / realistic
public int bx, by, bw, bh; // padded bounding box of the reference shape (crop px)
public float[] m1, m3, m6; // own mask blurred by 1, 3 and 6 px: shape, depth profile, rim
public Rect bounds; // world rect of the scaled lake including its rim
public float radius, level, depth; // metres (true scale)
}
public class Reach
{
public List<Vector2> p = new List<Vector2>();
public List<float> s = new List<float>(), w = new List<float>(), lvl = new List<float>();
public bool ext; public float coastS = -1; // ext: runs from the old outline to the sea
public int up = -1, down = -1; // graph nodes
public float acc0, lenKm; // km of channel draining into the start; own length
public List<Vector2> crop; // centre line in crop pixels (before smoothing)
public float extUp, extDown; // length of the straight run added to reach a shrunken lake
}
static List<Lake> lakes = new List<Lake>();
static List<Reach> streams = new List<Reach>();
static List<int>[] lakeBuckets; static int lbW, lbH;
static List<(int st, int k)>[] streamBuckets; static int sbW, sbH;
static int[] lakeLabel;
const float StreamBucket = 1000f, StreamReach = 760f, StreamStep = 40f, LakeBucket = 5000f;
static bool waterOff; // true while sampling the dry terrain that lake and river levels are fitted to
/// <summary>River width (m) from the km of channel draining through it.</summary>
public static float StreamWidth(float accKm) => Mathf.Clamp(1.8f * Mathf.Pow(Mathf.Max(accKm, 0f), 0.68f), 2f, 120f);
static float S01(float a, float b, float x) => Mathf.SmoothStep(0, 1, Mathf.InverseLerp(a, b, x));
static float PxX => SizeX * (1 - 2 * Margin) / (fields.bx1 - fields.bx0);
static float PxZ => SizeZ * (1 - 2 * Margin) / (fields.by1 - fields.by0);
static Vector2 WorldToCrop(float wx, float wz)
{
var f = fields;
float u = (wx / SizeX + 0.5f - Margin) / (1 - 2 * Margin);
float v = (0.5f - wz / SizeZ - Margin) / (1 - 2 * Margin);
return new Vector2(f.bx0 + u * (f.bx1 - f.bx0) - 0.5f, f.by0 + v * (f.by1 - f.by0) - 0.5f);
}
static void BuildHydrology()
{
waterOff = true;
BuildLakes();
LakeLevels();
BuildStreams();
StreamLevels();
BucketWater();
waterOff = false;
}
// ---------- lakes ----------
static void BuildLakes()
{
var f = fields; int N = CW * CH;
var isLake = new bool[N];
for (int i = 0; i < N; i++) isLake[i] = f.watMask[i] > 0 && f.waterWide[i] > 0.55f; // narrow channels stay rivers
lakeLabel = new int[N]; lakes = new List<Lake>();
var seen = new bool[N]; var q = new Queue<int>(); var members = new List<int>();
float pxArea = PxX * PxZ / 1e6f;
for (int st = 0; st < N; st++)
{
if (!isLake[st] || seen[st]) continue;
members.Clear(); seen[st] = true; q.Enqueue(st);
while (q.Count > 0)
{
int i = q.Dequeue(); members.Add(i); int x = i % CW, y = i / CW;
void T(int j) { if (isLake[j] && !seen[j]) { seen[j] = true; q.Enqueue(j); } }
if (x > 0) T(i - 1); if (x < CW - 1) T(i + 1); if (y > 0) T(i - CW); if (y < CH - 1) T(i + CW);
}
if (members.Count < 3) continue; // a blot on a river line, not a lake
var L = new Lake { id = lakes.Count };
int minx = CW, miny = CH, maxx = 0, maxy = 0; double sx = 0, sy = 0;
foreach (int i in members)
{
int x = i % CW, y = i / CW; sx += x; sy += y;
minx = Math.Min(minx, x); maxx = Math.Max(maxx, x); miny = Math.Min(miny, y); maxy = Math.Max(maxy, y);
lakeLabel[i] = L.id + 1;
}
L.area0 = members.Count * pxArea;
L.area1 = 0.04f * Mathf.Pow(L.area0, 1.05f);
L.s = Mathf.Min(1f, Mathf.Sqrt(L.area1 / L.area0));
const int pad = 28; // > 3 sigma of the widest blur, so every mask is ~0 at the box edge
L.bx = minx - pad; L.by = miny - pad; L.bw = maxx - minx + 1 + 2 * pad; L.bh = maxy - miny + 1 + 2 * pad;
var own = new float[L.bw * L.bh];
foreach (int i in members) own[(i / CW - L.by) * L.bw + (i % CW - L.bx)] = 1;
L.m1 = Blur(own, L.bw, L.bh, 1f); L.m3 = Normalise(Blur(own, L.bw, L.bh, 3f)); L.m6 = Normalise(Blur(own, L.bw, L.bh, 6f));
L.c = CropToWorld((float)(sx / members.Count), (float)(sy / members.Count));
Vector2 a = CropToWorld(L.bx, L.by), b = CropToWorld(L.bx + L.bw - 1, L.by + L.bh - 1);
a = L.c + (a - L.c) * L.s; b = L.c + (b - L.c) * L.s;
L.bounds = Rect.MinMaxRect(Mathf.Min(a.x, b.x), Mathf.Min(a.y, b.y), Mathf.Max(a.x, b.x), Mathf.Max(a.y, b.y));
L.radius = Mathf.Sqrt(L.area1 / Mathf.PI) * 1000f;
L.depth = Mathf.Clamp(2 + 0.01f * L.radius, 2, 40);
lakes.Add(L);
}
// Old water level of every painted lake from its real banks (low part of the ground just outside it).
f.lakeFloorW = null; f.lakeFloorLevel = null;
var wetM = new bool[N]; for (int i = 0; i < N; i++) wetM[i] = f.watMask[i] > 0;
var near = Dilate(wetM, 4);
var shore = lakes.Select(_ => new List<float>()).ToArray();
for (int y = 0; y < CH; y++) for (int x = 0; x < CW; x++)
{
int i = y * CW + x; if (!near[i] || wetM[i]) continue;
float bank = float.NaN; var hit = new HashSet<int>();
for (int dy = -3; dy <= 3; dy++) for (int dx = -3; dx <= 3; dx++)
{
int xx = x + dx, yy = y + dy; if (xx < 0 || yy < 0 || xx >= CW || yy >= CH) continue;
int l = lakeLabel[yy * CW + xx]; if (l <= 0 || !hit.Add(l)) continue;
if (float.IsNaN(bank)) { var w = CropToWorld(x, y); bank = RawHeight(w.x, w.y); }
shore[l - 1].Add(bank);
}
}
var lakeFloor = new float[lakes.Count];
for (int l = 0; l < lakes.Count; l++)
{
var sh = shore[l];
if (sh.Count == 0) sh.Add(RawHeight(lakes[l].c.x, lakes[l].c.y));
sh.Sort();
lakeFloor[l] = Mathf.Min(sh[(int)(sh.Count * 0.1f)] - 2, sh[sh.Count / 2] - 1);
}
var floorLv = new float[N]; var has = new bool[N]; var mem = new float[N];
for (int i = 0; i < N; i++)
{
int l = lakeLabel[i]; if (l <= 0) continue;
floorLv[i] = lakeFloor[l - 1]; has[i] = true; mem[i] = 1;
}
for (int pass = 0; pass < 10; pass++)
{
var nl = (float[])floorLv.Clone(); var nh = (bool[])has.Clone();
for (int y = 1; y < CH - 1; y++) for (int x = 1; x < CW - 1; x++)
{
int i = y * CW + x; if (has[i]) continue;
float acc = 0; int c = 0;
for (int dy = -1; dy <= 1; dy++) for (int dx = -1; dx <= 1; dx++) { int j = i + dy * CW + dx; if (has[j]) { acc += floorLv[j]; c++; } }
if (c > 0) { nl[i] = acc / c; nh[i] = true; }
}
floorLv = nl; has = nh;
}
f.lakeFloorLevel = floorLv;
// full strength over the painted lake itself, then a wide falloff so the basin grades into the slopes
var tight = Blur(mem, CW, CH, 1.0f); var wide = Blur(mem, CW, CH, 2.5f);
for (int i = 0; i < N; i++) tight[i] = Mathf.Max(tight[i], Mathf.Min(1f, wide[i] * 1.6f));
f.lakeFloorW = tight;
}
static float LakeSample(Lake L, float[] m, float wx, float wz)
{
var cp = WorldToCrop(L.c.x + (wx - L.c.x) / L.s, L.c.y + (wz - L.c.y) / L.s);
float lx = cp.x - L.bx, ly = cp.y - L.by;
if (lx < 0 || ly < 0 || lx > L.bw - 1 || ly > L.bh - 1) return 0;
return Bilinear(m, L.bw, L.bh, lx, ly);
}
// Level: the low part (30th percentile) of the dry ground just outside the scaled shore, but never more than
// 15 m above the lowest shore point (that low side gets a rim instead).
static void LakeLevels()
{
foreach (var L in lakes)
{
var samples = new List<float>();
float maxR = Mathf.Max(L.bounds.width, L.bounds.height), step = Mathf.Max(4f, L.radius / 40f);
for (int a = 0; a < 72; a++)
{
var d = new Vector2(Mathf.Cos(a * 5 * Mathf.Deg2Rad), Mathf.Sin(a * 5 * Mathf.Deg2Rad));
float edge = -1;
for (float r = 0; r < maxR; r += step) if (LakeSample(L, L.m1, L.c.x + d.x * r, L.c.y + d.y * r) >= 0.5f) edge = r;
if (edge < 0) continue;
float rr = edge + Mathf.Max(30f, 0.08f * L.radius);
samples.Add(Height(L.c.x + d.x * rr, L.c.y + d.y * rr));
}
if (samples.Count == 0) samples.Add(Height(L.c.x, L.c.y));
samples.Sort();
L.level = Mathf.Min(samples[(int)(samples.Count * 0.3f)], samples[0] + 15f) - 0.3f;
}
}
// ---------- river network ----------
static void BuildStreams()
{
var f = fields; int N = CW * CH;
float pxKm = 0.5f * (PxX + PxZ) / 1000f;
var nearLake = new bool[N];
for (int i = 0; i < N; i++) nearLake[i] = lakeLabel[i] > 0;
nearLake = Dilate(nearLake, 1);
var riv = new bool[N];
for (int i = 0; i < N; i++) riv[i] = f.watMask[i] > 0 && !nearLake[i];
var sk = Thin(riv, CW, CH);
int[] nb = new int[8];
int Neigh(int i, int[] o)
{
int x = i % CW, y = i / CW, c = 0;
for (int dy = -1; dy <= 1; dy++) for (int dx = -1; dx <= 1; dx++)
{
if (dx == 0 && dy == 0) continue;
int xx = x + dx, yy = y + dy; if (xx < 0 || yy < 0 || xx >= CW || yy >= CH) continue;
int j = yy * CW + xx; if (sk[j]) o[c++] = j;
}
return c;
}
var isNode = new bool[N];
for (int i = 0; i < N; i++) if (sk[i] && Neigh(i, nb) != 2) isNode[i] = true;
var parent = new int[N]; for (int i = 0; i < N; i++) parent[i] = i;
int Find(int i) { while (parent[i] != i) { parent[i] = parent[parent[i]]; i = parent[i]; } return i; }
for (int i = 0; i < N; i++)
{
if (!isNode[i]) continue;
int c = Neigh(i, nb);
for (int k = 0; k < c; k++) if (isNode[nb[k]]) { int a = Find(i), b = Find(nb[k]); if (a != b) parent[a] = b; }
}
// chains between node clusters
var chains = new List<(int a, int b, List<int> px)>();
var used = new bool[N]; var nb2 = new int[8];
for (int n = 0; n < N; n++)
{
if (!isNode[n]) continue;
int c = Neigh(n, nb);
for (int k = 0; k < c; k++)
{
int j = nb[k];
if (isNode[j] || used[j]) continue;
var path = new List<int> { n }; int prev = n, cur = j; bool ok = false;
while (true)
{
path.Add(cur);
if (isNode[cur]) { ok = true; break; }
used[cur] = true;
int cc = Neigh(cur, nb2), nxt = -1;
for (int t = 0; t < cc; t++) if (nb2[t] != prev && !(used[nb2[t]] && !isNode[nb2[t]])) { nxt = nb2[t]; break; }
if (nxt < 0) break;
prev = cur; cur = nxt;
}
if (ok) chains.Add((Find(n), Find(cur), path));
}
}
// cluster centroids
var cSum = new Dictionary<int, (double x, double y, int n)>();
for (int i = 0; i < N; i++)
if (isNode[i]) { int r = Find(i); cSum.TryGetValue(r, out var v); cSum[r] = (v.x + i % CW, v.y + i / CW, v.n + 1); }
Vector2 Centroid(int r) { var v = cSum[r]; return new Vector2((float)(v.x / v.n), (float)(v.y / v.n)); }
// what each dead end touches: a (realistic) lake, or the start of a river extension to the sea
var extStarts = rivers.Select(rp => WorldToCrop(rp.p[0].x, rp.p[0].y)).ToList();
int LakeAt(Vector2 cp)
{
int best = -1; float bd = 9;
for (int dy = -3; dy <= 3; dy++) for (int dx = -3; dx <= 3; dx++)
{
int x = Mathf.RoundToInt(cp.x) + dx, y = Mathf.RoundToInt(cp.y) + dy;
if (x < 0 || y < 0 || x >= CW || y >= CH) continue;
int l = lakeLabel[y * CW + x]; float d = dx * dx + dy * dy;
if (l > 0 && d <= bd) { bd = d; best = l - 1; }
}
return best;
}
int SeaAt(Vector2 cp) { for (int e = 0; e < extStarts.Count; e++) if ((extStarts[e] - cp).sqrMagnitude <= 9.5f) return e; return -1; }
// prune thinning spurs and merge pass-through clusters
for (int round = 0; round < 4; round++)
{
var deg = new Dictionary<int, int>();
foreach (var ch in chains) { deg[ch.a] = deg.GetValueOrDefault(ch.a) + 1; deg[ch.b] = deg.GetValueOrDefault(ch.b) + 1; }
bool Attached(int r) => LakeAt(Centroid(r)) >= 0 || SeaAt(Centroid(r)) >= 0;
chains = chains.Where(ch =>
{
int da = deg[ch.a], db = deg[ch.b], len = ch.px.Count;
if (da == 1 && db == 1) return len >= 8 || Attached(ch.a) || Attached(ch.b);
if (da == 1 && db >= 3 && len < 6 && !Attached(ch.a)) return false;
if (db == 1 && da >= 3 && len < 6 && !Attached(ch.b)) return false;
return true;
}).ToList();
deg.Clear();
foreach (var ch in chains) { deg[ch.a] = deg.GetValueOrDefault(ch.a) + 1; deg[ch.b] = deg.GetValueOrDefault(ch.b) + 1; }
bool merged = true;
while (merged)
{
merged = false;
foreach (var kv in deg)
{
if (kv.Value != 2) continue;
int r = kv.Key;
int i1 = chains.FindIndex(ch => ch.a == r || ch.b == r);
int i2 = chains.FindIndex(i1 + 1, ch => ch.a == r || ch.b == r);
if (i1 < 0 || i2 < 0) continue;
var c1 = chains[i1]; var c2 = chains[i2];
var p1 = c1.b == r ? c1.px : Enumerable.Reverse(c1.px).ToList(); int s1 = c1.b == r ? c1.a : c1.b;
var p2 = c2.a == r ? c2.px : Enumerable.Reverse(c2.px).ToList(); int e2 = c2.a == r ? c2.b : c2.a;
if (s1 == r || e2 == r) continue; // loop
var np = new List<int>(p1); np.AddRange(p2.Skip(1));
chains[i1] = (s1, e2, np); chains.RemoveAt(i2);
deg.Remove(r); merged = true; break;
}
}
}
// graph nodes: clusters (by root pixel), lakes (N + id), sea mouths (2N + ext index)
int NodeOf(int r, out Vector2 world)
{
var cp = Centroid(r);
int l = LakeAt(cp); if (l >= 0) { world = CropToWorld(cp.x, cp.y); return N + l; }
int e = SeaAt(cp); if (e >= 0) { world = CropToWorld(cp.x, cp.y); return 2 * N + e; }
world = CropToWorld(cp.x, cp.y); return r;
}
// a lake can't sit above the ground where a river reaches it from higher up (settled before flow directions)
for (int pass = 0; pass < 2; pass++)
foreach (var ch in chains)
{
int na = NodeOf(ch.a, out var wa), nb_ = NodeOf(ch.b, out var wb);
for (int end = 0; end < 2; end++)
{
int lakeNode = end == 0 ? na : nb_, other = end == 0 ? nb_ : na; var ow = end == 0 ? wb : wa;
if (lakeNode < N || lakeNode >= 2 * N || other == lakeNode) continue;
var L = lakes[lakeNode - N];
int idx = end == 0 ? Mathf.Min(2, ch.px.Count - 1) : Mathf.Max(0, ch.px.Count - 3);
var gw = CropToWorld(ch.px[idx] % CW, ch.px[idx] / CW);
float g = Height(gw.x, gw.y);
float eo = other >= 2 * N ? -1e6f : other >= N ? lakes[other - N].level : Height(ow.x, ow.y);
if (eo > L.level && g - 0.5f < L.level) L.level = g - 0.5f;
}
}
var elev = new Dictionary<int, float>();
float NodeElev(int node, Vector2 world)
{
if (elev.TryGetValue(node, out float e)) return e;
e = node >= 2 * N ? -1e6f : node >= N ? lakes[node - N].level : Height(world.x, world.y);
elev[node] = e; return e;
}
streams = new List<Reach>();
foreach (var ch in chains)
{
int na = NodeOf(ch.a, out var wa), nb_ = NodeOf(ch.b, out var wb);
if (na == nb_ && na >= N) continue; // a channel that leaves and re-enters the same lake
float ea = NodeElev(na, wa), eb = NodeElev(nb_, wb);
var pts = ch.px.Select(i => new Vector2(i % CW, i / CW)).ToList();
pts[0] = Centroid(ch.a); pts[pts.Count - 1] = Centroid(ch.b);
if (ea < eb) { pts.Reverse(); (na, nb_) = (nb_, na); }
streams.Add(new Reach { up = na, down = nb_, crop = pts, lenKm = (pts.Count - 1) * pxKm });
}
// drainage: process nodes from high to low, passing accumulated channel length downstream
var inflow = new Dictionary<int, float>();
var outs = streams.GroupBy(st => st.up).ToDictionary(g => g.Key, g => g.ToList());
foreach (var node in streams.SelectMany(st => new[] { st.up, st.down }).Distinct().OrderByDescending(nd => elev[nd]))
{
if (!outs.TryGetValue(node, out var list)) continue;
float share = inflow.GetValueOrDefault(node) / list.Count;
foreach (var st in list) { st.acc0 = share; inflow[st.down] = inflow.GetValueOrDefault(st.down) + share + st.lenKm; }
}
// geometry for the core rivers
int seed = 0;
foreach (var st in streams)
{
var wp = st.crop.Select(c => CropToWorld(c.x, c.y)).ToList();
if (st.up >= N && st.up < 2 * N) st.extUp = ExtendIntoLake(wp, lakes[st.up - N], atStart: true);
if (st.down >= N && st.down < 2 * N) st.extDown = ExtendIntoLake(wp, lakes[st.down - N], atStart: false);
if (st.down >= 2 * N) wp.Add(rivers[st.down - 2 * N].p[0]);
FinishGeometry(st, wp, ++seed, meander: 1f);
}
// extensions from the old outline to the sea continue whatever drains into their start
for (int e = 0; e < rivers.Count; e++)
{
var rp = rivers[e];
int cut = rp.s.FindIndex(v => v > rp.coastS + 2500);
var wp = rp.p.Take(cut < 0 ? rp.p.Count : cut + 1).ToList();
var st = new Reach { ext = true, up = 2 * N + e, down = -1, acc0 = inflow.GetValueOrDefault(2 * N + e, 30f) };
FinishGeometry(st, wp, ++seed, meander: 0.5f);
int k = 0; while (k < st.p.Count && Height(st.p[k].x, st.p[k].y) >= 0) k++;
st.coastS = k < st.p.Count ? st.s[k] : st.s[st.s.Count - 1];
for (int i = 0; i < st.p.Count; i++) st.w[i] *= 1 + S01(st.coastS - 3000, st.coastS, st.s[i]); // estuary flare
streams.Add(st);
}
}
static float ExtendIntoLake(List<Vector2> wp, Lake L, bool atStart)
{
Vector2 end = atStart ? wp[0] : wp[wp.Count - 1];
var ext = new List<Vector2>();
Vector2 dir = L.c - end; float dist = dir.magnitude; if (dist < 1) return 0; dir /= dist;
for (float d = 100; d < dist; d += 100)
{
var p = end + dir * d; ext.Add(p);
if (LakeSample(L, L.m1, p.x, p.y) > 0.8f) break;
}
if (ext.Count == 0) ext.Add(L.c);
float len = (ext[ext.Count - 1] - end).magnitude;
if (atStart) { ext.Reverse(); wp.InsertRange(0, ext); } else wp.AddRange(ext);
return len;
}
// smooth the pixel centre line, resample every StreamStep metres, assign widths and add a natural meander
static void FinishGeometry(Reach st, List<Vector2> wp, int seed, float meander)
{
for (int round = 0; round < 3; round++)
{
var np = new List<Vector2> { wp[0] };
for (int k = 0; k + 1 < wp.Count; k++) { np.Add(Vector2.Lerp(wp[k], wp[k + 1], 0.25f)); np.Add(Vector2.Lerp(wp[k], wp[k + 1], 0.75f)); }
np.Add(wp[wp.Count - 1]); wp = np;
}
var res = new List<Vector2> { wp[0] }; var dist = new List<float> { 0 };
float carry = 0, total = 0;
for (int k = 0; k + 1 < wp.Count; k++)
{
Vector2 a = wp[k], b = wp[k + 1]; float seg = (b - a).magnitude; if (seg < 1e-3f) continue;
float t = StreamStep - carry;
while (t <= seg) { res.Add(Vector2.Lerp(a, b, t / seg)); dist.Add(total + t); t += StreamStep; }
carry = seg - (t - StreamStep); total += seg;
}
if ((res[res.Count - 1] - wp[wp.Count - 1]).magnitude > 1) { res.Add(wp[wp.Count - 1]); dist.Add(total); }
int n = res.Count;
var w = new List<float>(n);
for (int k = 0; k < n; k++) w.Add(StreamWidth(st.acc0 + dist[k] / 1000f));
if (meander > 0 && n > 2)
{
var moved = new List<Vector2>(n);
for (int k = 0; k < n; k++)
{
Vector2 t = res[Mathf.Min(n - 1, k + 1)] - res[Mathf.Max(0, k - 1)]; t.Normalize();
var nrm = new Vector2(-t.y, t.x);
float lam = Mathf.Max(350f, 14f * w[k]), amp = Mathf.Clamp(2.5f * w[k] + 25f, 25f, 200f) * meander;
float fade = S01(0, lam, dist[k]) * S01(0, lam, total - dist[k]);
float off = (float)Noise.Fbm(dist[k] / lam + seed * 13.7, seed * 5.3, 3) * 1.6f * amp * fade;
// the straight runs added to reach a shrunken lake wander across the old lake floor like a floodplain
// river (faded in from the original channel, and out again before the lake so the end stays inside it)
float ext = 0, extLen = 0;
if (st.extUp > 0 && dist[k] < st.extUp) { extLen = st.extUp; ext = S01(0, 800, st.extUp - dist[k]) * S01(0, 0.2f * extLen, dist[k]); }
float fromEnd = total - dist[k];
if (st.extDown > 0 && fromEnd < st.extDown) { extLen = st.extDown; ext = S01(0, 800, st.extDown - fromEnd) * S01(0, 0.2f * extLen, fromEnd); }
if (ext > 0)
{
float lam2 = Mathf.Clamp(extLen / 3f, 1200f, 4000f), amp2 = Mathf.Clamp(0.12f * extLen, 150f, 1500f);
off += (float)Noise.Fbm(dist[k] / lam2 + seed * 3.1, seed * 9.7 + 40, 3) * 1.6f * amp2 * ext;
}
moved.Add(res[k] + nrm * off);
}
res = moved;
}
st.p = res; st.w = w; st.s = new List<float>(n) { 0 };
for (int k = 1; k < n; k++) st.s.Add(st.s[k - 1] + (res[k] - res[k - 1]).magnitude);
st.lvl = new List<float>(new float[n]);
}
// ---------- water levels ----------
// Each river follows the dry ground, smoothed over ~1 km and never rising downstream; it ends at the level of
// whatever it flows into (a lake, a bigger river, the sea), easing into it over its last stretch.
static void StreamLevels()
{
int N = CW * CH;
var nodeLevel = new Dictionary<int, float>();
foreach (var L in lakes) nodeLevel[N + L.id] = L.level;
var h0 = new Dictionary<Reach, float[]>();
foreach (var st in streams)
{
int n = st.p.Count; var raw = new float[n];
for (int k = 0; k < n; k++) raw[k] = Height(st.p[k].x, st.p[k].y);
var sm = new float[n];
for (int k = 0; k < n; k++)
{
float acc = 0; int c = 0;
for (int j = Mathf.Max(0, k - 12); j <= Mathf.Min(n - 1, k + 12); j++) { acc += raw[j]; c++; }
sm[k] = Mathf.Min(acc / c, raw[k]);
}
h0[st] = sm;
}
Lake LakeOf(int node) => node >= N && node < 2 * N ? lakes[node - N] : null;
foreach (var L in lakes) nodeLevel[N + L.id] = L.level;
// extensions to the sea first, then the network from its outlets upward
var order = streams.Where(s => s.ext).Concat(streams.Where(s => !s.ext).OrderBy(s =>
s.down >= 2 * N ? -1e6f : s.down >= N ? lakes[s.down - N].level : Height(s.p[s.p.Count - 1].x, s.p[s.p.Count - 1].y))).ToList();
foreach (var st in order)
{
int n = st.p.Count; var L = st.lvl; var g = h0[st];
var upLake = LakeOf(st.up); var downLake = LakeOf(st.down);
float start = upLake != null ? upLake.level : g[0] - 0.5f;
if (!st.ext && nodeLevel.TryGetValue(st.up, out float known) && upLake == null) start = Mathf.Min(start, known + 3f);
L[0] = start;
for (int k = 1; k < n; k++) L[k] = Mathf.Min(L[k - 1], g[k] - 0.5f);
if (st.ext)
{
float c0 = st.coastS - 3000; int k0 = st.s.FindIndex(v => v >= c0); float l0 = L[Mathf.Max(0, k0)];
for (int k = 0; k < n; k++)
{
if (st.s[k] >= st.coastS) L[k] = 0;
else if (st.s[k] >= c0) L[k] = Mathf.Min(L[k], Mathf.Lerp(l0, 0.3f, S01(c0, st.coastS, st.s[k])));
}
}
else if (st.down >= 0 && nodeLevel.TryGetValue(st.down, out float J))
{
if (J > L[n - 1] && J - L[n - 1] < 8f) for (int k = n - 1; k >= 0 && L[k] < J; k--) L[k] = J;
else if (J < L[n - 1])
{
float ramp = Mathf.Min(800f, st.s[n - 1] / 3f), s0 = st.s[n - 1] - ramp;
for (int k = 0; k < n; k++) if (st.s[k] > s0) L[k] = Mathf.Lerp(L[k], J, S01(s0, st.s[n - 1], st.s[k]));
}
}
if (downLake != null) for (int k = 0; k < n; k++) if (LakeSample(downLake, downLake.m1, st.p[k].x, st.p[k].y) > 0.5f) L[k] = Mathf.Min(L[k], downLake.level);
if (!nodeLevel.ContainsKey(st.up)) nodeLevel[st.up] = L[0];
}
}
static void BucketWater()
{
sbW = Mathf.CeilToInt(WorldSizeX / StreamBucket) + 2; sbH = Mathf.CeilToInt(WorldSizeZ / StreamBucket) + 2;
streamBuckets = new List<(int, int)>[sbW * sbH];
int BX(float x) => Mathf.Clamp((int)((x + WorldSizeX / 2) / StreamBucket) + 1, 0, sbW - 1);
int BZ(float z) => Mathf.Clamp((int)((z + WorldSizeZ / 2) / StreamBucket) + 1, 0, sbH - 1);
for (int si = 0; si < streams.Count; si++)
{
var st = streams[si];
for (int k = 0; k + 1 < st.p.Count; k++)
{
Vector2 a = st.p[k], b = st.p[k + 1];
for (int bz = BZ(Mathf.Min(a.y, b.y) - StreamReach); bz <= BZ(Mathf.Max(a.y, b.y) + StreamReach); bz++)
for (int bx = BX(Mathf.Min(a.x, b.x) - StreamReach); bx <= BX(Mathf.Max(a.x, b.x) + StreamReach); bx++)
(streamBuckets[bz * sbW + bx] ??= new List<(int, int)>()).Add((si, k));
}
}
lbW = Mathf.CeilToInt(WorldSizeX / LakeBucket) + 2; lbH = Mathf.CeilToInt(WorldSizeZ / LakeBucket) + 2;
lakeBuckets = new List<int>[lbW * lbH];
foreach (var L in lakes)
{
int x0 = Mathf.Clamp((int)((L.bounds.xMin + WorldSizeX / 2) / LakeBucket) + 1, 0, lbW - 1), x1 = Mathf.Clamp((int)((L.bounds.xMax + WorldSizeX / 2) / LakeBucket) + 1, 0, lbW - 1);
int z0 = Mathf.Clamp((int)((L.bounds.yMin + WorldSizeZ / 2) / LakeBucket) + 1, 0, lbH - 1), z1 = Mathf.Clamp((int)((L.bounds.yMax + WorldSizeZ / 2) / LakeBucket) + 1, 0, lbH - 1);
for (int z = z0; z <= z1; z++) for (int x = x0; x <= x1; x++) (lakeBuckets[z * lbW + x] ??= new List<int>()).Add(L.id);
}
}
static bool QueryStream(double wx, double wz, out float r, out float w, out float lvl, out float s, out Reach st)
{
r = float.MaxValue; w = 0; lvl = 0; s = 0; st = null;
if (streamBuckets == null) return false;
int bx = Mathf.Clamp((int)((wx + WorldSizeX / 2) / StreamBucket) + 1, 0, sbW - 1), bz = Mathf.Clamp((int)((wz + WorldSizeZ / 2) / StreamBucket) + 1, 0, sbH - 1);
var list = streamBuckets[bz * sbW + bx];
if (list == null) return false;
var pt = new Vector2((float)wx, (float)wz);
int bs = -1, bk = 0; float bt = 0;
foreach (var (si, k) in list)
{
var sp = streams[si]; Vector2 a = sp.p[k], ab = sp.p[k + 1] - a;
float t = Mathf.Clamp01(Vector2.Dot(pt - a, ab) / Mathf.Max(ab.sqrMagnitude, 1e-6f));
float d = (a + ab * t - pt).sqrMagnitude;
if (d < r) { r = d; bs = si; bk = k; bt = t; }
}
if (bs < 0) return false;
r = Mathf.Sqrt(r); st = streams[bs];
w = Mathf.Lerp(st.w[bk], st.w[bk + 1], bt); lvl = Mathf.Lerp(st.lvl[bk], st.lvl[bk + 1], bt); s = Mathf.Lerp(st.s[bk], st.s[bk + 1], bt);
return r < StreamReach;
}
[ThreadStatic] static List<(Reach, float, float, float, float)> nearBuf;
// nearest point of every river reach within StreamReach: (reach, distance, width, level, distance along)
static List<(Reach st, float r, float w, float lvl, float s)> NearReaches(double wx, double wz)
{
var o = nearBuf ??= new List<(Reach, float, float, float, float)>(); o.Clear();
if (streamBuckets == null) return o;
int bx = Mathf.Clamp((int)((wx + WorldSizeX / 2) / StreamBucket) + 1, 0, sbW - 1), bz = Mathf.Clamp((int)((wz + WorldSizeZ / 2) / StreamBucket) + 1, 0, sbH - 1);
var list = streamBuckets[bz * sbW + bx];
if (list == null) return o;
var pt = new Vector2((float)wx, (float)wz);
foreach (var (si, k) in list)
{
var sp = streams[si]; Vector2 a = sp.p[k], ab = sp.p[k + 1] - a;
float t = Mathf.Clamp01(Vector2.Dot(pt - a, ab) / Mathf.Max(ab.sqrMagnitude, 1e-6f));
float d = (a + ab * t - pt).magnitude;
if (d >= StreamReach) continue;
int idx = -1; for (int j = 0; j < o.Count; j++) if (o[j].Item1 == sp) { idx = j; break; }
if (idx >= 0 && o[idx].Item2 <= d) continue;
var e = (sp, d, Mathf.Lerp(sp.w[k], sp.w[k + 1], t), Mathf.Lerp(sp.lvl[k], sp.lvl[k + 1], t), Mathf.Lerp(sp.s[k], sp.s[k + 1], t));
if (idx >= 0) o[idx] = e; else o.Add(e);
}
return o;
}
// ---------- carving ----------
/// <summary>Carves lake basins (with a low rim where the shore would otherwise be lower than the water) and
/// river channels into the dry terrain. wet: how much of the riverbed/lakebed texture belongs here.</summary>
static float ApplyWater(float h, double wx, double wz, out float wet)
{
wet = 0; float inLake = 0;
if (lakeBuckets != null)
{
var list = lakeBuckets[Mathf.Clamp((int)((wz + WorldSizeZ / 2) / LakeBucket) + 1, 0, lbH - 1) * lbW + Mathf.Clamp((int)((wx + WorldSizeX / 2) / LakeBucket) + 1, 0, lbW - 1)];
if (list != null)
foreach (int id in list)
{
var L = lakes[id];
if (!L.bounds.Contains(new Vector2((float)wx, (float)wz))) continue;
float m1 = LakeSample(L, L.m1, (float)wx, (float)wz);
float inside = S01(0.42f, 0.58f, m1);
inLake = Mathf.Max(inLake, S01(0.25f, 0.45f, m1)); // rivers don't cut the lake's own shore
if (inside > 0)
{
float bed = L.level - 0.6f - L.depth * S01(0.5f, 0.97f, LakeSample(L, L.m3, (float)wx, (float)wz));
h = Mathf.Lerp(h, Mathf.Min(h, bed), inside);
wet = Mathf.Max(wet, inside);
}
float rim = (1 - inside) * S01(0.06f, 0.3f, LakeSample(L, L.m6, (float)wx, (float)wz));
if (rim > 0) h = Mathf.Max(h, Mathf.Lerp(h, L.level + 1f, rim));
}
}
// every river within reach pulls the ground toward its own channel profile; the pulls are blended (not
// nearest-wins) so two rivers close together never leave a cliff along the line between them
var near = NearReaches(wx, wz);
if (near.Count > 0)
{
float sumW = 0, sumT = 0, maxW = 0, jb = 0, jTop = 0;
foreach (var (st, r, w, lvl, s) in near)
{
float F = Mathf.Max(0.6f * w + 10f, 50f), V = F + Mathf.Max(120f, 3f * w), D = 0.4f + 0.03f * w;
float wgt = (r <= F ? 1f : S01(V, F, r)) * (1 - inLake);
if (wgt <= 0) continue;
float target = lvl - 0.15f - D * (1 - S01(0.1f * w, 0.5f * w, r));
if (lvl <= 0.5f) target = Mathf.Min(h, target); // at sea: only deepen, never raise the seabed
float k = wgt * wgt + 1e-4f; // nearer channels dominate where several overlap
sumW += k; sumT += k * target; maxW = Mathf.Max(maxW, wgt);
if (lvl > 0.3f) wet = Mathf.Max(wet, S01(1.3f * F, 0.7f * F, r) * Mathf.Clamp(w / 120f, 0f, 0.7f) * (1 - inLake));
if (st.ext && st.coastS > 0)
{
// low jetty-like sand banks either side of the river mouth, running out to sea
float js = s - st.coastS, jl = Mathf.Clamp(12f * w, 400f, 2000f);
float along = S01(jl, jl - 150f, js) * S01(-600f, -250f, js);
float b = S01(45f, 20f, Mathf.Abs(r - (0.5f * w + 70f))) * along;
if (b > jb) { jb = b; jTop = 3f - 1.5f * Mathf.Clamp01(js / jl); }
}
}
if (sumW > 0) h = Mathf.Lerp(h, sumT / sumW, maxW);
if (jb > 0) { h = Mathf.Max(h, Mathf.Lerp(h, jTop, jb)); wet *= 1 - jb; }
}
return h;
}
// ---------- water surfaces ----------
class MeshAcc { public List<Vector3> v = new List<Vector3>(); public List<Color> c = new List<Color>(); public List<int> t = new List<int>(); }
static int TileIndex(float x, float z)
{
int tx = Mathf.Clamp(Mathf.FloorToInt((x + WorldSizeX / 2) / TileW), 0, TilesX - 1);
int tz = Mathf.Clamp(Mathf.FloorToInt((z + WorldSizeZ / 2) / TileD), 0, TilesZ - 1);
return tz * TilesX + tx;
}
static Vector3 TileLocal(int tile, Vector2 p, float level) =>
new Vector3(p.x - (-WorldSizeX / 2 + (tile % TilesX) * TileW), level * VerticalExaggeration, p.y - (-WorldSizeZ / 2 + (tile / TilesX) * TileD));
/// <summary>One mesh per tile: flat lake surfaces plus soft-edged ribbons along every river.</summary>
static void BuildAllWaterSurfaces(Transform root)
{
var acc = new Dictionary<int, MeshAcc>();
MeshAcc A(int tile) => acc.TryGetValue(tile, out var m) ? m : acc[tile] = new MeshAcc();
// rivers: 4 vertices across (alpha 0,1,1,0) so the edges fade into the banks
float[] across = { -1.15f, -0.8f, 0.8f, 1.15f }; float[] alpha = { 0, 1, 1, 0 };
foreach (var st in streams)
{
int n = st.p.Count, lastTile = -1, lastK = -1, lastBase = 0;
bool Visible(int k)
{
if (st.ext && st.lvl[k] <= 0.3f) return false;
foreach (var L in lakes) if (L.bounds.Contains(st.p[k]) && LakeSample(L, L.m1, st.p[k].x, st.p[k].y) > 0.55f) return false;
return true;
}
var vis = new bool[n]; for (int k = 0; k < n; k++) vis[k] = Visible(k);
int Cross(MeshAcc m, int tile, int k)
{
Vector2 t = st.p[Mathf.Min(n - 1, k + 1)] - st.p[Mathf.Max(0, k - 1)]; t.Normalize();
var nrm = new Vector2(-t.y, t.x); int b = m.v.Count;
for (int a = 0; a < 4; a++) { m.v.Add(TileLocal(tile, st.p[k] + nrm * (across[a] * 0.5f * st.w[k]), st.lvl[k])); m.c.Add(new Color(1, 1, 1, alpha[a])); }
return b;
}
for (int k = 0; k + 1 < n; k++)
{
if (!vis[k] || !vis[k + 1]) { lastTile = -1; continue; }
int tile = TileIndex(0.5f * (st.p[k].x + st.p[k + 1].x), 0.5f * (st.p[k].y + st.p[k + 1].y));
var m = A(tile);
int b0 = tile == lastTile && lastK == k ? lastBase : Cross(m, tile, k);
int b1 = Cross(m, tile, k + 1);
for (int a = 0; a < 3; a++)
{
m.t.Add(b0 + a); m.t.Add(b1 + a); m.t.Add(b0 + a + 1);
m.t.Add(b0 + a + 1); m.t.Add(b1 + a); m.t.Add(b1 + a + 1);
}
lastTile = tile; lastK = k + 1; lastBase = b1;
}
}
// lakes: a flat grid at the lake level wherever the scaled shape reaches; the terrain draws the shoreline
foreach (var L in lakes)
{
float cell = Mathf.Clamp(L.radius / 30f, 8f, 60f);
int gx = Mathf.CeilToInt(L.bounds.width / cell) + 1, gz = Mathf.CeilToInt(L.bounds.height / cell) + 1;
var m1 = new float[gx * gz];
for (int j = 0; j < gz; j++) for (int i = 0; i < gx; i++)
m1[j * gx + i] = LakeSample(L, L.m1, L.bounds.xMin + i * cell, L.bounds.yMin + j * cell);
var idx = new Dictionary<(int, int, int), int>();
int V(MeshAcc m, int tile, int i, int j)
{
if (idx.TryGetValue((tile, i, j), out int v)) return v;
v = m.v.Count; m.v.Add(TileLocal(tile, new Vector2(L.bounds.xMin + i * cell, L.bounds.yMin + j * cell), L.level)); m.c.Add(Color.white);
idx[(tile, i, j)] = v; return v;
}
for (int j = 0; j + 1 < gz; j++) for (int i = 0; i + 1 < gx; i++)
{
if (Mathf.Max(Mathf.Max(m1[j * gx + i], m1[j * gx + i + 1]), Mathf.Max(m1[(j + 1) * gx + i], m1[(j + 1) * gx + i + 1])) < 0.35f) continue;
int tile = TileIndex(L.bounds.xMin + (i + 0.5f) * cell, L.bounds.yMin + (j + 0.5f) * cell);
var m = A(tile);
int a = V(m, tile, i, j), b = V(m, tile, i + 1, j), c = V(m, tile, i, j + 1), d = V(m, tile, i + 1, j + 1);
m.t.Add(a); m.t.Add(c); m.t.Add(b); m.t.Add(b); m.t.Add(c); m.t.Add(d);
}
}
var old = root.Find("Rivers & Lakes");
if (old) UnityEngine.Object.DestroyImmediate(old.gameObject);
if (AssetDatabase.IsValidFolder(OutputFolder + "/Water"))
foreach (var guid in AssetDatabase.FindAssets("t:Mesh", new[] { OutputFolder + "/Water" }))
AssetDatabase.DeleteAsset(AssetDatabase.GUIDToAssetPath(guid));
EnsureFolder(OutputFolder + "/Water");
var waterRoot = new GameObject("Rivers & Lakes").transform; waterRoot.SetParent(root, false);
var mat = FreshwaterMaterial();
foreach (var kv in acc.OrderBy(k => k.Key))
{
var m = kv.Value; if (m.t.Count == 0) continue;
int tx = kv.Key % TilesX, tz = kv.Key / TilesX;
var mesh = new Mesh { name = $"Water_{tx:D2}_{tz:D2}", indexFormat = UnityEngine.Rendering.IndexFormat.UInt32 };
mesh.SetVertices(m.v); mesh.SetColors(m.c); mesh.SetTriangles(m.t, 0);
mesh.SetNormals(Enumerable.Repeat(Vector3.up, m.v.Count).ToList());
mesh.RecalculateBounds();
AssetDatabase.CreateAsset(mesh, $"{OutputFolder}/Water/Water_{tx:D2}_{tz:D2}.asset");
var go = new GameObject($"Water {tx:D2}-{tz:D2}", typeof(MeshFilter), typeof(MeshRenderer));
go.transform.SetParent(waterRoot, false);
go.transform.position = new Vector3(-WorldSizeX / 2 + tx * TileW, 0, -WorldSizeZ / 2 + tz * TileD);
go.GetComponent<MeshFilter>().sharedMesh = mesh;
var mr = go.GetComponent<MeshRenderer>();
mr.sharedMaterial = mat;
mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
mr.receiveShadows = false;
}
}
// ---------- helpers ----------
// scale a blurred mask so its peak is 1 (small lakes blur to low peaks otherwise)
static float[] Normalise(float[] a) { float mx = a.Max(); if (mx > 1e-6f) for (int i = 0; i < a.Length; i++) a[i] /= mx; return a; }
// Zhang-Suen thinning: painted strokes -> 1 px centre lines
static bool[] Thin(bool[] m, int W, int H)
{
var a = (bool[])m.Clone(); var del = new List<int>(); bool changed = true;
while (changed)
{
changed = false;
for (int pass = 0; pass < 2; pass++)
{
del.Clear();
for (int y = 1; y < H - 1; y++) for (int x = 1; x < W - 1; x++)
{
int i = y * W + x; if (!a[i]) continue;
bool p2 = a[i - W], p3 = a[i - W + 1], p4 = a[i + 1], p5 = a[i + W + 1], p6 = a[i + W], p7 = a[i + W - 1], p8 = a[i - 1], p9 = a[i - W - 1];
int B = (p2 ? 1 : 0) + (p3 ? 1 : 0) + (p4 ? 1 : 0) + (p5 ? 1 : 0) + (p6 ? 1 : 0) + (p7 ? 1 : 0) + (p8 ? 1 : 0) + (p9 ? 1 : 0);
if (B < 2 || B > 6) continue;
bool[] seq = { p2, p3, p4, p5, p6, p7, p8, p9, p2 };
int Ac = 0; for (int k = 0; k < 8; k++) if (!seq[k] && seq[k + 1]) Ac++;
if (Ac != 1) continue;
if (pass == 0 ? (p2 && p4 && p6) || (p4 && p6 && p8) : (p2 && p4 && p8) || (p2 && p6 && p8)) continue;
del.Add(i);
}
foreach (int i in del) a[i] = false;
if (del.Count > 0) changed = true;
}
}
return a;
}
public static string HydrologySummary()
{
Prepare();
var sb = new System.Text.StringBuilder();
var core = streams.Where(s => !s.ext).ToList();
float total = streams.Sum(s => s.s.Count > 0 ? s.s[s.s.Count - 1] : 0) / 1000f;
sb.AppendLine($"{lakes.Count} lakes, {core.Count} river reaches + {streams.Count - core.Count} sea extensions, {total:F0} km of river");
var widths = streams.SelectMany(s => s.w).ToList(); widths.Sort();
if (widths.Count > 0) sb.AppendLine($"width p10 {widths[widths.Count / 10]:F1} p50 {widths[widths.Count / 2]:F1} p90 {widths[widths.Count * 9 / 10]:F1} max {widths[widths.Count - 1]:F1} m");
foreach (var L in lakes.OrderByDescending(l => l.area0))
sb.AppendLine($" lake {L.id} at ({L.c.x / 1000:F1},{L.c.y / 1000:F1}) km: {L.area0:F1} -> {L.area1:F2} km² (~{2 * L.radius:F0} m across), level {L.level:F0} m, depth {L.depth:F0} m");
return sb.ToString();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 88596a4da87208bdb959671668261658
@@ -12,7 +12,7 @@ namespace TravelersQuest.World.Editor
/// The plan-view map on the sheet supplies the outline, rivers/lakes and elevation bands (via the legend colours);
/// the labelled spot heights are pinned; procedural noise adds detail. Terrain only — no foliage, no objects.
/// </summary>
public static class BowlValleyTerrainBuilder
public static partial class BowlValleyTerrainBuilder
{
// ---------- configuration ----------
public const string ReferencePath = "Assets/Bowl Valley Terrain Reference Sheet.png";
@@ -63,8 +63,7 @@ namespace TravelersQuest.World.Editor
public float[] extBase, extDist; public int extW, extH; public float extX0, extZ0; // extDist: km outside the outline
public bool[] insideMask; public float[] watMask; // crop-resolution masks kept for river-mouth detection
public float[] edgeDepth; // smoothed distance inside the outline (crop pixels)
public float[] waterLevel; // river/lake surface level (true m) around core water, crop res
public float[] lakeLevel, lakeW; // per-lake flat level (spread outward) and lake membership
public float[] lakeFloorW, lakeFloorLevel; // painted lake areas -> flat basin floor at the old water level
}
static Fields fields;
@@ -164,6 +163,15 @@ namespace TravelersQuest.World.Editor
return Bilinear(a, CW, CH, x, y);
}
// Same mapping as SampleField but with a cubic B-spline: smooth slopes (no 535 m facets) for flattened floors.
static float SampleFieldSmooth(float[] a, float wx, float wz)
{
var f = fields;
float u = (wx / SizeX + 0.5f - Margin) / (1 - 2 * Margin);
float v = (0.5f - wz / SizeZ - Margin) / (1 - 2 * Margin);
return BSpline(a, CW, CH, f.bx0 + u * (f.bx1 - f.bx0) - 0.5f, f.by0 + v * (f.by1 - f.by0) - 0.5f);
}
static float[] spotOffsets;
public static float Inside(float wx, float wz) => SampleField(fields.inside, wx, wz);
@@ -178,8 +186,7 @@ namespace TravelersQuest.World.Editor
float ins = CutOutsideOutline ? 1 : Mathf.Clamp01(Inside((float)wx, (float)wz) * 1.25f);
float baseH = ins >= 1 ? coreH : Mathf.Lerp(SampleExt(fx, fz), coreH, ins);
float smooth = SampleField(fields.elevSmooth, (float)wx, (float)wz);
float water = SampleField(fields.water, (float)wx, (float)wz);
float waterWide = SampleField(fields.waterWide, (float)wx, (float)wz);
float waterWide = SampleFieldSmooth(fields.waterWide, (float)wx, (float)wz);
// lowland: broad swells + fine undulation
double low = 22 * Noise.Fbm(wx / 30000, wz / 30000, 4) + 6 * Noise.Fbm(wx / 3000, wz / 3000, 3);
@@ -196,23 +203,21 @@ namespace TravelersQuest.World.Editor
// soft ceiling so unlabelled ridges stay below the 3,250 m summit (no clamped plateaus)
if (h > 2800) h = 2800 + 420 * Math.Tanh((h - 2800) / 420);
// valleys: flatten detail near water, then carve channels and lake beds
float valley = Mathf.Clamp01(waterWide * 3f);
float floorH = Mathf.Min(smooth, baseH);
h = Mathf.Lerp((float)h, Mathf.Min((float)h, floorH + 8), valley * 0.75f);
float bed = floorH - 18 - 45 * Mathf.Clamp01(waterWide * 1.6f - 0.25f);
float carve = Mathf.SmoothStep(0, 1, Mathf.InverseLerp(0.12f, 0.55f, water));
h = Mathf.Lerp((float)h, Mathf.Min((float)h, bed), carve);
// lakes: bed carved down from the lake's own (flat) water level, so the whole lake holds water
if (fields.lakeW != null)
// river valleys: flatten detail along the painted rivers (the channels themselves are carved by ApplyWater)
// (full flatten at the river so the channel follows a real valley floor, a little low-level texture kept)
float valley = Mathf.Clamp01(waterWide * 5f);
float coreS = SampleFieldSmooth(fields.elev, fx, fz);
float baseS = ins >= 1 ? coreS : Mathf.Lerp(SampleExt(fx, fz), coreS, ins);
float floorH = Mathf.Min(SampleFieldSmooth(fields.elevSmooth, (float)wx, (float)wz), baseS);
h = Mathf.Lerp((float)h, Mathf.Min((float)h, floorH + 8 + 0.3f * (float)low), valley);
// painted lake areas: a flat basin floor at the water level their banks support; the (much smaller)
// realistic lake is carved into it by ApplyWater, so lake and rivers sit at consistent heights
if (fields.lakeFloorW != null)
{
float lw = SampleField(fields.lakeW, (float)wx, (float)wz);
if (lw > 0.02f)
{
float ll = SampleField(fields.lakeLevel, (float)wx, (float)wz);
float lakeBed = ll - 6 - 30 * Mathf.Clamp01(waterWide * 1.8f - 0.6f);
h = Mathf.Lerp((float)h, Mathf.Min((float)h, lakeBed), Mathf.SmoothStep(0, 1, Mathf.InverseLerp(0.12f, 0.55f, lw)));
}
float lw = SampleFieldSmooth(fields.lakeFloorW, (float)wx, (float)wz);
if (lw > 0.01f)
h = Mathf.Lerp((float)h, Mathf.Min((float)h, SampleFieldSmooth(fields.lakeFloorLevel, (float)wx, (float)wz) + 2f),
Mathf.SmoothStep(0, 1, Mathf.InverseLerp(0.04f, 0.6f, lw)));
}
return (float)h;
}
@@ -229,9 +234,9 @@ namespace TravelersQuest.World.Editor
}
if (!CutOutsideOutline)
{
h = ApplyRiver(h, wx, wz, out _);
float ih = IslandHeight(wx, wz);
if (ih > float.MinValue) h = SmoothMax(h, ih, 6);
if (!waterOff) h = ApplyWater(h, wx, wz, out _);
}
return Mathf.Clamp(h, -SeaDepth + 10, MaxHeight - 20);
}
@@ -250,10 +255,10 @@ namespace TravelersQuest.World.Editor
return ((u - 0.5f) * SizeX, (0.5f - v) * SizeZ);
}
static void SolveSpotOffsets()
static void SolveSpotOffsets(bool reset = true, int iterations = 4)
{
spotOffsets = new float[SpotHeights.Length];
for (int it = 0; it < 4; it++)
if (reset || spotOffsets == null) spotOffsets = new float[SpotHeights.Length];
for (int it = 0; it < iterations; it++)
for (int i = 0; i < SpotHeights.Length; i++)
{
var (sx, sz) = SpotWorld(i);
@@ -270,10 +275,16 @@ namespace TravelersQuest.World.Editor
BuildCoast(fields);
TraceRivers();
PlaceIslands();
BuildWaterLevels();
waterOff = true; SolveSpotOffsets(); // dry terrain first: lake and river levels are fitted to it
BuildHydrology();
SolveSpotOffsets(reset: false, iterations: 2);
}
else
{
rivers = new List<RiverPath>(); islands = new List<Island>(); riverBuckets = null;
lakes = new List<Lake>(); streams = new List<Reach>(); streamBuckets = null; lakeBuckets = null;
SolveSpotOffsets();
}
else { rivers = new List<RiverPath>(); islands = new List<Island>(); riverBuckets = null; }
SolveSpotOffsets();
}
// ---------- river extensions: from where a river/lake meets the original outline, down to the sea ----------
@@ -281,10 +292,6 @@ namespace TravelersQuest.World.Editor
{
public List<Vector2> p = new List<Vector2>(); public List<float> s = new List<float>(), bed = new List<float>();
public float coastS = -1;
// flared estuary: the channel opens up only where it has reached sea level near the coast
public float HalfWidth(float sAt, float bedAt) =>
650 + 0.003f * sAt + 1900 * Mathf.Pow(Mathf.SmoothStep(0, 1, Mathf.InverseLerp(30, -4, bedAt))
* Mathf.SmoothStep(0, 1, Mathf.InverseLerp(coastS - 8000, coastS + 300, sAt)), 1.3f);
}
static List<RiverPath> rivers = new List<RiverPath>();
static readonly List<Vector2> failedStarts = new List<Vector2>();
@@ -493,145 +500,8 @@ namespace TravelersQuest.World.Editor
return path != null && r < RiverReach;
}
// river valley + channel, flared estuary, and two jetty-like banks running out to sea
static float ApplyRiver(float h, double wx, double wz, out float wet)
{
wet = 0;
if (!QueryRiver(wx, wz, out float r, out float sAt, out float bed, out var rp)) return h;
float hw = rp.HalfWidth(sAt, bed);
float fadeIn = Mathf.SmoothStep(0, 1, sAt / 1500f); // blend into the existing river inside the outline
float nearMouth = Mathf.SmoothStep(0, 1, Mathf.InverseLerp(-6000, -2500, sAt - rp.coastS)); // keep land either side of the mouth
float bank = Mathf.SmoothStep(0, 1, Mathf.InverseLerp(hw * 3.2f, hw, r)) * fadeIn * (1 - nearMouth);
h = Mathf.Lerp(h, Mathf.Min(h, bed + 6 + (r - hw) * 0.015f), bank * 0.7f);
float c = Mathf.SmoothStep(0, 1, Mathf.InverseLerp(hw, hw * 0.55f, r)) * fadeIn;
h = Mathf.Lerp(h, Mathf.Min(h, bed), c);
wet = c;
float js = sAt - rp.coastS;
if (js > -2500 && js < JettyLength)
{
float armR = hw + 420;
float along = Mathf.SmoothStep(0, 1, Mathf.InverseLerp(JettyLength, JettyLength - 600, js)) * Mathf.SmoothStep(0, 1, Mathf.InverseLerp(-2500, -1200, js));
float jb = Mathf.SmoothStep(0, 1, Mathf.InverseLerp(340, 150, Mathf.Abs(r - armR))) * along;
if (jb > 0)
{
float top = 6f - 3f * Mathf.Clamp01(js / JettyLength);
h = Mathf.Max(h, Mathf.Lerp(h, top, jb));
wet *= 1 - jb;
}
}
return h;
}
// ---------- river & lake surfaces ----------
// Water level from the real banks: for every lake, the low part (10th percentile) of the ground just outside its
// shore; for rivers, the lowest nearby bank, smoothed along the channel. Both sit 2 m under that bank height.
static void BuildWaterLevels()
{
var f = fields; int N = CW * CH;
var wetM = new bool[N]; for (int i = 0; i < N; i++) wetM[i] = f.watMask[i] > 0;
var near = Dilate(wetM, 4);
var bank = new float[N];
Parallel.For(0, CH, y =>
{
for (int x = 0; x < CW; x++)
{
int i = y * CW + x;
if (near[i] && !wetM[i]) { var w = CropToWorld(x, y); bank[i] = RawHeight(w.x, w.y); }
}
});
var level = new float[N]; var has = new bool[N];
// lakes
var lake = new bool[N];
for (int i = 0; i < N; i++) lake[i] = wetM[i] && f.waterWide[i] > 0.55f; // narrow channels between lakes stay rivers
var lab = new int[N]; var q = new Queue<int>(); var members = new List<int>(); int nl = 0;
for (int st = 0; st < N; st++)
{
if (!lake[st] || lab[st] != 0) continue;
nl++; lab[st] = nl; q.Enqueue(st); members.Clear();
var shore = new List<float>(); var seen = new HashSet<int>();
while (q.Count > 0)
{
int i = q.Dequeue(); members.Add(i); int x = i % CW, y = i / CW;
for (int dy = -3; dy <= 3; dy++) for (int dx = -3; dx <= 3; dx++)
{
int xx = x + dx, yy = y + dy; if (xx < 0 || yy < 0 || xx >= CW || yy >= CH) continue;
int j = yy * CW + xx;
if (!wetM[j] && near[j] && seen.Add(j)) shore.Add(bank[j]);
}
void T(int j) { if (lake[j] && lab[j] == 0) { lab[j] = nl; q.Enqueue(j); } }
if (x > 0) T(i - 1); if (x < CW - 1) T(i + 1); if (y > 0) T(i - CW); if (y < CH - 1) T(i + CW);
}
if (shore.Count == 0) continue;
shore.Sort();
float lv = shore[(int)(shore.Count * 0.1f)] - 2;
// never below most of the lake's own bed (the surface mesh is limited to the lake's footprint anyway)
lv = Mathf.Min(lv, shore[shore.Count / 2] - 1); // never above the typical shoreline
foreach (var i in members) { level[i] = lv; has[i] = true; }
}
// rivers
var rv = new float[N]; var rw = new float[N]; var rmin = new float[N];
for (int y = 0; y < CH; y++) for (int x = 0; x < CW; x++)
{
int i = y * CW + x; if (!wetM[i] || lake[i]) continue;
float mn = float.MaxValue;
for (int dy = -4; dy <= 4; dy++) for (int dx = -4; dx <= 4; dx++)
{
int xx = x + dx, yy = y + dy; if (xx < 0 || yy < 0 || xx >= CW || yy >= CH) continue;
int j = yy * CW + xx; if (!wetM[j] && near[j]) mn = Mathf.Min(mn, bank[j]);
}
if (mn == float.MaxValue) continue;
var wp = CropToWorld(x, y); float bedH = RawHeight(wp.x, wp.y);
float lv = Mathf.Max(mn - 2, bedH + 5); // perched channels still hold water
rmin[i] = Mathf.Max(lv, bedH + 3); rv[i] = lv; rw[i] = 1;
}
var rvB = Blur(rv, CW, CH, 2f); var rwB = Blur(rw, CW, CH, 2f);
for (int i = 0; i < N; i++) if (rw[i] > 0 && rwB[i] > 1e-3f) { level[i] = Mathf.Max(rvB[i] / rwB[i], rmin[i]); has[i] = true; }
// spread levels a few pixels outward so the surface mesh can tuck under the banks
for (int pass = 0; pass < 8; pass++)
{
var nlv = (float[])level.Clone(); var nh = (bool[])has.Clone();
for (int y = 1; y < CH - 1; y++) for (int x = 1; x < CW - 1; x++)
{
int i = y * CW + x; if (has[i]) continue;
float acc = 0; int c = 0;
for (int dy = -1; dy <= 1; dy++) for (int dx = -1; dx <= 1; dx++) { int j = i + dy * CW + dx; if (has[j]) { acc += level[j]; c++; } }
if (c > 0) { nlv[i] = acc / c; nh[i] = true; }
}
level = nlv; has = nh;
}
for (int i = 0; i < N; i++) if (!has[i]) level[i] = -10000;
f.waterLevel = level;
// lake level field (spread a few px past the shore) + soft membership, used to carve the lakebeds
var ll = new float[N]; var lh = new bool[N]; var lm = new float[N];
for (int i = 0; i < N; i++) if (lake[i]) { ll[i] = level[i]; lh[i] = true; lm[i] = 1; }
for (int pass = 0; pass < 6; pass++)
{
var nll = (float[])ll.Clone(); var nlh = (bool[])lh.Clone();
for (int y = 1; y < CH - 1; y++) for (int x = 1; x < CW - 1; x++)
{
int i = y * CW + x; if (lh[i]) continue;
float acc = 0; int c = 0;
for (int dy = -1; dy <= 1; dy++) for (int dx = -1; dx <= 1; dx++) { int j = i + dy * CW + dx; if (lh[j]) { acc += ll[j]; c++; } }
if (c > 0) { nll[i] = acc / c; nlh[i] = true; }
}
ll = nll; lh = nlh;
}
f.lakeLevel = ll; f.lakeW = Blur(lm, CW, CH, 1.0f);
}
// extended river channels: surface 3 m above the bed; c = how strongly this point is in the channel
static void ExtWater(double wx, double wz, out float level, out float c)
{
level = -10000; c = 0;
if (!QueryRiver(wx, wz, out float r, out float sAt, out float bed, out var rp)) return;
float hw = rp.HalfWidth(sAt, bed);
float fadeIn = Mathf.SmoothStep(0, 1, sAt / 1500f);
c = Mathf.SmoothStep(0, 1, Mathf.InverseLerp(hw * 1.15f, hw * 0.6f, r)) * fadeIn;
level = bed + 3;
}
static Material WaterMaterial(string path, Color shallow, Color deep, float absorption, float waveLength, float foamDepth, float fadeDist)
// ---------- water materials ----------
static Material WaterMaterial(string path, Color shallow, Color deep, float absorption, float waveLength, float foamDepth, float fadeDist, bool vertexAlpha = false)
{
var mat = AssetDatabase.LoadAssetAtPath<Material>(path);
var shader = Shader.Find("TravelersQuest/BowlValleyWater");
@@ -640,88 +510,15 @@ namespace TravelersQuest.World.Editor
mat.SetColor("_ShallowColor", shallow); mat.SetColor("_DeepColor", deep);
mat.SetFloat("_Absorption", absorption); mat.SetFloat("_WaveLength", waveLength);
mat.SetFloat("_FoamDepth", foamDepth); mat.SetFloat("_NormalFadeDistance", fadeDist);
mat.SetFloat("_UseVertexAlpha", vertexAlpha ? 1 : 0);
EditorUtility.SetDirty(mat);
return mat;
}
static Material FreshwaterMaterial() => WaterMaterial(OutputFolder + "/Freshwater.mat",
new Color(0.16f, 0.44f, 0.40f), new Color(0.03f, 0.15f, 0.17f), 0.035f, 9f, 4f, 4000f);
new Color(0.16f, 0.44f, 0.40f), new Color(0.03f, 0.15f, 0.17f), 0.035f, 9f, 4f, 4000f, vertexAlpha: true);
static Material OceanMaterial() => WaterMaterial(OutputFolder + "/Ocean.mat",
new Color(0.10f, 0.50f, 0.56f), new Color(0.02f, 0.09f, 0.22f), 0.012f, 30f, 8f, 9000f);
const float RiverMaxDepth = 4f; // true metres of river water above the local ground
// Surface mesh over the rivers and lakes of one tile (every 2nd heightmap sample, ~122 m).
static Mesh BuildWaterMesh(float[] hm, int res, double ox, double oz, float tileW, float tileD)
{
const int step = 2; int g = (res - 1) / step + 1;
var lvl = new float[g * g]; var wet = new bool[g * g]; var terr = new float[g * g];
Parallel.For(0, g, j =>
{
for (int i = 0; i < g; i++)
{
int k = j * g + i;
double wx = ox + (double)i / (g - 1) * tileW, wz = oz + (double)j / (g - 1) * tileD;
terr[k] = hm[(j * step) * res + i * step];
float coreW = SampleField(fields.water, (float)wx, (float)wz);
float coreL = SampleField(fields.waterLevel, (float)wx, (float)wz);
ExtWater(wx, wz, out float extL, out float extC);
lvl[k] = extC > 0.05f ? (coreL > -5000 && coreW > 0.05f ? Mathf.Min(extL, coreL) : extL) : coreL;
wet[k] = (coreW > 0.2f && coreL > -5000) || extC > 0.3f;
if (lvl[k] > -5000)
{
// River levels are smoothed over ~1 km, so on steep reaches they overshoot the ground below.
// Keep river water at most RiverMaxDepth above the terrain; lakes stay flat at their level.
// On steep ground (as seen at the exaggerated scale) the river slips under the terrain,
// so cascades read as dry gullies instead of water draped over a cliff.
int hi = Mathf.Clamp(i * step, 1, res - 2), hj = Mathf.Clamp(j * step, 1, res - 2);
float cell = tileW / (res - 1);
float gx = (hm[hj * res + hi + 1] - hm[hj * res + hi - 1]) / (2 * cell);
float gz = (hm[(hj + 1) * res + hi] - hm[(hj - 1) * res + hi]) / (2 * cell);
float steep = Mathf.SmoothStep(0, 1, Mathf.InverseLerp(0.35f, 0.7f, Mathf.Sqrt(gx * gx + gz * gz) * VerticalExaggeration));
float depth = Mathf.Lerp(RiverMaxDepth, -1.5f, steep);
// Near a lake the surface never rises above the lake's own flat level unless the ground does.
float ceiling = terr[k] + depth;
if (SampleField(fields.lakeW, (float)wx, (float)wz) > 0.01f)
ceiling = Mathf.Max(ceiling, SampleField(fields.lakeLevel, (float)wx, (float)wz));
lvl[k] = Mathf.Min(lvl[k], ceiling);
// Vertices outside the wet area only exist to close a quad: tuck them under the ground so the
// mesh edge never hangs in the air.
if (!wet[k]) lvl[k] = Mathf.Min(lvl[k], terr[k] - 1);
}
}
});
var verts = new List<Vector3>(); var tris = new List<int>(); var map = new Dictionary<int, int>();
int V(int i, int j)
{
int k = j * g + i;
if (!map.TryGetValue(k, out int idx))
{
idx = verts.Count; map[k] = idx;
verts.Add(new Vector3((float)i / (g - 1) * tileW, lvl[k] * VerticalExaggeration, (float)j / (g - 1) * tileD));
}
return idx;
}
for (int j = 0; j < g - 1; j++)
for (int i = 0; i < g - 1; i++)
{
int a = j * g + i, b = a + 1, c = a + g, d = c + 1;
if (!(wet[a] || wet[b] || wet[c] || wet[d])) continue;
float lmax = Mathf.Max(Mathf.Max(lvl[a], lvl[b]), Mathf.Max(lvl[c], lvl[d]));
float lmin = Mathf.Min(Mathf.Min(lvl[a], lvl[b]), Mathf.Min(lvl[c], lvl[d]));
float tmin = Mathf.Min(Mathf.Min(terr[a], terr[b]), Mathf.Min(terr[c], terr[d]));
if (lmin < -5000 || lmax < 0.5f || lmax < tmin + 0.3f) continue; // undefined, at/below sea level, or no water showing
int va = V(i, j), vb = V(i + 1, j), vc = V(i, j + 1), vd = V(i + 1, j + 1);
tris.Add(va); tris.Add(vc); tris.Add(vb);
tris.Add(vb); tris.Add(vc); tris.Add(vd);
}
if (tris.Count == 0) return null;
var mesh = new Mesh { indexFormat = UnityEngine.Rendering.IndexFormat.UInt32 };
mesh.SetVertices(verts); mesh.SetTriangles(tris, 0);
var normals = new Vector3[verts.Count]; for (int n = 0; n < normals.Length; n++) normals[n] = Vector3.up;
mesh.normals = normals; mesh.RecalculateBounds();
return mesh;
}
// ---------- bay islands ----------
public struct Island { public float cx, cz, rx, rz, rot, top; public bool settlement; public int seed; }
static List<Island> islands = new List<Island>();
@@ -1093,7 +890,6 @@ namespace TravelersQuest.World.Editor
float gz = VerticalExaggeration * (hm[(j + 1) * res + i] - hm[(j - 1) * res + i]) / (2 * cellZ);
float slopeDeg = Mathf.Atan(Mathf.Sqrt(gx * gx + gz * gz)) * Mathf.Rad2Deg;
double wx = ox + u / n * tileW, wz = oz + v / n * tileD;
float water = SampleField(fields.water, (float)wx, (float)wz);
float jitter = (float)(Noise.Fbm(wx / 6000 + 3.3, wz / 6000 - 8.8, 4) * 70);
Array.Clear(wts, 0, L);
BandWeights(h + jitter, wts);
@@ -1111,12 +907,10 @@ namespace TravelersQuest.World.Editor
for (int k = 0; k < L; k++) wts[k] *= 1 - beach;
wts[3] += beach;
}
float wet = Mathf.SmoothStep(0, 1, Mathf.InverseLerp(0.18f, 0.5f, water));
if (CutOutsideOutline && h <= 1f) wet = 0;
float wet = 0;
if (!CutOutsideOutline)
{
ApplyRiver(h, wx, wz, out float riverWet);
wet = Mathf.Max(wet, riverWet);
ApplyWater(h, wx, wz, out wet); // riverbed / lakebed mud under the water
if (h < 0)
{
// seafloor under the ocean surface: sand in the shallows, dark silt deeper
@@ -1162,34 +956,13 @@ namespace TravelersQuest.World.Editor
if (!anySolid) go.SetActive(false); // tile lies wholly outside the outline
sb.Append(go.name).Append(anySolid ? " " : "(empty) ");
if (!CutOutsideOutline) AddWaterSurface(root.transform, hm, res, tx, tz);
}
UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(root.scene);
AssetDatabase.SaveAssets();
return sb.ToString();
}
static void AddWaterSurface(Transform root, float[] hm, int res, int tx, int tz)
{
double ox = -WorldSizeX / 2 + tx * TileW, oz = -WorldSizeZ / 2 + tz * TileD;
var wm = BuildWaterMesh(hm, res, ox, oz, TileW, TileD);
if (wm == null) return;
EnsureFolder(OutputFolder + "/Water");
string mp = $"{OutputFolder}/Water/Water_{tx:D2}_{tz:D2}.asset";
AssetDatabase.CreateAsset(wm, mp);
var waterRoot = root.Find("Rivers & Lakes") ?? new GameObject("Rivers & Lakes").transform;
waterRoot.SetParent(root, false);
var w = new GameObject($"Water {tx:D2}-{tz:D2}", typeof(MeshFilter), typeof(MeshRenderer));
w.transform.SetParent(waterRoot, false);
w.transform.position = new Vector3((float)ox, 0, (float)oz);
w.GetComponent<MeshFilter>().sharedMesh = wm;
var mr = w.GetComponent<MeshRenderer>();
mr.sharedMaterial = FreshwaterMaterial();
mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
mr.receiveShadows = false;
}
// Regenerates only the river/lake surface meshes from the terrain tiles already in the scene (no terrain rebuild).
// Regenerates only the river/lake surface meshes (no terrain rebuild): use after changing water rendering.
[MenuItem("Travelers Quest/Rebuild Bowl Valley Water Surfaces")]
public static void RebuildWaterSurfacesFromMenu() => UnityEngine.Debug.Log(RebuildWaterSurfaces());
@@ -1198,27 +971,11 @@ namespace TravelersQuest.World.Editor
if (fields == null) Prepare();
var root = GameObject.Find(RootName);
if (!root) return "No terrain root in the open scene.";
var old = root.transform.Find("Rivers & Lakes");
if (old) UnityEngine.Object.DestroyImmediate(old.gameObject);
foreach (var guid in AssetDatabase.FindAssets("t:Mesh", new[] { OutputFolder + "/Water" }))
AssetDatabase.DeleteAsset(AssetDatabase.GUIDToAssetPath(guid));
float rangeY = MaxHeight + SeaDepth, baseY = -SeaDepth;
int count = 0;
foreach (var t in root.GetComponentsInChildren<Terrain>(true))
{
var p = t.transform.position;
int tx = Mathf.RoundToInt((p.x + WorldSizeX / 2) / TileW), tz = Mathf.RoundToInt((p.z + WorldSizeZ / 2) / TileD);
var td = t.terrainData; int res = td.heightmapResolution;
var h = td.GetHeights(0, 0, res, res);
var hm = new float[res * res];
for (int j = 0; j < res; j++) for (int i = 0; i < res; i++) hm[j * res + i] = baseY + h[j, i] * rangeY;
AddWaterSurface(root.transform, hm, res, tx, tz);
count++;
}
BuildAllWaterSurfaces(root.transform);
UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(root.scene);
UnityEditor.SceneManagement.EditorSceneManager.SaveScene(root.scene);
AssetDatabase.SaveAssets();
return $"Rebuilt water surfaces over {count} tiles.";
return $"Rebuilt water surfaces for {lakes.Count} lakes and {streams.Count} river reaches.";
}
// elevation band membership (metres) with soft transitions
@@ -1248,6 +1005,7 @@ namespace TravelersQuest.World.Editor
if (sun && sun.type == LightType.Directional) sun.transform.rotation = Quaternion.Euler(38, 135, 0);
if (CreateOcean && !CutOutsideOutline) CreateOceanPlane(root.transform);
if (!CutOutsideOutline) BuildAllWaterSurfaces(root.transform);
// Camera framing for the whole continent (the overview camera, never the player's camera).
var overview = GameObject.Find(OverviewCameraName);
@@ -1330,13 +1088,15 @@ namespace TravelersQuest.World.Editor
}
// ---------- debug ----------
// debug: water numbers at a reference-map pixel (crop coordinates)
public static string ProbeWater(int px, int py)
// debug: the river or lake (if any) at a world point
public static string ProbeWater(float wx, float wz)
{
if (fields == null) Prepare();
var w = CropToWorld(px, py); int i = py * CW + px;
return $"px({px},{py}) world({w.x / 1000:F1},{w.y / 1000:F1})km wat={fields.watMask[i]} waterWide={fields.waterWide[i]:F2} " +
$"raw={RawHeight(w.x, w.y):F1} h={Height(w.x, w.y):F1} level={fields.waterLevel[i]:F1} field={SampleField(fields.water, w.x, w.y):F2}";
waterOff = true; float dry = Height(wx, wz); waterOff = false;
string r = QueryStream(wx, wz, out float d, out float w, out float lvl, out _, out var st)
? $"river {(st.ext ? "(to sea) " : "")}{d:F0} m from centre, {w:F1} m wide, level {lvl:F1} m" : "no river nearby";
foreach (var L in lakes) if (L.bounds.Contains(new Vector2(wx, wz))) r += $"; lake {L.id} m1={LakeSample(L, L.m1, wx, wz):F2} level {L.level:F1} m";
return $"({wx / 1000:F2},{wz / 1000:F2}) km dry {dry:F1} m, final {Height(wx, wz):F1} m: {r}";
}
public static string RiverSummary()
@@ -19,6 +19,7 @@ Shader "TravelersQuest/BowlValleyWater"
_NormalFadeDistance ("Wave Fade Distance", Float) = 6000
_Smoothness ("Smoothness", Range(0, 1)) = 0.94
_SunGlint ("Sun Glint", Float) = 3
[Toggle] _UseVertexAlpha ("Fade By Vertex Alpha (river edges)", Float) = 0
}
SubShader
@@ -48,16 +49,17 @@ Shader "TravelersQuest/BowlValleyWater"
half4 _ShallowColor, _DeepColor, _FoamColor;
float _Absorption, _RefractionTint, _Refraction, _FoamDepth, _EdgeSoftness;
float _WaveLength, _WaveSpeed, _WaveDirection, _NormalStrength, _NormalFadeDistance;
half _Smoothness, _SunGlint;
half _Smoothness, _SunGlint, _UseVertexAlpha;
CBUFFER_END
struct Attributes { float4 positionOS : POSITION; };
struct Attributes { float4 positionOS : POSITION; half4 color : COLOR; };
struct Varyings
{
float4 positionCS : SV_POSITION;
float3 positionWS : TEXCOORD0;
float4 screenPos : TEXCOORD1;
half fog : TEXCOORD2;
half edge : TEXCOORD3;
};
Varyings vert(Attributes v)
@@ -67,6 +69,7 @@ Shader "TravelersQuest/BowlValleyWater"
o.positionCS = TransformWorldToHClip(o.positionWS);
o.screenPos = ComputeScreenPos(o.positionCS);
o.fog = ComputeFogFactor(o.positionCS.z);
o.edge = lerp(1, v.color.a, _UseVertexAlpha);
return o;
}
@@ -139,7 +142,7 @@ Shader "TravelersQuest/BowlValleyWater"
float foamNoise = saturate(0.5 + 2.5 * (s.x + s.y) + 0.5 * sin(dot(i.positionWS.xz, float2(0.11, 0.07)) + _Time.y));
color = lerp(color, _FoamColor.rgb * lit, foamBand * foamBand * foamNoise * 0.85);
half alpha = saturate(thickness / max(_EdgeSoftness, 1e-3));
half alpha = saturate(thickness / max(_EdgeSoftness, 1e-3)) * saturate(i.edge);
color = MixFog(color, i.fog);
return half4(color, alpha);
}
@@ -12,7 +12,8 @@ Material:
m_Parent: {fileID: 0}
m_ModifiedSerializedProperties: 0
m_ValidKeywords: []
m_InvalidKeywords: []
m_InvalidKeywords:
- _USEVERTEXALPHA_ON
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
@@ -34,6 +35,7 @@ Material:
- _RefractionTint: 0.8
- _Smoothness: 0.94
- _SunGlint: 3
- _UseVertexAlpha: 1
- _WaveDirection: 35
- _WaveLength: 9
- _WaveSpeed: 1
@@ -119,6 +119,7 @@ Material:
- _SrcBlendAlpha: 1
- _SunGlint: 3
- _Surface: 0
- _UseVertexAlpha: 0
- _WaveDirection: 35
- _WaveLength: 30
- _WaveSpeed: 1

Some files were not shown because too many files have changed in this diff Show More