Prompt specification
Build or customize the Three.js 3D scene "Weathering and erosion sorting scene" 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: Weathering and erosion sorting scene
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/weathering-and-erosion-sorting-scene-x1200
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing rock weathering. Let viewers place process tokens onto a mountain-to-river model; distinguish in-place breakdown, removal, transport, and deposition through separate highlighted zones and resettable selections. Low-poly.
Working Three.js Starter (weathering-and-erosion-sorting-scene-x1200):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rock Weathering Field Lab</title>
<style>
:root {
--ink: #193029;
--muted: #66766f;
--panel: rgba(249, 251, 247, 0.94);
--line: rgba(33, 61, 51, 0.13);
--shadow: 0 18px 55px rgba(34, 59, 49, 0.15);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 73% 28%, #f4f3df 0, transparent 34%),
radial-gradient(circle at 22% 78%, #cbdccf 0, transparent 38%),
linear-gradient(145deg, #e7eee6 0%, #d8e5dc 55%, #cddbd2 100%);
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button {
font: inherit;
}
button:focus-visible {
outline: 3px solid rgba(39, 120, 103, 0.28);
outline-offset: 3px;
}
#stage,
#scene,
#labels {
position: absolute;
inset: 0;
}
#scene {
z-index: 1;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#labels {
z-index: 8;
pointer-events: none;
overflow: hidden;
}
#stage::after {
content: "";
position: absolute;
inset: 0;
z-index: 6;
pointer-events: none;
box-shadow: inset 0 0 110px rgba(40, 70, 56, 0.08);
}
header {
position: absolute;
top: 22px;
left: 24px;
right: 24px;
z-index: 30;
display: flex;
align-items: flex-start;
justify-content: space-between;
pointer-events: none;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
padding: 9px 12px 9px 9px;
border: 1px solid rgba(255, 255, 255, 0.68);
border-radius: 18px;
background: rgba(247, 250, 245, 0.76);
box-shadow: 0 10px 30px rgba(41, 66, 56, 0.09);
backdrop-filter: blur(14px);
}
.brand-mark {
position: relative;
width: 43px;
height: 43px;
overflow: hidden;
border-radius: 13px;
background: #244c3e;
}
.brand-mark::before {
content: "";
position: absolute;
left: -4px;
bottom: -12px;
width: 37px;
height: 37px;
transform: rotate(43deg);
background: #b7d65b;
}
.brand-mark::after {
content: "";
position: absolute;
right: 5px;
bottom: 5px;
width: 22px;
height: 8px;
transform: skewX(-28deg);
border-radius: 50%;
background: #55c9bd;
}
.eyebrow,
.panel-kicker {
margin: 0 0 3px;
color: #668078;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.brand h1 {
margin: 0;
font-size: 17px;
font-weight: 760;
letter-spacing: -0.02em;
}
.hud {
display: flex;
gap: 8px;
}
.hud-item {
min-width: 82px;
padding: 10px 13px;
border: 1px solid rgba(255, 255, 255, 0.65);
border-radius: 14px;
background: rgba(247, 250, 245, 0.78);
box-shadow: 0 10px 30px rgba(41, 66, 56, 0.08);
backdrop-filter: blur(14px);
text-align: right;
}
.hud-item strong {
display: block;
font-size: 18px;
line-height: 1;
}
.hud-item small {
display: block;
margin-top: 5px;
color: #6e8179;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.14em;
}
.panel {
position: absolute;
top: 104px;
bottom: 24px;
left: 24px;
z-index: 20;
width: 342px;
padding: 21px;
overflow: auto;
border: 1px solid rgba(255, 255, 255, 0.78);
border-radius: 24px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(18px);
scrollbar-width: thin;
scrollbar-color: rgba(44, 83, 70, 0.22) transparent;
}
.panel-heading h2 {
margin: 6px 0 7px;
font-size: 25px;
line-height: 1.08;
letter-spacing: -0.045em;
}
.panel-heading p {
margin: 0 0 18px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.process-list {
display: grid;
gap: 8px;
}
.process-card {
--process: #ff8055;
position: relative;
display: grid;
grid-template-columns: 39px 1fr auto;
gap: 11px;
align-items: center;
width: 100%;
min-height: 73px;
padding: 11px 11px 11px 13px;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 15px;
background: rgba(255, 255, 255, 0.56);
color: var(--ink);
cursor: pointer;
text-align: left;
transition:
transform 160ms ease,
border-color 160ms ease,
box-shadow 160ms ease,
background 160ms ease;
}
.process-card::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 3px;
background: var(--process);
opacity: 0;
transition: opacity 160ms ease;
}
.process-card:hover {
transform: translateX(2px);
border-color: color-mix(in srgb, var(--process), transparent 52%);
background: rgba(255, 255, 255, 0.9);
}
.process-card.active {
transform: translateX(3px);
border-color: color-mix(in srgb, var(--process), transparent 38%);
background: color-mix(in srgb, var(--process), white 91%);
box-shadow: 0 8px 20px color-mix(in srgb, var(--process), transparent 86%);
}
.process-card.active::before {
opacity: 1;
}
.process-icon {
display: grid;
width: 39px;
height: 39px;
place-items: center;
border-radius: 12px;
background: color-mix(in srgb, var(--process), white 84%);
color: var(--process);
}
.process-icon svg {
width: 23px;
height: 23px;
overflow: visible;
}
.process-copy {
min-width: 0;
}
.process-step {
display: block;
margin-bottom: 2px;
color: #829089;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.14em;
}
.process-copy strong {
display: block;
font-size: 12px;
letter-spacing: -0.01em;
}
.process-copy small {
display: block;
margin-top: 3px;
overflow: hidden;
color: #75847d;
font-size: 9px;
line-height: 1.35;
text-overflow: ellipsis;
white-space: nowrap;
}
.count {
display: grid;
min-width: 25px;
height: 25px;
place-items: center;
border: 1px solid var(--line);
border-radius: 50%;
color: color-mix(in srgb, var(--process), #24352e 20%);
background: rgba(255, 255, 255, 0.78);
font-size: 10px;
font-weight: 800;
}
.selection-card {
margin-top: 14px;
padding: 14px;
border: 1px solid var(--line);
border-radius: 16px;
background: rgba(232, 240, 232, 0.58);
}
.selection-row {
display: flex;
align-items: center;
gap: 9px;
}
.selection-dot {
flex: 0 0 auto;
width: 10px;
height: 10px;
border: 2px solid rgba(255, 255, 255, 0.85);
border-radius: 50%;
background: #a1ada7;
box-shadow: 0 0 0 1px rgba(25, 48, 41, 0.08);
}
.selection-card strong {
font-size: 11px;
}
.selection-card p {
margin: 7px 0 0 19px;
color: #718078;
font-size: 10px;
line-height: 1.45;
}
.progress-wrap {
margin-top: 13px;
}
.progress-label {
display: flex;
justify-content: space-between;
margin-bottom: 6px;
color: #718078;
font-size: 9px;
font-weight: 700;
}
.progress-track {
height: 5px;
overflow: hidden;
border-radius: 10px;
background: rgba(37, 75, 62, 0.1);
}
#progressFill {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #ff8055, #9d86ff, #2fc7c2, #b7d65b);
transition: width 250ms ease;
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-top: 12px;
}
.action {
min-height: 34px;
padding: 8px 9px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.73);
color: #42584f;
cursor: pointer;
font-size: 9px;
font-weight: 750;
transition:
background 150ms ease,
transform 150ms ease;
}
.action:hover:not(:disabled) {
transform: translateY(-1px);
background: white;
}
.action:disabled {
cursor: not-allowed;
opacity: 0.38;
}
.action.danger {
color: #a24835;
}
.key {
display: inline-grid;
min-width: 16px;
height: 16px;
margin-left: 4px;
padding: 0 4px;
place-items: center;
border: 1px solid rgba(35, 60, 51, 0.14);
border-radius: 4px;
background: rgba(255, 255, 255, 0.7);
color: #788780;
font-size: 8px;
}
.panel-note {
margin: 13px 2px 0;
color: #8a9791;
font-size: 9px;
line-height: 1.45;
}
.zone-label {
--zone: #ff8055;
position: absolute;
top: 0;
left: 0;
display: flex;
align-items: center;
gap: 7px;
padding: 7px 10px;
border: 1px solid color-mix(in srgb, var(--zone), white 35%);
border-radius: 999px;
background: rgba(250, 252, 248, 0.89);
box-shadow: 0 8px 24px rgba(30, 55, 45, 0.13);
color: #30443c;
cursor: pointer;
pointer-events: auto;
white-space: nowrap;
transform: translate(-50%, -50%);
transition:
background 150ms ease,
box-shadow 150ms ease;
}
.zone-label:hover {
background: white;
box-shadow: 0 10px 28px rgba(30, 55, 45, 0.2);
}
.zone-label .zone-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--zone);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--zone), transparent 78%);
}
.zone-label span {
font-size: 8px;
font-weight: 850;
letter-spacing: 0.11em;
}
.world-note {
position: absolute;
top: 0;
left: 0;
padding: 4px 7px;
border-radius: 5px;
background: rgba(245, 249, 243, 0.6);
color: rgba(48, 71, 61, 0.66);
font-size: 7px;
font-weight: 850;
letter-spacing: 0.15em;
white-space: nowrap;
transform: translate(-50%, -50%);
}
.scene-help {
position: absolute;
right: 24px;
bottom: 24px;
z-index: 20;
display: flex;
align-items: center;
gap: 11px;
padding: 11px 14px;
border: 1px solid rgba(255, 255, 255, 0.72);
border-radius: 14px;
background: rgba(248, 251, 246, 0.83);
box-shadow: 0 10px 28px rgba(41, 66, 56, 0.09);
backdrop-filter: blur(14px);
color: #687970;
font-size: 9px;
pointer-events: none;
}
.scene-help strong {
color: #31473e;
}
.mouse-icon {
position: relative;
width: 16px;
height: 22px;
border: 1.5px solid #60756c;
border-radius: 8px;
}
.mouse-icon::before {
content: "";
position: absolute;
top: 4px;
left: 6px;
width: 2px;
height: 5px;
border-radius: 3px;
background: #60756c;
}
#toast {
position: absolute;
left: 50%;
bottom: 28px;
z-index: 50;
max-width: min(440px, calc(100vw - 40px));
padding: 11px 16px;
border: 1px solid rgba(255, 255, 255, 0.8);
border-radius: 12px;
background: rgba(28, 52, 43, 0.9);
box-shadow: 0 12px 30px rgba(24, 44, 36, 0.2);
color: white;
font-size: 10px;
font-weight: 650;
opacity: 0;
pointer-events: none;
transform: translate(-50%, 12px);
transition:
opacity 180ms ease,
transform 180ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 820px) {
header {
top: 12px;
left: 12px;
right: 12px;
}
.brand {
padding: 7px;
border-radius: 14px;
}
.brand-mark {
width: 35px;
height: 35px;
border-radius: 10px;
}
.brand h1 {
font-size: 14px;
}
.brand .eyebrow {
display: none;
}
.hud-item {
min-width: 62px;
padding: 8px 9px;
}
.hud-item strong {
font-size: 15px;
}
.panel {
top: auto;
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
max-height: 47vh;
padding: 16px;
border-radius: 19px;
}
.panel-heading h2 {
font-size: 21px;
}
.panel-heading p {
margin-bottom: 12px;
}
.process-list {
grid-template-columns: 1fr 1fr;
}
.process-card {
grid-template-columns: 32px 1fr auto;
min-height: 62px;
gap: 8px;
padding: 9px;
}
.process-icon {
width: 32px;
height: 32px;
}
.process-copy small {
display: none;
}
.scene-help {
display: none;
}
#toast {
bottom: calc(47vh + 24px);
}
}
@media (max-width: 480px) {
.hud {
display: none;
}
.process-list {
grid-template-columns: 1fr;
}
.process-copy small {
display: block;
}
}
</style>
</head>
<body>
<main id="stage">
<div id="scene" aria-label="Interactive three-dimensional mountain-to-river weathering model"></div>
<div id="labels" aria-hidden="false"></div>
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<p class="eyebrow">Earth systems / interactive field lab</p>
<h1>Rock Weathering</h1>
</div>
</div>
<div class="hud" aria-label="Scenario summary">
<div class="hud-item">
<strong id="totalTokens">0</strong>
<small>Tokens</small>
</div>
<div class="hud-item">
<strong id="coverage">0/4</strong>
<small>Processes</small>
</div>
</div>
</header>
<aside class="panel" aria-label="Weathering process controls">
<div class="panel-heading">
<p class="panel-kicker">Construct a pathway</p>
<h2>Move rock through a landscape.</h2>
<p>
Choose a process, then click its highlighted zone. You can also drag
a process card directly onto the model.
</p>
</div>
<div class="process-list" id="processList">
<button
class="process-card active"
type="button"
draggable="true"
data-process="breakdown"
style="--process: #ff8055"
aria-pressed="true"
>
<div class="process-icon" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
<path d="M3 8.5 9 3l3.2 4.1L15 4l6 5.2-3.4 8.8H7.2L3 8.5Z"/>
<path d="m12 3-.7 8.2 3.7 6.8M11.3 11.2 6 18"/>
</svg>
</div>
<div class="process-copy">
<span class="process-step">01 / IN PLACE</span>
<strong>In-place breakdown</strong>
<small>Fracturing and chemical decay without movement.</small>
</div>
<span class="count" id="count-breakdown">0</span>
</button>
<button
class="process-card"
type="button"
draggable="true"
data-process="removal"
style="--process: #9d86ff"
aria-pressed="false"
>
<div class="process-icon" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
<path d="m5 4 6 7 6-2 3 4"/>
<path d="M3 9h5l4 6 5-1 4-8"/>
<path d="m8 16 3 5"/>
</svg>
</div>
<div class="process-copy">
<span class="process-step">02 / DOWN HILLSLOPE</span>
<strong>Removal</strong>
<small>Gravity and runoff detach loosened material.</small>
</div>
<span class="count" id="count-removal">0</span>
</button>
<button
class="process-card"
type="button"
draggable="true"
data-process="transport"
style="--process: #2fc7c2"
aria-pressed="false"
>
<div class="process-icon" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
<path d="M3 7c3-3 5 3 8 0s5 3 10 0"/>
<path d="M3 12c3-3 5 3 8 0s5 3 10 0"/>
<path d="M3 17c3-3 5 3 8 0s5 3 10 0"/>
</svg>
</div>
<div class="process-copy">
<span class="process-step">03 / RIVER CORRIDOR</span>
<strong>Transport</strong>
<small>Flow moves particles through the channel.</small>
</div>
<span class="count" id="count-transport">0</span>
</button>
<button
class="process-card"
type="button"
draggable="true"
data-process="deposition"
style="--process: #b7d65b"
aria-pressed="false"
>
<div class="process-icon" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
<path d="m3 8 9-5 9 5-9 4-9-4Z"/>
<path d="m4 13 8 4 8-4M4 17l8 4 8-4"/>
</svg>
</div>
<div class="process-copy">
<span class="process-step">04 / LOWER ENERGY</span>
<strong>Deposition</strong>
<small>Sediment settles as transport energy falls.</small>
</div>
<span class="count" id="count-deposition">0</span>
</button>
</div>
<section class="selection-card" aria-live="polite">
<div class="selection-row">
<span class="selection-dot" id="selectionDot"></span>
<strong id="selectionTitle">Placing · In-place breakdown</strong>
</div>
<p id="selectionText">
Click the fractured mountain zone to place the selected token.
</p>
<div class="progress-wrap">
<div class="progress-label">
<span>Pathway coverage</span>
<span id="progressText">1 of 4 processes represented</span>
</div>
<div class="progress-track">
<div id="progressFill"></div>
</div>
</div>
</section>
<div class="actions">
<button class="action danger" id="removeSelected" type="button" disabled>
Remove token
</button>
<button class="action" id="clearSelection" type="button">
Clear selection <span class="key">Esc</span>
</button>
<button class="action" id="clearAll" type="button">
Clear all tokens
</button>
<button class="action" id="resetView" type="button">
Reset view
</button>
</div>
<p class="panel-note">
Tip: click a placed token to inspect or remove it. Number keys 1–4
select processes. A mismatched placement can be used to test a hypothesis.
</p>
</aside>
<div class="scene-help">
<span class="mouse-icon" aria-hidden="true"></span>
<span><strong>Drag</strong> to orbit · <strong>Scroll</strong> to zoom · <strong>Click</strong> to place</span>
</div>
<div id="toast" role="status" aria-live="polite"></div>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const sceneContainer = document.getElementById("scene");
const labelContainer = document.getElementById("labels");
const toastElement = document.getElementById("toast");
const PROCESSES = {
breakdown: {
name: "In-place breakdown",
short: "Breakdown",
color: "#ff8055",
hex: 0xff8055,
description: "Fracturing, frost wedging and chemical decay without moving the rock."
},
removal: {
name: "Removal",
short: "Removal",
color: "#9d86ff",
hex: 0x9d86ff,
description: "Gravity, runoff and mass wasting carry loosened material downhill."
},
transport: {
name: "Transport",
short: "Transport",
color: "#2fc7c2",
hex: 0x2fc7c2,
description: "Flowing water and debris move particles through the channel."
},
deposition: {
name: "Deposition",
short: "Deposition",
color: "#b7d65b",
hex: 0xb7d65b,
description: "Energy falls, so sediment settles in lower-energy zones."
}
};
const zones = [
{
id: "breakdown",
process: "breakdown",
name: "Fractured mountain",
center: [-4.8, -8.4],
radii: [5.2, 4.0],
anchor: [-5.2, -8.2]
},
{
id: "removal",
process: "removal",
name: "Steep weathering front",
center: [-1.8, -1.0],
radii: [5.5, 3.4],
anchor: [-2.0, -0.8]
},
{
id: "transport",
process: "transport",
name: "River corridor",
center: [0, 5.3],
radii: [4.2, 4.8],
anchor: [0, 5.5]
},
{
id: "deposition",
process: "deposition",
name: "Receiving basin",
center: [1.1, 11.4],
radii: [7.0, 2.4],
anchor: [1.1, 11.4]
}
];
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setClearColor(0x000000, 0);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
sceneContainer.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0xdde8df, 40, 78);
const camera = new THREE.PerspectiveCamera(
40,
1,
0.1,
140
);
const cameraState = {
yaw: 0.72,
pitch: 0.88,
radius: 43,
target: new THREE.Vector3(0, 2.6, 0)
};
const hemisphere = new THREE.HemisphereLight(0xf7fff4, 0x64786f, 2.25);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff3d4, 3.2);
sun.position.set(-14, 25, 14);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.camera.left = -24;
sun.shadow.camera.right = 24;
sun.shadow.camera.top = 24;
sun.shadow.camera.bottom = -24;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 65;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xb8e7e0, 0.9);
fill.position.set(16, 9, -16);
scene.add(fill);
const worldGround = new THREE.Mesh(
new THREE.PlaneGeometry(140, 140),
new THREE.MeshStandardMaterial({
color: 0xdce7dc,
roughness: 1,
metalness: 0
})
);
worldGround.rotation.x = -Math.PI / 2;
worldGround.position.y = -2.35;
worldGround.receiveShadow = true;
scene.add(worldGround);
const model = new THREE.Group();
scene.add(model);
function riverX(z) {
return 1.15 * Math.sin(z * 0.22) - 0.45;
}
function riverBed(z) {
const t = THREE.MathUtils.clamp((z + 15) / 30, 0, 1);
return THREE.MathUtils.lerp(2.8, 0.35, t);
}
function terrainHeight(x, z) {
const bed = riverBed(z);
const ridge =
9.1 *
Math.exp(
-(
Math.pow(x + 4.8, 2) / 22 +
Math.pow(z + 8.2, 2) / 27
)
);
const foothills =
4.2 *
Math.exp(
-(
Math.pow(x + 2.0, 2) / 68 +
Math.pow(z + 0.8, 2) / 39
)
);
const roughness =
0.24 * Math.sin(x * 0.82) * Math.cos(z * 0.67) +
0.11 * Math.sin(x * 1.7 + z * 0.31);
const distance = Math.abs(x - riverX(z));
const valleyBlend = Math.exp(-Math.pow(distance / 2.65, 4));
const upland = bed + ridge + foothills + roughness;
const valleyFloor = bed + roughness * 0.08;
return THREE.MathUtils.lerp(upland, valleyFloor, valleyBlend);
}
function seededRandom(seed) {
let value = seed >>> 0;
return function () {
value += 0x6d2b79f5;
let result = value;
result = Math.imul(result ^ (result >>> 15), result | 1);
result ^= result + Math.imul(result ^ (result >>> 7), result | 61);
return ((result ^ (result >>> 14)) >>> 0) / 4294967296;
};
}
const random = seededRandom(1947);
function buildTerrain() {
const columns = 34;
const rows = 40;
const minX = -13;
const maxX = 13;
const minZ = -15;
const maxZ = 15;
const positions = [];
const colors = [];
const lowColor = new THREE.Color(0x6f916f);
const midColor = new THREE.Color(0x91a085);
const rockColor = new THREE.Color(0xaeb6a9);
const snowColor = new THREE.Color(0xe7e9df);
const bankColor = new THREE.Color(0x6f9d86);
function colorAt(x, z, height) {
const color = new THREE.Color();
if (height < 4.4) {
color.copy(lowColor).lerp(midColor, height / 4.4);
} else if (height < 8.4) {
color.copy(midColor).lerp(rockColor, (height - 4.4) / 4);
} else {
color.copy(rockColor).lerp(snowColor, (height - 8.4) / 2.5);
}
const riverDistance = Math.abs(x - riverX(z));
if (riverDistance < 3.1) {
color.lerp(bankColor, 0.34 * (1 - riverDistance / 3.1));
}
color.offsetHSL(0, 0, (random() - 0.5) * 0.035);
return color;
}
function pushTriangle(a, b, c, color) {
for (const point of [a, b, c]) {
positions.push(point[0], point[1], point[2]);
colors.push(color.r, color.g, color.b);
}
}
for (let iz = 0; iz < rows; iz++) {
for (let ix = 0; ix < columns; ix++) {
const x0 = THREE.MathUtils.lerp(minX, maxX, ix / columns);
const x1 = THREE.MathUtils.lerp(minX, maxX, (ix + 1) / columns);
const z0 = THREE.MathUtils.lerp(minZ, maxZ, iz / rows);
const z1 = THREE.MathUtils.lerp(minZ, maxZ, (iz + 1) / rows);
const a = [x0, terrainHeight(x0, z0), z0];
const b = [x1, terrainHeight(x1, z0), z0];
const c = [x0, terrainHeight(x0, z1), z1];
const d = [x1, terrainHeight(x1, z1), z1];
const averageHeight = (a[1] + b[1] + c[1] + d[1]) / 4;
const averageX = (x0 + x1) / 2;
const averageZ = (z0 + z1) / 2;
const color = colorAt(averageX, averageZ, averageHeight);
pushTriangle(a, c, b, color.clone().offsetHSL(0, 0, 0.008));
pushTriangle(b, c, d, color.clone().offsetHSL(0, 0, -0.008));
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(colors, 3)
);
geometry.computeVertexNormals();
const material = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.94,
metalness: 0,
flatShading: true
});
const terrain = new THREE.Mesh(geometry, material);
terrain.receiveShadow = true;
terrain.castShadow = true;
terrain.name = "terrain";
model.add(terrain);
return terrain;
}
const terrain = buildTerrain();
function buildDioramaBase() {
const perimeter = [];
const edgeSteps = 36;
for (let i = 0; i < edgeSteps; i++) {
perimeter.push([
THREE.MathUtils.lerp(-13, 13, i / edgeSteps),
-15
]);
}
for (let i = 0; i < edgeSteps; i++) {
perimeter.push([
13,
THREE.MathUtils.lerp(-15, 15, i / edgeSteps)
]);
}
for (let i = 0; i < edgeSteps; i++) {
perimeter.push([
THREE.MathUtils.lerp(13, -13, i / edgeSteps),
15
]);
}
for (let i = 0; i < edgeSteps; i++) {
perimeter.push([
-13,
THREE.MathUtils.lerp(15, -15, i / edgeSteps)
]);
}
const positions = [];
function pushTriangle(a, b, c) {
positions.push(...a, ...b, ...c);
}
for (let i = 0; i < perimeter.length; i++) {
const current = perimeter[i];
const next = perimeter[(i + 1) % perimeter.length];
const topA = [current[0], terrainHeight(current[0], current[1]), current[1]];
const topB = [next[0], terrainHeight(next[0], next[1]), next[1]];
const bottomA = [current[0], -1.2, current[1]];
const bottomB = [next[0], -1.2, next[1]];
pushTriangle(topA, bottomA, topB);
pushTriangle(topB, bottomA, bottomB);
}
const skirtGeometry = new THREE.BufferGeometry();
skirtGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
skirtGeometry.computeVertexNormals();
const skirt = new THREE.Mesh(
skirtGeometry,
new THREE.MeshStandardMaterial({
color: 0x667a6d,
roughness: 1,
flatShading: true,
side: THREE.DoubleSide
})
);
model.add(skirt);
const base = new THREE.Mesh(
new THREE.BoxGeometry(26.25, 1.1, 30.25),
new THREE.MeshStandardMaterial({
color: 0x53685e,
roughness: 0.95
})
);
base.position.y = -1.75;
base.castShadow = true;
base.receiveShadow = true;
model.add(base);
}
buildDioramaBase();
function buildRiver() {
const segments = 64;
const positions = [];
const leftBank = [];
const rightBank = [];
function bankPoint(side, z, width) {
const x = riverX(z) + width * side;
return [x, terrainHeight(x, z) + 0.07, z];
}
for (let i = 0; i < segments; i++) {
const t0 = i / segments;
const t1 = (i + 1) / segments;
const z0 = THREE.MathUtils.lerp(-15, 15, t0);
const z1 = THREE.MathUtils.lerp(-15, 15, t1);
const width0 = 0.85 + 0.9 * t0;
const width1 = 0.85 + 0.9 * t1;
const left0 = [riverX(z0) - width0, riverBed(z0) + 0.13, z0];
const right0 = [riverX(z0) + width0, riverBed(z0) + 0.13, z0];
const left1 = [riverX(z1) - width1, riverBed(z1) + 0.13, z1];
const right1 = [riverX(z1) + width1, riverBed(z1) + 0.13, z1];
positions.push(...left0, ...left1, ...right0);
positions.push(...right0, ...left1, ...right1);
leftBank.push(bankPoint(-1, z0, width0));
rightBank.push(bankPoint(1, z0, width0));
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.computeVertexNormals();
const water = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
color: 0x3ba7a5,
emissive: 0x123f42,
emissiveIntensity: 0.18,
roughness: 0.28,
metalness: 0.08,
transparent: true,
opacity: 0.9,
flatShading: true,
side: THREE.DoubleSide
})
);
water.receiveShadow = true;
model.add(water);
const bankMaterial = new THREE.LineBasicMaterial({
color: 0x91c7b1,
transparent: true,
opacity: 0.7
});
model.add(
new THREE.Line(
new THREE.BufferGeometry().setFromPoints(
leftBank.map((point) => new THREE.Vector3(...point))
),
bankMaterial
)
);
model.add(
new THREE.Line(
new THREE.BufferGeometry().setFromPoints(
rightBank.map((point) => new THREE.Vector3(...point))
),
bankMaterial
)
);
}
buildRiver();
function buildVegetationAndRocks() {
const trunkGeometry = new THREE.CylinderGeometry(0.11, 0.17, 1.3, 5);
const crownGeometry = new THREE.ConeGeometry(0.7, 1.9, 6);
const trunkMaterial = new THREE.MeshStandardMaterial({
color: 0x675445,
roughness: 1,
flatShading: true
});
const crownMaterial = new THREE.MeshStandardMaterial({
color: 0x355f4c,
roughness: 1,
flatShading: true
});
let treeCount = 0;
let attempts = 0;
while (treeCount < 30 && attempts < 250) {
attempts++;
const x = THREE.MathUtils.lerp(-12, 12, random());
const z = THREE.MathUtils.lerp(-14, 13, random());
const height = terrainHeight(x, z);
if (
Math.abs(x - riverX(z)) < 3.0 ||
height < 1.6 ||
height > 8.3 ||
random() < 0.35
) {
continue;
}
const scale = 0.55 + random() * 0.6;
const tree = new THREE.Group();
const trunk = new THREE.Mesh(trunkGeometry, trunkMaterial);
trunk.position.y = 0.65;
trunk.scale.setScalar(scale);
trunk.castShadow = true;
const crown = new THREE.Mesh(crownGeometry, crownMaterial);
crown.position.y = 1.55;
crown.scale.setScalar(scale);
crown.castShadow = true;
tree.add(trunk, crown);
tree.position.set(x, height, z);
tree.rotation.y = random() * Math.PI * 2;
model.add(tree);
treeCount++;
}
const rockGeometry = new THREE.DodecahedronGeometry(0.45, 0);
const rockMaterial = new THREE.MeshStandardMaterial({
color: 0x879184,
roughness: 1,
flatShading: true
});
for (let i = 0; i < 30; i++) {
const x = THREE.MathUtils.lerp(-12.2, 12.2, random());
const z = THREE.MathUtils.lerp(-14.3, 14.3, random());
const height = terrainHeight(x, z);
if (Math.abs(x - riverX(z)) < 1.4 && random() < 0.65) {
continue;
}
const rock = new THREE.Mesh(rockGeometry, rockMaterial);
const scale = 0.3 + random() * 0.8;
rock.position.set(x, height + scale * 0.22, z);
rock.scale.set(
scale * (0.8 + random() * 0.7),
scale * (0.55 + random() * 0.6),
scale * (0.8 + random() * 0.7)
);
rock.rotation.set(random(), random() * Math.PI, random());
rock.castShadow = true;
rock.receiveShadow = true;
model.add(rock);
}
}
buildVegetationAndRocks();
const zoneMeshes = [];
const zoneLabels = [];
function buildZone(zone) {
const process = PROCESSES[zone.process];
const segments = 32;
const rings = 3;
const positions = [];
function point(radiusRatio, angle) {
const x = zone.center[0] + Math.cos(angle) * zone.radii[0] * radiusRatio;
const z = zone.center[1] + Math.sin(angle) * zone.radii[1] * radiusRatio;
return [x, terrainHeight(x, z) + 0.25, z];
}
const center = point(0, 0);
const firstRing = [];
for (let s = 0; s < segments; s++) {
firstRing.push(point(1 / rings, (s / segments) * Math.PI * 2));
}
for (let s = 0; s < segments; s++) {
positions.push(...center, ...firstRing[(s + 1) % segments], ...firstRing[s]);
}
for (let ring = 1; ring < rings; ring++) {
for (let s = 0; s < segments; s++) {
const next = (s + 1) % segments;
const innerA = point(ring / rings, (s / segments) * Math.PI * 2);
const innerB = point(ring / rings, (next / segments) * Math.PI * 2);
const outerA = point((ring + 1) / rings, (s / segments) * Math.PI * 2);
const outerB = point((ring + 1) / rings, (next / segments) * Math.PI * 2);
positions.push(...innerA, ...outerA, ...innerB);
positions.push(...innerB, ...outerA, ...outerB);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.computeVertexNormals();
const material = new THREE.MeshBasicMaterial({
color: process.hex,
transparent: true,
opacity: 0.15,
depthWrite: false,
side: THREE.DoubleSide,
polygonOffset: true,
polygonOffsetFactor: -1,
polygonOffsetUnits: -1
});
const mesh = new THREE.Mesh(geometry, material);
mesh.userData.zoneId = zone.id;
mesh.renderOrder = 2;
model.add(mesh);
zoneMeshes.push(mesh);
const ringPoints = [];
for (let s = 0; s < 64; s++) {
const angle = (s / 64) * Math.PI * 2;
const x = zone.center[0] + Math.cos(angle) * zone.radii[0];
const z = zone.center[1] + Math.sin(angle) * zone.radii[1];
ringPoints.push(new THREE.Vector3(x, terrainHeight(x, z) + 0.31, z));
}
const outline = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints(ringPoints),
new THREE.LineBasicMaterial({
color: process.hex,
transparent: true,
opacity: 0.88
})
);
outline.renderOrder = 3;
model.add(outline);
const label = document.createElement("button");
label.type = "button";
label.className = "zone-label";
label.style.setProperty("--zone", process.color);
label.innerHTML = `
<span class="zone-dot"></span>
<span>${zone.name.toUpperCase()}</span>
`;
label.setAttribute(
"aria-label",
`Place the selected process token in ${zone.name}`
);
label.addEventListener("click", (event) => {
event.stopPropagation();
if (!selectedProcess) {
showToast("Choose a process before placing a token.");
return;
}
placeToken(
selectedProcess,
zone.id,
zone.anchor[0],
zone.anchor[1]
);
});
labelContainer.appendChild(label);
zoneLabels.push({
element: label,
position: new THREE.Vector3(
zone.center[0],
terrainHeight(zone.center[0], zone.center[1]) + 1.1,
zone.center[1]
)
});
}
zones.forEach(buildZone);
const worldNotes = [];
function addWorldNote(text, x, z, offset = 0.8) {
const element = document.createElement("div");
element.className = "world-note";
element.textContent = text;
labelContainer.appendChild(element);
worldNotes.push({
element,
position: new THREE.Vector3(x, terrainHeight(x, z) + offset, z)
});
}
addWorldNote("UPSTREAM · HIGH GROUND", -7.8, -12.8, 0.7);
addWorldNote("FLOW DIRECTION →", riverX(8) + 0.3, 8.1, 0.35);
addWorldNote("LOWLAND BASIN", 4.2, 13.4, 0.5);
const chevrons = [];
const chevronGeometry = new THREE.BufferGeometry();
chevronGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(
[
0, 0, 0.36,
-0.3, 0, -0.22,
0.3, 0, -0.22
],
3
)
);
chevronGeometry.computeVertexNormals();
const chevronMaterial = new THREE.MeshBasicMaterial({
color: 0xc6fff0,
transparent: true,
opacity: 0.72,
side: THREE.DoubleSide
});
for (let i = 0; i < 4; i++) {
const chevron = new THREE.Mesh(chevronGeometry, chevronMaterial);
chevron.userData.baseZ = -2 + i * 3.7;
chevron.position.set(riverX(chevron.userData.baseZ), 0, chevron.userData.baseZ);
model.add(chevron);
chevrons.push(chevron);
}
const tokenGroups = [];
const tokenCounts = {
breakdown: 0,
removal: 0,
transport: 0,
deposition: 0
};
const stemGeometry = new THREE.CylinderGeometry(0.07, 0.11, 0.42, 5);
const gemGeometry = new THREE.OctahedronGeometry(0.34, 0);
const ringGeometry = new THREE.TorusGeometry(0.43, 0.045, 4, 10);
const baseGeometry = new THREE.CylinderGeometry(0.46, 0.46, 0.065, 8);
let nextTokenId = 1;
let selectedProcess = "breakdown";
let selectedToken = null;
function placeToken(processId, zoneId, x, z) {
const process = PROCESSES[processId];
const zone = zones.find((entry) => entry.id === zoneId);
if (!process || !zone) {
return;
}
const group = new THREE.Group();
const id = nextTokenId++;
const stemMaterial = new THREE.MeshStandardMaterial({
color: new THREE.Color(process.hex).multiplyScalar(0.58),
roughness: 0.74,
metalness: 0.05,
flatShading: true
});
const gemMaterial = new THREE.MeshStandardMaterial({
color: process.hex,
emissive: process.hex,
emissiveIntensity: 0.1,
roughness: 0.34,
metalness: 0.12,
flatShading: true
});
const ringMaterial = new THREE.MeshStandardMaterial({
color: process.hex,
emissive: process.hex,
emissiveIntensity: 0.08,
roughness: 0.5,
flatShading: true
});
const baseMaterial = new THREE.MeshStandardMaterial({
color: 0xf4f7ef,
roughness: 0.75,
flatShading: true
});
const stem = new THREE.Mesh(stemGeometry, stemMaterial);
stem.position.y = 0.21;
const gem = new THREE.Mesh(gemGeometry, gemMaterial);
gem.position.y = 0.68;
const ring = new THREE.Mesh(ringGeometry, ringMaterial);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.06;
const base = new THREE.Mesh(baseGeometry, baseMaterial);
base.position.y = 0.035;
group.add(base, ring, stem, gem);
group.position.set(x, terrainHeight(x, z) + 0.29, z);
group.userData.id = id;
group.userData.process = processId;
group.userData.zone = zoneId;
group.userData.gem = gem;
group.userData.ring = ring;
group.userData.phase = random() * Math.PI * 2;
group.traverse((child) => {
if (child.isMesh) {
child.userData.tokenId = id;
child.castShadow = true;
child.receiveShadow = true;
}
});
model.add(group);
tokenGroups.push(group);
tokenCounts[processId]++;
selectedToken = null;
updateTokenAppearance();
updateUI();
showToast(`${process.name} placed in ${zone.name}.`);
}
function updateTokenAppearance() {
for (const group of tokenGroups) {
const active = group === selectedToken;
const process = PROCESSES[group.userData.process];
group.scale.setScalar(active ? 1.17 : 1);
group.traverse((child) => {
if (!child.isMesh || !child.material.emissive) {
return;
}
child.material.emissive.set(process.hex);
child.material.emissiveIntensity = active ? 0.58 : 0.08;
});
if (group.userData.ring) {
group.userData.ring.material.color.set(
active ? 0xffffff : process.hex
);
}
}
}
function removeSelectedToken() {
if (!selectedToken) {
showToast("Select a placed token first.");
return;
}
const process = selectedToken.userData.process;
const index = tokenGroups.indexOf(selectedToken);
if (index >= 0) {
tokenGroups.splice(index, 1);
}
model.remove(selectedToken);
tokenCounts[process] = Math.max(0, tokenCounts[process] - 1);
selectedToken = null;
updateTokenAppearance();
updateUI();
showToast("Token removed.");
}
function clearAllTokens() {
for (const group of tokenGroups) {
model.remove(group);
}
tokenGroups.length = 0;
for (const key of Object.keys(tokenCounts)) {
tokenCounts[key] = 0;
}
selectedToken = null;
updateTokenAppearance();
updateUI();
showToast("All tokens cleared.");
}
function setSelectedProcess(processId, allowToggle = true) {
if (!PROCESSES[processId]) {
return;
}
if (allowToggle && selectedProcess === processId) {
selectedProcess = null;
} else {
selectedProcess = processId;
}
selectedToken = null;
updateTokenAppearance();
updateUI();
}
function clearSelection() {
selectedProcess = null;
selectedToken = null;
updateTokenAppearance();
updateUI();
}
function updateUI() {
document.querySelectorAll(".process-card").forEach((card) => {
const active = card.dataset.process === selectedProcess;
card.classList.toggle("active", active);
card.setAttribute("aria-pressed", String(active));
});
for (const key of Object.keys(tokenCounts)) {
const element = document.getElementById(`count-${key}`);
if (element) {
element.textContent = tokenCounts[key];
}
}
const total = tokenGroups.length;
const represented = Object.values(tokenCounts).filter((count) => count > 0).length;
document.getElementById("totalTokens").textContent = total;
document.getElementById("coverage").textContent = `${represented}/4`;
document.getElementById("progressFill").style.width = `${represented * 25}%`;
document.getElementById("progressText").textContent =
`${represented} of 4 processes represented`;
const selectionDot = document.getElementById("selectionDot");
const selectionTitle = document.getElementById("selectionTitle");
const selectionText = document.getElementById("selectionText");
const removeButton = document.getElementById("removeSelected");
removeButton.disabled = !selectedToken;
if (selectedToken) {
const process = PROCESSES[selectedToken.userData.process];
const zone = zones.find(
(entry) => entry.id === selectedToken.userData.zone
);
selectionDot.style.background = process.color;
selectionTitle.textContent = `Selected · ${process.name}`;
selectionText.textContent = `Placed in ${zone.name}. Use “Remove token” to undo it.`;
} else if (selectedProcess) {
const process = PROCESSES[selectedProcess];
const zone = zones.find((entry) => entry.process === selectedProcess);
selectionDot.style.background = process.color;
selectionTitle.textContent = `Placing · ${process.name}`;
selectionText.textContent =
`Click the ${zone.name.toLowerCase()} zone, or drag this card onto the model.`;
} else {
selectionDot.style.background = "#a1ada7";
selectionTitle.textContent = "Ready for a new hypothesis";
selectionText.textContent =
"Choose a process card to begin, or select a placed token to inspect it.";
}
}
let toastTimer;
function showToast(message) {
toastElement.textContent = message;
toastElement.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toastElement.classList.remove("show");
}, 2400);
}
document.querySelectorAll(".process-card").forEach((card) => {
const processId = card.dataset.process;
card.addEventListener("click", () => {
setSelectedProcess(processId);
});
card.addEventListener("dragstart", (event) => {
event.dataTransfer.setData("text/plain", processId);
event.dataTransfer.effectAllowed = "copy";
setSelectedProcess(processId, false);
});
});
document.getElementById("removeSelected").addEventListener("click", removeSelectedToken);
document.getElementById("clearSelection").addEventListener("click", clearSelection);
document.getElementById("clearAll").addEventListener("click", clearAllTokens);
document.getElementById("resetView").addEventListener("click", resetCamera);
window.addEventListener("keydown", (event) => {
if (event.key === "Escape") {
clearSelection();
} else if (event.key === "Delete" || event.key === "Backspace") {
if (selectedToken) {
event.preventDefault();
removeSelectedToken();
}
} else if (["1", "2", "3", "4"].includes(event.key)) {
const ids = ["breakdown", "removal", "transport", "deposition"];
setSelectedProcess(ids[Number(event.key) - 1], false);
}
});
function findZoneAt(x, z) {
let bestZone = null;
let bestScore = Infinity;
for (const zone of zones) {
const dx = (x - zone.center[0]) / zone.radii[0];
const dz = (z - zone.center[1]) / zone.radii[1];
const score = dx * dx + dz * dz;
if (score <= 1.08 && score < bestScore) {
bestZone = zone;
bestScore = score;
}
}
return bestZone;
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const canvas = renderer.domElement;
function setRayFromClient(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);
}
function pickToken(clientX, clientY) {
setRayFromClient(clientX, clientY);
const hits = raycaster.intersectObjects(tokenGroups, true);
if (!hits.length) {
return null;
}
let object = hits[0].object;
while (object && object.userData.tokenId === undefined) {
object = object.parent;
}
return tokenGroups.find((group) => group.userData.id === object?.userData.tokenId) || null;
}
function pickZone(clientX, clientY) {
setRayFromClient(clientX, clientY);
const zoneHits = raycaster.intersectObjects(zoneMeshes, false);
if (zoneHits.length) {
const hit = zoneHits[0];
const zone = zones.find((entry) => entry.id === hit.object.userData.zoneId);
return { zone, point: hit.point };
}
const terrainHits = raycaster.intersectObject(terrain, false);
if (terrainHits.length) {
const point = terrainHits[0].point;
return {
zone: findZoneAt(point.x, point.z),
point
};
}
return { zone: null, point: null };
}
function handleCanvasClick(event) {
const token = pickToken(event.clientX, event.clientY);
if (token) {
selectedToken = token;
selectedProcess = null;
updateTokenAppearance();
updateUI();
return;
}
const picked = pickZone(event.clientX, event.clientY);
if (!picked.zone) {
if (selectedToken) {
selectedToken = null;
updateTokenAppearance();
updateUI();
}
return;
}
if (!selectedProcess) {
showToast("Choose a process card before placing a token.");
return;
}
placeToken(
selectedProcess,
picked.zone.id,
picked.point.x,
picked.point.z
);
}
let pointerState = null;
let dragging = false;
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) {
return;
}
pointerState = {
startX: event.clientX,
startY: event.clientY,
lastX: event.clientX,
lastY: event.clientY
};
dragging = false;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (pointerState) {
const totalDistance = Math.hypot(
event.clientX - pointerState.startX,
event.clientY - pointerState.startY
);
if (totalDistance > 4) {
dragging = true;
}
if (dragging) {
const deltaX = event.clientX - pointerState.lastX;
const deltaY = event.clientY - pointerState.lastY;
cameraState.yaw -= deltaX * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + deltaY * 0.0045,
0.48,
1.32
);
canvas.style.cursor = "grabbing";
}
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
} else {
const token = pickToken(event.clientX, event.clientY);
canvas.style.cursor = token
? "pointer"
: selectedProcess
? "crosshair"
: "grab";
}
});
canvas.addEventListener("pointerup", (event) => {
if (pointerState && !dragging) {
handleCanvasClick(event);
}
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
pointerState = null;
dragging = false;
canvas.style.cursor = selectedProcess ? "crosshair" : "grab";
});
canvas.addEventListener("pointercancel", () => {
pointerState = null;
dragging = false;
canvas.style.cursor = selectedProcess ? "crosshair" : "grab";
});
canvas.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
canvas.addEventListener("wheel", (event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.025,
25,
59
);
}, { passive: false });
canvas.addEventListener("dragover", (event) => {
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
});
canvas.addEventListener("drop", (event) => {
event.preventDefault();
const processId = event.dataTransfer.getData("text/plain");
if (!PROCESSES[processId]) {
return;
}
const picked = pickZone(event.clientX, event.clientY);
if (!picked.zone) {
showToast("Drop the token inside one of the colored landscape zones.");
return;
}
selectedProcess = processId;
selectedToken = null;
updateTokenAppearance();
placeToken(
processId,
picked.zone.id,
picked.point.x,
picked.point.z
);
});
function updateCamera() {
const aspectScale =
camera.aspect < 0.8 ? 1.35 :
camera.aspect < 1.15 ? 1.16 :
1;
const radius = cameraState.radius * aspectScale;
const horizontalRadius = radius * Math.sin(cameraState.pitch);
camera.position.set(
cameraState.target.x + horizontalRadius * Math.sin(cameraState.yaw),
cameraState.target.y + radius * Math.cos(cameraState.pitch),
cameraState.target.z + horizontalRadius * Math.cos(cameraState.yaw)
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.yaw = 0.72;
cameraState.pitch = 0.88;
cameraState.radius = 43;
cameraState.target.set(0, 2.6, 0);
showToast("Camera reset.");
}
function resize() {
const width = sceneContainer.clientWidth;
const height = sceneContainer.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
updateCamera();
}
if ("ResizeObserver" in window) {
new ResizeObserver(resize).observe(sceneContainer);
} else {
window.addEventListener("resize", resize);
}
function projectElement(element, worldPosition) {
const projected = worldPosition.clone().project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.2 &&
Math.abs(projected.y) < 1.2;
element.style.opacity = visible ? "1" : "0";
element.style.pointerEvents = visible ? "" : "none";
if (!visible) {
return;
}
const x = (projected.x * 0.5 + 0.5) * sceneContainer.clientWidth;
const y = (-projected.y * 0.5 + 0.5) * sceneContainer.clientHeight;
element.style.transform =
`translate3d(${x}px, ${y}px, 0) translate(-50%, -50%)`;
}
const clock = new THREE.Clock();
const reducedMotion = window.matchMedia(
"(prefers-reduced-motion: reduce)"
).matches;
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
updateCamera();
for (const group of tokenGroups) {
if (!reducedMotion) {
group.userData.gem.position.y =
0.68 + Math.sin(elapsed * 2.2 + group.userData.phase) * 0.035;
group.userData.ring.rotation.z = elapsed * 0.35;
}
}
for (let i = 0; i < chevrons.length; i++) {
const chevron = chevrons[i];
const travel = reducedMotion
? chevron.userData.baseZ
: -2 + ((chevron.userData.baseZ + 2 + elapsed * 0.36) % 13);
chevron.position.z = travel;
chevron.position.x = riverX(travel);
chevron.position.y = riverBed(travel) + 0.18;
chevron.rotation.y = 0;
}
for (const label of zoneLabels) {
projectElement(label.element, label.position);
}
for (const note of worldNotes) {
projectElement(note.element, note.position);
}
renderer.render(scene, camera);
}
updateUI();
resize();
animate();
</script>
</body>
</html>
```