Prompt specification
Build or customize the Three.js 3D scene "Synchronize a Transfer Without Adding Service" 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: Synchronize a Transfer Without Adding Service
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/synchronize-a-transfer-without-adding-service-x2144
Scene Description Prompt:
Make a voxel transit puzzle adjusting one route's timetable phase; compare transfer waits without adding services. One HTML file using Three.js from cdnjs.
Working Three.js Starter (synchronize-a-transfer-without-adding-service-x2144):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Transit — Phase Lab</title>
<style>
:root {
--bg: #07111b;
--panel: rgba(10, 23, 34, 0.92);
--panel-soft: rgba(18, 39, 53, 0.72);
--line: rgba(151, 190, 211, 0.16);
--text: #eef8ff;
--muted: #8da8b8;
--cyan: #38bdf8;
--cyan-soft: rgba(56, 189, 248, 0.14);
--green: #50e3a4;
--amber: #fbbf6a;
--red: #fb7185;
--cobalt: #38bdf8;
--mint: #4ade80;
--rose: #f472b6;
--orange: #f6ad55;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 62% 45%, transparent 30%, rgba(2, 8, 13, 0.24) 100%),
linear-gradient(90deg, rgba(3, 10, 16, 0.15), transparent 35%);
}
.brand {
position: fixed;
top: 24px;
right: 26px;
z-index: 4;
display: flex;
align-items: center;
gap: 12px;
pointer-events: none;
}
.brand-mark {
position: relative;
width: 38px;
height: 38px;
transform: rotate(-8deg);
}
.brand-mark i {
position: absolute;
display: block;
width: 17px;
height: 17px;
border-radius: 3px;
background: var(--cyan);
box-shadow: 0 0 24px rgba(56, 189, 248, 0.45);
}
.brand-mark i:nth-child(1) {
left: 0;
top: 0;
}
.brand-mark i:nth-child(2) {
right: 0;
top: 0;
background: var(--green);
}
.brand-mark i:nth-child(3) {
left: 10px;
bottom: 0;
background: var(--orange);
}
.brand strong {
display: block;
font-size: 13px;
letter-spacing: 0.19em;
}
.brand span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 10px;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.panel {
position: fixed;
z-index: 5;
top: 20px;
bottom: 20px;
left: 20px;
width: 382px;
padding: 23px;
overflow: auto;
border: 1px solid var(--line);
border-radius: 22px;
background: var(--panel);
box-shadow: 0 24px 70px rgba(0, 0, 0, 0.32);
backdrop-filter: blur(18px);
scrollbar-width: thin;
scrollbar-color: #284454 transparent;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
.signal {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px var(--cyan);
animation: signal 1.8s ease-in-out infinite;
}
@keyframes signal {
50% {
opacity: 0.4;
transform: scale(0.8);
}
}
h1 {
margin: 12px 0 9px;
font-size: clamp(32px, 4.8vh, 43px);
line-height: 0.98;
letter-spacing: -0.055em;
}
h1 em {
color: var(--cyan);
font-style: normal;
}
.intro {
margin: 0;
color: var(--muted);
font-size: 12.5px;
line-height: 1.55;
}
.route-card {
display: flex;
align-items: center;
gap: 11px;
margin-top: 17px;
padding: 12px;
border: 1px solid rgba(56, 189, 248, 0.22);
border-radius: 14px;
background: var(--cyan-soft);
}
.route-swatch {
width: 12px;
height: 34px;
flex: 0 0 auto;
border-radius: 5px;
background: var(--cobalt);
box-shadow: 0 0 16px rgba(56, 189, 248, 0.42);
}
.route-card > div:nth-child(2) {
min-width: 0;
flex: 1;
}
.route-card strong {
display: block;
font-size: 13px;
}
.route-card small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.route-card b {
padding: 5px 7px;
border: 1px solid rgba(80, 227, 164, 0.28);
border-radius: 999px;
color: var(--green);
background: rgba(80, 227, 164, 0.08);
font-size: 8px;
letter-spacing: 0.12em;
white-space: nowrap;
}
.phase-card {
margin-top: 12px;
padding: 14px;
border: 1px solid var(--line);
border-radius: 15px;
background: rgba(4, 13, 21, 0.38);
}
.phase-heading {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 12px;
}
.phase-heading label {
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.phase-heading strong {
color: var(--cyan);
font-size: 22px;
font-variant-numeric: tabular-nums;
letter-spacing: -0.04em;
}
.phase-heading strong small {
color: var(--muted);
font-size: 10px;
font-weight: 500;
letter-spacing: 0;
}
.phase-steps {
display: flex;
gap: 5px;
margin-top: 10px;
}
.phase-steps button {
width: 27px;
height: 27px;
padding: 0;
border: 1px solid var(--line);
border-radius: 8px;
background: var(--panel-soft);
cursor: pointer;
transition: 0.18s ease;
}
.phase-steps button:hover {
border-color: var(--cyan);
color: var(--cyan);
transform: translateY(-1px);
}
input[type="range"] {
width: 100%;
height: 22px;
margin: 9px 0 0;
appearance: none;
background: transparent;
cursor: pointer;
}
input[type="range"]::-webkit-slider-runnable-track {
height: 6px;
border-radius: 999px;
background:
linear-gradient(90deg, rgba(56, 189, 248, 0.78), rgba(56, 189, 248, 0.2));
border: 1px solid rgba(56, 189, 248, 0.16);
}
input[type="range"]::-moz-range-track {
height: 6px;
border-radius: 999px;
background: rgba(56, 189, 248, 0.45);
}
input[type="range"]::-webkit-slider-thumb {
width: 19px;
height: 19px;
margin-top: -8px;
appearance: none;
border: 3px solid #dff6ff;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 16px rgba(56, 189, 248, 0.75);
}
input[type="range"]::-moz-range-thumb {
width: 14px;
height: 14px;
border: 3px solid #dff6ff;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 16px rgba(56, 189, 248, 0.75);
}
.phase-rail {
position: relative;
height: 20px;
margin-top: 1px;
border-bottom: 1px solid rgba(141, 168, 184, 0.15);
}
.phase-rail::before {
content: "";
position: absolute;
left: 0;
right: 0;
bottom: -1px;
height: 2px;
background: linear-gradient(
90deg,
rgba(56, 189, 248, 0.12),
rgba(56, 189, 248, 0.75),
rgba(56, 189, 248, 0.12)
);
}
.phase-marker {
position: absolute;
bottom: -5px;
width: 10px;
height: 10px;
border: 2px solid #dff6ff;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px rgba(56, 189, 248, 0.8);
transform: translateX(-50%);
transition: left 0.12s ease;
}
.rail-labels {
display: flex;
justify-content: space-between;
margin-top: 4px;
color: #6f8b9d;
font-size: 8px;
font-variant-numeric: tabular-nums;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 17px 0 8px;
}
.section-title span {
color: #b5c9d6;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.section-title small {
color: var(--muted);
font-size: 9px;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
min-height: 82px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(4, 13, 21, 0.32);
}
.metric span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric strong {
display: block;
margin-top: 7px;
font-size: 26px;
line-height: 1;
letter-spacing: -0.05em;
font-variant-numeric: tabular-nums;
}
.metric strong.good {
color: var(--green);
}
.metric strong.bad {
color: var(--red);
}
.metric small {
display: block;
margin-top: 5px;
color: #7893a5;
font-size: 9px;
}
.objective {
position: relative;
margin-top: 10px;
padding: 12px;
overflow: hidden;
border: 1px solid rgba(251, 191, 106, 0.22);
border-radius: 14px;
background: rgba(251, 191, 106, 0.065);
transition: 0.25s ease;
}
.objective.complete {
border-color: rgba(80, 227, 164, 0.34);
background: rgba(80, 227, 164, 0.075);
}
.objective-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.objective strong {
font-size: 11px;
}
.objective-score {
color: var(--amber);
font-size: 12px;
font-weight: 800;
font-variant-numeric: tabular-nums;
}
.objective.complete .objective-score {
color: var(--green);
}
.objective p {
margin: 5px 0 9px;
color: var(--muted);
font-size: 9.5px;
line-height: 1.45;
}
.objective-track {
height: 5px;
overflow: hidden;
border-radius: 99px;
background: rgba(255, 255, 255, 0.08);
}
.objective-fill {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--amber), var(--red));
transition: width 0.2s ease, background 0.2s ease;
}
.objective.complete .objective-fill {
background: linear-gradient(90deg, var(--green), var(--cyan));
}
.station-list {
overflow: hidden;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(4, 13, 21, 0.27);
}
.station-row {
padding: 10px 11px;
border-bottom: 1px solid var(--line);
}
.station-row:last-child {
border-bottom: 0;
}
.station-main {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.station-name {
display: flex;
align-items: center;
gap: 7px;
min-width: 0;
}
.station-dot {
width: 7px;
height: 7px;
flex: 0 0 auto;
border-radius: 2px;
background: var(--cyan);
box-shadow: 0 0 8px rgba(56, 189, 248, 0.5);
}
.station-name strong {
font-size: 10.5px;
}
.station-name small {
margin-left: 4px;
color: #698698;
font-size: 8px;
font-weight: 500;
}
.wait-pair {
display: flex;
align-items: center;
gap: 5px;
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.wait-pair .old {
color: #708a9b;
}
.wait-pair .arrow {
color: #456170;
}
.wait-pair .new {
min-width: 30px;
color: var(--cyan);
font-weight: 800;
text-align: right;
}
.station-bars {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
margin-top: 7px;
}
.bar {
height: 3px;
overflow: hidden;
border-radius: 99px;
background: rgba(255, 255, 255, 0.055);
}
.bar i,
.bar b {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
transition: width 0.2s ease;
}
.bar i {
background: #4a6272;
}
.bar b {
background: var(--cyan);
box-shadow: 0 0 8px rgba(56, 189, 248, 0.5);
}
.lock-row {
display: flex;
align-items: center;
gap: 10px;
margin-top: 10px;
padding: 10px 11px;
border: 1px solid rgba(80, 227, 164, 0.16);
border-radius: 12px;
background: rgba(80, 227, 164, 0.045);
}
.lock-icon {
display: grid;
width: 27px;
height: 27px;
place-items: center;
border-radius: 8px;
color: var(--green);
background: rgba(80, 227, 164, 0.11);
font-size: 12px;
}
.lock-row div:nth-child(2) {
flex: 1;
}
.lock-row strong {
display: block;
font-size: 10px;
}
.lock-row small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 8.5px;
}
.lock-row > b {
color: var(--green);
font-size: 8px;
letter-spacing: 0.11em;
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 10px;
}
.actions button,
.camera-actions button {
padding: 10px 11px;
border: 1px solid var(--line);
border-radius: 11px;
background: var(--panel-soft);
color: #c8dce7;
font-size: 10px;
font-weight: 750;
cursor: pointer;
transition: 0.18s ease;
}
.actions button:hover,
.camera-actions button:hover {
border-color: rgba(56, 189, 248, 0.55);
color: var(--cyan);
transform: translateY(-1px);
}
.actions .primary {
border-color: rgba(56, 189, 248, 0.45);
color: #07111b;
background: var(--cyan);
}
.actions .primary:hover {
color: #07111b;
background: #7dd3fc;
}
.scene-footer {
position: fixed;
z-index: 4;
right: 24px;
bottom: 22px;
display: flex;
align-items: flex-end;
gap: 10px;
}
.legend,
.sim-bar,
.camera-actions {
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(9, 21, 31, 0.84);
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.22);
backdrop-filter: blur(13px);
}
.legend {
padding: 12px 14px;
}
.legend-title {
margin-bottom: 8px;
color: #7893a5;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.legend-items {
display: grid;
grid-template-columns: auto auto;
gap: 6px 15px;
font-size: 9px;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
color: #c4d7e2;
}
.legend-line {
width: 17px;
height: 4px;
border-radius: 99px;
background: currentColor;
box-shadow: 0 0 8px currentColor;
}
.sim-bar {
display: flex;
align-items: center;
gap: 9px;
padding: 9px 10px;
}
.play-button {
width: 31px;
height: 31px;
padding: 0;
border: 0;
border-radius: 9px;
color: #07111b;
background: var(--cyan);
font-size: 11px;
font-weight: 900;
cursor: pointer;
}
.clock {
min-width: 52px;
color: #eef8ff;
font-size: 13px;
font-weight: 800;
font-variant-numeric: tabular-nums;
}
.speed-group {
display: flex;
gap: 3px;
}
.speed-group button {
padding: 6px 7px;
border: 0;
border-radius: 7px;
color: #7792a4;
background: transparent;
font-size: 8px;
font-weight: 800;
cursor: pointer;
}
.speed-group button.active {
color: var(--cyan);
background: var(--cyan-soft);
}
.camera-actions {
display: flex;
gap: 4px;
padding: 5px;
}
.camera-actions button {
padding: 8px 9px;
background: transparent;
}
.help {
position: fixed;
z-index: 4;
right: 28px;
top: 78px;
color: rgba(180, 207, 220, 0.58);
font-size: 9px;
letter-spacing: 0.03em;
pointer-events: none;
}
.toast {
position: fixed;
z-index: 20;
left: 50%;
bottom: 28px;
max-width: min(90vw, 460px);
padding: 12px 16px;
border: 1px solid rgba(56, 189, 248, 0.35);
border-radius: 12px;
color: #dff6ff;
background: rgba(9, 25, 37, 0.95);
box-shadow: 0 15px 45px rgba(0, 0, 0, 0.35);
font-size: 11px;
line-height: 1.4;
opacity: 0;
pointer-events: none;
transform: translate(-50%, 15px);
transition: 0.25s ease;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 900px) {
.panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
height: 48vh;
padding: 18px;
border-radius: 18px;
}
h1 {
font-size: 31px;
}
.intro {
font-size: 11px;
}
.scene-footer {
top: 73px;
right: 12px;
bottom: auto;
}
.legend,
.camera-actions {
display: none;
}
.help {
display: none;
}
.brand {
top: 15px;
right: 16px;
}
.brand span {
display: none;
}
}
@media (max-height: 760px) and (min-width: 901px) {
.panel {
padding: 18px;
}
h1 {
font-size: 34px;
}
.intro {
font-size: 11px;
}
.route-card {
margin-top: 12px;
}
.section-title {
margin-top: 12px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel transit network"></canvas>
<div class="vignette"></div>
<header class="brand">
<div class="brand-mark" aria-hidden="true"><i></i><i></i><i></i></div>
<div>
<strong>PHASE / LAB</strong>
<span>Voxel transit puzzle</span>
</div>
</header>
<aside class="panel" aria-label="Transit puzzle controls">
<div class="eyebrow"><span class="signal"></span> Network puzzle / 04</div>
<h1>Shift the clock.<br><em>Not the capacity.</em></h1>
<p class="intro">
Align Cobalt's existing six-minute service pulse with fixed morning
passenger waves. Shift the phase only—never add another departure.
</p>
<div class="route-card">
<div class="route-swatch"></div>
<div>
<strong>Cobalt Line · Adjustable</strong>
<small>6-minute headway · three transfer banks</small>
</div>
<b>1 CONTROL</b>
</div>
<section class="phase-card">
<div class="phase-heading">
<label for="phase">Timetable phase</label>
<strong><span id="phaseValue">+0.00</span> <small>min</small></strong>
</div>
<div class="phase-steps">
<button type="button" id="phaseMinus" aria-label="Decrease phase">−</button>
<button type="button" id="phasePlus" aria-label="Increase phase">+</button>
<button type="button" id="phaseReset" aria-label="Reset phase">↺</button>
</div>
<input
id="phase"
type="range"
min="0"
max="5.75"
step="0.25"
value="0"
aria-label="Cobalt timetable phase"
/>
<div class="phase-rail">
<div class="phase-marker" id="phaseMarker" style="left: 0%"></div>
</div>
<div class="rail-labels">
<span>0</span><span>1.5</span><span>3.0</span><span>4.5</span><span>5.75</span>
</div>
</section>
<div class="section-title">
<span>Transfer comparison</span>
<small>90 peak transfers</small>
</div>
<div class="metric-grid">
<div class="metric">
<span>Weighted wait</span>
<strong id="currentWait">2.57</strong>
<small>minutes per transfer</small>
</div>
<div class="metric">
<span>Change vs baseline</span>
<strong id="waitDelta">0.00</strong>
<small id="deltaNote">Original phase: 0.00 min</small>
</div>
</div>
<section class="objective" id="objectiveCard">
<div class="objective-top">
<strong id="objectiveTitle">Tune the phase</strong>
<span class="objective-score" id="objectiveScore">2.57 / 2.15</span>
</div>
<p id="objectiveCopy">
Reach 2.15 minutes or less without increasing the timetable.
</p>
<div class="objective-track"><div class="objective-fill" id="objectiveFill"></div></div>
</section>
<div class="section-title">
<span>Station waits</span>
<small>baseline → current</small>
</div>
<div class="station-list">
<div class="station-row">
<div class="station-main">
<div class="station-name">
<i class="station-dot"></i>
<strong>Central</strong><small>45 transfers</small>
</div>
<div class="wait-pair">
<span class="old" id="baseCentral">3.00</span>
<span class="arrow">→</span>
<span class="new" id="newCentral">3.00</span>
</div>
</div>
<div class="station-bars">
<div class="bar"><i id="barBaseCentral"></i></div>
<div class="bar"><b id="barNewCentral"></b></div>
</div>
</div>
<div class="station-row">
<div class="station-main">
<div class="station-name">
<i class="station-dot" style="background:#4ade80;box-shadow:0 0 8px rgba(74,222,128,.5)"></i>
<strong>Market</strong><small>21 transfers</small>
</div>
<div class="wait-pair">
<span class="old" id="baseMarket">1.71</span>
<span class="arrow">→</span>
<span class="new" id="newMarket">1.71</span>
</div>
</div>
<div class="station-bars">
<div class="bar"><i id="barBaseMarket"></i></div>
<div class="bar"><b id="barNewMarket"></b></div>
</div>
</div>
<div class="station-row">
<div class="station-main">
<div class="station-name">
<i class="station-dot" style="background:#f472b6;box-shadow:0 0 8px rgba(244,114,182,.5)"></i>
<strong>Harbor</strong><small>24 transfers</small>
</div>
<div class="wait-pair">
<span class="old" id="baseHarbor">2.50</span>
<span class="arrow">→</span>
<span class="new" id="newHarbor">2.50</span>
</div>
</div>
<div class="station-bars">
<div class="bar"><i id="barBaseHarbor"></i></div>
<div class="bar"><b id="barNewHarbor"></b></div>
</div>
</div>
</div>
<div class="lock-row">
<div class="lock-icon">◆</div>
<div>
<strong>30 existing Cobalt departures</strong>
<small>Service count and headway are locked</small>
</div>
<b>LOCKED</b>
</div>
<div class="actions">
<button type="button" id="reveal">Reveal optimum</button>
<button type="button" class="primary" id="baseline">Restore baseline</button>
</div>
</aside>
<div class="help">DRAG TO ORBIT · SCROLL TO ZOOM</div>
<div class="scene-footer">
<div class="legend">
<div class="legend-title">Network services</div>
<div class="legend-items">
<div class="legend-item" style="color:#38bdf8"><i class="legend-line"></i>Cobalt</div>
<div class="legend-item" style="color:#f6ad55"><i class="legend-line"></i>Amber</div>
<div class="legend-item" style="color:#4ade80"><i class="legend-line"></i>Mint</div>
<div class="legend-item" style="color:#f472b6"><i class="legend-line"></i>Rose</div>
</div>
</div>
<div class="sim-bar">
<button class="play-button" id="playPause" aria-label="Pause simulation">Ⅱ</button>
<div class="clock" id="clock">08:30</div>
<div class="speed-group" aria-label="Simulation speed">
<button type="button" data-speed="1">1×</button>
<button type="button" data-speed="4" class="active">4×</button>
<button type="button" data-speed="12">12×</button>
</div>
</div>
<div class="camera-actions">
<button type="button" id="cameraReset">ISO</button>
<button type="button" id="cameraTop">TOP</button>
</div>
</div>
<div class="toast" id="toast" role="status" aria-live="polite"></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Puzzle model
// ------------------------------------------------------------
const HEADWAY = 6;
const TARGET_WAIT = 2.15;
const BEST_PHASE = 3;
const PHASE_MAX = 5.75;
const transferStations = [
{
id: "central",
name: "Central",
position: new THREE.Vector3(-6, 0, -6),
weight: 5,
events: [31, 38, 45, 52, 59, 66, 73, 80, 87],
feederColor: 0xf6ad55
},
{
id: "market",
name: "Market",
position: new THREE.Vector3(3, 0, -4),
weight: 3,
events: [33, 42, 51, 60, 69, 78, 87],
feederColor: 0x4ade80
},
{
id: "harbor",
name: "Harbor",
position: new THREE.Vector3(14, 0, 2),
weight: 4,
events: [35, 46, 57, 68, 79, 90],
feederColor: 0xf472b6
}
];
const routes = [
{
id: "cobalt",
name: "Cobalt",
color: 0x38bdf8,
css: "#38bdf8",
adjustable: true,
headway: 6,
fixedPhase: 0,
duration: 24,
times: [0, 6, 12, 18, 24],
points: [
new THREE.Vector3(-17, 0, -3),
new THREE.Vector3(-6, 0, -6),
new THREE.Vector3(3, 0, -4),
new THREE.Vector3(14, 0, 2),
new THREE.Vector3(18, 0, -8)
]
},
{
id: "amber",
name: "Amber",
color: 0xf6ad55,
css: "#f6ad55",
adjustable: false,
headway: 7,
fixedPhase: 0,
duration: 20,
times: [0, 6, 14, 20],
points: [
new THREE.Vector3(-8, 0, -13),
new THREE.Vector3(-6, 0, -6),
new THREE.Vector3(6, 0, 7),
new THREE.Vector3(12, 0, 13)
]
},
{
id: "mint",
name: "Mint",
color: 0x4ade80,
css: "#4ade80",
adjustable: false,
headway: 9,
fixedPhase: 2,
duration: 21,
times: [0, 7, 14, 21],
points: [
new THREE.Vector3(-17, 0, -3),
new THREE.Vector3(3, 0, -4),
new THREE.Vector3(-1, 0, 11),
new THREE.Vector3(12, 0, 13)
]
},
{
id: "rose",
name: "Rose",
color: 0xf472b6,
css: "#f472b6",
adjustable: false,
headway: 11,
fixedPhase: 4,
duration: 12,
times: [0, 6, 12],
points: [
new THREE.Vector3(-8, 0, -13),
new THREE.Vector3(6, 0, 7),
new THREE.Vector3(14, 0, 2)
]
}
];
const mod = (n, m) => ((n % m) + m) % m;
const clamp = THREE.MathUtils.clamp;
function calculateMetrics(phase) {
let weightedMinutes = 0;
let totalTransfers = 0;
const stations = transferStations.map((station) => {
let waitSum = 0;
for (const event of station.events) {
const wait = mod(phase - event, HEADWAY);
waitSum += wait;
weightedMinutes += wait * station.weight;
totalTransfers += station.weight;
}
return {
...station,
averageWait: waitSum / station.events.length,
transferCount: station.events.length * station.weight
};
});
return {
phase,
stations,
averageWait: weightedMinutes / totalTransfers,
weightedMinutes,
totalTransfers
};
}
const baselineMetrics = calculateMetrics(0);
let currentPhase = 0;
let currentMetrics = baselineMetrics;
// ------------------------------------------------------------
// UI
// ------------------------------------------------------------
const phaseInput = document.getElementById("phase");
const phaseValue = document.getElementById("phaseValue");
const phaseMarker = document.getElementById("phaseMarker");
const currentWaitEl = document.getElementById("currentWait");
const waitDeltaEl = document.getElementById("waitDelta");
const deltaNoteEl = document.getElementById("deltaNote");
const objectiveCard = document.getElementById("objectiveCard");
const objectiveTitle = document.getElementById("objectiveTitle");
const objectiveScore = document.getElementById("objectiveScore");
const objectiveCopy = document.getElementById("objectiveCopy");
const objectiveFill = document.getElementById("objectiveFill");
function setPhase(value, announce = false) {
currentPhase = clamp(Math.round(value * 4) / 4, 0, PHASE_MAX);
currentMetrics = calculateMetrics(currentPhase);
phaseInput.value = String(currentPhase);
updateUI();
if (announce) {
showToast(`Timetable phase set to ${currentPhase.toFixed(2)} minutes. Service count remains fixed at 30.`);
}
}
function updateUI() {
const delta = currentMetrics.averageWait - baselineMetrics.averageWait;
const improvement = (Math.abs(delta) / baselineMetrics.averageWait) * 100;
phaseValue.textContent = `+${currentPhase.toFixed(2)}`;
phaseMarker.style.left = `${(currentPhase / PHASE_MAX) * 100}%`;
currentWaitEl.textContent = currentMetrics.averageWait.toFixed(2);
waitDeltaEl.textContent = `${delta <= 0 ? "−" : "+"}${Math.abs(delta).toFixed(2)}`;
waitDeltaEl.className = delta < -0.001 ? "good" : delta > 0.001 ? "bad" : "";
if (Math.abs(delta) < 0.001) {
deltaNoteEl.textContent = "Original phase: 0.00 min";
} else if (delta < 0) {
deltaNoteEl.textContent = `${improvement.toFixed(0)}% below baseline`;
} else {
deltaNoteEl.textContent = `${improvement.toFixed(0)}% above baseline`;
}
const complete = currentMetrics.averageWait <= TARGET_WAIT;
objectiveCard.classList.toggle("complete", complete);
objectiveTitle.textContent = complete ? "Connection threshold met" : "Tune the phase";
objectiveScore.textContent = `${currentMetrics.averageWait.toFixed(2)} / ${TARGET_WAIT.toFixed(2)}`;
objectiveFill.style.width = `${Math.min(100, (currentMetrics.averageWait / TARGET_WAIT) * 100)}%`;
objectiveCopy.textContent = complete
? "Cobalt’s existing pulse now clears the threshold. No extra services were added."
: "Reach 2.15 minutes or less without increasing the timetable.";
for (const station of currentMetrics.stations) {
const base = baselineMetrics.stations.find((item) => item.id === station.id);
const suffix = station.id[0].toUpperCase() + station.id.slice(1);
document.getElementById(`base${suffix}`).textContent = base.averageWait.toFixed(2);
document.getElementById(`new${suffix}`).textContent = station.averageWait.toFixed(2);
document.getElementById(`barBase${suffix}`).style.width = `${(base.averageWait / HEADWAY) * 100}%`;
document.getElementById(`barNew${suffix}`).style.width = `${(station.averageWait / HEADWAY) * 100}%`;
}
}
phaseInput.addEventListener("input", (event) => setPhase(Number(event.target.value)));
document.getElementById("phaseMinus").addEventListener("click", () => setPhase(currentPhase - 0.25));
document.getElementById("phasePlus").addEventListener("click", () => setPhase(currentPhase + 0.25));
document.getElementById("phaseReset").addEventListener("click", () => setPhase(0));
document.getElementById("baseline").addEventListener("click", () => setPhase(0, true));
document.getElementById("reveal").addEventListener("click", () => {
setPhase(BEST_PHASE, true);
showToast("Optimum found: the 9-minute Market wave locks cleanly onto Cobalt at +3.00 minutes.");
});
let toastTimer;
function showToast(message) {
const toast = document.getElementById("toast");
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 3400);
}
// ------------------------------------------------------------
// Three.js scene
// ------------------------------------------------------------
const canvas = document.getElementById("scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111b);
scene.fog = new THREE.FogExp2(0x07111b, 0.018);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
160
);
const cameraState = {
yaw: 0.57,
pitch: 0.76,
radius: 47,
target: new THREE.Vector3(2.2, 0, 0)
};
function updateCamera() {
const { yaw, pitch, radius, target } = cameraState;
camera.position.set(
target.x + radius * Math.cos(pitch) * Math.sin(yaw),
target.y + radius * Math.sin(pitch),
target.z + radius * Math.cos(pitch) * Math.cos(yaw)
);
camera.lookAt(target);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xbfeaff, 0x10202b, 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xd8f2ff, 3.3);
sun.position.set(-16, 30, 18);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -34;
sun.shadow.camera.right = 34;
sun.shadow.camera.top = 30;
sun.shadow.camera.bottom = -30;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 85;
sun.shadow.bias = -0.0004;
scene.add(sun);
const rimLight = new THREE.PointLight(0x38bdf8, 45, 60, 2);
rimLight.position.set(15, 11, -18);
scene.add(rimLight);
const world = new THREE.Group();
scene.add(world);
function makeBox(width, height, depth, material, x, y, z, parent = world) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(width, height, depth), material);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x0c1d28,
roughness: 0.96,
metalness: 0.04
});
makeBox(52, 0.8, 40, groundMaterial, 1, -0.48, 0);
const grid = new THREE.GridHelper(52, 26, 0x2b4858, 0x193340);
grid.position.set(1, -0.06, 0);
grid.material.transparent = true;
grid.material.opacity = 0.34;
world.add(grid);
const baseBedMaterial = new THREE.MeshStandardMaterial({
color: 0x172833,
roughness: 0.78,
metalness: 0.35
});
const tieMaterial = new THREE.MeshStandardMaterial({
color: 0x2a3d48,
roughness: 0.9
});
function createRoute(route) {
const routeMaterial = new THREE.MeshStandardMaterial({
color: route.color,
emissive: route.color,
emissiveIntensity: route.adjustable ? 0.58 : 0.22,
roughness: 0.38,
metalness: 0.08
});
route.material = routeMaterial;
for (let i = 0; i < route.points.length - 1; i++) {
const a = route.points[i];
const b = route.points[i + 1];
const dx = b.x - a.x;
const dz = b.z - a.z;
const length = Math.hypot(dx, dz);
const angle = Math.atan2(dx, dz);
const midX = (a.x + b.x) / 2;
const midZ = (a.z + b.z) / 2;
const bed = makeBox(1.65, 0.2, length + 0.15, baseBedMaterial, midX, 0.29, midZ);
bed.rotation.y = angle;
const stripe = makeBox(
route.adjustable ? 0.34 : 0.27,
0.12,
length + 0.22,
routeMaterial,
midX,
0.48,
midZ
);
stripe.rotation.y = angle;
const tieCount = Math.floor(length / 1.25);
for (let j = 0; j <= tieCount; j++) {
const t = j / Math.max(1, tieCount);
const tie = makeBox(
1.34,
0.12,
0.17,
tieMaterial,
a.x + dx * t,
0.43,
a.z + dz * t
);
tie.rotation.y = angle;
}
}
}
routes.forEach(createRoute);
// ------------------------------------------------------------
// Voxel city
// ------------------------------------------------------------
let randomSeed = 2048;
function random() {
randomSeed = (randomSeed * 16807) % 2147483647;
return (randomSeed - 1) / 2147483646;
}
function pointSegmentDistance(point, a, b) {
const abx = b.x - a.x;
const abz = b.z - a.z;
const apx = point.x - a.x;
const apz = point.z - a.z;
const lengthSq = abx * abx + abz * abz;
const t = lengthSq === 0 ? 0 : clamp((apx * abx + apz * abz) / lengthSq, 0, 1);
const dx = point.x - (a.x + abx * t);
const dz = point.z - (a.z + abz * t);
return Math.hypot(dx, dz);
}
function distanceToNetwork(point) {
let minimum = Infinity;
for (const route of routes) {
for (let i = 0; i < route.points.length - 1; i++) {
minimum = Math.min(
minimum,
pointSegmentDistance(point, route.points[i], route.points[i + 1])
);
}
}
return minimum;
}
const buildingMaterials = [
new THREE.MeshStandardMaterial({ color: 0x18303e, roughness: 0.86 }),
new THREE.MeshStandardMaterial({ color: 0x1c3746, roughness: 0.8 }),
new THREE.MeshStandardMaterial({ color: 0x142a38, roughness: 0.92 }),
new THREE.MeshStandardMaterial({ color: 0x214050, roughness: 0.76 })
];
const roofMaterial = new THREE.MeshStandardMaterial({
color: 0x294758,
roughness: 0.74,
metalness: 0.08
});
const windowMaterial = new THREE.MeshStandardMaterial({
color: 0x8edcf5,
emissive: 0x3ca7ca,
emissiveIntensity: 0.75,
roughness: 0.35
});
for (let x = -20; x <= 21; x += 4) {
for (let z = -15; z <= 15; z += 4) {
const point = new THREE.Vector3(x + (random() - 0.5) * 1.5, 0, z + (random() - 0.5) * 1.5);
if (distanceToNetwork(point) < 2.35) continue;
if (Math.abs(point.x - 2.2) < 3 && Math.abs(point.z) < 3) continue;
if (random() < 0.16) continue;
const width = 1.35 + random() * 1.65;
const depth = 1.25 + random() * 1.7;
const height = 1.1 + Math.pow(random(), 1.8) * 5.8;
const material = buildingMaterials[Math.floor(random() * buildingMaterials.length)];
makeBox(width, height, depth, material, point.x, height / 2, point.z);
if (random() > 0.32) {
makeBox(
width * 0.62,
0.3 + random() * 0.55,
depth * 0.62,
roofMaterial,
point.x,
height + 0.2,
point.z
);
}
if (height > 2.5 && random() > 0.35) {
const windowRows = Math.min(3, Math.floor(height / 1.6));
for (let row = 0; row < windowRows; row++) {
makeBox(
width * 0.54,
0.1,
0.035,
windowMaterial,
point.x,
0.8 + row * 1.1,
point.z + depth / 2 + 0.025
);
}
}
}
}
// Small green voxel parks.
const parkMaterial = new THREE.MeshStandardMaterial({
color: 0x1e493a,
roughness: 0.95
});
const treeTrunkMaterial = new THREE.MeshStandardMaterial({ color: 0x604632 });
const treeTopMaterial = new THREE.MeshStandardMaterial({ color: 0x347a4d });
[[-12, 8], [10, -11], [15, 10]].forEach(([x, z]) => {
makeBox(3.4, 0.18, 2.6, parkMaterial, x, 0.02, z);
for (let i = 0; i < 3; i++) {
const tx = x + (i - 1) * 0.95;
makeBox(0.22, 0.8, 0.22, treeTrunkMaterial, tx, 0.42, z);
makeBox(0.9, 0.9, 0.9, treeTopMaterial, tx, 1.05, z);
}
});
// ------------------------------------------------------------
// Stations and labels
// ------------------------------------------------------------
const stationDefinitions = [
{ name: "West", position: new THREE.Vector3(-17, 0, -3) },
{ name: "North", position: new THREE.Vector3(-8, 0, -13) },
{ name: "Central", position: new THREE.Vector3(-6, 0, -6) },
{ name: "Market", position: new THREE.Vector3(3, 0, -4) },
{ name: "Stadium", position: new THREE.Vector3(6, 0, 7) },
{ name: "Harbor", position: new THREE.Vector3(14, 0, 2) },
{ name: "Hill", position: new THREE.Vector3(-1, 0, 11) },
{ name: "South", position: new THREE.Vector3(12, 0, 13) },
{ name: "East", position: new THREE.Vector3(18, 0, -8) }
];
const platformMaterial = new THREE.MeshStandardMaterial({
color: 0xb5cbd5,
roughness: 0.82
});
const platformSideMaterial = new THREE.MeshStandardMaterial({
color: 0x253d4b,
roughness: 0.8
});
function roundedRect(ctx, x, y, width, height, radius) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
}
function createLabel(text, color = "#cfeaf5") {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 128;
const ctx = labelCanvas.getContext("2d");
ctx.clearRect(0, 0, 512, 128);
roundedRect(ctx, 8, 18, 496, 88, 18);
ctx.fillStyle = "rgba(6, 17, 26, 0.88)";
ctx.fill();
ctx.strokeStyle = color;
ctx.globalAlpha = 0.45;
ctx.lineWidth = 3;
ctx.stroke();
ctx.globalAlpha = 1;
ctx.fillStyle = color;
ctx.font = "800 37px Inter, system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text.toUpperCase(), 256, 63);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(5.5, 1.38, 1);
sprite.renderOrder = 20;
return sprite;
}
for (const station of stationDefinitions) {
const matchingRoutes = routes.filter((route) =>
route.points.some((point) => point.distanceToSquared(station.position) < 0.01)
);
const group = new THREE.Group();
group.position.copy(station.position);
world.add(group);
makeBox(2.35, 0.34, 2.35, platformSideMaterial, 0, 0.45, 0, group);
makeBox(2.05, 0.16, 2.05, platformMaterial, 0, 0.69, 0, group);
matchingRoutes.forEach((route, index) => {
const beaconMaterial = new THREE.MeshStandardMaterial({
color: route.color,
emissive: route.color,
emissiveIntensity: route.adjustable ? 0.9 : 0.4,
roughness: 0.35
});
const offset = (index - (matchingRoutes.length - 1) / 2) * 0.42;
makeBox(0.19, 0.82, 0.19, beaconMaterial, offset, 1.16, -0.7, group);
});
const transferStation = transferStations.find((item) => item.id === station.name.toLowerCase());
const labelColor = transferStation ? "#ffffff" : "#9fc2d2";
const label = createLabel(station.name, labelColor);
label.position.set(station.position.x, 2.75, station.position.z);
world.add(label);
}
// ------------------------------------------------------------
// Trains
// ------------------------------------------------------------
const trainWindowMaterial = new THREE.MeshStandardMaterial({
color: 0x10212b,
emissive: 0x173f50,
emissiveIntensity: 0.45,
roughness: 0.3
});
const trainRoofMaterial = new THREE.MeshStandardMaterial({
color: 0xe4f1f5,
roughness: 0.62
});
function createTrain(route) {
const group = new THREE.Group();
const body = makeBox(0.76, 0.58, 1.35, route.material, 0, 0, 0, group);
body.castShadow = true;
makeBox(0.64, 0.27, 0.56, trainWindowMaterial, 0, 0.12, 0.69, group);
makeBox(0.64, 0.27, 0.56, trainWindowMaterial, 0, 0.12, -0.69, group);
makeBox(0.53, 0.13, 0.8, trainRoofMaterial, 0, 0.37, 0, group);
const lightMaterial = new THREE.MeshBasicMaterial({ color: 0xf5fdff });
makeBox(0.22, 0.12, 0.04, lightMaterial, 0, -0.08, 0.71, group);
world.add(group);
return group;
}
for (const route of routes) {
route.trains = [];
for (let i = 0; i < 6; i++) {
route.trains.push(createTrain(route));
}
}
function sampleRoute(route, elapsed) {
const time = clamp(elapsed, 0, route.duration);
let segment = 0;
while (
segment < route.times.length - 2 &&
time > route.times[segment + 1]
) {
segment++;
}
const startTime = route.times[segment];
const endTime = route.times[segment + 1];
const start = route.points[segment];
const end = route.points[segment + 1];
const fraction = clamp((time - startTime) / (endTime - startTime), 0, 1);
return {
position: new THREE.Vector3().lerpVectors(start, end, fraction),
angle: Math.atan2(end.x - start.x, end.z - start.z)
};
}
function updateTrains(simTime) {
for (const route of routes) {
const routePhase = route.adjustable ? currentPhase : route.fixedPhase;
const firstDeparture = Math.ceil((simTime - routePhase - route.duration) / route.headway);
const lastDeparture = Math.floor((simTime - routePhase) / route.headway);
route.trains.forEach((train) => (train.visible = false));
let trainIndex = 0;
for (let departure = firstDeparture; departure <= lastDeparture; departure++) {
const elapsed = simTime - (routePhase + departure * route.headway);
if (elapsed < 0 || elapsed > route.duration) continue;
const train = route.trains[trainIndex++ % route.trains.length];
const sample = sampleRoute(route, elapsed);
train.visible = true;
train.position.set(sample.position.x, 0.98, sample.position.z);
train.rotation.y = sample.angle;
}
}
}
// ------------------------------------------------------------
// Transfer-wave pulses
// ------------------------------------------------------------
const pulses = [];
function createPulse(station) {
const material = new THREE.MeshBasicMaterial({
color: station.feederColor,
transparent: true,
opacity: 0.9,
depthWrite: false
});
const ring = new THREE.Mesh(new THREE.TorusGeometry(0.72, 0.055, 6, 24), material);
ring.rotation.x = Math.PI / 2;
ring.position.copy(station.position);
ring.position.y = 0.83;
world.add(ring);
pulses.push({ mesh: ring, age: 0 });
}
function eventCrossed(previous, current, event) {
const a = mod(previous - event, 120);
const b = mod(current - event, 120);
return b < a;
}
// ------------------------------------------------------------
// Camera controls, implemented without addons
// ------------------------------------------------------------
const pointers = new Map();
let previousPinchDistance = 0;
canvas.addEventListener("pointerdown", (event) => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
previousPinchDistance = Math.hypot(a.x - b.x, a.y - b.y);
}
});
canvas.addEventListener("pointermove", (event) => {
if (!pointers.has(event.pointerId)) return;
const previous = pointers.get(event.pointerId);
const current = { x: event.clientX, y: event.clientY };
pointers.set(event.pointerId, current);
if (pointers.size === 1) {
cameraState.yaw -= (current.x - previous.x) * 0.006;
cameraState.pitch = clamp(
cameraState.pitch + (current.y - previous.y) * 0.0045,
0.22,
1.48
);
updateCamera();
} else if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
const distance = Math.hypot(a.x - b.x, a.y - b.y);
if (previousPinchDistance > 0) {
cameraState.radius = clamp(
cameraState.radius * (previousPinchDistance / distance),
23,
72
);
updateCamera();
}
previousPinchDistance = distance;
}
});
function releasePointer(event) {
pointers.delete(event.pointerId);
previousPinchDistance = 0;
}
canvas.addEventListener("pointerup", releasePointer);
canvas.addEventListener("pointercancel", releasePointer);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = clamp(
cameraState.radius * (1 + Math.sign(event.deltaY) * 0.09),
23,
72
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", () => {
cameraState.yaw = 0.57;
cameraState.pitch = 0.76;
cameraState.radius = 47;
updateCamera();
});
document.getElementById("cameraReset").addEventListener("click", () => {
cameraState.yaw = 0.57;
cameraState.pitch = 0.76;
cameraState.radius = 47;
updateCamera();
});
document.getElementById("cameraTop").addEventListener("click", () => {
cameraState.yaw = 0;
cameraState.pitch = 1.46;
cameraState.radius = 49;
updateCamera();
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
// ------------------------------------------------------------
// Simulation controls
// ------------------------------------------------------------
let simulationTime = 30.8;
let simulationSpeed = 4;
let simulationRunning = true;
const clockEl = document.getElementById("clock");
const playPause = document.getElementById("playPause");
playPause.addEventListener("click", () => {
simulationRunning = !simulationRunning;
playPause.textContent = simulationRunning ? "Ⅱ" : "▶";
playPause.setAttribute(
"aria-label",
simulationRunning ? "Pause simulation" : "Play simulation"
);
});
document.querySelectorAll("[data-speed]").forEach((button) => {
button.addEventListener("click", () => {
simulationSpeed = Number(button.dataset.speed);
document.querySelectorAll("[data-speed]").forEach((item) => {
item.classList.toggle("active", item === button);
});
});
});
function updateClock() {
const totalMinutes = 8 * 60 + Math.floor(simulationTime);
const hours = Math.floor(totalMinutes / 60) % 24;
const minutes = totalMinutes % 60;
clockEl.textContent = `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}`;
}
// ------------------------------------------------------------
// Animation loop
// ------------------------------------------------------------
const clock = new THREE.Clock();
let previousSimulationTime = simulationTime;
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
previousSimulationTime = simulationTime;
if (simulationRunning) {
simulationTime = mod(simulationTime + delta * simulationSpeed, 120);
for (const station of transferStations) {
for (const event of station.events) {
if (eventCrossed(previousSimulationTime, simulationTime, event)) {
createPulse(station);
}
}
}
}
updateTrains(simulationTime);
updateClock();
for (let i = pulses.length - 1; i >= 0; i--) {
const pulse = pulses[i];
pulse.age += delta;
const scale = 1 + pulse.age * 2.8;
pulse.mesh.scale.setScalar(scale);
pulse.mesh.material.opacity = Math.max(0, 0.9 - pulse.age * 0.9);
if (pulse.age > 1) {
world.remove(pulse.mesh);
pulse.mesh.geometry.dispose();
pulse.mesh.material.dispose();
pulses.splice(i, 1);
}
}
renderer.render(scene, camera);
}
updateUI();
updateTrains(simulationTime);
updateClock();
animate();
</script>
</body>
</html>
```