Prompt specification
Build or customize the Three.js 3D scene "Nutrient-cycle pathway 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: Nutrient-cycle pathway puzzle
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/nutrient-cycle-pathway-puzzle-x0728
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows forest-floor decomposition. Create a forest-floor board where users connect litter, decomposers, soil resources, and plants; conserved symbolic nutrient tokens move through the selected valid pathways over time. Low-poly.
Working Three.js Starter (nutrient-cycle-pathway-puzzle-x0728):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#15261d" />
<title>Forest Floor — Nutrient Pathway Lab</title>
<style>
:root {
--ink: #f4f0dc;
--muted: #aebba8;
--panel: rgba(19, 36, 28, 0.88);
--panel-2: rgba(29, 50, 39, 0.76);
--line: rgba(230, 244, 211, 0.16);
--accent: #d4f58c;
--accent-dark: #273a20;
--litter: #d9a441;
--decomposer: #e4775b;
--soil: #a98bd8;
--plant: #77c878;
--nitrogen: #55d6c3;
--phosphorus: #f4bd4f;
--potassium: #ed7fad;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #aab79b;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
#labels {
position: fixed;
inset: 0;
z-index: 2;
pointer-events: none;
overflow: hidden;
}
.hero {
position: fixed;
z-index: 5;
top: 28px;
left: 30px;
max-width: 560px;
pointer-events: none;
text-shadow: 0 2px 20px rgba(15, 27, 18, 0.42);
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
color: #e7f2d8;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.2em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 24px;
height: 2px;
background: var(--accent);
}
.hero h1 {
margin: 8px 0 2px;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(38px, 5vw, 68px);
font-weight: 500;
line-height: 0.98;
letter-spacing: -0.045em;
}
.hero p {
margin: 10px 0 0;
color: #e5ecdc;
font-size: 14px;
line-height: 1.45;
}
.conservation-badge {
position: fixed;
z-index: 6;
top: 28px;
right: 30px;
display: flex;
align-items: center;
gap: 11px;
padding: 10px 14px;
border: 1px solid rgba(234, 255, 211, 0.25);
border-radius: 999px;
background: rgba(22, 42, 30, 0.86);
box-shadow: 0 12px 34px rgba(12, 24, 15, 0.2);
backdrop-filter: blur(12px);
font-size: 11px;
font-weight: 750;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.conservation-badge .status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 0 4px rgba(212, 245, 140, 0.12);
}
.panel {
position: fixed;
z-index: 5;
width: 286px;
border: 1px solid var(--line);
border-radius: 18px;
background:
linear-gradient(145deg, rgba(255, 255, 255, 0.035), transparent 48%),
var(--panel);
box-shadow: 0 20px 55px rgba(13, 26, 17, 0.24);
backdrop-filter: blur(18px) saturate(115%);
overflow: hidden;
}
.builder {
left: 30px;
top: 178px;
}
.simulation {
right: 30px;
top: 98px;
width: 274px;
}
.panel-head {
padding: 18px 18px 14px;
border-bottom: 1px solid var(--line);
}
.panel-kicker {
color: var(--accent);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.panel h2 {
margin: 7px 0 6px;
font-family: Georgia, "Times New Roman", serif;
font-size: 22px;
font-weight: 500;
letter-spacing: -0.02em;
}
.panel-copy {
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.panel-body {
padding: 15px 16px 17px;
}
.node-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-bottom: 11px;
}
.palette-node {
position: relative;
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
padding: 10px 9px;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
cursor: pointer;
text-align: left;
transition:
transform 150ms ease,
border-color 150ms ease,
background 150ms ease;
}
.palette-node:hover {
transform: translateY(-1px);
border-color: rgba(255, 255, 255, 0.25);
background: rgba(255, 255, 255, 0.075);
}
.palette-node.selected {
border-color: var(--accent);
background: rgba(212, 245, 140, 0.12);
box-shadow: inset 0 0 0 1px rgba(212, 245, 140, 0.13);
}
.palette-node.valid-target {
border-color: rgba(212, 245, 140, 0.58);
background: rgba(212, 245, 140, 0.07);
}
.palette-icon {
display: grid;
place-items: center;
flex: 0 0 auto;
width: 22px;
height: 22px;
border-radius: 7px;
color: #142019;
background: var(--node-color);
font-size: 10px;
font-weight: 900;
transform: rotate(-3deg);
}
.palette-node span:last-child {
overflow: hidden;
font-size: 10px;
font-weight: 700;
line-height: 1.15;
text-overflow: ellipsis;
}
.selection-status {
min-height: 34px;
padding: 9px 10px;
border: 1px dashed rgba(212, 245, 140, 0.26);
border-radius: 9px;
color: #d7e1cf;
background: rgba(0, 0, 0, 0.1);
font-size: 10px;
line-height: 1.4;
}
.route-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin: 16px 1px 8px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.route-heading span:last-child {
color: var(--accent);
letter-spacing: 0.04em;
}
.route-list {
display: grid;
gap: 6px;
}
.route-row {
display: grid;
grid-template-columns: 1fr auto;
align-items: center;
gap: 8px;
width: 100%;
padding: 9px 10px;
border: 1px solid rgba(255, 255, 255, 0.09);
border-radius: 9px;
background: rgba(255, 255, 255, 0.025);
cursor: pointer;
text-align: left;
transition: 150ms ease;
}
.route-row:hover {
border-color: rgba(255, 255, 255, 0.22);
background: rgba(255, 255, 255, 0.06);
}
.route-row.active {
border-color: rgba(212, 245, 140, 0.32);
background: rgba(212, 245, 140, 0.065);
}
.route-name {
display: block;
font-size: 10px;
font-weight: 750;
}
.route-state {
display: flex;
align-items: center;
gap: 6px;
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.route-state::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: #657064;
}
.route-row.active .route-state {
color: var(--accent);
}
.route-row.active .route-state::before {
background: var(--accent);
box-shadow: 0 0 8px rgba(212, 245, 140, 0.65);
}
.mini-note {
margin: 13px 1px 0;
color: #8f9d8b;
font-size: 9px;
line-height: 1.45;
}
.conservation-card {
padding: 13px;
border: 1px solid rgba(212, 245, 140, 0.18);
border-radius: 12px;
background: rgba(212, 245, 140, 0.055);
}
.conservation-top {
display: flex;
align-items: end;
justify-content: space-between;
gap: 12px;
}
.big-number {
font-family: Georgia, "Times New Roman", serif;
font-size: 34px;
line-height: 1;
color: var(--accent);
}
.big-number small {
color: #aebba8;
font-family: inherit;
font-size: 13px;
}
.moving-count {
color: var(--muted);
font-size: 9px;
line-height: 1.45;
text-align: right;
}
.token-ledger {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-top: 12px;
}
.token-key {
display: flex;
align-items: center;
gap: 6px;
padding: 7px;
border-radius: 8px;
background: rgba(0, 0, 0, 0.12);
font-size: 9px;
font-weight: 800;
}
.token-key i {
display: block;
width: 9px;
height: 9px;
transform: rotate(45deg);
}
.token-key[data-type="N"] i {
border-radius: 2px;
background: var(--nitrogen);
}
.token-key[data-type="P"] i {
background: var(--phosphorus);
clip-path: polygon(50% 0, 100% 100%, 0 100%);
transform: none;
}
.token-key[data-type="K"] i {
border-radius: 50%;
background: var(--potassium);
transform: none;
}
.token-key span:last-child {
color: #aebba8;
}
.control-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-top: 14px;
}
.control-label {
color: var(--muted);
font-size: 10px;
font-weight: 700;
}
.control-value {
color: var(--accent);
font-size: 10px;
font-weight: 850;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 12px 0 3px;
border-radius: 99px;
appearance: none;
background: linear-gradient(
90deg,
var(--accent) 0%,
var(--accent) 40%,
rgba(255, 255, 255, 0.13) 40%,
rgba(255, 255, 255, 0.13) 100%
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
border: 3px solid #233729;
border-radius: 50%;
appearance: none;
background: var(--accent);
box-shadow: 0 0 0 1px rgba(212, 245, 140, 0.3);
}
input[type="range"]::-moz-range-thumb {
width: 10px;
height: 10px;
border: 3px solid #233729;
border-radius: 50%;
background: var(--accent);
}
.button-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-top: 16px;
}
.control-button {
display: flex;
align-items: center;
justify-content: center;
gap: 7px;
min-height: 37px;
padding: 8px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 9px;
background: rgba(255, 255, 255, 0.04);
cursor: pointer;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.03em;
transition: 150ms ease;
}
.control-button:hover {
border-color: rgba(212, 245, 140, 0.38);
background: rgba(212, 245, 140, 0.08);
}
.control-button.primary {
border-color: rgba(212, 245, 140, 0.36);
color: var(--accent);
background: rgba(212, 245, 140, 0.09);
}
.control-icon {
width: 8px;
height: 8px;
border-left: 2px solid currentColor;
border-top: 2px solid currentColor;
transform: rotate(-45deg);
}
.node-tag {
--node-color: #ffffff;
position: absolute;
top: 0;
left: 0;
display: flex;
align-items: center;
gap: 8px;
min-width: 116px;
padding: 7px 9px;
border: 1px solid rgba(255, 255, 255, 0.25);
border-radius: 10px;
background: rgba(19, 34, 25, 0.9);
box-shadow: 0 8px 22px rgba(11, 23, 14, 0.26);
backdrop-filter: blur(9px);
cursor: pointer;
pointer-events: auto;
transform-origin: 50% 100%;
transition:
border-color 150ms ease,
background 150ms ease,
box-shadow 150ms ease;
will-change: transform;
}
.node-tag:hover,
.node-tag.selected {
border-color: var(--node-color);
background: rgba(25, 43, 31, 0.96);
box-shadow:
0 8px 24px rgba(11, 23, 14, 0.3),
0 0 0 2px color-mix(in srgb, var(--node-color) 22%, transparent);
}
.node-tag .tag-icon {
display: grid;
place-items: center;
width: 22px;
height: 22px;
flex: 0 0 auto;
border-radius: 7px;
color: #162219;
background: var(--node-color);
font-size: 9px;
font-weight: 950;
transform: rotate(-3deg);
}
.node-tag b {
display: block;
font-size: 10px;
line-height: 1.1;
white-space: nowrap;
}
.node-tag small {
display: block;
margin-top: 3px;
color: #aebba8;
font-size: 8px;
white-space: nowrap;
}
.node-tag small span {
color: var(--node-color);
font-weight: 850;
}
.toast {
position: fixed;
z-index: 10;
left: 50%;
bottom: 64px;
max-width: min(520px, calc(100vw - 32px));
padding: 11px 16px;
border: 1px solid rgba(212, 245, 140, 0.32);
border-radius: 999px;
background: rgba(20, 38, 27, 0.94);
box-shadow: 0 12px 34px rgba(9, 22, 13, 0.3);
color: #eef6e6;
font-size: 11px;
font-weight: 700;
text-align: center;
pointer-events: none;
opacity: 0;
transform: translate(-50%, 12px);
transition:
opacity 180ms ease,
transform 180ms ease;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
.toast.error {
border-color: rgba(228, 119, 91, 0.5);
}
.camera-hint {
position: fixed;
z-index: 4;
right: 30px;
bottom: 25px;
display: flex;
align-items: center;
gap: 9px;
padding: 8px 11px;
border: 1px solid rgba(255, 255, 255, 0.16);
border-radius: 999px;
background: rgba(20, 36, 27, 0.72);
color: #d7e1cf;
font-size: 9px;
font-weight: 700;
pointer-events: none;
backdrop-filter: blur(10px);
}
.camera-hint i {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--accent);
}
@media (max-width: 980px) {
.hero {
top: 22px;
left: 22px;
}
.hero h1 {
font-size: 44px;
}
.conservation-badge {
top: 22px;
right: 22px;
}
.panel {
width: 254px;
}
.builder {
left: 22px;
top: 155px;
}
.simulation {
right: 22px;
top: 82px;
width: 246px;
}
.camera-hint {
right: 22px;
}
}
@media (max-width: 700px) {
.hero {
top: 15px;
left: 15px;
}
.hero h1 {
margin-top: 6px;
font-size: 34px;
}
.hero p {
display: none;
}
.eyebrow {
font-size: 8px;
}
.conservation-badge {
top: 15px;
right: 15px;
padding: 8px 10px;
font-size: 8px;
}
.panel {
width: auto;
}
.builder {
top: auto;
left: 12px;
right: 12px;
bottom: 54px;
max-height: 43vh;
overflow-y: auto;
}
.simulation {
display: none;
}
.node-grid {
grid-template-columns: repeat(4, 1fr);
}
.palette-node {
justify-content: center;
padding: 8px 4px;
}
.palette-node span:last-child {
display: none;
}
.route-list {
grid-template-columns: 1fr 1fr;
}
.route-row {
grid-template-columns: 1fr;
}
.route-state {
display: none;
}
.node-tag {
min-width: 95px;
padding: 5px 7px;
}
.node-tag .tag-icon {
width: 18px;
height: 18px;
}
.node-tag b {
font-size: 8px;
}
.node-tag small {
font-size: 7px;
}
.camera-hint {
display: none;
}
.toast {
bottom: calc(43vh + 68px);
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive three-dimensional forest floor nutrient cycle"></canvas>
<div id="labels" aria-live="polite"></div>
<header class="hero">
<div class="eyebrow">Field Lab 04 · Biogeochemistry</div>
<h1>Forest Floor</h1>
<p>
Connect a nutrient pathway, then follow conserved tokens as matter moves
from litter to plants and back again.
</p>
</header>
<div class="conservation-badge" aria-label="Nutrient token conservation status">
<span class="status-dot"></span>
<span id="headerConservation">24 / 24 conserved</span>
</div>
<section class="panel builder" aria-labelledby="builderTitle">
<div class="panel-head">
<div class="panel-kicker">Pathway Builder</div>
<h2 id="builderTitle">Connect the matter cycle</h2>
<p class="panel-copy">
Choose a source node, then a destination. Select an existing linked
pair again to pause that pathway.
</p>
</div>
<div class="panel-body">
<div class="node-grid">
<button class="palette-node" data-node="litter" style="--node-color: var(--litter)">
<span class="palette-icon">L</span>
<span>Litter</span>
</button>
<button class="palette-node" data-node="decomposers" style="--node-color: var(--decomposer)">
<span class="palette-icon">D</span>
<span>Decomposers</span>
</button>
<button class="palette-node" data-node="soil" style="--node-color: var(--soil)">
<span class="palette-icon">S</span>
<span>Soil resources</span>
</button>
<button class="palette-node" data-node="plants" style="--node-color: var(--plant)">
<span class="palette-icon">P</span>
<span>Plants</span>
</button>
</div>
<div class="selection-status" id="selectionStatus">
Select a node to begin a pathway.
</div>
<div class="route-heading">
<span>Valid transfers</span>
<span id="activeRouteCount">4 active</span>
</div>
<div class="route-list" id="routeList"></div>
<p class="mini-note">
Only the four transfers in the ecological cycle are valid. Toggling a
route changes where tokens travel, never how many exist.
</p>
</div>
</section>
<section class="panel simulation" aria-labelledby="simulationTitle">
<div class="panel-head">
<div class="panel-kicker">Live Simulation</div>
<h2 id="simulationTitle">Conserved nutrient tokens</h2>
<p class="panel-copy">
Each shape retains its identity while moving along active pathways.
</p>
</div>
<div class="panel-body">
<div class="conservation-card">
<div class="conservation-top">
<div class="big-number">
<span id="tokenTotal">24</span><small> / 24</small>
</div>
<div class="moving-count">
<span id="movingCount">0</span> tokens moving<br />
<span id="routeCount">4</span> routes active
</div>
</div>
<div class="token-ledger">
<div class="token-key" data-type="N"><i></i>N <span>8</span></div>
<div class="token-key" data-type="P"><i></i>P <span>8</span></div>
<div class="token-key" data-type="K"><i></i>K <span>8</span></div>
</div>
</div>
<div class="control-row">
<span class="control-label">Simulation speed</span>
<span class="control-value" id="speedValue">1.0×</span>
</div>
<input
id="speedControl"
type="range"
min="0.5"
max="2.5"
step="0.1"
value="1"
aria-label="Simulation speed"
/>
<div class="button-grid">
<button class="control-button primary" id="pauseButton">
<span class="control-icon"></span>
<span id="pauseText">Pause</span>
</button>
<button class="control-button" id="resetTokensButton">
Redistribute
</button>
<button class="control-button" id="resetRoutesButton">
All pathways
</button>
<button class="control-button" id="resetCameraButton">
Reset view
</button>
</div>
</div>
</section>
<div class="toast" id="toast" role="status"></div>
<div class="camera-hint">
<i></i>
Drag to orbit · wheel to zoom · right-drag to pan
</div>
<noscript>This interactive forest-floor model requires JavaScript.</noscript>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Core setup
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const labelsLayer = document.querySelector("#labels");
const toastElement = document.querySelector("#toast");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xaab79b);
scene.fog = new THREE.Fog(0xaab79b, 18, 34);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
60
);
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
const clock = new THREE.Clock();
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const hemi = new THREE.HemisphereLight(0xf2f5dc, 0x38422d, 2.15);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff2cb, 3.2);
sun.position.set(-6, 10, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -9;
sun.shadow.camera.right = 9;
sun.shadow.camera.top = 8;
sun.shadow.camera.bottom = -8;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 28;
sun.shadow.bias = -0.0008;
scene.add(sun);
const fill = new THREE.PointLight(0xcce9ca, 0.7, 20, 2);
fill.position.set(5, 4, -3);
scene.add(fill);
// A deterministic random generator keeps the diorama stable between loads.
let randomSeed = 8137;
function random() {
randomSeed = (randomSeed * 1664525 + 1013904223) >>> 0;
return randomSeed / 4294967296;
}
function range(min, max) {
return min + random() * (max - min);
}
function standardMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.88,
metalness: 0,
flatShading: true,
...options
});
}
// -------------------------------------------------------------------------
// Camera controls — implemented locally, without addons
// -------------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(0, 0.45, 0),
radius: 14.7,
theta: 0.62,
phi: 1.03
};
function updateCamera() {
const offset = new THREE.Vector3().setFromSphericalCoords(
cameraState.radius,
cameraState.phi,
cameraState.theta
);
camera.position.copy(cameraState.target).add(offset);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.target.set(0, 0.45, 0);
cameraState.radius = 14.7;
cameraState.theta = 0.62;
cameraState.phi = 1.03;
updateCamera();
}
let dragState = null;
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
dragState = {
pointerId: event.pointerId,
startX: event.clientX,
startY: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
startButton: event.button,
moved: false
};
canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = "grabbing";
});
canvas.addEventListener("pointermove", (event) => {
if (!dragState || dragState.pointerId !== event.pointerId) {
const hovered = pickNode(event.clientX, event.clientY);
canvas.style.cursor = hovered ? "pointer" : "grab";
return;
}
const dx = event.clientX - dragState.lastX;
const dy = event.clientY - dragState.lastY;
const totalDistance = Math.hypot(
event.clientX - dragState.startX,
event.clientY - dragState.startY
);
if (totalDistance > 4) dragState.moved = true;
if (dragState.moved) {
if (dragState.startButton === 2 || event.shiftKey) {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3()
.crossVectors(forward, new THREE.Vector3(0, 1, 0))
.normalize();
const panScale = cameraState.radius * 0.0014;
cameraState.target.addScaledVector(right, -dx * panScale);
cameraState.target.addScaledVector(forward, dy * panScale);
cameraState.target.x = THREE.MathUtils.clamp(cameraState.target.x, -3.5, 3.5);
cameraState.target.z = THREE.MathUtils.clamp(cameraState.target.z, -3.5, 3.5);
} else {
cameraState.theta -= dx * 0.0055;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.0045,
0.48,
1.34
);
}
updateCamera();
}
dragState.lastX = event.clientX;
dragState.lastY = event.clientY;
});
canvas.addEventListener("pointerup", (event) => {
if (!dragState || dragState.pointerId !== event.pointerId) return;
const wasClick =
!dragState.moved &&
dragState.startButton === 0 &&
Math.hypot(
event.clientX - dragState.startX,
event.clientY - dragState.startY
) < 6;
if (wasClick) pickNode(event.clientX, event.clientY);
dragState = null;
canvas.style.cursor = "grab";
});
canvas.addEventListener("pointercancel", () => {
dragState = null;
canvas.style.cursor = "grab";
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
9.2,
22
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetCamera);
// -------------------------------------------------------------------------
// Forest-floor board and low-poly scenery
// -------------------------------------------------------------------------
const board = new THREE.Group();
scene.add(board);
const slabMaterial = standardMaterial(0x574332);
const slab = new THREE.Mesh(
new THREE.BoxGeometry(12.9, 0.72, 8.9),
slabMaterial
);
slab.position.y = -0.38;
slab.receiveShadow = true;
slab.castShadow = true;
board.add(slab);
const woodMaterial = standardMaterial(0x735038);
const woodLight = standardMaterial(0x826047);
const railGeometryA = new THREE.BoxGeometry(13.2, 0.22, 0.28);
const railGeometryB = new THREE.BoxGeometry(0.28, 0.22, 8.8);
for (const z of [-4.35, 4.35]) {
const rail = new THREE.Mesh(railGeometryA, z < 0 ? woodMaterial : woodLight);
rail.position.set(0, 0.08, z);
rail.castShadow = true;
rail.receiveShadow = true;
board.add(rail);
}
for (const x of [-6.45, 6.45]) {
const rail = new THREE.Mesh(railGeometryB, woodLight);
rail.position.set(x, 0.08, 0);
rail.castShadow = true;
rail.receiveShadow = true;
board.add(rail);
}
// Exposed soil strata on the front edge.
const strataColors = [0x5a4636, 0x6b513c, 0x755a42];
strataColors.forEach((color, index) => {
const strata = new THREE.Mesh(
new THREE.BoxGeometry(12.5 - index * 0.18, 0.13, 0.035),
standardMaterial(color)
);
strata.position.set(0, -0.12 - index * 0.2, 4.465);
board.add(strata);
});
// Faceted ground plane with triangle-level color variation.
const groundGeometry = new THREE.PlaneGeometry(12.5, 8.25, 14, 10)
.toNonIndexed();
groundGeometry.rotateX(-Math.PI / 2);
const groundPosition = groundGeometry.attributes.position;
const groundColors = [];
const groundPalette = [
new THREE.Color(0x687347),
new THREE.Color(0x607044),
new THREE.Color(0x71804c),
new THREE.Color(0x59683f),
new THREE.Color(0x7b7950)
];
for (let i = 0; i < groundPosition.count; i += 3) {
const y = range(-0.025, 0.035);
const color = groundPalette[Math.floor(random() * groundPalette.length)];
for (let j = 0; j < 3; j++) {
groundPosition.setY(i + j, y);
groundColors.push(color.r, color.g, color.b);
}
}
groundGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(groundColors, 3)
);
groundGeometry.computeVertexNormals();
const ground = new THREE.Mesh(
groundGeometry,
standardMaterial(0xffffff, {
vertexColors: true,
side: THREE.DoubleSide
})
);
ground.position.y = 0.025;
ground.receiveShadow = true;
board.add(ground);
// Instanced low-poly leaf litter.
const leafGeometry = new THREE.CircleGeometry(0.12, 3);
leafGeometry.rotateX(-Math.PI / 2);
const leafMaterial = standardMaterial(0xffffff, {
side: THREE.DoubleSide
});
const litterCount = 88;
const litterInstances = new THREE.InstancedMesh(
leafGeometry,
leafMaterial,
litterCount
);
const dummy = new THREE.Object3D();
const litterColors = [
new THREE.Color(0xb77836),
new THREE.Color(0xc69242),
new THREE.Color(0x8f5d32),
new THREE.Color(0xd1a54d),
new THREE.Color(0x79613a)
];
for (let i = 0; i < litterCount; i++) {
dummy.position.set(range(-6.0, 6.0), range(0.075, 0.105), range(-3.95, 3.95));
dummy.rotation.set(range(-0.18, 0.18), range(0, Math.PI * 2), range(-0.12, 0.12));
dummy.scale.setScalar(range(0.65, 1.45));
dummy.updateMatrix();
litterInstances.setMatrixAt(i, dummy.matrix);
litterInstances.setColorAt(i, litterColors[Math.floor(random() * litterColors.length)]);
}
litterInstances.instanceMatrix.needsUpdate = true;
if (litterInstances.instanceColor) litterInstances.instanceColor.needsUpdate = true;
board.add(litterInstances);
// Instanced grass tufts.
const grassGeometry = new THREE.ConeGeometry(0.065, 0.38, 3);
const grassMaterial = standardMaterial(0x648c49);
const grassInstances = new THREE.InstancedMesh(
grassGeometry,
grassMaterial,
42
);
for (let i = 0; i < 42; i++) {
dummy.position.set(range(-6, 6), 0.17, range(-3.9, 3.9));
dummy.rotation.set(range(-0.15, 0.15), range(0, Math.PI * 2), range(-0.18, 0.18));
dummy.scale.set(range(0.7, 1.2), range(0.65, 1.35), range(0.7, 1.2));
dummy.updateMatrix();
grassInstances.setMatrixAt(i, dummy.matrix);
}
grassInstances.instanceMatrix.needsUpdate = true;
board.add(grassInstances);
// Instanced stones.
const stoneGeometry = new THREE.DodecahedronGeometry(0.18, 0);
const stoneMaterial = standardMaterial(0x777a69);
const stones = new THREE.InstancedMesh(stoneGeometry, stoneMaterial, 14);
for (let i = 0; i < 14; i++) {
dummy.position.set(range(-5.8, 5.8), 0.12, range(-3.7, 3.7));
dummy.rotation.set(range(0, 3), range(0, 3), range(0, 3));
dummy.scale.set(range(0.6, 1.35), range(0.45, 0.9), range(0.7, 1.3));
dummy.updateMatrix();
stones.setMatrixAt(i, dummy.matrix);
}
stones.instanceMatrix.needsUpdate = true;
stones.castShadow = true;
stones.receiveShadow = true;
board.add(stones);
function cylinderBetween(start, end, radius, material, radialSegments = 6) {
const direction = new THREE.Vector3().subVectors(end, start);
const length = direction.length();
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius, length, radialSegments),
material
);
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
// Roots along the exposed front edge.
const rootMaterial = standardMaterial(0x80613e);
for (let i = 0; i < 7; i++) {
const x = range(-5.6, 5.6);
const start = new THREE.Vector3(x, -0.08, 4.48);
const middle = new THREE.Vector3(
x + range(-0.18, 0.18),
range(-0.28, -0.42),
4.49
);
const end = new THREE.Vector3(
middle.x + range(-0.24, 0.24),
range(-0.52, -0.68),
4.49
);
board.add(cylinderBetween(start, middle, 0.025, rootMaterial, 5));
board.add(cylinderBetween(middle, end, 0.017, rootMaterial, 5));
}
function createTree(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.scale.setScalar(scale);
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.22, 0.36, 2.6, 6),
standardMaterial(0x68472f)
);
trunk.position.y = 1.3;
trunk.castShadow = true;
group.add(trunk);
const rootMaterialLocal = standardMaterial(0x5b402e);
for (let i = 0; i < 4; i++) {
const angle = (i / 4) * Math.PI * 2 + 0.4;
const start = new THREE.Vector3(0, 0.12, 0);
const end = new THREE.Vector3(
Math.cos(angle) * 0.75,
0.02,
Math.sin(angle) * 0.75
);
group.add(cylinderBetween(start, end, 0.09, rootMaterialLocal, 5));
}
const canopyColors = [0x345c39, 0x416d43, 0x52794a];
const canopyParts = [
[-0.55, 2.55, 0.05, 1.05],
[0.55, 2.7, 0.1, 1.08],
[0.05, 3.25, -0.08, 0.94],
[0.05, 2.45, 0.85, 0.85]
];
canopyParts.forEach((part, index) => {
const canopy = new THREE.Mesh(
new THREE.IcosahedronGeometry(part[3], 1),
standardMaterial(canopyColors[index % canopyColors.length])
);
canopy.position.set(part[0], part[1], part[2]);
canopy.scale.y = 0.9;
canopy.castShadow = true;
canopy.receiveShadow = true;
group.add(canopy);
});
board.add(group);
}
createTree(-5.15, -3.1, 1.02);
createTree(5.15, -3.15, 0.88);
// A cut stump near the rear center.
const stump = new THREE.Mesh(
new THREE.CylinderGeometry(0.36, 0.45, 0.52, 7),
standardMaterial(0x704d32)
);
stump.position.set(-0.2, 0.27, -3.15);
stump.castShadow = true;
board.add(stump);
const stumpTop = new THREE.Mesh(
new THREE.CylinderGeometry(0.34, 0.34, 0.035, 7),
standardMaterial(0xc29a62)
);
stumpTop.position.set(-0.2, 0.545, -3.15);
board.add(stumpTop);
// -------------------------------------------------------------------------
// Interactive habitat nodes
// -------------------------------------------------------------------------
const nodeDefinitions = [
{
id: "litter",
title: "Litter",
shortTitle: "Litter",
icon: "L",
x: -4.15,
z: -1.35,
color: 0xd9a441,
css: "#d9a441",
description: "Dead leaves and organic matter"
},
{
id: "decomposers",
title: "Decomposers",
shortTitle: "Decomposers",
icon: "D",
x: -1.55,
z: 1.25,
color: 0xe4775b,
css: "#e4775b",
description: "Fungi, microbes and detritivores"
},
{
id: "soil",
title: "Soil resources",
shortTitle: "Soil resources",
icon: "S",
x: 1.55,
z: -1.35,
color: 0xa98bd8,
css: "#a98bd8",
description: "Minerals, water and organic matter"
},
{
id: "plants",
title: "Plants",
shortTitle: "Plants",
icon: "P",
x: 4.2,
z: 1.25,
color: 0x77c878,
css: "#77c878",
description: "Roots, seedlings and canopy"
}
];
const nodes = new Map();
const nodeById = new Map();
const hitMeshes = [];
function addMushroom(parent, x, z, scale = 1, color = 0xc96650) {
const mushroom = new THREE.Group();
mushroom.position.set(x, 0.05, z);
mushroom.scale.setScalar(scale);
const stem = new THREE.Mesh(
new THREE.CylinderGeometry(0.055, 0.075, 0.34, 6),
standardMaterial(0xe8d9b7)
);
stem.position.y = 0.17;
stem.castShadow = true;
const cap = new THREE.Mesh(
new THREE.CylinderGeometry(0.24, 0.16, 0.14, 8),
standardMaterial(color)
);
cap.position.y = 0.38;
cap.castShadow = true;
mushroom.add(stem, cap);
parent.add(mushroom);
}
function addPlant(parent, x, z, scale = 1) {
const plant = new THREE.Group();
plant.position.set(x, 0.06, z);
plant.scale.setScalar(scale);
const stem = new THREE.Mesh(
new THREE.CylinderGeometry(0.025, 0.045, 0.65, 5),
standardMaterial(0x456e39)
);
stem.position.y = 0.325;
stem.castShadow = true;
const leafMaterialLocal = standardMaterial(0x69a957, {
side: THREE.DoubleSide
});
const leaf1 = new THREE.Mesh(
new THREE.CircleGeometry(0.19, 3),
leafMaterialLocal
);
leaf1.position.set(0.1, 0.45, 0);
leaf1.rotation.set(-0.5, 0.25, -0.7);
const leaf2 = new THREE.Mesh(
new THREE.CircleGeometry(0.17, 3),
leafMaterialLocal
);
leaf2.position.set(-0.1, 0.6, 0);
leaf2.rotation.set(0.4, 0.7, 0.75);
plant.add(stem, leaf1, leaf2);
parent.add(plant);
}
function createNode(definition) {
const group = new THREE.Group();
group.position.set(definition.x, 0.08, definition.z);
const base = new THREE.Mesh(
new THREE.CylinderGeometry(0.66, 0.72, 0.1, 8),
standardMaterial(0x3f4933)
);
base.position.y = 0.02;
base.receiveShadow = true;
group.add(base);
const ringMaterial = standardMaterial(definition.color, {
emissive: definition.color,
emissiveIntensity: 0.28,
roughness: 0.55
});
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.64, 0.035, 5, 24),
ringMaterial
);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.095;
group.add(ring);
if (definition.id === "litter") {
for (let i = 0; i < 11; i++) {
const leaf = new THREE.Mesh(
leafGeometry,
standardMaterial(
[0xb87937, 0xd29a43, 0x966132][i % 3],
{ side: THREE.DoubleSide }
)
);
const angle = random() * Math.PI * 2;
const radius = range(0.08, 0.46);
leaf.position.set(
Math.cos(angle) * radius,
range(0.11, 0.23),
Math.sin(angle) * radius
);
leaf.rotation.set(range(-0.35, 0.35), random() * Math.PI, range(-0.35, 0.35));
leaf.scale.setScalar(range(0.7, 1.4));
leaf.castShadow = true;
group.add(leaf);
}
}
if (definition.id === "decomposers") {
addMushroom(group, -0.28, -0.08, 0.92, 0xcc654f);
addMushroom(group, 0.18, 0.1, 1.08, 0xe57b5e);
addMushroom(group, 0.34, -0.25, 0.62, 0xb95848);
const worm = new THREE.Mesh(
new THREE.TorusGeometry(0.22, 0.045, 5, 12, Math.PI * 1.45),
standardMaterial(0xc78376)
);
worm.position.set(-0.1, 0.16, 0.28);
worm.rotation.x = Math.PI / 2;
group.add(worm);
}
if (definition.id === "soil") {
const soilColors = [0x9c80cf, 0x8266b6, 0xb298dc];
for (let i = 0; i < 4; i++) {
const crystal = new THREE.Mesh(
new THREE.OctahedronGeometry(range(0.13, 0.23), 0),
standardMaterial(soilColors[i], {
emissive: soilColors[i],
emissiveIntensity: 0.08
})
);
crystal.position.set(
range(-0.38, 0.38),
range(0.16, 0.26),
range(-0.34, 0.34)
);
crystal.scale.y = range(1.2, 1.8);
crystal.rotation.set(random(), random(), random());
crystal.castShadow = true;
group.add(crystal);
}
const rootMaterialLocal = standardMaterial(0x8c6d43);
group.add(
cylinderBetween(
new THREE.Vector3(-0.42, 0.14, 0.1),
new THREE.Vector3(0.05, 0.18, 0.02),
0.022,
rootMaterialLocal,
5
)
);
}
if (definition.id === "plants") {
addPlant(group, -0.27, -0.05, 1.0);
addPlant(group, 0.15, 0.16, 1.2);
addPlant(group, 0.31, -0.2, 0.7);
}
const hitMaterial = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
colorWrite: false
});
const hitMesh = new THREE.Mesh(
new THREE.SphereGeometry(0.78, 8, 6),
hitMaterial
);
hitMesh.position.y = 0.48;
hitMesh.userData.nodeId = definition.id;
group.add(hitMesh);
hitMeshes.push(hitMesh);
const label = document.createElement("button");
label.className = "node-tag";
label.style.setProperty("--node-color", definition.css);
label.setAttribute("aria-label", `${definition.title}: ${definition.description}`);
label.innerHTML = `
<span class="tag-icon">${definition.icon}</span>
<span>
<b>${definition.shortTitle}</b>
<small><span class="node-count">0</span> units stored</small>
</span>
`;
label.addEventListener("click", (event) => {
event.stopPropagation();
selectNode(definition.id);
});
labelsLayer.appendChild(label);
const node = {
...definition,
group,
ring,
ringMaterial,
hitMesh,
label,
countElement: label.querySelector(".node-count"),
labelAnchor: new THREE.Vector3(definition.x, 1.55, definition.z)
};
nodes.set(definition.id, node);
nodeById.set(definition.id, node);
board.add(group);
}
nodeDefinitions.forEach(createNode);
// -------------------------------------------------------------------------
// Valid pathways and active route graph
// -------------------------------------------------------------------------
const ROUTES = [
{ id: "litter-decomposers", source: "litter", target: "decomposers" },
{ id: "decomposers-soil", source: "decomposers", target: "soil" },
{ id: "soil-plants", source: "soil", target: "plants" },
{ id: "plants-litter", source: "plants", target: "litter" }
];
const VALID_TARGETS = {
litter: ["decomposers"],
decomposers: ["soil"],
soil: ["plants"],
plants: ["litter"]
};
const activeRoutes = new Set(ROUTES.map((route) => route.id));
const edgeMap = new Map();
let selectedSource = null;
function createRouteCurve(source, target) {
const start = nodes.get(source).group.position.clone();
const end = nodes.get(target).group.position.clone();
start.y += 0.53;
end.y += 0.53;
const control = start.clone().add(end).multiplyScalar(0.5);
const horizontalDistance = Math.hypot(end.x - start.x, end.z - start.z);
control.y = 1.25 + Math.min(horizontalDistance * 0.13, 0.65);
if (source === "plants" && target === "litter") {
control.y = 2.05;
control.z -= 0.35;
}
return new THREE.QuadraticBezierCurve3(start, control, end);
}
function rebuildEdges() {
const oldEdges = new Map(edgeMap);
for (const edge of oldEdges.values()) {
board.remove(edge.group);
edge.tube.geometry.dispose();
edge.tube.material.dispose();
edge.arrow.geometry.dispose();
edge.arrow.material.dispose();
}
edgeMap.clear();
for (const route of ROUTES) {
if (!activeRoutes.has(route.id)) continue;
const curve = createRouteCurve(route.source, route.target);
const group = new THREE.Group();
const tubeMaterial = standardMaterial(0xb8ce91, {
emissive: 0x6e874f,
emissiveIntensity: 0.22,
transparent: true,
opacity: 0.52,
roughness: 0.65
});
const tube = new THREE.Mesh(
new THREE.TubeGeometry(curve, 48, 0.028, 5, false),
tubeMaterial
);
group.add(tube);
const arrowMaterial = standardMaterial(0xc9dda4, {
emissive: 0x819c56,
emissiveIntensity: 0.15
});
const arrow = new THREE.Mesh(
new THREE.ConeGeometry(0.105, 0.27, 5),
arrowMaterial
);
const arrowPoint = curve.getPoint(0.64);
const arrowTangent = curve.getTangent(0.64);
arrow.position.copy(arrowPoint);
arrow.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
arrowTangent.normalize()
);
group.add(arrow);
const edge = {
...route,
curve,
group,
tube,
arrow
};
edgeMap.set(route.id, edge);
board.add(group);
}
// Preserve progress for tokens already moving along retained routes.
for (const token of tokens) {
if (!token.travel) continue;
const replacement = edgeMap.get(token.travel.edge.id);
if (replacement) {
token.travel.edge = replacement;
} else {
token.travel = null;
token.delay = 0.3;
}
}
refreshSelection();
updateRouteRows();
}
// -------------------------------------------------------------------------
// Conserved nutrient tokens
// -------------------------------------------------------------------------
const TOKEN_TYPES = [
{
id: "N",
name: "Nitrogen",
color: 0x55d6c3,
geometry: new THREE.OctahedronGeometry(0.105, 0)
},
{
id: "P",
name: "Phosphorus",
color: 0xf4bd4f,
geometry: new THREE.TetrahedronGeometry(0.13, 0)
},
{
id: "K",
name: "Potassium",
color: 0xed7fad,
geometry: new THREE.DodecahedronGeometry(0.105, 0)
}
];
const TOKEN_MATERIALS = new Map(
TOKEN_TYPES.map((type) => [
type.id,
standardMaterial(type.color, {
emissive: type.color,
emissiveIntensity: 0.55,
roughness: 0.38
})
])
);
const tokens = [];
const nodeIds = nodeDefinitions.map((node) => node.id);
const TOTAL_TOKENS = 24;
for (let i = 0; i < TOTAL_TOKENS; i++) {
const type = TOKEN_TYPES[i % TOKEN_TYPES.length];
const mesh = new THREE.Mesh(type.geometry, TOKEN_MATERIALS.get(type.id));
mesh.castShadow = true;
board.add(mesh);
tokens.push({
id: i,
type,
mesh,
current: nodeIds[Math.floor(i / 6)],
travel: null,
delay: range(0.1, 2.7),
duration: range(3.8, 6.2),
phase: random() * Math.PI * 2,
orbitRadius: range(0.32, 0.55),
lane: range(-0.085, 0.085)
});
}
function redistributeTokens() {
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
token.current = nodeIds[i % nodeIds.length];
token.travel = null;
token.delay = range(0.1, 2.6);
token.phase = random() * Math.PI * 2;
token.orbitRadius = range(0.32, 0.55);
}
updateHUD();
}
// -------------------------------------------------------------------------
// Interaction and pathway controls
// -------------------------------------------------------------------------
let toastTimeout;
function showToast(message, type = "info") {
toastElement.textContent = message;
toastElement.classList.toggle("error", type === "error");
toastElement.classList.add("show");
window.clearTimeout(toastTimeout);
toastTimeout = window.setTimeout(() => {
toastElement.classList.remove("show");
}, 2400);
}
function toggleRoute(routeId, announce = true) {
const route = ROUTES.find((item) => item.id === routeId);
if (!route) return "";
let action;
if (activeRoutes.has(routeId)) {
activeRoutes.delete(routeId);
action = "paused";
} else {
activeRoutes.add(routeId);
action = "connected";
}
rebuildEdges();
updateHUD();
if (announce) {
const sourceTitle = nodes.get(route.source).title;
const targetTitle = nodes.get(route.target).title;
showToast(
action === "paused"
? `${sourceTitle} → ${targetTitle} pathway paused.`
: `${sourceTitle} → ${targetTitle} pathway connected.`
);
}
return action;
}
function selectNode(id) {
if (!nodeById.has(id)) return;
if (!selectedSource) {
selectedSource = id;
refreshSelection();
showToast(`Source selected: ${nodes.get(id).title}. Choose a valid destination.`);
return;
}
if (selectedSource === id) {
selectedSource = null;
refreshSelection();
showToast("Source selection cleared.");
return;
}
const route = ROUTES.find(
(item) => item.source === selectedSource && item.target === id
);
if (!route) {
const sourceTitle = nodes.get(selectedSource).title;
selectedSource = null;
refreshSelection();
showToast(
`${sourceTitle} cannot transfer directly to ${nodes.get(id).title.toLowerCase()}.`,
"error"
);
return;
}
const action = toggleRoute(route.id, false);
selectedSource = null;
refreshSelection();
showToast(
action === "paused"
? `${nodes.get(route.source).title} → ${nodes.get(route.target).title} pathway paused.`
: `${nodes.get(route.source).title} → ${nodes.get(route.target).title} pathway connected.`
);
}
function refreshSelection() {
const validTargets = selectedSource ? VALID_TARGETS[selectedSource] : [];
document.querySelectorAll(".palette-node").forEach((button) => {
button.classList.toggle("selected", button.dataset.node === selectedSource);
button.classList.toggle(
"valid-target",
validTargets.includes(button.dataset.node)
);
});
for (const node of nodes.values()) {
node.label.classList.toggle("selected", node.id === selectedSource);
}
const status = document.querySelector("#selectionStatus");
if (selectedSource) {
const targetNames = validTargets
.map((id) => nodes.get(id).title.toLowerCase())
.join(" or ");
status.textContent = `Source: ${nodes.get(selectedSource).title}. Now choose ${targetNames}.`;
} else {
status.textContent = "Select a node to begin a pathway.";
}
}
const routeList = document.querySelector("#routeList");
function buildRouteRows() {
routeList.innerHTML = ROUTES.map((route) => {
const source = nodes.get(route.source);
const target = nodes.get(route.target);
return `
<button
class="route-row"
data-route="${route.id}"
aria-pressed="true"
title="Toggle ${source.title} to ${target.title}"
>
<span class="route-name">${source.title} → ${target.title}</span>
<span class="route-state">Active</span>
</button>
`;
}).join("");
routeList.querySelectorAll(".route-row").forEach((button) => {
button.addEventListener("click", () => toggleRoute(button.dataset.route));
});
}
function updateRouteRows() {
routeList.querySelectorAll(".route-row").forEach((button) => {
const active = activeRoutes.has(button.dataset.route);
button.classList.toggle("active", active);
button.setAttribute("aria-pressed", String(active));
button.querySelector(".route-state").textContent = active ? "Active" : "Paused";
});
document.querySelector("#activeRouteCount").textContent =
`${activeRoutes.size} active`;
}
buildRouteRows();
document.querySelectorAll(".palette-node").forEach((button) => {
button.addEventListener("click", () => selectNode(button.dataset.node));
});
function pickNode(clientX, clientY) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(hitMeshes, false);
if (intersections.length) {
selectNode(intersections[0].object.userData.nodeId);
return true;
}
return false;
}
// -------------------------------------------------------------------------
// Simulation controls
// -------------------------------------------------------------------------
let paused = false;
let speed = 1;
let simulationTime = 0;
const pauseButton = document.querySelector("#pauseButton");
const pauseText = document.querySelector("#pauseText");
const speedControl = document.querySelector("#speedControl");
const speedValue = document.querySelector("#speedValue");
pauseButton.addEventListener("click", () => {
paused = !paused;
pauseText.textContent = paused ? "Resume" : "Pause";
pauseButton.classList.toggle("primary", !paused);
showToast(paused ? "Simulation paused." : "Simulation resumed.");
});
speedControl.addEventListener("input", () => {
speed = Number(speedControl.value);
speedValue.textContent = `${speed.toFixed(1)}×`;
const percentage = ((speed - 0.5) / 2) * 100;
speedControl.style.background = `linear-gradient(
90deg,
var(--accent) 0%,
var(--accent) ${percentage}%,
rgba(255,255,255,.13) ${percentage}%,
rgba(255,255,255,.13) 100%
)`;
});
document.querySelector("#resetTokensButton").addEventListener("click", () => {
redistributeTokens();
showToast("Tokens redistributed. Quantity remains conserved.");
});
document.querySelector("#resetRoutesButton").addEventListener("click", () => {
ROUTES.forEach((route) => activeRoutes.add(route.id));
selectedSource = null;
rebuildEdges();
updateHUD();
showToast("All four ecological pathways are active.");
});
document.querySelector("#resetCameraButton").addEventListener("click", () => {
resetCamera();
showToast("Camera view reset.");
});
window.addEventListener("keydown", (event) => {
if (event.key === "Escape") {
selectedSource = null;
refreshSelection();
}
if (
event.code === "Space" &&
document.activeElement?.tagName !== "INPUT" &&
document.activeElement?.tagName !== "BUTTON"
) {
event.preventDefault();
pauseButton.click();
}
});
// -------------------------------------------------------------------------
// HUD
// -------------------------------------------------------------------------
function updateHUD() {
const counts = {
litter: 0,
decomposers: 0,
soil: 0,
plants: 0
};
let moving = 0;
for (const token of tokens) {
counts[token.current]++;
if (token.travel) moving++;
}
for (const node of nodes.values()) {
node.countElement.textContent = counts[node.id];
}
document.querySelector("#tokenTotal").textContent = tokens.length;
document.querySelector("#headerConservation").textContent =
`${tokens.length} / ${tokens.length} conserved`;
document.querySelector("#movingCount").textContent = moving;
document.querySelector("#routeCount").textContent = activeRoutes.size;
}
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
const upVector = new THREE.Vector3(0, 1, 0);
const sideVector = new THREE.Vector3();
const tangentVector = new THREE.Vector3();
function updateTokens(delta) {
for (const token of tokens) {
if (token.travel) {
const travel = token.travel;
travel.progress = Math.min(1, travel.progress + (delta * speed) / token.duration);
const edge = travel.edge;
const point = edge.curve.getPoint(travel.progress);
tangentVector.copy(edge.curve.getTangent(travel.progress)).normalize();
sideVector.crossVectors(tangentVector, upVector).normalize();
point.addScaledVector(sideVector, token.lane);
point.y += 0.04;
token.mesh.position.copy(point);
token.mesh.rotation.x += delta * 2.4;
token.mesh.rotation.y += delta * 3.1;
if (travel.progress >= 1) {
token.current = edge.target;
token.travel = null;
token.delay = range(0.35, 2.6);
token.phase = random() * Math.PI * 2;
}
} else {
const node = nodes.get(token.current);
const angle = token.phase + simulationTime * 0.18;
token.mesh.position.set(
node.group.position.x + Math.cos(angle) * token.orbitRadius,
node.group.position.y + 0.52 + Math.sin(simulationTime * 2 + token.phase) * 0.025,
node.group.position.z + Math.sin(angle) * token.orbitRadius
);
token.mesh.rotation.x += delta * 0.65;
token.mesh.rotation.y += delta * 0.9;
token.delay -= delta * speed;
if (token.delay <= 0) {
const outgoing = [...edgeMap.values()].filter(
(edge) => edge.source === token.current
);
if (outgoing.length) {
const edge = outgoing[Math.floor(Math.random() * outgoing.length)];
token.travel = {
edge,
progress: 0
};
} else {
token.delay = 0.7;
}
}
}
}
}
function updateNodeVisuals(elapsed) {
for (const node of nodes.values()) {
const isSource = selectedSource === node.id;
const isValidTarget =
selectedSource && VALID_TARGETS[selectedSource].includes(node.id);
const pulse = 1 + Math.sin(elapsed * 3.2 + node.x) * 0.025;
node.ring.scale.setScalar(isSource ? pulse * 1.12 : pulse);
if (isSource) {
node.ringMaterial.color.set(0xd4f58c);
node.ringMaterial.emissive.set(0xd4f58c);
node.ringMaterial.emissiveIntensity = 0.75;
} else if (isValidTarget) {
node.ringMaterial.color.set(0xd4f58c);
node.ringMaterial.emissive.set(0xd4f58c);
node.ringMaterial.emissiveIntensity = 0.45;
} else {
node.ringMaterial.color.set(node.color);
node.ringMaterial.emissive.set(node.color);
node.ringMaterial.emissiveIntensity = 0.28;
}
}
for (const edge of edgeMap.values()) {
const highlighted =
selectedSource &&
(edge.source === selectedSource || edge.target === selectedSource);
const color = highlighted ? 0xd4f58c : 0xb8ce91;
edge.tube.material.color.set(color);
edge.tube.material.emissive.set(color);
edge.tube.material.opacity = highlighted ? 0.92 : 0.48;
edge.tube.material.emissiveIntensity = highlighted ? 0.5 : 0.2;
edge.arrow.material.color.set(color);
edge.arrow.material.emissive.set(color);
edge.arrow.material.emissiveIntensity = highlighted ? 0.42 : 0.14;
}
}
function updateLabels() {
for (const node of nodes.values()) {
const projected = node.labelAnchor.clone().project(camera);
const visible = projected.z > -1 && projected.z < 1;
node.label.style.visibility = visible ? "visible" : "hidden";
if (!visible) continue;
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
node.label.style.transform =
`translate3d(${x}px, ${y}px, 0) translate(-50%, -100%)`;
}
}
let hudTimer = 0;
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
if (!paused) simulationTime += delta * speed;
updateTokens(paused ? 0 : delta);
updateNodeVisuals(elapsed);
updateLabels();
hudTimer += delta;
if (hudTimer > 0.15) {
updateHUD();
hudTimer = 0;
}
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
resetCamera();
rebuildEdges();
refreshSelection();
updateHUD();
animate();
</script>
</body>
</html>
```