bpHigh commited on
Commit
b25585e
·
verified ·
1 Parent(s): 79c4cf2

Realistic 3D replay: imagery, modelled dams, five cameras; live-mode results

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ openenv/flood_openenv/web/twin/basin_imagery.jpg filter=lfs diff=lfs merge=lfs -text
core/flood_core/replay.py CHANGED
@@ -133,6 +133,7 @@ def replay(task: dict, plan_id: str, runs_dir: Path | None = None) -> dict:
133
  "category": cat, "flood_cost": round(res.flood_by_point[p["id"]], 1)}
134
  ref = task.get("reference", {})
135
  return {"task_id": task["task_id"], "plan": plan_id, "tier": task["tier"], "steps": H, "tail": T,
 
136
  "times": task["times"][:H + T + 1], "lags_h": task["lags_h"],
137
  "feasible": res.feasible, "violations": res.violations[:12],
138
  "cost": round(res.cost, 1), "flood_cost": round(res.flood_cost, 1), "pool_cost": round(res.pool_cost, 1),
 
133
  "category": cat, "flood_cost": round(res.flood_by_point[p["id"]], 1)}
134
  ref = task.get("reference", {})
135
  return {"task_id": task["task_id"], "plan": plan_id, "tier": task["tier"], "steps": H, "tail": T,
136
+ "start_utc": task["start_utc"], "step_hours": task["step_hours"],
137
  "times": task["times"][:H + T + 1], "lags_h": task["lags_h"],
138
  "feasible": res.feasible, "violations": res.violations[:12],
139
  "cost": round(res.cost, 1), "flood_cost": round(res.flood_cost, 1), "pool_cost": round(res.pool_cost, 1),
data/cumberland/SOURCE.md CHANGED
@@ -31,7 +31,7 @@ interpolation (`basin.json`, `gap_hours_filled`).
31
 
32
  | river forecasts NWS issued, Jan-Jun 2025 (live mode) | Ohio River Forecast Center products RVFCMU and RVFCML, from the Iowa Environmental Mesonet's NWS text archive (`mesonet.agron.iastate.edu/cgi-bin/afos/retrieve.py`) | SHEF `.ER ... HGIFF` stage forecasts, 6-hourly to about 5 days, at BRKK2 (30 issues), CLAT1 (219), NAST1 (228); turned into flow through the NWS ratings; `forecasts.csv.gz` (`tools/curate_forecasts.py`) |
33
 
34
- | the 3D replay's map: terrain, rivers, reservoirs | USGS 3D Elevation Program (3DEPElevation ImageServer); USGS National Hydrography Dataset (NHDPlus small-scale flowlines and waterbodies); dam locations from CWMS, gauge locations from NWPS | `openenv/flood_openenv/web/twin/basin.json.gz` (`tools/twin/build_basin.py`); display only, never in a cost |
35
 
36
  ## Derived
37
 
 
31
 
32
  | river forecasts NWS issued, Jan-Jun 2025 (live mode) | Ohio River Forecast Center products RVFCMU and RVFCML, from the Iowa Environmental Mesonet's NWS text archive (`mesonet.agron.iastate.edu/cgi-bin/afos/retrieve.py`) | SHEF `.ER ... HGIFF` stage forecasts, 6-hourly to about 5 days, at BRKK2 (30 issues), CLAT1 (219), NAST1 (228); turned into flow through the NWS ratings; `forecasts.csv.gz` (`tools/curate_forecasts.py`) |
33
 
34
+ | the 3D replay's map: imagery, terrain, rivers, reservoirs | USGS The National Map orthoimagery (USGSImageryOnly, USDA NAIP; the Kentucky side colour-matched to Tennessee's at the state-line seam); USGS 3D Elevation Program (3DEPElevation ImageServer); USGS National Hydrography Dataset (NHDPlus small-scale flowlines and waterbodies); dam locations from CWMS, gauge locations from NWPS | `openenv/flood_openenv/web/twin/basin.json.gz` (`tools/twin/build_basin.py`); display only, never in a cost |
35
 
36
  ## Derived
37
 
openenv/flood_openenv/gradio_ui.py CHANGED
@@ -45,15 +45,21 @@ def results_md(runs_dir: Path) -> str:
45
  for spec in sorted({e["spec"] for e in eps}):
46
  es = [e for e in eps if e["spec"] == spec]
47
  mode = es[0].get("mode", "plan")
 
 
48
  rows.append((mode, model_label(spec), len(es), statistics.fmean(e["reward"] for e in es),
49
  sum(bool(e.get("solved")) for e in es), d.get("run", f.parent.name)))
50
- lines = ["| mode | model | tasks | mean reward | solved | run |", "|---|---|---:|---:|---:|---|"]
51
- for m, name, n, r, s, run in sorted(rows, key=lambda x: (x[0] != "live", -x[3])):
52
- lines.append(f"| {m} | {name} | {n} | **{r:.3f}** | {s} | `{run}` |")
53
- return ("### Every committed run\n\nLive mode: decide block by block on forecast scenarios that carry real 2025 NWS "
54
- "forecast errors, graded per decision against the scenario-optimal decision. Plan mode: the whole storm "
55
- "in hindsight, graded against the exact LP optimum. A lazy operator (hold every release) scores 0.215 "
56
- "in live mode; a perfect solver planning on the mean forecast 0.552.\n\n" + "\n".join(lines))
 
 
 
 
57
 
58
 
59
  def build_ui(*_args, **_kwargs) -> gr.Blocks:
 
45
  for spec in sorted({e["spec"] for e in eps}):
46
  es = [e for e in eps if e["spec"] == spec]
47
  mode = es[0].get("mode", "plan")
48
+ if mode != "live": # the Space serves live mode; plan-mode runs stay in the dataset
49
+ continue
50
  rows.append((mode, model_label(spec), len(es), statistics.fmean(e["reward"] for e in es),
51
  sum(bool(e.get("solved")) for e in es), d.get("run", f.parent.name)))
52
+ base = [("Scenario-optimal decisions (the reference)", 24, 1.0, 24), ("A perfect solver planning on the mean forecast",
53
+ 24, 0.552, 0),
54
+ ("A perfect solver planning on one scenario", 24, 0.444, 0), ("Hold every release (the lazy operator)", 24,
55
+ 0.215, 0)]
56
+ lines = ["| model or policy | tasks | mean reward | solved | run |", "|---|---:|---:|---:|---|"]
57
+ for m, name, n, r, s, run in sorted(rows, key=lambda x: -x[3]):
58
+ lines.append(f"| {name} | {n} | **{r:.3f}** | {s} | `{run}` |")
59
+ lines += [f"| {name} | {n} | {r:.3f} | {s} | no model (eval/live_baselines.py) |" for name, n, r, s in base]
60
+ return ("### Live mode results\n\nThe agent commits each day's releases on 8 forecast scenarios that carry the errors "
61
+ "of real 2025 NWS river forecasts; each decision is graded against the scenario-optimal decision (a "
62
+ "two-stage stochastic LP), so luck does not count.\n\n" + "\n".join(lines))
63
 
64
 
65
  def build_ui(*_args, **_kwargs) -> gr.Blocks:
openenv/flood_openenv/web/twin/app.js CHANGED
@@ -6,8 +6,9 @@ import { CSS2DRenderer, CSS2DObject } from "three/addons/renderers/CSS2DRenderer
6
  import { Line2 } from "three/addons/lines/Line2.js";
7
  import { LineGeometry } from "three/addons/lines/LineGeometry.js";
8
  import { LineMaterial } from "three/addons/lines/LineMaterial.js";
 
9
 
10
- const VEX = 14; // vertical exaggeration
11
  const CAT_COL = ["#3f9be8", "#f2c94c", "#f2994a", "#eb5757", "#b44fd6"];
12
  const CAT_NAME = ["below action", "action", "minor flood", "moderate flood", "major flood"];
13
  const DAM_ORDER = ["WC", "DH", "CH", "JPP"];
@@ -38,6 +39,8 @@ const renderer = new THREE.WebGLRenderer({ antialias: true });
38
  renderer.setPixelRatio(Math.min(2, window.devicePixelRatio));
39
  renderer.setSize(innerWidth, innerHeight);
40
  renderer.outputColorSpace = THREE.SRGBColorSpace;
 
 
41
  stage.appendChild(renderer.domElement);
42
  const labels = new CSS2DRenderer();
43
  labels.setSize(innerWidth, innerHeight);
@@ -47,32 +50,92 @@ labels.domElement.style.pointerEvents = "none";
47
  stage.appendChild(labels.domElement);
48
 
49
  const scene = new THREE.Scene();
50
- scene.background = new THREE.Color("#0b0d0f");
51
- scene.fog = new THREE.Fog("#0b0d0f", 260, 520);
52
  const camera = new THREE.PerspectiveCamera(42, innerWidth / innerHeight, 0.1, 2000);
53
  const controls = new OrbitControls(camera, renderer.domElement);
54
  controls.enableDamping = true;
55
  controls.maxPolarAngle = Math.PI * 0.47;
56
- scene.add(new THREE.HemisphereLight("#cfe3ff", "#3a3020", 1.6));
57
- const sun = new THREE.DirectionalLight("#fff4e0", 2.4);
 
58
  sun.position.set(-80, 160, 60);
59
- scene.add(sun);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  let H; // terrain height sampler (km, exaggerated)
62
 
63
  function buildTerrain(t) {
64
  const raw = Uint8Array.from(atob(t.data), (c) => c.charCodeAt(0));
65
  const dm = new Uint16Array(raw.buffer);
 
 
66
  const { w, h } = t;
67
  const elev = (i, j) => (t.min_m + dm[Math.min(h - 1, Math.max(0, j)) * w + Math.min(w - 1, Math.max(0, i))] * t.scale_m);
68
- H = (x, y) => { // x km east, y km north of the SW corner
 
 
 
 
 
 
 
 
 
69
  const fi = (x / t.width_km) * (w - 1), fj = (1 - y / t.height_km) * (h - 1);
70
  const i = Math.floor(fi), j = Math.floor(fj), a = fi - i, b = fj - j;
71
  const e = elev(i, j) * (1 - a) * (1 - b) + elev(i + 1, j) * a * (1 - b) + elev(i, j + 1) * (1 - a) * b
72
  + elev(i + 1, j + 1) * a * b;
73
  return (e / 1000) * VEX;
74
  };
75
- const geo = new THREE.PlaneGeometry(t.width_km, t.height_km, w - 1, h - 1);
 
 
76
  geo.rotateX(-Math.PI / 2);
77
  geo.translate(t.width_km / 2, 0, -t.height_km / 2);
78
  const pos = geo.attributes.position;
@@ -83,7 +146,7 @@ function buildTerrain(t) {
83
  .map(([s, c]) => [s, new THREE.Color(c)]);
84
  const tmp = new THREE.Color();
85
  for (let k = 0; k < pos.count; k++) {
86
- const i = k % w, j = Math.floor(k / w);
87
  const v = dm[j * w + i];
88
  pos.setY(k, ((t.min_m + v * t.scale_m) / 1000) * VEX);
89
  const s = (v - lo) / (hi - lo || 1);
@@ -95,13 +158,31 @@ function buildTerrain(t) {
95
  }
96
  geo.setAttribute("color", new THREE.BufferAttribute(col, 3));
97
  geo.computeVertexNormals();
98
- scene.add(new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.95 })));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  }
100
 
101
  const P = (x, y, lift = 0) => new THREE.Vector3(x, H(x, y) + lift, -y);
102
 
103
  // Lakes: flat shapes at the shore's height, raised with the pool level, coloured by flood pool in use.
104
  const lakeMeshes = {}; // pool -> [{mesh, base}]
 
105
  function buildLakes(lakes) {
106
  for (const l of lakes) {
107
  const shape = new THREE.Shape(l.ring.map(([x, y]) => new THREE.Vector2(x, y)));
@@ -109,8 +190,8 @@ function buildLakes(lakes) {
109
  geo.rotateX(-Math.PI / 2);
110
  const hs = l.ring.map(([x, y]) => H(x, y)).sort((a, b) => a - b);
111
  const base = hs[Math.floor(hs.length * 0.2)] + 0.05;
112
- const mat = new THREE.MeshStandardMaterial({ color: "#2d6fb8", roughness: 0.25, metalness: 0.1, transparent: true,
113
- opacity: 0.92 });
114
  const mesh = new THREE.Mesh(geo, mat);
115
  mesh.position.y = base;
116
  scene.add(mesh);
@@ -168,7 +249,7 @@ function buildRivers(b) {
168
  mat.resolution.set(innerWidth, innerHeight);
169
  lineMats.push(mat);
170
  scene.add(new Line2(geo, mat));
171
- reaches.push({ ...r, pts, len, total: len[len.length - 1], mat });
172
  }
173
  // particles
174
  const N = 2600;
@@ -183,7 +264,7 @@ function buildRivers(b) {
183
  }
184
  const geo = new THREE.BufferGeometry();
185
  geo.setAttribute("position", new THREE.BufferAttribute(pos, 3));
186
- const mat = new THREE.PointsMaterial({ color: "#d8f0ff", size: 0.55, transparent: true, opacity: 0.85,
187
  depthWrite: false });
188
  const pts = new THREE.Points(geo, mat);
189
  scene.add(pts);
@@ -199,6 +280,20 @@ function along(r, s) {
199
 
200
  // Points: dams, gauges, towns.
201
  const markers = { dams: {}, gauges: {} };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  function label(html, cls = "lbl") {
203
  const el = document.createElement("div");
204
  el.className = cls;
@@ -206,26 +301,169 @@ function label(html, cls = "lbl") {
206
  return new CSS2DObject(el);
207
  }
208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
  function buildPoints(b) {
 
 
210
  for (const [k, d] of Object.entries(b.dams)) {
211
  const [x, y] = d.xy;
212
- const m = new THREE.Mesh(new THREE.BoxGeometry(1.6, 1.2, 0.6), new THREE.MeshStandardMaterial({ color: "#e8e6df" }));
213
- m.position.copy(P(x, y, 0.6));
214
- scene.add(m);
 
 
 
 
 
 
 
 
215
  if (DAM_ORDER.includes(k)) {
216
- const bar = new THREE.Mesh(new THREE.CylinderGeometry(0.5, 0.5, 1, 16), new THREE.MeshStandardMaterial({ color: "#2bb3a3" }));
217
- bar.position.copy(P(x, y, 1.2));
218
- scene.add(bar);
219
- const lb = label(`<b>${DAM_NAME[k]}</b>`, "lbl dam-l");
220
  lb.position.copy(P(x, y, 4));
221
  scene.add(lb);
222
- markers.dams[k] = { bar, lb, base: P(x, y, 1.2).y };
223
  }
224
  }
225
  for (const [k, g] of Object.entries(b.gauges)) {
226
  const [x, y] = g.xy;
227
- const pil = new THREE.Mesh(new THREE.CylinderGeometry(0.45, 0.45, 3, 12), new THREE.MeshStandardMaterial({ color: CAT_COL[0] }));
228
- pil.position.copy(P(x, y, 1.5));
 
 
 
 
 
 
229
  scene.add(pil);
230
  const lb = label(`<b>${g.name.replace("Cumberland River at ", "")}</b>`, k === "NAS" ? "lbl below east" : "lbl below");
231
  lb.position.copy(P(x, y, 0.2));
@@ -240,21 +478,111 @@ function buildPoints(b) {
240
  }
241
  }
242
 
 
 
 
 
 
 
 
243
  function frameBasin() {
244
  const t = state.basin.terrain;
245
- // the dams and gauges span x 25-180 km; centre them between the side panels
 
246
  controls.target.set(98, 0, -t.height_km * 0.56);
247
  camera.position.set(98, 205, t.height_km * 0.42);
248
  controls.update();
249
- $("cam-basin").classList.add("on");
250
  }
251
 
252
- function goTo(x, y) {
 
 
 
 
 
 
 
 
 
 
253
  const p = P(x, y);
 
 
254
  controls.target.copy(p);
255
- camera.position.set(p.x - 10, p.y + 34, p.z + 34);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
  controls.update();
257
- $("cam-basin").classList.remove("on");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
258
  }
259
 
260
  // ------------------------------------------------------------------------------------------------ state at time t
@@ -276,6 +604,14 @@ function apply(t) {
276
  state.t = t;
277
  const step = Math.floor(t);
278
  $("scrub").value = t;
 
 
 
 
 
 
 
 
279
  $("clock").innerHTML = `<b>${r.times[step]}</b><span>step ${step} of ${nT - 1}${step >= r.steps ? " · tail (water in transit)" : ""}</span>`;
280
  // lakes and dam bars
281
  for (const k of DAM_ORDER) {
@@ -283,15 +619,13 @@ function apply(t) {
283
  const pct = lerpArr(d.pct, Math.min(t, r.steps));
284
  const col = poolColor(pct);
285
  const rise = ((lerpArr(d.elev_ft, Math.min(t, r.steps)) - d.elev_ft[0]) * 0.3048 / 1000) * VEX;
286
- for (const L of lakeMeshes[k] || []) { L.mesh.material.color.copy(col); L.mesh.position.y = L.base + rise; }
 
 
287
  const m = markers.dams[k];
288
- const hgt = Math.max(0.2, 1 + Math.max(0, pct) * 0.08);
289
- m.bar.scale.y = hgt;
290
- m.bar.position.y = m.base + hgt / 2;
291
- m.bar.material.color.copy(col);
292
  const rel = step < r.steps ? d.release[step] : d.release[r.steps - 1];
293
  m.lb.element.innerHTML = `<b>${DAM_NAME[k]}</b> <small>${poolText(pct)} · ${kcfs(rel)} cfs</small>`;
294
- m.lb.position.y = m.base + hgt + 2.4;
295
  }
296
  // gauges
297
  for (const [k, g] of Object.entries(r.gauges)) {
@@ -299,7 +633,10 @@ function apply(t) {
299
  const m = markers.gauges[k];
300
  if (!m) continue;
301
  m.pil.material.color.set(CAT_COL[c]);
302
- m.pil.scale.y = 0.6 + Math.min(4, q / g.thresholds.minor) * 1.2;
 
 
 
303
  m.lb.element.innerHTML = `<b>${g.name.replace("Cumberland River at ", "").replace(/, (KY|TN)$/, "")}</b> <small>${kcfs(q)} cfs</small>`;
304
  }
305
  // rivers
@@ -313,6 +650,8 @@ function apply(t) {
313
  }
314
  rc.flow = rc.kind === "gauge" ? lerpArr(r.gauges[rc.gauge].flow, t)
315
  : lerpArr(rc.kind === "release" ? r.dams[rc.dam].release : r.dams[rc.dam].inflow, Math.min(t, r.steps - 1));
 
 
316
  }
317
  // panels
318
  $("dams").innerHTML = "<h3>Dams</h3>" + DAM_ORDER.map((k) => {
@@ -436,6 +775,7 @@ async function main() {
436
  buildRivers(state.basin);
437
  buildPoints(state.basin);
438
  frameBasin();
 
439
  const go = $("goto");
440
  for (const [k, d] of Object.entries(state.basin.dams)) go.insertAdjacentHTML("beforeend", `<option value="d:${k}">${d.name}</option>`);
441
  for (const [k, g] of Object.entries(state.basin.gauges)) go.insertAdjacentHTML("beforeend", `<option value="g:${k}">${g.name}</option>`);
@@ -466,12 +806,20 @@ $("restart").onclick = () => apply(0);
466
  $("speed").onchange = (e) => (state.speed = parseFloat(e.target.value));
467
  $("scrub").oninput = (e) => apply(parseFloat(e.target.value));
468
  $("cam-basin").onclick = () => frameBasin();
 
 
 
 
469
  $("panels").onclick = () => document.body.classList.toggle("nopanels");
470
  addEventListener("keydown", (e) => {
471
  if (e.target.tagName === "SELECT" || e.target.tagName === "INPUT") return;
472
  if (e.code === "Space") { e.preventDefault(); toggle(); }
473
  if (e.code === "Home") apply(0);
474
  if (e.key === "b") frameBasin();
 
 
 
 
475
  if (e.key === "h") document.body.classList.toggle("nopanels");
476
  });
477
  // The header wraps on narrow screens: the panels start below it, whatever its height (RailSim learnt this the hard way).
@@ -507,7 +855,21 @@ function loop(now) {
507
  }
508
  geo.attributes.position.needsUpdate = true;
509
  }
510
- controls.update();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
511
  renderer.render(scene, camera);
512
  labels.render(scene, camera);
513
  requestAnimationFrame(loop);
 
6
  import { Line2 } from "three/addons/lines/Line2.js";
7
  import { LineGeometry } from "three/addons/lines/LineGeometry.js";
8
  import { LineMaterial } from "three/addons/lines/LineMaterial.js";
9
+ import { Sky } from "three/addons/objects/Sky.js";
10
 
11
+ const VEX = 6; // vertical exaggeration
12
  const CAT_COL = ["#3f9be8", "#f2c94c", "#f2994a", "#eb5757", "#b44fd6"];
13
  const CAT_NAME = ["below action", "action", "minor flood", "moderate flood", "major flood"];
14
  const DAM_ORDER = ["WC", "DH", "CH", "JPP"];
 
39
  renderer.setPixelRatio(Math.min(2, window.devicePixelRatio));
40
  renderer.setSize(innerWidth, innerHeight);
41
  renderer.outputColorSpace = THREE.SRGBColorSpace;
42
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
43
+ renderer.toneMappingExposure = 0.75;
44
  stage.appendChild(renderer.domElement);
45
  const labels = new CSS2DRenderer();
46
  labels.setSize(innerWidth, innerHeight);
 
50
  stage.appendChild(labels.domElement);
51
 
52
  const scene = new THREE.Scene();
53
+ scene.background = new THREE.Color("#9fb6cc");
54
+ scene.fog = new THREE.Fog("#b9c8d6", 220, 700);
55
  const camera = new THREE.PerspectiveCamera(42, innerWidth / innerHeight, 0.1, 2000);
56
  const controls = new OrbitControls(camera, renderer.domElement);
57
  controls.enableDamping = true;
58
  controls.maxPolarAngle = Math.PI * 0.47;
59
+ const hemi = new THREE.HemisphereLight("#d6e6ff", "#4a4030", 1.4);
60
+ scene.add(hemi);
61
+ const sun = new THREE.DirectionalLight("#fff1dc", 2.6);
62
  sun.position.set(-80, 160, 60);
63
+ scene.add(sun, sun.target);
64
+ const sky = new Sky();
65
+ sky.scale.setScalar(4000);
66
+ Object.assign(sky.material.uniforms, {});
67
+ sky.material.uniforms.turbidity.value = 5;
68
+ sky.material.uniforms.rayleigh.value = 1.2;
69
+ sky.material.uniforms.mieCoefficient.value = 0.004;
70
+ sky.material.uniforms.mieDirectionalG.value = 0.8;
71
+ scene.add(sky);
72
+
73
+ // The sun where it was over the basin (36.4 N, 85.8 W) at the replay's clock, from the standard solar position
74
+ // formulas; it sets the sky, the light and the haze.
75
+ function sunAt(ms) {
76
+ const d = new Date(ms), rad = Math.PI / 180;
77
+ const day = (Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()) - Date.UTC(d.getUTCFullYear(), 0, 0)) / 864e5;
78
+ const g = (2 * Math.PI / 365) * (day - 1 + (d.getUTCHours() - 12) / 24);
79
+ const decl = 0.006918 - 0.399912 * Math.cos(g) + 0.070257 * Math.sin(g) - 0.006758 * Math.cos(2 * g)
80
+ + 0.000907 * Math.sin(2 * g) - 0.002697 * Math.cos(3 * g) + 0.00148 * Math.sin(3 * g);
81
+ const eqt = 229.18 * (0.000075 + 0.001868 * Math.cos(g) - 0.032077 * Math.sin(g) - 0.014615 * Math.cos(2 * g)
82
+ - 0.040849 * Math.sin(2 * g));
83
+ const lat = 36.4 * rad, lon = -85.8;
84
+ const tst = d.getUTCHours() * 60 + d.getUTCMinutes() + eqt + 4 * lon;
85
+ const ha = (tst / 4 - 180) * rad;
86
+ const cz = Math.sin(lat) * Math.sin(decl) + Math.cos(lat) * Math.cos(decl) * Math.cos(ha);
87
+ const el = Math.asin(Math.max(-1, Math.min(1, cz)));
88
+ const az = Math.atan2(Math.sin(ha), Math.cos(ha) * Math.sin(lat) - Math.tan(decl) * Math.cos(lat)) + Math.PI;
89
+ return { el, az }; // radians; azimuth from north, clockwise
90
+ }
91
+
92
+ function setSun(ms) {
93
+ const { el, az } = sunAt(ms);
94
+ const dir = new THREE.Vector3(Math.sin(az) * Math.cos(el), Math.sin(el), -Math.cos(az) * Math.cos(el));
95
+ sky.material.uniforms.sunPosition.value.copy(dir);
96
+ const t = state.basin.terrain, c = new THREE.Vector3(t.width_km / 2, 0, -t.height_km / 2);
97
+ sun.target.position.copy(c);
98
+ sun.position.copy(c).addScaledVector(dir, 300);
99
+ const day = Math.max(0, Math.min(1, (el + 0.1) / 0.35)); // 0 at night, 1 a little after sunrise
100
+ // night keeps a moonlit level, so the map stays readable at 3 AM
101
+ sun.intensity = 0.7 + 2.0 * day;
102
+ sun.color.set(new THREE.Color("#ff9a5a").lerp(new THREE.Color("#fff1dc"), Math.min(1, Math.max(0, el / 0.4))));
103
+ hemi.intensity = 0.75 + 0.75 * day;
104
+ renderer.toneMappingExposure = 0.6 + 0.2 * day;
105
+ const haze = new THREE.Color("#3a4a5e").lerp(new THREE.Color("#b9c8d6"), day);
106
+ scene.fog.color.copy(haze);
107
+ sky.visible = el > -0.2;
108
+ scene.background = new THREE.Color("#1c2638").lerp(new THREE.Color("#9fb6cc"), day);
109
+ }
110
 
111
  let H; // terrain height sampler (km, exaggerated)
112
 
113
  function buildTerrain(t) {
114
  const raw = Uint8Array.from(atob(t.data), (c) => c.charCodeAt(0));
115
  const dm = new Uint16Array(raw.buffer);
116
+ let lo0 = Infinity;
117
+ for (let k = 0; k < dm.length; k++) lo0 = Math.min(lo0, dm[k]);
118
  const { w, h } = t;
119
  const elev = (i, j) => (t.min_m + dm[Math.min(h - 1, Math.max(0, j)) * w + Math.min(w - 1, Math.max(0, i))] * t.scale_m);
120
+ const mw0 = Math.ceil(w / 2), mh0 = Math.ceil(h / 2);
121
+ const elevM = (i, j) => elev(Math.min(w - 1, i * 2), Math.min(h - 1, j * 2));
122
+ H = (x, y) => { // x km east, y km north of the SW corner, on the drawn (half-res) mesh
123
+ const fi = (x / t.width_km) * (mw0 - 1), fj = (1 - y / t.height_km) * (mh0 - 1);
124
+ const i = Math.floor(fi), j = Math.floor(fj), a = fi - i, b = fj - j;
125
+ const e = elevM(i, j) * (1 - a) * (1 - b) + elevM(i + 1, j) * a * (1 - b) + elevM(i, j + 1) * (1 - a) * b
126
+ + elevM(i + 1, j + 1) * a * b;
127
+ return (e / 1000) * VEX;
128
+ };
129
+ const Hfull = (x, y) => {
130
  const fi = (x / t.width_km) * (w - 1), fj = (1 - y / t.height_km) * (h - 1);
131
  const i = Math.floor(fi), j = Math.floor(fj), a = fi - i, b = fj - j;
132
  const e = elev(i, j) * (1 - a) * (1 - b) + elev(i + 1, j) * a * (1 - b) + elev(i, j + 1) * (1 - a) * b
133
  + elev(i + 1, j + 1) * a * b;
134
  return (e / 1000) * VEX;
135
  };
136
+ // the mesh at half the terrain's resolution (the imagery carries the detail); heights from the full grid
137
+ const mw = Math.ceil(w / 2), mh = Math.ceil(h / 2);
138
+ const geo = new THREE.PlaneGeometry(t.width_km, t.height_km, mw - 1, mh - 1);
139
  geo.rotateX(-Math.PI / 2);
140
  geo.translate(t.width_km / 2, 0, -t.height_km / 2);
141
  const pos = geo.attributes.position;
 
146
  .map(([s, c]) => [s, new THREE.Color(c)]);
147
  const tmp = new THREE.Color();
148
  for (let k = 0; k < pos.count; k++) {
149
+ const i = Math.min(w - 1, (k % mw) * 2), j = Math.min(h - 1, Math.floor(k / mw) * 2);
150
  const v = dm[j * w + i];
151
  pos.setY(k, ((t.min_m + v * t.scale_m) / 1000) * VEX);
152
  const s = (v - lo) / (hi - lo || 1);
 
158
  }
159
  geo.setAttribute("color", new THREE.BufferAttribute(col, 3));
160
  geo.computeVertexNormals();
161
+ const mat = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.95 });
162
+ scene.add(new THREE.Mesh(geo, mat));
163
+ // land beyond the map, fading into the haze, so the basin does not float in a void
164
+ const ground = new THREE.Mesh(new THREE.PlaneGeometry(3000, 3000), new THREE.MeshStandardMaterial({ color: "#4f5a3c",
165
+ roughness: 1 }));
166
+ ground.rotation.x = -Math.PI / 2;
167
+ ground.position.set(t.width_km / 2, ((t.min_m + lo0 * t.scale_m) / 1000) * VEX - 0.05, -t.height_km / 2);
168
+ scene.add(ground);
169
+ if (state.basin.imagery) { // the orthoimagery replaces the elevation colours once it has loaded
170
+ new THREE.TextureLoader().load(state.basin.imagery.file, (tex) => {
171
+ tex.colorSpace = THREE.SRGBColorSpace;
172
+ tex.anisotropy = renderer.capabilities.getMaxAnisotropy();
173
+ mat.map = tex;
174
+ mat.vertexColors = false;
175
+ mat.color.set("#ffffff");
176
+ mat.needsUpdate = true;
177
+ });
178
+ }
179
  }
180
 
181
  const P = (x, y, lift = 0) => new THREE.Vector3(x, H(x, y) + lift, -y);
182
 
183
  // Lakes: flat shapes at the shore's height, raised with the pool level, coloured by flood pool in use.
184
  const lakeMeshes = {}; // pool -> [{mesh, base}]
185
+ const WATER = new THREE.Color("#1f4e6e");
186
  function buildLakes(lakes) {
187
  for (const l of lakes) {
188
  const shape = new THREE.Shape(l.ring.map(([x, y]) => new THREE.Vector2(x, y)));
 
190
  geo.rotateX(-Math.PI / 2);
191
  const hs = l.ring.map(([x, y]) => H(x, y)).sort((a, b) => a - b);
192
  const base = hs[Math.floor(hs.length * 0.2)] + 0.05;
193
+ const mat = new THREE.MeshPhysicalMaterial({ color: WATER, roughness: 0.12, metalness: 0.05, clearcoat: 1,
194
+ clearcoatRoughness: 0.08, transparent: true, opacity: 0.9 });
195
  const mesh = new THREE.Mesh(geo, mat);
196
  mesh.position.y = base;
197
  scene.add(mesh);
 
249
  mat.resolution.set(innerWidth, innerHeight);
250
  lineMats.push(mat);
251
  scene.add(new Line2(geo, mat));
252
+ reaches.push({ ...r, river: p.river, pts, len, total: len[len.length - 1], mat });
253
  }
254
  // particles
255
  const N = 2600;
 
264
  }
265
  const geo = new THREE.BufferGeometry();
266
  geo.setAttribute("position", new THREE.BufferAttribute(pos, 3));
267
+ const mat = new THREE.PointsMaterial({ color: "#e4f4ff", size: 0.3, map: DOT, transparent: true, opacity: 0.9,
268
  depthWrite: false });
269
  const pts = new THREE.Points(geo, mat);
270
  scene.add(pts);
 
280
 
281
  // Points: dams, gauges, towns.
282
  const markers = { dams: {}, gauges: {} };
283
+ // a soft round sprite for the particles (plain points draw as squares)
284
+ const DOT = (() => {
285
+ const c = document.createElement("canvas");
286
+ c.width = c.height = 64;
287
+ const g = c.getContext("2d"), grd = g.createRadialGradient(32, 32, 0, 32, 32, 32);
288
+ grd.addColorStop(0, "rgba(255,255,255,1)");
289
+ grd.addColorStop(0.45, "rgba(255,255,255,0.75)");
290
+ grd.addColorStop(1, "rgba(255,255,255,0)");
291
+ g.fillStyle = grd;
292
+ g.fillRect(0, 0, 64, 64);
293
+ return new THREE.CanvasTexture(c);
294
+ })();
295
+ const sprays = {};
296
+ const damGroups = {};
297
  function label(html, cls = "lbl") {
298
  const el = document.createElement("div");
299
  el.className = cls;
 
301
  return new CSS2DObject(el);
302
  }
303
 
304
+ // The dams as built (approximate, from USACE project descriptions; display only). Lengths in km along the axis,
305
+ // height in metres (drawn with the terrain's exaggeration). Wolf Creek: a 1,750 m earth-and-concrete dam with a
306
+ // gated spillway and a six-unit powerhouse; Dale Hollow and Center Hill: concrete gravity dams with earth wings;
307
+ // J. Percy Priest: a concrete spillway section in a long earth embankment; Cordell Hull and Old Hickory: lock and dams.
308
+ const DAM_SPEC = {
309
+ WC: { concrete: 0.55, earthL: 0.15, earthR: 1.05, height: 79, gates: 10, units: 6 },
310
+ DH: { concrete: 0.42, earthL: 0.05, earthR: 0.10, height: 61, gates: 6, units: 3 },
311
+ CH: { concrete: 0.47, earthL: 0.20, earthR: 0.0, height: 76, gates: 8, units: 3 },
312
+ JPP: { concrete: 0.33, earthL: 0.30, earthR: 0.20, height: 45, gates: 4, units: 1 },
313
+ COH: { concrete: 0.25, earthL: 0.10, earthR: 0.0, height: 28, gates: 5, units: 3, lock: true },
314
+ OH: { concrete: 0.40, earthL: 0.30, earthR: 0.0, height: 30, gates: 6, units: 4, lock: true },
315
+ };
316
+ const M_CONC = new THREE.MeshStandardMaterial({ color: "#d4cfc4", roughness: 0.85 });
317
+ const M_CONC_D = new THREE.MeshStandardMaterial({ color: "#a9a397", roughness: 0.9 });
318
+ const M_GATE = new THREE.MeshStandardMaterial({ color: "#3f4a52", roughness: 0.5, metalness: 0.6 });
319
+ const M_EARTH = new THREE.MeshStandardMaterial({ color: "#6f7d4a", roughness: 1 });
320
+ const M_RIP = new THREE.MeshStandardMaterial({ color: "#8d887c", roughness: 1 });
321
+ const M_ROAD = new THREE.MeshStandardMaterial({ color: "#3b3b3b", roughness: 0.9 });
322
+ const M_ROOF = new THREE.MeshStandardMaterial({ color: "#7c3f2c", roughness: 0.7 });
323
+ const M_GLASS = new THREE.MeshStandardMaterial({ color: "#26343d", roughness: 0.3, metalness: 0.4 });
324
+
325
+ function prism(profile, length, mat) {
326
+ // a cross-section in the (z downstream, y up) plane, extruded along x (the dam axis), centred on x = 0
327
+ const sh = new THREE.Shape(profile.map(([z, y]) => new THREE.Vector2(z, y)));
328
+ const g = new THREE.ExtrudeGeometry(sh, { depth: length, bevelEnabled: false });
329
+ g.rotateY(Math.PI / 2); // extrude direction (shape z) -> +x
330
+ g.translate(-length / 2, 0, 0);
331
+ // after rotateY the shape's x became -z: flip so +z is downstream
332
+ g.scale(1, 1, -1);
333
+ return new THREE.Mesh(g, mat);
334
+ }
335
+
336
+ function makeDam(spec) {
337
+ const g = new THREE.Group();
338
+ const hgt = (spec.height / 1000) * VEX; // km, exaggerated like the terrain
339
+ // profiles in proportion to the drawn height, so faces slope as on the real dams (the terrain is exaggerated, the
340
+ // footprint along the river follows): a gravity section's base is about 0.75 of its height, an embankment's 3x
341
+ const base = 0.75 * hgt;
342
+ // concrete gravity section: vertical upstream face, sloped downstream face, flat crest with a road
343
+ const conc = prism([[-0.01, 0], [base, 0], [0.012, hgt], [-0.01, hgt]], spec.concrete, M_CONC);
344
+ g.add(conc);
345
+ const road = new THREE.Mesh(new THREE.BoxGeometry(spec.concrete, 0.02, 0.016), M_ROAD);
346
+ road.position.set(0, hgt + 0.01, 0.001);
347
+ g.add(road);
348
+ // gated spillway in the middle of the concrete: piers standing above the crest, tainter gates between
349
+ const span = spec.concrete * 0.55, n = spec.gates, bay = span / n;
350
+ for (let i = 0; i <= n; i++) {
351
+ const pier = new THREE.Mesh(new THREE.BoxGeometry(bay * 0.18, hgt * 0.16, 0.04), M_CONC_D);
352
+ pier.position.set(-span / 2 + i * bay, hgt + hgt * 0.08, 0.004);
353
+ g.add(pier);
354
+ }
355
+ for (let i = 0; i < n; i++) {
356
+ const gate = new THREE.Mesh(new THREE.BoxGeometry(bay * 0.8, hgt * 0.12, 0.006), M_GATE);
357
+ gate.position.set(-span / 2 + (i + 0.5) * bay, hgt - hgt * 0.02, -0.006);
358
+ g.add(gate);
359
+ const chute = new THREE.Mesh(new THREE.BoxGeometry(bay * 0.8, 0.004, base * 1.1), M_CONC_D);
360
+ chute.position.set(-span / 2 + (i + 0.5) * bay, hgt * 0.04, base * 0.6);
361
+ chute.rotation.x = Math.atan2(hgt * 0.9, base);
362
+ g.add(chute);
363
+ }
364
+ // powerhouse at the toe, on one side of the spillway: a hall with a roof, intakes and a tailrace deck
365
+ const phW = Math.min(spec.concrete * 0.38, 0.03 + spec.units * 0.022);
366
+ const phx = span / 2 + phW / 2 + 0.01;
367
+ const hall = new THREE.Mesh(new THREE.BoxGeometry(phW, hgt * 0.28, 0.05), M_CONC);
368
+ hall.position.set(phx, hgt * 0.14, base + 0.03);
369
+ g.add(hall);
370
+ const roof = new THREE.Mesh(new THREE.BoxGeometry(phW * 1.02, 0.012, 0.055), M_ROOF);
371
+ roof.position.set(phx, hgt * 0.28 + 0.006, base + 0.03);
372
+ g.add(roof);
373
+ for (let i = 0; i < spec.units; i++) {
374
+ const win = new THREE.Mesh(new THREE.BoxGeometry(phW / spec.units * 0.55, hgt * 0.08, 0.002), M_GLASS);
375
+ win.position.set(phx - phW / 2 + (i + 0.5) * phW / spec.units, hgt * 0.18, base + 0.056);
376
+ g.add(win);
377
+ const pen = new THREE.Mesh(new THREE.CylinderGeometry(0.006, 0.006, hgt * 0.9, 8), M_CONC_D);
378
+ pen.position.set(phx - phW / 2 + (i + 0.5) * phW / spec.units, hgt * 0.55, base * 0.5);
379
+ pen.rotation.x = Math.atan2(base, hgt) * 0.9;
380
+ g.add(pen);
381
+ }
382
+ // earth embankments continuing the axis: wide trapezoids, grassed, with riprap on the upstream face
383
+ for (const [len, side] of [[spec.earthL, -1], [spec.earthR, 1]]) {
384
+ if (!len) continue;
385
+ const bw = 1.5 * hgt;
386
+ const emb = prism([[-bw, 0], [bw, 0], [0.008, hgt * 0.98], [-0.008, hgt * 0.98]], len, M_EARTH);
387
+ emb.position.x = side * (spec.concrete / 2 + len / 2);
388
+ g.add(emb);
389
+ const rip = prism([[-bw - 0.004, 0], [-0.0075, hgt * 0.97], [-0.014, hgt * 0.97], [-bw - 0.012, 0]], len, M_RIP);
390
+ rip.position.x = emb.position.x;
391
+ g.add(rip);
392
+ const r2 = new THREE.Mesh(new THREE.BoxGeometry(len, 0.012, 0.012), M_ROAD);
393
+ r2.position.set(emb.position.x, hgt * 0.98 + 0.006, 0);
394
+ g.add(r2);
395
+ }
396
+ // a navigation lock beside the dam: two long walls and the chamber between them, with gates at each end
397
+ if (spec.lock) {
398
+ const lx = -spec.concrete / 2 + 0.03, lw = 0.025, ll = 0.26;
399
+ for (const off of [-lw, lw]) {
400
+ const wall = new THREE.Mesh(new THREE.BoxGeometry(0.01, hgt * 1.05, ll), M_CONC);
401
+ wall.position.set(lx + off, hgt * 0.52, 0.02);
402
+ g.add(wall);
403
+ }
404
+ for (const zz of [-ll / 2 + 0.02, ll / 2 + 0.02]) {
405
+ const lg = new THREE.Mesh(new THREE.BoxGeometry(lw * 2, hgt * 0.9, 0.006), M_GATE);
406
+ lg.position.set(lx, hgt * 0.45, zz);
407
+ g.add(lg);
408
+ }
409
+ }
410
+ return g;
411
+ }
412
+
413
+ // A USGS gauge house on the bank: a small concrete hut with a roof, a radio mast and a solar panel.
414
+ function makeGaugeHouse() {
415
+ const g = new THREE.Group();
416
+ const s = 0.05; // drawn larger than life so it shows at a few km
417
+ const hut = new THREE.Mesh(new THREE.BoxGeometry(s, s * 0.9, s), M_CONC);
418
+ hut.position.y = s * 0.45;
419
+ g.add(hut);
420
+ const roof = new THREE.Mesh(new THREE.ConeGeometry(s * 0.8, s * 0.45, 4), M_ROOF);
421
+ roof.rotation.y = Math.PI / 4;
422
+ roof.position.y = s * 0.9 + s * 0.22;
423
+ g.add(roof);
424
+ const mast = new THREE.Mesh(new THREE.CylinderGeometry(0.0025, 0.0025, s * 3.2, 6), M_GATE);
425
+ mast.position.set(s * 0.4, s * 1.6, 0);
426
+ g.add(mast);
427
+ const panel = new THREE.Mesh(new THREE.BoxGeometry(s * 0.7, 0.003, s * 0.45), M_GLASS);
428
+ panel.position.set(s * 0.4, s * 2.2, s * 0.1);
429
+ panel.rotation.x = -0.6;
430
+ g.add(panel);
431
+ return g;
432
+ }
433
+
434
  function buildPoints(b) {
435
+ const riverPts = b.rivers.filter((r) => r.river === "Cumberland River" || ["Obey River", "Caney Fork", "Stones River"]
436
+ .includes(r.river)).flatMap((r) => r.pts.map((p, i, a) => ({ p, q: a[Math.min(a.length - 1, i + 1)], r: a[Math.max(0, i - 1)] })));
437
  for (const [k, d] of Object.entries(b.dams)) {
438
  const [x, y] = d.xy;
439
+ let best = riverPts[0], bd = Infinity;
440
+ for (const v of riverPts) { const dd = Math.hypot(v.p[0] - x, v.p[1] - y); if (dd < bd) { bd = dd; best = v; } }
441
+ // across the river: local +z points downstream (NHD flowlines run with the flow), local x along the dam axis
442
+ const dx = best.q[0] - best.r[0], dy = best.q[1] - best.r[1];
443
+ const ang = Math.atan2(dy, dx);
444
+ const big = DAM_ORDER.includes(k);
445
+ const grp = makeDam(DAM_SPEC[k] || DAM_SPEC.COH);
446
+ grp.position.set(x, H(x, y) - 0.05, -y);
447
+ grp.rotation.y = Math.atan2(dx, -dy);
448
+ scene.add(grp);
449
+ damGroups[k] = grp;
450
  if (DAM_ORDER.includes(k)) {
451
+ const lb = label(`<b>${DAM_NAME[k]}</b>`, "lbl dam-l");
 
 
 
452
  lb.position.copy(P(x, y, 4));
453
  scene.add(lb);
454
+ markers.dams[k] = { lb, base: P(x, y, 1.2).y };
455
  }
456
  }
457
  for (const [k, g] of Object.entries(b.gauges)) {
458
  const [x, y] = g.xy;
459
+ const house = makeGaugeHouse();
460
+ house.position.copy(P(x, y, 0));
461
+ house.scale.setScalar(4);
462
+ scene.add(house);
463
+ const pil = new THREE.Mesh(new THREE.CylinderGeometry(0.06, 0.06, 1, 10), new THREE.MeshStandardMaterial({ color: CAT_COL[0],
464
+ emissive: CAT_COL[0], emissiveIntensity: 0.35 }));
465
+ pil.position.copy(P(x + 0.35, y, 0.5));
466
+ pil.userData.base = P(x + 0.35, y, 0).y;
467
  scene.add(pil);
468
  const lb = label(`<b>${g.name.replace("Cumberland River at ", "")}</b>`, k === "NAS" ? "lbl below east" : "lbl below");
469
  lb.position.copy(P(x, y, 0.2));
 
478
  }
479
  }
480
 
481
+ // Cameras: the basin, straight down, a dam close up, low over a gauge, or a flight down the Cumberland.
482
+ const cam = { mode: "basin", dam: -1, gauge: -1, fly: null, s: 0 };
483
+
484
+ function setCamButtons(id) {
485
+ for (const b of ["cam-basin", "cam-top", "cam-dam", "cam-gauge", "cam-fly"]) $(b).classList.toggle("on", b === id);
486
+ }
487
+
488
  function frameBasin() {
489
  const t = state.basin.terrain;
490
+ cam.mode = "basin";
491
+ controls.enabled = true;
492
  controls.target.set(98, 0, -t.height_km * 0.56);
493
  camera.position.set(98, 205, t.height_km * 0.42);
494
  controls.update();
495
+ setCamButtons("cam-basin");
496
  }
497
 
498
+ function frameTop() {
499
+ const t = state.basin.terrain;
500
+ cam.mode = "top";
501
+ controls.enabled = true;
502
+ controls.target.set(100, 0, -t.height_km * 0.55);
503
+ camera.position.set(100, 300, -t.height_km * 0.55 + 0.01);
504
+ controls.update();
505
+ setCamButtons("cam-top");
506
+ }
507
+
508
+ function goTo(x, y, dist = 34, hgt = 26) {
509
  const p = P(x, y);
510
+ cam.mode = "point";
511
+ controls.enabled = true;
512
  controls.target.copy(p);
513
+ camera.position.set(p.x - dist * 0.3, p.y + hgt, p.z + dist);
514
+ controls.update();
515
+ setCamButtons(null);
516
+ }
517
+
518
+ function nextDam() {
519
+ cam.dam = (cam.dam + 1) % DAM_ORDER.length;
520
+ const d = state.basin.dams[DAM_ORDER[cam.dam]];
521
+ // close in, from downstream and to one side, so the spillway, the powerhouse and the embankment fill the frame
522
+ const k = DAM_ORDER[cam.dam], m = damGroups[k];
523
+ const p = P(d.xy[0], d.xy[1]);
524
+ const down = new THREE.Vector3(0, 0, 1).applyQuaternion(m.quaternion), side = new THREE.Vector3(1, 0, 0).applyQuaternion(m.quaternion);
525
+ cam.mode = "point";
526
+ controls.enabled = true;
527
+ controls.target.copy(p).add(new THREE.Vector3(0, 0.35, 0));
528
+ camera.position.copy(p).addScaledVector(down, 2.6).addScaledVector(side, 1.2).add(new THREE.Vector3(0, 1.4, 0));
529
  controls.update();
530
+ setCamButtons("cam-dam");
531
+ }
532
+
533
+ function nextGauge() {
534
+ const ks = Object.keys(state.basin.gauges);
535
+ cam.gauge = (cam.gauge + 1) % ks.length;
536
+ const g = state.basin.gauges[ks[cam.gauge]];
537
+ goTo(g.xy[0], g.xy[1], 9, 3.5);
538
+ setCamButtons("cam-gauge");
539
+ }
540
+
541
+ // The flight path: the Cumberland's NHD reaches chained downstream (each starts where the last ended), from Wolf
542
+ // Creek Dam to below Nashville, smoothed.
543
+ function flightPath() {
544
+ const b = state.basin;
545
+ const segs = b.rivers.filter((r) => r.river === "Cumberland River" && r.pts.length >= 2).map((r) => r.pts);
546
+ const x0 = b.dams.WC.xy[0] + 1, x1 = b.gauges.NAS.xy[0] - 12;
547
+ let cur = segs.reduce((a, c) => (Math.abs(c[0][0] - x0) + Math.abs(c[0][1] - b.dams.WC.xy[1]) <
548
+ Math.abs(a[0][0] - x0) + Math.abs(a[0][1] - b.dams.WC.xy[1]) ? c : a));
549
+ const pts = [...cur], used = new Set([cur]);
550
+ for (let guard = 0; guard < 600; guard++) {
551
+ const end = pts[pts.length - 1];
552
+ let nxt = null, nd = 0.6;
553
+ for (const sg of segs) {
554
+ if (used.has(sg)) continue;
555
+ const dd = Math.hypot(sg[0][0] - end[0], sg[0][1] - end[1]);
556
+ if (dd < nd) { nd = dd; nxt = sg; }
557
+ }
558
+ if (!nxt || end[0] < x1) break;
559
+ used.add(nxt);
560
+ pts.push(...nxt.slice(1));
561
+ }
562
+ const v = pts.filter((_, i) => i % 3 === 0).map(([x, y]) => P(x, y, 0));
563
+ return new THREE.CatmullRomCurve3(v, false, "centripetal", 0.5);
564
+ }
565
+
566
+ function startFly() {
567
+ cam.fly ||= flightPath();
568
+ cam.mode = "fly";
569
+ cam.s = 0.02;
570
+ const p0 = cam.fly.getPointAt(0), a0 = cam.fly.getPointAt(0.05);
571
+ camera.position.copy(p0).addScaledVector(p0.clone().sub(a0).setY(0).normalize(), 9).add(new THREE.Vector3(0, 6.5, 0));
572
+ controls.target.copy(a0);
573
+ controls.enabled = false;
574
+ setCamButtons("cam-fly");
575
+ }
576
+
577
+ function updateFly(dt) {
578
+ const L = cam.fly.getLength();
579
+ cam.s = (cam.s + dt * 3 / L) % 1; // about 3 km of river a second
580
+ const p = cam.fly.getPointAt(cam.s), a = cam.fly.getPointAt(Math.min(1, cam.s + 0.03));
581
+ const back = p.clone().sub(a).setY(0).normalize();
582
+ const want = p.clone().addScaledVector(back, 9).add(new THREE.Vector3(0, 6.5, 0));
583
+ camera.position.lerp(want, 0.08);
584
+ controls.target.lerp(a.clone().add(new THREE.Vector3(0, 0.3, 0)), 0.1);
585
+ camera.lookAt(controls.target);
586
  }
587
 
588
  // ------------------------------------------------------------------------------------------------ state at time t
 
604
  state.t = t;
605
  const step = Math.floor(t);
606
  $("scrub").value = t;
607
+ if (r.start_utc) setSun(Date.parse(r.start_utc) + t * r.step_hours * 3600e3);
608
+ for (const k of DAM_ORDER) {
609
+ const sp = sprays[k];
610
+ if (!sp) continue;
611
+ const d = r.dams[k];
612
+ sp.level = Math.min(1, d.release[Math.min(step, r.steps - 1)] / d.max_release);
613
+ sp.pm.opacity = sp.level > 0.02 ? 0.35 + 0.55 * sp.level : 0;
614
+ }
615
  $("clock").innerHTML = `<b>${r.times[step]}</b><span>step ${step} of ${nT - 1}${step >= r.steps ? " · tail (water in transit)" : ""}</span>`;
616
  // lakes and dam bars
617
  for (const k of DAM_ORDER) {
 
619
  const pct = lerpArr(d.pct, Math.min(t, r.steps));
620
  const col = poolColor(pct);
621
  const rise = ((lerpArr(d.elev_ft, Math.min(t, r.steps)) - d.elev_ft[0]) * 0.3048 / 1000) * VEX;
622
+ // real water, tinted toward the flood-pool colour as the pool fills
623
+ const tint = WATER.clone().lerp(col, Math.min(1, Math.max(0, pct / 100)) * 0.3 + 0.04);
624
+ for (const L of lakeMeshes[k] || []) { L.mesh.material.color.copy(tint); L.mesh.position.y = L.base + rise; }
625
  const m = markers.dams[k];
 
 
 
 
626
  const rel = step < r.steps ? d.release[step] : d.release[r.steps - 1];
627
  m.lb.element.innerHTML = `<b>${DAM_NAME[k]}</b> <small>${poolText(pct)} · ${kcfs(rel)} cfs</small>`;
628
+ m.lb.position.y = m.base + 2.4;
629
  }
630
  // gauges
631
  for (const [k, g] of Object.entries(r.gauges)) {
 
633
  const m = markers.gauges[k];
634
  if (!m) continue;
635
  m.pil.material.color.set(CAT_COL[c]);
636
+ m.pil.material.emissive.set(CAT_COL[c]);
637
+ const ph = 0.25 + Math.min(1.5, q / g.thresholds.minor) * 0.5; // a slim staff, capped at 1.5 x minor flood
638
+ m.pil.scale.y = ph;
639
+ m.pil.position.y = m.pil.userData.base + ph / 2;
640
  m.lb.element.innerHTML = `<b>${g.name.replace("Cumberland River at ", "").replace(/, (KY|TN)$/, "")}</b> <small>${kcfs(q)} cfs</small>`;
641
  }
642
  // rivers
 
650
  }
651
  rc.flow = rc.kind === "gauge" ? lerpArr(r.gauges[rc.gauge].flow, t)
652
  : lerpArr(rc.kind === "release" ? r.dams[rc.dam].release : r.dams[rc.dam].inflow, Math.min(t, r.steps - 1));
653
+ // the river widens with its flow (2 px at a trickle, about 9 px above minor flood)
654
+ rc.mat.linewidth = 1.5 + Math.min(6, 6 * Math.sqrt(Math.max(0, rc.flow) / 120000));
655
  }
656
  // panels
657
  $("dams").innerHTML = "<h3>Dams</h3>" + DAM_ORDER.map((k) => {
 
775
  buildRivers(state.basin);
776
  buildPoints(state.basin);
777
  frameBasin();
778
+ if (new URL(location).searchParams.get("cam") === "top") frameTop();
779
  const go = $("goto");
780
  for (const [k, d] of Object.entries(state.basin.dams)) go.insertAdjacentHTML("beforeend", `<option value="d:${k}">${d.name}</option>`);
781
  for (const [k, g] of Object.entries(state.basin.gauges)) go.insertAdjacentHTML("beforeend", `<option value="g:${k}">${g.name}</option>`);
 
806
  $("speed").onchange = (e) => (state.speed = parseFloat(e.target.value));
807
  $("scrub").oninput = (e) => apply(parseFloat(e.target.value));
808
  $("cam-basin").onclick = () => frameBasin();
809
+ $("cam-top").onclick = () => frameTop();
810
+ $("cam-dam").onclick = () => nextDam();
811
+ $("cam-gauge").onclick = () => nextGauge();
812
+ $("cam-fly").onclick = () => startFly();
813
  $("panels").onclick = () => document.body.classList.toggle("nopanels");
814
  addEventListener("keydown", (e) => {
815
  if (e.target.tagName === "SELECT" || e.target.tagName === "INPUT") return;
816
  if (e.code === "Space") { e.preventDefault(); toggle(); }
817
  if (e.code === "Home") apply(0);
818
  if (e.key === "b") frameBasin();
819
+ if (e.key === "t") frameTop();
820
+ if (e.key === "d") nextDam();
821
+ if (e.key === "g") nextGauge();
822
+ if (e.key === "f") startFly();
823
  if (e.key === "h") document.body.classList.toggle("nopanels");
824
  });
825
  // The header wraps on narrow screens: the panels start below it, whatever its height (RailSim learnt this the hard way).
 
855
  }
856
  geo.attributes.position.needsUpdate = true;
857
  }
858
+ for (const sp of Object.values(sprays)) { // spray tumbling below each releasing dam
859
+ if (!sp.level) continue;
860
+ const ca = Math.cos(sp.ang), sa = Math.sin(sp.ang);
861
+ for (let i = 0; i < sp.seeds.length; i++) {
862
+ const s0 = sp.seeds[i];
863
+ s0[0] = (s0[0] + dt * (0.4 + sp.level)) % 1;
864
+ const along = 0.3 + s0[0] * 2.4 * (0.4 + sp.level), side = (s0[1] - 0.5) * 0.9;
865
+ const px = sp.x + ca * along - sa * side, py = sp.y + sa * along + ca * side;
866
+ const h = H(px, py) + 0.15 + Math.sin(s0[0] * Math.PI) * 0.5 * sp.level * (0.5 + s0[2]);
867
+ sp.pos[3 * i] = px; sp.pos[3 * i + 1] = h; sp.pos[3 * i + 2] = -py;
868
+ }
869
+ sp.g.attributes.position.needsUpdate = true;
870
+ }
871
+ if (cam.mode === "fly" && cam.fly) updateFly(dt);
872
+ else controls.update();
873
  renderer.render(scene, camera);
874
  labels.render(scene, camera);
875
  requestAnimationFrame(loop);
openenv/flood_openenv/web/twin/basin.json.gz CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:fa06124fbe0d870d2aeb6ff896048bc64dfbb56aca507a6debca19efd70769bc
3
- size 779515
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7b966b5ec74091d31e514ebaae51db7d04ed74d492d4b4f01632ae4f37a59daa
3
+ size 1327332
openenv/flood_openenv/web/twin/basin_imagery.jpg ADDED

Git LFS Details

  • SHA256: 1e55320f13dbb6e2e9ce3345804157ee76158df78731cb783033a325a9bad197
  • Pointer size: 132 Bytes
  • Size of remote file: 1.95 MB
openenv/flood_openenv/web/twin/index.html CHANGED
@@ -36,6 +36,10 @@
36
  </div>
37
  <div class="cams" role="group" aria-label="Camera">
38
  <button id="cam-basin" class="on" title="The whole basin (B)">Basin</button>
 
 
 
 
39
  <select id="goto" aria-label="Go to"><option value="">Go to…</option></select>
40
  </div>
41
  <button id="panels" title="Hide or show the panels (H)">Panels</button>
@@ -63,7 +67,7 @@
63
  <footer id="bottom" class="panel">
64
  <input id="scrub" type="range" min="0" max="29" step="0.01" value="0" aria-label="Time">
65
  <div id="charts"></div>
66
- <div class="credit">Terrain: USGS 3DEP · Rivers and lakes: USGS NHD · Dams: USACE CWMS · Gauges and flood stages: NOAA NWS ·
67
  Flows and storage: the grader's own simulation of this plan on the 2025 record</div>
68
  </footer>
69
 
 
36
  </div>
37
  <div class="cams" role="group" aria-label="Camera">
38
  <button id="cam-basin" class="on" title="The whole basin (B)">Basin</button>
39
+ <button id="cam-top" title="Straight down, like a map (T)">Top</button>
40
+ <button id="cam-dam" title="Close to a dam; press again for the next (D)">Dam</button>
41
+ <button id="cam-gauge" title="Low over a flood gauge; press again for the next (G)">Gauge</button>
42
+ <button id="cam-fly" title="Fly down the Cumberland from Wolf Creek to Nashville (F)">Flyover</button>
43
  <select id="goto" aria-label="Go to"><option value="">Go to…</option></select>
44
  </div>
45
  <button id="panels" title="Hide or show the panels (H)">Panels</button>
 
67
  <footer id="bottom" class="panel">
68
  <input id="scrub" type="range" min="0" max="29" step="0.01" value="0" aria-label="Time">
69
  <div id="charts"></div>
70
+ <div class="credit">Imagery: USGS The National Map (USDA NAIP) · Terrain: USGS 3DEP · Rivers and lakes: USGS NHD · Dams: USACE CWMS · Gauges and flood stages: NOAA NWS ·
71
  Flows and storage: the grader's own simulation of this plan on the 2025 record</div>
72
  </footer>
73