Prompt specification
Build or customize the Three.js 3D scene "One Station Closure on Two Networks" 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: One Station Closure on Two Networks
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/one-station-closure-on-two-networks-x2114
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows transport network hubs, fragility, and resilience. Animate the same origin-destination requests before and after removing a station. Recompute reachable paths instead of assuming every central-looking node has equal importance. Voxel style.
Working Three.js Starter (one-station-closure-on-two-networks-x2114):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Network Impact Lab — Transport Fragility & Resilience</title>
<style>
:root {
--bg: #06100f;
--panel: #0a1715;
--panel-2: #0d1d1a;
--line: #203a35;
--line-bright: #365b52;
--text: #e4f3ed;
--muted: #78958a;
--teal: #54e3c2;
--amber: #ffb454;
--red: #ff5575;
--blue: #6f8dff;
--mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: var(--mono);
}
button, input { font: inherit; }
button {
color: inherit;
background: none;
border: 0;
cursor: pointer;
}
.app {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
background:
radial-gradient(circle at 80% 10%, rgba(62, 160, 132, 0.08), transparent 35%),
var(--bg);
}
.header {
height: 66px;
flex: 0 0 66px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 0 22px;
border-bottom: 1px solid var(--line);
background: rgba(6, 16, 15, 0.92);
z-index: 20;
}
.brand {
display: flex;
align-items: center;
gap: 14px;
min-width: 0;
}
.brand-mark {
width: 31px;
height: 31px;
position: relative;
flex: 0 0 auto;
border: 1px solid var(--teal);
transform: rotate(45deg);
box-shadow: inset 0 0 0 6px var(--bg), inset 0 0 0 12px rgba(84, 227, 194, 0.15);
}
.brand-mark::after {
content: "";
position: absolute;
width: 5px;
height: 5px;
top: 12px;
left: 12px;
background: var(--teal);
}
.brand h1 {
margin: 0;
font-size: 14px;
line-height: 1.15;
letter-spacing: 0.14em;
font-weight: 700;
white-space: nowrap;
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.13em;
text-transform: uppercase;
white-space: nowrap;
}
.header-meta {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
justify-content: flex-end;
}
.meta-chip,
.state-chip {
height: 28px;
display: inline-flex;
align-items: center;
gap: 8px;
padding: 0 10px;
border: 1px solid var(--line);
color: var(--muted);
font-size: 9px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.state-chip {
color: var(--amber);
border-color: rgba(255, 180, 84, 0.38);
background: rgba(255, 180, 84, 0.06);
}
.state-chip.intact {
color: var(--teal);
border-color: rgba(84, 227, 194, 0.35);
background: rgba(84, 227, 194, 0.06);
}
.state-dot {
width: 6px;
height: 6px;
background: currentColor;
box-shadow: 0 0 10px currentColor;
}
.app-main {
min-height: 0;
flex: 1;
display: grid;
grid-template-columns: 326px minmax(0, 1fr);
}
.sidebar {
min-height: 0;
overflow-y: auto;
padding: 18px;
border-right: 1px solid var(--line);
background:
linear-gradient(180deg, rgba(13, 29, 26, 0.95), rgba(7, 18, 16, 0.96)),
var(--panel);
scrollbar-width: thin;
scrollbar-color: var(--line-bright) transparent;
}
.section {
padding-bottom: 18px;
margin-bottom: 18px;
border-bottom: 1px solid var(--line);
}
.section:last-child {
border-bottom: 0;
margin-bottom: 0;
padding-bottom: 0;
}
.eyebrow {
margin-bottom: 9px;
color: var(--muted);
font-size: 9px;
line-height: 1.3;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.target-card {
padding: 14px;
border: 1px solid rgba(255, 85, 117, 0.35);
background:
linear-gradient(135deg, rgba(255, 85, 117, 0.09), transparent 70%),
var(--panel-2);
}
.target-card.intact {
border-color: rgba(84, 227, 194, 0.3);
background:
linear-gradient(135deg, rgba(84, 227, 194, 0.08), transparent 70%),
var(--panel-2);
}
.target-top {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
}
.target-code {
color: var(--red);
font-size: 10px;
letter-spacing: 0.13em;
}
.target-card.intact .target-code { color: var(--teal); }
.target-name {
margin: 6px 0 0;
font-size: 18px;
line-height: 1.2;
letter-spacing: -0.02em;
}
.impact-score {
min-width: 55px;
padding: 7px 8px;
text-align: right;
border-left: 2px solid var(--red);
}
.target-card.intact .impact-score {
border-left-color: var(--teal);
}
.impact-score strong {
display: block;
font-size: 19px;
line-height: 1;
color: var(--red);
}
.target-card.intact .impact-score strong { color: var(--teal); }
.impact-score span {
display: block;
margin-top: 5px;
color: var(--muted);
font-size: 8px;
letter-spacing: 0.1em;
}
.target-stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1px;
margin-top: 14px;
background: var(--line);
border: 1px solid var(--line);
}
.target-stat {
padding: 8px;
background: rgba(6, 16, 15, 0.8);
}
.target-stat strong {
display: block;
font-size: 13px;
color: var(--text);
}
.target-stat span {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 7px;
letter-spacing: 0.08em;
line-height: 1.25;
text-transform: uppercase;
}
.button-row {
display: flex;
gap: 8px;
margin-top: 10px;
}
.button {
min-height: 34px;
flex: 1;
padding: 0 11px;
border: 1px solid var(--line-bright);
background: rgba(255, 255, 255, 0.025);
color: var(--text);
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
transition: 140ms ease;
}
.button:hover {
border-color: var(--teal);
color: var(--teal);
background: rgba(84, 227, 194, 0.06);
}
.button.primary {
color: var(--teal);
border-color: rgba(84, 227, 194, 0.42);
}
.button:disabled {
opacity: 0.35;
cursor: default;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
min-height: 76px;
padding: 10px;
border: 1px solid var(--line);
background: var(--panel-2);
}
.metric-label {
color: var(--muted);
font-size: 8px;
line-height: 1.3;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.metric-value {
margin-top: 9px;
font-size: 20px;
line-height: 1;
letter-spacing: -0.04em;
}
.metric-sub {
margin-top: 7px;
color: var(--muted);
font-size: 8px;
}
.metric-value.teal { color: var(--teal); }
.metric-value.amber { color: var(--amber); }
.metric-value.red { color: var(--red); }
.method-note {
margin: 11px 0 0;
padding: 10px;
border-left: 2px solid var(--teal);
color: #91aaa1;
background: rgba(84, 227, 194, 0.035);
font-size: 9px;
line-height: 1.55;
}
.station-list {
display: flex;
flex-direction: column;
gap: 5px;
max-height: 245px;
overflow-y: auto;
padding-right: 3px;
scrollbar-width: thin;
scrollbar-color: var(--line-bright) transparent;
}
.station-row {
width: 100%;
min-height: 39px;
display: grid;
grid-template-columns: 33px minmax(0, 1fr) 49px;
align-items: center;
gap: 8px;
padding: 6px 8px;
border: 1px solid transparent;
background: rgba(255, 255, 255, 0.018);
text-align: left;
transition: 120ms ease;
}
.station-row:hover {
border-color: var(--line-bright);
background: rgba(84, 227, 194, 0.045);
}
.station-row.active {
border-color: rgba(255, 85, 117, 0.5);
background: rgba(255, 85, 117, 0.075);
}
.station-id {
color: var(--muted);
font-size: 9px;
}
.station-row.active .station-id { color: var(--red); }
.station-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 9px;
}
.station-impact {
position: relative;
height: 22px;
overflow: hidden;
border: 1px solid var(--line);
background: var(--bg);
}
.station-impact i {
position: absolute;
inset: 0 auto 0 0;
width: var(--impact, 0%);
background: linear-gradient(90deg, rgba(255, 85, 117, 0.3), var(--red));
}
.station-impact span {
position: relative;
z-index: 1;
display: grid;
place-items: center;
height: 100%;
font-size: 8px;
}
.control-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
min-height: 36px;
}
.control-label {
color: var(--muted);
font-size: 9px;
letter-spacing: 0.05em;
}
.switch {
position: relative;
width: 34px;
height: 18px;
flex: 0 0 auto;
}
.switch input {
position: absolute;
opacity: 0;
pointer-events: none;
}
.switch i {
position: absolute;
inset: 0;
border: 1px solid var(--line-bright);
background: var(--bg);
}
.switch i::after {
content: "";
position: absolute;
width: 12px;
height: 12px;
top: 2px;
left: 2px;
background: var(--muted);
transition: 140ms ease;
}
.switch input:checked + i {
border-color: var(--teal);
background: rgba(84, 227, 194, 0.08);
}
.switch input:checked + i::after {
left: 18px;
background: var(--teal);
}
input[type="range"] {
width: 150px;
height: 3px;
accent-color: var(--teal);
}
.stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: var(--bg);
}
.stage canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
cursor: grab;
touch-action: none;
}
.stage canvas:active { cursor: grabbing; }
.stage::after {
content: "";
position: absolute;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at center, transparent 48%, rgba(3, 9, 8, 0.42) 100%),
linear-gradient(90deg, rgba(255,255,255,0.015) 1px, transparent 1px);
background-size: auto, 64px 64px;
z-index: 3;
}
.view-label {
position: absolute;
z-index: 7;
min-width: 190px;
padding: 12px 14px;
border-top: 1px solid var(--line-bright);
border-bottom: 1px solid rgba(32, 58, 53, 0.6);
background: linear-gradient(180deg, rgba(6, 16, 15, 0.9), rgba(6, 16, 15, 0.48));
pointer-events: none;
}
.view-label .label-top {
display: flex;
align-items: center;
gap: 8px;
color: var(--teal);
font-size: 10px;
letter-spacing: 0.11em;
}
.view-label.case .label-top { color: var(--amber); }
.view-label .label-index {
display: grid;
place-items: center;
width: 22px;
height: 22px;
border: 1px solid currentColor;
font-size: 8px;
}
.view-label p {
margin: 7px 0 0;
color: var(--muted);
font-size: 8px;
line-height: 1.4;
letter-spacing: 0.05em;
}
.legend {
position: absolute;
z-index: 8;
left: 50%;
bottom: 16px;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 16px;
padding: 9px 13px;
border: 1px solid var(--line);
background: rgba(6, 16, 15, 0.88);
pointer-events: none;
white-space: nowrap;
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
color: var(--muted);
font-size: 8px;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.legend-swatch {
width: 14px;
height: 5px;
background: var(--teal);
}
.legend-swatch.rerouted { background: var(--amber); }
.legend-swatch.lost {
background: repeating-linear-gradient(90deg, var(--red) 0 4px, transparent 4px 7px);
}
.help {
position: absolute;
z-index: 8;
right: 15px;
bottom: 17px;
color: var(--muted);
font-size: 8px;
line-height: 1.5;
text-align: right;
pointer-events: none;
}
.tooltip {
position: absolute;
z-index: 30;
display: none;
min-width: 190px;
padding: 10px;
border: 1px solid var(--line-bright);
background: rgba(6, 16, 15, 0.96);
box-shadow: 0 12px 28px rgba(0,0,0,.3);
pointer-events: none;
white-space: pre-line;
font-size: 9px;
line-height: 1.5;
}
.tooltip strong {
display: block;
margin-bottom: 4px;
color: var(--teal);
font-size: 10px;
}
@media (max-width: 860px) {
html, body { overflow: hidden; }
.app-main {
display: flex;
flex-direction: column-reverse;
}
.sidebar {
flex: 1 1 38%;
border-right: 0;
border-top: 1px solid var(--line);
}
.stage {
flex: 0 0 62%;
min-height: 360px;
}
.header {
padding: 0 13px;
}
.brand p,
.meta-chip.optional {
display: none;
}
.legend {
gap: 9px;
bottom: 10px;
}
.help { display: none; }
}
</style>
</head>
<body>
<div class="app">
<header class="header">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>NETWORK IMPACT LAB</h1>
<p>Transport hubs · fragility · resilience</p>
</div>
</div>
<div class="header-meta">
<div class="meta-chip optional"><span id="stationCount">20</span> STATIONS</div>
<div class="meta-chip optional"><span id="requestCount">64</span> O→D REQUESTS</div>
<div class="state-chip" id="networkState">
<span class="state-dot"></span>
<span id="networkStateText">SCENARIO ACTIVE</span>
</div>
</div>
</header>
<main class="app-main">
<aside class="sidebar">
<section class="section">
<div class="eyebrow">01 / Removal target</div>
<div class="target-card" id="targetCard">
<div class="target-top">
<div>
<div class="target-code" id="targetCode">C3 / REMOVED</div>
<h2 class="target-name" id="targetName">Tech Quarter</h2>
</div>
<div class="impact-score">
<strong id="targetScore">0</strong>
<span>IMPACT</span>
</div>
</div>
<div class="target-stats">
<div class="target-stat">
<strong id="targetLoad">0</strong>
<span>Routed load</span>
</div>
<div class="target-stat">
<strong id="targetLost">0</strong>
<span>Stranded</span>
</div>
<div class="target-stat">
<strong id="targetPairLoss">0</strong>
<span>Pair loss</span>
</div>
</div>
<div class="button-row">
<button class="button primary" id="restoreButton">Reinsert station</button>
<button class="button" id="focusButton">Focus target</button>
</div>
</div>
</section>
<section class="section">
<div class="eyebrow">02 / Request outcome</div>
<div class="metric-grid">
<div class="metric">
<div class="metric-label">Reachable demand</div>
<div class="metric-value teal" id="reachableValue">0/0</div>
<div class="metric-sub" id="reachableSub">0% of requests</div>
</div>
<div class="metric">
<div class="metric-label">Unreachable</div>
<div class="metric-value red" id="lostValue">0</div>
<div class="metric-sub">No valid path</div>
</div>
<div class="metric">
<div class="metric-label">Rerouted</div>
<div class="metric-value amber" id="reroutedValue">0</div>
<div class="metric-sub">Valid alternative</div>
</div>
<div class="metric">
<div class="metric-label">Mean detour</div>
<div class="metric-value amber" id="detourValue">0%</div>
<div class="metric-sub">Among reroutes</div>
</div>
</div>
<p class="method-note">
Every removal triggers a fresh weighted shortest-path search.
Reachability, stranded demand, detours and station load are computed
from the request ledger—not from a node’s visual position.
</p>
</section>
<section class="section">
<div class="eyebrow">03 / Computed station fragility</div>
<div class="station-list" id="stationList"></div>
</section>
<section class="section">
<div class="eyebrow">04 / Animation</div>
<div class="control-row">
<span class="control-label">Playback</span>
<button class="button primary" id="playButton" style="flex: 0 0 94px">Pause</button>
</div>
<div class="control-row">
<span class="control-label">Simulation speed</span>
<input id="speedControl" type="range" min="0.25" max="2" step="0.05" value="1" />
</div>
<div class="control-row">
<span class="control-label">Show affected requests only</span>
<label class="switch">
<input id="affectedOnly" type="checkbox" />
<i></i>
</label>
</div>
<div class="button-row">
<button class="button" id="cameraButton">Reset camera</button>
<button class="button" id="restoreAllButton">Restore all</button>
</div>
</section>
</aside>
<section class="stage" id="stage" aria-label="Interactive 3D transit network comparison">
<div class="view-label baseline-label" id="baselineLabel">
<div class="label-top">
<span class="label-index">01</span>
<span>BASELINE / INTACT</span>
</div>
<p id="baselineSubtitle">Identical demand ledger</p>
</div>
<div class="view-label case-label" id="caseLabel">
<div class="label-top">
<span class="label-index">02</span>
<span>REMOVAL CASE</span>
</div>
<p id="caseSubtitle">Live path recomputation</p>
</div>
<div class="legend">
<div class="legend-item"><i class="legend-swatch"></i>Unchanged</div>
<div class="legend-item"><i class="legend-swatch rerouted"></i>Rerouted</div>
<div class="legend-item"><i class="legend-swatch lost"></i>Unreachable</div>
</div>
<div class="help">
DRAG TO ORBIT · SHIFT-DRAG TO PAN · WHEEL TO ZOOM<br />
CLICK A STATION TO REMOVE IT
</div>
<div class="tooltip" id="tooltip"></div>
</section>
</main>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = id => document.getElementById(id);
const stage = $("stage");
const tooltip = $("tooltip");
const COLORS = {
bg: 0x06100f,
floor: 0x10221f,
floorAlt: 0x0d1d1a,
edge: 0x42665e,
edgeDim: 0x263b37,
teal: 0x54e3c2,
tealDark: 0x2d9f89,
amber: 0xffb454,
red: 0xff5575,
white: 0xe4f3ed,
muted: 0x78958a,
blue: 0x6f8dff
};
const rawNodes = [
["A1", "Westhaven", 0, 0, 0.9],
["A2", "North Exchange", 0, 1, 1.3],
["A3", "Museum", 0, 2, 0.7],
["A4", "East Terminal", 0, 3, 1.1],
["A5", "Beacon Park", 0, 4, 0.6],
["B1", "Ironworks", 1, 0, 0.8],
["B2", "Civic Center", 1, 1, 1.4],
["B3", "Central Exchange",1, 2, 1.2],
["B4", "Atelier Quarter", 1, 3, 0.6],
["B5", "South Port", 1, 4, 0.9],
["C1", "Garden West", 2, 0, 0.7],
["C2", "University", 2, 1, 1.3],
["C3", "Tech Quarter", 2, 2, 1.5],
["C4", "Arena District", 2, 3, 1.0],
["C5", "East Junction", 2, 4, 0.8],
["D1", "West Depot", 3, 0, 1.0],
["D2", "Willow Street", 3, 1, 0.8],
["D3", "Mill District", 3, 2, 1.1],
["D4", "Creek Crossing", 3, 3, 0.7],
["D5", "Docklands", 3, 4, 1.2]
];
const nodes = rawNodes.map(([id, name, row, col, demandWeight]) => ({
id,
name,
row,
col,
demandWeight,
x: (col - 2) * 2.45,
z: (row - 1.5) * 2.15
}));
const nodeById = new Map(nodes.map(node => [node.id, node]));
const edges = [];
const edgeKeys = new Set();
function addEdge(a, b, time, capacity) {
const key = [a, b].sort().join("-");
if (edgeKeys.has(key)) return;
edgeKeys.add(key);
edges.push({
id: `E${String(edges.length + 1).padStart(2, "0")}`,
a,
b,
time,
capacity
});
}
// Deliberately non-uniform topology. D2 is a leaf through D1, so removing
// D1 changes actual pair reachability even though node size is not a proxy.
const horizontalRules = [
[0, 1], [1, 2], [2, 3], [3, 4],
[0, 1], [3, 4],
[0, 1], [1, 2], [2, 3], [3, 4],
[0, 1], [2, 3], [3, 4]
];
let horizontalIndex = 0;
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 4; col++) {
const rule = horizontalRules[horizontalIndex++];
const a = rawNodes[row * 5 + col][0];
const b = rawNodes[row * 5 + col + 1][0];
const time = 0.92 + ((row + col) % 3) * 0.09;
const capacity = 680 + ((row * 5 + col) % 4) * 110;
addEdge(a, b, time, capacity);
}
}
for (let col = 0; col < 5; col++) {
for (let row = 0; row < 3; row++) {
// C2–D2 is omitted, making D2 depend on D1.
if (col === 1 && row === 2) continue;
const a = rawNodes[row * 5 + col][0];
const b = rawNodes[(row + 1) * 5 + col][0];
const time = 1.10 + ((row + col) % 2) * 0.12;
const capacity = 720 + ((row + col * 2) % 4) * 100;
addEdge(a, b, time, capacity);
}
}
const adjacency = new Map(nodes.map(node => [node.id, []]));
for (const edge of edges) {
adjacency.get(edge.a).push({ to: edge.b, edge });
adjacency.get(edge.b).push({ to: edge.a, edge });
}
function mulberry32(seed) {
return function() {
let t = seed += 0x6D2B79F5;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const random = mulberry32(41827);
function weightedEndpoint() {
const total = nodes.reduce((sum, node) => sum + node.demandWeight, 0);
let value = random() * total;
for (const node of nodes) {
value -= node.demandWeight;
if (value <= 0) return node.id;
}
return nodes[nodes.length - 1].id;
}
// This exact ledger is reused in both views.
const requests = Array.from({ length: 64 }, (_, index) => {
let origin = weightedEndpoint();
let destination = weightedEndpoint();
while (destination === origin) {
destination = weightedEndpoint();
}
return {
id: `R${String(index + 1).padStart(2, "0")}`,
origin,
destination,
phase: random()
};
});
function shortestPath(origin, destination, removedId = null) {
if (origin === destination) return null;
const distances = new Map();
const previous = new Map();
const previousEdge = new Map();
const visited = new Set();
for (const node of nodes) {
distances.set(node.id, Infinity);
}
distances.set(origin, 0);
while (true) {
let current = null;
let currentDistance = Infinity;
for (const node of nodes) {
const distance = distances.get(node.id);
if (!visited.has(node.id) && distance < currentDistance) {
current = node.id;
currentDistance = distance;
}
}
if (current === null || current === destination) break;
if (current === removedId) break;
visited.add(current);
for (const link of adjacency.get(current)) {
if (link.to === removedId || visited.has(link.to)) continue;
const candidate = currentDistance + link.edge.time;
if (candidate < distances.get(link.to)) {
distances.set(link.to, candidate);
previous.set(link.to, current);
previousEdge.set(link.to, link.edge.id);
}
}
}
if (!previous.has(destination) && origin !== destination) return null;
const path = [destination];
const edgeIds = [];
let cursor = destination;
while (cursor !== origin) {
edgeIds.push(previousEdge.get(cursor));
cursor = previous.get(cursor);
if (cursor === undefined) return null;
path.push(cursor);
}
path.reverse();
edgeIds.reverse();
return {
path,
edgeIds,
cost: distances.get(destination)
};
}
const baselineRoutes = requests.map(request =>
shortestPath(request.origin, request.destination)
);
function computeRoutes(removedId) {
return requests.map((request, index) => {
const baseline = baselineRoutes[index];
if (!removedId) {
return {
request,
baseline,
scenario: baseline,
status: "unchanged",
detour: 1,
lost: false
};
}
const scenario = shortestPath(request.origin, request.destination, removedId);
if (!scenario) {
return {
request,
baseline,
scenario: null,
status: "lost",
detour: Infinity,
lost: true
};
}
const samePath =
baseline &&
baseline.path.length === scenario.path.length &&
baseline.path.every((id, pathIndex) => id === scenario.path[pathIndex]);
return {
request,
baseline,
scenario,
status: samePath ? "unchanged" : "rerouted",
detour: baseline ? scenario.cost / baseline.cost : 1,
lost: false
};
});
}
function countPairReachability(blockedId, removeFromGraph) {
const endpointIds = nodes
.map(node => node.id)
.filter(id => id !== blockedId);
let reachablePairs = 0;
for (const source of endpointIds) {
const visited = new Set([source]);
const queue = [source];
while (queue.length) {
const current = queue.shift();
for (const link of adjacency.get(current)) {
if (removeFromGraph && link.to === blockedId) continue;
if (visited.has(link.to)) continue;
visited.add(link.to);
queue.push(link.to);
}
}
for (const target of endpointIds) {
if (source < target && visited.has(target)) {
reachablePairs++;
}
}
}
return reachablePairs;
}
function evaluateRemoval(removedId) {
const routes = computeRoutes(removedId);
const lost = routes.filter(route => route.lost).length;
const rerouted = routes.filter(route => route.status === "rerouted").length;
const detours = routes
.filter(route => route.status === "rerouted")
.map(route => route.detour);
const averageDetour = detours.length
? detours.reduce((sum, value) => sum + value, 0) / detours.length
: 1;
const baselinePairs = countPairReachability(removedId, false);
const afterPairs = countPairReachability(removedId, true);
const pairLoss = baselinePairs - afterPairs;
let endpointLoad = 0;
let transitLoad = 0;
for (const baseline of baselineRoutes) {
if (!baseline) continue;
if (baseline.path[0] === removedId || baseline.path.at(-1) === removedId) {
endpointLoad++;
}
transitLoad += baseline.path.filter(id => id === removedId).length;
}
const score = Math.round(
lost * 12 +
rerouted * 2 +
averageDetour * 8 +
pairLoss * 5 +
endpointLoad * 1.5 +
transitLoad * 0.15
);
return {
id: removedId,
routes,
lost,
rerouted,
averageDetour,
baselinePairs,
afterPairs,
pairLoss,
endpointLoad,
transitLoad,
score
};
}
const evaluations = new Map(
nodes.map(node => [node.id, evaluateRemoval(node.id)])
);
const sortedEvaluations = [...evaluations.values()].sort((a, b) => b.score - a.score);
const maximumImpact = sortedEvaluations[0].score || 1;
function aggregateUsage(routeEntries) {
const usage = {
through: Object.fromEntries(nodes.map(node => [node.id, 0])),
endpoints: Object.fromEntries(nodes.map(node => [node.id, 0])),
edges: Object.fromEntries(edges.map(edge => [edge.id, 0]))
};
for (const entry of routeEntries) {
const route = entry.route;
if (!route) continue;
for (const id of route.path) usage.through[id]++;
usage.endpoints[route.path[0]]++;
usage.endpoints[route.path.at(-1)]++;
for (const edgeId of route.edgeIds) usage.edges[edgeId]++;
}
return usage;
}
const baselineUsage = aggregateUsage(
requests.map((request, index) => ({ route: baselineRoutes[index] }))
);
const maximumThrough = Math.max(...Object.values(baselineUsage.through), 1);
// -------------------------------------------------------------------------
// Renderer and camera
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.domElement.setAttribute("aria-label", "Voxel transport network comparison");
stage.prepend(renderer.domElement);
const camera = new THREE.OrthographicCamera(-8, 8, 6, -6, 0.1, 100);
const target = new THREE.Vector3(0, 0.25, 0);
const spherical = {
radius: 19,
theta: 0.72,
phi: 0.92
};
function updateCamera() {
const sinPhi = Math.sin(spherical.phi);
camera.position.set(
target.x + spherical.radius * sinPhi * Math.sin(spherical.theta),
target.y + spherical.radius * Math.cos(spherical.phi),
target.z + spherical.radius * sinPhi * Math.cos(spherical.theta)
);
camera.lookAt(target);
camera.updateMatrixWorld();
}
function resetCamera() {
target.set(0, 0.25, 0);
spherical.radius = 19;
spherical.theta = 0.72;
spherical.phi = 0.92;
camera.zoom = 1;
camera.updateProjectionMatrix();
updateCamera();
}
updateCamera();
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const xAxis = new THREE.Vector3(1, 0, 0);
function makeBeam(start, end, width, height, material, y = null) {
const direction = new THREE.Vector3().subVectors(end, start);
const length = direction.length();
const midpoint = new THREE.Vector3()
.addVectors(start, end)
.multiplyScalar(0.5);
if (y !== null) midpoint.y = y;
const mesh = new THREE.Mesh(unitBox, material);
mesh.position.copy(midpoint);
mesh.scale.set(length, height, width);
direction.normalize();
mesh.quaternion.setFromUnitVectors(xAxis, direction);
return mesh;
}
function makeLabel(code) {
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 64;
const context = canvas.getContext("2d");
context.clearRect(0, 0, 128, 64);
context.fillStyle = "rgba(6, 16, 15, 0.86)";
context.fillRect(6, 11, 116, 42);
context.strokeStyle = "rgba(84, 227, 194, 0.55)";
context.lineWidth = 2;
context.strokeRect(6, 11, 116, 42);
context.fillStyle = "#dff8ef";
context.font = "bold 25px monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(code, 64, 32);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(0.68, 0.34, 1);
sprite.renderOrder = 20;
return sprite;
}
function seededFloorRandom(seed) {
let value = seed;
return () => {
value = (value * 1664525 + 1013904223) >>> 0;
return value / 4294967296;
};
}
function createGraphScene(isScenario) {
const scene = new THREE.Scene();
scene.background = new THREE.Color(COLORS.bg);
scene.fog = new THREE.FogExp2(COLORS.bg, 0.026);
scene.add(new THREE.HemisphereLight(0xb9eadc, 0x0a1211, 1.55));
const keyLight = new THREE.DirectionalLight(0xc8fff0, 2.7);
keyLight.position.set(8, 13, 7);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x557bff, 1.15);
rimLight.position.set(-9, 7, -8);
scene.add(rimLight);
const floorRandom = seededFloorRandom(isScenario ? 912 : 817);
const floorCount = 23 * 15;
const floorMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.96,
metalness: 0.03
});
const floor = new THREE.InstancedMesh(unitBox, floorMaterial, floorCount);
const transform = new THREE.Object3D();
const color = new THREE.Color();
let floorIndex = 0;
for (let row = 0; row < 15; row++) {
for (let col = 0; col < 23; col++) {
const height = 0.06 + floorRandom() * 0.08;
transform.position.set(
(col - 11) * 1.05,
-0.07 + height * 0.5,
(row - 7) * 1.05
);
transform.scale.set(0.98, height, 0.98);
transform.updateMatrix();
floor.setMatrixAt(floorIndex, transform.matrix);
color.setHex(floorRandom() > 0.84 ? COLORS.floorAlt : COLORS.floor);
color.multiplyScalar(0.76 + floorRandom() * 0.28);
floor.setColorAt(floorIndex, color);
floorIndex++;
}
}
floor.instanceMatrix.needsUpdate = true;
if (floor.instanceColor) floor.instanceColor.needsUpdate = true;
scene.add(floor);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0x25433d,
roughness: 0.72,
metalness: 0.22
});
const baseMaterial = new THREE.MeshStandardMaterial({
color: 0x152b27,
roughness: 0.86,
metalness: 0.12
});
const nodeVisuals = new Map();
const edgeVisuals = new Map();
const pickables = [];
for (const edge of edges) {
const edgeMaterial = new THREE.MeshStandardMaterial({
color: COLORS.edge,
emissive: 0x0c2722,
emissiveIntensity: 0.45,
roughness: 0.72,
metalness: 0.18
});
const a = nodeById.get(edge.a);
const b = nodeById.get(edge.b);
const start = new THREE.Vector3(a.x, 0.12, a.z);
const end = new THREE.Vector3(b.x, 0.12, b.z);
const beam = makeBeam(start, end, 0.13, 0.085, edgeMaterial, 0.15);
scene.add(beam);
const marker = new THREE.Mesh(
unitBox,
new THREE.MeshBasicMaterial({ color: 0x5f8b80 })
);
marker.scale.set(0.12, 0.07, 0.18);
marker.position.set((a.x + b.x) / 2, 0.22, (a.z + b.z) / 2);
marker.rotation.y = Math.atan2(b.z - a.z, b.x - a.x);
scene.add(marker);
edgeVisuals.set(edge.id, { beam, marker, material: edgeMaterial });
}
for (const node of nodes) {
const group = new THREE.Group();
group.position.set(node.x, 0, node.z);
scene.add(group);
const base = new THREE.Mesh(unitBox, baseMaterial);
base.scale.set(0.74, 0.13, 0.74);
base.position.y = 0.085;
group.add(base);
const tower = new THREE.Group();
group.add(tower);
const blocks = [];
for (let i = 0; i < 3; i++) {
const block = new THREE.Mesh(unitBox, bodyMaterial);
block.userData.nodeId = node.id;
tower.add(block);
blocks.push(block);
pickables.push(block);
}
const capMaterial = new THREE.MeshStandardMaterial({
color: COLORS.teal,
emissive: COLORS.tealDark,
emissiveIntensity: 1.0,
roughness: 0.42,
metalness: 0.25
});
const cap = new THREE.Mesh(unitBox, capMaterial);
cap.scale.set(0.34, 0.11, 0.34);
cap.userData.nodeId = node.id;
tower.add(cap);
pickables.push(cap);
const label = makeLabel(node.id);
group.add(label);
const ringMaterial = new THREE.MeshBasicMaterial({
color: COLORS.white,
transparent: true,
opacity: 0.85
});
const ring = new THREE.Group();
for (let i = 0; i < 4; i++) {
const bar = new THREE.Mesh(unitBox, ringMaterial);
const angle = i * Math.PI / 2;
bar.position.set(Math.cos(angle) * 0.51, 0.16, Math.sin(angle) * 0.51);
bar.scale.set(0.28, 0.035, 0.055);
bar.rotation.y = -angle;
ring.add(bar);
}
group.add(ring);
const ghostMaterial = new THREE.LineBasicMaterial({
color: COLORS.red,
transparent: true,
opacity: 0.9
});
const ghost = new THREE.LineSegments(
new THREE.EdgesGeometry(new THREE.BoxGeometry(0.72, 0.82, 0.72)),
ghostMaterial
);
ghost.position.y = 0.53;
ghost.visible = false;
group.add(ghost);
const cross = new THREE.Group();
for (let i = 0; i < 2; i++) {
const bar = new THREE.Mesh(
unitBox,
new THREE.MeshBasicMaterial({ color: COLORS.red })
);
bar.scale.set(0.65, 0.075, 0.075);
bar.rotation.z = i === 0 ? Math.PI / 4 : -Math.PI / 4;
cross.add(bar);
}
cross.position.y = 0.52;
cross.visible = false;
group.add(cross);
nodeVisuals.set(node.id, {
group,
tower,
blocks,
cap,
label,
ring,
ghost,
cross
});
}
const routeRoot = new THREE.Group();
scene.add(routeRoot);
return {
scene,
isScenario,
nodeVisuals,
edgeVisuals,
pickables,
routeRoot
};
}
const baselineState = createGraphScene(false);
const scenarioState = createGraphScene(true);
const routeMaterials = {
baseline: new THREE.MeshBasicMaterial({
color: COLORS.teal,
transparent: true,
opacity: 0.23,
depthWrite: false
}),
unchanged: new THREE.MeshBasicMaterial({
color: COLORS.teal,
transparent: true,
opacity: 0.23,
depthWrite: false
}),
rerouted: new THREE.MeshBasicMaterial({
color: COLORS.amber,
transparent: true,
opacity: 0.36,
depthWrite: false
}),
lost: new THREE.MeshBasicMaterial({
color: COLORS.red,
transparent: true,
opacity: 0.42,
depthWrite: false
})
};
const vehicleMaterials = {
baseline: new THREE.MeshStandardMaterial({
color: COLORS.teal,
emissive: COLORS.tealDark,
emissiveIntensity: 1.4,
roughness: 0.35
}),
unchanged: new THREE.MeshStandardMaterial({
color: COLORS.teal,
emissive: COLORS.tealDark,
emissiveIntensity: 1.4,
roughness: 0.35
}),
rerouted: new THREE.MeshStandardMaterial({
color: COLORS.amber,
emissive: 0xa66319,
emissiveIntensity: 1.5,
roughness: 0.35
}),
lost: new THREE.MeshStandardMaterial({
color: COLORS.red,
emissive: 0xa71f3d,
emissiveIntensity: 1.4,
roughness: 0.35
})
};
function pathPoints(path) {
return path.map(id => {
const node = nodeById.get(id);
return new THREE.Vector3(node.x, 0.39, node.z);
});
}
function preparePath(points) {
const cumulative = [0];
for (let i = 1; i < points.length; i++) {
cumulative.push(cumulative[i - 1] + points[i].distanceTo(points[i - 1]));
}
return {
points,
cumulative,
length: cumulative.at(-1)
};
}
function samplePath(prepared, fraction) {
const distance = prepared.length * Math.max(0, Math.min(1, fraction));
for (let i = 1; i < prepared.cumulative.length; i++) {
if (distance <= prepared.cumulative[i]) {
const segmentLength = prepared.cumulative[i] - prepared.cumulative[i - 1];
const local = segmentLength
? (distance - prepared.cumulative[i - 1]) / segmentLength
: 0;
return new THREE.Vector3().lerpVectors(
prepared.points[i - 1],
prepared.points[i],
local
);
}
}
return prepared.points.at(-1).clone();
}
function makeVehicle(material) {
const group = new THREE.Group();
const body = new THREE.Mesh(unitBox, material);
body.scale.set(0.18, 0.14, 0.18);
group.add(body);
const cap = new THREE.Mesh(
unitBox,
new THREE.MeshBasicMaterial({ color: COLORS.white })
);
cap.scale.set(0.095, 0.055, 0.095);
cap.position.y = 0.09;
group.add(cap);
return group;
}
function makeRouteRecord(state, request, route, status) {
const group = new THREE.Group();
state.routeRoot.add(group);
if (!route) {
const origin = nodeById.get(request.origin);
const destination = nodeById.get(request.destination);
const start = new THREE.Vector3(origin.x, 0.39, origin.z);
const end = new THREE.Vector3(destination.x, 0.39, destination.z);
const direction = new THREE.Vector3().subVectors(end, start);
for (let i = 0; i < 9; i++) {
const point = new THREE.Vector3().lerpVectors(start, end, (i + 0.5) / 9);
const dash = makeBeam(
point.clone().addScaledVector(direction.clone().normalize(), -0.14),
point.clone().addScaledVector(direction.clone().normalize(), 0.14),
0.07,
0.035,
routeMaterials.lost,
0.39
);
group.add(dash);
}
const marker = new THREE.Mesh(unitBox, vehicleMaterials.lost);
marker.scale.set(0.25, 0.25, 0.25);
marker.position.copy(end);
group.add(marker);
return {
group,
vehicle: null,
marker,
prepared: null,
status,
request
};
}
const points = pathPoints(route.path);
for (let i = 1; i < points.length; i++) {
const beam = makeBeam(
points[i - 1],
points[i],
status === "baseline" ? 0.065 : 0.075,
0.035,
routeMaterials[status],
0.39
);
group.add(beam);
}
const vehicle = makeVehicle(vehicleMaterials[status]);
vehicle.position.copy(points[0]);
group.add(vehicle);
return {
group,
vehicle,
marker: null,
prepared: preparePath(points),
status,
request
};
}
function updateGraphVisuals(state, usage, removedId, selectedId) {
for (const node of nodes) {
const visual = state.nodeVisuals.get(node.id);
const through = usage.through[node.id];
const normalized = Math.sqrt(through / maximumThrough);
const totalHeight = 0.48 + normalized * 1.55;
const segmentHeight = totalHeight / 3;
visual.tower.visible = !(state.isScenario && node.id === removedId);
visual.blocks.forEach((block, index) => {
const width = 0.50 - index * 0.075;
const depth = 0.48 - index * 0.065;
const y = 0.15 + index * segmentHeight + segmentHeight / 2;
const offset = (index - 1) * 0.025;
block.scale.set(width, segmentHeight, depth);
block.position.set(offset, y, -offset * 0.55);
});
const topY = 0.15 + totalHeight + 0.055;
visual.cap.position.set(0, topY, 0);
visual.cap.scale.set(0.35 + normalized * 0.12, 0.11, 0.35 + normalized * 0.12);
visual.label.position.set(0, topY + 0.35, 0);
const selected = node.id === selectedId;
const removed = state.isScenario && node.id === removedId;
visual.ring.visible = selected && !removed;
visual.ghost.visible = removed;
visual.cross.visible = removed;
visual.cap.material.color.setHex(
selected ? COLORS.white : removed ? COLORS.red : COLORS.teal
);
visual.cap.material.emissive.setHex(
selected ? COLORS.blue : removed ? COLORS.red : COLORS.tealDark
);
visual.label.material.color.setHex(removed ? COLORS.red : COLORS.white);
visual.label.material.opacity = removed ? 0.9 : 0.68;
}
for (const edge of edges) {
const visual = state.edgeVisuals.get(edge.id);
const touchesRemoved =
state.isScenario &&
removedId &&
(edge.a === removedId || edge.b === removedId);
visual.material.color.setHex(touchesRemoved ? COLORS.red : COLORS.edge);
visual.material.emissive.setHex(touchesRemoved ? 0x541222 : 0x0c2722);
visual.material.emissiveIntensity = touchesRemoved ? 0.95 : 0.45;
visual.material.opacity = touchesRemoved ? 0.62 : 1;
visual.material.transparent = touchesRemoved;
visual.marker.material.color.setHex(
touchesRemoved ? COLORS.red : COLORS.tealDark
);
}
}
let removedId = sortedEvaluations[0].id;
let currentRoutes = computeRoutes(removedId);
let scenarioUsage = aggregateUsage(
currentRoutes.map(entry => ({ route: entry.scenario }))
);
updateGraphVisuals(
baselineState,
baselineUsage,
null,
removedId
);
updateGraphVisuals(
scenarioState,
scenarioUsage,
removedId,
removedId
);
const baselineRouteRecords = requests.map((request, index) =>
makeRouteRecord(
baselineState,
request,
baselineRoutes[index],
"baseline"
)
);
let scenarioRouteRecords = [];
function rebuildScenarioRoutes() {
scenarioState.routeRoot.clear();
scenarioRouteRecords = currentRoutes.map(entry =>
makeRouteRecord(
scenarioState,
entry.request,
entry.scenario,
entry.status
)
);
}
rebuildScenarioRoutes();
function updateBaselineVehicleColors() {
baselineRouteRecords.forEach((record, index) => {
const status = currentRoutes[index].status;
record.vehicle.children[0].material = vehicleMaterials[status];
});
}
updateBaselineVehicleColors();
// -------------------------------------------------------------------------
// Interface
// -------------------------------------------------------------------------
function buildStationList() {
$("stationList").innerHTML = "";
for (const evaluation of sortedEvaluations) {
const node = nodeById.get(evaluation.id);
const row = document.createElement("button");
row.className = "station-row";
row.dataset.stationId = node.id;
row.innerHTML = `
<span class="station-id">${node.id}</span>
<span class="station-name">${node.name}</span>
<span class="station-impact">
<i style="--impact:${Math.max(4, evaluation.score / maximumImpact * 100).toFixed(1)}%"></i>
<span>${evaluation.score}</span>
</span>
`;
$("stationList").appendChild(row);
}
}
function updateStationList() {
document.querySelectorAll(".station-row").forEach(row => {
row.classList.toggle("active", row.dataset.stationId === removedId);
});
}
function updateMetrics() {
const lost = currentRoutes.filter(entry => entry.lost).length;
const reachable = currentRoutes.length - lost;
const rerouted = currentRoutes.filter(entry => entry.status === "rerouted").length;
const detours = currentRoutes
.filter(entry => entry.status === "rerouted")
.map(entry => Math.max(0, (entry.detour - 1) * 100));
const averageDetour = detours.length
? detours.reduce((sum, value) => sum + value, 0) / detours.length
: 0;
const evaluation = removedId ? evaluations.get(removedId) : null;
const basePairs = evaluation ? evaluation.baselinePairs : countPairReachability(null, false);
const afterPairs = evaluation ? evaluation.afterPairs : basePairs;
$("reachableValue").textContent = `${reachable}/${requests.length}`;
$("reachableSub").textContent = `${Math.round(reachable / requests.length * 100)}% of requests`;
$("lostValue").textContent = lost;
$("reroutedValue").textContent = rerouted;
$("detourValue").textContent = `${Math.round(averageDetour)}%`;
const targetCard = $("targetCard");
targetCard.classList.toggle("intact", !removedId);
if (removedId) {
const node = nodeById.get(removedId);
$("targetCode").textContent = `${node.id} / REMOVED`;
$("targetName").textContent = node.name;
$("targetScore").textContent = evaluation.score;
$("targetLoad").textContent = baselineUsage.through[removedId];
$("targetLost").textContent = evaluation.lost;
$("targetPairLoss").textContent = evaluation.pairLoss;
$("restoreButton").disabled = false;
$("networkState").classList.remove("intact");
$("networkStateText").textContent = "SCENARIO ACTIVE";
$("caseSubtitle").textContent = `${node.id} removed · live recomputation`;
} else {
$("targetCode").textContent = "NETWORK / INTACT";
$("targetName").textContent = "No station removed";
$("targetScore").textContent = "0";
$("targetLoad").textContent = "—";
$("targetLost").textContent = "0";
$("targetPairLoss").textContent = "0";
$("restoreButton").disabled = true;
$("networkState").classList.add("intact");
$("networkStateText").textContent = "BASELINE ONLY";
$("caseSubtitle").textContent = "All stations present · no disruption";
}
$("baselineSubtitle").textContent =
`${requests.length} identical O→D requests · ${afterPairs}/${basePairs} pairs reachable`;
updateStationList();
}
function setRemoved(nextRemovedId) {
removedId = nextRemovedId;
currentRoutes = computeRoutes(removedId);
scenarioUsage = aggregateUsage(
currentRoutes.map(entry => ({ route: entry.scenario }))
);
updateGraphVisuals(
baselineState,
baselineUsage,
null,
removedId
);
updateGraphVisuals(
scenarioState,
scenarioUsage,
removedId,
removedId
);
rebuildScenarioRoutes();
updateBaselineVehicleColors();
updateMetrics();
}
buildStationList();
updateMetrics();
$("stationList").addEventListener("click", event => {
const row = event.target.closest(".station-row");
if (!row) return;
const id = row.dataset.stationId;
setRemoved(id === removedId ? null : id);
});
$("restoreButton").addEventListener("click", () => setRemoved(null));
$("restoreAllButton").addEventListener("click", () => setRemoved(null));
let playing = true;
let simulationTime = 0;
let playbackSpeed = 1;
$("playButton").addEventListener("click", () => {
playing = !playing;
$("playButton").textContent = playing ? "Pause" : "Play";
});
$("speedControl").addEventListener("input", event => {
playbackSpeed = Number(event.target.value);
});
$("focusButton").addEventListener("click", () => {
if (!removedId) return;
target.set(
nodeById.get(removedId).x,
0.25,
nodeById.get(removedId).z
);
camera.zoom = 1.7;
camera.updateProjectionMatrix();
updateCamera();
});
$("cameraButton").addEventListener("click", resetCamera);
// -------------------------------------------------------------------------
// Direct camera controls: orbit, pan, zoom and picking.
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let dragging = false;
let dragMoved = false;
let pointerButton = 0;
let lastPointerX = 0;
let lastPointerY = 0;
function getViewports() {
const width = stage.clientWidth;
const height = stage.clientHeight;
if (width < 700) {
const topHeight = Math.floor(height / 2);
return [
{ x: 0, y: height - topHeight, w: width, h: topHeight, state: baselineState },
{ x: 0, y: 0, w: width, h: height - topHeight, state: scenarioState }
];
}
const leftWidth = Math.floor(width / 2);
return [
{ x: 0, y: 0, w: leftWidth, h: height, state: baselineState },
{ x: leftWidth, y: 0, w: width - leftWidth, h: height, state: scenarioState }
];
}
function positionViewLabels(viewports) {
const height = stage.clientHeight;
const baseline = viewports[0];
const scenario = viewports[1];
$("baselineLabel").style.left = `${baseline.x}px`;
$("baselineLabel").style.top = `${height - baseline.y - baseline.h}px`;
$("baselineLabel").style.width = `${baseline.w}px`;
$("caseLabel").style.left = `${scenario.x}px`;
$("caseLabel").style.top = `${height - scenario.y - scenario.h}px`;
$("caseLabel").style.width = `${scenario.w}px`;
}
function updateProjection(viewports) {
const viewport = viewports[0];
const aspect = viewport.w / viewport.h;
const halfHeight = Math.max(5.6, 6.65 / aspect);
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.updateProjectionMatrix();
}
function resize() {
const width = stage.clientWidth;
const height = stage.clientHeight;
renderer.setSize(width, height, false);
const viewports = getViewports();
updateProjection(viewports);
positionViewLabels(viewports);
}
new ResizeObserver(resize).observe(stage);
resize();
function pickAt(clientX, clientY) {
const rect = stage.getBoundingClientRect();
const localX = clientX - rect.left;
const localY = clientY - rect.top;
const viewports = getViewports();
const viewport = viewports.find(view =>
localX >= view.x &&
localX <= view.x + view.w &&
localY >= rect.height - view.y - view.h &&
localY <= rect.height - view.y
);
if (!viewport) return null;
const top = rect.height - viewport.y - viewport.h;
const x = localX - viewport.x;
const y = localY - top;
pointer.x = (x / viewport.w) * 2 - 1;
pointer.y = -(y / viewport.h) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(
viewport.state.pickables,
false
);
if (!intersections.length) return null;
const id = intersections[0].object.userData.nodeId;
return id ? nodeById.get(id) : null;
}
function showTooltip(node, clientX, clientY) {
if (!node) {
tooltip.style.display = "none";
renderer.domElement.style.cursor = dragging ? "grabbing" : "grab";
return;
}
const evaluation = evaluations.get(node.id);
const load = baselineUsage.through[node.id];
tooltip.innerHTML =
`<strong>${node.id} · ${node.name}</strong>` +
`Baseline routed load: ${load} requests\n` +
`Removal impact score: ${evaluation.score}\n` +
`Click to remove from scenario`;
tooltip.style.display = "block";
const rect = stage.getBoundingClientRect();
const tooltipWidth = 210;
const tooltipHeight = 95;
let x = clientX - rect.left + 14;
let y = clientY - rect.top + 14;
if (x + tooltipWidth > rect.width - 8) x -= tooltipWidth + 24;
if (y + tooltipHeight > rect.height - 8) y -= tooltipHeight + 24;
tooltip.style.left = `${Math.max(8, x)}px`;
tooltip.style.top = `${Math.max(8, y)}px`;
renderer.domElement.style.cursor = "pointer";
}
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
dragMoved = false;
pointerButton = event.button;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
tooltip.style.display = "none";
});
renderer.domElement.addEventListener("pointermove", event => {
if (dragging) {
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
if (Math.abs(dx) + Math.abs(dy) > 2) dragMoved = true;
const panning = event.shiftKey || pointerButton === 2;
if (panning) {
const right = new THREE.Vector3();
camera.matrixWorld.extractBasis(right, new THREE.Vector3(), new THREE.Vector3());
target.addScaledVector(right, -dx * 0.012);
target.z += dy * 0.012;
} else {
spherical.theta -= dx * 0.006;
spherical.phi = THREE.MathUtils.clamp(
spherical.phi - dy * 0.005,
0.30,
1.38
);
}
lastPointerX = event.clientX;
lastPointerY = event.clientY;
updateCamera();
return;
}
showTooltip(pickAt(event.clientX, event.clientY), event.clientX, event.clientY);
});
renderer.domElement.addEventListener("pointerup", event => {
dragging = false;
if (!dragMoved) {
const node = pickAt(event.clientX, event.clientY);
if (node) setRemoved(node.id === removedId ? null : node.id);
}
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener("pointerleave", () => {
if (!dragging) tooltip.style.display = "none";
});
renderer.domElement.addEventListener("contextmenu", event => {
event.preventDefault();
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
const factor = Math.exp(-event.deltaY * 0.0012);
camera.zoom = THREE.MathUtils.clamp(camera.zoom * factor, 0.65, 2.5);
camera.updateProjectionMatrix();
}, { passive: false });
window.addEventListener("keydown", event => {
if (event.code === "Space" && event.target === document.body) {
event.preventDefault();
$("playButton").click();
}
if (event.key.toLowerCase() === "r" && event.target === document.body) {
setRemoved(null);
}
});
// -------------------------------------------------------------------------
// Synchronized request animation
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
const delta = Math.min(clock.getDelta(), 0.05);
if (playing) {
simulationTime += delta * playbackSpeed;
}
const affectedOnly = $("affectedOnly").checked;
function animateRecords(records) {
for (const record of records) {
const affected = currentRoutes[record.request.index ?? requests.indexOf(record.request)].status !== "unchanged";
record.group.visible = !affectedOnly || affected;
if (!record.group.visible) continue;
const requestIndex = requests.indexOf(record.request);
const phase = (simulationTime * 0.065 + requests[requestIndex].phase) % 1;
if (record.vehicle && record.prepared) {
record.vehicle.position.copy(samplePath(record.prepared, phase));
}
if (record.marker) {
const pulse = 1 + Math.sin(simulationTime * 7 + requestIndex) * 0.22;
record.marker.scale.set(0.25 * pulse, 0.25 * pulse, 0.25 * pulse);
record.marker.rotation.y = simulationTime * 1.5;
}
}
}
animateRecords(baselineRouteRecords);
animateRecords(scenarioRouteRecords);
const viewports = getViewports();
renderer.setScissorTest(true);
for (const viewport of viewports) {
renderer.setViewport(viewport.x, viewport.y, viewport.w, viewport.h);
renderer.setScissor(viewport.x, viewport.y, viewport.w, viewport.h);
renderer.render(viewport.state.scene, camera);
}
renderer.setScissorTest(false);
}
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```