Prompt specification
Build or customize the Three.js 3D scene "Late Arrival and Gate Capacity Scenario" 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: Late Arrival and Gate Capacity Scenario
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/late-arrival-and-gate-capacity-scenario-x2084
Scene Description Prompt:
Create a standalone low-poly scene in one HTML file using Three.js from cdnjs. Create a fictional boarding-flow simulation with limited aisle capacity and timed arrivals. Show how outcomes depend on the chosen rules rather than claiming airline operational accuracy.
Working Three.js Starter (late-arrival-and-gate-capacity-scenario-x2084):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Boarding Lab — Fictional Flow Simulation</title>
<style>
:root {
color-scheme: dark;
--bg: #08111d;
--panel: #101c2c;
--panel-2: #132337;
--line: rgba(155, 190, 220, .17);
--text: #edf6ff;
--muted: #91a7bb;
--cyan: #54d8d1;
--amber: #ffc857;
--coral: #ff8066;
--green: #91d36b;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font: 14px/1.45 Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, select, input { font: inherit; }
button, select {
color: var(--text);
background: #17283b;
border: 1px solid var(--line);
border-radius: 9px;
}
button {
cursor: pointer;
transition: background .15s, border-color .15s, transform .15s;
}
button:hover {
background: #20364c;
border-color: rgba(84, 216, 209, .45);
}
button:active { transform: translateY(1px); }
select {
width: 100%;
padding: 10px 11px;
outline: none;
}
select:focus-visible, button:focus-visible, input:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 2px;
}
.app {
display: grid;
grid-template-columns: 320px minmax(0, 1fr);
width: 100%;
height: 100%;
}
aside {
min-height: 0;
overflow-y: auto;
padding: 24px 22px;
background:
radial-gradient(circle at 12% 0%, rgba(84,216,209,.08), transparent 30%),
linear-gradient(180deg, #101c2c, #0b1624);
border-right: 1px solid var(--line);
scrollbar-width: thin;
scrollbar-color: #2c4359 transparent;
}
.brand {
display: flex;
align-items: center;
gap: 11px;
margin-bottom: 20px;
}
.brand-mark {
display: grid;
place-items: center;
width: 38px;
height: 38px;
border: 1px solid rgba(84,216,209,.5);
border-radius: 11px;
color: var(--cyan);
background: rgba(84,216,209,.08);
font-weight: 900;
letter-spacing: -.08em;
}
.brand h1 {
margin: 0;
font-size: 18px;
letter-spacing: .03em;
}
.brand small {
display: block;
color: var(--muted);
font-size: 10px;
letter-spacing: .13em;
text-transform: uppercase;
}
.disclaimer {
margin: 0 0 22px;
padding: 11px 12px;
border: 1px solid rgba(255,200,87,.25);
border-radius: 10px;
background: rgba(255,200,87,.055);
color: #d9cba8;
font-size: 12px;
}
.section-title {
margin: 24px 0 11px;
color: #bed0df;
font-size: 10px;
font-weight: 800;
letter-spacing: .15em;
text-transform: uppercase;
}
.control { margin-bottom: 17px; }
.control label {
display: flex;
justify-content: space-between;
align-items: center;
gap: 10px;
margin-bottom: 7px;
color: #dbe8f3;
font-size: 12px;
font-weight: 650;
}
.range-value {
color: var(--cyan);
font-variant-numeric: tabular-nums;
}
.note {
min-height: 43px;
margin: 7px 1px 0;
color: var(--muted);
font-size: 11px;
}
input[type="range"] {
width: 100%;
accent-color: var(--cyan);
cursor: pointer;
}
.run-row {
display: grid;
grid-template-columns: 1fr 82px;
gap: 9px;
margin-top: 22px;
}
.primary {
padding: 11px 14px;
border-color: rgba(84,216,209,.6);
background: var(--cyan);
color: #07151b;
font-weight: 800;
}
.primary:hover { background: #79e6e0; }
.secondary { padding: 10px 12px; }
.speed-row {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin-top: 9px;
}
.speed-row button {
padding: 7px 4px;
color: var(--muted);
font-size: 11px;
}
.speed-row button.active {
color: var(--cyan);
border-color: rgba(84,216,209,.55);
background: rgba(84,216,209,.09);
}
.compare-box {
margin-top: 24px;
padding-top: 20px;
border-top: 1px solid var(--line);
}
.compare-box p {
margin: 0 0 11px;
color: var(--muted);
font-size: 11px;
}
.wide { width: 100%; padding: 10px 12px; }
.model-key {
display: grid;
gap: 8px;
margin-top: 23px;
padding-top: 18px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 11px;
}
.key-row {
display: flex;
align-items: center;
gap: 8px;
}
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--cyan);
}
.dot.amber { background: var(--amber); }
.dot.coral { background: var(--coral); }
.dot.green { background: var(--green); }
main {
display: grid;
grid-template-rows: minmax(390px, 1fr) 255px;
min-width: 0;
min-height: 0;
}
#viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 35%, #172a42 0%, #0a1524 65%);
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.scene-top {
position: absolute;
z-index: 2;
top: 18px;
left: 20px;
right: 20px;
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 16px;
pointer-events: none;
}
.scene-title {
padding: 10px 12px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(8,17,29,.72);
backdrop-filter: blur(8px);
}
.scene-title strong {
display: block;
font-size: 12px;
letter-spacing: .03em;
}
.scene-title span {
color: var(--muted);
font-size: 10px;
}
.scene-status {
display: flex;
gap: 7px;
flex-wrap: wrap;
justify-content: flex-end;
}
.pill {
padding: 7px 10px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(8,17,29,.72);
color: #c8d9e8;
font-size: 10px;
font-weight: 700;
letter-spacing: .04em;
backdrop-filter: blur(8px);
}
.pill.live {
color: var(--cyan);
border-color: rgba(84,216,209,.35);
}
.scene-bottom {
position: absolute;
z-index: 2;
left: 20px;
right: 20px;
bottom: 17px;
display: flex;
justify-content: space-between;
align-items: flex-end;
gap: 15px;
pointer-events: none;
}
.capacity-card {
width: min(310px, 48%);
padding: 10px 12px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(8,17,29,.76);
backdrop-filter: blur(8px);
}
.capacity-label {
display: flex;
justify-content: space-between;
margin-bottom: 7px;
color: #c7d7e4;
font-size: 10px;
font-weight: 700;
letter-spacing: .05em;
text-transform: uppercase;
}
.meter {
height: 6px;
overflow: hidden;
border-radius: 99px;
background: #24384d;
}
#capacityFill {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--cyan), var(--amber));
transition: width .12s linear;
}
.camera-hint {
color: rgba(220,235,247,.6);
font-size: 10px;
text-shadow: 0 1px 4px #000;
}
.analysis {
display: grid;
grid-template-columns: minmax(340px, 1.25fr) minmax(340px, 1fr);
min-height: 0;
border-top: 1px solid var(--line);
background: #0c1725;
}
.analysis > div {
min-width: 0;
padding: 17px 20px;
}
.analysis > div + div {
border-left: 1px solid var(--line);
}
.panel-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 10px;
}
.panel-head h2 {
margin: 0;
color: #d9e7f2;
font-size: 10px;
letter-spacing: .14em;
text-transform: uppercase;
}
.panel-head span {
color: var(--muted);
font-size: 10px;
}
#timeline {
display: block;
width: 100%;
height: 160px;
}
.metrics {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 8px;
margin-bottom: 10px;
}
.metric {
min-width: 0;
padding: 9px 10px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255,255,255,.018);
}
.metric span {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 9px;
letter-spacing: .05em;
text-transform: uppercase;
}
.metric strong {
display: block;
overflow: hidden;
color: var(--text);
font-size: 17px;
font-variant-numeric: tabular-nums;
text-overflow: ellipsis;
}
#outcomeText {
min-height: 48px;
margin: 0 0 9px;
color: #b9cad9;
font-size: 11px;
}
.table-wrap {
max-height: 92px;
overflow-y: auto;
scrollbar-width: thin;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 10px;
font-variant-numeric: tabular-nums;
}
th, td {
padding: 6px 7px;
border-bottom: 1px solid rgba(155,190,220,.09);
text-align: right;
white-space: nowrap;
}
th {
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: .04em;
text-transform: uppercase;
}
th:first-child, td:first-child { text-align: left; }
tr.current td { color: var(--cyan); background: rgba(84,216,209,.05); }
@media (max-width: 950px) {
html, body { overflow: auto; height: auto; min-height: 100%; }
.app {
display: block;
height: auto;
}
aside {
overflow: visible;
border-right: 0;
border-bottom: 1px solid var(--line);
}
main {
display: block;
}
#viewport { height: 62vh; min-height: 430px; }
.analysis {
grid-template-columns: 1fr;
}
.analysis > div + div {
border-left: 0;
border-top: 1px solid var(--line);
}
}
@media (max-width: 520px) {
aside { padding: 20px 16px; }
.scene-top { left: 12px; right: 12px; top: 12px; }
.scene-bottom { left: 12px; right: 12px; bottom: 12px; }
.scene-status { max-width: 160px; }
.camera-hint { display: none; }
.metrics { grid-template-columns: repeat(2, 1fr); }
.analysis > div { padding: 16px 12px; }
}
</style>
</head>
<body>
<div class="app">
<aside>
<div class="brand">
<div class="brand-mark">B/</div>
<div>
<h1>BOARDING LAB</h1>
<small>Fictional flow sandbox</small>
</div>
</div>
<p class="disclaimer">
This is an invented model for comparing rules and arrival patterns.
It is not an airline, airport, safety, or operational-accuracy simulation.
</p>
<div class="section-title">Scenario rules</div>
<div class="control">
<label for="rule">Boarding rule</label>
<select id="rule">
<option value="priority">Priority lane</option>
<option value="front">Front-to-back</option>
<option value="back">Back-to-front</option>
<option value="random">Randomized draw</option>
</select>
<p class="note" id="ruleNote"></p>
</div>
<div class="control">
<label for="arrival">Timed arrival pattern</label>
<select id="arrival">
<option value="steady">Evenly spaced</option>
<option value="early">Early surge</option>
<option value="late">Late rush</option>
<option value="pairs">Two-group waves</option>
</select>
<p class="note" id="arrivalNote"></p>
</div>
<div class="control">
<label for="groupSize">
Travelers per group
<output class="range-value" id="groupSizeValue"></output>
</label>
<input id="groupSize" type="range" min="1" max="4" step="1" value="3">
</div>
<div class="control">
<label for="capacity">
Toy aisle capacity
<output class="range-value" id="capacityValue"></output>
</label>
<input id="capacity" type="range" min="4" max="12" step="1" value="6">
<p class="note">Simultaneous aisle positions only; not a real-world capacity standard.</p>
</div>
<div class="control">
<label for="service">
Seating / stow time
<output class="range-value" id="serviceValue"></output>
</label>
<input id="service" type="range" min="2" max="8" step="1" value="4">
</div>
<div class="run-row">
<button id="runButton" class="primary">Pause</button>
<button id="resetButton" class="secondary">Reset</button>
</div>
<div class="speed-row" aria-label="Simulation speed">
<button data-speed="1" class="active">1×</button>
<button data-speed="2">2×</button>
<button data-speed="4">4×</button>
</div>
<div class="compare-box">
<div class="section-title" style="margin-top:0">Comparison</div>
<p>
Compare all four rules using the same arrival schedule, groups,
aisle limit, and seating time.
</p>
<button id="compareButton" class="wide">Compare all rules</button>
</div>
<div class="model-key">
<div class="key-row"><span class="dot"></span> Standard traveler</div>
<div class="key-row"><span class="dot coral"></span> Priority traveler</div>
<div class="key-row"><span class="dot amber"></span> In aisle / boarding</div>
<div class="key-row"><span class="dot green"></span> Seated</div>
</div>
</aside>
<main>
<section id="viewport" aria-label="Interactive three-dimensional boarding scene">
<div class="scene-top">
<div class="scene-title">
<strong>LOW-POLY AIRCRAFT / GATE 04</strong>
<span>Drag to orbit · Scroll to zoom · Double-click to reset camera</span>
</div>
<div class="scene-status">
<span class="pill live" id="runStatus">RUNNING</span>
<span class="pill" id="seatedPill">0 / 72 seated</span>
<span class="pill" id="queuePill">0 waiting</span>
</div>
</div>
<div class="scene-bottom">
<div class="capacity-card">
<div class="capacity-label">
<span>Aisle occupancy</span>
<span id="capacityText">0 / 6</span>
</div>
<div class="meter"><div id="capacityFill"></div></div>
</div>
<div class="camera-hint">Illustrative geometry · fictional data</div>
</div>
</section>
<section class="analysis">
<div>
<div class="panel-head">
<h2>Arrival and seating timeline</h2>
<span id="timelineSummary">72 fictional travelers</span>
</div>
<canvas id="timeline"></canvas>
</div>
<div>
<div class="panel-head">
<h2>Outcome</h2>
<span id="scenarioLabel">Priority lane · Evenly spaced</span>
</div>
<div class="metrics">
<div class="metric">
<span>Average wait</span>
<strong id="avgWaitValue">—</strong>
</div>
<div class="metric">
<span>Elapsed</span>
<strong id="elapsedValue">00:00</strong>
</div>
<div class="metric">
<span>Blocked time</span>
<strong id="blockedValue">0s</strong>
</div>
<div class="metric">
<span>Aisle now</span>
<strong id="aisleValue">0 / 6</strong>
</div>
</div>
<p id="outcomeText"></p>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Rule</th>
<th>Avg wait</th>
<th>Finish</th>
<th>Stall</th>
</tr>
</thead>
<tbody id="compareBody">
<tr><td colspan="4">Run “Compare all rules” for a rule-by-rule result.</td></tr>
</tbody>
</table>
</div>
</div>
</section>
</main>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = id => document.getElementById(id);
const viewport = $("viewport");
const RULE_LABELS = {
priority: "Priority lane",
front: "Front-to-back",
back: "Back-to-front",
random: "Randomized draw"
};
const ARRIVAL_LABELS = {
steady: "Evenly spaced",
early: "Early surge",
late: "Late rush",
pairs: "Two-group waves"
};
const RULE_NOTES = {
priority: "Priority groups take precedence among groups that have already arrived.",
front: "Groups assigned farther-forward seats take precedence among arrived groups.",
back: "Groups assigned farther-rear seats take precedence among arrived groups.",
random: "A seeded random draw changes the order while keeping comparisons reproducible."
};
const ARRIVAL_NOTES = {
steady: "Groups arrive at regular intervals throughout the scenario.",
early: "Most groups arrive early, leaving a thinner tail near the end.",
late: "Arrivals accumulate later, producing a pronounced final rush.",
pairs: "Two groups arrive close together, followed by a short gap."
};
const COLORS = {
background: 0x0a1524,
standard: 0x54d8d1,
priority: 0xff8066,
boarding: 0xffc857,
seated: 0x91d36b,
floor: 0x263d50,
aisle: 0x102639
};
let config;
let data;
let groups = [];
let passengers = [];
let sim;
let running = true;
let speed = 1;
let comparisonResults = null;
// ---------------------------------------------------------------------------
// Three.js scene
// ---------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(COLORS.background);
scene.fog = new THREE.Fog(COLORS.background, 38, 80);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 120);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.75));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.domElement.setAttribute("aria-label", "Low-poly fictional aircraft boarding simulation");
viewport.prepend(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xb9ddff, 0x172033, 2.1));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.6);
keyLight.position.set(9, 18, 10);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -22;
keyLight.shadow.camera.right = 22;
keyLight.shadow.camera.top = 27;
keyLight.shadow.camera.bottom = -18;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 60;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x53d9ff, 1.3);
rimLight.position.set(-12, 8, -12);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xffc857, 30, 28, 2);
warmLight.position.set(4, 5, 12);
scene.add(warmLight);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(90, 90),
new THREE.MeshStandardMaterial({ color: 0x091421, roughness: 0.95, metalness: 0.05 })
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.52;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(70, 70, 0x274058, 0x14283b);
grid.position.y = -0.50;
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
const seatMaterials = [];
const capacityMarkers = [];
const shared = {
seatBase: new THREE.BoxGeometry(0.82, 0.18, 0.72),
seatBack: new THREE.BoxGeometry(0.82, 0.68, 0.14),
personBody: new THREE.CylinderGeometry(0.15, 0.21, 0.58, 5),
personHead: new THREE.SphereGeometry(0.16, 6, 4),
bag: new THREE.BoxGeometry(0.20, 0.28, 0.16),
rail: new THREE.BoxGeometry(0.12, 0.72, 23.2),
marker: new THREE.BoxGeometry(0.20, 0.08, 0.20)
};
const seatBackMaterial = new THREE.MeshStandardMaterial({
color: 0x38556c,
roughness: 0.85
});
const skinMaterial = new THREE.MeshStandardMaterial({
color: 0xe2b38f,
roughness: 0.9
});
const bagMaterial = new THREE.MeshStandardMaterial({
color: 0x182534,
roughness: 0.95
});
function createLine(points, color = 0x41627d, opacity = 1) {
const geometry = new THREE.BufferGeometry().setFromPoints(
points.map(p => new THREE.Vector3(...p))
);
const material = new THREE.LineBasicMaterial({
color,
transparent: opacity < 1,
opacity
});
return new THREE.Line(geometry, material);
}
function makeLabel(text, color = "#9ee8e3") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(8,17,29,0.86)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = color;
ctx.lineWidth = 4;
ctx.strokeRect(3, 3, canvas.width - 6, canvas.height - 6);
ctx.fillStyle = color;
ctx.font = "700 42px system-ui";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, canvas.width / 2, canvas.height / 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(3.5, 0.875, 1);
return sprite;
}
function createTriangle(points, material) {
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(points.flat(), 3)
);
geometry.setIndex([0, 1, 2]);
geometry.computeVertexNormals();
const mesh = new THREE.Mesh(geometry, material);
mesh.material.side = THREE.DoubleSide;
return mesh;
}
function createStaticCabin() {
// Cutaway aircraft floor.
const shape = new THREE.Shape();
shape.moveTo(-2.25, -14);
shape.lineTo(2.25, -14);
shape.lineTo(4.05, -11.3);
shape.lineTo(4.05, 10.7);
shape.lineTo(3.0, 13.0);
shape.lineTo(-3.0, 13.0);
shape.lineTo(-4.05, 10.7);
shape.lineTo(-4.05, -11.3);
shape.closePath();
const floorGeometry = new THREE.ShapeGeometry(shape);
floorGeometry.rotateX(Math.PI / 2);
const floor = new THREE.Mesh(
floorGeometry,
new THREE.MeshStandardMaterial({
color: COLORS.floor,
roughness: 0.9,
metalness: 0.08,
side: THREE.DoubleSide
})
);
floor.position.y = -0.24;
floor.receiveShadow = true;
scene.add(floor);
const outline = createLine([
[-2.25,-0.22,-14], [2.25,-0.22,-14], [4.05,-0.22,-11.3],
[4.05,-0.22,10.7], [3,-0.22,13], [-3,-0.22,13],
[-4.05,-0.22,10.7], [-4.05,-0.22,-11.3], [-2.25,-0.22,-14]
], 0x5b819e, 0.8);
scene.add(outline);
// Aisle strip.
const aisle = new THREE.Mesh(
new THREE.PlaneGeometry(1.48, 23.0),
new THREE.MeshStandardMaterial({ color: COLORS.aisle, roughness: 1 })
);
aisle.rotation.x = -Math.PI / 2;
aisle.position.set(0, -0.215, -0.2);
aisle.receiveShadow = true;
scene.add(aisle);
// Low cutaway fuselage walls.
const railMaterial = new THREE.MeshStandardMaterial({
color: 0xa7bcc8,
roughness: 0.65,
metalness: 0.12
});
for (const side of [-1, 1]) {
const rail = new THREE.Mesh(shared.rail, railMaterial);
rail.position.set(side * 4.05, 0.15, -0.2);
rail.castShadow = true;
scene.add(rail);
}
// Nose and tail wall pieces.
const nose = new THREE.Mesh(
new THREE.BoxGeometry(4.5, 0.62, 0.12),
railMaterial
);
nose.position.set(0, 0.06, -12.35);
nose.rotation.x = -0.18;
scene.add(nose);
const tail = new THREE.Mesh(
new THREE.BoxGeometry(6.0, 0.62, 0.12),
railMaterial
);
tail.position.set(0, 0.06, 11.7);
scene.add(tail);
// Cockpit windows.
const glass = new THREE.MeshStandardMaterial({
color: 0x12364c,
emissive: 0x0b2638,
emissiveIntensity: 0.8,
roughness: 0.35
});
for (const side of [-1, 1]) {
const window = new THREE.Mesh(new THREE.BoxGeometry(0.82, 0.33, 0.06), glass);
window.position.set(side * 1.05, 0.40, -12.65);
window.rotation.z = side * 0.23;
scene.add(window);
}
// Low-poly wings.
const wingMaterial = new THREE.MeshStandardMaterial({
color: 0x7891a1,
roughness: 0.78,
side: THREE.DoubleSide
});
const rightWing = createTriangle([
[4.0,-0.08,-0.5], [7.1,-0.08,1.4], [4.0,-0.08,3.2]
], wingMaterial);
const leftWing = createTriangle([
[-4.0,-0.08,3.2], [-7.1,-0.08,1.4], [-4.0,-0.08,-0.5]
], wingMaterial);
rightWing.castShadow = leftWing.castShadow = true;
scene.add(rightWing, leftWing);
// Seat rows: three seats on each side.
const seatX = [-3.18, -2.18, -1.18, 1.18, 2.18, 3.18];
const rows = 12;
for (let row = 0; row < rows; row++) {
const z = -9.2 + row * 1.62;
for (let col = 0; col < 6; col++) {
const material = new THREE.MeshStandardMaterial({
color: col === 2 || col === 3 ? 0x41647b : 0x31546b,
roughness: 0.82
});
seatMaterials.push(material);
const base = new THREE.Mesh(shared.seatBase, material);
base.position.set(seatX[col], -0.07, z);
base.castShadow = true;
base.receiveShadow = true;
scene.add(base);
const back = new THREE.Mesh(shared.seatBack, seatBackMaterial);
back.position.set(seatX[col], 0.30, z + 0.33);
back.castShadow = true;
scene.add(back);
}
}
// Boarding doorway at the rear.
const doorFrame = new THREE.MeshStandardMaterial({
color: 0x54d8d1,
emissive: 0x123d3d,
emissiveIntensity: 0.6
});
for (const x of [1.85, 3.05]) {
const post = new THREE.Mesh(new THREE.BoxGeometry(0.10, 1.7, 0.14), doorFrame);
post.position.set(x, 0.62, 12.85);
scene.add(post);
}
const top = new THREE.Mesh(new THREE.BoxGeometry(1.30, 0.10, 0.14), doorFrame);
top.position.set(2.45, 1.45, 12.85);
scene.add(top);
// Gate queue platform.
const platform = new THREE.Mesh(
new THREE.BoxGeometry(10.5, 0.16, 12),
new THREE.MeshStandardMaterial({ color: 0x162b3d, roughness: 0.92 })
);
platform.position.set(0, -0.35, 18.0);
platform.receiveShadow = true;
scene.add(platform);
for (let row = 0; row < 8; row++) {
const z = 14.4 + row * 1.05;
scene.add(createLine([
[-3.1,-0.25,z], [3.1,-0.25,z]
], 0x315068, 0.45));
}
// Capacity indicators beside the aisle.
for (let i = 0; i < 12; i++) {
const material = new THREE.MeshStandardMaterial({
color: 0x244256,
emissive: 0x000000
});
const marker = new THREE.Mesh(shared.marker, material);
marker.position.set(0.68, -0.17, 11.4 - i * 0.82);
scene.add(marker);
capacityMarkers.push(marker);
}
const gateLabel = makeLabel("GATE 04", "#9ee8e3");
gateLabel.position.set(-0.5, 2.5, 17.0);
gateLabel.scale.set(3.8, 0.95, 1);
scene.add(gateLabel);
const doorLabel = makeLabel("BOARDING", "#ffc857");
doorLabel.position.set(2.45, 2.15, 12.85);
doorLabel.scale.set(2.8, 0.70, 1);
scene.add(doorLabel);
const cabinLabel = makeLabel("CUTAWAY / 72 SEATS", "#9bb7cb");
cabinLabel.position.set(-0.5, 2.2, -10.2);
cabinLabel.scale.set(3.8, 0.95, 1);
scene.add(cabinLabel);
}
createStaticCabin();
// ---------------------------------------------------------------------------
// Direct camera controls: no Three.js addons
// ---------------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 0, 1.5);
let cameraYaw = 0.68;
let cameraPolar = 0.89;
let cameraRadius = 38;
let dragging = false;
let dragX = 0;
let dragY = 0;
function updateCamera() {
const sinPolar = Math.sin(cameraPolar);
camera.position.set(
cameraTarget.x + cameraRadius * sinPolar * Math.sin(cameraYaw),
cameraTarget.y + cameraRadius * Math.cos(cameraPolar),
cameraTarget.z + cameraRadius * sinPolar * Math.cos(cameraYaw)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraYaw = 0.68;
cameraPolar = 0.89;
cameraRadius = 38;
updateCamera();
}
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
dragging = true;
dragX = event.clientX;
dragY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - dragX;
const dy = event.clientY - dragY;
dragX = event.clientX;
dragY = event.clientY;
cameraYaw -= dx * 0.006;
cameraPolar = THREE.MathUtils.clamp(cameraPolar - dy * 0.005, 0.35, 1.30);
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("dblclick", resetCamera);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(cameraRadius + event.deltaY * 0.025, 16, 62);
updateCamera();
}, { passive: false });
function resize() {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
if (!width || !height) return;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
new ResizeObserver(resize).observe(viewport);
resize();
resetCamera();
// ---------------------------------------------------------------------------
// Scenario data
// ---------------------------------------------------------------------------
const seatX = [-3.18, -2.18, -1.18, 1.18, 2.18, 3.18];
const TOTAL_TRAVELERS = 72;
function readConfig() {
return {
rule: $("rule").value,
arrival: $("arrival").value,
groupSize: Number($("groupSize").value),
capacity: Number($("capacity").value),
service: Number($("service").value)
};
}
function seededRank(id) {
let h = (id + 1) * 2654435761;
h = (h ^ (h >>> 16)) >>> 0;
h = Math.imul(h, 0x7feb352d) >>> 0;
h = (h ^ (h >>> 15)) >>> 0;
return h / 4294967296;
}
function assignRanks(dataGroups, rule) {
for (const group of dataGroups) {
group.rank = seededRank(group.id);
}
dataGroups.sort((a, b) => {
if (rule === "priority") {
return b.priority - a.priority || a.id - b.id;
}
if (rule === "front") {
return a.minRow - b.minRow || a.id - b.id;
}
if (rule === "back") {
return b.maxRow - a.maxRow || a.id - b.id;
}
return a.rank - b.rank || a.id - b.id;
});
}
function createData(localConfig) {
const localGroups = [];
const localPassengers = [];
const groupCount = TOTAL_TRAVELERS / localConfig.groupSize;
const span = Math.max(54, groupCount * 2.65);
for (let groupId = 0; groupId < groupCount; groupId++) {
const group = {
id: groupId,
state: "scheduled",
priority: ((groupId * 7) % 11 < 2) ? 1 : 0,
passengers: [],
blockedEpisode: false,
rank: 0,
arrival: 0,
minRow: Infinity,
maxRow: -Infinity
};
const fraction = groupCount === 1 ? 0 : groupId / (groupCount - 1);
if (localConfig.arrival === "steady") {
group.arrival = span * fraction;
} else if (localConfig.arrival === "early") {
group.arrival = span * Math.pow(fraction, 1.75);
} else if (localConfig.arrival === "late") {
group.arrival = span * Math.pow(fraction, 0.43);
} else {
const waveCount = Math.ceil(groupCount / 2);
const wave = Math.floor(groupId / 2);
const waveTime = waveCount > 1 ? wave * span / (waveCount - 1) : 0;
group.arrival = Math.min(span, waveTime + (groupId % 2) * 0.35);
}
for (let j = 0; j < localConfig.groupSize; j++) {
const slot = groupId * localConfig.groupSize + j;
const row = Math.floor(slot / 6);
const col = slot % 6;
const seatZ = -9.2 + row * 1.62;
const travel = 4.1 + Math.abs(11.65 - seatZ) * 0.43;
const stow = localConfig.service + (col === 2 || col === 3 ? 0.35 : 0);
const passenger = {
id: slot,
groupId,
group,
slot,
row,
col,
seatX: seatX[col],
seatZ,
state: "scheduled",
arrival: group.arrival,
boardStart: null,
travel,
duration: travel + stow
};
group.passengers.push(passenger);
localPassengers.push(passenger);
group.minRow = Math.min(group.minRow, row);
group.maxRow = Math.max(group.maxRow, row);
}
localGroups.push(group);
}
assignRanks(localGroups, localConfig.rule);
return {
groups: localGroups,
passengers: localPassengers,
lastArrival: localGroups.reduce((max, g) => Math.max(max, g.arrival), 0)
};
}
function groupComparator(a, b) {
if (config.rule === "priority") {
return b.priority - a.priority || a.id - b.id;
}
if (config.rule === "front") {
return a.minRow - b.minRow || a.id - b.id;
}
if (config.rule === "back") {
return b.maxRow - a.maxRow || a.id - b.id;
}
return a.rank - b.rank || a.id - b.id;
}
// ---------------------------------------------------------------------------
// Passenger meshes
// ---------------------------------------------------------------------------
function createPersonMesh(passenger) {
const person = new THREE.Group();
const bodyMaterial = new THREE.MeshStandardMaterial({
color: COLORS.standard,
roughness: 0.75
});
const body = new THREE.Mesh(shared.personBody, bodyMaterial);
body.position.y = 0.48;
body.castShadow = true;
const head = new THREE.Mesh(shared.personHead, skinMaterial);
head.position.y = 0.94;
head.castShadow = true;
const bag = new THREE.Mesh(shared.bag, bagMaterial);
bag.position.set(0.23, 0.22, 0.02);
bag.castShadow = true;
person.add(body, head, bag);
person.userData.bodyMaterial = bodyMaterial;
person.userData.bag = bag;
person.visible = false;
return person;
}
function rebuildPassengerMeshes() {
for (const passenger of passengers) {
if (passenger.mesh) {
scene.remove(passenger.mesh);
passenger.mesh.userData.bodyMaterial.dispose();
}
}
passengers = data.passengers;
groups = data.groups;
for (const passenger of passengers) {
passenger.mesh = createPersonMesh(passenger);
passenger.current = new THREE.Vector3();
passenger.target = new THREE.Vector3();
passenger.hasPosition = false;
passenger.lastVisualState = "";
scene.add(passenger.mesh);
}
for (const material of seatMaterials) {
material.color.set(material.userData?.baseColor ?? 0x31546b);
}
}
// ---------------------------------------------------------------------------
// Live simulation
// ---------------------------------------------------------------------------
function resetSimulation(startImmediately = true) {
config = readConfig();
data = createData(config);
rebuildPassengerMeshes();
sim = {
t: 0,
aisle: 0,
blockedTime: 0,
blockedEvents: 0,
ended: false,
finishTime: null,
history: [{ t: 0, seated: 0, waiting: 0 }],
lastHistoryTime: 0
};
running = startImmediately;
updateRunButton();
updateHUD();
drawTimeline();
}
function startGroup(group, time) {
group.state = "boarding";
group.blockedEpisode = false;
for (const passenger of group.passengers) {
passenger.state = "boarding";
passenger.boardStart = time;
}
}
function simulationStep(dt) {
if (sim.ended) return;
sim.t += dt;
let aisle = 0;
for (const group of groups) {
if (group.state === "scheduled" && group.arrival <= sim.t) {
group.state = "queue";
for (const passenger of group.passengers) {
passenger.state = "queue";
}
}
if (group.state === "boarding") {
let allSeated = true;
for (const passenger of group.passengers) {
const age = sim.t - passenger.boardStart;
if (age >= passenger.duration) {
passenger.state = "seated";
} else {
allSeated = false;
if (age < passenger.travel) aisle++;
}
}
if (allSeated) group.state = "complete";
}
}
sim.aisle = aisle;
// The first eligible group cannot be skipped. This creates head-of-line
// stalls when the next intact group does not fit in the toy aisle limit.
const candidate = groups
.filter(group => group.state === "queue")
.sort(groupComparator)[0];
if (candidate) {
const free = config.capacity - sim.aisle;
if (candidate.passengers.length <= free) {
startGroup(candidate, sim.t);
} else {
sim.blockedTime += dt;
if (!candidate.blockedEpisode) {
sim.blockedEvents++;
candidate.blockedEpisode = true;
}
}
}
if (sim.t - sim.lastHistoryTime >= 0.5) {
const seated = passengers.filter(p => p.state === "seated").length;
const waiting = passengers.filter(p => p.state === "queue").length;
sim.history.push({ t: sim.t, seated, waiting });
sim.lastHistoryTime = sim.t;
}
if (passengers.every(p => p.state === "seated")) {
sim.ended = true;
sim.finishTime = sim.t;
running = false;
updateRunButton();
}
}
// ---------------------------------------------------------------------------
// Visual animation
// ---------------------------------------------------------------------------
function queuePosition(index, target) {
const perRow = 7;
const row = Math.floor(index / perRow);
const column = index % perRow;
target.set(
-2.75 + column * 0.84,
-0.22,
14.45 + row * 0.92
);
}
function boardingPosition(passenger, target) {
const age = Math.max(0, sim.t - passenger.boardStart);
const entryDuration = passenger.travel * 0.13;
if (age < entryDuration) {
const u = age / entryDuration;
target.set(
THREE.MathUtils.lerp(2.45, 0, u),
-0.22,
THREE.MathUtils.lerp(12.72, 11.65, u)
);
return;
}
if (age < passenger.travel) {
const u = (age - entryDuration) / (passenger.travel - entryDuration);
target.set(
0,
-0.22,
THREE.MathUtils.lerp(11.65, passenger.seatZ, u)
);
return;
}
const u = THREE.MathUtils.clamp(
(age - passenger.travel) / (passenger.duration - passenger.travel),
0,
1
);
target.set(
THREE.MathUtils.lerp(0, passenger.seatX, u),
-0.16,
passenger.seatZ
);
}
function updateVisuals(realDt) {
const queueGroups = groups
.filter(group => group.state === "queue")
.sort(groupComparator);
let queueIndex = 0;
for (const group of queueGroups) {
for (const passenger of group.passengers) {
queuePosition(queueIndex++, passenger.target);
}
}
const alpha = 1 - Math.exp(-realDt * 9);
for (const passenger of passengers) {
const mesh = passenger.mesh;
const state = passenger.state;
if (state === "scheduled") {
mesh.visible = false;
continue;
}
mesh.visible = true;
if (state === "queue") {
const target = passenger.target;
if (!passenger.hasPosition) {
passenger.current.copy(target);
passenger.hasPosition = true;
}
} else if (state === "boarding") {
boardingPosition(passenger, passenger.target);
passenger.current.lerp(passenger.target, Math.min(1, realDt * 15));
} else if (state === "seated") {
passenger.target.set(passenger.seatX, -0.09, passenger.seatZ);
passenger.current.lerp(passenger.target, Math.min(1, realDt * 12));
}
passenger.current.copy(passenger.target);
mesh.position.copy(passenger.current);
const seatedScale = state === "seated" ? 0.67 : 1;
const desiredScale = seatedScale;
const currentScale = mesh.scale.x;
const nextScale = THREE.MathUtils.lerp(currentScale, desiredScale, alpha);
mesh.scale.setScalar(nextScale);
mesh.userData.bag.visible = state !== "seated";
if (passenger.lastVisualState !== state) {
const material = mesh.userData.bodyMaterial;
if (state === "queue") {
material.color.set(passenger.group.priority ? COLORS.priority : COLORS.standard);
} else if (state === "boarding") {
material.color.set(COLORS.boarding);
} else if (state === "seated") {
material.color.set(COLORS.seated);
}
passenger.lastVisualState = state;
}
if (state === "seated") {
seatMaterials[passenger.slot].color.set(0x4b9d80);
} else if (state === "boarding") {
seatMaterials[passenger.slot].color.set(0x9b7945);
} else {
seatMaterials[passenger.slot].color.set(
passenger.col === 2 || passenger.col === 3 ? 0x41647b : 0x31546b
);
}
}
capacityMarkers.forEach((marker, index) => {
const active = index < sim.aisle;
marker.material.color.set(active ? 0xffc857 : 0x244256);
marker.material.emissive.set(active ? 0x4b3000 : 0x000000);
marker.material.emissiveIntensity = active ? 0.8 : 0;
});
}
// ---------------------------------------------------------------------------
// Headless comparison of all rules
// ---------------------------------------------------------------------------
function simulatePolicy(policy) {
const localConfig = { ...config, rule: policy };
const localData = createData(localConfig);
const localGroups = localData.groups;
const localPassengers = localData.passengers;
const comparator = (a, b) => {
if (policy === "priority") return b.priority - a.priority || a.id - b.id;
if (policy === "front") return a.minRow - b.minRow || a.id - b.id;
if (policy === "back") return b.maxRow - a.maxRow || a.id - b.id;
return a.rank - b.rank || a.id - b.id;
};
const dt = 0.1;
const horizon = Math.max(localData.lastArrival + 240, 300);
let t = 0;
let seated = 0;
let aisle = 0;
let blockedTime = 0;
let blockedEvents = 0;
while (t < horizon) {
t += dt;
aisle = 0;
for (const group of localGroups) {
if (group.state === "scheduled" && group.arrival <= t) {
group.state = "queue";
for (const passenger of group.passengers) passenger.state = "queue";
}
if (group.state === "boarding") {
let allSeated = true;
for (const passenger of group.passengers) {
const age = t - passenger.boardStart;
if (age >= passenger.duration) {
if (passenger.state !== "seated") {
passenger.state = "seated";
seated++;
}
} else {
allSeated = false;
if (age < passenger.travel) aisle++;
}
}
if (allSeated) group.state = "complete";
}
}
const candidate = localGroups
.filter(group => group.state === "queue")
.sort(comparator)[0];
if (candidate) {
const free = localConfig.capacity - aisle;
if (candidate.passengers.length <= free) {
candidate.state = "boarding";
for (const passenger of candidate.passengers) {
passenger.state = "boarding";
passenger.boardStart = t;
}
} else {
blockedTime += dt;
if (!candidate.blockedEpisode) {
blockedEvents++;
candidate.blockedEpisode = true;
}
}
}
if (seated === TOTAL_TRAVELERS) break;
}
const boarded = localPassengers.filter(p => p.boardStart !== null);
const averageWait = boarded.length
? boarded.reduce((sum, p) => sum + (p.boardStart - p.arrival), 0) / boarded.length
: 0;
return {
policy,
label: RULE_LABELS[policy],
finished: seated === TOTAL_TRAVELERS,
duration: seated === TOTAL_TRAVELERS ? t : Infinity,
averageWait,
blockedTime,
blockedEvents
};
}
function runComparison() {
comparisonResults = ["priority", "front", "back", "random"].map(simulatePolicy);
renderComparison();
updateHUD();
}
function renderComparison() {
const body = $("compareBody");
body.replaceChildren();
if (!comparisonResults) return;
for (const result of comparisonResults) {
const row = document.createElement("tr");
if (result.policy === config.rule) row.className = "current";
const values = [
result.label,
`${result.averageWait.toFixed(1)}s`,
Number.isFinite(result.duration) ? formatTime(result.duration) : "—",
`${result.blockedTime.toFixed(1)}s`
];
for (const value of values) {
const cell = document.createElement("td");
cell.textContent = value;
row.appendChild(cell);
}
body.appendChild(row);
}
}
// ---------------------------------------------------------------------------
// Timeline and HUD
// ---------------------------------------------------------------------------
function formatTime(seconds) {
const safe = Math.max(0, Math.floor(seconds));
const minutes = Math.floor(safe / 60);
const remainder = safe % 60;
return `${String(minutes).padStart(2, "0")}:${String(remainder).padStart(2, "0")}`;
}
function signedDifference(value, suffix = "s") {
if (Math.abs(value) < 0.05) return `matched the comparison`;
return `${value > 0 ? "+" : ""}${value.toFixed(1)}${suffix}`;
}
function getMetrics() {
const boarded = passengers.filter(p => p.boardStart !== null);
const seated = passengers.filter(p => p.state === "seated").length;
const waiting = passengers.filter(p => p.state === "queue").length;
const scheduled = passengers.filter(p => p.state === "scheduled").length;
const averageWait = boarded.length
? boarded.reduce((sum, p) => sum + (p.boardStart - p.arrival), 0) / boarded.length
: null;
return { boarded, seated, waiting, scheduled, averageWait };
}
function updateRunButton() {
$("runButton").textContent = sim?.ended ? "Run again" : running ? "Pause" : "Resume";
$("runStatus").textContent = sim?.ended ? "COMPLETE" : running ? "RUNNING" : "PAUSED";
$("runStatus").classList.toggle("live", running && !sim?.ended);
}
function updateHUD() {
if (!sim) return;
const metrics = getMetrics();
$("seatedPill").textContent = `${metrics.seated} / ${TOTAL_TRAVELERS} seated`;
$("queuePill").textContent = `${metrics.waiting} waiting`;
$("capacityText").textContent = `${sim.aisle} / ${config.capacity}`;
$("aisleValue").textContent = `${sim.aisle} / ${config.capacity}`;
$("capacityFill").style.width = `${Math.min(100, sim.aisle / config.capacity * 100)}%`;
$("avgWaitValue").textContent = metrics.averageWait === null
? "—"
: `${metrics.averageWait.toFixed(1)}s`;
$("elapsedValue").textContent = formatTime(sim.t);
$("blockedValue").textContent = `${sim.blockedTime.toFixed(1)}s`;
$("timelineSummary").textContent =
`${TOTAL_TRAVELERS} fictional travelers · ${metrics.scheduled} not yet arrived`;
$("scenarioLabel").textContent =
`${RULE_LABELS[config.rule]} · ${ARRIVAL_LABELS[config.arrival]}`;
if (sim.ended) {
const current = comparisonResults?.find(r => r.policy === config.rule);
const fastest = comparisonResults
?.filter(r => Number.isFinite(r.duration))
.sort((a, b) => a.duration - b.duration)[0];
let ending = `Under the fictional ${RULE_LABELS[config.rule]} rule with ${ARRIVAL_LABELS[config.arrival].toLowerCase()} arrivals, all ${TOTAL_TRAVELERS} travelers finished in ${formatTime(sim.finishTime)}.`;
if (current && fastest) {
const waitDifference = current.averageWait - fastest.averageWait;
const timeDifference = current.duration - fastest.duration;
ending += ` Compared with ${fastest.label}, average wait ${signedDifference(waitDifference)} and completion time ${signedDifference(timeDifference)}.`;
}
ending += " These outcomes belong only to this invented scenario.";
$("outcomeText").textContent = ending;
} else {
$("outcomeText").textContent =
`Running ${RULE_LABELS[config.rule].toLowerCase()} with ${ARRIVAL_LABELS[config.arrival].toLowerCase()}. ` +
`${metrics.seated} seated, ${metrics.waiting} at the gate, ${metrics.scheduled} not yet arrived. ` +
"Compare the rules to see how the selected policy changes waits and stalls.";
}
}
function drawTimeline() {
if (!sim || !data) return;
const canvas = $("timeline");
const rect = canvas.getBoundingClientRect();
if (!rect.width || !rect.height) return;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const width = Math.floor(rect.width * dpr);
const height = Math.floor(rect.height * dpr);
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
}
const ctx = canvas.getContext("2d");
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
const w = rect.width;
const h = rect.height;
ctx.clearRect(0, 0, w, h);
const left = 30;
const right = 8;
const top = 12;
const bottom = 23;
const plotW = w - left - right;
const plotH = h - top - bottom;
const horizon = Math.max(data.lastArrival + 75, 100);
const x = t => left + t / horizon * plotW;
// Grid.
ctx.strokeStyle = "rgba(150,180,205,.10)";
ctx.lineWidth = 1;
for (let i = 0; i <= 4; i++) {
const yy = top + plotH * i / 4;
ctx.beginPath();
ctx.moveTo(left, yy);
ctx.lineTo(w - right, yy);
ctx.stroke();
}
ctx.fillStyle = "#8199ad";
ctx.font = "9px system-ui";
ctx.textAlign = "left";
ctx.fillText("72", 5, top + 4);
ctx.fillText("0", 12, top + plotH);
// Planned arrivals.
const bins = 54;
const counts = new Array(bins).fill(0);
for (const group of groups) {
const index = Math.min(bins - 1, Math.floor(group.arrival / horizon * bins));
counts[index] += group.passengers.length;
}
const maxCount = Math.max(1, ...counts);
const barW = Math.max(1, plotW / bins - 1);
for (let i = 0; i < bins; i++) {
const barH = counts[i] / maxCount * (plotH * 0.48);
const xx = left + i / bins * plotW;
ctx.fillStyle = "rgba(84,216,209,.20)";
ctx.fillRect(xx, top + plotH - barH, barW, barH);
}
// Queue line.
if (sim.history.length > 1) {
ctx.beginPath();
sim.history.forEach((point, index) => {
const xx = x(point.t);
const yy = top + plotH - point.waiting / TOTAL_TRAVELERS * plotH;
if (index === 0) ctx.moveTo(xx, yy);
else ctx.lineTo(xx, yy);
});
ctx.strokeStyle = "rgba(255,200,87,.75)";
ctx.lineWidth = 1.4;
ctx.stroke();
}
// Seated line.
if (sim.history.length > 1) {
ctx.beginPath();
sim.history.forEach((point, index) => {
const xx = x(point.t);
const yy = top + plotH - point.seated / TOTAL_TRAVELERS * plotH;
if (index === 0) ctx.moveTo(xx, yy);
else ctx.lineTo(xx, yy);
});
ctx.strokeStyle = "#54d8d1";
ctx.lineWidth = 2;
ctx.stroke();
}
// Current cursor.
const cursorX = x(Math.min(sim.t, horizon));
ctx.strokeStyle = "rgba(255,255,255,.45)";
ctx.setLineDash([3, 4]);
ctx.beginPath();
ctx.moveTo(cursorX, top);
ctx.lineTo(cursorX, top + plotH);
ctx.stroke();
ctx.setLineDash([]);
ctx.fillStyle = "#91a7bb";
ctx.textAlign = "left";
ctx.fillText("0:00", left, h - 7);
ctx.textAlign = "center";
ctx.fillText(formatTime(horizon / 2), x(horizon / 2), h - 7);
ctx.textAlign = "right";
ctx.fillText(formatTime(horizon), w - right, h - 7);
ctx.textAlign = "left";
ctx.fillStyle = "rgba(84,216,209,.9)";
ctx.fillText("SEATED", left, top - 2);
ctx.fillStyle = "rgba(255,200,87,.85)";
ctx.fillText("WAITING", left + 52, top - 2);
}
// ---------------------------------------------------------------------------
// UI events
// ---------------------------------------------------------------------------
function updateControlLabels() {
$("groupSizeValue").textContent = `${$("groupSize").value} traveler${$("groupSize").value === "1" ? "" : "s"}`;
$("capacityValue").textContent = `${$("capacity").value} people`;
$("serviceValue").textContent = `${$("service").value}s`;
$("ruleNote").textContent = RULE_NOTES[$("rule").value];
$("arrivalNote").textContent = ARRIVAL_NOTES[$("arrival").value];
}
for (const id of ["groupSize", "capacity", "service"]) {
$(id).addEventListener("input", updateControlLabels);
}
for (const id of ["rule", "arrival", "groupSize", "capacity", "service"]) {
$(id).addEventListener("change", () => {
comparisonResults = null;
renderComparison();
resetSimulation(true);
updateControlLabels();
});
}
$("runButton").addEventListener("click", () => {
if (sim.ended) {
resetSimulation(true);
return;
}
running = !running;
updateRunButton();
});
$("resetButton").addEventListener("click", () => resetSimulation(false));
$("compareButton").addEventListener("click", runComparison);
document.querySelectorAll("[data-speed]").forEach(button => {
button.addEventListener("click", () => {
speed = Number(button.dataset.speed);
document.querySelectorAll("[data-speed]").forEach(b => b.classList.toggle("active", b === button));
});
});
updateControlLabels();
// ---------------------------------------------------------------------------
// Animation loop
// ---------------------------------------------------------------------------
let previousFrame = performance.now();
let accumulator = 0;
let lastHudUpdate = 0;
function animate(now) {
requestAnimationFrame(animate);
const realDt = Math.min(0.05, (now - previousFrame) / 1000);
previousFrame = now;
if (running && !sim.ended) {
accumulator += realDt * speed;
while (accumulator >= 0.1) {
simulationStep(0.1);
accumulator -= 0.1;
if (sim.ended) break;
}
} else {
accumulator = 0;
}
updateVisuals(realDt);
renderer.render(scene, camera);
if (now - lastHudUpdate > 100) {
updateHUD();
drawTimeline();
lastHudUpdate = now;
}
}
resetSimulation(true);
requestAnimationFrame(animate);
</script>
</body>
</html>
```