Prompt specification
Build or customize the Three.js 3D scene "Dwell Variability and Bus Bunching Toy Model" 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: Dwell Variability and Bus Bunching Toy Model
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/dwell-variability-and-bus-bunching-toy-model-x2088
Scene Description Prompt:
Compare voxel buses with constant and varying fictional boarding times; track headways and bunching in the stated toy model. Three.js from cdnjs, standalone HTML.
Working Three.js Starter (dwell-variability-and-bus-bunching-toy-model-x2088):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Voxel Transit Lab — Headway & Bunching</title>
<style>
:root {
color-scheme: dark;
--bg: #071019;
--panel: #0d1723;
--panel-2: #111e2c;
--line: #203246;
--text: #e9f3fb;
--muted: #8da2b5;
--cyan: #58dcff;
--cyan-soft: rgba(88, 220, 255, .12);
--coral: #ff826f;
--coral-soft: rgba(255, 130, 111, .12);
--green: #70e1a5;
--amber: #ffc66d;
--red: #ff657a;
}
* { 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;
border: 1px solid var(--line);
background: #142233;
border-radius: 9px;
cursor: pointer;
transition: border-color .18s, background .18s, transform .18s;
}
button:hover {
border-color: #3b5873;
background: #192b3e;
}
button:active { transform: translateY(1px); }
#app {
width: 100%;
height: 100%;
display: grid;
grid-template-rows: 72px minmax(0, 1fr);
background:
radial-gradient(circle at 50% -20%, rgba(52, 104, 145, .18), transparent 42%),
var(--bg);
}
header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
padding: 0 22px;
border-bottom: 1px solid var(--line);
background: rgba(8, 17, 27, .9);
backdrop-filter: blur(16px);
z-index: 10;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
width: 38px;
height: 38px;
display: grid;
place-items: center;
border: 1px solid #31516b;
border-radius: 11px;
background: linear-gradient(145deg, #18364a, #0d1b29);
box-shadow: inset 0 0 20px rgba(88, 220, 255, .07);
}
.brand-mark::before {
content: "";
width: 19px;
height: 9px;
border-radius: 2px;
background: var(--cyan);
box-shadow:
0 -4px 0 -1px #d8f7ff,
0 4px 0 -2px #0b1520,
5px 4px 0 -3px #0b1520;
transform: translateY(-1px);
}
h1 {
margin: 0;
font-size: 17px;
line-height: 1.1;
letter-spacing: .01em;
}
.subtitle {
margin-top: 4px;
color: var(--muted);
font-size: 11px;
letter-spacing: .08em;
text-transform: uppercase;
}
.header-actions {
display: flex;
align-items: center;
gap: 9px;
}
.header-actions button {
height: 36px;
padding: 0 13px;
font-size: 12px;
font-weight: 700;
}
.primary {
border-color: #32728a;
background: #143b4c;
color: #bff5ff;
}
.clock {
min-width: 78px;
padding: 8px 10px;
border: 1px solid var(--line);
border-radius: 8px;
color: #b9cad8;
background: #0a141f;
font: 600 12px ui-monospace, SFMono-Regular, Menlo, monospace;
text-align: center;
}
main {
min-height: 0;
display: grid;
grid-template-columns: 264px minmax(480px, 1fr) 306px;
gap: 12px;
padding: 12px;
}
.panel,
.workspace,
.chart-panel {
border: 1px solid var(--line);
border-radius: 14px;
background: linear-gradient(180deg, rgba(16, 29, 43, .98), rgba(10, 20, 31, .98));
box-shadow: 0 18px 55px rgba(0, 0, 0, .18);
}
.controls-panel,
.metrics-panel {
min-height: 0;
overflow: auto;
scrollbar-width: thin;
scrollbar-color: #294057 transparent;
}
.panel-section {
padding: 16px;
border-bottom: 1px solid var(--line);
}
.panel-section:last-child { border-bottom: 0; }
.eyebrow {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: .13em;
text-transform: uppercase;
}
h2 {
margin: 5px 0 10px;
font-size: 16px;
}
h3 {
margin: 0;
font-size: 13px;
}
p {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.scenario-list {
display: grid;
gap: 8px;
margin-top: 14px;
}
.scenario-row {
display: grid;
grid-template-columns: 10px 1fr;
gap: 10px;
align-items: start;
padding: 10px;
border: 1px solid #1c3043;
border-radius: 9px;
background: rgba(4, 10, 16, .28);
}
.dot {
width: 8px;
height: 8px;
margin-top: 4px;
border-radius: 50%;
}
.dot.cyan {
background: var(--cyan);
box-shadow: 0 0 10px rgba(88, 220, 255, .55);
}
.dot.coral {
background: var(--coral);
box-shadow: 0 0 10px rgba(255, 130, 111, .55);
}
.scenario-row strong {
display: block;
margin-bottom: 3px;
font-size: 12px;
}
.scenario-row span:last-child {
display: block;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.control { margin-top: 16px; }
.control-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 9px;
font-size: 12px;
}
.control-head output {
color: var(--cyan);
font: 700 12px ui-monospace, SFMono-Regular, Menlo, monospace;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
border-radius: 10px;
outline: none;
background: #25394c;
appearance: none;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
border: 2px solid #0b1723;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 0 1px #3c7388;
cursor: pointer;
appearance: none;
}
input[type="range"]::-moz-range-thumb {
width: 13px;
height: 13px;
border: 2px solid #0b1723;
border-radius: 50%;
background: var(--cyan);
cursor: pointer;
}
.range-ends {
display: flex;
justify-content: space-between;
margin-top: 7px;
color: #61788c;
font-size: 9px;
text-transform: uppercase;
letter-spacing: .07em;
}
.segmented {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 5px;
}
.segmented button {
height: 32px;
font-size: 11px;
font-weight: 700;
}
.segmented button.active {
border-color: #3c829b;
background: #173b4b;
color: #c6f7ff;
}
.toggle {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 8px 0;
color: #b6c6d4;
font-size: 12px;
cursor: pointer;
}
.toggle input {
width: 16px;
height: 16px;
accent-color: var(--cyan);
}
details summary {
color: #d7e5ef;
font-size: 12px;
font-weight: 700;
cursor: pointer;
}
details p,
details ul {
margin: 10px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
details ul {
padding-left: 17px;
}
code {
color: #b8eaf4;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
}
.workspace {
min-width: 0;
min-height: 0;
display: grid;
grid-template-rows: minmax(320px, 1fr) 218px;
overflow: hidden;
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 42%, rgba(32, 64, 86, .23), transparent 48%),
#08121c;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#stage canvas:active { cursor: grabbing; }
.stage-toolbar {
position: absolute;
z-index: 4;
top: 13px;
left: 13px;
right: 13px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
pointer-events: none;
}
.stage-title {
padding: 9px 11px;
border: 1px solid rgba(48, 75, 96, .75);
border-radius: 9px;
background: rgba(7, 15, 24, .76);
backdrop-filter: blur(10px);
}
.stage-title strong {
display: block;
font-size: 11px;
}
.stage-title span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
}
.camera-buttons {
display: flex;
gap: 5px;
pointer-events: auto;
}
.camera-buttons button {
height: 29px;
padding: 0 9px;
background: rgba(9, 20, 31, .82);
font-size: 10px;
}
.stage-legend {
position: absolute;
z-index: 4;
left: 13px;
bottom: 13px;
display: flex;
flex-wrap: wrap;
gap: 8px;
max-width: calc(100% - 26px);
pointer-events: none;
}
.legend-chip {
display: flex;
align-items: center;
gap: 6px;
padding: 7px 9px;
border: 1px solid rgba(48, 75, 96, .65);
border-radius: 8px;
background: rgba(7, 15, 24, .75);
color: #b7c8d6;
font-size: 9px;
backdrop-filter: blur(8px);
}
.legend-chip .dot { margin: 0; }
#loading {
position: absolute;
z-index: 20;
inset: 0;
display: grid;
place-items: center;
background: #08121c;
color: var(--muted);
font-size: 12px;
letter-spacing: .1em;
text-transform: uppercase;
}
#loading.hidden { display: none; }
.chart-panel {
min-width: 0;
padding: 13px 15px 10px;
border: 0;
border-top: 1px solid var(--line);
border-radius: 0;
box-shadow: none;
}
.chart-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
margin-bottom: 8px;
}
.chart-title strong {
display: block;
font-size: 12px;
}
.chart-title span {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.chart-tabs {
display: flex;
gap: 4px;
}
.chart-tabs button {
height: 27px;
padding: 0 9px;
font-size: 9px;
}
.chart-tabs button.active {
border-color: #3b7187;
background: #173746;
color: #c7f4ff;
}
#chart {
display: block;
width: 100%;
height: 144px;
}
.metrics-panel { overflow: hidden; }
.metric-intro {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.live-badge {
display: flex;
align-items: center;
gap: 5px;
color: var(--green);
font-size: 9px;
font-weight: 800;
letter-spacing: .1em;
text-transform: uppercase;
}
.live-badge::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 9px rgba(112, 225, 165, .75);
}
.metric-card {
position: relative;
overflow: hidden;
margin-top: 11px;
padding: 13px;
border: 1px solid #20364a;
border-radius: 11px;
background: #0b1723;
}
.metric-card::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 3px;
height: 100%;
background: var(--cyan);
}
.metric-card.variable::before { background: var(--coral); }
.metric-card-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.metric-card-head strong {
font-size: 11px;
}
.state-pill {
padding: 4px 7px;
border-radius: 999px;
background: var(--cyan-soft);
color: var(--cyan);
font-size: 8px;
font-weight: 800;
text-transform: uppercase;
letter-spacing: .07em;
}
.variable .state-pill {
background: var(--coral-soft);
color: var(--coral);
}
.primary-metric {
display: flex;
align-items: baseline;
gap: 7px;
margin: 13px 0 11px;
}
.primary-metric span {
font: 750 30px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: -.05em;
}
.primary-metric small {
color: var(--muted);
font-size: 10px;
}
.mini-metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.mini-metric {
padding: 8px;
border: 1px solid #1b3043;
border-radius: 8px;
background: rgba(16, 31, 45, .55);
}
.mini-metric span {
display: block;
color: var(--muted);
font-size: 8px;
text-transform: uppercase;
letter-spacing: .08em;
}
.mini-metric strong {
display: block;
margin-top: 4px;
font: 700 12px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.comparison-box {
margin-top: 12px;
padding: 13px;
border: 1px solid #20364a;
border-radius: 11px;
background: #0b1723;
}
.meter-row {
margin-top: 10px;
}
.meter-label {
display: flex;
justify-content: space-between;
gap: 8px;
margin-bottom: 5px;
color: #a9bbca;
font-size: 9px;
}
.meter {
height: 5px;
overflow: hidden;
border-radius: 10px;
background: #203346;
}
.meter > div {
width: 0;
height: 100%;
border-radius: inherit;
transition: width .25s;
}
#constantBar { background: var(--cyan); }
#variableBar { background: var(--coral); }
.comparison-copy {
margin-top: 12px;
padding-top: 11px;
border-top: 1px solid #1c3043;
color: #b9c9d6;
font-size: 11px;
line-height: 1.5;
}
.events {
display: grid;
gap: 7px;
margin-top: 10px;
}
.event {
display: grid;
grid-template-columns: 25px 1fr auto;
gap: 8px;
align-items: center;
padding: 8px;
border: 1px solid #1b3043;
border-radius: 8px;
background: rgba(7, 15, 23, .45);
font-size: 9px;
}
.event-id {
display: grid;
place-items: center;
width: 24px;
height: 24px;
border-radius: 6px;
background: var(--cyan-soft);
color: var(--cyan);
font-weight: 800;
}
.event.variable .event-id {
background: var(--coral-soft);
color: var(--coral);
}
.event strong {
display: block;
margin-bottom: 2px;
color: #d9e6ef;
font-size: 10px;
}
.event span {
color: var(--muted);
}
.event-gap {
color: #dce8f1;
font: 700 10px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.event-gap.close { color: var(--red); }
.footnote {
padding: 12px 16px 16px;
color: #64798c;
font-size: 9px;
line-height: 1.5;
}
@media (max-width: 1120px) {
html, body { overflow: auto; }
#app { height: auto; min-height: 100%; }
main {
grid-template-columns: 240px minmax(0, 1fr);
align-items: start;
}
.workspace { height: 720px; }
.metrics-panel {
grid-column: 1 / -1;
display: grid;
grid-template-columns: 1fr 1fr;
overflow: visible;
}
.metrics-panel .panel-section { border-right: 1px solid var(--line); }
}
@media (max-width: 760px) {
header { padding: 0 12px; }
.subtitle { display: none; }
.header-actions .reset-button { display: none; }
main {
display: block;
padding: 8px;
}
.controls-panel,
.metrics-panel {
margin-bottom: 8px;
}
.workspace { height: 680px; }
.metrics-panel { display: block; }
.camera-buttons { display: none; }
}
</style>
</head>
<body>
<div id="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>Voxel Transit Lab</h1>
<div class="subtitle">Headway stability under variable boarding</div>
</div>
</div>
<div class="header-actions">
<div class="clock" id="clock">T+ 00:00</div>
<button id="resetButton" class="reset-button">Reset</button>
<button id="playButton" class="primary">Pause</button>
</div>
</header>
<main>
<aside class="panel controls-panel">
<section class="panel-section">
<div class="eyebrow">Comparison</div>
<h2>Same route, different clocks</h2>
<p>
Eight buses circulate around an eight-stop toy loop. Compare a
constant boarding clock with a load-sensitive, stochastic clock.
</p>
<div class="scenario-list">
<div class="scenario-row">
<i class="dot cyan"></i>
<div>
<strong>Constant boarding</strong>
<span>Every bus receives the same 15-second boarding time.</span>
</div>
</div>
<div class="scenario-row">
<i class="dot coral"></i>
<div>
<strong>Varying boarding</strong>
<span>Boarding time changes with crowding, randomness, and rare surges.</span>
</div>
</div>
</div>
</section>
<section class="panel-section">
<div class="eyebrow">Experiment</div>
<div class="control">
<div class="control-head">
<label for="variability">Boarding variability</label>
<output id="variabilityOut">82%</output>
</div>
<input id="variability" type="range" min="0" max="100" value="82" />
<div class="range-ends">
<span>Fixed</span>
<span>Volatile</span>
</div>
</div>
<div class="control">
<div class="control-head">
<label for="demand">Boarding demand</label>
<output id="demandOut">58%</output>
</div>
<input id="demand" type="range" min="0" max="100" value="58" />
<div class="range-ends">
<span>Light</span>
<span>Heavy</span>
</div>
</div>
<div class="control">
<div class="control-head"><span>Simulation speed</span></div>
<div class="segmented" id="speedButtons">
<button data-speed="1" class="active">1×</button>
<button data-speed="2">2×</button>
<button data-speed="4">4×</button>
</div>
</div>
</section>
<section class="panel-section">
<div class="eyebrow">Display</div>
<label class="toggle">
Stop labels
<input id="labelsToggle" type="checkbox" checked />
</label>
<label class="toggle">
Live headway bubbles
<input id="bubblesToggle" type="checkbox" checked />
</label>
</section>
<section class="panel-section">
<details open>
<summary>Toy model & metrics</summary>
<ul>
<li>8 buses, 8 stops, one-way loop.</li>
<li>Segment run: 14 s ± 2 s, with matched random draws in both worlds.</li>
<li>Constant boarding/dwell: exactly 15 s.</li>
<li>
Varying dwell:
<code>d = clip(15 × [1 + v(f − 1)], 4, 45)</code>
</li>
<li>
<code>f = 0.42 + 1.10L + 0.46ε + 0.42S</code>,
where L is post-boarding load ratio, ε ∈ [−0.5, 0.5],
and S is a 12% surge flag.
</li>
<li>Reference headway: 30 s.</li>
<li>A close gap is below 16.5 s, or 55% of reference.</li>
<li>Bunching index = share of recent gaps classified as close.</li>
</ul>
</details>
</section>
</aside>
<section class="workspace">
<div id="stage">
<div id="loading">Building voxel transit lab…</div>
<div class="stage-toolbar">
<div class="stage-title">
<strong>Paired-network laboratory</strong>
<span>Drag to orbit · wheel to zoom · shift-drag to pan</span>
</div>
<div class="camera-buttons">
<button data-focus="overview">Overview</button>
<button data-focus="constant">Constant</button>
<button data-focus="variable">Varying</button>
</div>
</div>
<div class="stage-legend">
<div class="legend-chip"><i class="dot cyan"></i> Constant boarding</div>
<div class="legend-chip"><i class="dot coral"></i> Varying boarding</div>
<div class="legend-chip">Stop badge = latest arrival gap</div>
</div>
</div>
<div class="chart-panel">
<div class="chart-head">
<div class="chart-title">
<strong id="chartTitle">Arrival headway</strong>
<span id="chartSubtitle">Rolling mean of recent stop-arrival gaps</span>
</div>
<div class="chart-tabs" id="chartTabs">
<button data-chart="headway" class="active">Headway</button>
<button data-chart="dwell">Boarding time</button>
</div>
</div>
<canvas id="chart"></canvas>
</div>
</section>
<aside class="panel metrics-panel">
<section class="panel-section">
<div class="metric-intro">
<div>
<div class="eyebrow">Live diagnostics</div>
<h2>Headway & bunching</h2>
</div>
<div class="live-badge">Live</div>
</div>
<div class="metric-card">
<div class="metric-card-head">
<strong>Constant boarding</strong>
<span class="state-pill" id="constantState">Stable</span>
</div>
<div class="primary-metric">
<span id="constantMean">—</span>
<small>s mean gap</small>
</div>
<div class="mini-metrics">
<div class="mini-metric">
<span>Headway CV</span>
<strong id="constantCV">—</strong>
</div>
<div class="mini-metric">
<span>Bunching index</span>
<strong id="constantBunch">—</strong>
</div>
<div class="mini-metric">
<span>Mean boarding</span>
<strong id="constantDwell">—</strong>
</div>
<div class="mini-metric">
<span>Recent span</span>
<strong id="constantSpan">—</strong>
</div>
</div>
</div>
<div class="metric-card variable">
<div class="metric-card-head">
<strong>Varying boarding</strong>
<span class="state-pill" id="variableState">Stable</span>
</div>
<div class="primary-metric">
<span id="variableMean">—</span>
<small>s mean gap</small>
</div>
<div class="mini-metrics">
<div class="mini-metric">
<span>Headway CV</span>
<strong id="variableCV">—</strong>
</div>
<div class="mini-metric">
<span>Bunching index</span>
<strong id="variableBunch">—</strong>
</div>
<div class="mini-metric">
<span>Mean boarding</span>
<strong id="variableDwell">—</strong>
</div>
<div class="mini-metric">
<span>Recent span</span>
<strong id="variableSpan">—</strong>
</div>
</div>
</div>
</section>
<section class="panel-section">
<div class="eyebrow">Comparison</div>
<h2>Close-gap frequency</h2>
<div class="meter-row">
<div class="meter-label">
<span>Constant</span>
<strong id="constantBunchLabel">0%</strong>
</div>
<div class="meter"><div id="constantBar"></div></div>
</div>
<div class="meter-row">
<div class="meter-label">
<span>Varying</span>
<strong id="variableBunchLabel">0%</strong>
</div>
<div class="meter"><div id="variableBar"></div></div>
</div>
<div class="comparison-copy" id="comparisonCopy">
Collecting arrival gaps…
</div>
</section>
<section class="panel-section">
<div class="eyebrow">Arrival log</div>
<h2>Latest observations</h2>
<div class="events" id="eventLog">
<div class="event">
<div class="event-id">—</div>
<div><strong>Waiting for arrivals</strong><span>Simulation is warming up</span></div>
<div class="event-gap">—</div>
</div>
</div>
</section>
<div class="footnote">
This is a deterministic toy model, not an empirical service forecast.
Both networks receive the same demand sequence and matched segment-run
noise so that boarding-time variation is the principal intervention.
</div>
</aside>
</main>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
/* -------------------------------------------------------------------------- */
/* Constants and deterministic utilities */
/* -------------------------------------------------------------------------- */
const STOPS = 8;
const BUSES = 8;
const CAPACITY = 55;
const TRAVEL = 14;
const DWELL = 15;
const SEGMENT_TIME = TRAVEL + DWELL;
const REFERENCE_HEADWAY = 30;
const CLOSE_GAP = REFERENCE_HEADWAY * 0.55;
const COLORS = {
constant: 0x58dcff,
variable: 0xff826f,
road: 0x172535,
city: 0x17283a,
window: 0x8cecff
};
const params = {
variability: 0.82,
demand: 0.58
};
const clamp = (x, lo, hi) => Math.max(lo, Math.min(hi, x));
const mean = values =>
values.length ? values.reduce((sum, x) => sum + x, 0) / values.length : 0;
function stdDev(values) {
if (values.length < 2) return 0;
const m = mean(values);
return Math.sqrt(
values.reduce((sum, x) => sum + (x - m) ** 2, 0) / values.length
);
}
function hash01(a, b = 0, c = 0) {
let h = Math.imul(a + 101, 374761393);
h = Math.imul(h ^ Math.imul(b + 17, 668265263), 1274126177);
h ^= Math.imul(c + 31, 2246822519);
h = Math.imul(h ^ (h >>> 13), 3266489917);
return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
}
function formatClock(seconds) {
const s = Math.floor(seconds);
return `T+ ${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}`;
}
/* -------------------------------------------------------------------------- */
/* Toy simulation */
/* -------------------------------------------------------------------------- */
class ToySimulation {
constructor(mode) {
this.mode = mode;
this.time = 0;
this.sampleClock = 0;
this.gaps = [];
this.dwellSamples = [];
this.events = [];
this.lastArrival = Array(STOPS).fill(TRAVEL - SEGMENT_TIME);
this.lastGap = Array(STOPS).fill(null);
this.history = [
{ t: 0, gap: SEGMENT_TIME, dwell: DWELL }
];
this.buses = Array.from({ length: BUSES }, (_, id) => ({
id,
state: "moving",
currentStop: id,
progress: 0,
travelDuration: TRAVEL + (hash01(id, 0, 91) - 0.5) * 4,
stopTimer: 0,
dwell: DWELL,
load: 7 + Math.floor(hash01(id, 3, 7) * 8),
visit: 0
}));
}
update(dt) {
this.time += dt;
for (const bus of this.buses) {
if (bus.state === "moving") {
bus.progress += dt / bus.travelDuration;
if (bus.progress >= 1) {
bus.progress = 0;
bus.currentStop = (bus.currentStop + 1) % STOPS;
this.handleArrival(bus);
bus.state = "stopping";
bus.stopTimer = bus.dwell;
}
} else {
bus.stopTimer -= dt;
if (bus.stopTimer <= 0) {
bus.state = "moving";
bus.travelDuration =
TRAVEL +
(hash01(bus.id, bus.visit + 1, bus.currentStop) - 0.5) * 4;
}
}
}
this.sampleClock += dt;
if (this.sampleClock >= 1) {
this.sampleClock -= 1;
this.recordSample();
}
}
handleArrival(bus) {
const stop = bus.currentStop;
const gap = this.time - this.lastArrival[stop];
if (gap > 0 && gap < 180) {
this.gaps.push(gap);
this.dwellSamples.push(bus.dwell);
}
this.lastArrival[stop] = this.time;
this.lastGap[stop] = gap;
// Deterministic demand trace, shared by both scenarios.
const demandNoise = 0.70 + hash01(bus.id, stop, bus.visit + 17) * 0.60;
const boarding = Math.round(params.demand * 8 * demandNoise);
const alightFraction = 0.22 + hash01(bus.id + 101, stop, bus.visit) * 0.16;
const alighting = Math.min(bus.load, Math.round(bus.load * alightFraction));
bus.load = clamp(bus.load + boarding - alighting, 0, CAPACITY);
if (this.mode === "constant") {
bus.dwell = DWELL;
} else {
const loadRatio = bus.load / CAPACITY;
const epsilon = hash01(bus.id + 211, stop, bus.visit + 9) - 0.5;
const surge = hash01(bus.id + 307, stop, bus.visit + 23) > 0.88 ? 1 : 0;
const factor =
0.42 +
1.10 * loadRatio +
0.46 * epsilon +
0.42 * surge;
bus.dwell = clamp(
DWELL * (1 + params.variability * (factor - 1)),
4,
45
);
}
bus.visit += 1;
this.events.unshift({
t: this.time,
mode: this.mode,
bus: bus.id,
stop,
gap,
dwell: bus.dwell,
close: gap < CLOSE_GAP
});
if (this.events.length > 30) this.events.length = 30;
}
recordSample() {
const recentGaps = this.gaps.slice(-8);
const recentDwells = this.dwellSamples.slice(-8);
this.history.push({
t: this.time,
gap: recentGaps.length ? mean(recentGaps) : SEGMENT_TIME,
dwell: recentDwells.length ? mean(recentDwells) : DWELL
});
if (this.history.length > 110) this.history.shift();
}
metrics() {
const recentGaps = this.gaps.slice(-64);
const recentDwells = this.dwellSamples.slice(-64);
if (!recentGaps.length) {
return {
ready: false,
meanGap: 0,
cv: 0,
bunchPct: 0,
closeCount: 0,
span: 0,
meanDwell: DWELL
};
}
const m = mean(recentGaps);
const cv = m ? (stdDev(recentGaps) / m) * 100 : 0;
const closeCount = recentGaps.filter(g => g < CLOSE_GAP).length;
const bunchPct = (closeCount / recentGaps.length) * 100;
return {
ready: true,
meanGap: m,
cv,
bunchPct,
closeCount,
span: Math.max(...recentGaps) - Math.min(...recentGaps),
meanDwell: mean(recentDwells)
};
}
}
let simulations = [
new ToySimulation("constant"),
new ToySimulation("variable")
];
/* -------------------------------------------------------------------------- */
/* Three.js scene */
/* -------------------------------------------------------------------------- */
const stage = document.getElementById("stage");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x08121c);
scene.fog = new THREE.FogExp2(0x08121c, 0.015);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
stage.prepend(renderer.domElement);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 120);
const cameraState = {
target: new THREE.Vector3(0, 0, 0),
radius: 40,
theta: 0,
phi: 0.88
};
function updateCamera() {
const { target, radius, theta, phi } = cameraState;
camera.position.set(
target.x + radius * Math.sin(phi) * Math.cos(theta),
target.y + radius * Math.cos(phi),
target.z + radius * Math.sin(phi) * Math.sin(theta)
);
camera.lookAt(target);
}
updateCamera();
const hemi = new THREE.HemisphereLight(0xb8dfff, 0x101827, 1.65);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xe6f5ff, 2.25);
sun.position.set(-10, 24, 12);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -28;
sun.shadow.camera.right = 28;
sun.shadow.camera.top = 22;
sun.shadow.camera.bottom = -22;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 65;
sun.shadow.bias = -0.0005;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x3aa8ff, 0.85);
rimLight.position.set(16, 10, -14);
scene.add(rimLight);
function createTextSprite(text, color = "#dcecf6", width = 512, height = 128) {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const context = canvas.getContext("2d");
context.clearRect(0, 0, width, height);
context.fillStyle = "rgba(7, 15, 24, .82)";
context.fillRect(0, 0, width, height);
context.strokeStyle = color;
context.globalAlpha = 0.65;
context.lineWidth = 4;
context.strokeRect(3, 3, width - 6, height - 6);
context.globalAlpha = 1;
context.fillStyle = color;
context.textAlign = "center";
context.textBaseline = "middle";
context.font = `700 ${Math.floor(height * 0.43)}px ui-sans-serif, system-ui`;
context.fillText(text, width / 2, height / 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.userData.canvas = canvas;
sprite.userData.context = context;
sprite.userData.texture = texture;
return sprite;
}
function paintSprite(sprite, text, color = "#dcecf6", subtitle = "") {
const canvas = sprite.userData.canvas;
const context = sprite.userData.context;
const { width, height } = canvas;
context.clearRect(0, 0, width, height);
context.fillStyle = "rgba(7, 15, 24, .84)";
context.fillRect(0, 0, width, height);
context.strokeStyle = color;
context.globalAlpha = 0.7;
context.lineWidth = 4;
context.strokeRect(3, 3, width - 6, height - 6);
context.globalAlpha = 1;
context.fillStyle = color;
context.textAlign = "center";
context.textBaseline = "middle";
context.font = `750 ${Math.floor(height * (subtitle ? 0.34 : 0.43))}px ui-sans-serif, system-ui`;
context.fillText(text, width / 2, subtitle ? height * 0.40 : height * 0.5);
if (subtitle) {
context.fillStyle = "#9bb0c1";
context.font = `600 ${Math.floor(height * 0.19)}px ui-sans-serif, system-ui`;
context.fillText(subtitle, width / 2, height * 0.73);
}
sprite.userData.texture.needsUpdate = true;
}
function createBuilding(x, z, width, depth, height, color) {
const group = new THREE.Group();
const body = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
new THREE.MeshStandardMaterial({
color,
roughness: 0.82,
metalness: 0.08
})
);
body.position.y = height / 2;
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const roof = new THREE.Mesh(
new THREE.BoxGeometry(width * 0.78, 0.13, depth * 0.78),
new THREE.MeshStandardMaterial({ color: 0x294057, roughness: 0.8 })
);
roof.position.y = height + 0.06;
roof.castShadow = true;
group.add(roof);
const windowMaterial = new THREE.MeshStandardMaterial({
color: 0x5cb6ce,
emissive: 0x173d4c,
emissiveIntensity: 0.75,
roughness: 0.4
});
const rows = Math.max(1, Math.floor(height / 0.7));
for (let row = 0; row < rows; row++) {
const windowMesh = new THREE.Mesh(
new THREE.BoxGeometry(width * 0.68, 0.08, depth + 0.018),
windowMaterial
);
windowMesh.position.y = 0.35 + row * 0.62;
group.add(windowMesh);
}
group.position.set(x, 0, z);
return group;
}
function makeBus(color) {
const group = new THREE.Group();
const bodyMaterial = new THREE.MeshStandardMaterial({
color,
roughness: 0.55,
metalness: 0.12
});
const darkMaterial = new THREE.MeshStandardMaterial({
color: 0x09131d,
roughness: 0.65
});
const windowMaterial = new THREE.MeshStandardMaterial({
color: 0x153b50,
emissive: 0x0b5e78,
emissiveIntensity: 0.55,
roughness: 0.25,
metalness: 0.15
});
const body = new THREE.Mesh(
new THREE.BoxGeometry(2.05, 0.68, 0.88),
bodyMaterial
);
body.position.y = 0.78;
body.castShadow = true;
group.add(body);
const lower = new THREE.Mesh(
new THREE.BoxGeometry(2.08, 0.23, 0.93),
darkMaterial
);
lower.position.y = 0.48;
lower.castShadow = true;
group.add(lower);
const roof = new THREE.Mesh(
new THREE.BoxGeometry(1.73, 0.17, 0.78),
bodyMaterial
);
roof.position.y = 1.18;
roof.castShadow = true;
group.add(roof);
const frontWindow = new THREE.Mesh(
new THREE.BoxGeometry(0.035, 0.31, 0.68),
windowMaterial
);
frontWindow.position.set(1.035, 0.91, 0);
group.add(frontWindow);
for (const side of [-1, 1]) {
for (let i = 0; i < 4; i++) {
const windowMesh = new THREE.Mesh(
new THREE.BoxGeometry(0.31, 0.25, 0.025),
windowMaterial
);
windowMesh.position.set(-0.66 + i * 0.44, 0.94, side * 0.45);
group.add(windowMesh);
}
}
for (const x of [-0.64, 0.64]) {
for (const z of [-0.48, 0.48]) {
const wheel = new THREE.Mesh(
new THREE.BoxGeometry(0.38, 0.31, 0.16),
darkMaterial
);
wheel.position.set(x, 0.35, z);
wheel.castShadow = true;
group.add(wheel);
}
}
const headlightMaterial = new THREE.MeshStandardMaterial({
color: 0xfff2b8,
emissive: 0xffd766,
emissiveIntensity: 1.6
});
for (const z of [-0.25, 0.25]) {
const light = new THREE.Mesh(
new THREE.BoxGeometry(0.04, 0.11, 0.13),
headlightMaterial
);
light.position.set(1.06, 0.65, z);
group.add(light);
}
const loadTrack = new THREE.Mesh(
new THREE.BoxGeometry(1.1, 0.055, 0.12),
new THREE.MeshBasicMaterial({ color: 0x183246 })
);
loadTrack.position.set(0, 1.38, 0);
group.add(loadTrack);
const loadFill = new THREE.Mesh(
new THREE.BoxGeometry(1, 0.06, 0.13),
new THREE.MeshBasicMaterial({ color })
);
loadFill.position.set(0, 1.39, 0);
group.add(loadFill);
group.userData.loadFill = loadFill;
return group;
}
function buildRoute(offsetX, mode) {
const routeGroup = new THREE.Group();
routeGroup.position.x = offsetX;
scene.add(routeGroup);
const color = mode === "constant" ? COLORS.constant : COLORS.variable;
const colorHex = mode === "constant" ? "#58dcff" : "#ff826f";
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(17.2, 12.2),
new THREE.MeshStandardMaterial({
color: mode === "constant" ? 0x0c1b27 : 0x111a25,
roughness: 0.95
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.02;
ground.receiveShadow = true;
routeGroup.add(ground);
const points = [
new THREE.Vector3(-6, 0, -4),
new THREE.Vector3(2, 0, -4),
new THREE.Vector3(6, 0, -2),
new THREE.Vector3(6, 0, 2),
new THREE.Vector3(2, 0, 4),
new THREE.Vector3(-2, 0, 4),
new THREE.Vector3(-6, 0, 2),
new THREE.Vector3(-6, 0, -2)
];
const curve = new THREE.CatmullRomCurve3(
points,
true,
"catmullrom",
0.22
);
const road = new THREE.Mesh(
new THREE.TubeGeometry(curve, 180, 0.55, 4, true),
new THREE.MeshStandardMaterial({
color: COLORS.road,
roughness: 0.95
})
);
road.scale.y = 0.22;
road.position.y = 0.11;
road.receiveShadow = true;
routeGroup.add(road);
const routeLine = new THREE.Mesh(
new THREE.TubeGeometry(curve, 180, 0.045, 6, true),
new THREE.MeshBasicMaterial({ color })
);
routeLine.position.y = 0.24;
routeGroup.add(routeLine);
const buildingSpots = [
[-2.8, -1.7, 1.05, 0.95, 1.8],
[0.3, -1.8, 1.35, 0.85, 2.7],
[2.8, -0.8, 0.95, 1.2, 1.3],
[-2.5, 1.6, 1.15, 0.85, 2.2],
[1.2, 1.7, 1.4, 1.0, 1.1]
];
buildingSpots.forEach((spot, i) => {
routeGroup.add(
createBuilding(
spot[0],
spot[1],
spot[2],
spot[3],
spot[4],
i % 2 ? 0x1a3043 : 0x20374b
)
);
});
const stopVisuals = [];
for (let i = 0; i < STOPS; i++) {
const t = i / STOPS;
const point = curve.getPointAt(t);
const platform = new THREE.Mesh(
new THREE.BoxGeometry(1.05, 0.15, 1.05),
new THREE.MeshStandardMaterial({
color: 0x2b4256,
roughness: 0.82
})
);
platform.position.copy(point);
platform.position.y = 0.16;
platform.receiveShadow = true;
routeGroup.add(platform);
const pole = new THREE.Mesh(
new THREE.BoxGeometry(0.09, 1.0, 0.09),
new THREE.MeshStandardMaterial({ color: 0x60798e })
);
pole.position.copy(point);
pole.position.y = 0.65;
pole.castShadow = true;
routeGroup.add(pole);
const ring = new THREE.Mesh(
new THREE.RingGeometry(0.58, 0.67, 32),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.7,
side: THREE.DoubleSide
})
);
ring.rotation.x = -Math.PI / 2;
ring.position.copy(point);
ring.position.y = 0.245;
routeGroup.add(ring);
const label = createTextSprite(`S${i + 1}`, colorHex);
label.scale.set(0.82, 0.205, 1);
label.position.copy(point);
label.position.y = 1.55;
routeGroup.add(label);
const badge = createTextSprite("—", colorHex, 256, 96);
badge.scale.set(1.05, 0.394, 1);
badge.position.copy(point);
badge.position.y = 2.13;
routeGroup.add(badge);
stopVisuals.push({ ring, label, badge });
}
const heading = createTextSprite(
mode === "constant" ? "CONSTANT BOARDING" : "VARYING BOARDING",
colorHex,
640,
128
);
heading.scale.set(5.2, 1.04, 1);
heading.position.set(0, 5.35, 0);
routeGroup.add(heading);
const busVisuals = [];
for (let i = 0; i < BUSES; i++) {
const bus = makeBus(color);
routeGroup.add(bus);
busVisuals.push(bus);
}
return {
group: routeGroup,
curve,
buses: busVisuals,
stops: stopVisuals,
heading,
mode
};
}
const routeVisuals = [
buildRoute(-8.25, "constant"),
buildRoute(8.25, "variable")
];
// A subtle shared ground grid grounds both miniature networks.
const grid = new THREE.GridHelper(70, 70, 0x173044, 0x102235);
grid.position.y = -0.035;
grid.material.transparent = true;
grid.material.opacity = 0.26;
scene.add(grid);
const base = new THREE.Mesh(
new THREE.PlaneGeometry(70, 46),
new THREE.MeshStandardMaterial({
color: 0x07111a,
roughness: 1
})
);
base.rotation.x = -Math.PI / 2;
base.position.y = -0.08;
base.receiveShadow = true;
scene.add(base);
/* -------------------------------------------------------------------------- */
/* Direct camera controls — no Three.js addons */
/* -------------------------------------------------------------------------- */
let dragging = false;
let dragButton = 0;
let lastPointerX = 0;
let lastPointerY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
dragButton = event.button;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
const panning = dragButton === 2 || event.shiftKey;
if (panning) {
const scale = cameraState.radius * 0.0014;
cameraState.target.x -= dx * scale;
cameraState.target.z -= dy * scale;
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = clamp(cameraState.phi + dy * 0.005, 0.35, 1.35);
}
updateCamera();
});
function endDrag(event) {
dragging = false;
if (event.pointerId !== undefined && renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener("contextmenu", event => event.preventDefault());
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
18,
66
);
updateCamera();
}, { passive: false });
renderer.domElement.addEventListener("dblclick", () => {
cameraState.target.set(0, 0, 0);
cameraState.radius = 40;
cameraState.theta = 0;
cameraState.phi = 0.88;
updateCamera();
});
/* -------------------------------------------------------------------------- */
/* UI */
/* -------------------------------------------------------------------------- */
const playButton = document.getElementById("playButton");
const resetButton = document.getElementById("resetButton");
const variabilityInput = document.getElementById("variability");
const demandInput = document.getElementById("demand");
const variabilityOut = document.getElementById("variabilityOut");
const demandOut = document.getElementById("demandOut");
const labelsToggle = document.getElementById("labelsToggle");
const bubblesToggle = document.getElementById("bubblesToggle");
let running = true;
let speed = 1;
let chartMode = "headway";
function resetSimulations() {
simulations = [
new ToySimulation("constant"),
new ToySimulation("variable")
];
}
function resetExperiment() {
resetSimulations();
accumulator = 0;
}
variabilityInput.addEventListener("input", () => {
params.variability = Number(variabilityInput.value) / 100;
variabilityOut.textContent = `${variabilityInput.value}%`;
});
variabilityInput.addEventListener("change", resetExperiment);
demandInput.addEventListener("input", () => {
params.demand = Number(demandInput.value) / 100;
demandOut.textContent = `${demandInput.value}%`;
});
demandInput.addEventListener("change", resetExperiment);
playButton.addEventListener("click", () => {
running = !running;
playButton.textContent = running ? "Pause" : "Run";
});
resetButton.addEventListener("click", resetExperiment);
document.getElementById("speedButtons").addEventListener("click", event => {
const button = event.target.closest("button[data-speed]");
if (!button) return;
speed = Number(button.dataset.speed);
document.querySelectorAll("#speedButtons button").forEach(item => {
item.classList.toggle("active", item === button);
});
});
document.querySelectorAll("[data-focus]").forEach(button => {
button.addEventListener("click", () => {
const focus = button.dataset.focus;
if (focus === "constant") {
cameraState.target.set(-8.25, 0, 0);
cameraState.radius = 25;
} else if (focus === "variable") {
cameraState.target.set(8.25, 0, 0);
cameraState.radius = 25;
} else {
cameraState.target.set(0, 0, 0);
cameraState.radius = 40;
}
updateCamera();
});
});
document.getElementById("chartTabs").addEventListener("click", event => {
const button = event.target.closest("button[data-chart]");
if (!button) return;
chartMode = button.dataset.chart;
document.querySelectorAll("#chartTabs button").forEach(item => {
item.classList.toggle("active", item === button);
});
document.getElementById("chartTitle").textContent =
chartMode === "headway" ? "Arrival headway" : "Boarding time";
document.getElementById("chartSubtitle").textContent =
chartMode === "headway"
? "Rolling mean of recent stop-arrival gaps"
: "Rolling mean of recently assigned boarding times";
drawChart();
});
function applyDisplayToggles() {
routeVisuals.forEach(route => {
route.heading.visible = labelsToggle.checked;
route.stops.forEach(stop => {
stop.label.visible = labelsToggle.checked;
stop.badge.visible = bubblesToggle.checked;
stop.ring.visible = bubblesToggle.checked;
});
});
}
labelsToggle.addEventListener("change", applyDisplayToggles);
bubblesToggle.addEventListener("change", applyDisplayToggles);
window.addEventListener("keydown", event => {
if (event.target instanceof HTMLInputElement) return;
if (event.code === "Space") {
event.preventDefault();
playButton.click();
}
if (event.key.toLowerCase() === "r") resetExperiment();
if (event.key === "1") {
document.querySelector('[data-speed="1"]').click();
}
if (event.key === "2") {
document.querySelector('[data-speed="2"]').click();
}
if (event.key === "4") {
document.querySelector('[data-speed="4"]').click();
}
});
/* -------------------------------------------------------------------------- */
/* Visual updates */
/* -------------------------------------------------------------------------- */
function updateBusVisuals() {
routeVisuals.forEach((route, routeIndex) => {
const simulation = simulations[routeIndex];
route.buses.forEach((busMesh, busIndex) => {
const bus = simulation.buses[busIndex];
const routeT =
bus.state === "moving"
? (bus.currentStop + bus.progress) / STOPS
: bus.currentStop / STOPS;
const point = route.curve.getPointAt(routeT);
const tangent = route.curve.getTangentAt(routeT);
busMesh.position.copy(point);
busMesh.position.y = 0.46;
busMesh.rotation.y = Math.atan2(-tangent.z, tangent.x);
const loadRatio = bus.load / CAPACITY;
const fill = busMesh.userData.loadFill;
fill.scale.x = Math.max(0.02, loadRatio);
fill.position.x = -0.5 + 0.5 * loadRatio;
});
});
}
function updateStopBadges() {
routeVisuals.forEach((route, routeIndex) => {
const simulation = simulations[routeIndex];
route.stops.forEach((stop, index) => {
const gap = simulation.lastGap[index];
if (gap === null || gap === undefined) {
paintSprite(stop.badge, "—", "#9bb0c1", "warming up");
stop.ring.material.color.setHex(0x60798e);
return;
}
const close = gap < CLOSE_GAP;
const large = gap > REFERENCE_HEADWAY * 1.45;
const color = close ? "#ff657a" : large ? "#ffc66d" :
route.mode === "constant" ? "#58dcff" : "#ff826f";
paintSprite(
stop.badge,
`${gap.toFixed(1)}s`,
color,
close ? "close gap" : "arrival gap"
);
stop.ring.material.color.setHex(
close ? 0xff657a : large ? 0xffc66d :
route.mode === "constant" ? 0x58dcff : 0xff826f
);
const pulse = close ? 1.12 + Math.sin(simulation.time * 5) * 0.08 : 1;
stop.ring.scale.setScalar(pulse);
});
});
}
/* -------------------------------------------------------------------------- */
/* Metric dashboard */
/* -------------------------------------------------------------------------- */
function setText(id, text) {
document.getElementById(id).textContent = text;
}
function stateLabel(metrics) {
if (!metrics.ready) return "Warming";
if (metrics.bunchPct >= 20) return "Bunched";
if (metrics.bunchPct >= 8) return "Pairs forming";
return "Stable";
}
function updateMetricDashboard() {
const constant = simulations[0].metrics();
const variable = simulations[1].metrics();
const fillMetrics = (prefix, metrics) => {
if (!metrics.ready) {
setText(`${prefix}Mean`, "—");
setText(`${prefix}CV`, "—");
setText(`${prefix}Bunch`, "—");
setText(`${prefix}Dwell`, `${metrics.meanDwell.toFixed(1)}s`);
setText(`${prefix}Span`, "—");
return;
}
setText(`${prefix}Mean`, metrics.meanGap.toFixed(1));
setText(`${prefix}CV`, `${metrics.cv.toFixed(1)}%`);
setText(`${prefix}Bunch`, `${metrics.bunchPct.toFixed(1)}%`);
setText(`${prefix}Dwell`, `${metrics.meanDwell.toFixed(1)}s`);
setText(`${prefix}Span`, `${metrics.span.toFixed(1)}s`);
};
fillMetrics("constant", constant);
fillMetrics("variable", variable);
setText("constantState", stateLabel(constant));
setText("variableState", stateLabel(variable));
const constantBunch = constant.ready ? constant.bunchPct : 0;
const variableBunch = variable.ready ? variable.bunchPct : 0;
setText("constantBunchLabel", `${constantBunch.toFixed(1)}%`);
setText("variableBunchLabel", `${variableBunch.toFixed(1)}%`);
document.getElementById("constantBar").style.width =
`${clamp(constantBunch, 0, 100)}%`;
document.getElementById("variableBar").style.width =
`${clamp(variableBunch, 0, 100)}%`;
const copy = document.getElementById("comparisonCopy");
if (!constant.ready || !variable.ready) {
copy.textContent = "Collecting the first complete arrival gaps…";
} else {
const difference = variableBunch - constantBunch;
if (difference > 1) {
copy.innerHTML =
`<strong style="color:var(--coral)">Variable boarding is creating more pairs.</strong> ` +
`The varying world has ${difference.toFixed(1)} percentage points more close gaps ` +
`than the constant world.`;
} else if (difference < -1) {
copy.innerHTML =
`<strong style="color:var(--cyan)">The constant world is currently less bunched.</strong> ` +
`Its close-gap rate is ${Math.abs(difference).toFixed(1)} percentage points lower.`;
} else {
copy.innerHTML =
`<strong>No material bunching gap yet.</strong> ` +
`Both worlds are showing similar close-gap frequencies in the recent sample.`;
}
}
const events = simulations
.flatMap(sim => sim.events.map(event => ({ ...event })))
.sort((a, b) => b.t - a.t)
.slice(0, 4);
const eventLog = document.getElementById("eventLog");
if (!events.length) {
eventLog.innerHTML = `
<div class="event">
<div class="event-id">—</div>
<div><strong>Waiting for arrivals</strong><span>Simulation is warming up</span></div>
<div class="event-gap">—</div>
</div>`;
} else {
eventLog.innerHTML = events.map(event => {
const id = event.mode === "constant" ? "C" : "V";
return `
<div class="event ${event.mode}">
<div class="event-id">${id}${event.bus + 1}</div>
<div>
<strong>Stop ${event.stop + 1} · ${event.dwell.toFixed(1)}s boarding</strong>
<span>${event.mode === "constant" ? "Constant" : "Varying"} world</span>
</div>
<div class="event-gap ${event.close ? "close" : ""}">
${event.gap.toFixed(1)}s
</div>
</div>`;
}).join("");
}
document.getElementById("clock").textContent =
formatClock(simulations[0].time);
}
/* -------------------------------------------------------------------------- */
/* Chart */
/* -------------------------------------------------------------------------- */
const chart = document.getElementById("chart");
const chartContext = chart.getContext("2d");
function drawChart() {
const rect = chart.getBoundingClientRect();
const width = Math.max(1, rect.width);
const height = Math.max(1, rect.height);
const dpr = Math.min(window.devicePixelRatio || 1, 2);
if (
chart.width !== Math.round(width * dpr) ||
chart.height !== Math.round(height * dpr)
) {
chart.width = Math.round(width * dpr);
chart.height = Math.round(height * dpr);
}
const ctx = chartContext;
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, chart.width, chart.height);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
const pad = { left: 36, right: 12, top: 10, bottom: 24 };
const plotW = width - pad.left - pad.right;
const plotH = height - pad.top - pad.bottom;
const isHeadway = chartMode === "headway";
const target = isHeadway ? REFERENCE_HEADWAY : DWELL;
const yMax = isHeadway ? 60 : 36;
const yMin = 0;
const xAt = index => pad.left + (index / 89) * plotW;
const yAt = value =>
pad.top + plotH - ((clamp(value, yMin, yMax) - yMin) / (yMax - yMin)) * plotH;
// Reference band.
ctx.fillStyle = "rgba(112, 225, 165, .055)";
ctx.fillRect(
pad.left,
yAt(target * 1.2),
plotW,
yAt(target * 0.8) - yAt(target * 1.2)
);
ctx.strokeStyle = "rgba(112, 225, 165, .45)";
ctx.setLineDash([4, 5]);
ctx.beginPath();
ctx.moveTo(pad.left, yAt(target));
ctx.lineTo(pad.left + plotW, yAt(target));
ctx.stroke();
ctx.setLineDash([]);
// Grid.
ctx.font = "9px ui-monospace, SFMono-Regular, Menlo, monospace";
ctx.textAlign = "right";
ctx.textBaseline = "middle";
const step = isHeadway ? 15 : 9;
for (let value = yMin; value <= yMax; value += step) {
const y = yAt(value);
ctx.strokeStyle = "rgba(75, 104, 128, .16)";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(pad.left, y);
ctx.lineTo(pad.left + plotW, y);
ctx.stroke();
ctx.fillStyle = "#6f8497";
ctx.fillText(`${value}s`, pad.left - 7, y);
}
const histories = simulations.map(sim => sim.history);
const pointCount = Math.max(...histories.map(history => history.length));
const startIndex = Math.max(0, pointCount - 90);
function drawSeries(history, color) {
if (history.length < 2) return;
ctx.strokeStyle = color;
ctx.lineWidth = 1.8;
ctx.lineJoin = "round";
ctx.lineCap = "round";
ctx.beginPath();
let started = false;
for (let i = startIndex; i < history.length; i++) {
const item = history[i];
const x = pad.left + ((i - startIndex) / 89) * plotW;
const y = yAt(isHeadway ? item.gap : item.dwell);
if (!started) {
ctx.moveTo(x, y);
started = true;
} else {
ctx.lineTo(x, y);
}
}
ctx.stroke();
const last = history[history.length - 1];
const x = pad.left + ((history.length - 1 - startIndex) / 89) * plotW;
const y = yAt(isHeadway ? last.gap : last.dwell);
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(x, y, 2.8, 0, Math.PI * 2);
ctx.fill();
}
drawSeries(histories[0], "#58dcff");
drawSeries(histories[1], "#ff826f");
// Plot labels.
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.font = "700 9px ui-sans-serif, system-ui";
ctx.fillStyle = "#58dcff";
ctx.fillText("CONSTANT", pad.left + 5, pad.top + 2);
ctx.fillStyle = "#ff826f";
ctx.fillText("VARYING", pad.left + 69, pad.top + 2);
ctx.textAlign = "right";
ctx.fillStyle = "#6f8497";
ctx.font = "9px ui-monospace, SFMono-Regular, Menlo, monospace";
ctx.fillText("← time", pad.left + plotW, height - 15);
}
/* -------------------------------------------------------------------------- */
/* Resize and animation */
/* -------------------------------------------------------------------------- */
function resize() {
const width = stage.clientWidth;
const height = stage.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / Math.max(1, height);
camera.updateProjectionMatrix();
drawChart();
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(stage);
resizeObserver.observe(chart.parentElement);
window.addEventListener("resize", resize);
let accumulator = 0;
let lastFrame = performance.now();
let lastUI = 0;
function animate(now) {
requestAnimationFrame(animate);
const realDt = Math.min(0.1, (now - lastFrame) / 1000);
lastFrame = now;
if (running) {
accumulator += realDt * speed;
const fixedStep = 0.05;
while (accumulator >= fixedStep) {
simulations[0].update(fixedStep);
simulations[1].update(fixedStep);
accumulator -= fixedStep;
}
}
updateBusVisuals();
if (now - lastUI > 160) {
lastUI = now;
updateStopBadges();
updateMetricDashboard();
drawChart();
}
renderer.render(scene, camera);
}
applyDisplayToggles();
updateBusVisuals();
updateMetricDashboard();
resize();
requestAnimationFrame(animate);
document.getElementById("loading").classList.add("hidden");
</script>
</body>
</html>
```