Prompt specification
Build or customize the Three.js 3D scene "Terrace-channel connectivity puzzle" 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: Terrace-channel connectivity puzzle
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/terrace-channel-connectivity-puzzle-x1112
Scene Description Prompt:
Terrace-channel connectivity puzzle. Create a slope model with adjustable terrace outlets; users connect water routes to all plots without bypassing intended steps, using explicit geometric rules rather than engineering recommendations. Please build this with Three.js from cdnjs in one self-contained HTML file, using low-poly forms.
Working Three.js Starter (terrace-channel-connectivity-puzzle-x1112):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Terrace Flow — Geometric Connectivity Puzzle</title>
<style>
:root {
--ink: #17362f;
--muted: #6b7f78;
--panel: rgba(249, 247, 235, 0.94);
--line: rgba(23, 54, 47, 0.13);
--green: #287d5c;
--green-light: #dcebdc;
--blue: #178da8;
--orange: #d87836;
--red: #c94b45;
--shadow: 0 18px 50px rgba(24, 45, 38, 0.18);
}
* { box-sizing: border-box; }
html, body {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
background: #cbd9cf;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button { font: inherit; }
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.brand {
position: fixed;
left: 22px;
top: 18px;
z-index: 5;
pointer-events: none;
text-shadow: 0 1px 0 rgba(255,255,255,.45);
}
.brand .eyebrow {
font-size: 10px;
font-weight: 800;
letter-spacing: .23em;
color: #42655b;
}
.brand h1 {
margin: 2px 0 0;
font-size: clamp(25px, 3vw, 40px);
line-height: .95;
letter-spacing: -.045em;
}
.brand p {
margin: 7px 0 0;
font-size: 12px;
color: #527067;
}
.panel {
position: fixed;
z-index: 6;
right: 18px;
top: 18px;
width: min(325px, calc(100vw - 36px));
max-height: calc(100vh - 112px);
overflow: auto;
padding: 17px;
border: 1px solid rgba(255,255,255,.64);
border-radius: 18px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(13px);
}
.panel::-webkit-scrollbar { width: 7px; }
.panel::-webkit-scrollbar-thumb {
background: rgba(23,54,47,.2);
border-radius: 9px;
}
.panel-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}
.panel-head strong {
font-size: 14px;
letter-spacing: -.01em;
}
.badge {
flex: none;
padding: 5px 8px;
border-radius: 999px;
background: #e1eadf;
color: var(--green);
font-size: 10px;
font-weight: 850;
letter-spacing: .08em;
text-transform: uppercase;
}
.objective {
margin: 0 0 13px;
font-size: 12px;
line-height: 1.5;
color: #4d655d;
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-bottom: 15px;
}
.metric {
min-width: 0;
padding: 9px 8px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255,255,255,.48);
}
.metric b {
display: block;
font-size: 18px;
line-height: 1;
letter-spacing: -.04em;
}
.metric span {
display: block;
margin-top: 5px;
overflow: hidden;
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: .07em;
text-overflow: ellipsis;
text-transform: uppercase;
white-space: nowrap;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 15px 0 7px;
color: #35554b;
font-size: 10px;
font-weight: 850;
letter-spacing: .12em;
text-transform: uppercase;
}
.section-title span {
color: #8a9993;
font-size: 9px;
font-weight: 700;
letter-spacing: .04em;
text-transform: none;
}
.req {
display: flex;
align-items: center;
gap: 9px;
min-height: 33px;
margin: 4px 0;
padding: 6px 8px;
border: 1px solid transparent;
border-radius: 9px;
color: #60756e;
font-size: 11px;
transition: .18s ease;
}
.req .dot {
width: 9px;
height: 9px;
flex: none;
border: 2px solid #a8b5b0;
border-radius: 50%;
background: transparent;
}
.req .label {
flex: 1;
font-weight: 680;
}
.req .state {
color: #91a09a;
font-size: 9px;
font-weight: 800;
letter-spacing: .04em;
text-transform: uppercase;
}
.req.done {
border-color: rgba(40,125,92,.14);
background: rgba(220,235,220,.72);
color: #246848;
}
.req.done .dot {
border-color: var(--green);
background: var(--green);
box-shadow: inset 0 0 0 2px #e5f0e4;
}
.req.done .state { color: var(--green); }
.req.bad {
border-color: rgba(201,75,69,.14);
background: rgba(250,225,220,.72);
color: #9e433f;
}
.req.bad .dot {
border-color: var(--red);
background: var(--red);
}
.req.bad .state { color: var(--red); }
details {
margin-top: 14px;
padding-top: 12px;
border-top: 1px solid var(--line);
}
summary {
cursor: pointer;
color: #35554b;
font-size: 11px;
font-weight: 850;
}
.rules {
margin: 10px 0 0;
padding-left: 17px;
color: #5f746c;
font-size: 10.5px;
line-height: 1.55;
}
.rules li { margin: 5px 0; }
.disclaimer {
margin-top: 12px;
color: #82918b;
font-size: 9px;
line-height: 1.45;
}
.legend {
position: fixed;
z-index: 5;
left: 22px;
bottom: 20px;
display: flex;
flex-wrap: wrap;
gap: 8px 13px;
max-width: 460px;
padding: 10px 12px;
border: 1px solid rgba(255,255,255,.5);
border-radius: 13px;
background: rgba(249,247,235,.82);
box-shadow: 0 10px 30px rgba(24,45,38,.11);
backdrop-filter: blur(10px);
pointer-events: none;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
color: #526a61;
font-size: 9px;
font-weight: 750;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 50%;
}
.swatch.blue { background: var(--blue); }
.swatch.orange { background: var(--orange); }
.swatch.green { background: #5b9945; }
.swatch.red { background: var(--red); }
.swatch.rock { background: #7e857f; }
.toolbar {
position: fixed;
z-index: 7;
left: 50%;
bottom: 18px;
display: flex;
gap: 7px;
transform: translateX(-50%);
padding: 7px;
border: 1px solid rgba(255,255,255,.62);
border-radius: 15px;
background: rgba(249,247,235,.93);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
}
.tool {
min-width: 39px;
height: 39px;
padding: 0 12px;
border: 0;
border-radius: 10px;
background: transparent;
color: #49645b;
cursor: pointer;
font-size: 11px;
font-weight: 800;
transition: transform .15s ease, background .15s ease, color .15s ease;
}
.tool:hover {
background: #e8eee4;
color: var(--ink);
transform: translateY(-1px);
}
.tool:active { transform: translateY(0); }
.tool.primary {
background: var(--green);
color: white;
}
.tool.primary:hover {
background: #226b4f;
color: white;
}
.tool:disabled {
opacity: .42;
cursor: default;
transform: none;
}
.tool .key {
margin-left: 5px;
opacity: .55;
font-size: 9px;
}
#toast {
position: fixed;
z-index: 12;
left: 50%;
top: 22px;
max-width: min(540px, calc(100vw - 34px));
padding: 11px 16px;
border: 1px solid rgba(255,255,255,.55);
border-radius: 12px;
background: rgba(24,54,46,.94);
box-shadow: 0 14px 35px rgba(20,42,36,.22);
color: white;
font-size: 11px;
font-weight: 650;
line-height: 1.4;
text-align: center;
opacity: 0;
transform: translate(-50%, -12px);
transition: .22s ease;
pointer-events: none;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.error { background: rgba(147,58,52,.96); }
#success {
position: fixed;
z-index: 11;
left: 50%;
top: 50%;
width: min(390px, calc(100vw - 34px));
padding: 25px;
border: 1px solid rgba(255,255,255,.7);
border-radius: 20px;
background: rgba(248,250,239,.97);
box-shadow: 0 30px 90px rgba(21,48,40,.3);
text-align: center;
transform: translate(-50%, -50%) scale(.93);
opacity: 0;
pointer-events: none;
transition: .25s ease;
}
#success.show {
opacity: 1;
transform: translate(-50%, -50%) scale(1);
pointer-events: auto;
}
#success .seal {
display: grid;
width: 56px;
height: 56px;
margin: 0 auto 12px;
place-items: center;
border-radius: 50%;
background: #dcecdc;
color: var(--green);
font-size: 26px;
}
#success h2 {
margin: 0;
font-size: 24px;
letter-spacing: -.04em;
}
#success p {
margin: 9px 0 17px;
color: #62776f;
font-size: 12px;
line-height: 1.5;
}
#success button {
border: 0;
border-radius: 10px;
padding: 10px 17px;
background: var(--green);
color: white;
cursor: pointer;
font-weight: 800;
}
@media (max-width: 850px) {
.panel {
top: auto;
right: 10px;
bottom: 76px;
width: 270px;
max-height: 55vh;
padding: 13px;
}
.brand {
left: 13px;
top: 12px;
}
.brand p { display: none; }
.legend { display: none; }
.toolbar {
bottom: 10px;
left: 10px;
right: 10px;
justify-content: center;
transform: none;
overflow-x: auto;
}
.tool {
padding: 0 9px;
white-space: nowrap;
}
}
@media (max-width: 540px) {
.panel {
width: calc(100vw - 20px);
max-height: 43vh;
}
.metrics { margin-bottom: 9px; }
.objective { display: none; }
.tool .key { display: none; }
.tool { padding: 0 8px; font-size: 10px; }
}
</style>
</head>
<body>
<div id="viewport"></div>
<header class="brand">
<div class="eyebrow">GEOMETRIC WATER PUZZLE</div>
<h1>Terrace Flow</h1>
<p>Connect every plot without skipping a terrace step.</p>
</header>
<aside class="panel">
<div class="panel-head">
<strong>Route ledger</strong>
<span class="badge" id="progressBadge">0 / 12</span>
</div>
<p class="objective">
Start at the source or an outlet, add bends on the current terrace,
and finish at its permitted downstream target.
</p>
<div class="metrics">
<div class="metric">
<b id="chainMetric">0/4</b>
<span>Terrace steps</span>
</div>
<div class="metric">
<b id="plotMetric">0/8</b>
<span>Plots fed</span>
</div>
<div class="metric">
<b id="routeMetric">0/12</b>
<span>Valid routes</span>
</div>
</div>
<div class="section-title">
Downhill chain
<span>source → spillway</span>
</div>
<div id="chainList"></div>
<div class="section-title">
Plot branches
<span>each needs its upstream chain</span>
</div>
<div id="plotList"></div>
<details open>
<summary>Geometric rules</summary>
<ol class="rules">
<li>A terrace can only connect to its immediate downstream gate or its own plots.</li>
<li>Channel bends must remain on the active terrace’s rectangular surface.</li>
<li>A retaining wall may only be crossed at the matching outlet gate.</li>
<li>Straight channel segments cannot intersect terrace stones.</li>
<li>A plot is not fed until every upstream terrace gate is also connected.</li>
<li>Drag orange outlet gates sideways to alter the available geometry.</li>
</ol>
<div class="disclaimer">
Abstract geometry game only. The model does not represent hydraulic sizing,
engineering practice, or real-world irrigation recommendations.
</div>
</details>
</aside>
<div class="legend">
<div class="legend-item"><span class="swatch blue"></span>Water route</div>
<div class="legend-item"><span class="swatch orange"></span>Movable outlet</div>
<div class="legend-item"><span class="swatch green"></span>Fed plot</div>
<div class="legend-item"><span class="swatch red"></span>Blocked route</div>
<div class="legend-item"><span class="swatch rock"></span>Stone obstacle</div>
</div>
<nav class="toolbar" aria-label="Puzzle tools">
<button class="tool" id="undoBtn" title="Undo last bend or route">Undo <span class="key">Z</span></button>
<button class="tool" id="clearBtn">Clear routes</button>
<button class="tool" id="hintBtn">Hint</button>
<button class="tool" id="flowBtn" class="primary">Release water</button>
<button class="tool" id="viewBtn">Reset view</button>
<button class="tool" id="resetBtn">Reset puzzle</button>
</nav>
<div id="toast" role="status" aria-live="polite"></div>
<div id="success" role="dialog" aria-modal="true" aria-labelledby="successTitle">
<div class="seal">✓</div>
<h2 id="successTitle">Every plot is connected</h2>
<p>
All terrace steps are valid and every plot receives water through its
required upstream path.
</p>
<button id="closeSuccess">Continue exploring</button>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Constants and state
// -------------------------------------------------------------------------
const $ = id => document.getElementById(id);
const viewport = $("viewport");
const toastElement = $("toast");
const successElement = $("success");
const WORLD_WIDTH = 12;
const HALF_WIDTH = WORLD_WIDTH / 2;
const GROUND_Y = -0.45;
const terraces = [
{ index: 0, z0: -8, z1: -4, y: 3.00, name: "Upper terrace" },
{ index: 1, z0: -4, z1: 0, y: 2.20, name: "Second terrace" },
{ index: 2, z0: 0, z1: 4, y: 1.40, name: "Third terrace" },
{ index: 3, z0: 4, z1: 8, y: 0.60, name: "Lower terrace" }
];
const plotDefinitions = [
{ id: "P1", terrace: 0, x: -2.4, z: -6.05 },
{ id: "P2", terrace: 0, x: 2.7, z: -5.15 },
{ id: "P3", terrace: 1, x: -2.6, z: -2.20 },
{ id: "P4", terrace: 1, x: 2.6, z: -1.15 },
{ id: "P5", terrace: 2, x: -2.7, z: 1.05 },
{ id: "P6", terrace: 2, x: 2.5, z: 2.50 },
{ id: "P7", terrace: 3, x: -2.8, z: 5.05 },
{ id: "P8", terrace: 3, x: 2.5, z: 6.45 }
];
const outletDefinitions = [
{ id: "O1", terrace: 1, z: -4, x: 3.4 },
{ id: "O2", terrace: 2, z: 0, x: -3.4 },
{ id: "O3", terrace: 3, z: 4, x: 3.4 },
{ id: "O4", terrace: 4, z: 8, x: -3.4 }
];
const hubsByTerrace = ["source", "O1", "O2", "O3"];
const obstacleDefinitions = [
{ terrace: 0, x: -2.90, z: -5.45, r: 0.66 },
{ terrace: 0, x: 0.70, z: -6.15, r: 0.50 },
{ terrace: 1, x: 0.00, z: -1.70, r: 0.75 },
{ terrace: 2, x: 0.15, z: 2.15, r: 0.75 },
{ terrace: 3, x: -0.15, z: 6.15, r: 0.75 }
];
const initialOutletX = Object.fromEntries(
outletDefinitions.map(outlet => [outlet.id, outlet.x])
);
const state = {
routes: new Map(),
routeOrder: [],
requirements: [],
requirementByPair: new Map(),
active: null,
complete: false,
flowing: false,
draggingOutlet: null,
pointerDown: null,
camera: {
theta: 0.69,
phi: 0.72,
radius: 20.5,
target: new THREE.Vector3(0, 1.15, 0)
}
};
// -------------------------------------------------------------------------
// Renderer, camera, lighting
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color("#cbd9cf");
scene.fog = new THREE.Fog("#cbd9cf", 27, 48);
const camera = new THREE.PerspectiveCamera(
42,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
viewport.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight("#f5f4d9", "#6b806f", 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight("#fff3cf", 3.1);
sun.position.set(-8, 15, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -15;
sun.shadow.camera.right = 15;
sun.shadow.camera.top = 16;
sun.shadow.camera.bottom = -16;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 45;
sun.shadow.normalBias = 0.035;
scene.add(sun);
const fill = new THREE.DirectionalLight("#b9d9df", 1.0);
fill.position.set(10, 7, -10);
scene.add(fill);
// -------------------------------------------------------------------------
// Materials and helpers
// -------------------------------------------------------------------------
function standard(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.88,
metalness: 0,
flatShading: true,
...options
});
}
const materials = {
soil: standard("#896445"),
soilDark: standard("#654934"),
grass: [
standard("#7d9c58"),
standard("#759550"),
standard("#88a45e"),
standard("#6f914e")
],
rock: standard("#747a72"),
rockLight: standard("#8b9189"),
wood: standard("#9a6337"),
woodDark: standard("#6b472c"),
water: standard("#1599bd", {
roughness: 0.35,
metalness: 0.05,
emissive: "#0c6377",
emissiveIntensity: 0.45
}),
invalid: standard("#d94f48", {
roughness: 0.5,
emissive: "#7e211d",
emissiveIntensity: 0.32
}),
droplet: new THREE.MeshBasicMaterial({ color: "#c9f6ff" }),
plotSoil: standard("#705039"),
crop: standard("#628d45"),
cropFed: standard("#4fa13b", {
emissive: "#244b1d",
emissiveIntensity: 0.25
}),
outlet: standard("#d87836"),
outletDark: standard("#9f4f28"),
source: standard("#237f9c")
};
const nodes = new Map();
const interactiveMeshes = [];
const terrainPickMeshes = [];
const plotCropMaterials = new Map();
const pulseNodes = new Map();
const segmentGeometryCache = new Map();
const dropletGeometry = new THREE.OctahedronGeometry(0.095, 0);
const nodeMarkerGeometry = new THREE.OctahedronGeometry(0.17, 0);
function addInteractive(mesh, nodeId) {
mesh.userData.nodeId = nodeId;
interactiveMeshes.push(mesh);
}
function makeLabel(text, options = {}) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 64;
const context = canvas.getContext("2d");
context.clearRect(0, 0, 256, 64);
context.fillStyle = options.background || "rgba(248,247,233,0.94)";
context.fillRect(2, 4, 252, 54);
context.strokeStyle = options.border || "rgba(23,54,47,0.20)";
context.lineWidth = 3;
context.strokeRect(2, 4, 252, 54);
context.fillStyle = options.color || "#17362f";
context.font = "800 29px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 128, 32);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
}));
sprite.scale.set(options.width || 1.25, 0.31, 1);
sprite.renderOrder = 20;
sprite.raycast = () => {};
return sprite;
}
function registerNode({
id,
type,
terrace,
anchor,
group
}) {
group.position.copy(anchor);
scene.add(group);
nodes.set(id, {
id,
type,
terrace,
anchor: anchor.clone(),
group
});
}
// -------------------------------------------------------------------------
// Environment
// -------------------------------------------------------------------------
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(80, 80),
standard("#a5b99a")
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = GROUND_Y;
ground.receiveShadow = true;
scene.add(ground);
function buildTerraces() {
terraces.forEach((terrace, index) => {
const depth = terrace.z1 - terrace.z0;
const centerZ = (terrace.z0 + terrace.z1) / 2;
const embankmentHeight = terrace.y - GROUND_Y;
const embankment = new THREE.Mesh(
new THREE.BoxGeometry(WORLD_WIDTH, embankmentHeight, depth),
index % 2 ? materials.soil : materials.soilDark
);
embankment.position.set(0, GROUND_Y + embankmentHeight / 2, centerZ);
embankment.castShadow = true;
embankment.receiveShadow = true;
scene.add(embankment);
const grass = new THREE.Mesh(
new THREE.BoxGeometry(WORLD_WIDTH, 0.14, depth),
materials.grass[index]
);
grass.position.set(0, terrace.y - 0.07, centerZ);
grass.castShadow = true;
grass.receiveShadow = true;
grass.userData.terrace = index;
scene.add(grass);
terrainPickMeshes.push(grass);
const nextY = index < terraces.length - 1
? terraces[index + 1].y
: -0.2;
const wallHeight = terrace.y - nextY;
const wall = new THREE.Mesh(
new THREE.BoxGeometry(WORLD_WIDTH + 0.05, wallHeight, 0.19),
materials.soilDark
);
wall.position.set(0, nextY + wallHeight / 2, terrace.z1 - 0.02);
wall.castShadow = true;
wall.receiveShadow = true;
scene.add(wall);
for (let block = 0; block < 12; block++) {
const blockWidth = WORLD_WIDTH / 12;
const blockMesh = new THREE.Mesh(
new THREE.BoxGeometry(blockWidth * 0.91, wallHeight * 0.72, 0.12),
block % 2 ? materials.rock : materials.rockLight
);
blockMesh.position.set(
-HALF_WIDTH + blockWidth * (block + 0.5),
nextY + wallHeight * 0.53,
terrace.z1 + 0.09
);
blockMesh.rotation.z = (block % 3 - 1) * 0.018;
blockMesh.castShadow = true;
scene.add(blockMesh);
}
const label = makeLabel(
`T${index + 1} • ${terrace.y.toFixed(1)} m`,
{
width: 1.45,
color: "#496259",
background: "rgba(245,242,220,0.78)"
}
);
label.position.set(-5.15, terrace.y + 0.58, centerZ);
scene.add(label);
});
}
function buildTree(x, z, y, scale = 1) {
const group = new THREE.Group();
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.09 * scale, 0.13 * scale, 0.85 * scale, 6),
materials.woodDark
);
trunk.position.y = 0.42 * scale;
trunk.castShadow = true;
group.add(trunk);
const crown = new THREE.Mesh(
new THREE.ConeGeometry(0.48 * scale, 1.35 * scale, 7),
standard(indexColor(group.id))
);
crown.position.y = 1.25 * scale;
crown.castShadow = true;
group.add(crown);
group.position.set(x, y, z);
scene.add(group);
}
function indexColor(id) {
const colors = ["#4f7950", "#628652", "#416c48", "#769658"];
return colors[Math.abs(id) % colors.length];
}
function buildDecoration() {
const treeData = [
[-5.55, -7.15, 3.00, 0.72],
[ 5.45, -6.40, 3.00, 0.80],
[-5.55, -2.75, 2.20, 0.66],
[ 5.50, -1.20, 2.20, 0.78],
[-5.55, 1.15, 1.40, 0.72],
[ 5.45, 2.85, 1.40, 0.69],
[-5.55, 5.30, 0.60, 0.75],
[ 5.50, 6.85, 0.60, 0.70]
];
treeData.forEach((entry, index) => {
buildTree(entry[0], entry[1], entry[2], entry[3]);
});
}
function buildSource() {
const anchor = new THREE.Vector3(-4.7, 3.14, -7.2);
const group = new THREE.Group();
const tank = new THREE.Mesh(
new THREE.CylinderGeometry(0.48, 0.55, 0.66, 8),
materials.source
);
tank.position.y = 0.08;
tank.castShadow = true;
group.add(tank);
addInteractive(tank, "source");
const roof = new THREE.Mesh(
new THREE.ConeGeometry(0.58, 0.34, 8),
materials.woodDark
);
roof.position.y = 0.56;
roof.castShadow = true;
group.add(roof);
const marker = new THREE.Mesh(nodeMarkerGeometry, materials.droplet);
marker.scale.setScalar(0.85);
group.add(marker);
const label = makeLabel("SOURCE", { width: 1.35 });
label.position.y = 1.03;
group.add(label);
registerNode({
id: "source",
type: "source",
terrace: 0,
anchor,
group
});
}
function buildOutlet(definition) {
const anchor = new THREE.Vector3(
definition.x,
terraces[definition.terrace]?.y ?? -0.2,
definition.z
);
anchor.y += 0.42;
const group = new THREE.Group();
const leftPost = new THREE.Mesh(
new THREE.BoxGeometry(0.14, 0.82, 0.18),
materials.wood
);
leftPost.position.set(-0.39, 0.02, 0);
leftPost.castShadow = true;
group.add(leftPost);
addInteractive(leftPost, definition.id);
const rightPost = leftPost.clone();
rightPost.position.x = 0.39;
group.add(rightPost);
addInteractive(rightPost, definition.id);
const lintel = new THREE.Mesh(
new THREE.BoxGeometry(0.96, 0.14, 0.21),
materials.woodDark
);
lintel.position.y = 0.43;
lintel.castShadow = true;
group.add(lintel);
addInteractive(lintel, definition.id);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.27, 0.075, 5, 10),
materials.outlet
);
ring.position.y = -0.03;
ring.castShadow = true;
group.add(ring);
addInteractive(ring, definition.id);
const chute = new THREE.Mesh(
new THREE.BoxGeometry(0.18, 0.075, 0.92),
materials.water
);
chute.position.set(0, -0.08, 0.36);
group.add(chute);
addInteractive(chute, definition.id);
const handle = new THREE.Mesh(
new THREE.OctahedronGeometry(0.16, 0),
materials.outlet
);
handle.position.set(0, 0.75, 0);
group.add(handle);
addInteractive(handle, definition.id);
const label = makeLabel(definition.id, {
width: 0.92,
color: "#8d421e",
border: "rgba(216,120,54,0.48)"
});
label.position.y = 1.03;
group.add(label);
registerNode({
id: definition.id,
type: "outlet",
terrace: definition.terrace,
anchor,
group
});
}
function buildPlot(definition, index) {
const terrace = terraces[definition.terrace];
const anchor = new THREE.Vector3(
definition.x,
terrace.y + 0.18,
definition.z - 0.72
);
const bed = new THREE.Mesh(
new THREE.BoxGeometry(1.72, 0.13, 1.43),
materials.plotSoil
);
bed.position.set(definition.x, terrace.y + 0.065, definition.z);
bed.castShadow = true;
bed.receiveShadow = true;
scene.add(bed);
addInteractive(bed, definition.id);
const outline = new THREE.LineSegments(
new THREE.EdgesGeometry(bed.geometry),
new THREE.LineBasicMaterial({ color: "#b68b60" })
);
outline.position.copy(bed.position);
scene.add(outline);
const cropMaterial = materials.crop.clone();
plotCropMaterials.set(definition.id, cropMaterial);
for (let row = 0; row < 3; row++) {
const z = definition.z - 0.48 + row * 0.48;
const furrow = new THREE.Mesh(
new THREE.BoxGeometry(1.5, 0.025, 0.055),
materials.soilDark
);
furrow.position.set(definition.x, terrace.y + 0.145, z);
scene.add(furrow);
for (let column = 0; column < 4; column++) {
const crop = new THREE.Mesh(
new THREE.ConeGeometry(0.12, 0.36, 4),
cropMaterial
);
crop.position.set(
definition.x - 0.54 + column * 0.36,
terrace.y + 0.31,
z
);
crop.rotation.y = (index + row + column) * 0.31;
crop.castShadow = true;
scene.add(crop);
}
}
const group = new THREE.Group();
const marker = new THREE.Mesh(nodeMarkerGeometry, materials.water);
marker.scale.setScalar(0.68);
group.add(marker);
const label = makeLabel(definition.id, { width: 0.76 });
label.position.y = 0.57;
group.add(label);
registerNode({
id: definition.id,
type: "plot",
terrace: definition.terrace,
anchor,
group
});
}
function buildObstacle(definition, index) {
const terrace = terraces[definition.terrace];
const rock = new THREE.Mesh(
new THREE.IcosahedronGeometry(definition.r, 0),
index % 2 ? materials.rock : materials.rockLight
);
rock.position.set(
definition.x,
terrace.y + definition.r * 0.52,
definition.z
);
rock.scale.y = 0.86;
rock.rotation.set(index * 0.41, index * 0.77, index * 0.19);
rock.castShadow = true;
rock.receiveShadow = true;
scene.add(rock);
const ring = new THREE.Mesh(
new THREE.RingGeometry(definition.r * 0.87, definition.r, 20),
new THREE.MeshBasicMaterial({
color: "#a84840",
transparent: true,
opacity: 0.25,
side: THREE.DoubleSide
})
);
ring.rotation.x = -Math.PI / 2;
ring.position.set(
definition.x,
terrace.y + 0.012,
definition.z
);
scene.add(ring);
}
buildTerraces();
buildDecoration();
buildSource();
outletDefinitions.forEach(buildOutlet);
plotDefinitions.forEach(buildPlot);
obstacleDefinitions.forEach(buildObstacle);
// -------------------------------------------------------------------------
// Requirements and route model
// -------------------------------------------------------------------------
function makeRequirement(type, from, to, terrace, label) {
const key = `${from}|${to}`;
const requirement = { key, type, from, to, terrace, label };
state.requirements.push(requirement);
state.requirementByPair.set(key, requirement);
return requirement;
}
const chainRequirements = [];
terraces.forEach((terrace, index) => {
const from = hubsByTerrace[index];
const to = `O${index + 1}`;
chainRequirements.push(makeRequirement(
"chain",
from,
to,
index,
`${from.toUpperCase()} → ${to}`
));
});
const plotRequirements = plotDefinitions.map(plot => {
const from = hubsByTerrace[plot.terrace];
return makeRequirement(
"plot",
from,
plot.id,
plot.terrace,
`${from.toUpperCase()} → ${plot.id}`
);
});
function allowedTargets(from) {
const targets = new Set();
state.requirements.forEach(requirement => {
if (requirement.from === from) {
targets.add(requirement.to);
}
});
return targets;
}
function requirementFor(from, to) {
return state.requirementByPair.get(`${from}|${to}`);
}
function upstreamChainValid(terrace) {
for (let index = 0; index <= terrace; index++) {
const route = state.routes.get(chainRequirements[index].key);
if (!route || !route.valid) return false;
}
return true;
}
function plotIsFed(plotId) {
const plot = plotDefinitions.find(item => item.id === plotId);
const requirement = plotRequirements.find(item => item.to === plotId);
const route = state.routes.get(requirement.key);
return Boolean(
route &&
route.valid &&
upstreamChainValid(plot.terrace)
);
}
function distanceToSegment2D(px, pz, ax, az, bx, bz) {
const dx = bx - ax;
const dz = bz - az;
const lengthSquared = dx * dx + dz * dz;
if (lengthSquared === 0) {
return Math.hypot(px - ax, pz - az);
}
const t = THREE.MathUtils.clamp(
((px - ax) * dx + (pz - az) * dz) / lengthSquared,
0,
1
);
const closestX = ax + t * dx;
const closestZ = az + t * dz;
return Math.hypot(px - closestX, pz - closestZ);
}
function validateRoute(route) {
const terrace = terraces[route.terrace];
const reasons = [];
route.waypoints.forEach(point => {
if (
point.z < terrace.z0 - 0.02 ||
point.z > terrace.z1 - 0.08 ||
point.x < -HALF_WIDTH + 0.08 ||
point.x > HALF_WIDTH - 0.08
) {
reasons.push("A bend leaves the active terrace surface.");
}
});
for (let index = 0; index < route.points.length - 1; index++) {
const a = route.points[index];
const b = route.points[index + 1];
const minZ = Math.min(a.z, b.z);
const maxZ = Math.max(a.z, b.z);
if (
minZ < terrace.z0 - 0.06 ||
maxZ > terrace.z1 + 0.06
) {
reasons.push("A channel segment crosses an unapproved retaining edge.");
}
obstacleDefinitions
.filter(obstacle => obstacle.terrace === route.terrace)
.forEach(obstacle => {
const distance = distanceToSegment2D(
obstacle.x,
obstacle.z,
a.x,
a.z,
b.x,
b.z
);
if (distance < obstacle.r - 0.035) {
reasons.push("A channel segment intersects a terrace stone.");
}
});
}
const target = nodes.get(route.to);
if (target.type === "outlet") {
if (Math.abs(target.anchor.z - terrace.z1) > 0.06) {
reasons.push("The downstream outlet is not on this terrace's edge.");
}
} else if (target.terrace !== route.terrace) {
reasons.push("The target plot belongs to another terrace.");
}
route.valid = reasons.length === 0;
route.reason = [...new Set(reasons)].join(" ");
return route.valid;
}
function getSegmentGeometry(length) {
const rounded = Math.max(0.05, Math.round(length * 1000) / 1000);
if (!segmentGeometryCache.has(rounded)) {
segmentGeometryCache.set(
rounded,
new THREE.CylinderGeometry(0.082, 0.082, rounded, 6)
);
}
return segmentGeometryCache.get(rounded);
}
function disposeRouteVisual(route) {
if (!route.group) return;
route.segmentMeshes?.forEach(mesh => {
mesh.geometry.dispose();
});
while (route.group.children.length) {
route.group.remove(route.group.children[0]);
}
}
function buildRouteVisual(route) {
disposeRouteVisual(route);
route.group = route.group || new THREE.Group();
if (!route.group.parent) scene.add(route.group);
route.segmentMeshes = [];
route.flowDots = [];
const totalLength = route.totalLength || 1;
let cumulative = 0;
const material = route.valid ? materials.water : materials.invalid;
for (let index = 0; index < route.points.length - 1; index++) {
const a = route.points[index];
const b = route.points[index + 1];
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
if (length < 0.001) continue;
const geometry = getSegmentGeometry(length);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.clone().normalize()
);
mesh.castShadow = true;
mesh.receiveShadow = true;
route.group.add(mesh);
route.segmentMeshes.push(mesh);
const dotCount = Math.max(1, Math.min(3, Math.ceil(length / 1.5)));
for (let dot = 0; dot < dotCount; dot++) {
const droplet = new THREE.Mesh(dropletGeometry, materials.droplet);
droplet.visible = false;
route.group.add(droplet);
route.flowDots.push({
mesh: droplet,
offset: (cumulative + length * dot / dotCount) / totalLength
});
}
cumulative += length;
}
}
function rebuildRoute(route) {
const from = nodes.get(route.from);
const to = nodes.get(route.to);
route.points = [
from.anchor.clone(),
...route.waypoints.map(point => point.clone()),
to.anchor.clone()
];
route.totalLength = 0;
for (let index = 0; index < route.points.length - 1; index++) {
route.totalLength += route.points[index].distanceTo(route.points[index + 1]);
}
validateRoute(route);
buildRouteVisual(route);
}
function commitRoute(from, to, waypoints = []) {
const requirement = requirementFor(from, to);
if (!requirement) return false;
const key = requirement.key;
const oldRoute = state.routes.get(key);
if (oldRoute) {
disposeRouteVisual(oldRoute);
state.routeOrder = state.routeOrder.filter(item => item !== key);
}
const route = {
key,
from,
to,
terrace: requirement.terrace,
waypoints: waypoints.map(point => point.clone()),
points: [],
valid: false,
reason: "",
group: new THREE.Group(),
flowDots: [],
segmentMeshes: []
};
state.routes.set(key, route);
state.routeOrder.push(key);
rebuildRoute(route);
refreshUI();
if (!route.valid) {
showToast(route.reason || "That route violates a geometric rule.", true);
}
return true;
}
function removeRoute(key) {
const route = state.routes.get(key);
if (!route) return;
disposeRouteVisual(route);
state.routes.delete(key);
state.routeOrder = state.routeOrder.filter(item => item !== key);
refreshUI();
}
function clearRoutes() {
state.routes.forEach(route => disposeRouteVisual(route));
state.routes.clear();
state.routeOrder = [];
state.active = null;
state.flowing = false;
updatePreview();
refreshUI();
}
// -------------------------------------------------------------------------
// Interaction and route drawing
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const previewLine = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({
color: "#1595b4",
transparent: true,
opacity: 0.9
})
);
previewLine.visible = false;
previewLine.renderOrder = 12;
scene.add(previewLine);
function setRay(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
function getNodeHit(event) {
setRay(event);
const hits = raycaster.intersectObjects(interactiveMeshes, false);
if (!hits.length) return null;
const nodeId = hits[0].object.userData.nodeId;
return nodeId ? nodes.get(nodeId) : null;
}
function getTerraceHit(event) {
setRay(event);
const hits = raycaster.intersectObjects(terrainPickMeshes, false);
if (!hits.length) return null;
const hit = hits[0];
return {
terrace: hit.object.userData.terrace,
point: hit.point.clone()
};
}
function startRoute(from) {
const node = nodes.get(from);
if (!node || node.type === "plot" || from === "O4") {
showToast("Start at the SOURCE or at outlet O1, O2, or O3.", true);
return;
}
state.active = {
from,
terrace: hubsByTerrace.indexOf(from),
waypoints: [],
hover: null
};
updatePreview();
showToast(`Route started at ${from.toUpperCase()}. Click soil to add bends, then a permitted target.`);
}
function cancelRoute() {
state.active = null;
updatePreview();
}
function finishRoute(to) {
if (!state.active) return;
const from = state.active.from;
const requirement = requirementFor(from, to);
if (!requirement) {
showToast(
`Invalid step. ${from.toUpperCase()} may only connect to its immediate downstream outlet or its terrace plots.`,
true
);
return;
}
commitRoute(from, to, state.active.waypoints);
cancelRoute();
}
function handleClick(event) {
const nodeHit = getNodeHit(event);
if (nodeHit) {
if (state.active) {
if (allowedTargets(state.active.from).has(nodeHit.id)) {
finishRoute(nodeHit.id);
} else if (
nodeHit.type === "source" ||
(nodeHit.type === "outlet" && nodeHit.id !== "O4")
) {
const nextFrom = nodeHit.id;
cancelRoute();
startRoute(nextFrom);
} else {
showToast("That target would bypass a terrace step.", true);
}
} else {
if (
nodeHit.type === "source" ||
(nodeHit.type === "outlet" && nodeHit.id !== "O4")
) {
startRoute(nodeHit.id);
} else if (nodeHit.type === "plot") {
const plot = plotDefinitions.find(item => item.id === nodeHit.id);
const from = hubsByTerrace[plot.terrace];
commitRoute(from, plot.id);
} else {
showToast("O4 is the terminal spillway. Connect O3 to it first.");
}
}
return;
}
const terraceHit = getTerraceHit(event);
if (state.active) {
if (!terraceHit) {
showToast("Click the terrace surface to place a channel bend.", true);
return;
}
const terrace = terraces[state.active.terrace];
if (terraceHit.terrace !== state.active.terrace) {
showToast("That bend is on another terrace. Stay on the active surface.", true);
return;
}
const point = terraceHit.point;
if (
point.z < terrace.z0 + 0.10 ||
point.z > terrace.z1 - 0.14
) {
showToast("Place bends inside the active terrace rectangle.", true);
return;
}
state.active.waypoints.push(
new THREE.Vector3(point.x, terrace.y + 0.15, point.z)
);
updatePreview();
} else {
showToast("Start with the SOURCE or an outlet gate.");
}
}
function updatePreview() {
if (!state.active || !state.active.hover) {
previewLine.visible = false;
return;
}
const lastPoint = state.active.waypoints.length
? state.active.waypoints[state.active.waypoints.length - 1]
: nodes.get(state.active.from).anchor;
previewLine.geometry.dispose();
previewLine.geometry = new THREE.BufferGeometry().setFromPoints([
lastPoint,
state.active.hover
]);
previewLine.visible = true;
}
function updateHover(event) {
if (!state.active) {
renderer.domElement.style.cursor = "grab";
return;
}
const hit = getTerraceHit(event);
if (!hit || hit.terrace !== state.active.terrace) {
state.active.hover = null;
previewLine.visible = false;
renderer.domElement.style.cursor = "crosshair";
return;
}
state.active.hover = hit.point.clone();
state.active.hover.y = terraces[hit.terrace].y + 0.15;
updatePreview();
renderer.domElement.style.cursor = "crosshair";
}
function moveOutlet(outletId, x) {
const node = nodes.get(outletId);
if (!node) return;
node.anchor.x = THREE.MathUtils.clamp(x, -5.35, 5.35);
node.group.position.x = node.anchor.x;
state.routes.forEach(rebuildRoute);
refreshUI();
}
renderer.domElement.addEventListener("pointerdown", event => {
const nodeHit = getNodeHit(event);
const pointerState = {
startX: event.clientX,
startY: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
button: event.button,
nodeHit,
orbiting: event.button !== 0 || event.altKey,
draggingOutlet: false
};
state.pointerDown = pointerState;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
});
renderer.domElement.addEventListener("pointermove", event => {
updateHover(event);
const pointerState = state.pointerDown;
if (!pointerState) return;
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
const totalDistance = Math.hypot(
event.clientX - pointerState.startX,
event.clientY - pointerState.startY
);
if (
pointerState.button === 0 &&
!pointerState.draggingOutlet &&
pointerState.nodeHit?.type === "outlet" &&
totalDistance > 5
) {
pointerState.draggingOutlet = true;
state.draggingOutlet = pointerState.nodeHit.id;
}
if (pointerState.draggingOutlet) {
setRay(event);
const plane = new THREE.Plane(
new THREE.Vector3(0, 1, 0),
-nodes.get(state.draggingOutlet).anchor.y
);
const intersection = new THREE.Vector3();
if (raycaster.ray.intersectPlane(plane, intersection)) {
moveOutlet(state.draggingOutlet, intersection.x);
}
} else if (
pointerState.orbiting ||
(totalDistance > 6 && pointerState.button === 0)
) {
pointerState.orbiting = true;
state.camera.theta -= dx * 0.006;
state.camera.phi = THREE.MathUtils.clamp(
state.camera.phi - dy * 0.005,
0.34,
1.30
);
}
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
});
renderer.domElement.addEventListener("pointerup", event => {
const pointerState = state.pointerDown;
state.pointerDown = null;
state.draggingOutlet = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
if (!pointerState) return;
const totalDistance = Math.hypot(
event.clientX - pointerState.startX,
event.clientY - pointerState.startY
);
if (pointerState.draggingOutlet) {
refreshUI();
showToast(`${pointerState.nodeHit.id} moved. Existing channels were rechecked geometrically.`);
} else if (!pointerState.orbiting && totalDistance < 6 && event.button === 0) {
handleClick(event);
}
renderer.domElement.style.cursor = state.active ? "crosshair" : "grab";
});
renderer.domElement.addEventListener("pointercancel", event => {
state.pointerDown = null;
state.draggingOutlet = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("contextmenu", event => {
event.preventDefault();
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
state.camera.radius = THREE.MathUtils.clamp(
state.camera.radius + event.deltaY * 0.012,
11,
31
);
}, { passive: false });
// -------------------------------------------------------------------------
// UI, hints, and controls
// -------------------------------------------------------------------------
const requirementElements = new Map();
function createRequirementElement(requirement) {
const element = document.createElement("div");
element.className = "req";
element.innerHTML = `
<span class="dot"></span>
<span class="label">${requirement.label}</span>
<span class="state">open</span>
`;
requirementElements.set(requirement.key, element);
return element;
}
chainRequirements.forEach(requirement => {
$("chainList").appendChild(createRequirementElement(requirement));
});
plotRequirements.forEach(requirement => {
$("plotList").appendChild(createRequirementElement(requirement));
});
function refreshUI() {
let validRoutes = 0;
let validChains = 0;
let fedPlots = 0;
chainRequirements.forEach(requirement => {
const route = state.routes.get(requirement.key);
if (route?.valid) {
validRoutes++;
validChains++;
}
});
plotRequirements.forEach(requirement => {
const route = state.routes.get(requirement.key);
if (route?.valid) validRoutes++;
if (plotIsFed(requirement.to)) fedPlots++;
});
const complete = state.requirements.every(requirement => {
return state.routes.get(requirement.key)?.valid;
});
if (complete !== state.complete) {
state.complete = complete;
if (complete) {
state.flowing = true;
successElement.classList.add("show");
showToast("Complete! Every plot is connected through its required terrace steps.");
} else {
state.flowing = false;
successElement.classList.remove("show");
}
}
state.requirements.forEach(requirement => {
const element = requirementElements.get(requirement.key);
const route = state.routes.get(requirement.key);
element.classList.remove("done", "bad");
let status = "open";
if (route && !route.valid) {
element.classList.add("bad");
status = "blocked";
} else if (requirement.type === "chain" && route?.valid) {
element.classList.add("done");
status = "done";
} else if (requirement.type === "plot" && plotIsFed(requirement.to)) {
element.classList.add("done");
status = "fed";
} else if (requirement.type === "plot" && route?.valid) {
status = "waiting";
}
element.querySelector(".state").textContent = status;
});
plotDefinitions.forEach(plot => {
const material = plotCropMaterials.get(plot.id);
const fed = plotIsFed(plot.id);
material.color.set(fed ? "#4fa13b" : "#628d45");
material.emissive.set(fed ? "#244b1d" : "#000000");
material.emissiveIntensity = fed ? 0.25 : 0;
});
$("chainMetric").textContent = `${validChains}/4`;
$("plotMetric").textContent = `${fedPlots}/8`;
$("routeMetric").textContent = `${validRoutes}/12`;
$("progressBadge").textContent = `${validRoutes} / 12`;
$("flowBtn").textContent = state.flowing ? "Pause water" : "Release water";
$("flowBtn").disabled = !state.complete;
}
let toastTimer;
function showToast(message, isError = false) {
toastElement.textContent = message;
toastElement.classList.toggle("error", isError);
toastElement.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toastElement.classList.remove("show");
}, 3600);
}
function pulseNode(nodeId) {
pulseNodes.set(nodeId, performance.now());
}
function showHint() {
const missingChain = chainRequirements.find(requirement => {
return !state.routes.get(requirement.key)?.valid;
});
if (missingChain) {
const outlet = missingChain.to;
const current = nodes.get(outlet).anchor.x;
const suggestion = -3.8;
pulseNode(outlet);
pulseNode(missingChain.from);
if (Math.abs(current - suggestion) > 0.6) {
showToast(
`Try moving ${outlet} to about x = −3.8 m. Its current diagonal meets the center stone; align the gates to make a clear corridor.`
);
} else {
showToast(
`${outlet} is aligned. Connect ${missingChain.from.toUpperCase()} → ${outlet}, adding a bend if the channel turns red.`
);
}
return;
}
const missingPlot = plotRequirements.find(requirement => {
return !state.routes.get(requirement.key)?.valid;
});
if (missingPlot) {
pulseNode(missingPlot.from);
pulseNode(missingPlot.to);
showToast(
`Now connect ${missingPlot.from.toUpperCase()} → ${missingPlot.to}. Keep the channel inside that terrace and around the stones.`
);
return;
}
showToast("All required routes are geometrically valid.");
}
function undo() {
if (state.active?.waypoints.length) {
state.active.waypoints.pop();
updatePreview();
return;
}
const lastKey = state.routeOrder[state.routeOrder.length - 1];
if (lastKey) {
removeRoute(lastKey);
showToast("Last route removed.");
}
}
function resetCamera() {
state.camera.theta = 0.69;
state.camera.phi = 0.72;
state.camera.radius = 20.5;
state.camera.target.set(0, 1.15, 0);
}
function resetPuzzle() {
clearRoutes();
outletDefinitions.forEach(outlet => {
const node = nodes.get(outlet.id);
node.anchor.x = initialOutletX[outlet.id];
node.group.position.x = node.anchor.x;
});
state.routes.forEach(rebuildRoute);
state.complete = false;
state.flowing = false;
successElement.classList.remove("show");
refreshUI();
showToast("Puzzle reset.");
}
$("undoBtn").addEventListener("click", undo);
$("clearBtn").addEventListener("click", () => {
clearRoutes();
showToast("All routes cleared.");
});
$("hintBtn").addEventListener("click", showHint);
$("flowBtn").addEventListener("click", () => {
if (!state.complete) {
showToast("Complete all terrace steps and plot branches before releasing water.", true);
return;
}
state.flowing = !state.flowing;
refreshUI();
});
$("viewBtn").addEventListener("click", resetCamera);
$("resetBtn").addEventListener("click", resetPuzzle);
$("closeSuccess").addEventListener("click", () => {
successElement.classList.remove("show");
});
window.addEventListener("keydown", event => {
if (event.key === "Escape") {
cancelRoute();
showToast("Route cancelled.");
}
if (event.key.toLowerCase() === "z" && !event.ctrlKey && !event.metaKey) {
undo();
}
});
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
function pointAlongRoute(route, distance) {
let remaining = distance;
for (let index = 0; index < route.points.length - 1; index++) {
const a = route.points[index];
const b = route.points[index + 1];
const length = a.distanceTo(b);
if (remaining <= length) {
const t = length === 0 ? 0 : remaining / length;
return new THREE.Vector3().lerpVectors(a, b, t);
}
remaining -= length;
}
return route.points[route.points.length - 1].clone();
}
function updateCamera() {
const { theta, phi, radius, target } = state.camera;
const sinPhi = Math.sin(phi);
camera.position.set(
target.x + radius * sinPhi * Math.sin(theta),
target.y + radius * Math.cos(phi),
target.z + radius * sinPhi * Math.cos(theta)
);
camera.lookAt(target);
}
let previousTime = performance.now();
function animate(time) {
requestAnimationFrame(animate);
const delta = Math.min((time - previousTime) / 1000, 0.05);
previousTime = time;
updateCamera();
state.routes.forEach(route => {
route.flowDots.forEach(dot => {
dot.mesh.visible = state.flowing && route.valid;
if (dot.mesh.visible) {
const distance = (
time * 0.00135 * route.totalLength +
dot.offset * route.totalLength
) % route.totalLength;
dot.mesh.position.copy(pointAlongRoute(route, distance));
dot.mesh.rotation.x += delta * 5;
dot.mesh.rotation.y += delta * 4;
}
});
});
pulseNodes.forEach((startTime, nodeId) => {
const node = nodes.get(nodeId);
const elapsed = (time - startTime) / 1000;
if (elapsed > 2.2) {
node.group.scale.setScalar(1);
pulseNodes.delete(nodeId);
return;
}
const scale = 1 + Math.sin(elapsed * 8) * 0.09 * (1 - elapsed / 2.2);
node.group.scale.setScalar(scale);
});
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
refreshUI();
updateCamera();
requestAnimationFrame(animate);
</script>
</body>
</html>
```