Prompt specification
Build or customize the Three.js 3D scene "Simultaneous Versus Staggered Closures" 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: Simultaneous Versus Staggered Closures
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/simultaneous-versus-staggered-closures-x2112
Scene Description Prompt:
Compare two maintenance schedules on the same toy network with identical work durations. Measure temporary disconnections and travel increases under explicit simplified assumptions. Build this with Three.js from cdnjs as a low-poly scene in one self-contained HTML file.
Working Three.js Starter (simultaneous-versus-staggered-closures-x2112):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Maintenance Planner — Network Impact Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #081117;
--panel: #101c25;
--panel-2: #15242e;
--line: #263945;
--text: #e9f2f4;
--muted: #91a6b1;
--orange: #ff8a3d;
--orange-soft: #472d20;
--cyan: #28d7e5;
--pink: #ed5c9d;
--green: #67d69a;
--red: #ef476f;
--yellow: #e9c46a;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
font-variant-numeric: tabular-nums;
}
body {
overflow: hidden;
}
button,
input,
select {
font: inherit;
}
button,
select {
color: var(--text);
}
.app {
height: 100dvh;
display: grid;
grid-template-rows: 64px minmax(0, 1fr) 196px;
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 18px;
background: #0b151d;
border-bottom: 1px solid var(--line);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-mark {
width: 36px;
height: 36px;
position: relative;
flex: 0 0 auto;
border: 1px solid #35505f;
border-radius: 10px;
background: #12242e;
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--orange);
box-shadow: 14px 8px 0 var(--cyan), 3px 16px 0 var(--yellow);
}
.brand-mark::before {
left: 7px;
top: 7px;
}
.brand-mark::after {
display: none;
}
.brand h1 {
margin: 0;
font-size: 16px;
line-height: 1.2;
letter-spacing: 0.01em;
}
.brand p {
margin: 3px 0 0;
color: var(--muted);
font-size: 11px;
}
.top-meta {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
justify-content: flex-end;
}
.badge {
padding: 6px 9px;
border: 1px solid var(--line);
border-radius: 999px;
background: #111f28;
color: #b8c8d0;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.badge.accent {
color: #ffd0b4;
border-color: #68402d;
background: #2a1c18;
}
.icon-button {
height: 34px;
padding: 0 12px;
border: 1px solid var(--line);
border-radius: 9px;
background: #14232c;
cursor: pointer;
}
.icon-button:hover {
border-color: #486171;
background: #1a2d38;
}
.workspace {
min-height: 0;
display: grid;
grid-template-columns: 282px minmax(360px, 1fr) 324px;
gap: 10px;
padding: 10px;
}
.panel {
min-height: 0;
overflow: auto;
border: 1px solid var(--line);
border-radius: 14px;
background: var(--panel);
box-shadow: 0 12px 35px #0003;
scrollbar-width: thin;
scrollbar-color: #304652 transparent;
}
.panel-section {
padding: 15px;
border-bottom: 1px solid var(--line);
}
.panel-section:last-child {
border-bottom: 0;
}
.eyebrow {
margin: 0 0 8px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
h2,
h3 {
margin: 0;
}
h2 {
font-size: 16px;
}
h3 {
font-size: 12px;
}
.subtle {
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.schedule-list {
display: grid;
gap: 9px;
margin-top: 13px;
}
.schedule-card {
width: 100%;
padding: 12px;
text-align: left;
border: 1px solid var(--line);
border-radius: 11px;
background: #0e1921;
cursor: pointer;
transition: border-color 150ms, background 150ms, transform 150ms;
}
.schedule-card:hover {
border-color: #46606f;
transform: translateY(-1px);
}
.schedule-card.active {
border-color: var(--orange);
background:
linear-gradient(135deg, #2b1c17 0%, #111e26 70%);
box-shadow: inset 3px 0 0 var(--orange);
}
.schedule-card header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.schedule-name {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
font-weight: 800;
}
.schedule-letter {
display: grid;
width: 24px;
height: 24px;
place-items: center;
border-radius: 7px;
background: #22343e;
color: #c9d6dc;
font-size: 11px;
}
.schedule-card.active .schedule-letter {
background: var(--orange);
color: #28170f;
}
.schedule-card p {
margin: 7px 0 9px 32px;
color: var(--muted);
font-size: 10px;
line-height: 1.4;
}
.mini-stat {
margin-left: 32px;
color: #c9d6dc;
font-size: 10px;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 12px;
}
.metric-card {
min-width: 0;
padding: 10px;
border: 1px solid #243844;
border-radius: 9px;
background: #0c171f;
}
.metric-card span {
display: block;
color: var(--muted);
font-size: 9px;
line-height: 1.25;
text-transform: uppercase;
letter-spacing: 0.055em;
}
.metric-card strong {
display: block;
margin-top: 5px;
overflow: hidden;
color: #f3f8fa;
font-size: 15px;
line-height: 1.15;
text-overflow: ellipsis;
white-space: nowrap;
}
details {
border: 1px solid #263a46;
border-radius: 9px;
background: #0d1921;
}
summary {
padding: 10px;
cursor: pointer;
color: #d6e1e5;
font-size: 11px;
font-weight: 700;
}
.details-body {
padding: 0 10px 10px;
}
.details-body ol {
margin: 0;
padding-left: 17px;
}
.details-body li {
margin: 0 0 7px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.route {
margin-top: 10px;
color: #c9d6dc;
font-size: 10px;
line-height: 1.65;
}
.route b {
color: var(--orange);
}
table {
width: 100%;
border-collapse: collapse;
}
.task-table {
margin-top: 10px;
}
.task-table th,
.task-table td {
padding: 7px 4px;
border-bottom: 1px solid #20313b;
text-align: left;
font-size: 10px;
}
.task-table th {
color: var(--muted);
font-weight: 700;
}
.task-table td:last-child,
.task-table th:last-child {
text-align: right;
}
.task-id {
color: var(--yellow);
font-weight: 800;
}
.stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 14px;
background: #dbe7da;
box-shadow: 0 12px 35px #0004;
}
.stage canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.stage-hud {
position: absolute;
z-index: 4;
top: 12px;
left: 12px;
right: 12px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
pointer-events: none;
}
.hud-card {
padding: 9px 11px;
border: 1px solid #ffffff35;
border-radius: 10px;
background: #10202adf;
color: #eaf2f4;
box-shadow: 0 5px 18px #0002;
backdrop-filter: blur(8px);
}
.hud-card strong {
display: block;
font-size: 12px;
}
.hud-card span {
display: block;
margin-top: 3px;
color: #afc2ca;
font-size: 9px;
}
.stage-legend {
position: absolute;
z-index: 4;
right: 12px;
bottom: 12px;
display: flex;
gap: 12px;
padding: 8px 10px;
border: 1px solid #ffffff30;
border-radius: 9px;
background: #10202adf;
color: #d7e2e5;
font-size: 9px;
pointer-events: none;
}
.legend-item {
display: flex;
align-items: center;
gap: 5px;
}
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #6b7e87;
}
.dot.open {
background: var(--yellow);
}
.dot.active {
background: var(--orange);
}
.dot.offline {
background: var(--red);
}
.label-layer {
position: absolute;
z-index: 3;
inset: 0;
overflow: hidden;
pointer-events: none;
}
.map-label {
position: absolute;
left: 0;
top: 0;
white-space: nowrap;
will-change: transform;
}
.node-label {
padding: 3px 6px;
border: 1px solid #ffffff35;
border-radius: 6px;
background: #10202acb;
color: #f2f7f8;
font-size: 9px;
font-weight: 800;
box-shadow: 0 3px 10px #0002;
}
.task-label {
padding: 2px 5px;
border: 1px solid #ffffff30;
border-radius: 5px;
background: #172832cc;
color: #f4d9b8;
font-size: 8px;
font-weight: 800;
transition: opacity 120ms;
}
.crew-label {
padding: 2px 5px;
border-radius: 5px;
color: #071218;
font-size: 8px;
font-weight: 900;
box-shadow: 0 2px 8px #0003;
}
.compare-panel {
padding: 0;
}
.compare-panel .panel-section {
padding: 14px;
}
.comparison {
margin-top: 12px;
font-size: 10px;
}
.comparison th,
.comparison td {
padding: 9px 5px;
border-bottom: 1px solid #243641;
text-align: right;
vertical-align: middle;
}
.comparison th:first-child,
.comparison td:first-child {
text-align: left;
}
.comparison thead th {
color: var(--muted);
font-size: 9px;
font-weight: 800;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.comparison tbody td:first-child {
color: #cbd7dc;
}
.comparison .a-value {
color: #cbd7dc;
font-weight: 700;
}
.comparison .b-value {
color: #fff;
font-weight: 800;
}
.diff {
display: inline-block;
min-width: 49px;
padding: 3px 5px;
border-radius: 5px;
text-align: center;
font-weight: 800;
}
.diff.good {
background: #163526;
color: #80e0a7;
}
.diff.bad {
background: #3b2028;
color: #ff9ab4;
}
.diff.neutral {
background: #1c2b34;
color: #aabac2;
}
.interpretation {
margin-top: 13px;
padding: 12px;
border-left: 3px solid var(--orange);
border-radius: 0 9px 9px 0;
background: #17232b;
color: #cbd7dc;
font-size: 10px;
line-height: 1.55;
}
.timeline-panel {
min-height: 0;
margin: 0 10px 10px;
padding: 11px 14px 10px;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 14px;
background: var(--panel);
box-shadow: 0 12px 35px #0003;
}
.transport {
display: grid;
grid-template-columns: 40px 92px minmax(160px, 1fr) 90px;
align-items: center;
gap: 10px;
margin-bottom: 10px;
}
.play-button {
width: 40px;
height: 36px;
padding: 0;
border: 0;
border-radius: 9px;
background: var(--orange);
color: #25150e;
font-size: 15px;
font-weight: 900;
cursor: pointer;
}
.clock {
color: #f2f7f8;
font-size: 15px;
font-weight: 800;
}
.clock small {
display: block;
margin-top: 1px;
color: var(--muted);
font-size: 8px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
}
input[type="range"] {
width: 100%;
accent-color: var(--orange);
cursor: pointer;
}
.speed-select {
height: 34px;
padding: 0 8px;
border: 1px solid var(--line);
border-radius: 8px;
background: #0d1921;
font-size: 10px;
}
.timeline-body {
min-width: 0;
}
.timeline-row {
display: grid;
grid-template-columns: 76px minmax(0, 1fr);
align-items: center;
gap: 9px;
margin-bottom: 7px;
}
.timeline-row-label {
display: flex;
align-items: center;
gap: 6px;
color: #c8d5da;
font-size: 10px;
font-weight: 700;
}
.team-dot {
width: 8px;
height: 8px;
border-radius: 50%;
}
.track {
position: relative;
height: 27px;
overflow: hidden;
border: 1px solid #263a45;
border-radius: 7px;
background:
linear-gradient(90deg, #ffffff08 1px, transparent 1px) 0 0 / 25% 100%,
#0a151c;
cursor: crosshair;
}
.timeline-bar {
position: absolute;
top: 3px;
bottom: 3px;
overflow: hidden;
border-radius: 4px;
white-space: nowrap;
}
.timeline-bar.work {
min-width: 2px;
border: 1px solid #ffb078;
background: linear-gradient(180deg, #ff9b52, #df6227);
color: #2b160c;
padding: 3px 5px;
font-size: 8px;
font-weight: 900;
}
.timeline-bar.travel {
min-width: 2px;
border: 1px dashed #6a9cad;
background: #284653;
color: #bfe4ec;
padding: 3px 4px;
font-size: 7px;
font-weight: 700;
}
.playhead {
position: absolute;
z-index: 5;
top: 0;
bottom: 0;
width: 2px;
background: #ffffff;
box-shadow: 0 0 8px #fff8;
pointer-events: none;
}
.time-axis {
position: relative;
height: 20px;
margin-left: 85px;
border-top: 1px solid #263943;
}
.axis-tick {
position: absolute;
top: 5px;
color: #8298a3;
font-size: 8px;
transform: translateX(-50%);
}
.axis-tick:first-child {
transform: none;
}
.axis-tick:last-child {
transform: translateX(-100%);
}
.fallback {
position: absolute;
inset: 0;
display: grid;
place-items: center;
padding: 30px;
background: #dbe7da;
color: #23343d;
text-align: center;
}
@media (max-width: 1120px) {
body {
overflow: auto;
}
.app {
height: auto;
min-height: 100dvh;
}
.workspace {
grid-template-columns: 260px minmax(0, 1fr);
}
.right-panel {
grid-column: 1 / -1;
}
.stage {
min-height: 580px;
}
}
@media (max-width: 760px) {
.app {
display: block;
}
.topbar {
min-height: 64px;
}
.top-meta .badge {
display: none;
}
.workspace {
display: flex;
flex-direction: column;
}
.stage {
order: -1;
min-height: 520px;
}
.timeline-panel {
min-height: 205px;
margin: 0 10px 10px;
}
.transport {
grid-template-columns: 40px 80px 1fr;
}
.speed-select {
display: none;
}
.stage-legend {
gap: 7px;
}
}
</style>
</head>
<body>
<div class="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>Maintenance Planner</h1>
<p>Toy network · disconnection and travel impact lab</p>
</div>
</div>
<div class="top-meta">
<span class="badge">10 nodes</span>
<span class="badge">13 links</span>
<span class="badge accent">Identical work durations</span>
<button id="resetCamera" class="icon-button">Reset view</button>
</div>
</header>
<main class="workspace">
<aside class="panel left-panel">
<section class="panel-section">
<p class="eyebrow">Scenario</p>
<h2>Compare schedules</h2>
<div class="schedule-list">
<button class="schedule-card active" data-schedule="A">
<header>
<span class="schedule-name">
<span class="schedule-letter">A</span>
Coordinated single crew
</span>
</header>
<p>Serial work in a low-travel order. Closures do not overlap.</p>
<div class="mini-stat" id="miniA"></div>
</button>
<button class="schedule-card" data-schedule="B">
<header>
<span class="schedule-name">
<span class="schedule-letter">B</span>
Parallel two-crew plan
</span>
</header>
<p>Parallel work, simultaneous outages, and longer crew regrouping.</p>
<div class="mini-stat" id="miniB"></div>
</button>
</div>
</section>
<section class="panel-section">
<p class="eyebrow">Selected schedule</p>
<h3 id="selectedTitle"></h3>
<div id="selectedMetrics" class="metric-grid"></div>
</section>
<section class="panel-section">
<p class="eyebrow">Explicit model</p>
<details open>
<summary>Measurement assumptions</summary>
<div class="details-body">
<ol>
<li>
Every active work edge is fully closed. Work durations are
identical in both schedules.
</li>
<li>
A node is disconnected when it cannot reach depot A using
the currently open links.
</li>
<li>
Road-user travel is measured for all 90 ordered origin–destination
pairs, once per minute during active closures.
</li>
<li>
For connected pairs, the shortest route is recomputed under
the current closure set. Unreachable pairs are counted as
disconnections rather than assigned an artificial delay.
</li>
<li>
Crew travel uses baseline shortest-path times and ignores
other closures. Maintenance travel may therefore enter a
work zone; no repair productivity effect is modeled.
</li>
<li>
Calendar time includes work and crew travel. Geometry is
illustrative; edge travel minutes define the network.
</li>
</ol>
</div>
</details>
<details style="margin-top: 9px">
<summary>Exact schedule definitions</summary>
<div class="details-body route">
<div><b>A / Crew 1</b><br />BI → BC → EF → FG → CJ → CH</div>
<div style="margin-top: 8px">
<b>B / Crew 1</b><br />BI → EF
</div>
<div style="margin-top: 8px">
<b>B / Crew 2</b><br />CJ → BC → FG → CH
</div>
<div style="margin-top: 8px">
All crews start at depot B. The task-side hub used for crew
travel is shown in the code and is fixed for both schedules.
</div>
</div>
</details>
</section>
<section class="panel-section">
<p class="eyebrow">Fixed maintenance work</p>
<table class="task-table">
<thead>
<tr>
<th>Task</th>
<th>Link</th>
<th>Work</th>
</tr>
</thead>
<tbody id="taskRows"></tbody>
</table>
</section>
</aside>
<section class="stage" id="stage" aria-label="Interactive 3D maintenance network">
<div class="stage-hud">
<div class="hud-card">
<strong id="stageSchedule">Schedule A</strong>
<span id="stageClosures">Active closure: BI</span>
</div>
<div class="hud-card">
<strong>Drag to orbit</strong>
<span>Scroll to zoom · double-click to reset</span>
</div>
</div>
<div class="stage-legend">
<span class="legend-item"><i class="dot"></i>Open link</span>
<span class="legend-item"><i class="dot open"></i>Scheduled work</span>
<span class="legend-item"><i class="dot active"></i>Closed now</span>
<span class="legend-item"><i class="dot offline"></i>Offline node</span>
</div>
<div id="labelLayer" class="label-layer"></div>
</section>
<aside class="panel right-panel compare-panel">
<section class="panel-section">
<p class="eyebrow">Head-to-head</p>
<h2>Impact comparison</h2>
<p class="subtle" style="margin-top: 6px">
Difference column shows B minus A. Lower values are shaded green.
</p>
<table class="comparison">
<thead>
<tr>
<th>Metric</th>
<th>A</th>
<th>B</th>
<th>Δ B−A</th>
</tr>
</thead>
<tbody id="comparisonRows"></tbody>
</table>
<div id="interpretation" class="interpretation"></div>
</section>
<section class="panel-section">
<p class="eyebrow">How to read the trade-off</p>
<p class="subtle">
Schedule B compresses the calendar by working in parallel, but its
bridge closures overlap and its crews travel farther. “Outage clock”
is the union of time with at least one offline node, while node·min
sums all offline nodes across that time.
</p>
</section>
</aside>
</main>
<footer class="timeline-panel">
<div class="transport">
<button id="playButton" class="play-button" aria-label="Play timeline">▶</button>
<div class="clock">
<span id="clockText">08:00</span>
<small id="clockOffset">+0 min</small>
</div>
<input
id="timeSlider"
type="range"
min="0"
max="296"
value="0"
step="0.25"
aria-label="Maintenance timeline"
/>
<select id="speedSelect" class="speed-select" aria-label="Playback speed">
<option value="10">10 min / sec</option>
<option value="30" selected>30 min / sec</option>
<option value="60">60 min / sec</option>
<option value="120">120 min / sec</option>
</select>
</div>
<div class="timeline-body">
<div id="timelineRows"></div>
<div id="timeAxis" class="time-axis"></div>
</div>
</footer>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Toy network
// -------------------------------------------------------------------------
const nodes = [
{ id: "A", name: "Alder", pos: [-6.0, 3.2] },
{ id: "B", name: "Forge", pos: [-2.0, 4.2], depot: true },
{ id: "C", name: "Cedar", pos: [ 2.0, 4.2] },
{ id: "D", name: "Docks", pos: [ 6.0, 3.4] },
{ id: "E", name: "Elm", pos: [-5.5, -3.0] },
{ id: "F", name: "Foundry", pos: [-1.0, -2.6] },
{ id: "G", name: "Garden", pos: [ 3.0, -2.5] },
{ id: "H", name: "Hill", pos: [ 7.0, -3.0] },
{ id: "I", name: "Isle", pos: [-3.2, 1.0] },
{ id: "J", name: "Junction",pos: [ 4.2, 1.0] }
];
const nodeById = new Map(nodes.map(node => [node.id, node]));
const edges = [
{ id: "AB", a: "A", b: "B", cost: 6 },
{ id: "BC", a: "B", b: "C", cost: 6 },
{ id: "CD", a: "C", b: "D", cost: 6 },
{ id: "AE", a: "A", b: "E", cost: 8 },
{ id: "EF", a: "E", b: "F", cost: 6 },
{ id: "BF", a: "B", b: "F", cost: 7 },
{ id: "CF", a: "C", b: "F", cost: 9 },
{ id: "FG", a: "F", b: "G", cost: 8 },
{ id: "CH", a: "C", b: "H", cost: 8 },
{ id: "GD", a: "G", b: "D", cost: 8 },
{ id: "BI", a: "B", b: "I", cost: 4 },
{ id: "CJ", a: "C", b: "J", cost: 4 }
];
const edgeById = new Map(edges.map(edge => [edge.id, edge]));
const tasks = {
BI: { id: "BI", edge: "BI", duration: 45, site: "B", name: "B–I spur" },
CJ: { id: "CJ", edge: "CJ", duration: 45, site: "C", name: "C–J spur" },
BC: { id: "BC", edge: "BC", duration: 60, site: "B", name: "B–C trunk" },
EF: { id: "EF", edge: "EF", duration: 40, site: "F", name: "E–F feeder" },
FG: { id: "FG", edge: "FG", duration: 50, site: "F", name: "F–G link" },
CH: { id: "CH", edge: "CH", duration: 40, site: "C", name: "C–H branch" }
};
const taskIds = Object.keys(tasks);
const scheduleDefinitions = {
A: {
key: "A",
title: "Coordinated single crew",
shortTitle: "Schedule A",
crews: [
{
name: "Crew 1",
color: 0x28d7e5,
css: "#28d7e5",
tasks: ["BI", "BC", "EF", "FG", "CJ", "CH"]
}
]
},
B: {
key: "B",
title: "Parallel two-crew plan",
shortTitle: "Schedule B",
crews: [
{
name: "Crew 1",
color: 0x28d7e5,
css: "#28d7e5",
tasks: ["BI", "EF"]
},
{
name: "Crew 2",
color: 0xed5c9d,
css: "#ed5c9d",
tasks: ["CJ", "BC", "FG", "CH"]
}
]
}
};
// -------------------------------------------------------------------------
// Graph calculations
// -------------------------------------------------------------------------
function edgeBetween(a, b) {
return edges.find(edge =>
(edge.a === a && edge.b === b) ||
(edge.a === b && edge.b === a)
);
}
function shortestPath(source, target) {
const distance = new Map(nodes.map(node => [node.id, Infinity]));
const previous = new Map();
const visited = new Set();
distance.set(source, 0);
while (visited.size < nodes.length) {
let current = null;
let currentDistance = Infinity;
for (const node of nodes) {
if (
!visited.has(node.id) &&
distance.get(node.id) < currentDistance
) {
current = node.id;
currentDistance = distance.get(node.id);
}
}
if (current === null) break;
if (current === target) break;
visited.add(current);
for (const edge of edges) {
if (edge.a !== current && edge.b !== current) continue;
const neighbor = edge.a === current ? edge.b : edge.a;
if (visited.has(neighbor)) continue;
const candidate = currentDistance + edge.cost;
if (candidate < distance.get(neighbor)) {
distance.set(neighbor, candidate);
previous.set(neighbor, current);
}
}
}
if (!Number.isFinite(distance.get(target))) {
return { path: [], cost: Infinity };
}
const path = [target];
let cursor = target;
while (cursor !== source) {
cursor = previous.get(cursor);
path.unshift(cursor);
}
return { path, cost: distance.get(target) };
}
function distanceMatrix(blockedTaskIds = new Set()) {
const blockedEdges = new Set(
[...blockedTaskIds].map(taskId => tasks[taskId].edge)
);
const matrix = nodes.map(() => nodes.map(() => Infinity));
nodes.forEach((node, i) => matrix[i][i] = 0);
for (const edge of edges) {
if (blockedEdges.has(edge.id)) continue;
const a = nodes.findIndex(node => node.id === edge.a);
const b = nodes.findIndex(node => node.id === edge.b);
matrix[a][b] = edge.cost;
matrix[b][a] = edge.cost;
}
for (let k = 0; k < matrix.length; k++) {
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix.length; j++) {
matrix[i][j] = Math.min(
matrix[i][j],
matrix[i][k] + matrix[k][j]
);
}
}
}
return matrix;
}
const baselineMatrix = distanceMatrix();
function buildCrew(definition, crewDefinition, crewIndex) {
const segments = [];
let time = 0;
let currentSite = "B";
for (const taskId of crewDefinition.tasks) {
const task = tasks[taskId];
if (currentSite !== task.site) {
const route = shortestPath(currentSite, task.site);
if (route.path.length > 1) {
segments.push({
type: "travel",
start: time,
end: time + route.cost,
from: currentSite,
to: task.site,
path: route.path,
cost: route.cost
});
time += route.cost;
}
currentSite = task.site;
}
segments.push({
type: "work",
start: time,
end: time + task.duration,
taskId,
task,
site: task.site
});
time += task.duration;
}
return {
name: crewDefinition.name,
color: crewDefinition.color,
css: crewDefinition.css,
index: crewIndex,
segments,
travelMinutes: segments
.filter(segment => segment.type === "travel")
.reduce((sum, segment) => sum + segment.cost, 0)
};
}
function buildSchedule(definition) {
const crews = definition.crews.map((crew, index) =>
buildCrew(definition, crew, index)
);
const workSegments = crews.flatMap(crew =>
crew.segments.filter(segment => segment.type === "work")
);
const makespan = Math.max(
...crews.flatMap(crew => crew.segments.map(segment => segment.end))
);
return {
...definition,
crews,
workSegments,
makespan,
crewTravel: crews.reduce(
(sum, crew) => sum + crew.travelMinutes,
0
)
};
}
function mergeIntervals(intervals) {
const merged = [];
for (const interval of intervals) {
const previous = merged[merged.length - 1];
if (previous && interval.start <= previous.end + 0.0001) {
previous.end = Math.max(previous.end, interval.end);
} else {
merged.push({ ...interval });
}
}
return merged;
}
function analyzeSchedule(schedule) {
const boundaries = [
0,
schedule.makespan,
...schedule.workSegments.flatMap(segment => [segment.start, segment.end])
].sort((a, b) => a - b);
const uniqueBoundaries = [...new Set(boundaries.map(value => Number(value.toFixed(6))))];
let nodeDisconnectedMin = 0;
let disconnectedPairMin = 0;
let roadDelayPairMin = 0;
let connectedOpportunityMin = 0;
let peakDisconnectedNodes = 0;
let peakDisconnectedPairs = 0;
const outageIntervals = [];
const totalPairs = nodes.length * (nodes.length - 1);
for (let index = 0; index < uniqueBoundaries.length - 1; index++) {
const start = uniqueBoundaries[index];
const end = uniqueBoundaries[index + 1];
const duration = end - start;
const midpoint = start + duration / 2;
const activeTaskIds = new Set(
schedule.workSegments
.filter(segment =>
segment.start <= midpoint && midpoint < segment.end
)
.map(segment => segment.taskId)
);
if (activeTaskIds.size === 0) continue;
const matrix = distanceMatrix(activeTaskIds);
const rootIndex = nodes.findIndex(node => node.id === "A");
const disconnectedNodes = nodes.filter((node, nodeIndex) =>
!Number.isFinite(matrix[rootIndex][nodeIndex])
).length;
let reachablePairs = 0;
let disconnectedPairs = 0;
let addedTravel = 0;
for (let i = 0; i < nodes.length; i++) {
for (let j = 0; j < nodes.length; j++) {
if (i === j) continue;
if (!Number.isFinite(matrix[i][j])) {
disconnectedPairs++;
} else {
reachablePairs++;
addedTravel += Math.max(
0,
matrix[i][j] - baselineMatrix[i][j]
);
}
}
}
nodeDisconnectedMin += disconnectedNodes * duration;
disconnectedPairMin += disconnectedPairs * duration;
roadDelayPairMin += addedTravel * duration;
connectedOpportunityMin += reachablePairs * duration;
peakDisconnectedNodes = Math.max(
peakDisconnectedNodes,
disconnectedNodes
);
peakDisconnectedPairs = Math.max(
peakDisconnectedPairs,
disconnectedPairs
);
if (disconnectedNodes > 0) {
outageIntervals.push({ start, end });
}
}
const mergedOutages = mergeIntervals(outageIntervals);
return {
calendar: schedule.makespan,
crewTravel: schedule.crewTravel,
nodeDisconnectedMin,
disconnectedPairMin,
roadDelayPairMin,
averageDelay:
connectedOpportunityMin > 0
? roadDelayPairMin / connectedOpportunityMin
: 0,
peakDisconnectedNodes,
peakDisconnectedPairs,
outageClock: mergedOutages.reduce(
(sum, interval) => sum + interval.end - interval.start,
0
),
outageWindows: mergedOutages.length
};
}
const schedules = Object.fromEntries(
Object.entries(scheduleDefinitions).map(([key, definition]) => {
const schedule = buildSchedule(definition);
schedule.metrics = analyzeSchedule(schedule);
return [key, schedule];
})
);
// -------------------------------------------------------------------------
// Formatting and UI
// -------------------------------------------------------------------------
const numberFormatter = new Intl.NumberFormat();
const compactFormatter = new Intl.NumberFormat(undefined, {
notation: "compact",
maximumFractionDigits: 1
});
function formatDuration(minutes) {
const rounded = Math.round(minutes);
if (rounded < 60) return `${rounded}m`;
const hours = Math.floor(rounded / 60);
const remainder = rounded % 60;
return remainder
? `${hours}h ${remainder}m`
: `${hours}h`;
}
function formatNumber(value) {
return numberFormatter.format(Math.round(value));
}
function formatCompact(value) {
return compactFormatter.format(value);
}
function formatClock(minutes) {
const total = 8 * 60 + Math.floor(minutes);
const hours = Math.floor(total / 60) % 24;
const remainder = total % 60;
return `${String(hours).padStart(2, "0")}:${String(remainder).padStart(2, "0")}`;
}
function signedDifference(a, b, type) {
const difference = b - a;
if (Math.abs(difference) < 0.0001) return "0";
const sign = difference > 0 ? "+" : "−";
const absolute = Math.abs(difference);
if (type === "duration") {
return `${sign}${formatDuration(absolute)}`;
}
if (type === "compact") {
return `${sign}${formatCompact(absolute)}`;
}
return `${sign}${formatNumber(absolute)}`;
}
const comparisonRows = [
{
label: "Calendar duration",
key: "calendar",
type: "duration",
format: value => formatDuration(value)
},
{
label: "Any-outage clock",
key: "outageClock",
type: "duration",
format: value => formatDuration(value)
},
{
label: "Outage windows",
key: "outageWindows",
type: "number",
format: value => formatNumber(value)
},
{
label: "Offline node·min",
key: "nodeDisconnectedMin",
type: "number",
format: value => formatNumber(value)
},
{
label: "Offline OD trip·min",
key: "disconnectedPairMin",
type: "number",
format: value => formatNumber(value)
},
{
label: "Added road travel",
key: "roadDelayPairMin",
type: "compact",
format: value => `${formatCompact(value)} pair·min`
},
{
label: "Avg delay / connected trip",
key: "averageDelay",
type: "number",
format: value => `${value.toFixed(2)}m`
},
{
label: "Crew travel",
key: "crewTravel",
type: "duration",
format: value => formatDuration(value)
},
{
label: "Peak offline nodes",
key: "peakDisconnectedNodes",
type: "number",
format: value => formatNumber(value)
}
];
function renderTaskTable() {
document.getElementById("taskRows").innerHTML = taskIds
.map(id => {
const task = tasks[id];
return `
<tr>
<td class="task-id">${id}</td>
<td>${task.name}</td>
<td>${task.duration}m</td>
</tr>
`;
})
.join("");
}
function renderComparison() {
const a = schedules.A.metrics;
const b = schedules.B.metrics;
document.getElementById("comparisonRows").innerHTML =
comparisonRows.map(row => {
const aValue = a[row.key];
const bValue = b[row.key];
const difference = bValue - aValue;
const diffClass = Math.abs(difference) < 0.0001
? "neutral"
: difference < 0
? "good"
: "bad";
return `
<tr>
<td>${row.label}</td>
<td class="a-value">${row.format(aValue)}</td>
<td class="b-value">${row.format(bValue)}</td>
<td>
<span class="diff ${diffClass}">
${signedDifference(aValue, bValue, row.type)}
</span>
</td>
</tr>
`;
}).join("");
const calendarGain = a.calendar - b.calendar;
const travelIncrease = b.crewTravel - a.crewTravel;
const outageGain = a.outageClock - b.outageClock;
const roadDelayChange = b.roadDelayPairMin - a.roadDelayPairMin;
document.getElementById("interpretation").innerHTML = `
<strong>Trade-off:</strong> B finishes ${formatDuration(calendarGain)}
sooner and shortens the any-outage clock by ${formatDuration(outageGain)},
but adds ${formatDuration(travelIncrease)} of crew travel.
Its simultaneous bridge work raises the peak to
${b.peakDisconnectedNodes} offline nodes. Integrated road-user delay
changes by ${signedDifference(a.roadDelayPairMin, b.roadDelayPairMin, "compact")}
pair·min.
`;
}
function renderSelectedMetrics() {
const schedule = schedules[activeScheduleKey];
const metrics = schedule.metrics;
document.getElementById("selectedTitle").textContent =
`${schedule.shortTitle} · ${schedule.title}`;
const cards = [
["Calendar", formatDuration(metrics.calendar)],
["Any outage", formatDuration(metrics.outageClock)],
["Offline node·min", formatNumber(metrics.nodeDisconnectedMin)],
["Crew travel", formatDuration(metrics.crewTravel)],
["Road delay", `${formatCompact(metrics.roadDelayPairMin)} pair·min`],
["Peak offline", formatNumber(metrics.peakDisconnectedNodes)]
];
document.getElementById("selectedMetrics").innerHTML = cards
.map(([label, value]) => `
<div class="metric-card">
<span>${label}</span>
<strong title="${value}">${value}</strong>
</div>
`)
.join("");
for (const key of ["A", "B"]) {
const metric = schedules[key].metrics;
document.getElementById(`mini${key}`).textContent =
`${formatDuration(metric.calendar)} finish · ` +
`${formatDuration(metric.crewTravel)} crew travel · ` +
`${metric.peakDisconnectedNodes} peak offline`;
}
}
function renderTimeline() {
const schedule = schedules[activeScheduleKey];
document.getElementById("timelineRows").innerHTML =
schedule.crews.map((crew, crewIndex) => `
<div class="timeline-row">
<div class="timeline-row-label">
<i class="team-dot" style="background:${crew.css}"></i>
${crew.name}
</div>
<div class="track" data-crew="${crewIndex}">
${crew.segments.map(segment => {
const left = segment.start / schedule.makespan * 100;
const width = (segment.end - segment.start) / schedule.makespan * 100;
if (segment.type === "work") {
return `
<div
class="timeline-bar work"
style="left:${left}%;width:${width}%"
title="${segment.taskId}: ${segment.task.duration} minutes"
>
${segment.taskId} · ${segment.task.duration}m
</div>
`;
}
return `
<div
class="timeline-bar travel"
style="left:${left}%;width:${width}%"
title="Crew travel: ${segment.cost} minutes"
>
${segment.cost > 8 ? `travel ${segment.cost}m` : ""}
</div>
`;
}).join("")}
<div class="playhead" id="playhead${crewIndex}"></div>
</div>
</div>
`).join("");
document.getElementById("timeAxis").innerHTML =
[0, 0.25, 0.5, 0.75, 1].map(fraction => {
const minutes = schedule.makespan * fraction;
return `
<span class="axis-tick" style="left:${fraction * 100}%">
${formatDuration(minutes)}
</span>
`;
}).join("");
const slider = document.getElementById("timeSlider");
slider.max = schedule.makespan;
slider.value = currentTime;
}
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const stage = document.getElementById("stage");
const labelLayer = document.getElementById("labelLayer");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdbe7da);
scene.fog = new THREE.Fog(0xdbe7da, 23, 42);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
let renderer;
try {
renderer = new THREE.WebGLRenderer({ antialias: true });
} catch (error) {
stage.innerHTML = `
<div class="fallback">
WebGL could not be initialized. The schedule calculations still work,
but the 3D scene requires a WebGL-capable browser.
</div>
`;
throw error;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
stage.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xf7fbff, 0x6c785f, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff0d9, 3.0);
sun.position.set(-8, 16, 10);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -15;
sun.shadow.camera.right = 15;
sun.shadow.camera.top = 15;
sun.shadow.camera.bottom = -15;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 40;
sun.shadow.bias = -0.0005;
scene.add(sun);
const ground = new THREE.Mesh(
new THREE.CircleGeometry(13, 64),
new THREE.MeshStandardMaterial({
color: 0xbfd1b4,
roughness: 0.98,
flatShading: true
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.14;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(24, 24, 0x91aa91, 0x9eb79f);
grid.position.y = -0.025;
grid.material.transparent = true;
grid.material.opacity = 0.16;
scene.add(grid);
const base = new THREE.Mesh(
new THREE.CylinderGeometry(12.9, 12.9, 0.32, 48),
new THREE.MeshStandardMaterial({
color: 0x8da38c,
roughness: 0.95,
flatShading: true
})
);
base.position.y = -0.32;
base.receiveShadow = true;
scene.add(base);
// Low-poly hills around the board.
const hillMaterial = new THREE.MeshStandardMaterial({
color: 0x9db597,
roughness: 1,
flatShading: true
});
[
[-9.8, -5.5, 1.6, 0.8],
[9.3, 6.0, 1.9, 1.0],
[8.8, -7.0, 1.2, 0.7],
[-8.5, 7.2, 1.3, 0.7]
].forEach(([x, z, sx, sy]) => {
const hill = new THREE.Mesh(
new THREE.IcosahedronGeometry(1, 0),
hillMaterial
);
hill.position.set(x, -0.1, z);
hill.scale.set(sx, sy, sx);
hill.rotation.y = x * 0.37;
hill.receiveShadow = true;
hill.castShadow = true;
scene.add(hill);
});
// Seeded low-poly trees.
let seed = 7381;
function random() {
seed = (seed * 16807) % 2147483647;
return (seed - 1) / 2147483646;
}
const trunkGeometry = new THREE.CylinderGeometry(0.08, 0.11, 0.6, 5);
const leafGeometry = new THREE.ConeGeometry(0.46, 1.25, 6);
const trunkMaterial = new THREE.MeshStandardMaterial({ color: 0x7c5a3d });
const leafMaterials = [0x426d50, 0x537b57, 0x6f8e61].map(color =>
new THREE.MeshStandardMaterial({
color,
roughness: 1,
flatShading: true
})
);
for (let index = 0; index < 58; index++) {
const angle = random() * Math.PI * 2;
const radius = 8.4 + random() * 3.4;
const x = Math.cos(angle) * radius;
const z = Math.sin(angle) * radius;
const tree = new THREE.Group();
tree.position.set(x, -0.08, z);
tree.rotation.y = random() * Math.PI * 2;
const scale = 0.65 + random() * 0.55;
tree.scale.setScalar(scale);
const trunk = new THREE.Mesh(trunkGeometry, trunkMaterial);
trunk.position.y = 0.3;
trunk.castShadow = true;
const leaves = new THREE.Mesh(
leafGeometry,
leafMaterials[Math.floor(random() * leafMaterials.length)]
);
leaves.position.y = 1.02;
leaves.rotation.y = random() * Math.PI;
leaves.castShadow = true;
tree.add(trunk, leaves);
scene.add(tree);
}
// Road geometry.
const edgeVisuals = new Map();
const normalRoadColor = 0x61747b;
const scheduledRoadColor = 0xd8ae59;
const activeRoadColor = 0xff7838;
function midpoint(edge) {
const a = nodeById.get(edge.a).pos;
const b = nodeById.get(edge.b).pos;
return [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
}
for (const edge of edges) {
const a = nodeById.get(edge.a).pos;
const b = nodeById.get(edge.b).pos;
const dx = b[0] - a[0];
const dz = b[1] - a[1];
const length = Math.hypot(dx, dz);
const group = new THREE.Group();
group.position.set((a[0] + b[0]) / 2, 0.08, (a[1] + b[1]) / 2);
group.rotation.y = -Math.atan2(dz, dx);
const material = new THREE.MeshStandardMaterial({
color: normalRoadColor,
roughness: 0.9,
flatShading: true
});
const road = new THREE.Mesh(
new THREE.BoxGeometry(length, 0.12, 0.48),
material
);
road.receiveShadow = true;
group.add(road);
const dashMaterial = new THREE.MeshBasicMaterial({ color: 0xdbe3df });
const dashCount = Math.max(1, Math.floor(length / 1.25));
for (let dashIndex = 0; dashIndex < dashCount; dashIndex++) {
const dash = new THREE.Mesh(
new THREE.BoxGeometry(0.42, 0.025, 0.055),
dashMaterial
);
dash.position.set(
-length / 2 + (dashIndex + 0.5) * length / dashCount,
0.082,
0
);
group.add(dash);
}
scene.add(group);
const task = taskIds.includes(edge.id) ? tasks[edge.id] : null;
let marker = null;
let barrier = null;
if (task) {
marker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.28, 0),
new THREE.MeshStandardMaterial({
color: scheduledRoadColor,
emissive: 0x372000,
roughness: 0.55,
flatShading: true
})
);
const center = midpoint(edge);
marker.position.set(center[0], 0.95, center[1]);
marker.castShadow = true;
scene.add(marker);
barrier = new THREE.Group();
barrier.position.set(center[0], 0.1, center[1]);
barrier.rotation.y = group.rotation.y;
const postMaterial = new THREE.MeshStandardMaterial({
color: 0xf2f2e9,
roughness: 0.8
});
for (const side of [-1, 1]) {
const post = new THREE.Mesh(
new THREE.BoxGeometry(0.14, 0.72, 0.14),
postMaterial
);
post.position.set(0, 0.36, side * 0.4);
post.castShadow = true;
barrier.add(post);
}
const bar = new THREE.Mesh(
new THREE.BoxGeometry(0.14, 0.18, 0.95),
new THREE.MeshStandardMaterial({ color: 0xef476f })
);
bar.position.y = 0.58;
barrier.add(bar);
barrier.visible = false;
scene.add(barrier);
}
edgeVisuals.set(edge.id, {
edge,
group,
material,
task,
marker,
barrier
});
}
// Node buildings.
const nodeVisuals = new Map();
const roofColors = [
0xd86f52, 0x527d91, 0xd5a84c, 0x648c69,
0x9b6d9b, 0x4f91a0, 0xbc7555, 0x779456,
0xc05d74, 0x568c8a
];
nodes.forEach((node, index) => {
const group = new THREE.Group();
group.position.set(node.pos[0], 0, node.pos[1]);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0xeee7d3,
roughness: 0.85,
flatShading: true
});
const roofMaterial = new THREE.MeshStandardMaterial({
color: roofColors[index],
roughness: 0.82,
flatShading: true
});
const pad = new THREE.Mesh(
new THREE.CylinderGeometry(0.68, 0.75, 0.24, 8),
new THREE.MeshStandardMaterial({
color: 0x8b9d8d,
roughness: 1,
flatShading: true
})
);
pad.position.y = 0.12;
pad.receiveShadow = true;
const building = new THREE.Mesh(
new THREE.BoxGeometry(0.76, 0.72, 0.68),
bodyMaterial
);
building.position.y = 0.59;
building.castShadow = true;
building.receiveShadow = true;
const roof = new THREE.Mesh(
new THREE.ConeGeometry(0.63, 0.58, 4),
roofMaterial
);
roof.position.y = 1.25;
roof.rotation.y = Math.PI / 4;
roof.castShadow = true;
group.add(pad, building, roof);
if (node.depot) {
const tower = new THREE.Mesh(
new THREE.CylinderGeometry(0.12, 0.16, 0.95, 8),
bodyMaterial
);
tower.position.set(0.47, 0.75, 0.25);
tower.castShadow = true;
group.add(tower);
const beacon = new THREE.Mesh(
new THREE.ConeGeometry(0.2, 0.35, 6),
roofMaterial
);
beacon.position.set(0.47, 1.37, 0.25);
group.add(beacon);
}
scene.add(group);
nodeVisuals.set(node.id, {
group,
bodyMaterial,
roofMaterial,
originalBodyColor: bodyMaterial.color.clone(),
originalRoofColor: roofMaterial.color.clone()
});
});
// Crew vehicles.
const crewGroups = [];
function createCrewVehicle(color) {
const group = new THREE.Group();
const colorMaterial = new THREE.MeshStandardMaterial({
color,
roughness: 0.55,
flatShading: true
});
const darkMaterial = new THREE.MeshStandardMaterial({
color: 0x26333a,
roughness: 0.85
});
const glassMaterial = new THREE.MeshStandardMaterial({
color: 0xc9e8ea,
roughness: 0.35
});
const body = new THREE.Mesh(
new THREE.BoxGeometry(0.88, 0.3, 0.48),
colorMaterial
);
body.position.y = 0.18;
body.castShadow = true;
const cab = new THREE.Mesh(
new THREE.BoxGeometry(0.34, 0.34, 0.44),
glassMaterial
);
cab.position.set(0.29, 0.43, 0);
cab.castShadow = true;
const beacon = new THREE.Mesh(
new THREE.ConeGeometry(0.12, 0.25, 6),
colorMaterial
);
beacon.position.set(0.02, 0.53, 0);
beacon.castShadow = true;
group.add(body, cab, beacon);
const wheelGeometry = new THREE.CylinderGeometry(0.13, 0.13, 0.09, 8);
for (const x of [-0.27, 0.27]) {
for (const z of [-0.25, 0.25]) {
const wheel = new THREE.Mesh(wheelGeometry, darkMaterial);
wheel.rotation.x = Math.PI / 2;
wheel.position.set(x, 0.08, z);
wheel.castShadow = true;
group.add(wheel);
}
}
group.scale.setScalar(0.9);
scene.add(group);
return group;
}
for (let index = 0; index < 2; index++) {
crewGroups.push(createCrewVehicle(
index === 0 ? 0x28d7e5 : 0xed5c9d
));
}
// DOM labels.
const nodeLabels = new Map();
const taskLabels = new Map();
const crewLabels = [];
for (const node of nodes) {
const element = document.createElement("div");
element.className = "map-label node-label";
element.textContent = `${node.id} · ${node.name}`;
labelLayer.appendChild(element);
nodeLabels.set(node.id, element);
}
for (const taskId of taskIds) {
const task = tasks[taskId];
const element = document.createElement("div");
element.className = "map-label task-label";
element.textContent = `${task.id} · ${task.duration}m`;
labelLayer.appendChild(element);
taskLabels.set(taskId, element);
}
for (let index = 0; index < 2; index++) {
const element = document.createElement("div");
element.className = "map-label crew-label";
labelLayer.appendChild(element);
crewLabels.push(element);
}
// -------------------------------------------------------------------------
// Custom camera controls, without Three.js addons
// -------------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(0, 0.2, 0),
yaw: 0.63,
pitch: 0.67,
radius: 21.5
};
function resetCamera() {
cameraState.target.set(0, 0.2, 0);
cameraState.yaw = 0.63;
cameraState.pitch = 0.67;
cameraState.radius = 21.5;
}
function updateCamera() {
const horizontal = Math.cos(cameraState.pitch) * cameraState.radius;
camera.position.set(
cameraState.target.x + Math.sin(cameraState.yaw) * horizontal,
cameraState.target.y + Math.sin(cameraState.pitch) * cameraState.radius,
cameraState.target.z + Math.cos(cameraState.yaw) * horizontal
);
camera.lookAt(cameraState.target);
camera.updateMatrixWorld();
}
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const deltaX = event.clientX - pointerX;
const deltaY = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.yaw -= deltaX * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + deltaY * 0.005,
0.28,
1.38
);
});
renderer.domElement.addEventListener("pointerup", event => {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
10,
34
);
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
renderer.domElement.addEventListener("contextmenu", event => event.preventDefault());
document.getElementById("resetCamera").addEventListener("click", resetCamera);
// -------------------------------------------------------------------------
// Scene state and playback
// -------------------------------------------------------------------------
let activeScheduleKey = "A";
let currentTime = 0;
let playing = false;
let playbackRate = 30;
let activeCacheKey = "";
function activeTaskIdsAt(time) {
const schedule = schedules[activeScheduleKey];
return schedule.workSegments
.filter(segment =>
segment.start <= time && time < segment.end
)
.map(segment => segment.taskId);
}
function updateSceneState() {
const activeTasks = activeTaskIdsAt(currentTime);
const activeSet = new Set(activeTasks);
const key = [...activeSet].sort().join(",");
if (key === activeCacheKey) return;
activeCacheKey = key;
const matrix = distanceMatrix(activeSet);
const rootIndex = nodes.findIndex(node => node.id === "A");
const disconnected = new Set(
nodes.filter((node, index) =>
!Number.isFinite(matrix[rootIndex][index])
).map(node => node.id)
);
for (const visual of edgeVisuals.values()) {
const taskId = visual.task?.id;
if (taskId && activeSet.has(taskId)) {
visual.material.color.setHex(activeRoadColor);
visual.barrier.visible = true;
visual.marker.material.color.setHex(activeRoadColor);
visual.marker.material.emissive.setHex(0x6c2100);
} else if (visual.task) {
visual.material.color.setHex(scheduledRoadColor);
visual.barrier.visible = false;
visual.marker.material.color.setHex(scheduledRoadColor);
visual.marker.material.emissive.setHex(0x372000);
} else {
visual.material.color.setHex(normalRoadColor);
}
if (visual.task) {
taskLabels.get(taskId).style.opacity =
activeSet.has(taskId) ? "1" : "0.48";
}
}
for (const node of nodes) {
const visual = nodeVisuals.get(node.id);
if (disconnected.has(node.id)) {
visual.bodyMaterial.color.setHex(0xffc1cc);
visual.roofMaterial.color.setHex(0xef476f);
} else {
visual.bodyMaterial.color.copy(visual.originalBodyColor);
visual.roofMaterial.color.copy(visual.originalRoofColor);
}
}
const schedule = schedules[activeScheduleKey];
document.getElementById("stageSchedule").textContent =
`${schedule.shortTitle} · ${schedule.title}`;
document.getElementById("stageClosures").textContent =
activeTasks.length
? `Active closure${activeTasks.length > 1 ? "s" : ""}: ${activeTasks.join(" · ")}`
: "Network open — crews repositioning";
}
function pathPoint(path, ratio) {
if (path.length === 1) {
const position = nodeById.get(path[0]).pos;
return { x: position[0], z: position[1], angle: 0 };
}
const costs = [];
let total = 0;
for (let index = 0; index < path.length - 1; index++) {
const edge = edgeBetween(path[index], path[index + 1]);
costs.push(edge.cost);
total += edge.cost;
}
let remaining = ratio * total;
for (let index = 0; index < costs.length; index++) {
const cost = costs[index];
const a = nodeById.get(path[index]).pos;
const b = nodeById.get(path[index + 1]).pos;
if (remaining <= cost || index === costs.length - 1) {
const t = cost === 0 ? 0 : THREE.MathUtils.clamp(remaining / cost, 0, 1);
const dx = b[0] - a[0];
const dz = b[1] - a[1];
return {
x: a[0] + dx * t,
z: a[1] + dz * t,
angle: -Math.atan2(dz, dx)
};
}
remaining -= cost;
}
return { x: 0, z: 0, angle: 0 };
}
function updateCrewVehicles() {
const schedule = schedules[activeScheduleKey];
schedule.crews.forEach((crew, crewIndex) => {
const group = crewGroups[crewIndex];
const label = crewLabels[crewIndex];
label.textContent = crew.name.toUpperCase();
label.style.background = crew.css;
const segment = crew.segments.find(item =>
currentTime >= item.start && currentTime < item.end
) || crew.segments[crew.segments.length - 1];
if (!segment) {
group.visible = false;
label.style.display = "none";
return;
}
group.visible = true;
label.style.display = "block";
if (segment.type === "travel") {
const ratio = THREE.MathUtils.clamp(
(currentTime - segment.start) / (segment.end - segment.start),
0,
1
);
const point = pathPoint(segment.path, ratio);
group.position.set(point.x, 0.34, point.z);
group.rotation.y = point.angle;
} else {
const position = nodeById.get(segment.site).pos;
group.position.set(position[0], 0.34, position[1]);
const edge = edgeById.get(segment.task.edge);
const a = nodeById.get(edge.a).pos;
const b = nodeById.get(edge.b).pos;
group.rotation.y = -Math.atan2(b[1] - a[1], b[0] - a[0]);
}
});
}
function updateLabels() {
const width = stage.clientWidth;
const height = stage.clientHeight;
function place(element, x, y, z) {
const vector = new THREE.Vector3(x, y, z).project(camera);
const visible = vector.z > -1 && vector.z < 1;
element.style.display = visible ? "" : "none";
if (!visible) return;
const screenX = (vector.x * 0.5 + 0.5) * width;
const screenY = (-vector.y * 0.5 + 0.5) * height;
element.style.transform =
`translate(-50%, -50%) translate(${screenX}px, ${screenY}px)`;
}
for (const node of nodes) {
place(
nodeLabels.get(node.id),
node.pos[0],
1.9,
node.pos[1]
);
}
for (const taskId of taskIds) {
const task = tasks[taskId];
const edge = edgeById.get(task.edge);
const center = midpoint(edge);
place(
taskLabels.get(taskId),
center[0],
1.45,
center[1]
);
}
const schedule = schedules[activeScheduleKey];
schedule.crews.forEach((crew, index) => {
const group = crewGroups[index];
place(
crewLabels[index],
group.position.x,
group.position.y + 1.05,
group.position.z
);
});
}
function updateTimeReadout() {
const schedule = schedules[activeScheduleKey];
document.getElementById("clockText").textContent =
formatClock(currentTime);
document.getElementById("clockOffset").textContent =
`+${Math.floor(currentTime)} min`;
document.getElementById("timeSlider").value = currentTime;
const fraction = currentTime / schedule.makespan * 100;
schedule.crews.forEach((_, index) => {
const playhead = document.getElementById(`playhead${index}`);
if (playhead) playhead.style.left = `${fraction}%`;
});
}
function setPlaying(value) {
playing = value;
document.getElementById("playButton").textContent = playing ? "❚❚" : "▶";
document.getElementById("playButton").setAttribute(
"aria-label",
playing ? "Pause timeline" : "Play timeline"
);
}
function selectSchedule(key) {
activeScheduleKey = key;
currentTime = 0;
activeCacheKey = "";
setPlaying(false);
document.querySelectorAll(".schedule-card").forEach(button => {
button.classList.toggle("active", button.dataset.schedule === key);
});
renderSelectedMetrics();
renderTimeline();
updateSceneState();
updateTimeReadout();
}
document.querySelectorAll(".schedule-card").forEach(button => {
button.addEventListener("click", () => {
selectSchedule(button.dataset.schedule);
});
});
document.getElementById("playButton").addEventListener("click", () => {
const schedule = schedules[activeScheduleKey];
if (!playing && currentTime >= schedule.makespan - 0.01) {
currentTime = 0;
}
setPlaying(!playing);
});
document.getElementById("timeSlider").addEventListener("input", event => {
currentTime = Number(event.target.value);
updateTimeReadout();
});
document.getElementById("speedSelect").addEventListener("change", event => {
playbackRate = Number(event.target.value);
});
document.getElementById("timelineRows").addEventListener("click", event => {
const track = event.target.closest(".track");
if (!track) return;
const bounds = track.getBoundingClientRect();
const ratio = THREE.MathUtils.clamp(
(event.clientX - bounds.left) / bounds.width,
0,
1
);
currentTime = ratio * schedules[activeScheduleKey].makespan;
updateTimeReadout();
});
window.addEventListener("keydown", event => {
if (event.code === "Space" && event.target === document.body) {
event.preventDefault();
const schedule = schedules[activeScheduleKey];
if (!playing && currentTime >= schedule.makespan - 0.01) currentTime = 0;
setPlaying(!playing);
}
});
// -------------------------------------------------------------------------
// Resize and animation
// -------------------------------------------------------------------------
function resizeRenderer() {
const width = stage.clientWidth;
const height = stage.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / Math.max(height, 1);
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resizeRenderer);
resizeObserver.observe(stage);
const animationClock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(animationClock.getDelta(), 0.05);
const schedule = schedules[activeScheduleKey];
if (playing) {
currentTime += delta * playbackRate;
if (currentTime >= schedule.makespan) {
currentTime = schedule.makespan;
setPlaying(false);
}
}
updateCamera();
updateSceneState();
updateCrewVehicles();
updateTimeReadout();
const elapsed = animationClock.elapsedTime;
for (const visual of edgeVisuals.values()) {
if (!visual.marker) continue;
visual.marker.rotation.y += delta * 1.2;
visual.marker.rotation.x = Math.sin(elapsed * 1.4) * 0.08;
const isActive = visual.barrier?.visible;
const scale = isActive ? 1 + Math.sin(elapsed * 5) * 0.12 : 0.78;
visual.marker.scale.setScalar(scale);
}
updateLabels();
renderer.render(scene, camera);
}
renderTaskTable();
renderComparison();
renderSelectedMetrics();
renderTimeline();
resizeRenderer();
updateCamera();
updateSceneState();
updateTimeReadout();
animate();
</script>
</body>
</html>
```