Prompt specification
Build or customize the Three.js 3D scene "Compare routes when an oasis stop is unavailable" 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: Compare routes when an oasis stop is unavailable
Category: Art & Culture · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/compare-routes-when-an-oasis-stop-is-unavailable-x2636
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows trans-Saharan salt and gold trade routes. Let users close one fictional route node in the schematic network. Show the resulting detour and required water capacity using explicit teaching assumptions. Low-poly.
Working Three.js Starter (compare-routes-when-an-oasis-stop-is-unavailable-x2636):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Trans-Saharan Salt & Gold — Route Closure Lab</title>
<style>
:root {
--ink: #263238;
--muted: #69777a;
--paper: rgba(255, 248, 231, 0.94);
--line: rgba(55, 72, 70, 0.16);
--gold: #d99a21;
--gold-dark: #9b6813;
--teal: #247d82;
--teal-dark: #15575b;
--coral: #db654b;
--closed: #be3f3f;
--shadow: 0 18px 50px rgba(68, 48, 25, 0.20);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #ead8b4;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
#label-layer {
position: fixed;
inset: 0;
pointer-events: none;
overflow: hidden;
z-index: 2;
}
.brand {
position: fixed;
z-index: 10;
top: 22px;
left: 24px;
max-width: 430px;
pointer-events: none;
text-shadow: 0 2px 12px rgba(255, 245, 220, 0.65);
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 6px 10px;
border: 1px solid rgba(45, 59, 55, 0.18);
border-radius: 999px;
background: rgba(255, 249, 232, 0.76);
backdrop-filter: blur(8px);
color: #52625f;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--coral);
box-shadow: 0 0 0 3px rgba(219, 101, 75, 0.16);
}
h1 {
margin: 10px 0 3px;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(28px, 3.4vw, 49px);
font-weight: 700;
line-height: 0.98;
letter-spacing: -0.045em;
}
.brand p {
margin: 8px 0 0;
color: #566460;
font-size: 13px;
font-weight: 600;
}
.panel {
position: fixed;
z-index: 20;
top: 18px;
right: 18px;
width: min(390px, calc(100vw - 36px));
max-height: calc(100vh - 36px);
overflow: auto;
padding: 18px;
border: 1px solid rgba(255, 255, 255, 0.52);
border-radius: 22px;
background: var(--paper);
box-shadow: var(--shadow);
backdrop-filter: blur(16px) saturate(1.15);
scrollbar-width: thin;
scrollbar-color: rgba(73, 84, 77, 0.24) transparent;
}
.panel-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 14px;
}
.panel h2 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: 21px;
letter-spacing: -0.025em;
}
.panel h3 {
margin: 0 0 9px;
font-size: 11px;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
color: #68736f;
}
.step {
display: inline-grid;
place-items: center;
width: 27px;
height: 27px;
margin-right: 7px;
border-radius: 8px;
background: #2e514d;
color: white;
font-family: ui-sans-serif, system-ui, sans-serif;
font-size: 12px;
vertical-align: 2px;
}
.route-switch {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
margin: 12px 0 14px;
padding: 4px;
border-radius: 12px;
background: rgba(64, 79, 73, 0.08);
}
.route-switch button {
border: 0;
border-radius: 9px;
padding: 9px 7px;
background: transparent;
color: #64716d;
cursor: pointer;
font: inherit;
font-size: 12px;
font-weight: 800;
}
.route-switch button[data-route="gold"].active {
background: #f5d98f;
color: #7e570f;
box-shadow: 0 3px 10px rgba(121, 84, 18, 0.13);
}
.route-switch button[data-route="salt"].active {
background: #b9dfe0;
color: #145d61;
box-shadow: 0 3px 10px rgba(21, 92, 97, 0.12);
}
label {
display: block;
margin-bottom: 6px;
color: #596863;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
}
select {
width: 100%;
height: 42px;
padding: 0 38px 0 12px;
border: 1px solid rgba(50, 72, 66, 0.17);
border-radius: 11px;
outline: none;
background: rgba(255, 255, 255, 0.66);
color: var(--ink);
font: inherit;
font-size: 13px;
font-weight: 700;
}
select:focus {
border-color: var(--teal);
box-shadow: 0 0 0 3px rgba(36, 125, 130, 0.12);
}
.button-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
margin-top: 9px;
}
button {
font: inherit;
}
.primary,
.secondary {
min-height: 42px;
border-radius: 11px;
cursor: pointer;
font-size: 12px;
font-weight: 850;
transition: transform 120ms ease, box-shadow 120ms ease, background 120ms ease;
}
.primary {
border: 1px solid #284c48;
background: #315c56;
color: #fffdf7;
box-shadow: 0 7px 16px rgba(35, 73, 68, 0.17);
}
.primary:hover {
transform: translateY(-1px);
background: #264f49;
box-shadow: 0 9px 20px rgba(35, 73, 68, 0.22);
}
.secondary {
border: 1px solid rgba(55, 72, 67, 0.15);
padding: 0 13px;
background: rgba(255, 255, 255, 0.55);
color: #56645f;
}
.secondary:hover {
background: rgba(255, 255, 255, 0.9);
}
.status {
margin: 10px 0 15px;
padding: 10px 11px;
border-left: 3px solid var(--coral);
border-radius: 0 9px 9px 0;
background: rgba(219, 101, 75, 0.08);
color: #6d5148;
font-size: 12px;
line-height: 1.45;
}
.status.open {
border-left-color: var(--teal);
background: rgba(36, 125, 130, 0.08);
color: #41615e;
}
.metric-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin: 9px 0 13px;
}
.metric {
min-width: 0;
padding: 10px 9px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.44);
}
.metric .value {
display: block;
overflow: hidden;
color: #263b38;
font-family: Georgia, "Times New Roman", serif;
font-size: 20px;
font-weight: 700;
line-height: 1;
text-overflow: ellipsis;
white-space: nowrap;
}
.metric .value.gold {
color: var(--gold-dark);
}
.metric .value.teal {
color: var(--teal-dark);
}
.metric .caption {
display: block;
margin-top: 6px;
color: #74807c;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.07em;
line-height: 1.25;
text-transform: uppercase;
}
.route-summary {
margin-bottom: 14px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255, 255, 255, 0.38);
}
.route-summary .corridor {
margin-bottom: 8px;
color: #2e4440;
font-size: 12px;
font-weight: 850;
}
.path-line {
display: flex;
align-items: flex-start;
gap: 8px;
margin-top: 9px;
}
.path-key {
flex: 0 0 52px;
padding-top: 4px;
color: #7b8581;
font-size: 9px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.path-chips {
display: flex;
flex: 1;
flex-wrap: wrap;
align-items: center;
gap: 4px;
line-height: 1.25;
}
.chip {
padding: 4px 7px;
border: 1px solid rgba(53, 74, 69, 0.11);
border-radius: 7px;
background: rgba(255, 255, 255, 0.67);
color: #435651;
font-size: 10px;
font-weight: 750;
}
.arrow {
color: #9aa39f;
font-size: 10px;
}
.water-card {
margin-top: 8px;
padding: 13px;
border-radius: 13px;
background: #2f5b57;
color: white;
}
.water-top {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 10px;
}
.water-title {
color: #c7dfdb;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.water-number {
margin-top: 3px;
font-family: Georgia, "Times New Roman", serif;
font-size: 27px;
line-height: 1;
}
.water-number small {
font-family: ui-sans-serif, system-ui, sans-serif;
font-size: 11px;
font-weight: 700;
}
.water-delta {
padding: 5px 8px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.11);
color: #d8ebe8;
font-size: 10px;
font-weight: 800;
}
.water-bar {
height: 7px;
margin: 12px 0 9px;
overflow: hidden;
border-radius: 99px;
background: rgba(255, 255, 255, 0.14);
}
.water-bar > div {
height: 100%;
width: 50%;
border-radius: inherit;
background: linear-gradient(90deg, #9ed9d7, #f1d17e);
transition: width 350ms ease;
}
.water-card p {
margin: 0;
color: #c8d9d6;
font-size: 10px;
line-height: 1.45;
}
.lesson-note {
margin: 10px 0 0;
padding: 10px 11px;
border: 1px solid rgba(120, 90, 30, 0.13);
border-radius: 10px;
background: rgba(238, 204, 126, 0.17);
color: #655636;
font-size: 11px;
line-height: 1.45;
}
details {
margin-top: 14px;
border-top: 1px solid var(--line);
padding-top: 12px;
}
summary {
cursor: pointer;
color: #445853;
font-size: 11px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.assumptions {
margin: 10px 0 0;
padding-left: 18px;
color: #64716d;
font-size: 11px;
line-height: 1.52;
}
.assumptions li {
margin-bottom: 6px;
}
.formula {
margin-top: 9px;
padding: 9px;
border-radius: 9px;
background: rgba(45, 71, 66, 0.07);
color: #455c57;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.45;
}
.node-label,
.edge-label {
position: absolute;
left: 0;
top: 0;
white-space: nowrap;
will-change: transform;
}
.node-label {
display: flex;
align-items: center;
gap: 6px;
padding: 5px 8px 5px 6px;
border: 1px solid rgba(61, 76, 70, 0.14);
border-radius: 8px;
background: rgba(255, 250, 237, 0.89);
box-shadow: 0 4px 14px rgba(69, 50, 29, 0.13);
color: #344743;
font-size: 10px;
font-weight: 800;
}
.node-label .node-dot {
width: 8px;
height: 8px;
border-radius: 3px;
background: var(--teal);
transform: rotate(45deg);
}
.node-label.fictional {
border-color: rgba(203, 93, 63, 0.42);
background: rgba(255, 241, 225, 0.94);
}
.node-label.fictional .node-dot {
background: var(--coral);
}
.node-label.closed {
border-color: rgba(190, 63, 63, 0.5);
background: rgba(255, 235, 229, 0.95);
color: #8d2e2e;
}
.node-label.closed .node-dot {
background: var(--closed);
}
.fictional-tag {
padding: 2px 4px;
border-radius: 4px;
background: rgba(219, 101, 75, 0.13);
color: #a34c36;
font-size: 7px;
font-weight: 900;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.edge-label {
padding: 3px 6px;
border-radius: 6px;
background: rgba(43, 65, 60, 0.76);
color: white;
font-size: 9px;
font-weight: 800;
box-shadow: 0 3px 10px rgba(25, 42, 38, 0.13);
}
.legend {
position: fixed;
z-index: 12;
left: 24px;
bottom: 22px;
display: flex;
flex-wrap: wrap;
gap: 13px;
max-width: 420px;
padding: 10px 13px;
border: 1px solid rgba(255, 255, 255, 0.45);
border-radius: 13px;
background: rgba(255, 248, 230, 0.79);
box-shadow: 0 10px 28px rgba(70, 50, 26, 0.12);
backdrop-filter: blur(10px);
color: #566560;
font-size: 10px;
font-weight: 750;
pointer-events: none;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 18px;
height: 4px;
border-radius: 99px;
background: var(--teal);
}
.swatch.gold {
background: var(--gold);
}
.swatch.closed {
width: 9px;
height: 9px;
border-radius: 3px;
background: var(--closed);
transform: rotate(45deg);
}
.swatch.fictional {
width: 9px;
height: 9px;
border-radius: 50%;
background: transparent;
border: 2px solid var(--coral);
}
.controls-hint {
position: fixed;
z-index: 11;
left: 24px;
bottom: 77px;
color: rgba(49, 67, 62, 0.78);
font-size: 10px;
font-weight: 750;
text-shadow: 0 1px 8px rgba(255, 247, 225, 0.8);
pointer-events: none;
}
.toast {
position: fixed;
z-index: 40;
top: 20px;
left: 50%;
max-width: calc(100vw - 40px);
padding: 10px 15px;
border-radius: 999px;
background: rgba(43, 67, 62, 0.92);
box-shadow: 0 10px 25px rgba(35, 51, 47, 0.2);
color: white;
font-size: 12px;
font-weight: 750;
opacity: 0;
transform: translate(-50%, -12px);
transition: opacity 180ms ease, transform 180ms ease;
pointer-events: none;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
.north {
position: fixed;
z-index: 10;
right: 432px;
bottom: 24px;
display: grid;
place-items: center;
width: 42px;
height: 42px;
border: 1px solid rgba(56, 72, 67, 0.15);
border-radius: 50%;
background: rgba(255, 248, 229, 0.72);
color: #465b55;
font-family: Georgia, serif;
font-size: 12px;
font-weight: 700;
pointer-events: none;
}
.north::before {
content: "";
position: absolute;
top: 5px;
border-right: 5px solid transparent;
border-bottom: 12px solid #d99a21;
border-left: 5px solid transparent;
}
.north span {
margin-top: 15px;
}
@media (max-width: 900px) {
.brand {
top: 12px;
left: 14px;
}
.brand h1 {
font-size: 29px;
}
.brand p {
display: none;
}
.panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 48vh;
padding: 14px;
border-radius: 17px;
}
.legend,
.controls-hint,
.north {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" tabindex="0" aria-label="Interactive low-poly map of fictional trans-Saharan salt and gold routes"></canvas>
<div id="label-layer" aria-hidden="true"></div>
<header class="brand">
<div class="eyebrow">Interactive route-closure lab</div>
<h1>Salt & Gold<br>Across the Sahara</h1>
<p>Close a node, inspect the detour, and calculate the water burden per traveler.</p>
</header>
<aside class="panel" aria-label="Route simulation controls and results">
<div class="panel-header">
<div>
<h2><span class="step">1</span>Close one route node</h2>
<p style="margin:6px 0 0;color:#74807c;font-size:11px;line-height:1.4">
Closing removes road access and the node’s modeled water point.
</p>
</div>
</div>
<label for="node-select">Selected node</label>
<select id="node-select" aria-label="Select a route node"></select>
<div class="button-row">
<button id="close-button" class="primary" type="button">Close selected node</button>
<button id="reset-button" class="secondary" type="button">Reopen</button>
</div>
<div id="network-status" class="status open">
All nodes are open. Suggested experiment: close Tazoult Relay, a fictional route node.
</div>
<h3><span class="step">2</span>Inspect a trade corridor</h3>
<div class="route-switch" role="group" aria-label="Choose trade corridor">
<button type="button" data-route="gold" class="active">Gold · northbound</button>
<button type="button" data-route="salt">Salt · southbound</button>
</div>
<div class="metric-grid">
<div class="metric">
<span id="baseline-distance" class="value">—</span>
<span class="caption">Original distance</span>
</div>
<div class="metric">
<span id="detour-distance" class="value">—</span>
<span class="caption">New distance</span>
</div>
<div class="metric">
<span id="added-distance" class="value">—</span>
<span class="caption">Added distance</span>
</div>
</div>
<div class="route-summary">
<div id="corridor-name" class="corridor">Gold corridor · Gao → Sijilmasa</div>
<div class="path-line">
<span class="path-key">Original</span>
<div id="original-path" class="path-chips"></div>
</div>
<div class="path-line">
<span class="path-key">After</span>
<div id="detour-path" class="path-chips"></div>
</div>
</div>
<h3>Minimum carried water</h3>
<div class="water-card">
<div class="water-top">
<div>
<div class="water-title">Required after closure</div>
<div class="water-number"><span id="water-value">—</span> <small>L / traveler</small></div>
</div>
<div id="water-delta" class="water-delta">—</div>
</div>
<div class="water-bar"><div id="water-bar-fill"></div></div>
<p id="water-explanation"></p>
</div>
<div id="lesson-note" class="lesson-note"></div>
<details open>
<summary>Explicit teaching assumptions</summary>
<ul class="assumptions">
<li>This is a schematic network. Geography, edge lengths, and daily assumptions are invented for instruction.</li>
<li>Historical place names are used for orientation; route relationships and kilometer values are not historical survey data.</li>
<li>Every open node is treated as having potable water and sufficient rest for one night.</li>
<li>Each graph edge is one water-to-water crossing. There is no assumed reliable water between its endpoints.</li>
<li>The detour is the shortest available path measured in the fictional kilometers shown on the edges.</li>
<li>Caravan pace: <strong>30 km per day</strong>.</li>
<li>Personal drinking use: <strong>3 L per traveler per day</strong>, before the heat adjustment.</li>
<li>Heat and dust adjustment: <strong>×1.25</strong>.</li>
<li>Safety reserve: <strong>+50%</strong> above adjusted demand.</li>
<li>Water capacity is based on the longest single crossing, not total caravan distance, because water can be replenished at open nodes.</li>
<li>Capacity is per traveler and excludes water or feed carried for animals.</li>
</ul>
<div class="formula">
capacity = longest crossing ÷ 30 × 3 L × 1.25 × 1.50
</div>
</details>
</aside>
<div class="controls-hint">Drag to orbit · wheel to zoom · Shift/right-drag to pan · click a node to select it</div>
<div class="legend" aria-label="Map legend">
<div class="legend-item"><span class="swatch gold"></span> Gold route</div>
<div class="legend-item"><span class="swatch"></span> Salt route</div>
<div class="legend-item"><span class="swatch fictional"></span> Fictional node</div>
<div class="legend-item"><span class="swatch closed"></span> Closed node</div>
</div>
<div class="north" aria-hidden="true"><span>N</span></div>
<div id="toast" class="toast" role="status"></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Teaching model
// -------------------------------------------------------------------------
const nodes = [
{ id: "sijilmasa", name: "Sijilmasa", short: "Sijilmasa", x: -7.0, z: -0.3, kind: "salt", fictional: false },
{ id: "tazoult", name: "Tazoult Relay", short: "Tazoult", x: -5.35, z: 1.55, kind: "fictional", fictional: true },
{ id: "taghaza", name: "Taghaza", short: "Taghaza", x: -3.8, z: -1.7, kind: "salt", fictional: false },
{ id: "awdaghost", name: "Awdaghost", short: "Awdaghost", x: -2.2, z: 2.55, kind: "gold", fictional: false },
{ id: "walata", name: "Walata", short: "Walata", x: -1.0, z: -0.7, kind: "salt", fictional: false },
{ id: "timbuktu", name: "Timbuktu", short: "Timbuktu", x: 1.1, z: 0.1, kind: "mixed", fictional: false },
{ id: "noura", name: "Noura Well", short: "Noura", x: 0.0, z: 2.75, kind: "fictional", fictional: true },
{ id: "gao", name: "Gao", short: "Gao", x: 4.2, z: -0.2, kind: "gold", fictional: false }
];
const edges = [
{ id: "e-sz", a: "sijilmasa", b: "tazoult", km: 520 },
{ id: "e-st", a: "sijilmasa", b: "taghaza", km: 620 },
{ id: "e-za", a: "tazoult", b: "awdaghost", km: 430 },
{ id: "e-zn", a: "tazoult", b: "noura", km: 560 },
{ id: "e-ag", a: "awdaghost", b: "gao", km: 560 },
{ id: "e-an", a: "awdaghost", b: "noura", km: 480 },
{ id: "e-wn", a: "walata", b: "noura", km: 610 },
{ id: "e-tn", a: "taghaza", b: "noura", km: 700 },
{ id: "e-tm", a: "taghaza", b: "timbuktu", km: 930 },
{ id: "e-wm", a: "walata", b: "timbuktu", km: 390 },
{ id: "e-wg", a: "walata", b: "gao", km: 900 },
{ id: "e-mn", a: "timbuktu", b: "noura", km: 510 },
{ id: "e-mg", a: "timbuktu", b: "gao", km: 480 },
{ id: "e-ng", a: "noura", b: "gao", km: 750 }
];
const routes = {
gold: {
from: "gao",
to: "sijilmasa",
name: "Gold corridor · Gao → Sijilmasa",
color: 0xd99a21
},
salt: {
from: "sijilmasa",
to: "gao",
name: "Salt corridor · Sijilmasa → Gao",
color: 0x247d82
}
};
const assumptions = {
kmPerDay: 30,
litersPerDay: 3,
heatFactor: 1.25,
reserveFactor: 1.50
};
const state = {
selected: "tazoult",
closed: null,
route: "gold"
};
const nodeById = new Map(nodes.map(n => [n.id, n]));
const edgeById = new Map(edges.map(e => [e.id, e]));
function shortestPath(from, to, closedNode) {
const distances = new Map(nodes.map(n => [n.id, Infinity]));
const previous = new Map();
const unvisited = new Set(nodes.map(n => n.id));
distances.set(from, 0);
while (unvisited.size) {
let current = null;
let best = Infinity;
for (const id of unvisited) {
if (distances.get(id) < best) {
best = distances.get(id);
current = id;
}
}
if (current === null || !Number.isFinite(best)) break;
if (current === to) break;
unvisited.delete(current);
for (const edge of edges) {
let neighbor = null;
if (edge.a === current) neighbor = edge.b;
if (edge.b === current) neighbor = edge.a;
if (!neighbor || !unvisited.has(neighbor)) continue;
if (closedNode && (neighbor === closedNode || current === closedNode)) continue;
const candidate = best + edge.km;
if (candidate < distances.get(neighbor)) {
distances.set(neighbor, candidate);
previous.set(neighbor, { node: current, edge: edge.id });
}
}
}
if (!Number.isFinite(distances.get(to))) return null;
const pathNodes = [to];
const pathEdges = [];
let cursor = to;
while (cursor !== from) {
const step = previous.get(cursor);
if (!step) return null;
pathEdges.push(step.edge);
pathNodes.push(step.node);
cursor = step.node;
}
pathNodes.reverse();
pathEdges.reverse();
return {
nodes: pathNodes,
edges: pathEdges,
distance: distances.get(to),
edgeObjects: pathEdges.map(id => edgeById.get(id))
};
}
function waterCapacity(path) {
if (!path || !path.edgeObjects.length) {
return { liters: 0, longestKm: 0, days: 0, base: 0, adjusted: 0 };
}
const longestKm = Math.max(...path.edgeObjects.map(e => e.km));
const days = longestKm / assumptions.kmPerDay;
const base = days * assumptions.litersPerDay;
const adjusted = base * assumptions.heatFactor;
const liters = adjusted * assumptions.reserveFactor;
return { liters, longestKm, days, base, adjusted };
}
// -------------------------------------------------------------------------
// Scene setup
// -------------------------------------------------------------------------
const canvas = document.getElementById("scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xead8b4);
scene.fog = new THREE.Fog(0xead8b4, 15, 29);
const camera = new THREE.PerspectiveCamera(43, window.innerWidth / window.innerHeight, 0.1, 80);
scene.add(new THREE.HemisphereLight(0xfff3d6, 0x8a6640, 2.0));
const sun = new THREE.DirectionalLight(0xffe3a4, 2.5);
sun.position.set(-7, 12, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -13;
sun.shadow.camera.right = 13;
sun.shadow.camera.top = 10;
sun.shadow.camera.bottom = -10;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
sun.shadow.bias = -0.0005;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xcde5df, 0.6);
fill.position.set(9, 6, -8);
scene.add(fill);
// Low-poly terrain with flat-colored triangular faces.
function createTerrain() {
const width = 23;
const depth = 13;
const sx = 25;
const sz = 17;
const positions = [];
const colors = [];
const palette = [0xe8c987, 0xe4c27e, 0xedcf90, 0xdfb873, 0xe8c17b];
const point = (i, j) => {
const x = -width / 2 + (i / sx) * width;
const z = -depth / 2 + (j / sz) * depth;
const y =
0.035 * Math.sin(x * 0.65) +
0.025 * Math.cos(z * 0.8) +
0.018 * Math.sin((x + z) * 1.3);
return [x, y, z];
};
const addTriangle = (a, b, c, colorIndex) => {
const color = new THREE.Color(palette[colorIndex % palette.length]);
for (const p of [a, b, c]) {
positions.push(...p);
colors.push(color.r, color.g, color.b);
}
};
for (let j = 0; j < sz; j++) {
for (let i = 0; i < sx; i++) {
const a = point(i, j);
const b = point(i + 1, j);
const c = point(i + 1, j + 1);
const d = point(i, j + 1);
const tint = Math.abs(Math.sin(i * 1.7 + j * 0.9)) * 2;
addTriangle(a, b, c, Math.floor(tint));
addTriangle(a, c, d, Math.floor(tint) + 1);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3));
geometry.computeVertexNormals();
const mesh = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
flatShading: true,
roughness: 1
})
);
mesh.receiveShadow = true;
scene.add(mesh);
}
createTerrain();
function addDune(x, z, sx, sz, color) {
const dune = new THREE.Mesh(
new THREE.IcosahedronGeometry(1, 1),
new THREE.MeshStandardMaterial({
color,
flatShading: true,
roughness: 1
})
);
dune.position.set(x, 0.02, z);
dune.scale.set(sx, 0.18, sz);
dune.rotation.y = Math.random() * Math.PI;
dune.receiveShadow = true;
scene.add(dune);
}
[
[-9.4, 2.7, 1.7, 0.7],
[-8.2, -3.0, 1.4, 0.6],
[-5.9, 3.8, 1.2, 0.55],
[-1.8, -3.7, 1.5, 0.6],
[2.8, 3.4, 1.7, 0.65],
[6.7, 1.7, 1.8, 0.75],
[8.2, -2.7, 1.6, 0.7]
].forEach(([x, z, sx, sz], i) => addDune(x, z, sx, sz, i % 2 ? 0xe7c17a : 0xdfb671));
function addMountain(x, z, radius, height, color, rotation = 0) {
const mountain = new THREE.Mesh(
new THREE.ConeGeometry(radius, height, 5, 1),
new THREE.MeshStandardMaterial({
color,
flatShading: true,
roughness: 1
})
);
mountain.position.set(x, height / 2 - 0.05, z);
mountain.rotation.y = rotation;
mountain.castShadow = true;
mountain.receiveShadow = true;
scene.add(mountain);
}
[
[-8.5, -4.3, 1.55, 1.8, 0xa66e4f],
[-6.8, -4.5, 1.15, 1.35, 0xb47d58],
[-5.2, -4.1, 1.75, 2.2, 0x9c664b],
[-3.0, -4.7, 1.35, 1.55, 0xb17a58],
[-0.7, -4.4, 1.8, 2.15, 0x986148],
[1.8, -4.8, 1.45, 1.75, 0xaf7552],
[4.0, -4.25, 2.0, 2.35, 0x986047],
[6.3, -4.6, 1.4, 1.6, 0xb37b57],
[8.2, -4.0, 1.8, 2.0, 0xa36c50]
].forEach((m, i) => addMountain(...m, i * 0.31));
// A stylized low-poly Nile ribbon.
const riverCurve = new THREE.CatmullRomCurve3([
new THREE.Vector3(-2.9, 0.11, 1.6),
new THREE.Vector3(-1.9, 0.11, 1.0),
new THREE.Vector3(-0.7, 0.11, 0.65),
new THREE.Vector3(0.8, 0.11, 0.55),
new THREE.Vector3(2.0, 0.11, 0.15),
new THREE.Vector3(3.3, 0.11, 0.05),
new THREE.Vector3(4.2, 0.11, -0.2)
]);
const river = new THREE.Mesh(
new THREE.TubeGeometry(riverCurve, 34, 0.075, 4, false),
new THREE.MeshStandardMaterial({
color: 0x5b9b9c,
roughness: 0.8,
flatShading: true
})
);
scene.add(river);
function addTree(x, z, scale = 1) {
const group = new THREE.Group();
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.035, 0.055, 0.34, 5),
new THREE.MeshStandardMaterial({ color: 0x765038, flatShading: true })
);
trunk.position.y = 0.17;
const crown = new THREE.Mesh(
new THREE.ConeGeometry(0.22, 0.62, 6),
new THREE.MeshStandardMaterial({ color: 0x607b4d, flatShading: true })
);
crown.position.y = 0.57;
group.add(trunk, crown);
group.position.set(x, 0.04, z);
group.scale.setScalar(scale);
group.rotation.y = Math.random() * Math.PI;
scene.add(group);
}
[
[-5.9, 2.6, 0.9], [-4.9, 3.1, 0.75], [-1.4, -1.5, 0.7],
[0.2, -1.4, 0.65], [-2.9, 2.2, 0.7], [2.8, 1.4, 0.65]
].forEach(t => addTree(...t));
// -------------------------------------------------------------------------
// Edges, nodes, labels and arrows
// -------------------------------------------------------------------------
const clickables = [];
const nodeVisuals = new Map();
const edgeVisuals = new Map();
const labelLayer = document.getElementById("label-layer");
const neutralEdge = new THREE.Color(0x8b7d61);
const closedEdge = new THREE.Color(0xb84b45);
const goldColor = new THREE.Color(0xd99a21);
const tealColor = new THREE.Color(0x247d82);
function createEdgeVisual(edge) {
const a = nodeById.get(edge.a);
const b = nodeById.get(edge.b);
const start = new THREE.Vector3(a.x, 0.27, a.z);
const end = new THREE.Vector3(b.x, 0.27, b.z);
const direction = end.clone().sub(start);
const length = direction.length();
const midpoint = start.clone().add(end).multiplyScalar(0.5);
const baseMaterial = new THREE.MeshStandardMaterial({
color: neutralEdge,
roughness: 0.95,
transparent: true,
opacity: 0.48
});
const base = new THREE.Mesh(
new THREE.CylinderGeometry(0.035, 0.035, length, 5),
baseMaterial
);
base.position.copy(midpoint);
base.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction.clone().normalize());
base.receiveShadow = true;
scene.add(base);
const overlayMaterial = new THREE.MeshBasicMaterial({
color: tealColor,
transparent: true,
opacity: 0.95,
depthWrite: false
});
const overlay = new THREE.Mesh(
new THREE.CylinderGeometry(0.066, 0.066, length, 6),
overlayMaterial
);
overlay.position.copy(midpoint);
overlay.quaternion.copy(base.quaternion);
overlay.visible = false;
scene.add(overlay);
const arrow = new THREE.Mesh(
new THREE.ConeGeometry(0.105, 0.28, 4),
new THREE.MeshBasicMaterial({
color: tealColor,
transparent: true,
opacity: 0.95,
depthWrite: false
})
);
arrow.position.set(midpoint.x, 0.54, midpoint.z);
arrow.visible = false;
scene.add(arrow);
const label = document.createElement("div");
label.className = "edge-label";
label.textContent = `${edge.km} km`;
label.style.display = "none";
labelLayer.appendChild(label);
edgeVisuals.set(edge.id, { base, overlay, arrow, label, midpoint });
}
edges.forEach(createEdgeVisual);
function nodeColor(node) {
if (node.kind === "gold") return 0xd99a21;
if (node.kind === "salt") return 0x247d82;
if (node.kind === "fictional") return 0xdb654b;
return 0xb49762;
}
function createNodeVisual(node) {
const group = new THREE.Group();
group.position.set(node.x, 0.05, node.z);
const baseMaterial = new THREE.MeshStandardMaterial({
color: 0xf0dfb8,
flatShading: true,
roughness: 0.85
});
const base = new THREE.Mesh(
new THREE.CylinderGeometry(0.34, 0.42, 0.16, 6),
baseMaterial
);
base.position.y = 0.08;
base.castShadow = true;
base.receiveShadow = true;
const coreMaterial = new THREE.MeshStandardMaterial({
color: nodeColor(node),
emissive: 0x000000,
flatShading: true,
roughness: 0.62
});
const core = new THREE.Mesh(
new THREE.OctahedronGeometry(node.fictional ? 0.27 : 0.23, 0),
coreMaterial
);
core.position.y = 0.56;
core.castShadow = true;
const ringMaterial = new THREE.MeshBasicMaterial({
color: node.fictional ? 0xdb654b : 0x425c57,
transparent: true,
opacity: 0.8
});
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.38, 0.035, 4, 16),
ringMaterial
);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.18;
const closedGroup = new THREE.Group();
closedGroup.position.y = 0.58;
const crossMaterial = new THREE.MeshBasicMaterial({ color: 0xbe3f3f });
const cross1 = new THREE.Mesh(new THREE.BoxGeometry(0.54, 0.10, 0.10), crossMaterial);
const cross2 = new THREE.Mesh(new THREE.BoxGeometry(0.54, 0.10, 0.10), crossMaterial);
cross1.rotation.z = Math.PI / 4;
cross2.rotation.z = -Math.PI / 4;
closedGroup.add(cross1, cross2);
closedGroup.visible = false;
group.add(base, core, ring, closedGroup);
group.traverse(child => {
if (child.isMesh) {
child.userData.nodeId = node.id;
clickables.push(child);
}
});
scene.add(group);
const label = document.createElement("div");
label.className = "node-label";
label.innerHTML = `
<span class="node-dot"></span>
<span>${node.name}</span>
${node.fictional ? '<span class="fictional-tag">fictional</span>' : ""}
`;
labelLayer.appendChild(label);
nodeVisuals.set(node.id, {
group,
base,
baseMaterial,
core,
coreMaterial,
ring,
ringMaterial,
closedGroup,
label,
anchor: new THREE.Vector3(node.x, 1.02, node.z)
});
}
nodes.forEach(createNodeVisual);
const selectionHalo = new THREE.Mesh(
new THREE.TorusGeometry(0.53, 0.045, 5, 24),
new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.8,
depthWrite: false
})
);
selectionHalo.rotation.x = Math.PI / 2;
scene.add(selectionHalo);
// -------------------------------------------------------------------------
// Small low-poly caravan
// -------------------------------------------------------------------------
function createCamel() {
const group = new THREE.Group();
const brown = new THREE.MeshStandardMaterial({
color: 0x9a6035,
flatShading: true,
roughness: 0.95
});
const darkBrown = new THREE.MeshStandardMaterial({
color: 0x714326,
flatShading: true,
roughness: 0.95
});
const cloth = new THREE.MeshStandardMaterial({
color: 0xb14f3e,
flatShading: true,
roughness: 0.95
});
const body = new THREE.Mesh(new THREE.DodecahedronGeometry(0.19, 0), brown);
body.scale.set(1.35, 0.8, 0.75);
body.position.y = 0.30;
body.castShadow = true;
const hump = new THREE.Mesh(new THREE.ConeGeometry(0.12, 0.25, 5), brown);
hump.position.set(-0.03, 0.46, 0);
hump.castShadow = true;
const neck = new THREE.Mesh(new THREE.CylinderGeometry(0.045, 0.065, 0.30, 5), brown);
neck.position.set(0.20, 0.43, 0);
neck.rotation.z = -0.32;
const head = new THREE.Mesh(new THREE.BoxGeometry(0.23, 0.10, 0.11), darkBrown);
head.position.set(0.31, 0.57, 0);
const pack = new THREE.Mesh(new THREE.BoxGeometry(0.23, 0.20, 0.20), cloth);
pack.position.set(-0.03, 0.36, 0.17);
pack.castShadow = true;
group.add(body, hump, neck, head, pack);
const legGeometry = new THREE.CylinderGeometry(0.025, 0.03, 0.25, 4);
[[0.12, 0.10], [0.12, -0.10], [-0.12, 0.10], [-0.12, -0.10]].forEach(([x, z]) => {
const leg = new THREE.Mesh(legGeometry, darkBrown);
leg.position.set(x, 0.13, z);
group.add(leg);
});
return group;
}
const caravan = new THREE.Group();
const camelOne = createCamel();
const camelTwo = createCamel();
camelTwo.position.set(-0.33, 0, 0.06);
camelTwo.scale.setScalar(0.88);
caravan.add(camelOne, camelTwo);
scene.add(caravan);
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
const nodeSelect = document.getElementById("node-select");
const closeButton = document.getElementById("close-button");
const resetButton = document.getElementById("reset-button");
const status = document.getElementById("network-status");
const toast = document.getElementById("toast");
const closableNodes = nodes.filter(n => n.id !== "sijilmasa" && n.id !== "gao");
closableNodes.forEach(node => {
const option = document.createElement("option");
option.value = node.id;
option.textContent = `${node.name}${node.fictional ? " — fictional" : ""}`;
nodeSelect.appendChild(option);
});
nodeSelect.value = state.selected;
function showToast(message) {
toast.textContent = message;
toast.classList.add("show");
clearTimeout(showToast.timer);
showToast.timer = setTimeout(() => toast.classList.remove("show"), 1800);
}
function pathChips(path) {
if (!path) return '<span class="chip">No route</span>';
return path.nodes.map((id, index) => {
const node = nodeById.get(id);
return `${index ? '<span class="arrow">→</span>' : ""}<span class="chip">${node.short}</span>`;
}).join("");
}
function updateEdgeAndNodeVisuals() {
const goldPath = shortestPath(routes.gold.from, routes.gold.to, state.closed);
const saltPath = shortestPath(routes.salt.from, routes.salt.to, state.closed);
const selectedPath = state.route === "gold" ? goldPath : saltPath;
const selectedEdges = new Set(selectedPath?.edges || []);
const goldEdges = new Set(goldPath?.edges || []);
const saltEdges = new Set(saltPath?.edges || []);
const activeColor = new THREE.Color(routes[state.route].color);
for (const edge of edges) {
const visual = edgeVisuals.get(edge.id);
const closedIncident = state.closed && (edge.a === state.closed || edge.b === state.closed);
const inGold = goldEdges.has(edge.id);
const inSalt = saltEdges.has(edge.id);
const inSelected = selectedEdges.has(edge.id);
if (closedIncident) {
visual.base.material.color.copy(closedEdge);
visual.base.material.opacity = 0.72;
visual.overlay.visible = false;
visual.arrow.visible = false;
visual.label.style.display = "none";
continue;
}
visual.base.material.color.copy(neutralEdge);
visual.base.material.opacity = 0.42;
visual.overlay.visible = inGold || inSalt;
if (inSelected) {
visual.overlay.material.color.copy(activeColor);
visual.overlay.material.opacity = 0.98;
visual.base.material.color.copy(activeColor).multiplyScalar(0.7);
visual.base.material.opacity = 0.72;
} else if (inGold || inSalt) {
visual.overlay.material.color.copy(inGold ? goldColor : tealColor);
visual.overlay.material.opacity = 0.38;
}
visual.arrow.visible = inSelected;
visual.label.style.display = inSelected ? "block" : "none";
}
// Orient arrows along the active corridor.
if (selectedPath) {
for (let i = 0; i < selectedPath.edges.length; i++) {
const edge = edgeById.get(selectedPath.edges[i]);
const visual = edgeVisuals.get(edge.id);
const from = nodeById.get(selectedPath.nodes[i]);
const to = nodeById.get(selectedPath.nodes[i + 1]);
const direction = new THREE.Vector3(to.x - from.x, 0, to.z - from.z).normalize();
visual.arrow.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction);
visual.arrow.material.color.copy(activeColor);
visual.arrow.material.opacity = 0.95;
}
}
for (const node of nodes) {
const visual = nodeVisuals.get(node.id);
const isClosed = state.closed === node.id;
const selected = state.selected === node.id;
visual.baseMaterial.color.set(isClosed ? 0xe5b0a4 : 0xf0dfb8);
visual.coreMaterial.color.set(isClosed ? 0xbe3f3f : nodeColor(node));
visual.coreMaterial.emissive.set(isClosed ? 0x4a0909 : 0x000000);
visual.core.rotation.y = isClosed ? 0.55 : 0.22;
visual.ringMaterial.color.set(isClosed ? 0xbe3f3f : node.fictional ? 0xdb654b : 0x425c57);
visual.ringMaterial.opacity = selected ? 1 : 0.72;
visual.closedGroup.visible = isClosed;
visual.label.classList.toggle("fictional", node.fictional);
visual.label.classList.toggle("closed", isClosed);
visual.label.style.zIndex = selected ? "4" : "2";
}
const selectedNode = nodeById.get(state.selected);
selectionHalo.position.set(selectedNode.x, 0.23, selectedNode.z);
selectionHalo.material.color.set(selectedNode.fictional ? 0xdb654b : 0xffffff);
selectionHalo.material.opacity = 0.82;
}
function updateResults() {
const route = routes[state.route];
const baseline = shortestPath(route.from, route.to, null);
const after = shortestPath(route.from, route.to, state.closed);
const baselineWater = waterCapacity(baseline);
const afterWater = waterCapacity(after);
const added = after ? after.distance - baseline.distance : 0;
document.getElementById("baseline-distance").textContent = `${baseline.distance.toLocaleString()} km`;
document.getElementById("detour-distance").textContent = after ? `${after.distance.toLocaleString()} km` : "No route";
document.getElementById("added-distance").textContent = `${added >= 0 ? "+" : ""}${added.toLocaleString()} km`;
document.getElementById("baseline-distance").className = `value ${state.route === "gold" ? "gold" : "teal"}`;
document.getElementById("detour-distance").className = `value ${state.route === "gold" ? "gold" : "teal"}`;
document.getElementById("added-distance").className = `value ${state.route === "gold" ? "gold" : "teal"}`;
document.getElementById("corridor-name").textContent = route.name;
document.getElementById("original-path").innerHTML = pathChips(baseline);
document.getElementById("detour-path").innerHTML = pathChips(after);
document.getElementById("water-value").textContent = afterWater.liters.toFixed(1);
const waterDelta = afterWater.liters - baselineWater.liters;
document.getElementById("water-delta").textContent =
`${waterDelta >= 0 ? "+" : ""}${waterDelta.toFixed(1)} L vs original`;
const maxCapacity = Math.max(baselineWater.liters, afterWater.liters, 1) * 1.15;
document.getElementById("water-bar-fill").style.width =
`${Math.min(100, (afterWater.liters / maxCapacity) * 100)}%`;
document.getElementById("water-explanation").textContent =
`Longest open crossing: ${afterWater.longestKm.toLocaleString()} km. ` +
`At ${assumptions.kmPerDay} km/day, that is ${afterWater.days.toFixed(1)} travel days. ` +
`Capacity includes heat/dust and the 50% reserve.`;
const note = document.getElementById("lesson-note");
if (!state.closed) {
note.textContent =
"Close Tazoult Relay to make the gold corridor use the longer southern detour. " +
"The gold and salt corridors are evaluated independently.";
} else if (added === 0) {
note.textContent =
`This closure does not affect the ${state.route} corridor: its original shortest path avoids ` +
`${nodeById.get(state.closed).name}. Other corridors can still be affected.`;
} else if (waterDelta > 0) {
note.textContent =
`The detour adds ${added.toLocaleString()} km and raises water capacity by ` +
`${waterDelta.toFixed(1)} L per traveler because its longest no-resupply crossing is longer.`;
} else {
note.textContent =
`The detour adds ${added.toLocaleString()} km, but required water capacity falls by ` +
`${Math.abs(waterDelta).toFixed(1)} L: the replacement route has a shorter longest crossing. ` +
`Total distance and water burden are different constraints.`;
}
if (state.closed) {
const closedNode = nodeById.get(state.closed);
status.classList.remove("open");
status.textContent =
`${closedNode.name} is closed. Its route links and modeled water point are unavailable. ` +
`Only one node is closed at a time.`;
} else {
status.classList.add("open");
status.textContent =
"All nodes are open. Suggested experiment: close Tazoult Relay, a fictional route node.";
}
closeButton.textContent =
state.closed === state.selected ? "Reopen selected node" : "Close selected node";
updateEdgeAndNodeVisuals();
}
nodeSelect.addEventListener("change", () => {
state.selected = nodeSelect.value;
updateResults();
});
closeButton.addEventListener("click", () => {
state.closed = state.closed === state.selected ? null : state.selected;
updateResults();
showToast(
state.closed
? `${nodeById.get(state.closed).name} closed`
: `${nodeById.get(state.selected).name} reopened`
);
});
resetButton.addEventListener("click", () => {
state.closed = null;
updateResults();
showToast("All route nodes reopened");
});
document.querySelectorAll("[data-route]").forEach(button => {
button.addEventListener("click", () => {
state.route = button.dataset.route;
document.querySelectorAll("[data-route]").forEach(b => {
b.classList.toggle("active", b === button);
});
updateResults();
});
});
// -------------------------------------------------------------------------
// Camera controls implemented directly, without addons
// -------------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(-1.0, 0.2, 0.25),
desiredTarget: new THREE.Vector3(-1.0, 0.2, 0.25),
radius: 14.8,
desiredRadius: 14.8,
theta: 0.10,
desiredTheta: 0.10,
phi: 0.83,
desiredPhi: 0.83
};
function updateCamera() {
cameraState.theta += (cameraState.desiredTheta - cameraState.theta) * 0.12;
cameraState.phi += (cameraState.desiredPhi - cameraState.phi) * 0.12;
cameraState.radius += (cameraState.desiredRadius - cameraState.radius) * 0.12;
cameraState.target.lerp(cameraState.desiredTarget, 0.12);
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x + cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z + cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
const pointer = {
down: false,
moved: false,
button: 0,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0
};
const raycaster = new THREE.Raycaster();
const pointerNDC = new THREE.Vector2();
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("pointerdown", event => {
pointer.down = true;
pointer.moved = false;
pointer.button = event.button;
pointer.startX = pointer.lastX = event.clientX;
pointer.startY = pointer.lastY = event.clientY;
canvas.setPointerCapture(event.pointerId);
canvas.focus();
});
canvas.addEventListener("pointermove", event => {
if (!pointer.down) return;
const dx = event.clientX - pointer.lastX;
const dy = event.clientY - pointer.lastY;
const totalDistance = Math.hypot(
event.clientX - pointer.startX,
event.clientY - pointer.startY
);
if (totalDistance > 4) pointer.moved = true;
if (pointer.button === 2 || event.shiftKey) {
const right = new THREE.Vector3(
Math.cos(cameraState.desiredTheta),
0,
-Math.sin(cameraState.desiredTheta)
);
const forward = new THREE.Vector3(
-Math.sin(cameraState.desiredTheta),
0,
-Math.cos(cameraState.desiredTheta)
);
const scale = cameraState.desiredRadius * 0.0016;
cameraState.desiredTarget.addScaledVector(right, -dx * scale);
cameraState.desiredTarget.addScaledVector(forward, -dy * scale);
cameraState.desiredTarget.x = THREE.MathUtils.clamp(cameraState.desiredTarget.x, -9, 9);
cameraState.desiredTarget.z = THREE.MathUtils.clamp(cameraState.desiredTarget.z, -6, 6);
} else {
cameraState.desiredTheta -= dx * 0.006;
cameraState.desiredPhi = THREE.MathUtils.clamp(
cameraState.desiredPhi + dy * 0.005,
0.28,
1.28
);
}
pointer.lastX = event.clientX;
pointer.lastY = event.clientY;
});
canvas.addEventListener("pointerup", event => {
pointer.down = false;
if (canvas.hasPointerCapture(event.pointerId)) canvas.releasePointerCapture(event.pointerId);
if (!pointer.moved && event.button === 0) {
const rect = canvas.getBoundingClientRect();
pointerNDC.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointerNDC.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointerNDC, camera);
const hits = raycaster.intersectObjects(clickables, false);
if (hits.length) {
const id = hits[0].object.userData.nodeId;
state.selected = id;
nodeSelect.value = id;
updateResults();
showToast(`${nodeById.get(id).name} selected — use “Close selected node”`);
}
}
});
canvas.addEventListener("pointercancel", () => {
pointer.down = false;
});
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraState.desiredRadius = THREE.MathUtils.clamp(
cameraState.desiredRadius * Math.exp(event.deltaY * 0.001),
8.5,
25
);
}, { passive: false });
canvas.addEventListener("keydown", event => {
const step = 0.08;
if (event.key === "ArrowLeft") cameraState.desiredTheta += step;
if (event.key === "ArrowRight") cameraState.desiredTheta -= step;
if (event.key === "ArrowUp") cameraState.desiredPhi = Math.max(0.28, cameraState.desiredPhi - step);
if (event.key === "ArrowDown") cameraState.desiredPhi = Math.min(1.28, cameraState.desiredPhi + step);
if (event.key === "+" || event.key === "=") cameraState.desiredRadius = Math.max(8.5, cameraState.desiredRadius - 0.8);
if (event.key === "-") cameraState.desiredRadius = Math.min(25, cameraState.desiredRadius + 0.8);
});
// -------------------------------------------------------------------------
// Labels, caravan animation and render loop
// -------------------------------------------------------------------------
const projected = new THREE.Vector3();
function positionLabel(element, worldPosition, offsetY = 0) {
projected.copy(worldPosition).project(camera);
const visible = projected.z > -1 && projected.z < 1;
if (!visible) {
element.style.display = "none";
return;
}
element.style.display = "";
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight + offsetY;
element.style.transform = `translate(-50%, -100%) translate(${x}px, ${y}px)`;
}
function samplePath(path, fraction) {
if (!path || path.nodes.length < 2) return null;
const points = path.nodes.map(id => {
const n = nodeById.get(id);
return new THREE.Vector3(n.x, 0.48, n.z);
});
const lengths = [];
let total = 0;
for (let i = 0; i < points.length - 1; i++) {
const length = points[i].distanceTo(points[i + 1]);
lengths.push(length);
total += length;
}
let remaining = ((fraction % 1) + 1) % 1 * total;
for (let i = 0; i < lengths.length; i++) {
if (remaining <= lengths[i] || i === lengths.length - 1) {
const t = lengths[i] === 0 ? 0 : remaining / lengths[i];
const position = points[i].clone().lerp(points[i + 1], t);
const direction = points[i + 1].clone().sub(points[i]).normalize();
return { position, direction };
}
remaining -= lengths[i];
}
return null;
}
function updateLabels() {
for (const node of nodes) {
const visual = nodeVisuals.get(node.id);
positionLabel(visual.label, visual.anchor, 0);
}
for (const edge of edges) {
const visual = edgeVisuals.get(edge.id);
if (visual.label.style.display !== "none") {
positionLabel(visual.label, visual.midpoint, -2);
}
}
}
function resize() {
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
}
window.addEventListener("resize", resize);
const clock = new THREE.Clock();
function animate() {
const elapsed = clock.getElapsedTime();
updateCamera();
const route = routes[state.route];
const activePath = shortestPath(route.from, route.to, state.closed);
const sample = samplePath(activePath, elapsed * 0.035);
if (sample) {
caravan.visible = true;
caravan.position.copy(sample.position);
caravan.rotation.y = Math.atan2(sample.direction.x, sample.direction.z);
caravan.position.y += Math.sin(elapsed * 7) * 0.015;
} else {
caravan.visible = false;
}
const pulse = 1 + Math.sin(elapsed * 3.4) * 0.08;
selectionHalo.scale.setScalar(pulse);
for (const node of nodes) {
const visual = nodeVisuals.get(node.id);
visual.core.rotation.y += 0.003;
visual.core.position.y = 0.56 + Math.sin(elapsed * 1.5 + node.x) * 0.035;
}
updateLabels();
renderer.render(scene, camera);
}
updateResults();
resize();
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```