Prompt specification
Build or customize the Three.js 3D scene "Coarse and fine river grids" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Coarse and fine river grids
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/coarse-and-fine-river-grids-x1302
Scene Description Prompt:
A terrain cutaway overlays coarse and fine grids on one river, highlighting bends lost at lower resolution. Three.js from cdnjs; one HTML file.
Working Three.js Starter (coarse-and-fine-river-grids-x1302):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Resolution Changes the River</title>
<style>
:root {
--bg: #07131b;
--panel: rgba(8, 22, 30, 0.82);
--line: rgba(177, 224, 231, 0.16);
--text: #e6f3f3;
--muted: #8da8ad;
--cyan: #70e4e8;
--amber: #ffbd63;
--green: #83c69a;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
body.dragging #scene canvas {
cursor: grabbing;
}
.vignette {
position: fixed;
inset: 0;
z-index: 2;
pointer-events: none;
background:
radial-gradient(circle at 52% 44%, transparent 38%, rgba(2, 8, 12, 0.22) 78%),
linear-gradient(180deg, rgba(3, 10, 14, 0.12), transparent 22%, transparent 74%, rgba(3, 10, 14, 0.28));
}
.intro {
position: fixed;
top: 30px;
left: 34px;
z-index: 5;
width: min(430px, calc(100vw - 68px));
pointer-events: none;
}
.eyebrow {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 14px;
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.2em;
text-transform: uppercase;
}
.eyebrow::before {
width: 29px;
height: 1px;
content: "";
background: var(--cyan);
box-shadow: 0 0 10px rgba(112, 228, 232, 0.7);
}
h1 {
max-width: 420px;
margin: 0;
font-size: clamp(34px, 4.1vw, 62px);
font-weight: 530;
line-height: 0.98;
letter-spacing: -0.052em;
text-wrap: balance;
}
h1 em {
color: var(--amber);
font-style: normal;
font-weight: 430;
}
.intro p {
max-width: 360px;
margin: 18px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.65;
}
.panel {
position: fixed;
top: 28px;
right: 28px;
z-index: 6;
width: 272px;
padding: 17px;
border: 1px solid var(--line);
border-radius: 14px;
background: var(--panel);
box-shadow: 0 22px 65px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(18px) saturate(120%);
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 13px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.live-dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 10px rgba(131, 198, 154, 0.8);
}
.mode-switch {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 3px;
margin-bottom: 14px;
padding: 3px;
border: 1px solid rgba(255, 255, 255, 0.06);
border-radius: 8px;
background: rgba(0, 0, 0, 0.16);
}
.mode-switch button {
padding: 8px 4px;
border: 0;
border-radius: 5px;
color: var(--muted);
background: transparent;
cursor: pointer;
font-size: 10px;
transition: 160ms ease;
}
.mode-switch button:hover {
color: var(--text);
}
.mode-switch button.active {
color: #07131b;
background: var(--cyan);
box-shadow: 0 3px 12px rgba(112, 228, 232, 0.18);
font-weight: 700;
}
.layer-list {
display: grid;
gap: 6px;
}
.layer-toggle {
display: grid;
grid-template-columns: 13px 1fr auto;
align-items: center;
gap: 9px;
width: 100%;
padding: 10px 9px;
border: 1px solid rgba(255, 255, 255, 0.055);
border-radius: 8px;
color: var(--muted);
background: rgba(255, 255, 255, 0.025);
cursor: pointer;
text-align: left;
transition: 160ms ease;
}
.layer-toggle:hover {
border-color: rgba(255, 255, 255, 0.12);
color: var(--text);
}
.layer-toggle.active {
color: var(--text);
background: rgba(255, 255, 255, 0.055);
}
.swatch {
width: 9px;
height: 9px;
border-radius: 2px;
}
.swatch.cyan {
background: var(--cyan);
box-shadow: 0 0 9px rgba(112, 228, 232, 0.55);
}
.swatch.amber {
background: var(--amber);
box-shadow: 0 0 9px rgba(255, 189, 99, 0.55);
}
.swatch.flow {
border: 1px solid var(--cyan);
border-radius: 50%;
background: rgba(112, 228, 232, 0.12);
}
.layer-toggle strong {
display: block;
font-size: 11px;
font-weight: 600;
}
.layer-toggle small {
display: block;
margin-top: 2px;
color: #708b91;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 8px;
letter-spacing: 0.08em;
}
.layer-toggle .cell-size {
color: #708b91;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
}
.panel-rule {
height: 1px;
margin: 15px 0;
background: var(--line);
}
.readout {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 15px;
}
.readout span {
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 8px;
letter-spacing: 0.14em;
line-height: 1.6;
}
.readout b {
color: var(--amber);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 23px;
font-weight: 500;
letter-spacing: -0.05em;
}
.controls-note {
margin: 15px 0 0;
color: #708b91;
font-size: 9px;
line-height: 1.55;
}
.reset-button {
width: 100%;
margin-top: 11px;
padding: 8px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 7px;
color: var(--muted);
background: transparent;
cursor: pointer;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
letter-spacing: 0.1em;
text-transform: uppercase;
transition: 160ms ease;
}
.reset-button:hover {
color: var(--text);
border-color: rgba(255, 255, 255, 0.18);
}
.legend {
position: fixed;
bottom: 28px;
left: 34px;
z-index: 5;
display: grid;
gap: 10px;
pointer-events: none;
}
.legend-title {
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.legend-items {
display: flex;
flex-wrap: wrap;
gap: 10px 18px;
}
.legend-item {
display: flex;
align-items: center;
gap: 8px;
color: #a8bdc0;
font-size: 10px;
}
.line-key {
width: 20px;
height: 2px;
border-radius: 2px;
}
.line-key.fine {
background: var(--cyan);
box-shadow: 0 0 8px rgba(112, 228, 232, 0.4);
}
.line-key.coarse {
height: 3px;
background: var(--amber);
box-shadow: 0 0 8px rgba(255, 189, 99, 0.4);
}
.line-key.sample {
width: 8px;
height: 8px;
border: 1px solid var(--amber);
background: rgba(255, 189, 99, 0.12);
transform: rotate(45deg);
}
.stats {
position: fixed;
right: 30px;
bottom: 28px;
z-index: 5;
display: flex;
gap: 28px;
pointer-events: none;
}
.stat {
min-width: 78px;
}
.stat span {
display: block;
margin-bottom: 5px;
color: #708b91;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 8px;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.stat b {
color: var(--text);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 17px;
font-weight: 500;
}
.stat b.amber {
color: var(--amber);
}
#worldCallout {
position: fixed;
z-index: 5;
opacity: 0;
pointer-events: none;
transform: translate(-50%, calc(-100% - 24px));
transition: opacity 180ms ease;
}
#worldCallout.visible {
opacity: 1;
}
.callout-card {
min-width: 158px;
padding: 10px 12px;
border: 1px solid rgba(255, 189, 99, 0.35);
border-radius: 8px;
background: rgba(10, 23, 29, 0.88);
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(12px);
}
.callout-card span {
display: block;
color: var(--amber);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 7px;
font-weight: 700;
letter-spacing: 0.15em;
}
.callout-card strong {
display: block;
margin-top: 4px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 20px;
font-weight: 500;
letter-spacing: -0.04em;
}
.callout-card small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 8px;
}
#worldCallout::after {
position: absolute;
bottom: -25px;
left: 50%;
width: 1px;
height: 25px;
content: "";
background: linear-gradient(var(--amber), rgba(255, 189, 99, 0.2));
}
#worldCallout::before {
position: absolute;
bottom: -28px;
left: calc(50% - 3px);
width: 6px;
height: 6px;
border: 1px solid var(--amber);
border-radius: 50%;
content: "";
background: #0b1a20;
box-shadow: 0 0 10px rgba(255, 189, 99, 0.65);
}
@media (max-width: 780px) {
.intro {
top: 18px;
left: 18px;
}
.intro p {
display: none;
}
h1 {
max-width: 320px;
font-size: 37px;
}
.panel {
top: 145px;
right: 12px;
width: 220px;
padding: 12px;
}
.layer-toggle {
padding: 8px;
}
.legend {
bottom: 14px;
left: 18px;
}
.legend-items {
gap: 8px 12px;
}
.stats,
#worldCallout {
display: none;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="vignette"></div>
<header class="intro">
<div class="eyebrow">Hydrology / Grid Study 04</div>
<h1>Resolution changes<br />the <em>river.</em></h1>
<p>
One cutaway terrain, sampled at two densities. The coarse reconstruction
preserves the valley but cuts across its sharpest meanders.
</p>
</header>
<aside class="panel">
<div class="panel-heading">
<span>Comparison layers</span>
<i class="live-dot"></i>
</div>
<div class="mode-switch" aria-label="Grid comparison mode">
<button class="active" data-mode="both" aria-pressed="true">Overlay</button>
<button data-mode="fine" aria-pressed="false">Fine</button>
<button data-mode="coarse" aria-pressed="false">Coarse</button>
</div>
<div class="layer-list">
<button class="layer-toggle active" data-group="fine" aria-pressed="true">
<i class="swatch cyan"></i>
<span>
<strong>Fine grid + trace</strong>
<small>continuous centerline</small>
</span>
<span class="cell-size">16 m</span>
</button>
<button class="layer-toggle active" data-group="coarse" aria-pressed="true">
<i class="swatch amber"></i>
<span>
<strong>Coarse grid + trace</strong>
<small>straight-cell reconstruction</small>
</span>
<span class="cell-size">48 m</span>
</button>
<button class="layer-toggle active" data-group="flow" aria-pressed="true">
<i class="swatch flow"></i>
<span>
<strong>Flow particles</strong>
<small>downstream direction</small>
</span>
<span class="cell-size">LIVE</span>
</button>
</div>
<div class="panel-rule"></div>
<div class="readout">
<span>Maximum centerline<br />offset</span>
<b id="errorReadout">—</b>
</div>
<p class="controls-note">
Drag to orbit · Shift-drag to pan<br />
Scroll to zoom · Press R to reset
</p>
<button class="reset-button" id="resetView">Reset camera</button>
</aside>
<div class="legend">
<div class="legend-title">Sampling comparison</div>
<div class="legend-items">
<div class="legend-item">
<i class="line-key fine"></i>
16 m fine grid
</div>
<div class="legend-item">
<i class="line-key coarse"></i>
48 m coarse grid
</div>
<div class="legend-item">
<i class="line-key sample"></i>
coarse sample node
</div>
</div>
</div>
<div class="stats">
<div class="stat">
<span>Grid ratio</span>
<b>3 : 1</b>
</div>
<div class="stat">
<span>Detected bends</span>
<b id="bendReadout">—</b>
</div>
<div class="stat">
<span>Vertical cut</span>
<b>24 m</b>
</div>
</div>
<div id="worldCallout">
<div class="callout-card">
<span>Maximum centerline offset</span>
<strong id="calloutError">—</strong>
<small>fine path vs. coarse chord</small>
</div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const sceneHost = document.getElementById("scene");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07131b);
scene.fog = new THREE.FogExp2(0x07131b, 0.0155);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
180
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute(
"aria-label",
"Interactive cutaway terrain comparing fine and coarse river grids"
);
sceneHost.appendChild(renderer.domElement);
const world = new THREE.Group();
scene.add(world);
const fineGroup = new THREE.Group();
const coarseGroup = new THREE.Group();
const flowGroup = new THREE.Group();
world.add(fineGroup, coarseGroup, flowGroup);
const WIDTH = 38;
const DEPTH = 18;
const X0 = -WIDTH / 2;
const X1 = WIDTH / 2;
const Z0 = -DEPTH / 2;
const Z1 = DEPTH / 2;
const FLOOR_Y = -2.4;
const FINE_SPACING = 1.5833333333;
const COARSE_SPACING = 4.75;
const METERS_PER_UNIT = 10;
const colors = {
fine: 0x70e4e8,
coarse: 0xffbd63,
land: 0x55765a,
high: 0x7c8b68,
sand: 0xb69b6d
};
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
function smoothstep(min, max, value) {
const x = clamp((value - min) / (max - min), 0, 1);
return x * x * (3 - 2 * x);
}
function riverZ(x) {
return (
2.15 * Math.sin(x * 0.42 + 0.15) +
1.05 * Math.sin(x * 0.9 + 0.8)
);
}
function riverSlope(x) {
const e = 0.025;
return (riverZ(x + e) - riverZ(x - e)) / (2 * e);
}
function valleyFloor(x) {
return 0.18 + 0.015 * x + 0.08 * Math.sin(x * 0.25);
}
function waterY(x) {
return valleyFloor(x) + 0.07;
}
function terrainHeight(x, z) {
const distance = Math.abs(z - riverZ(x));
const valley = Math.pow(clamp(distance / 7.4, 0, 1), 1.46) * 1.45;
const roughness =
(Math.sin(x * 0.72 + z * 0.83) * 0.12 +
Math.cos(z * 1.72 - x * 0.31) * 0.075) *
smoothstep(0.4, 5.8, distance);
return valleyFloor(x) + valley + roughness;
}
function coarseXNodes() {
const nodes = [];
for (let i = 0; i < 9; i++) {
nodes.push(X0 + i * COARSE_SPACING);
}
return nodes;
}
function coarseZAt(x) {
const nodes = coarseXNodes();
if (x <= nodes[0]) return riverZ(nodes[0]);
if (x >= nodes[nodes.length - 1]) {
return riverZ(nodes[nodes.length - 1]);
}
for (let i = 0; i < nodes.length - 1; i++) {
const a = nodes[i];
const b = nodes[i + 1];
if (x >= a && x <= b) {
const t = (x - a) / (b - a);
return THREE.MathUtils.lerp(riverZ(a), riverZ(b), t);
}
}
return riverZ(x);
}
function countBends() {
let bends = 0;
let previousSign = 0;
for (let x = X0 + 0.2; x < X1 - 0.2; x += 0.18) {
const slope = riverZ(x + 0.12) - riverZ(x - 0.12);
const sign = Math.sign(slope);
if (sign !== 0) {
if (previousSign !== 0 && sign !== previousSign) bends++;
previousSign = sign;
}
}
return bends;
}
let maxOffsetX = 0;
let maxOffset = 0;
for (let x = X0 + 0.15; x < X1 - 0.15; x += 0.08) {
const offset = Math.abs(riverZ(x) - coarseZAt(x));
if (offset > maxOffset) {
maxOffset = offset;
maxOffsetX = x;
}
}
const maxOffsetMeters = Math.round(maxOffset * METERS_PER_UNIT);
const bendCount = countBends();
document.getElementById("errorReadout").textContent = `${maxOffsetMeters} m`;
document.getElementById("calloutError").textContent = `${maxOffsetMeters} m`;
document.getElementById("bendReadout").textContent = String(bendCount);
const calloutAnchor = new THREE.Vector3(
maxOffsetX,
waterY(maxOffsetX) + 0.72,
riverZ(maxOffsetX)
);
// Lighting
scene.add(new THREE.HemisphereLight(0xb9e9ff, 0x182119, 1.75));
const sun = new THREE.DirectionalLight(0xffe3b7, 3.1);
sun.position.set(8, 20, 13);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -28;
sun.shadow.camera.right = 28;
sun.shadow.camera.top = 24;
sun.shadow.camera.bottom = -24;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 65;
sun.shadow.bias = -0.00035;
sun.shadow.normalBias = 0.025;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x62caff, 1.15);
rimLight.position.set(-17, 9, -13);
scene.add(rimLight);
const riverLight = new THREE.PointLight(0x38d7e0, 14, 18, 2);
riverLight.position.set(0, 3.5, riverZ(0));
scene.add(riverLight);
// Terrain surface
function createTerrain() {
const nx = 150;
const nz = 72;
const positions = [];
const colorsArray = [];
const uvs = [];
const indices = [];
const grass = new THREE.Color(colors.land);
const high = new THREE.Color(colors.high);
const sand = new THREE.Color(colors.sand);
const color = new THREE.Color();
for (let iz = 0; iz <= nz; iz++) {
const z = THREE.MathUtils.lerp(Z0, Z1, iz / nz);
for (let ix = 0; ix <= nx; ix++) {
const x = THREE.MathUtils.lerp(X0, X1, ix / nx);
const y = terrainHeight(x, z);
const distance = Math.abs(z - riverZ(x));
positions.push(x, y, z);
uvs.push(ix / nx, iz / nz);
if (distance < 2.05) {
color.copy(sand).lerp(grass, smoothstep(1.15, 2.45, distance));
} else {
color.copy(grass).lerp(high, clamp((y - 0.35) / 1.65, 0, 1));
}
const variation =
0.91 +
0.07 * Math.sin(x * 0.83 + z * 1.31) +
0.035 * Math.cos(z * 2.1 - x * 0.46);
color.multiplyScalar(variation);
colorsArray.push(color.r, color.g, color.b);
}
}
for (let iz = 0; iz < nz; iz++) {
for (let ix = 0; ix < nx; ix++) {
const a = iz * (nx + 1) + ix;
const b = a + 1;
const c = a + nx + 1;
const d = c + 1;
indices.push(a, c, b, b, c, d);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute("color", new THREE.Float32BufferAttribute(colorsArray, 3));
geometry.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2));
geometry.setIndex(indices);
geometry.computeVertexNormals();
const material = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.94,
metalness: 0.02
});
const mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
world.add(mesh);
}
createTerrain();
// Geological cutaway walls
function createWall(points) {
const positions = [];
const colorsArray = [];
const palette = [
new THREE.Color(0x263b3f),
new THREE.Color(0x485149),
new THREE.Color(0x715f4c),
new THREE.Color(0x947154),
new THREE.Color(0xbd9466)
];
const bandTops = [-1.85, -1.25, -0.7, -0.35];
function addTriangle(a, b, c, color) {
positions.push(...a, ...b, ...c);
for (let i = 0; i < 3; i++) colorsArray.push(color.r, color.g, color.b);
}
for (let i = 0; i < points.length - 1; i++) {
const p0 = points[i];
const p1 = points[i + 1];
for (let band = 0; band < 5; band++) {
const bottom = band === 0 ? FLOOR_Y : bandTops[band - 1];
const top = band < 4 ? bandTops[band] : p0.y;
if (top <= bottom) continue;
const color = palette[band].clone();
color.multiplyScalar(
0.92 + 0.06 * Math.sin(p0.x * 0.51 + p0.z * 0.8 + band)
);
const a = [p0.x, bottom, p0.z];
const b = [p1.x, bottom, p1.z];
const c = [p0.x, top, p0.z];
const d = [p1.x, top, p1.z];
addTriangle(a, b, c, color);
addTriangle(b, d, c, color);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(colorsArray, 3)
);
geometry.computeVertexNormals();
const mesh = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 1,
side: THREE.DoubleSide
})
);
mesh.castShadow = true;
mesh.receiveShadow = true;
world.add(mesh);
}
const boundarySegments = 100;
const front = [];
const back = [];
const north = [];
const south = [];
for (let i = 0; i <= boundarySegments; i++) {
const z = THREE.MathUtils.lerp(Z0, Z1, i / boundarySegments);
front.push({ x: X1, z, y: terrainHeight(X1, z) });
back.push({ x: X0, z, y: terrainHeight(X0, z) });
}
for (let i = 0; i <= boundarySegments; i++) {
const x = THREE.MathUtils.lerp(X0, X1, i / boundarySegments);
north.push({ x, z: Z1, y: terrainHeight(x, Z1) });
south.push({ x, z: Z0, y: terrainHeight(x, Z0) });
}
createWall(front);
createWall(back);
createWall(north);
createWall(south);
// Crisp top edge
const edgePoints = [];
for (const point of front) edgePoints.push(new THREE.Vector3(point.x, point.y + 0.025, point.z));
for (const point of north) edgePoints.push(new THREE.Vector3(point.x, point.y + 0.025, point.z));
for (let i = back.length - 1; i >= 0; i--) {
edgePoints.push(new THREE.Vector3(back[i].x, back[i].y + 0.025, back[i].z));
}
for (let i = south.length - 1; i >= 0; i--) {
edgePoints.push(new THREE.Vector3(south[i].x, south[i].y + 0.025, south[i].z));
}
const edgeGeometry = new THREE.BufferGeometry().setFromPoints(edgePoints);
const edge = new THREE.LineLoop(
edgeGeometry,
new THREE.LineBasicMaterial({
color: 0xc7ddd1,
transparent: true,
opacity: 0.42
})
);
world.add(edge);
// Base plinth
const plinth = new THREE.Mesh(
new THREE.BoxGeometry(WIDTH + 0.45, 0.14, DEPTH + 0.45),
new THREE.MeshStandardMaterial({
color: 0x101d23,
roughness: 0.86,
metalness: 0.1
})
);
plinth.position.y = FLOOR_Y - 0.07;
plinth.receiveShadow = true;
plinth.castShadow = true;
world.add(plinth);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(140, 110),
new THREE.MeshStandardMaterial({
color: 0x071117,
roughness: 1
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = FLOOR_Y - 0.15;
ground.receiveShadow = true;
world.add(ground);
// Draped terrain ribbons
function createTerrainRibbon(halfWidth, segments, colorA, colorB) {
const positions = [];
const uvs = [];
const colorsArray = [];
const indices = [];
const color = new THREE.Color();
for (let i = 0; i <= segments; i++) {
const x = THREE.MathUtils.lerp(X0, X1, i / segments);
const z = riverZ(x);
const slope = riverSlope(x);
const normal = new THREE.Vector2(-slope, 1).normalize();
for (let side = 0; side < 2; side++) {
const sign = side === 0 ? -1 : 1;
const px = x + normal.x * halfWidth * sign;
const pz = z + normal.y * halfWidth * sign;
const py = terrainHeight(px, pz) + 0.022;
positions.push(px, py, pz);
uvs.push(i / segments, side);
color.copy(colorA).lerp(colorB, 0.25 + 0.2 * Math.sin(x * 0.7));
colorsArray.push(color.r, color.g, color.b);
}
}
for (let i = 0; i < segments; i++) {
const a = i * 2;
const b = a + 1;
const c = a + 2;
const d = a + 3;
indices.push(a, b, c, b, d, c);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2));
geometry.setAttribute("color", new THREE.Float32BufferAttribute(colorsArray, 3));
geometry.setIndex(indices);
geometry.computeVertexNormals();
const mesh = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.9,
side: THREE.DoubleSide
})
);
mesh.receiveShadow = true;
return mesh;
}
world.add(
createTerrainRibbon(
1.95,
220,
new THREE.Color(0xc5aa76),
new THREE.Color(0x8d805f)
)
);
// Water ribbon with a lightweight animated shader
function createWater() {
const segments = 240;
const positions = [];
const uvs = [];
const indices = [];
for (let i = 0; i <= segments; i++) {
const u = i / segments;
const x = THREE.MathUtils.lerp(X0 - 0.08, X1 + 0.08, u);
const z = riverZ(x);
const slope = riverSlope(x);
const normal = new THREE.Vector2(-slope, 1).normalize();
const halfWidth = 0.82;
for (let side = 0; side < 2; side++) {
const sign = side === 0 ? -1 : 1;
positions.push(
x + normal.x * halfWidth * sign,
waterY(x),
z + normal.y * halfWidth * sign
);
uvs.push(u, side);
}
}
for (let i = 0; i < segments; i++) {
const a = i * 2;
const b = a + 1;
const c = a + 2;
const d = a + 3;
indices.push(a, c, b, b, c, d);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2));
geometry.setIndex(indices);
geometry.computeVertexNormals();
const material = new THREE.ShaderMaterial({
transparent: true,
depthWrite: true,
side: THREE.DoubleSide,
uniforms: {
uTime: { value: 0 },
uDeep: { value: new THREE.Color(0x075266) },
uShallow: { value: new THREE.Color(0x20a6ad) },
uFoam: { value: new THREE.Color(0xbffbf0) }
},
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
uniform float uTime;
uniform vec3 uDeep;
uniform vec3 uShallow;
uniform vec3 uFoam;
varying vec2 vUv;
void main() {
float across = abs(vUv.y - 0.5) * 2.0;
float wave = sin(vUv.x * 260.0 - uTime * 5.2 + sin(vUv.x * 71.0) * 2.0);
float glint = pow(max(wave, 0.0), 12.0);
float band = 0.5 + 0.5 * sin(vUv.x * 54.0 - uTime * 1.3);
vec3 color = mix(uDeep, uShallow, 0.35 + band * 0.16);
color += uFoam * glint * 0.34;
float edge = 1.0 - smoothstep(0.72, 1.0, across);
color *= mix(0.72, 1.0, edge);
gl_FragColor = vec4(color, 0.96);
#include <tonemapping_fragment>
#include <colorspace_fragment>
}
`
});
const mesh = new THREE.Mesh(geometry, material);
mesh.renderOrder = 3;
world.add(mesh);
return material;
}
const waterMaterial = createWater();
// Exposed water cross-section at the front cut
const section = new THREE.Mesh(
new THREE.PlaneGeometry(1.64, 0.24),
new THREE.MeshBasicMaterial({
color: 0x39c4cb,
transparent: true,
opacity: 0.94,
side: THREE.DoubleSide
})
);
section.rotation.y = Math.PI / 2;
section.position.set(X1 + 0.018, valleyFloor(X1) - 0.025, riverZ(X1));
world.add(section);
// Draped grid lines
function createDrapedGrid(spacing, color, opacity) {
const positions = [];
const halfWidth = WIDTH / 2;
function addSegment(x1, z1, x2, z2) {
positions.push(
x1,
terrainHeight(x1, z1) + 0.042,
z1,
x2,
terrainHeight(x2, z2) + 0.042,
z2
);
}
for (let x = -halfWidth; x <= halfWidth + 0.001; x += spacing) {
let previousZ = Z0;
for (let i = 1; i <= 100; i++) {
const z = THREE.MathUtils.lerp(Z0, Z1, i / 100);
addSegment(x, previousZ, x, z);
previousZ = z;
}
}
for (let z = Z0; z <= Z1 + 0.001; z += spacing) {
let previousX = X0;
for (let i = 1; i <= 180; i++) {
const x = THREE.MathUtils.lerp(X0, X1, i / 180);
addSegment(previousX, z, x, z);
previousX = x;
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
const material = new THREE.LineBasicMaterial({
color,
transparent: true,
opacity,
depthWrite: false
});
const grid = new THREE.LineSegments(geometry, material);
grid.renderOrder = 2;
return grid;
}
fineGroup.add(
createDrapedGrid(FINE_SPACING, colors.fine, 0.115)
);
coarseGroup.add(
createDrapedGrid(COARSE_SPACING, colors.coarse, 0.43)
);
// Fine continuous river centerline
const finePathPoints = [];
for (let i = 0; i <= 140; i++) {
const x = THREE.MathUtils.lerp(X0 + 0.1, X1 - 0.1, i / 140);
finePathPoints.push(
new THREE.Vector3(x, waterY(x) + 0.14, riverZ(x))
);
}
const fineCurve = new THREE.CatmullRomCurve3(
finePathPoints,
false,
"centripetal"
);
const fineGlow = new THREE.Mesh(
new THREE.TubeGeometry(fineCurve, 260, 0.075, 5, false),
new THREE.MeshBasicMaterial({
color: colors.fine,
transparent: true,
opacity: 0.14,
depthTest: false,
depthWrite: false
})
);
fineGlow.renderOrder = 8;
fineGroup.add(fineGlow);
const fineTrace = new THREE.Mesh(
new THREE.TubeGeometry(fineCurve, 260, 0.027, 5, false),
new THREE.MeshBasicMaterial({
color: 0xa4ffff,
depthTest: false,
depthWrite: false
})
);
fineTrace.renderOrder = 9;
fineGroup.add(fineTrace);
// Coarse polyline: straight chords between widely spaced samples
const coarseNodes = coarseXNodes();
const coarseMaterial = new THREE.MeshBasicMaterial({
color: colors.coarse,
transparent: true,
opacity: 0.96,
depthTest: false,
depthWrite: false
});
const up = new THREE.Vector3(0, 1, 0);
const segmentGeometry = new THREE.CylinderGeometry(0.068, 0.068, 1, 7);
for (let i = 0; i < coarseNodes.length - 1; i++) {
const xa = coarseNodes[i];
const xb = coarseNodes[i + 1];
const a = new THREE.Vector3(xa, waterY(xa) + 0.19, riverZ(xa));
const b = new THREE.Vector3(xb, waterY(xb) + 0.19, riverZ(xb));
const direction = b.clone().sub(a);
const length = direction.length();
const segment = new THREE.Mesh(segmentGeometry, coarseMaterial);
segment.position.copy(a).add(b).multiplyScalar(0.5);
segment.quaternion.setFromUnitVectors(up, direction.normalize());
segment.scale.y = length;
segment.renderOrder = 11;
coarseGroup.add(segment);
}
const nodeGeometry = new THREE.OctahedronGeometry(0.12, 0);
for (const x of coarseNodes) {
const node = new THREE.Mesh(nodeGeometry, coarseMaterial);
node.position.set(x, waterY(x) + 0.21, riverZ(x));
node.renderOrder = 12;
coarseGroup.add(node);
}
// Highlight the coarse cell containing the largest bend error
function createCoarseHighlight() {
const cellIndex = Math.floor((maxOffsetX - X0) / COARSE_SPACING);
const x0 = X0 + cellIndex * COARSE_SPACING;
const x1 = Math.min(X1, x0 + COARSE_SPACING);
const riverCenter = riverZ(maxOffsetX);
const zIndex = Math.floor((riverCenter - Z0) / COARSE_SPACING);
const z0 = Z0 + zIndex * COARSE_SPACING;
const z1 = Math.min(Z1, z0 + COARSE_SPACING);
const nx = 22;
const nz = 12;
const positions = [];
const uvs = [];
const indices = [];
for (let iz = 0; iz <= nz; iz++) {
const z = THREE.MathUtils.lerp(z0, z1, iz / nz);
for (let ix = 0; ix <= nx; ix++) {
const x = THREE.MathUtils.lerp(x0, x1, ix / nx);
positions.push(x, terrainHeight(x, z) + 0.052, z);
uvs.push(ix / nx, iz / nz);
}
}
for (let iz = 0; iz < nz; iz++) {
for (let ix = 0; ix < nx; ix++) {
const a = iz * (nx + 1) + ix;
const b = a + 1;
const c = a + nx + 1;
const d = c + 1;
indices.push(a, c, b, b, c, d);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute("uv", new THREE.Float32BufferAttribute(uvs, 2));
geometry.setIndex(indices);
geometry.computeVertexNormals();
const patch = new THREE.Mesh(
geometry,
new THREE.MeshBasicMaterial({
color: colors.coarse,
transparent: true,
opacity: 0.11,
side: THREE.DoubleSide,
depthWrite: false
})
);
patch.renderOrder = 4;
coarseGroup.add(patch);
const outlinePoints = [];
const samples = 34;
for (let i = 0; i <= samples; i++) {
const x = THREE.MathUtils.lerp(x0, x1, i / samples);
outlinePoints.push(
new THREE.Vector3(x, terrainHeight(x, z0) + 0.065, z0)
);
}
for (let i = 0; i <= samples; i++) {
const z = THREE.MathUtils.lerp(z0, z1, i / samples);
outlinePoints.push(
new THREE.Vector3(x1, terrainHeight(x1, z) + 0.065, z)
);
}
for (let i = samples; i >= 0; i--) {
const x = THREE.MathUtils.lerp(x0, x1, i / samples);
outlinePoints.push(
new THREE.Vector3(x, terrainHeight(x, z1) + 0.065, z1)
);
}
for (let i = samples; i >= 0; i--) {
const z = THREE.MathUtils.lerp(z0, z1, i / samples);
outlinePoints.push(
new THREE.Vector3(x0, terrainHeight(x0, z) + 0.065, z)
);
}
const outlineGeometry = new THREE.BufferGeometry().setFromPoints(outlinePoints);
const outline = new THREE.LineLoop(
outlineGeometry,
new THREE.LineBasicMaterial({
color: colors.coarse,
transparent: true,
opacity: 0.62,
depthTest: false,
depthWrite: false
})
);
outline.renderOrder = 10;
coarseGroup.add(outline);
}
createCoarseHighlight();
// Offset bracket between the fine river and coarse chord
const actualZ = riverZ(maxOffsetX);
const reconstructedZ = coarseZAt(maxOffsetX);
const offsetY = waterY(maxOffsetX) + 0.31;
const offsetGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(maxOffsetX, offsetY, actualZ),
new THREE.Vector3(maxOffsetX, offsetY, reconstructedZ)
]);
const offsetLine = new THREE.Line(
offsetGeometry,
new THREE.LineDashedMaterial({
color: colors.coarse,
dashSize: 0.14,
gapSize: 0.1,
transparent: true,
opacity: 0.95,
depthTest: false,
depthWrite: false
})
);
offsetLine.computeLineDistances();
offsetLine.renderOrder = 13;
coarseGroup.add(offsetLine);
const tickGeometry = new THREE.BufferGeometry();
tickGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute([
maxOffsetX - 0.13, offsetY, actualZ,
maxOffsetX + 0.13, offsetY, actualZ,
maxOffsetX - 0.13, offsetY, reconstructedZ,
maxOffsetX + 0.13, offsetY, reconstructedZ
], 3)
);
const ticks = new THREE.LineSegments(
tickGeometry,
new THREE.LineBasicMaterial({
color: colors.coarse,
transparent: true,
opacity: 0.95,
depthTest: false,
depthWrite: false
})
);
ticks.renderOrder = 13;
coarseGroup.add(ticks);
// Flow particles
const flowCount = 72;
const flowPositions = new Float32Array(flowCount * 3);
const flowGeometry = new THREE.BufferGeometry();
flowGeometry.setAttribute(
"position",
new THREE.BufferAttribute(flowPositions, 3)
);
const flowMaterial = new THREE.PointsMaterial({
color: 0xd6ffff,
size: 0.085,
sizeAttenuation: true,
transparent: true,
opacity: 0.78,
depthWrite: false,
blending: THREE.AdditiveBlending
});
const flowPoints = new THREE.Points(flowGeometry, flowMaterial);
flowPoints.frustumCulled = false;
flowPoints.renderOrder = 7;
flowGroup.add(flowPoints);
// Direct camera controls, without examples or addons
const cameraState = {
azimuth: 0.72,
polar: 0.72,
radius: 35,
target: new THREE.Vector3(0, 0.1, 0)
};
const initialCamera = { ...cameraState };
function updateCamera() {
const { azimuth, polar, radius, target } = cameraState;
const horizontal = radius * Math.cos(polar);
camera.position.set(
target.x + horizontal * Math.sin(azimuth),
target.y + radius * Math.sin(polar),
target.z + horizontal * Math.cos(azimuth)
);
camera.lookAt(target);
camera.updateMatrixWorld();
}
updateCamera();
function resetCamera() {
cameraState.azimuth = initialCamera.azimuth;
cameraState.polar = initialCamera.polar;
cameraState.radius = initialCamera.radius;
cameraState.target.copy(initialCamera.target);
updateCamera();
}
const drag = {
active: false,
pan: false,
lastX: 0,
lastY: 0
};
renderer.domElement.addEventListener("pointerdown", (event) => {
drag.active = true;
drag.pan = event.shiftKey || event.button === 1 || event.button === 2;
drag.lastX = event.clientX;
drag.lastY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
document.body.classList.add("dragging");
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!drag.active) return;
const dx = event.clientX - drag.lastX;
const dy = event.clientY - drag.lastY;
drag.lastX = event.clientX;
drag.lastY = event.clientY;
if (drag.pan) {
camera.updateMatrixWorld();
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
const right = new THREE.Vector3()
.crossVectors(forward, camera.up)
.normalize();
const screenUp = new THREE.Vector3()
.crossVectors(right, forward)
.normalize();
const scale = cameraState.radius * 0.00135;
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(screenUp, dy * scale);
cameraState.target.y = clamp(cameraState.target.y, -1.5, 4);
} else {
cameraState.azimuth -= dx * 0.006;
cameraState.polar = clamp(
cameraState.polar + dy * 0.005,
0.18,
1.38
);
}
updateCamera();
});
function endDrag(event) {
drag.active = false;
document.body.classList.remove("dragging");
if (event.pointerId !== undefined && renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener("contextmenu", (event) => event.preventDefault());
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
17,
65
);
updateCamera();
},
{ passive: false }
);
window.addEventListener("keydown", (event) => {
if (event.key.toLowerCase() === "r") resetCamera();
});
document.getElementById("resetView").addEventListener("click", resetCamera);
// UI visibility controls
const groups = {
fine: fineGroup,
coarse: coarseGroup,
flow: flowGroup
};
const groupButtons = [...document.querySelectorAll("[data-group]")];
const modeButtons = [...document.querySelectorAll("[data-mode]")];
function syncButtons() {
for (const button of groupButtons) {
const visible = groups[button.dataset.group].visible;
button.classList.toggle("active", visible);
button.setAttribute("aria-pressed", String(visible));
}
}
for (const button of groupButtons) {
button.addEventListener("click", () => {
const group = groups[button.dataset.group];
group.visible = !group.visible;
for (const modeButton of modeButtons) {
modeButton.classList.remove("active");
modeButton.setAttribute("aria-pressed", "false");
}
syncButtons();
});
}
for (const button of modeButtons) {
button.addEventListener("click", () => {
const mode = button.dataset.mode;
fineGroup.visible = mode === "both" || mode === "fine";
coarseGroup.visible = mode === "both" || mode === "coarse";
for (const modeButton of modeButtons) {
const active = modeButton === button;
modeButton.classList.toggle("active", active);
modeButton.setAttribute("aria-pressed", String(active));
}
syncButtons();
});
}
// Resize
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
// Animation
const clock = new THREE.Clock();
const projected = new THREE.Vector3();
const callout = document.getElementById("worldCallout");
function animate() {
const elapsed = clock.getElapsedTime();
waterMaterial.uniforms.uTime.value = elapsed;
const positionAttribute = flowGeometry.getAttribute("position");
for (let i = 0; i < flowCount; i++) {
const x =
X0 +
((i * 0.412 + elapsed * 1.65) % (X1 - X0));
positionAttribute.setXYZ(
i,
x,
waterY(x) + 0.095 + Math.sin(elapsed * 2 + i) * 0.006,
riverZ(x)
);
}
positionAttribute.needsUpdate = true;
projected.copy(calloutAnchor).project(camera);
const onScreen =
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.15 &&
Math.abs(projected.y) < 1.15;
if (onScreen) {
callout.style.left = `${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
callout.style.top = `${(-projected.y * 0.5 + 0.5) * window.innerHeight}px`;
callout.classList.add("visible");
} else {
callout.classList.remove("visible");
}
renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```