Prompt specification
Build or customize the Three.js 3D scene "Coastal Village and Wetland Diorama" 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: Coastal Village and Wetland Diorama
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/coastal-village-and-wetland-diorama-x3923
Scene Description Prompt:
Create an original voxel coastal village with tidal wetlands, varied land uses, and ecological connections. Three.js from cdnjs in standalone HTML.
Working Three.js Starter (coastal-village-and-wetland-diorama-x3923):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tidehaven Commons — A Living Voxel Coast</title>
<style>
:root {
--ink: #12373a;
--muted: #547477;
--paper: rgba(247, 242, 224, 0.9);
--paper-solid: #f7f2e0;
--line: rgba(24, 70, 72, 0.17);
--teal: #177f7c;
--mint: #83d9bc;
--coral: #ed8d68;
--gold: #e7bb62;
--navy: #183f4c;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #b9d8d4;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input { font: inherit; }
#scene {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 52% 48%, transparent 42%, rgba(20, 61, 66, 0.09) 100%),
linear-gradient(180deg, rgba(255,255,255,0.04), rgba(18,55,58,0.05));
}
.topbar {
position: fixed;
top: 24px;
left: 26px;
z-index: 10;
width: min(390px, calc(100vw - 52px));
pointer-events: none;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 10px;
color: #285d60;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--coral);
box-shadow: 0 0 0 5px rgba(237, 141, 104, 0.16);
}
h1 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(30px, 4vw, 52px);
font-weight: 500;
line-height: 0.98;
letter-spacing: -0.04em;
color: #16484b;
}
.subtitle {
max-width: 345px;
margin: 12px 0 0;
color: #426c6d;
font-size: 12px;
line-height: 1.55;
}
.panel {
background: var(--paper);
border: 1px solid rgba(255,255,255,0.58);
box-shadow: 0 16px 44px rgba(25, 66, 67, 0.13);
backdrop-filter: blur(15px) saturate(1.1);
-webkit-backdrop-filter: blur(15px) saturate(1.1);
}
.controls {
position: fixed;
z-index: 20;
top: 24px;
right: 26px;
width: 258px;
padding: 15px;
border-radius: 18px;
}
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
color: #315f61;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.live {
display: inline-flex;
align-items: center;
gap: 5px;
color: #438077;
letter-spacing: 0.08em;
}
.live::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: #57b89a;
animation: pulse 1.8s ease-in-out infinite;
}
@keyframes pulse {
50% { opacity: 0.3; transform: scale(0.75); }
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.button-row + .button-row { margin-top: 8px; }
.ui-button {
min-height: 39px;
padding: 8px 10px;
border: 1px solid var(--line);
border-radius: 11px;
color: #315f61;
background: rgba(255,255,255,0.54);
font-size: 11px;
font-weight: 750;
cursor: pointer;
transition: 160ms ease;
}
.ui-button:hover {
transform: translateY(-1px);
background: white;
border-color: rgba(23,127,124,0.35);
}
.ui-button.active {
color: white;
border-color: var(--teal);
background: var(--teal);
box-shadow: 0 5px 14px rgba(23,127,124,0.22);
}
.ui-button.wide { grid-column: 1 / -1; }
.tide-control {
margin-top: 14px;
padding-top: 13px;
border-top: 1px solid var(--line);
}
.tide-head {
display: flex;
justify-content: space-between;
margin-bottom: 8px;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#tideValue {
color: var(--teal);
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 5px 0;
appearance: none;
border-radius: 999px;
background: linear-gradient(90deg, #8eb9ae, #e7bb62, #e7bb62);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 16px;
height: 16px;
appearance: none;
border: 3px solid var(--paper-solid);
border-radius: 50%;
background: var(--teal);
box-shadow: 0 1px 5px rgba(16,62,63,0.25);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 3px solid var(--paper-solid);
border-radius: 50%;
background: var(--teal);
}
.range-ends {
display: flex;
justify-content: space-between;
margin-top: 5px;
color: #6d8889;
font-size: 9px;
}
.readout {
position: fixed;
z-index: 10;
left: 26px;
bottom: 25px;
width: 300px;
padding: 15px 17px;
border-radius: 17px;
pointer-events: none;
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}
.metric + .metric {
padding-left: 12px;
border-left: 1px solid var(--line);
}
.metric-value {
display: block;
color: #1d6666;
font-family: Georgia, serif;
font-size: 23px;
line-height: 1;
font-variant-numeric: tabular-nums;
}
.metric-label {
display: block;
margin-top: 5px;
color: #6a8384;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.1em;
line-height: 1.25;
text-transform: uppercase;
}
.legend {
position: fixed;
z-index: 10;
right: 26px;
bottom: 25px;
width: 258px;
padding: 14px 16px;
border-radius: 17px;
pointer-events: none;
}
.legend-title {
margin-bottom: 10px;
color: #315f61;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.legend-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px 12px;
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
color: #527173;
font-size: 9px;
font-weight: 650;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 2px;
box-shadow: inset 0 0 0 1px rgba(0,0,0,0.08);
}
.help {
position: fixed;
z-index: 8;
left: 50%;
bottom: 26px;
transform: translateX(-50%);
color: rgba(29, 80, 81, 0.78);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.06em;
text-transform: uppercase;
pointer-events: none;
white-space: nowrap;
}
#labels {
position: fixed;
inset: 0;
z-index: 5;
overflow: hidden;
pointer-events: none;
}
.map-label {
position: absolute;
left: 0;
top: 0;
display: flex;
align-items: center;
gap: 6px;
padding: 5px 8px;
border: 1px solid rgba(255,255,255,0.6);
border-radius: 7px;
color: #285e60;
background: rgba(250,247,232,0.82);
box-shadow: 0 5px 15px rgba(30,75,73,0.12);
backdrop-filter: blur(5px);
font-size: 8px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
white-space: nowrap;
will-change: transform;
}
.map-label::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--teal);
}
.map-label.habitat::before { background: #5c9976; }
.map-label.community::before { background: #e7a26e; }
.map-label.work::before { background: #dfbd62; }
.map-label.water::before { background: #49a5b0; }
.loading {
position: fixed;
inset: 0;
z-index: 100;
display: grid;
place-items: center;
color: #275f60;
background: #b9d8d4;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
transition: opacity 500ms ease;
}
.loading.hide { opacity: 0; pointer-events: none; }
@media (max-width: 850px) {
.topbar { top: 16px; left: 17px; }
.subtitle { max-width: 270px; }
.controls { top: 15px; right: 15px; width: 210px; padding: 12px; }
.readout { left: 15px; bottom: 15px; width: 245px; }
.legend { display: none; }
.help { display: none; }
}
@media (max-width: 620px) {
.topbar { width: calc(100vw - 34px); }
h1 { font-size: 31px; }
.subtitle { display: none; }
.controls {
top: auto;
right: 12px;
bottom: 12px;
width: 190px;
}
.readout {
left: 12px;
bottom: 12px;
width: 156px;
padding: 12px;
}
.metric-value { font-size: 18px; }
.metric-label { font-size: 7px; }
.map-label { font-size: 7px; }
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel coastal village"></canvas>
<div class="vignette"></div>
<div id="labels"></div>
<header class="topbar">
<div class="eyebrow">A living coast in blocks</div>
<h1>Tidehaven<br>Commons</h1>
<p class="subtitle">
A coastal commons shaped by saltmarsh, working water, shared gardens,
and paths that let the tide—and life—move inland.
</p>
</header>
<section class="controls panel" aria-label="Scene controls">
<div class="panel-title">
<span>Coast controls</span>
<span class="live">Live model</span>
</div>
<div class="button-row">
<button id="tideButton" class="ui-button" aria-pressed="false">Pause tide</button>
<button id="lensButton" class="ui-button" aria-pressed="false">Ecology lens</button>
</div>
<div class="button-row">
<button id="resetButton" class="ui-button wide">Reset camera</button>
</div>
<div class="tide-control">
<div class="tide-head">
<span>Tidal offset</span>
<span id="tideValue">+0.00 m</span>
</div>
<input id="tideSlider" type="range" min="-0.25" max="0.25" step="0.01" value="0"
aria-label="Tidal offset">
<div class="range-ends">
<span>Low water</span>
<span>High water</span>
</div>
</div>
</section>
<section class="readout panel" aria-label="Live coastal readings">
<div class="metrics">
<div class="metric">
<span id="waterMetric" class="metric-value">+0.18</span>
<span class="metric-label">Water level<br>metres</span>
</div>
<div class="metric">
<span id="edgeMetric" class="metric-value">128</span>
<span class="metric-label">Tidal edge<br>voxels</span>
</div>
<div class="metric">
<span id="habitatMetric" class="metric-value">82%</span>
<span class="metric-label">Habitat<br>link score</span>
</div>
</div>
</section>
<section class="legend panel" aria-label="Land use legend">
<div class="legend-title">Shared coastal mosaic</div>
<div class="legend-grid">
<div class="legend-item"><i class="swatch" style="background:#e9956f"></i>Homes</div>
<div class="legend-item"><i class="swatch" style="background:#e5bd61"></i>Commons & work</div>
<div class="legend-item"><i class="swatch" style="background:#72a66f"></i>Gardens</div>
<div class="legend-item"><i class="swatch" style="background:#5c9976"></i>Saltmarsh</div>
<div class="legend-item"><i class="swatch" style="background:#4da2ad"></i>Tidal water</div>
<div class="legend-item"><i class="swatch" style="background:#b8d393"></i>Upland habitat</div>
</div>
</section>
<div class="help">Drag to orbit · Shift-drag to pan · Scroll to zoom · Double-click to focus</div>
<div id="loading" class="loading">Building the coast…</div>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
/* --------------------------------------------------------------------------
Tidehaven Commons
All geometry, materials, terrain, controls, and animation are procedural.
No external assets or Three.js addons are used.
--------------------------------------------------------------------------- */
const canvas = document.querySelector('#scene');
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: 'high-performance'
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.8));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.13;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color('#b9d8d4');
scene.fog = new THREE.Fog('#b9d8d4', 58, 115);
const camera = new THREE.OrthographicCamera(-30, 30, 20, -20, 0.1, 220);
const hemi = new THREE.HemisphereLight('#e9f3dc', '#456e70', 2.1);
scene.add(hemi);
const sun = new THREE.DirectionalLight('#fff1c7', 3.0);
sun.position.set(-28, 42, 25);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -36;
sun.shadow.camera.right = 36;
sun.shadow.camera.top = 32;
sun.shadow.camera.bottom = -32;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 90;
sun.shadow.bias = -0.0007;
sun.shadow.normalBias = 0.025;
scene.add(sun);
const fill = new THREE.DirectionalLight('#9edbd7', 0.8);
fill.position.set(25, 15, -25);
scene.add(fill);
const cubeGeometry = new THREE.BoxGeometry(1, 1, 1);
const dummy = new THREE.Object3D();
const tempColor = new THREE.Color();
const MAT = {
cream: standard('#f2d9a4'),
pale: standard('#f5e9c9'),
coral: standard('#e9956f'),
salmon: standard('#d97f68'),
teal: standard('#4b9991'),
blueTeal: standard('#397f83'),
roof: standard('#bf6957'),
roofDark: standard('#9b554e'),
roofGold: standard('#d9a84e'),
roofBlue: standard('#4b7781'),
wood: standard('#9d7350'),
woodLight: standard('#c39965'),
woodDark: standard('#70513c'),
trunk: standard('#73533d'),
leafA: standard('#4f815d'),
leafB: standard('#699668'),
leafC: standard('#83a36a'),
grass: standard('#668a62'),
reed: standard('#77965f'),
soil: standard('#7e6749'),
path: standard('#b18a5c'),
pathDark: standard('#8d6c4a'),
window: new THREE.MeshStandardMaterial({
color: '#255c66', roughness: 0.3, metalness: 0.05,
emissive: '#4a9f9e', emissiveIntensity: 0.32
}),
panel: standard('#28576c', 0.35),
metal: standard('#59787a', 0.45),
rope: standard('#5f5b45'),
white: standard('#f4eed8'),
dark: standard('#304d4e'),
glass: new THREE.MeshStandardMaterial({
color: '#89c4b2', transparent: true, opacity: 0.38,
roughness: 0.18, metalness: 0.05, depthWrite: false
})
};
function standard(color, roughness = 0.85) {
return new THREE.MeshStandardMaterial({
color,
roughness,
metalness: 0,
flatShading: true
});
}
function addBox(w, h, d, material, x, y, z, parent = scene) {
const mesh = new THREE.Mesh(cubeGeometry, material);
mesh.scale.set(w, h, d);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function setInstance(mesh, index, x, y, z, sx, sy, sz, ry = 0, color = null) {
dummy.position.set(x, y, z);
dummy.rotation.set(0, ry, 0);
dummy.scale.set(sx, sy, sz);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
if (color !== null) mesh.setColorAt(index, color);
}
function randomGenerator(seed) {
let state = seed >>> 0;
return () => {
state += 0x6D2B79F5;
let t = state;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const rand = randomGenerator(73129);
function hash2(x, y) {
let n = Math.imul(x, 374761393) + Math.imul(y, 668265263);
n = (n ^ (n >>> 13)) >>> 0;
n = Math.imul(n, 1274126177) >>> 0;
return ((n ^ (n >>> 16)) >>> 0) / 4294967295;
}
function segmentDistance(px, pz, ax, az, bx, bz) {
const dx = bx - ax;
const dz = bz - az;
const lengthSq = dx * dx + dz * dz;
const t = lengthSq === 0
? 0
: THREE.MathUtils.clamp(((px - ax) * dx + (pz - az) * dz) / lengthSq, 0, 1);
const cx = ax + t * dx;
const cz = az + t * dz;
return Math.hypot(px - cx, pz - cz);
}
function polylineDistance(x, z, points) {
let d = Infinity;
for (let i = 0; i < points.length - 1; i++) {
d = Math.min(d, segmentDistance(
x, z,
points[i][0], points[i][1],
points[i + 1][0], points[i + 1][1]
));
}
return d;
}
/* --------------------------------------------------------------------------
Terrain
--------------------------------------------------------------------------- */
const NX = 52;
const NZ = 42;
const CELL = 0.92;
const terrain = new Map();
const terrainCells = [];
const creekPoints = [
[-24.0, 3.0],
[-19.0, 3.2],
[-14.2, 4.0],
[-10.3, 1.8],
[-7.0, -1.1],
[-3.5, 0.1]
];
function coastSignal(x, z) {
const nx = x / (NX * CELL * 0.5);
const nz = z / (NZ * CELL * 0.5);
const radius = Math.sqrt((nx / 0.94) ** 2 + (nz / 0.87) ** 2);
const edgeNoise =
Math.sin(x * 0.36 + z * 0.13) * 0.065 +
Math.sin(z * 0.49 - x * 0.08) * 0.04;
return 1 - radius + edgeNoise;
}
for (let j = 0; j < NZ; j++) {
for (let i = 0; i < NX; i++) {
const x = (i - (NX - 1) / 2) * CELL;
const z = (j - (NZ - 1) / 2) * CELL;
const coast = coastSignal(x, z);
if (coast < -1.13) continue;
let top;
if (coast > 0.12) {
top = 0.62 + (coast - 0.12) * 2.15;
} else if (coast > -0.04) {
top = 0.18 + (coast + 0.04) * 0.9;
} else {
top = -0.62 + coast * 0.35;
}
top += Math.sin(x * 0.82) * Math.cos(z * 0.67) * 0.055;
const creekDistance = polylineDistance(x, z, creekPoints);
if (creekDistance < 1.18) {
top = Math.min(top, -0.38 + creekDistance * 0.49);
}
top = Math.round(top / 0.22) * 0.22;
terrain.set(`${i},${j}`, top);
terrainCells.push({ i, j, x, z, top, coast });
}
}
function getTopAt(x, z) {
const i = THREE.MathUtils.clamp(Math.round(x / CELL + (NX - 1) / 2), 0, NX - 1);
const j = THREE.MathUtils.clamp(Math.round(z / CELL + (NZ - 1) / 2), 0, NZ - 1);
return terrain.get(`${i},${j}`) ?? -0.88;
}
const terrainMaterial = new THREE.MeshStandardMaterial({
color: '#ffffff',
roughness: 0.94,
metalness: 0,
flatShading: true,
vertexColors: true
});
const terrainMesh = new THREE.InstancedMesh(
cubeGeometry,
terrainMaterial,
terrainCells.length
);
terrainMesh.castShadow = true;
terrainMesh.receiveShadow = true;
terrainCells.forEach((cell, index) => {
setInstance(
terrainMesh, index,
cell.x, cell.top - CELL * 0.5, cell.z,
CELL * 0.985, CELL, CELL * 0.985
);
let color;
if (cell.top < 0.08) {
color = '#638a7e';
} else if (cell.coast < 0.17) {
color = '#b9ad7e';
} else if (cell.top < 0.72) {
color = '#6f8c64';
} else {
const variation = hash2(cell.i, cell.j);
color = variation > 0.72 ? '#88a06b' : variation > 0.35 ? '#78956a' : '#6f9066';
}
terrainMesh.setColorAt(index, tempColor.set(color));
});
terrainMesh.instanceMatrix.needsUpdate = true;
terrainMesh.instanceColor.needsUpdate = true;
scene.add(terrainMesh);
/* --------------------------------------------------------------------------
Animated ocean and tidal creek water
--------------------------------------------------------------------------- */
const waterUniforms = {
uTime: { value: 0 },
uTide: { value: 0.15 }
};
const waterMaterial = new THREE.ShaderMaterial({
uniforms: waterUniforms,
transparent: true,
depthWrite: false,
side: THREE.DoubleSide,
vertexShader: `
uniform float uTime;
varying vec2 vUv;
varying float vWave;
void main() {
vUv = uv;
vec3 p = position;
float a = sin(p.x * 0.29 + uTime * 0.74);
float b = sin(p.y * 0.37 - uTime * 0.58);
float c = sin((p.x + p.y) * 0.16 + uTime * 0.31);
vWave = a * 0.055 + b * 0.035 + c * 0.025;
p.z += vWave;
gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0);
}
`,
fragmentShader: `
uniform float uTime;
uniform float uTide;
varying vec2 vUv;
varying float vWave;
void main() {
vec3 shallow = vec3(0.24, 0.64, 0.64);
vec3 deep = vec3(0.10, 0.38, 0.47);
float depthMix = smoothstep(0.10, 0.82, length(vUv - 0.5));
vec3 color = mix(shallow, deep, depthMix * 0.72);
float ribbons = sin((vUv.x * 180.0 + vUv.y * 115.0) + uTime * 0.45);
ribbons = smoothstep(0.90, 1.0, ribbons) * 0.08;
float glint = pow(max(0.0, sin(vUv.x * 460.0 + uTime * 0.6)), 22.0);
glint *= pow(max(0.0, sin(vUv.y * 390.0 - uTime * 0.4)), 8.0);
color += ribbons + glint * 0.16;
color += vec3(0.06, 0.10, 0.08) * (vWave + 0.04);
gl_FragColor = vec4(color, 0.80);
}
`
});
const water = new THREE.Mesh(
new THREE.PlaneGeometry(140, 140, 120, 120),
waterMaterial
);
water.rotation.x = -Math.PI / 2;
water.position.y = 0.15;
water.renderOrder = 2;
scene.add(water);
/* --------------------------------------------------------------------------
Village paths, bridges, and communal spaces
--------------------------------------------------------------------------- */
const mainWalk = [
[-14.0, 4.4],
[-11.0, 1.8],
[-8.0, -2.8],
[-3.2, -4.0],
[2.0, -6.0],
[7.5, -9.8]
];
const gardenWalk = [
[2.0, -6.0],
[6.2, -2.0],
[10.0, 3.5],
[13.8, 7.1]
];
const workWalk = [
[2.0, -6.0],
[5.5, -3.0],
[8.6, 0.0]
];
const homeWalk = [
[-8.0, -2.8],
[-10.0, -6.2],
[-13.0, -9.5]
];
function addBoardwalk(points, width = 0.78) {
for (let p = 0; p < points.length - 1; p++) {
const [ax, az] = points[p];
const [bx, bz] = points[p + 1];
const length = Math.hypot(bx - ax, bz - az);
const angle = Math.atan2(bz - az, bx - ax);
const steps = Math.max(1, Math.ceil(length / 0.68));
for (let s = 0; s < steps; s++) {
const t = (s + 0.5) / steps;
const x = THREE.MathUtils.lerp(ax, bx, t);
const z = THREE.MathUtils.lerp(az, bz, t);
let y = getTopAt(x, z) + 0.13;
const nearCreek = polylineDistance(x, z, creekPoints) < 1.55;
if (nearCreek) y = Math.max(y, 0.68);
addBox(length / steps + 0.035, 0.13, width, MAT.path, x, y, z)
.rotation.y = -angle;
if (s % 4 === 0) {
addBox(0.11, Math.max(0.32, y - getTopAt(x, z)), 0.11,
MAT.woodDark, x, y - 0.12, z);
}
}
}
}
addBoardwalk(mainWalk);
addBoardwalk(gardenWalk, 0.7);
addBoardwalk(workWalk, 0.68);
addBoardwalk(homeWalk, 0.62);
/* --------------------------------------------------------------------------
Buildings
--------------------------------------------------------------------------- */
const buildingMeshes = [];
function addBuilding({
x, z, w, d, h,
wall = MAT.cream,
roof = MAT.roof,
style = 'home'
}) {
const base = getTopAt(x, z);
const group = new THREE.Group();
scene.add(group);
const foundation = addBox(w + 0.32, 0.28, d + 0.32, MAT.stone ?? MAT.pale, x, base + 0.05, z, group);
buildingMeshes.push(foundation);
const body = addBox(w, h, d, wall, x, base + h / 2 + 0.12, z, group);
buildingMeshes.push(body);
addBox(w + 0.46, 0.24, d + 0.46, roof, x, base + h + 0.24, z, group);
addBox(w * 0.72, 0.21, d * 0.72, roof, x, base + h + 0.46, z, group);
addBox(w * 0.42, 0.18, d * 0.42, roof, x, base + h + 0.65, z, group);
const windowY = base + h * 0.58;
const frontZ = z + d / 2 + 0.025;
const frontCount = Math.max(1, Math.floor(w / 1.25));
for (let i = 0; i < frontCount; i++) {
const wx = x + (i - (frontCount - 1) / 2) * (w / (frontCount + 0.35));
addBox(0.44, 0.48, 0.06, MAT.window, wx, windowY, frontZ, group);
}
const sideX = x + w / 2 + 0.025;
addBox(0.06, 0.48, 0.46, MAT.window, sideX, windowY, z, group);
const door = addBox(0.58, 1.12, 0.07, MAT.woodDark,
x + w * 0.22, base + 0.68, frontZ + 0.01, group);
buildingMeshes.push(door);
if (style === 'home') {
addBox(0.32, 0.78, 0.34, MAT.woodDark,
x - w * 0.25, base + h + 0.83, z - d * 0.18, group);
}
if (style === 'market') {
const awningColors = [MAT.coral, MAT.pale, MAT.coral, MAT.pale];
for (let i = 0; i < 8; i++) {
const stallX = x - w * 0.63 + i * (w * 1.26 / 7);
const canopy = addBox(w * 1.26 / 7, 0.13, 1.15,
awningColors[i % 4], stallX, base + 1.65, z + d / 2 + 0.62, group);
canopy.rotation.x = 0.13;
addBox(0.08, 1.55, 0.08, MAT.woodDark,
stallX, base + 0.82, z + d / 2 + 1.02, group);
}
}
if (style === 'school') {
addBox(0.72, 1.35, 0.72, MAT.pale, x, base + h + 1.13, z, group);
addBox(0.48, 0.34, 0.48, MAT.roof, x, base + h + 1.92, z, group);
for (let i = 0; i < 3; i++) {
const panel = addBox(1.15, 0.10, 0.74, MAT.panel,
x - 1.25 + i * 1.25, base + h + 0.88, z + d * 0.05, group);
panel.rotation.x = -0.14;
}
}
if (style === 'workshop') {
addBox(0.48, 1.65, 0.48, MAT.woodDark,
x + w * 0.27, base + h + 1.03, z - d * 0.2, group);
for (let i = 0; i < 4; i++) {
const panel = addBox(1.25, 0.1, 0.8, MAT.panel,
x - 1.45 + i * 1.3, base + 0.16, z + d / 2 + 1.15, group);
panel.rotation.x = -0.24;
}
}
return { x, z, base, w, d, h, group };
}
const homes = [
{ x: -13.0, z: -9.3, w: 3.2, d: 2.8, h: 2.0, wall: MAT.coral, roof: MAT.roofDark },
{ x: -8.6, z: -10.2, w: 3.0, d: 2.7, h: 2.1, wall: MAT.pale, roof: MAT.roofBlue },
{ x: -13.2, z: -5.4, w: 2.8, d: 2.6, h: 1.9, wall: MAT.pale, roof: MAT.roof },
{ x: -8.8, z: -6.0, w: 3.4, d: 2.8, h: 2.15, wall: MAT.salmon, roof: MAT.roofDark },
{ x: -4.8, z: -10.0, w: 2.8, d: 2.5, h: 1.9, wall: MAT.teal, roof: MAT.roofGold }
];
homes.forEach(home => addBuilding({ ...home, style: 'home' }));
const market = addBuilding({
x: -1.3, z: -1.7, w: 4.8, d: 3.4, h: 2.55,
wall: MAT.pale, roof: MAT.roofGold, style: 'market'
});
const school = addBuilding({
x: 7.0, z: -8.0, w: 5.4, d: 3.4, h: 2.8,
wall: MAT.cream, roof: MAT.roof, style: 'school'
});
const workshop = addBuilding({
x: 8.8, z: 0.2, w: 4.3, d: 3.0, h: 2.25,
wall: MAT.teal, roof: MAT.roofBlue, style: 'workshop'
});
const saltShed = addBuilding({
x: -16.1, z: -1.5, w: 2.6, d: 2.4, h: 1.75,
wall: MAT.pale, roof: MAT.roofDark, style: 'home'
});
const wharfHut = addBuilding({
x: -14.2, z: 5.2, w: 2.3, d: 2.0, h: 1.6,
wall: MAT.blueTeal, roof: MAT.roofDark, style: 'home'
});
/* Shared gardens and greenhouse. */
const gardenBase = getTopAt(13.8, 7.0);
for (let row = 0; row < 3; row++) {
for (let col = 0; col < 2; col++) {
const bx = 12.4 + col * 2.35;
const bz = 5.3 + row * 1.65;
const by = getTopAt(bx, bz);
addBox(1.7, 0.25, 0.95, MAT.soil, bx, by + 0.13, bz);
for (let plant = 0; plant < 4; plant++) {
const px = bx - 0.56 + plant * 0.37;
addBox(0.24, 0.30, 0.24,
plant % 2 ? MAT.leafB : MAT.leafA,
px, by + 0.39, bz);
}
}
}
const greenhouseX = 16.6;
const greenhouseZ = 7.1;
const greenhouseBase = getTopAt(greenhouseX, greenhouseZ);
addBox(2.0, 1.35, 1.8, MAT.glass,
greenhouseX, greenhouseBase + 0.72, greenhouseZ);
for (let i = 0; i < 5; i++) {
addBox(0.07, 1.4, 0.07, MAT.white,
greenhouseX - 0.9 + i * 0.45, greenhouseBase + 0.72, greenhouseZ + 0.92);
}
addBox(2.15, 0.12, 2.0, MAT.white,
greenhouseX, greenhouseBase + 1.42, greenhouseZ);
/* --------------------------------------------------------------------------
Docks, boat, fish nursery
--------------------------------------------------------------------------- */
function addDock(ax, az, bx, bz, width = 1.15) {
const length = Math.hypot(bx - ax, bz - az);
const angle = Math.atan2(bz - az, bx - ax);
const boards = Math.ceil(length / 0.48);
for (let i = 0; i < boards; i++) {
const t = (i + 0.5) / boards;
const x = THREE.MathUtils.lerp(ax, bx, t);
const z = THREE.MathUtils.lerp(az, bz, t);
const plank = addBox(length / boards + 0.025, 0.13, width,
i % 2 ? MAT.woodLight : MAT.wood, x, 0.91, z);
plank.rotation.y = -angle;
if (i % 3 === 0) {
addBox(0.13, 1.12, 0.13, MAT.woodDark, x, 0.40, z - width * 0.37);
addBox(0.13, 1.12, 0.13, MAT.woodDark, x, 0.40, z + width * 0.37);
}
}
}
addDock(-15.0, 4.2, -23.1, 4.2, 1.2);
addDock(10.0, 3.3, 15.0, 4.1, 0.75);
const boat = new THREE.Group();
scene.add(boat);
addBox(1.55, 0.30, 0.66, MAT.woodDark, 0, 0, 0, boat);
addBox(1.12, 0.22, 0.48, MAT.cream, -0.05, 0.22, 0, boat);
addBox(0.12, 1.7, 0.12, MAT.woodDark, 0.12, 0.86, 0, boat);
addBox(0.72, 0.50, 0.06, MAT.pale, 0.48, 1.28, 0, boat);
boat.position.set(-21.9, 0.3, 4.65);
boat.rotation.y = -0.12;
const fish = [];
const fishMaterial = standard('#e8a85c');
for (let i = 0; i < 14; i++) {
const mesh = addBox(0.16, 0.08, 0.07, fishMaterial,
-18 + rand() * 4, -0.15, 3.3 + rand() * 1.8);
fish.push({
mesh,
phase: rand() * Math.PI * 2,
radius: 0.25 + rand() * 0.55,
centerX: -18 + rand() * 4,
centerZ: 3.3 + rand() * 1.8
});
}
/* --------------------------------------------------------------------------
Upland trees and wetland reeds
--------------------------------------------------------------------------- */
const buildingCenters = [
...homes.map(h => [h.x, h.z]),
[market.x, market.z], [school.x, school.z],
[workshop.x, workshop.z], [saltShed.x, saltShed.z],
[wharfHut.x, wharfHut.z], [13.8, 7.0]
];
const treeCells = terrainCells.filter(cell => {
if (cell.top < 0.88 || cell.coast < 0.12) return false;
if (hash2(cell.i + 21, cell.j - 7) > 0.11) return false;
const nearBuilding = buildingCenters.some(([x, z]) =>
Math.abs(cell.x - x) < 3.1 && Math.abs(cell.z - z) < 3.0);
if (nearBuilding) return false;
const nearPath = [mainWalk, gardenWalk, workWalk, homeWalk]
.some(path => polylineDistance(cell.x, cell.z, path) < 1.0);
return !nearPath;
});
const trunkMesh = new THREE.InstancedMesh(cubeGeometry, MAT.trunk, treeCells.length);
const canopyMesh = new THREE.InstancedMesh(cubeGeometry, MAT.leafA, treeCells.length * 2);
canopyMesh.material = new THREE.MeshStandardMaterial({
color: '#ffffff', roughness: 0.9, flatShading: true, vertexColors: true
});
trunkMesh.castShadow = true;
canopyMesh.castShadow = true;
treeCells.forEach((cell, index) => {
const h = 0.7 + hash2(cell.i, cell.j) * 0.5;
setInstance(trunkMesh, index,
cell.x, cell.top + h / 2, cell.z,
0.18, h, 0.18);
const c1 = hash2(cell.i + 40, cell.j) > 0.5 ? '#4e805c' : '#679264';
const c2 = hash2(cell.i - 12, cell.j + 30) > 0.5 ? '#739967' : '#568760';
setInstance(canopyMesh, index * 2,
cell.x, cell.top + h + 0.42, cell.z,
1.15, 0.92, 1.15, hash2(cell.i, cell.j) * 2, tempColor.set(c1));
setInstance(canopyMesh, index * 2 + 1,
cell.x + 0.28, cell.top + h + 0.77, cell.z - 0.12,
0.75, 0.65, 0.76, hash2(cell.i + 8, cell.j) * 2, tempColor.set(c2));
});
trunkMesh.instanceMatrix.needsUpdate = true;
canopyMesh.instanceMatrix.needsUpdate = true;
canopyMesh.instanceColor.needsUpdate = true;
scene.add(trunkMesh, canopyMesh);
const reedCells = terrainCells.filter(cell =>
cell.top > -0.10 && cell.top < 0.58 && cell.coast < 0.31
);
const reedMesh = new THREE.InstancedMesh(
cubeGeometry,
new THREE.MeshStandardMaterial({
color: '#ffffff', roughness: 0.95, flatShading: true, vertexColors: true
}),
reedCells.length * 3
);
reedCells.forEach((cell, index) => {
for (let s = 0; s < 3; s++) {
const offsetX = (hash2(cell.i * 3 + s, cell.j) - 0.5) * 0.55;
const offsetZ = (hash2(cell.i, cell.j * 3 + s) - 0.5) * 0.55;
const h = 0.3 + hash2(cell.i + s, cell.j - s) * 0.46;
const color = s % 2 ? '#78985f' : '#577f64';
setInstance(
reedMesh, index * 3 + s,
cell.x + offsetX, cell.top + h / 2, cell.z + offsetZ,
0.07, h, 0.07, 0,
tempColor.set(color)
);
}
});
reedMesh.instanceMatrix.needsUpdate = true;
reedMesh.instanceColor.needsUpdate = true;
scene.add(reedMesh);
/* --------------------------------------------------------------------------
Tidal edge foam and creek flow markers
--------------------------------------------------------------------------- */
const foamCells = terrainCells.filter(cell => cell.top > -0.20 && cell.top < 0.78);
const foamMaterial = new THREE.MeshBasicMaterial({
color: '#eff6dd',
transparent: true,
opacity: 0.62,
depthWrite: false
});
const foam = new THREE.InstancedMesh(cubeGeometry, foamMaterial, foamCells.length);
foam.renderOrder = 3;
scene.add(foam);
const flowCount = 90;
const flowMaterial = new THREE.MeshBasicMaterial({
color: '#b7ffe4',
transparent: true,
opacity: 0.68,
depthWrite: false
});
const flow = new THREE.InstancedMesh(cubeGeometry, flowMaterial, flowCount);
flow.renderOrder = 4;
scene.add(flow);
const creekLengths = [];
let totalCreekLength = 0;
for (let i = 0; i < creekPoints.length - 1; i++) {
const length = Math.hypot(
creekPoints[i + 1][0] - creekPoints[i][0],
creekPoints[i + 1][1] - creekPoints[i][1]
);
creekLengths.push(length);
totalCreekLength += length;
}
function creekPointAt(distance) {
let remaining = THREE.MathUtils.euclideanModulo(distance, totalCreekLength);
for (let i = 0; i < creekLengths.length; i++) {
if (remaining <= creekLengths[i]) {
const t = remaining / creekLengths[i];
return [
THREE.MathUtils.lerp(creekPoints[i][0], creekPoints[i + 1][0], t),
THREE.MathUtils.lerp(creekPoints[i][1], creekPoints[i + 1][1], t)
];
}
remaining -= creekLengths[i];
}
return creekPoints[0];
}
/* --------------------------------------------------------------------------
Ecological corridor overlay
--------------------------------------------------------------------------- */
const corridorGroup = new THREE.Group();
corridorGroup.visible = false;
scene.add(corridorGroup);
const corridorSegments = [
[[-17.0, 9.1], [-14.0, 4.1]],
[[-14.0, 4.1], [-10.1, 1.8]],
[[-10.1, 1.8], [-7.0, -1.1]],
[[-7.0, -1.1], [0.0, -1.2]],
[[0.0, -1.2], [9.4, 0.0]],
[[9.4, 0.0], [13.8, 7.0]],
[[13.8, 7.0], [18.6, 2.6]]
];
const corridorMaterial = new THREE.MeshBasicMaterial({
color: '#b5ffe2',
transparent: true,
opacity: 0.88,
depthTest: false,
depthWrite: false
});
const corridorCells = [];
for (const [a, b] of corridorSegments) {
const length = Math.hypot(b[0] - a[0], b[1] - a[1]);
const count = Math.ceil(length / 0.72);
for (let i = 0; i <= count; i++) {
const t = i / count;
const x = THREE.MathUtils.lerp(a[0], b[0], t);
const z = THREE.MathUtils.lerp(a[1], b[1], t);
const ground = getTopAt(x, z);
const y = Math.max(ground + 0.34, 0.42);
corridorCells.push({ x, y, z, phase: rand() * Math.PI * 2 });
}
}
const corridorMesh = new THREE.InstancedMesh(
cubeGeometry, corridorMaterial, corridorCells.length
);
corridorMesh.renderOrder = 20;
corridorGroup.add(corridorMesh);
corridorCells.forEach((cell, index) => {
setInstance(corridorMesh, index,
cell.x, cell.y, cell.z,
0.13, 0.13, 0.13);
});
corridorMesh.instanceMatrix.needsUpdate = true;
const corridorNodes = [
[-17.0, 9.1], [-14.0, 4.1], [-10.1, 1.8],
[0.0, -1.2], [9.4, 0.0], [13.8, 7.0], [18.6, 2.6]
];
const nodeMaterial = new THREE.MeshBasicMaterial({
color: '#d7fff0',
transparent: true,
opacity: 0.95,
depthTest: false
});
for (const [x, z] of corridorNodes) {
const y = Math.max(getTopAt(x, z) + 0.35, 0.42);
for (let i = 0; i < 8; i++) {
const a = i / 8 * Math.PI * 2;
const node = addBox(0.17, 0.17, 0.17, nodeMaterial,
x + Math.cos(a) * 0.72, y, z + Math.sin(a) * 0.72, corridorGroup);
node.renderOrder = 21;
}
}
/* --------------------------------------------------------------------------
Voxel birds
--------------------------------------------------------------------------- */
const birds = [];
const birdBodyMaterial = standard('#344f52');
const birdWingMaterial = standard('#e8e4cd');
for (let i = 0; i < 9; i++) {
const bird = new THREE.Group();
addBox(0.36, 0.13, 0.18, birdBodyMaterial, 0, 0, 0, bird);
const leftWing = addBox(0.52, 0.055, 0.20, birdWingMaterial,
-0.28, 0, 0, bird);
const rightWing = addBox(0.52, 0.055, 0.20, birdWingMaterial,
0.28, 0, 0, bird);
scene.add(bird);
birds.push({
group: bird,
leftWing,
rightWing,
phase: rand() * Math.PI * 2,
radius: 7 + rand() * 14,
height: 5.8 + rand() * 4.8,
speed: 0.07 + rand() * 0.04,
centerX: -2 + rand() * 7,
centerZ: -2 + rand() * 6
});
}
/* --------------------------------------------------------------------------
Small offshore voxel islets
--------------------------------------------------------------------------- */
const islets = [
{ x: -25, z: 12, w: 3.2, d: 2.1 },
{ x: 24, z: -11, w: 3.8, d: 2.7 },
{ x: 20, z: 15, w: 2.4, d: 1.8 }
];
for (const islet of islets) {
for (let i = 0; i < 7; i++) {
const x = islet.x + (rand() - 0.5) * islet.w;
const z = islet.z + (rand() - 0.5) * islet.d;
const h = 0.22 + rand() * 0.34;
addBox(0.55, h, 0.55, i % 2 ? MAT.path : MAT.grass,
x, -0.18 + h / 2, z);
}
}
/* --------------------------------------------------------------------------
HTML labels projected into the 3D scene
--------------------------------------------------------------------------- */
const labelDefinitions = [
{ text: 'Upland homes', point: [-11.2, getTopAt(-11.2, -8.0) + 3.0, -8.0], type: 'community' },
{ text: 'Market hall', point: [-1.3, market.base + market.h + 1.5, -1.7], type: 'community' },
{ text: 'School & solar', point: [7.0, school.base + school.h + 1.8, -8.0], type: 'community' },
{ text: 'Maker yard', point: [8.8, workshop.base + workshop.h + 1.4, 0.2], type: 'work' },
{ text: 'Shared gardens', point: [13.8, gardenBase + 1.6, 7.0], type: '' },
{ text: 'Saltmarsh', point: [-17.0, 0.9, 9.1], type: 'habitat' },
{ text: 'Tidal creek', point: [-11.1, 1.2, 2.1], type: 'water' },
{ text: 'Nursery shallows', point: [-19.0, 0.7, 4.2], type: 'water' },
{ text: 'Fishing wharf', point: [-14.5, 2.3, 5.0], type: 'work' }
];
for (const definition of labelDefinitions) {
const element = document.createElement('div');
element.className = `map-label ${definition.type}`;
element.textContent = definition.text;
document.querySelector('#labels').appendChild(element);
definition.element = element;
definition.world = new THREE.Vector3(...definition.point);
}
/* --------------------------------------------------------------------------
Direct camera controls — no OrbitControls addon
--------------------------------------------------------------------------- */
const controls = {
target: new THREE.Vector3(0, 0.5, 0),
theta: 0.67,
phi: 0.82,
viewSize: 38,
radius: 72
};
function updateCamera() {
const aspect = window.innerWidth / window.innerHeight;
camera.left = -controls.viewSize * aspect / 2;
camera.right = controls.viewSize * aspect / 2;
camera.top = controls.viewSize / 2;
camera.bottom = -controls.viewSize / 2;
const sinPhi = Math.sin(controls.phi);
camera.position.set(
controls.target.x + controls.radius * sinPhi * Math.sin(controls.theta),
controls.target.y + controls.radius * Math.cos(controls.phi),
controls.target.z + controls.radius * sinPhi * Math.cos(controls.theta)
);
camera.lookAt(controls.target);
camera.updateProjectionMatrix();
}
updateCamera();
function resetCamera() {
controls.target.set(0, 0.5, 0);
controls.theta = 0.67;
controls.phi = 0.82;
controls.viewSize = 38;
updateCamera();
}
function panCamera(dx, dy) {
const scale = controls.viewSize / window.innerHeight * 1.15;
const right = new THREE.Vector3(Math.cos(controls.theta), 0, -Math.sin(controls.theta));
const forward = new THREE.Vector3(-Math.sin(controls.theta), 0, -Math.cos(controls.theta));
controls.target.addScaledVector(right, -dx * scale);
controls.target.addScaledVector(forward, dy * scale);
}
const pointers = new Map();
let pointerLast = null;
let pinchDistance = 0;
canvas.addEventListener('pointerdown', event => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
pointerLast = { x: event.clientX, y: event.clientY, id: event.pointerId };
if (pointers.size === 2) {
const points = [...pointers.values()];
pinchDistance = Math.hypot(points[0].x - points[1].x, points[0].y - points[1].y);
}
});
canvas.addEventListener('pointermove', event => {
if (!pointers.has(event.pointerId)) return;
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 2) {
const points = [...pointers.values()];
const distance = Math.hypot(points[0].x - points[1].x, points[0].y - points[1].y);
if (pinchDistance > 0) {
controls.viewSize = THREE.MathUtils.clamp(
controls.viewSize * (pinchDistance / Math.max(1, distance)),
16, 68
);
updateCamera();
}
pinchDistance = distance;
return;
}
if (!pointerLast || pointerLast.id !== event.pointerId) {
pointerLast = { x: event.clientX, y: event.clientY, id: event.pointerId };
return;
}
const dx = event.clientX - pointerLast.x;
const dy = event.clientY - pointerLast.y;
if (event.shiftKey || event.buttons === 2) {
panCamera(dx, dy);
} else {
controls.theta -= dx * 0.006;
controls.phi = THREE.MathUtils.clamp(controls.phi + dy * 0.005, 0.38, 1.35);
}
pointerLast.x = event.clientX;
pointerLast.y = event.clientY;
updateCamera();
});
function endPointer(event) {
pointers.delete(event.pointerId);
if (pointers.size === 1) {
const [id, point] = [...pointers.entries()][0];
pointerLast = { x: point.x, y: point.y, id };
} else {
pointerLast = null;
pinchDistance = 0;
}
}
canvas.addEventListener('pointerup', endPointer);
canvas.addEventListener('pointercancel', endPointer);
canvas.addEventListener('contextmenu', event => event.preventDefault());
canvas.addEventListener('wheel', event => {
event.preventDefault();
controls.viewSize = THREE.MathUtils.clamp(
controls.viewSize * Math.exp(event.deltaY * 0.001),
16, 68
);
updateCamera();
}, { passive: false });
const raycaster = new THREE.Raycaster();
const pointerNdc = new THREE.Vector2();
canvas.addEventListener('dblclick', event => {
pointerNdc.set(
event.clientX / window.innerWidth * 2 - 1,
-(event.clientY / window.innerHeight) * 2 + 1
);
raycaster.setFromCamera(pointerNdc, camera);
const hit = raycaster.intersectObject(terrainMesh)[0];
if (hit) {
const cell = terrainCells[hit.instanceId];
controls.target.set(cell.x, cell.top, cell.z);
updateCamera();
}
});
/* --------------------------------------------------------------------------
UI and simulation state
--------------------------------------------------------------------------- */
const tideButton = document.querySelector('#tideButton');
const lensButton = document.querySelector('#lensButton');
const resetButton = document.querySelector('#resetButton');
const tideSlider = document.querySelector('#tideSlider');
const tideValue = document.querySelector('#tideValue');
const waterMetric = document.querySelector('#waterMetric');
const edgeMetric = document.querySelector('#edgeMetric');
const habitatMetric = document.querySelector('#habitatMetric');
let paused = false;
let ecologyLens = false;
let tideOffset = 0;
let tide = 0.16;
tideButton.addEventListener('click', () => {
paused = !paused;
tideButton.textContent = paused ? 'Resume tide' : 'Pause tide';
tideButton.classList.toggle('active', paused);
tideButton.setAttribute('aria-pressed', String(paused));
});
lensButton.addEventListener('click', () => {
ecologyLens = !ecologyLens;
corridorGroup.visible = ecologyLens;
lensButton.classList.toggle('active', ecologyLens);
lensButton.setAttribute('aria-pressed', String(ecologyLens));
});
resetButton.addEventListener('click', resetCamera);
tideSlider.addEventListener('input', () => {
tideOffset = Number(tideSlider.value);
tideValue.textContent = `${tideOffset >= 0 ? '+' : ''}${tideOffset.toFixed(2)} m`;
});
window.addEventListener('resize', () => {
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.8));
renderer.setSize(window.innerWidth, window.innerHeight);
updateCamera();
});
/* --------------------------------------------------------------------------
Animation
--------------------------------------------------------------------------- */
const clock = new THREE.Clock();
let elapsed = 0;
let uiAccumulator = 0;
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
elapsed += delta;
if (!paused) {
tide = 0.12 + Math.sin(elapsed * 0.073) * 0.35 + tideOffset;
} else {
tide = 0.12 + Math.sin(elapsed * 0.073) * 0.35 + tideOffset;
}
tide = THREE.MathUtils.clamp(tide, -0.28, 0.72);
water.position.y = tide;
waterUniforms.uTime.value = elapsed;
waterUniforms.uTide.value = tide;
boat.position.y = tide + 0.10;
boat.rotation.z = Math.sin(elapsed * 0.9) * 0.025;
/* Wetland fish move in a compact nursery shoal. */
for (const f of fish) {
const a = elapsed * 0.48 + f.phase;
f.mesh.position.x = f.centerX + Math.cos(a) * f.radius;
f.mesh.position.z = f.centerZ + Math.sin(a * 1.13) * f.radius;
f.mesh.position.y = tide - 0.16 + Math.sin(a * 2.0) * 0.05;
f.mesh.rotation.y = -a;
}
/* Foam squares appear only where the moving tide meets terrain. */
foamCells.forEach((cell, index) => {
const distance = Math.abs(cell.top - tide);
const visibility = THREE.MathUtils.clamp(1 - distance / 0.18, 0, 1);
setInstance(
foam, index,
cell.x, tide + 0.018, cell.z,
CELL * 0.87 * visibility,
0.035,
CELL * 0.87 * visibility
);
});
foam.instanceMatrix.needsUpdate = true;
/* Light markers indicate tidal flow through the creek. */
for (let i = 0; i < flowCount; i++) {
const distance = (i / flowCount) * totalCreekLength - elapsed * 1.45;
const [x, z] = creekPointAt(distance);
const pulse = 0.75 + Math.sin(elapsed * 2.3 + i * 0.6) * 0.18;
setInstance(
flow, i,
x, tide + 0.075, z,
0.10 * pulse, 0.07, 0.10 * pulse
);
}
flow.instanceMatrix.needsUpdate = true;
/* Flock behavior: slow circling over creek, marsh, and dunes. */
for (const bird of birds) {
const angle = elapsed * bird.speed + bird.phase;
const x = bird.centerX + Math.cos(angle) * bird.radius;
const z = bird.centerZ + Math.sin(angle) * bird.radius * 0.68;
const y = bird.height + Math.sin(angle * 2.3) * 0.55;
bird.group.position.set(x, y, z);
bird.group.rotation.y = -angle - Math.PI / 2;
const flap = Math.sin(elapsed * 7.5 + bird.phase) * 0.42;
bird.leftWing.rotation.z = flap;
bird.rightWing.rotation.z = -flap;
}
/* Ecological corridor pulses when the lens is active. */
if (ecologyLens) {
corridorCells.forEach((cell, index) => {
const pulse = 0.85 + Math.sin(elapsed * 2.5 + cell.phase) * 0.25;
setInstance(
corridorMesh, index,
cell.x, cell.y + Math.sin(elapsed * 1.5 + cell.phase) * 0.07, cell.z,
0.13 * pulse, 0.13 * pulse, 0.13 * pulse
);
});
corridorMesh.instanceMatrix.needsUpdate = true;
}
/* Project HTML labels from world coordinates. */
for (const label of labelDefinitions) {
const projected = label.world.clone().project(camera);
const visible = projected.z > -1 && projected.z < 1 &&
projected.x > -1.15 && projected.x < 1.15 &&
projected.y > -1.15 && projected.y < 1.15;
if (!visible) {
label.element.style.display = 'none';
continue;
}
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
label.element.style.display = 'flex';
label.element.style.transform =
`translate(${x}px, ${y}px) translate(-50%, -50%)`;
}
/* Update the compact readings at a lower frequency. */
uiAccumulator += delta;
if (uiAccumulator > 0.18) {
uiAccumulator = 0;
const wetTiles = terrainCells.filter(cell => cell.top < tide).length;
const habitatScore = THREE.MathUtils.clamp(
Math.round(78 + (tide + 0.18) * 18),
65, 94
);
waterMetric.textContent = `${tide >= 0 ? '+' : ''}${(tide * 1.35).toFixed(2)}`;
edgeMetric.textContent = wetTiles.toLocaleString();
habitatMetric.textContent = `${habitatScore}%`;
}
renderer.render(scene, camera);
}
animate();
requestAnimationFrame(() => {
const loading = document.querySelector('#loading');
loading.classList.add('hide');
setTimeout(() => loading.remove(), 600);
});
</script>
</body>
</html>
```