Prompt specification
Build or customize the Three.js 3D scene "Priority Queue With Explicit Criteria" 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: Priority Queue With Explicit Criteria
Category: Art & Culture · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/priority-queue-with-explicit-criteria-x3252
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows queue order and explicit priority rules. Create a public-service simulation with openly displayed priority rules and tie-breaking. Let users inspect who waits longer without assuming a scheduling algorithm defines social fairness. Low-poly.
Working Three.js Starter (priority-queue-with-explicit-criteria-x3252):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Public Service Hall — Priority and Wait-Time Lab</title>
<style>
:root {
--ink: #eef5ef;
--muted: #aabbb7;
--panel: rgba(18, 34, 37, 0.94);
--panel-2: rgba(25, 44, 47, 0.88);
--line: rgba(225, 242, 236, 0.14);
--mint: #8bd8b6;
--mint-dark: #193d35;
--urgent: #ff806c;
--appointment: #78bce7;
--standard: #efc75d;
--shadow: 0 18px 55px rgba(7, 18, 19, 0.28);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dbe4df;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, select, input { font: inherit; }
button, select { color: inherit; }
button {
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.06);
border-radius: 9px;
padding: 8px 11px;
cursor: pointer;
transition: background 140ms ease, border-color 140ms ease, transform 140ms ease;
}
button:hover {
background: rgba(255, 255, 255, 0.12);
border-color: rgba(255, 255, 255, 0.26);
}
button:active { transform: translateY(1px); }
button:focus-visible, select:focus-visible, input:focus-visible {
outline: 2px solid var(--mint);
outline-offset: 2px;
}
select {
border: 1px solid var(--line);
background: #20383b;
border-radius: 8px;
padding: 7px 9px;
}
#stage {
position: fixed;
inset: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.topbar {
position: fixed;
z-index: 10;
top: 0;
left: 0;
right: 0;
height: 72px;
padding: 11px 18px;
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: center;
gap: 16px;
background: linear-gradient(180deg, rgba(12, 27, 29, 0.97), rgba(12, 27, 29, 0.82));
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
backdrop-filter: blur(12px);
}
.brand {
display: flex;
align-items: center;
gap: 11px;
min-width: 0;
}
.brand-mark {
width: 38px;
height: 38px;
flex: 0 0 auto;
display: grid;
place-items: center;
background: var(--mint);
color: #15362e;
clip-path: polygon(50% 0, 100% 24%, 100% 76%, 50% 100%, 0 76%, 0 24%);
}
.brand-mark::after {
content: "";
width: 13px;
height: 18px;
border: 3px solid currentColor;
border-bottom: 0;
}
.brand small {
display: block;
color: var(--mint);
letter-spacing: 0.15em;
font-size: 9px;
font-weight: 800;
text-transform: uppercase;
margin-bottom: 2px;
}
.brand h1 {
margin: 0;
font-size: 18px;
line-height: 1.1;
font-weight: 720;
white-space: nowrap;
}
.clock-card {
min-width: 188px;
padding: 8px 18px;
display: grid;
grid-template-columns: auto auto;
align-items: baseline;
gap: 0 12px;
text-align: center;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.045);
}
.clock-card span:first-child {
grid-column: 1 / -1;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.14em;
}
#clock {
font-size: 23px;
font-variant-numeric: tabular-nums;
letter-spacing: 0.03em;
}
#queueCount {
color: var(--muted);
font-size: 11px;
}
.top-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
}
.mobile-only { display: none; }
.panel {
position: fixed;
z-index: 6;
top: 88px;
width: 318px;
max-height: calc(100vh - 190px);
overflow: auto;
padding: 17px;
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 16px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
scrollbar-width: thin;
scrollbar-color: rgba(255, 255, 255, 0.2) transparent;
}
.left-panel { left: 16px; }
.right-panel { right: 16px; width: 304px; }
.panel-heading {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 10px;
margin-bottom: 14px;
}
.panel-heading h2 {
margin: 0 0 4px;
font-size: 16px;
letter-spacing: -0.01em;
}
.panel-heading p {
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.badge {
flex: 0 0 auto;
padding: 4px 7px;
border-radius: 6px;
color: var(--mint);
background: rgba(139, 216, 182, 0.11);
border: 1px solid rgba(139, 216, 182, 0.23);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.tier-key {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin-bottom: 14px;
}
.tier {
position: relative;
padding: 9px 7px 8px;
min-height: 68px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
}
.tier b {
display: block;
margin-bottom: 4px;
font-size: 11px;
}
.tier small {
display: block;
color: var(--muted);
font-size: 9px;
line-height: 1.3;
}
.tier-number {
position: absolute;
top: 6px;
right: 7px;
color: rgba(255, 255, 255, 0.32);
font-size: 16px;
font-weight: 900;
}
.urgent-color { color: var(--urgent); }
.appointment-color { color: var(--appointment); }
.standard-color { color: var(--standard); }
.rules {
margin: 0;
padding-left: 21px;
color: #dbe7e2;
font-size: 11px;
line-height: 1.55;
}
.rules li { margin: 0 0 7px; padding-left: 3px; }
.rules li::marker { color: var(--mint); font-weight: 800; }
.rules b { color: white; }
.explain-box {
margin: 14px 0;
padding: 11px 12px;
border-left: 3px solid var(--mint);
border-radius: 4px 10px 10px 4px;
background: rgba(139, 216, 182, 0.08);
color: #dce9e3;
font-size: 10.5px;
line-height: 1.5;
}
.explain-box strong {
display: block;
margin-bottom: 3px;
color: var(--mint);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 15px 0 8px;
color: var(--muted);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.section-title span {
color: rgba(255, 255, 255, 0.35);
letter-spacing: 0;
text-transform: none;
font-weight: 600;
}
.desk-status {
display: grid;
gap: 5px;
}
.desk-line {
display: grid;
grid-template-columns: 36px 1fr;
align-items: center;
min-height: 29px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255, 255, 255, 0.035);
font-size: 10px;
overflow: hidden;
}
.desk-number {
align-self: stretch;
display: grid;
place-items: center;
background: rgba(255, 255, 255, 0.07);
font-weight: 850;
}
.desk-detail {
padding: 6px 8px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.desk-detail small {
display: block;
margin-top: 1px;
color: var(--muted);
font-size: 8px;
}
.order-list, .history-list {
display: grid;
gap: 5px;
}
.order-item, .history-item {
width: 100%;
display: grid;
grid-template-columns: 29px 1fr auto;
align-items: center;
gap: 8px;
padding: 7px;
border-radius: 9px;
text-align: left;
background: rgba(255, 255, 255, 0.035);
}
.rank {
width: 27px;
height: 27px;
display: grid;
place-items: center;
border-radius: 50%;
background: rgba(255, 255, 255, 0.09);
color: white;
font-size: 10px;
font-weight: 900;
}
.person-line {
min-width: 0;
font-size: 10px;
font-weight: 700;
}
.person-line small {
display: block;
margin-top: 2px;
overflow: hidden;
color: var(--muted);
font-size: 8px;
font-weight: 500;
text-overflow: ellipsis;
white-space: nowrap;
}
.wait-pill {
padding: 4px 6px;
border-radius: 6px;
background: rgba(255, 255, 255, 0.07);
font-size: 9px;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.empty {
padding: 12px;
border: 1px dashed var(--line);
border-radius: 9px;
color: var(--muted);
font-size: 10px;
text-align: center;
}
.metric-switch {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 5px;
margin-bottom: 9px;
}
.metric-switch button {
padding: 7px 4px;
color: var(--muted);
font-size: 9px;
}
.metric-switch button.active {
color: #15362e;
background: var(--mint);
border-color: var(--mint);
font-weight: 800;
}
.metric-detail {
min-height: 78px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.04);
}
.metric-detail strong {
display: block;
margin-bottom: 4px;
font-size: 20px;
font-variant-numeric: tabular-nums;
}
.metric-detail span {
color: var(--muted);
font-size: 10px;
line-height: 1.4;
}
.group-table {
margin-top: 10px;
border-top: 1px solid var(--line);
}
.group-row {
display: grid;
grid-template-columns: 1fr 57px 57px;
gap: 7px;
align-items: center;
padding: 9px 0;
border-bottom: 1px solid var(--line);
font-size: 9px;
}
.group-row.header {
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.group-row > :not(:first-child) {
text-align: right;
font-variant-numeric: tabular-nums;
}
.group-name {
font-weight: 750;
}
.group-bar {
display: block;
height: 3px;
margin-top: 5px;
border-radius: 3px;
background: rgba(255, 255, 255, 0.08);
overflow: hidden;
}
.group-bar i {
display: block;
height: 100%;
border-radius: inherit;
background: currentColor;
}
.outcome-note {
margin-top: 12px;
padding: 10px 11px;
border: 1px solid rgba(239, 199, 93, 0.2);
border-radius: 10px;
background: rgba(239, 199, 93, 0.07);
color: #e7e4d6;
font-size: 10px;
line-height: 1.48;
}
.definition {
margin: 12px 0;
color: var(--muted);
font-size: 9px;
line-height: 1.5;
}
.legend {
position: fixed;
z-index: 4;
top: 82px;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 12px;
padding: 7px 10px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 9px;
background: rgba(18, 34, 37, 0.78);
box-shadow: 0 8px 25px rgba(7, 18, 19, 0.12);
backdrop-filter: blur(10px);
font-size: 9px;
white-space: nowrap;
}
.legend span { display: flex; align-items: center; gap: 5px; }
.dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }
.dot.urgent { background: var(--urgent); }
.dot.appointment { background: var(--appointment); }
.dot.standard { background: var(--standard); }
.inspector {
position: fixed;
z-index: 8;
left: 50%;
bottom: 102px;
width: min(470px, calc(100vw - 28px));
transform: translateX(-50%);
padding: 15px;
border: 1px solid rgba(255, 255, 255, 0.17);
border-radius: 15px;
background: rgba(16, 31, 34, 0.97);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
}
.inspector[hidden] { display: none; }
.inspector-top {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 10px;
}
.inspector h2 {
margin: 0 0 3px;
font-size: 17px;
}
.inspector h2 small {
margin-left: 7px;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.close-button {
width: 30px;
height: 30px;
padding: 0;
border-radius: 50%;
font-size: 16px;
}
.inspect-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 6px;
margin: 12px 0;
}
.inspect-cell {
padding: 8px;
border-radius: 8px;
background: rgba(255, 255, 255, 0.05);
}
.inspect-cell span {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 8px;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.inspect-cell strong {
display: block;
font-size: 11px;
font-variant-numeric: tabular-nums;
}
.rule-result {
padding: 10px 11px;
border-left: 3px solid var(--mint);
border-radius: 4px 9px 9px 4px;
background: rgba(139, 216, 182, 0.07);
color: #dce9e3;
font-size: 10px;
line-height: 1.45;
}
.inspect-actions {
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px;
margin-top: 10px;
}
.inspect-actions small {
color: var(--muted);
font-size: 8px;
}
.dock {
position: fixed;
z-index: 10;
left: 50%;
bottom: 17px;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 8px;
max-width: calc(100vw - 28px);
padding: 9px;
border: 1px solid rgba(255, 255, 255, 0.14);
border-radius: 14px;
background: rgba(16, 31, 34, 0.95);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
white-space: nowrap;
}
.dock button, .dock select, .dock label {
font-size: 10px;
}
.dock .primary {
min-width: 84px;
color: #14382e;
background: var(--mint);
border-color: var(--mint);
font-weight: 850;
}
.dock-divider {
width: 1px;
height: 27px;
background: var(--line);
}
.dock-label {
display: flex;
align-items: center;
gap: 6px;
color: var(--muted);
}
.dock-label select { padding: 6px; }
.check-label {
display: flex;
align-items: center;
gap: 5px;
color: var(--muted);
cursor: pointer;
}
.check-label input { accent-color: var(--mint); }
.add-urgent { border-color: rgba(255, 128, 108, 0.45); }
.add-appointment { border-color: rgba(120, 188, 231, 0.45); }
.add-standard { border-color: rgba(239, 199, 93, 0.45); }
.tooltip {
position: fixed;
z-index: 20;
pointer-events: none;
display: none;
min-width: 165px;
padding: 9px 10px;
border: 1px solid rgba(255, 255, 255, 0.16);
border-radius: 9px;
background: rgba(13, 27, 29, 0.96);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.25);
font-size: 10px;
line-height: 1.45;
}
.tooltip strong { display: block; }
.tooltip span { color: var(--muted); }
@media (max-width: 1050px) {
.panel { width: 285px; }
.right-panel { width: 278px; }
.dock { gap: 6px; }
.dock button, .dock select, .dock label { font-size: 9px; }
.check-label.labels-check { display: none; }
}
@media (max-width: 720px) {
.topbar {
height: 64px;
grid-template-columns: 1fr auto;
padding: 9px 11px;
}
.brand h1 { font-size: 14px; }
.brand small { font-size: 8px; }
.brand-mark { width: 31px; height: 31px; }
.clock-card { display: none; }
.mobile-only { display: inline-block; }
.panel {
display: none;
top: 73px;
bottom: 91px;
width: min(88vw, 340px);
max-height: none;
}
.panel.mobile-open { display: block; }
.left-panel { left: 10px; }
.right-panel { right: 10px; }
.legend { display: none; }
.dock {
width: calc(100vw - 20px);
bottom: 9px;
flex-wrap: wrap;
justify-content: center;
white-space: normal;
}
.dock-divider { display: none; }
.dock .camera-button, .dock .check-label { display: none; }
.inspector { bottom: 98px; }
.inspect-grid { grid-template-columns: repeat(2, 1fr); }
}
</style>
</head>
<body>
<div id="stage" aria-label="Interactive low-poly public service queue"></div>
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<small>Civic Queue Lab</small>
<h1>Public Service Hall</h1>
</div>
</div>
<div class="clock-card">
<span>Simulation time</span>
<strong id="clock">09:12</strong>
<span id="queueCount">12 waiting</span>
</div>
<div class="top-actions">
<button id="toggleRules" class="mobile-only">Rules</button>
<button id="toggleOutcomes" class="mobile-only">Outcomes</button>
</div>
</header>
<div class="legend" aria-label="Request type legend">
<span><i class="dot urgent"></i> Emergency</span>
<span><i class="dot appointment"></i> Appointment</span>
<span><i class="dot standard"></i> Standard</span>
<span>Labels show global rank and wait</span>
</div>
<aside id="rulesPanel" class="panel left-panel">
<div class="panel-heading">
<div>
<h2>Published priority rules</h2>
<p>Policy version 1 · visible before every decision</p>
</div>
<span class="badge">Live rules</span>
</div>
<div class="tier-key">
<div class="tier">
<span class="tier-number">3</span>
<b class="urgent-color">Emergency</b>
<small>Highest tier</small>
</div>
<div class="tier">
<span class="tier-number">2</span>
<b class="appointment-color">Appointment</b>
<small>And aged Standard</small>
</div>
<div class="tier">
<span class="tier-number">1</span>
<b class="standard-color">Standard</b>
<small>Before aging</small>
</div>
</div>
<ol class="rules">
<li><b>Emergency requests enter tier 3</b> and are selected before all other requests.</li>
<li><b>Appointment requests enter tier 2.</b></li>
<li><b>Standard requests enter tier 1.</b></li>
<li><b>After 8 waiting minutes, a Standard request is aged into tier 2.</b> It then competes with appointments.</li>
<li><b>Tie-break: earlier recorded arrival wins</b> within the same tier. If arrival times are identical, the earlier entry sequence wins.</li>
<li><b>One global order is used.</b> Whenever an open desk becomes available, it takes the highest-ranked applicant.</li>
</ol>
<div class="explain-box">
<strong>Priority is policy, not a fairness score.</strong>
This simulation reports observed waiting times. It does not assume that the scheduling rule, FIFO, or equal rank defines social fairness.
</div>
<div class="section-title">At the desks <span id="openDeskSummary"></span></div>
<div id="deskStatus" class="desk-status"></div>
<div class="section-title">Next up <span>Global queue order</span></div>
<div id="orderList" class="order-list"></div>
</aside>
<aside id="outcomesPanel" class="panel right-panel">
<div class="panel-heading">
<div>
<h2>Observed wait outcomes</h2>
<p>Descriptive results, not a fairness judgment</p>
</div>
<span class="badge">Outcomes</span>
</div>
<div class="metric-switch" role="group" aria-label="Outcome metric">
<button data-metric="longest" class="active">Longest</button>
<button data-metric="median">Median</button>
<button data-metric="spread">Spread</button>
</div>
<div id="metricDetail" class="metric-detail"></div>
<div class="section-title">Wait by request type <span>Minutes</span></div>
<div id="groupRows" class="group-table"></div>
<div id="outcomeNote" class="outcome-note"></div>
<p class="definition">
“Open” cases include people still waiting and people currently being served.
Completed averages use time from recorded arrival to service start.
Equal waiting time, equal treatment, need-based access, and other social criteria are different questions.
</p>
<div class="section-title">Completed history <span>Click to inspect</span></div>
<div id="historyList" class="history-list"></div>
</aside>
<section id="inspector" class="inspector" hidden aria-live="polite">
<div class="inspector-top">
<div>
<h2 id="inspectorName">Applicant</h2>
<div id="inspectorType" class="appointment-color">Request type</div>
</div>
<button id="closeInspector" class="close-button" aria-label="Close inspector">×</button>
</div>
<div class="inspect-grid">
<div class="inspect-cell">
<span>Arrival</span>
<strong id="inspectArrival">—</strong>
</div>
<div class="inspect-cell">
<span>Wait</span>
<strong id="inspectWait">—</strong>
</div>
<div class="inspect-cell">
<span>Priority tier</span>
<strong id="inspectTier">—</strong>
</div>
<div class="inspect-cell">
<span>Global rank</span>
<strong id="inspectRank">—</strong>
</div>
</div>
<div id="inspectRule" class="rule-result"></div>
<div class="inspect-actions">
<small>Wait = service start − recorded arrival.</small>
<button id="focusApplicant">Focus in hall</button>
</div>
</section>
<footer class="dock">
<button id="playPause" class="primary">Pause</button>
<button id="resetSimulation">Reset</button>
<label class="dock-label">
Speed
<select id="speed">
<option value="0.5">0.5×</option>
<option value="1" selected>1×</option>
<option value="2">2×</option>
<option value="4">4×</option>
</select>
</label>
<label class="dock-label">
Open desks
<select id="deskCount">
<option value="1">1</option>
<option value="2" selected>2</option>
<option value="3">3</option>
</select>
</label>
<span class="dock-divider"></span>
<button class="add-urgent" data-add="urgent">+ Emergency</button>
<button class="add-appointment" data-add="appointment">+ Appointment</button>
<button class="add-standard" data-add="standard">+ Standard</button>
<span class="dock-divider"></span>
<label class="check-label">
<input id="autoArrivals" type="checkbox" checked>
Auto arrivals
</label>
<label class="check-label labels-check">
<input id="showLabels" type="checkbox" checked>
Labels
</label>
<button id="resetCamera" class="camera-button">Reset camera</button>
</footer>
<div id="tooltip" class="tooltip"></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (selector) => document.querySelector(selector);
const stage = $("#stage");
const TYPE = {
urgent: {
label: "Emergency",
short: "EMERGENCY",
color: 0xff806c,
css: "#ff806c",
duration: 3.5
},
appointment: {
label: "Appointment",
short: "APPOINTMENT",
color: 0x78bce7,
css: "#78bce7",
duration: 5.5
},
standard: {
label: "Standard",
short: "STANDARD",
color: 0xefc75d,
css: "#efc75d",
duration: 7.0
}
};
const AGING_THRESHOLD = 8;
const QUEUE_COLUMNS = 6;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdbe5df);
scene.fog = new THREE.Fog(0xdbe5df, 25, 48);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
stage.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const world = new THREE.Group();
const citizenLayer = new THREE.Group();
scene.add(world, citizenLayer);
const ambient = new THREE.HemisphereLight(0xeaf7f1, 0x7c8179, 2.1);
scene.add(ambient);
const sun = new THREE.DirectionalLight(0xfff4dd, 3.0);
sun.position.set(8, 18, 11);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -18;
sun.shadow.camera.right = 18;
sun.shadow.camera.top = 18;
sun.shadow.camera.bottom = -18;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 45;
sun.shadow.bias = -0.0004;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xb9d8e4, 1.0);
fill.position.set(-10, 8, 5);
scene.add(fill);
function material(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.82,
metalness: 0,
flatShading: true,
...options
});
}
function addBox(width, height, depth, color, x, y, z, parent = world, options = {}) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material(color, options)
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addCylinder(radiusTop, radiusBottom, height, color, x, y, z, parent = world, sides = 8) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radiusTop, radiusBottom, height, sides),
material(color)
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function roundedRect(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
}
function makeTextTexture(lines, options = {}) {
const canvas = document.createElement("canvas");
canvas.width = options.width || 1024;
canvas.height = options.height || 256;
const ctx = canvas.getContext("2d");
ctx.fillStyle = options.background || "#173235";
ctx.fillRect(0, 0, canvas.width, canvas.height);
if (options.border) {
ctx.strokeStyle = options.border;
ctx.lineWidth = 8;
ctx.strokeRect(4, 4, canvas.width - 8, canvas.height - 8);
}
ctx.textAlign = "center";
ctx.textBaseline = "middle";
if (lines[0]) {
ctx.fillStyle = options.primary || "#eef5ef";
ctx.font = `800 ${options.primarySize || 66}px system-ui`;
ctx.fillText(lines[0], canvas.width / 2, lines[0].includes("\n") ? 88 : 100);
}
if (lines[1]) {
ctx.fillStyle = options.secondary || "#91b7ad";
ctx.font = `600 ${options.secondarySize || 30}px system-ui`;
ctx.fillText(lines[1], canvas.width / 2, 184);
}
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy());
return texture;
}
function makeSign(texture, width, height, x, y, z, parent = world) {
const mesh = new THREE.Mesh(
new THREE.PlaneGeometry(width, height),
new THREE.MeshBasicMaterial({ map: texture, transparent: true })
);
mesh.position.set(x, y, z);
parent.add(mesh);
return mesh;
}
// Architecture: deliberately low-poly and restrained.
addBox(28, 0.5, 23, 0xcbd5ce, 0, -0.34, 0);
addBox(28, 7.2, 0.4, 0xd7ded8, 0, 3.25, -9.55);
addBox(0.4, 2.4, 19, 0xcdd6d0, -13.8, 0.85, 0);
addBox(0.4, 2.4, 19, 0xcdd6d0, 13.8, 0.85, 0);
addBox(20.5, 0.05, 9.2, 0xb9c9c2, 0, -0.065, 3.25);
addBox(3.3, 0.055, 1.25, 0x385d58, 0, -0.025, 8.7);
for (let i = 0; i < 7; i++) {
addBox(0.06, 0.012, 8.1, 0xaebfb7, -7.8 + i * 2.6, -0.03, 3.2);
}
const hallSignTexture = makeTextTexture(
["PUBLIC SERVICE HALL", "GLOBAL COUNTERS • VISIBLE PRIORITY ORDER"],
{ background: "#21463f", primary: "#f4f5e9", secondary: "#9ed8c0", border: "#739e91" }
);
makeSign(hallSignTexture, 10.5, 2.62, 0, 4.55, -9.31);
for (let i = -2; i <= 2; i++) {
addBox(3.9, 2.25, 0.10, 0xc5d1ca, i * 4.75, 2.1, -9.28);
}
// Ceiling beams.
for (const x of [-8, 0, 8]) {
addBox(0.22, 0.28, 18.5, 0x9eafa8, x, 6.4, 0);
}
// Low-poly plants.
function makePlant(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.scale.setScalar(scale);
addCylinder(0.43, 0.32, 0.65, 0xb77654, 0, 0.31, 0, group, 7);
addCylinder(0.07, 0.08, 1.25, 0x52745c, 0, 1.15, 0, group, 6);
const leafMaterial = material(0x4f8066);
for (let i = 0; i < 5; i++) {
const leaf = new THREE.Mesh(new THREE.IcosahedronGeometry(0.48, 0), leafMaterial);
const angle = (i / 5) * Math.PI * 2;
leaf.position.set(Math.cos(angle) * 0.38, 1.55 + (i % 2) * 0.22, Math.sin(angle) * 0.38);
leaf.scale.set(0.72, 1.2, 0.72);
leaf.rotation.y = angle;
leaf.castShadow = true;
group.add(leaf);
}
world.add(group);
}
makePlant(-11.2, -6.8, 1.15);
makePlant(11.2, -6.8, 1.15);
makePlant(-11.2, 6.4, 0.9);
makePlant(11.2, 6.4, 0.9);
// Benches.
for (const x of [-10, 10]) {
addBox(3.0, 0.16, 0.75, 0x8b684e, x, 0.62, 3.1);
addBox(3.0, 0.78, 0.14, 0x8b684e, x, 1.02, 2.72);
addBox(0.18, 0.62, 0.62, 0x3d514d, x - 1.1, 0.31, 3.1);
addBox(0.18, 0.62, 0.62, 0x3d514d, x + 1.1, 0.31, 3.1);
}
function buildPerson(color, isCitizen = false) {
const group = new THREE.Group();
const bodyMaterial = material(color);
const skinColors = [0xc98f6b, 0x9c694f, 0xe1ad83, 0x744a38, 0xd39b72];
const skin = material(skinColors[Math.floor(Math.random() * skinColors.length)]);
const dark = material(0x263537);
const white = material(0xf5f0df);
const body = new THREE.Mesh(
new THREE.CylinderGeometry(0.32, 0.44, 1.05, 6),
bodyMaterial
);
body.position.y = 0.83;
body.castShadow = true;
group.add(body);
const head = new THREE.Mesh(new THREE.SphereGeometry(0.31, 8, 6), skin);
head.position.y = 1.59;
head.castShadow = true;
group.add(head);
const hair = new THREE.Mesh(
new THREE.SphereGeometry(0.325, 8, 5, 0, Math.PI * 2, 0, Math.PI / 2),
material(0x293032)
);
hair.position.y = 1.6;
hair.castShadow = true;
group.add(hair);
const leftArm = addBox(0.16, 0.72, 0.18, color, -0.43, 1.0, 0, group);
const rightArm = addBox(0.16, 0.72, 0.18, color, 0.43, 1.0, 0, group);
leftArm.rotation.z = -0.08;
rightArm.rotation.z = 0.08;
addBox(0.19, 0.55, 0.22, dark, -0.17, 0.25, 0, group);
addBox(0.19, 0.55, 0.22, dark, 0.17, 0.25, 0, group);
if (isCitizen) {
addBox(0.22, 0.27, 0.045, white, 0, 1.02, 0.405, group);
}
return { group, body };
}
const desks = [];
function buildDesk(index, x) {
const group = new THREE.Group();
group.position.set(x, 0, -5.1);
world.add(group);
addBox(3.55, 1.3, 1.6, 0x496b66, 0, 0.62, 0, group);
addBox(3.85, 0.16, 1.9, 0xe0d7bd, 0, 1.35, 0, group);
addBox(3.2, 0.10, 0.12, 0x8da49d, 0, 0.72, 0.82, group);
const signTexture = makeTextTexture(
[`COUNTER ${String(index + 1).padStart(2, "0")}`, "SERVICE"],
{
width: 512,
height: 256,
background: "#315a54",
primary: "#f4f4df",
secondary: "#9bd4bd",
primarySize: 58,
secondarySize: 28
}
);
makeSign(signTexture, 2.15, 1.08, 0, 0.69, 0.806, group);
addBox(0.72, 0.48, 0.10, 0x263b3b, 0.76, 1.68, -0.18, group);
addBox(0.54, 0.34, 0.04, 0x8bc3b1, 0.76, 1.68, -0.115, group);
const lamp = new THREE.Mesh(
new THREE.SphereGeometry(0.13, 8, 5),
material(0x8bd8b6, { emissive: 0x285c47, emissiveIntensity: 0.8 })
);
lamp.position.set(1.42, 1.57, 0.45);
group.add(lamp);
const staff = buildPerson(0x3e7871, false);
staff.group.position.set(x, 0, -6.35);
world.add(staff.group);
desks.push({
index,
x,
group,
lamp,
staff: staff.group,
busy: false,
citizen: null
});
}
buildDesk(0, -5.35);
buildDesk(1, 0);
buildDesk(2, 5.35);
// Wall clock.
const clockGroup = new THREE.Group();
clockGroup.position.set(0, 4.65, -9.19);
world.add(clockGroup);
const clockFace = new THREE.Mesh(
new THREE.CircleGeometry(0.74, 32),
new THREE.MeshBasicMaterial({ color: 0xf0ead8 })
);
clockGroup.add(clockFace);
const clockRing = new THREE.Mesh(
new THREE.TorusGeometry(0.74, 0.055, 6, 32),
material(0x345c56)
);
clockRing.position.z = 0.01;
clockGroup.add(clockRing);
const hourPivot = new THREE.Group();
const minutePivot = new THREE.Group();
clockGroup.add(hourPivot, minutePivot);
addBox(0.06, 0.40, 0.035, 0x263d3c, 0, 0.2, 0.035, hourPivot);
addBox(0.045, 0.57, 0.035, 0x263d3c, 0, 0.285, 0.035, minutePivot);
const clockDot = new THREE.Mesh(
new THREE.CircleGeometry(0.065, 12),
new THREE.MeshBasicMaterial({ color: 0xe56d56 })
);
clockDot.position.z = 0.06;
clockGroup.add(clockDot);
// Simulation state.
let citizens = [];
let history = [];
let nextId = 1;
let simTime = 12;
let nextAutoArrival = 15.2;
let running = true;
let selectedId = null;
let metric = "longest";
let rngState = 12783;
function random() {
rngState = (1664525 * rngState + 1013904223) >>> 0;
return rngState / 4294967296;
}
const firstNames = [
"Ari", "Bea", "Cleo", "Dev", "Esha", "Faye", "Gio", "Hana",
"Iris", "Jon", "Kai", "Lina", "Milo", "Nia", "Omar", "Pia",
"Rafi", "Sora", "Tariq", "Uma", "Vic", "Wren", "Yara", "Zane"
];
const lastNames = [
"Adeyemi", "Bennett", "Costa", "Dubois", "Evans", "Farah", "Gupta",
"Hassan", "Ito", "Jones", "Khan", "Lopez", "Meyer", "Nakamura",
"Okafor", "Park", "Quinn", "Rivera", "Singh", "Taylor", "Ueda", "Young"
];
function randomName() {
const first = firstNames[Math.floor(random() * firstNames.length)];
const last = lastNames[Math.floor(random() * lastNames.length)];
return `${first} ${last}`;
}
function getTier(citizen) {
if (citizen.state === "served" && citizen.serviceTier !== undefined) {
return citizen.serviceTier;
}
if (citizen.type === "urgent") return 3;
if (citizen.type === "appointment") return 2;
if (simTime - citizen.arrival >= AGING_THRESHOLD) return 2;
return 1;
}
function isAged(citizen) {
return citizen.type === "standard" && getTier(citizen) === 2;
}
function tierDescription(citizen) {
if (citizen.type === "urgent") return "Emergency · tier 3";
if (citizen.type === "appointment") return "Appointment · tier 2";
if (isAged(citizen)) return "Standard, aged · tier 2";
return "Standard · tier 1";
}
function waitFor(citizen) {
if (citizen.state === "served") {
return citizen.serviceStart - citizen.arrival;
}
if (citizen.state === "serving") {
return citizen.serviceStart - citizen.arrival;
}
return simTime - citizen.arrival;
}
function getOrder() {
return citizens
.filter(c => c.state === "waiting")
.sort((a, b) => {
const tierDifference = getTier(b) - getTier(a);
if (tierDifference !== 0) return tierDifference;
if (a.arrival !== b.arrival) return a.arrival - b.arrival;
return a.id - b.id;
});
}
function drawLabel(citizen) {
const ctx = citizen.labelCanvas.getContext("2d");
const w = citizen.labelCanvas.width;
const h = citizen.labelCanvas.height;
ctx.clearRect(0, 0, w, h);
roundedRect(ctx, 3, 3, w - 6, h - 6, 18);
ctx.fillStyle = "rgba(15, 30, 32, 0.94)";
ctx.fill();
ctx.strokeStyle = TYPE[citizen.type].css;
ctx.lineWidth = 5;
ctx.stroke();
let headline;
let waitText;
if (citizen.state === "waiting") {
const order = getOrder();
const rank = order.findIndex(c => c.id === citizen.id) + 1;
headline = `#${String(rank).padStart(2, "0")} ${TYPE[citizen.type].short}${isAged(citizen) ? " · AGED" : ""}`;
waitText = `WAIT ${waitFor(citizen).toFixed(1)} min`;
} else if (citizen.state === "serving") {
headline = `DESK ${citizen.desk + 1} · ${TYPE[citizen.type].short}`;
waitText = `WAIT ${waitFor(citizen).toFixed(1)} min`;
} else {
headline = `SERVED · ${TYPE[citizen.type].short}`;
waitText = `WAIT ${waitFor(citizen).toFixed(1)} min`;
}
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = TYPE[citizen.type].css;
ctx.font = "800 25px system-ui";
ctx.fillText(headline, w / 2, 30);
ctx.fillStyle = "#f2f5ef";
ctx.font = "700 22px system-ui";
ctx.fillText(waitText, w / 2, 65);
citizen.labelTexture.needsUpdate = true;
}
function makeCitizen(type, name, arrival) {
const id = nextId++;
const visual = buildPerson(TYPE[type].color, true);
if (type === "urgent") {
addBox(0.25, 0.07, 0.04, 0xfff6e9, 0, 1.05, 0.445, visual.group);
addBox(0.07, 0.25, 0.04, 0xfff6e9, 0, 1.05, 0.446, visual.group);
} else if (type === "appointment") {
addBox(0.27, 0.36, 0.08, 0xe7edf0, 0.47, 0.77, 0.12, visual.group);
}
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.57, 0.055, 5, 20),
new THREE.MeshBasicMaterial({ color: 0xffffff })
);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.055;
ring.visible = false;
visual.group.add(ring);
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 320;
labelCanvas.height = 96;
const labelTexture = new THREE.CanvasTexture(labelCanvas);
labelTexture.colorSpace = THREE.SRGBColorSpace;
const label = new THREE.Sprite(
new THREE.SpriteMaterial({
map: labelTexture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
label.position.y = 2.38;
label.scale.set(1.9, 0.57, 1);
label.renderOrder = 20;
visual.group.add(label);
const citizen = {
id,
name,
type,
arrival,
state: "waiting",
desk: null,
serviceStart: null,
serviceEnd: null,
serviceTier: null,
removeAfter: null,
group: visual.group,
body: visual.body,
ring,
label,
labelCanvas,
labelTexture,
target: new THREE.Vector3(),
seeded: false
};
visual.group.userData.citizenId = id;
citizenLayer.add(visual.group);
citizens.push(citizen);
return citizen;
}
function dispatchWaiting() {
const order = getOrder();
const openCount = Number($("#deskCount").value);
let orderIndex = 0;
for (const desk of desks) {
if (desk.index >= openCount) continue;
if (!desk.busy && orderIndex < order.length) {
const citizen = order[orderIndex++];
citizen.state = "serving";
citizen.desk = desk.index;
citizen.serviceStart = simTime;
citizen.serviceTier = getTier(citizen);
citizen.serviceEnd = simTime + TYPE[citizen.type].duration;
desk.busy = true;
desk.citizen = citizen;
}
}
}
function updateTargets(snap = false) {
const order = getOrder();
const rankMap = new Map(order.map((c, index) => [c.id, index]));
for (const citizen of citizens) {
if (citizen.state === "waiting") {
const rank = rankMap.get(citizen.id) ?? 0;
const row = Math.floor(rank / QUEUE_COLUMNS);
const column = rank % QUEUE_COLUMNS;
const x = (column - (QUEUE_COLUMNS - 1) / 2) * 1.65 + (row % 2 ? 0.28 : -0.28);
const z = -0.15 + row * 1.43;
citizen.target.set(x, 0, z);
} else if (citizen.state === "serving") {
citizen.target.set(desks[citizen.desk].x, 0, -3.48);
} else if (citizen.state === "served") {
citizen.target.set(-12.0, 0, 7.8);
}
if (snap) citizen.group.position.copy(citizen.target);
}
}
function completeService(citizen) {
citizen.serviceEnd = simTime;
citizen.state = "served";
citizen.removeAfter = simTime + 2.8;
const desk = desks[citizen.desk];
desk.busy = false;
desk.citizen = null;
history.unshift(citizen);
}
function spawnAutomatic(arrival) {
const roll = random();
const type = roll < 0.12 ? "urgent" : roll < 0.42 ? "appointment" : "standard";
const citizen = makeCitizen(type, randomName(), arrival);
return citizen;
}
function resetSimulation() {
for (const citizen of citizens) {
citizen.group.traverse(object => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const materials = Array.isArray(object.material) ? object.material : [object.material];
for (const mat of materials) {
if (mat.map) mat.map.dispose();
mat.dispose();
}
}
});
}
citizenLayer.clear();
citizens = [];
history = [];
nextId = 1;
simTime = 12;
nextAutoArrival = 15.2;
selectedId = null;
rngState = 12783;
running = true;
$("#playPause").textContent = "Pause";
for (const desk of desks) {
desk.busy = false;
desk.citizen = null;
}
const initialPopulation = [
["urgent", "Mara Okafor", 11.4],
["appointment", "Eli Chen", 10.1],
["standard", "Samira Bello", 3.6],
["standard", "Jonah Reed", 0.4],
["appointment", "Ana Costa", 9.2],
["standard", "Louis Park", 6.0],
["urgent", "Nora Singh", 11.85],
["standard", "Ibrahim Ali", 1.4],
["appointment", "Mina Chen", 4.4],
["standard", "Theo James", 7.3],
["standard", "Rosa Diaz", 2.5],
["appointment", "Owen Hart", 8.0]
];
for (const [type, name, arrival] of initialPopulation) {
makeCitizen(type, name, arrival);
}
dispatchWaiting();
updateTargets(true);
updateUI();
updateLabels();
}
function updateSimulation(realDelta) {
// At 1×, one real second advances 0.5 simulation minutes.
simTime += realDelta * 0.5;
if ($("#autoArrivals").checked) {
while (simTime >= nextAutoArrival) {
spawnAutomatic(nextAutoArrival);
nextAutoArrival += 3.2 + random() * 3.4;
}
}
for (const citizen of citizens) {
if (citizen.state === "serving" && simTime >= citizen.serviceEnd) {
completeService(citizen);
}
}
dispatchWaiting();
updateTargets();
for (let i = citizens.length - 1; i >= 0; i--) {
const citizen = citizens[i];
if (citizen.state === "served" && simTime > citizen.removeAfter) {
citizenLayer.remove(citizen.group);
citizens.splice(i, 1);
}
}
}
function formatClock(minutes) {
const totalMinutes = Math.round(9 * 60 + minutes);
const hours = Math.floor(totalMinutes / 60) % 24;
const mins = totalMinutes % 60;
return `${String(hours).padStart(2, "0")}:${String(mins).padStart(2, "0")}`;
}
function updateClockHands() {
const minuteAngle = -((simTime % 60) / 60) * Math.PI * 2;
const hour = (9 + simTime / 60) % 12;
const hourAngle = -(hour / 12) * Math.PI * 2;
minutePivot.rotation.z = minuteAngle;
hourPivot.rotation.z = hourAngle;
}
function updatePeople(delta, elapsed) {
for (const citizen of citizens) {
const movement = 1 - Math.exp(-delta * 4.2);
citizen.group.position.lerp(citizen.target, movement);
const dx = citizen.target.x - citizen.group.position.x;
const dz = citizen.target.z - citizen.group.position.z;
const moving = Math.hypot(dx, dz) > 0.06;
citizen.group.position.y = moving ? Math.sin(elapsed * 9 + citizen.id) * 0.035 : 0;
const targetRotation = citizen.state === "serving" ? Math.PI : 0;
citizen.group.rotation.y += (targetRotation - citizen.group.rotation.y) * movement;
citizen.ring.visible = citizen.id === selectedId;
citizen.label.visible = $("#showLabels").checked;
}
for (const desk of desks) {
desk.staff.rotation.y = Math.sin(elapsed * 0.5 + desk.index) * 0.035;
}
}
function updateLabels() {
for (const citizen of citizens) drawLabel(citizen);
}
function median(values) {
if (!values.length) return 0;
const sorted = [...values].sort((a, b) => a - b);
const middle = Math.floor(sorted.length / 2);
return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
}
function average(values) {
if (!values.length) return null;
return values.reduce((sum, value) => sum + value, 0) / values.length;
}
function updateUI() {
const waiting = citizens.filter(c => c.state === "waiting");
const openCases = citizens.filter(c => c.state === "waiting" || c.state === "serving");
const order = getOrder();
$("#clock").textContent = formatClock(simTime);
$("#queueCount").textContent = `${waiting.length} waiting`;
$("#openDeskSummary").textContent = `${$("#deskCount").value} of 3 open`;
for (const desk of desks) {
const openCount = Number($("#deskCount").value);
const isClosed = desk.index >= openCount;
const color = isClosed ? 0x687978 : desk.busy ? 0xefc75d : 0x8bd8b6;
desk.lamp.material.color.setHex(color);
desk.lamp.material.emissive.setHex(color);
desk.lamp.material.emissiveIntensity = isClosed ? 0.15 : 0.8;
}
$("#deskStatus").innerHTML = desks.map(desk => {
const openCount = Number($("#deskCount").value);
const closed = desk.index >= openCount;
const citizen = desk.citizen;
const main = closed
? "Closed"
: citizen
? citizen.name
: "Open · next applicant will be selected";
const sub = closed
? "No service scheduled"
: citizen
? `${TYPE[citizen.type].label} · wait ${waitFor(citizen).toFixed(1)} min`
: "Waiting for the global queue";
return `
<div class="desk-line">
<div class="desk-number">${String(desk.index + 1).padStart(2, "0")}</div>
<div class="desk-detail">
${main}
<small>${sub}</small>
</div>
</div>
`;
}).join("");
$("#orderList").innerHTML = order.length ? order.slice(0, 7).map((citizen, index) => `
<button class="order-item" data-id="${citizen.id}">
<span class="rank">${index + 1}</span>
<span class="person-line">
${citizen.name}
<small>${tierDescription(citizen)}</small>
</span>
<span class="wait-pill">${waitFor(citizen).toFixed(1)}m</span>
</button>
`).join("") : `<div class="empty">No one is waiting.</div>`;
const waits = openCases.map(waitFor);
const longest = openCases.length
? openCases.reduce((best, citizen) => waitFor(citizen) > waitFor(best) ? citizen : best)
: null;
if (metric === "longest") {
$("#metricDetail").innerHTML = longest
? `<strong>${waitFor(longest).toFixed(1)} min</strong>
<span>Longest open wait: ${longest.name}, ${TYPE[longest.type].label.toLowerCase()} request.</span>`
: `<strong>0.0 min</strong><span>There are no open service episodes.</span>`;
} else if (metric === "median") {
const value = median(waits);
$("#metricDetail").innerHTML = `
<strong>${value.toFixed(1)} min</strong>
<span>Median wait across ${openCases.length} open service episode${openCases.length === 1 ? "" : "s"}.</span>
`;
} else {
const spread = waits.length ? Math.max(...waits) - Math.min(...waits) : 0;
$("#metricDetail").innerHTML = `
<strong>${spread.toFixed(1)} min</strong>
<span>Difference between the longest and shortest open waits.</span>
`;
}
const maximumAverage = Math.max(
0.1,
...Object.keys(TYPE).map(type => {
const values = openCases.filter(c => c.type === type).map(waitFor);
return average(values) || 0;
})
);
$("#groupRows").innerHTML = `
<div class="group-row header">
<span>Request type</span><span>Open avg.</span><span>Done avg.</span>
</div>
${Object.entries(TYPE).map(([type, info]) => {
const openValues = openCases.filter(c => c.type === type).map(waitFor);
const doneValues = history.filter(c => c.type === type).map(waitFor);
const openAverage = average(openValues);
const doneAverage = average(doneValues);
const width = openAverage ? (openAverage / maximumAverage) * 100 : 0;
return `
<div class="group-row">
<div class="group-name ${type}-color">
${info.label}
<span class="group-bar"><i style="width:${width}%"></i></span>
</div>
<div>${openAverage === null ? "—" : openAverage.toFixed(1)}</div>
<div>${doneAverage === null ? "—" : doneAverage.toFixed(1)}</div>
</div>
`;
}).join("")}
`;
$("#outcomeNote").innerHTML = longest
? `<strong>Observation:</strong> ${longest.name} currently has the longest open wait at ${waitFor(longest).toFixed(1)} minutes. This identifies an observed outcome; it does not determine whether the policy is fair.`
: `<strong>Observation:</strong> No open cases are being tracked. Completed service history will appear below.`;
$("#historyList").innerHTML = history.length ? history.slice(0, 6).map(citizen => `
<button class="history-item" data-id="${citizen.id}">
<span class="rank">✓</span>
<span class="person-line">
${citizen.name}
<small>${TYPE[citizen.type].label} · desk ${citizen.desk + 1}</small>
</span>
<span class="wait-pill">${waitFor(citizen).toFixed(1)}m</span>
</button>
`).join("") : `<div class="empty">No services completed yet. Increase speed to observe outcomes.</div>`;
updateInspector();
}
function updateInspector() {
const panel = $("#inspector");
const citizen = citizens.find(c => c.id === selectedId);
if (!citizen) {
panel.hidden = true;
return;
}
panel.hidden = false;
$("#inspectorName").innerHTML = `${citizen.name}`;
$("#inspectorType").className = `${citizen.type}-color`;
$("#inspectorType").textContent = `${TYPE[citizen.type].label} request`;
$("#inspectArrival").textContent = formatClock(citizen.arrival);
$("#inspectWait").textContent = `${waitFor(citizen).toFixed(1)} min`;
const tier = getTier(citizen);
$("#inspectTier").textContent = `Tier ${tier}${isAged(citizen) ? " · aged" : ""}`;
const order = getOrder();
const rank = order.findIndex(c => c.id === citizen.id);
if (citizen.state === "waiting") {
$("#inspectRank").textContent = `${rank + 1} of ${order.length}`;
const ahead = order.slice(0, rank);
const higher = ahead.filter(c => getTier(c) > tier).length;
const sameTierEarlier = ahead.filter(c => getTier(c) === tier).length;
$("#inspectRule").innerHTML = `
<strong>Why this position?</strong><br>
${tierDescription(citizen)}. ${higher} higher-tier request${higher === 1 ? " is" : "s are"} ahead.
${sameTierEarlier} same-tier request${sameTierEarlier === 1 ? " arrived" : "s arrived"} earlier and therefore rank ahead under the tie-break.
`;
} else if (citizen.state === "serving") {
$("#inspectRank").textContent = `Desk ${citizen.desk + 1}`;
$("#inspectRule").innerHTML = `
<strong>Selected at ${formatClock(citizen.serviceStart)}.</strong><br>
This request was the highest-ranked open case when desk ${citizen.desk + 1} became available.
Its recorded wait was ${waitFor(citizen).toFixed(1)} minutes.
`;
} else {
$("#inspectRank").textContent = "Completed";
$("#inspectRule").innerHTML = `
<strong>Service completed.</strong><br>
Arrival ${formatClock(citizen.arrival)} · service start ${formatClock(citizen.serviceStart)} ·
service end ${formatClock(citizen.serviceEnd)}. Total wait: ${waitFor(citizen).toFixed(1)} minutes.
`;
}
}
function selectCitizen(id) {
selectedId = id;
updateUI();
}
// Custom camera controls. No Three.js examples or addons are used.
const cameraTarget = new THREE.Vector3(0, 0.8, -0.5);
let cameraAzimuth = 0.17;
let cameraPolar = 1.03;
let cameraRadius = 25.5;
const defaultCamera = {
target: new THREE.Vector3(0, 0.8, -0.5),
azimuth: 0.17,
polar: 1.03,
radius: 25.5
};
function updateCamera() {
const sinPolar = Math.sin(cameraPolar);
camera.position.set(
cameraTarget.x + cameraRadius * sinPolar * Math.sin(cameraAzimuth),
cameraTarget.y + cameraRadius * Math.cos(cameraPolar),
cameraTarget.z + cameraRadius * sinPolar * Math.cos(cameraAzimuth)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraTarget.copy(defaultCamera.target);
cameraAzimuth = defaultCamera.azimuth;
cameraPolar = defaultCamera.polar;
cameraRadius = defaultCamera.radius;
updateCamera();
}
const canvas = renderer.domElement;
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let pointerDown = false;
let panning = false;
let pointerStart = { x: 0, y: 0 };
let lastPointer = { x: 0, y: 0 };
function setPointerFromEvent(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function pickCitizen(event) {
setPointerFromEvent(event);
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(citizenLayer.children, true);
for (const hit of hits) {
let object = hit.object;
while (object && object.userData.citizenId === undefined) {
object = object.parent;
}
if (object) {
return citizens.find(c => c.id === object.userData.citizenId);
}
}
return null;
}
canvas.addEventListener("pointerdown", event => {
pointerDown = true;
panning = event.button === 2 || event.button === 1 || event.shiftKey;
pointerStart = { x: event.clientX, y: event.clientY };
lastPointer = { x: event.clientX, y: event.clientY };
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
if (pointerDown) {
const dx = event.clientX - lastPointer.x;
const dy = event.clientY - lastPointer.y;
if (panning) {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3().crossVectors(forward, new THREE.Vector3(0, 1, 0)).normalize();
const factor = cameraRadius * 0.0016;
cameraTarget.addScaledVector(right, -dx * factor);
cameraTarget.addScaledVector(forward, dy * factor);
cameraTarget.x = THREE.MathUtils.clamp(cameraTarget.x, -12, 12);
cameraTarget.z = THREE.MathUtils.clamp(cameraTarget.z, -8, 10);
} else {
cameraAzimuth -= dx * 0.006;
cameraPolar = THREE.MathUtils.clamp(cameraPolar - dy * 0.005, 0.42, 1.42);
}
lastPointer = { x: event.clientX, y: event.clientY };
}
const citizen = pickCitizen(event);
const tooltip = $("#tooltip");
if (citizen) {
tooltip.style.display = "block";
tooltip.style.left = `${Math.min(event.clientX + 14, window.innerWidth - 190)}px`;
tooltip.style.top = `${Math.min(event.clientY + 14, window.innerHeight - 90)}px`;
tooltip.innerHTML = `
<strong>${citizen.name}</strong>
<span>${TYPE[citizen.type].label} · ${tierDescription(citizen)}</span>
<span>Wait ${waitFor(citizen).toFixed(1)} min · click to inspect</span>
`;
canvas.style.cursor = "pointer";
} else {
tooltip.style.display = "none";
canvas.style.cursor = pointerDown ? (panning ? "grabbing" : "grabbing") : "grab";
}
});
canvas.addEventListener("pointerup", event => {
const movement = Math.hypot(
event.clientX - pointerStart.x,
event.clientY - pointerStart.y
);
if (movement < 6 && event.button === 0) {
const citizen = pickCitizen(event);
if (citizen) selectCitizen(citizen.id);
}
pointerDown = false;
panning = false;
if (canvas.hasPointerCapture(event.pointerId)) canvas.releasePointerCapture(event.pointerId);
});
canvas.addEventListener("pointerleave", () => {
$("#tooltip").style.display = "none";
pointerDown = false;
});
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(cameraRadius * Math.exp(event.deltaY * 0.001), 8, 40);
updateCamera();
}, { passive: false });
canvas.addEventListener("contextmenu", event => event.preventDefault());
// UI events.
$("#playPause").addEventListener("click", () => {
running = !running;
$("#playPause").textContent = running ? "Pause" : "Play";
});
$("#resetSimulation").addEventListener("click", resetSimulation);
$("#deskCount").addEventListener("change", () => {
dispatchWaiting();
updateTargets();
updateUI();
});
document.querySelectorAll("[data-add]").forEach(button => {
button.addEventListener("click", () => {
const citizen = makeCitizen(button.dataset.add, randomName(), simTime);
if (running) dispatchWaiting();
updateTargets();
selectCitizen(citizen.id);
updateUI();
});
});
document.querySelectorAll("[data-metric]").forEach(button => {
button.addEventListener("click", () => {
metric = button.dataset.metric;
document.querySelectorAll("[data-metric]").forEach(b => {
b.classList.toggle("active", b === button);
});
updateUI();
});
});
$("#orderList").addEventListener("click", event => {
const button = event.target.closest("[data-id]");
if (button) selectCitizen(Number(button.dataset.id));
});
$("#historyList").addEventListener("click", event => {
const button = event.target.closest("[data-id]");
if (button) selectCitizen(Number(button.dataset.id));
});
$("#closeInspector").addEventListener("click", () => {
selectedId = null;
updateUI();
});
$("#focusApplicant").addEventListener("click", () => {
const citizen = citizens.find(c => c.id === selectedId);
if (!citizen) return;
cameraTarget.set(citizen.group.position.x, 0.75, citizen.group.position.z);
cameraRadius = 12;
cameraPolar = 1.0;
updateCamera();
});
$("#resetCamera").addEventListener("click", resetCamera);
$("#toggleRules").addEventListener("click", () => {
$("#rulesPanel").classList.toggle("mobile-open");
$("#outcomesPanel").classList.remove("mobile-open");
});
$("#toggleOutcomes").addEventListener("click", () => {
$("#outcomesPanel").classList.toggle("mobile-open");
$("#rulesPanel").classList.remove("mobile-open");
});
window.addEventListener("keydown", event => {
if (["INPUT", "SELECT", "TEXTAREA"].includes(document.activeElement.tagName)) return;
if (event.code === "Space") {
event.preventDefault();
$("#playPause").click();
}
if (event.key === "1") document.querySelector('[data-add="urgent"]').click();
if (event.key === "2") document.querySelector('[data-add="appointment"]').click();
if (event.key === "3") document.querySelector('[data-add="standard"]').click();
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
const clock = new THREE.Clock();
let elapsed = 0;
let uiTimer = 0;
let labelTimer = 0;
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
elapsed += delta;
if (running) {
updateSimulation(delta * Number($("#speed").value));
}
updatePeople(delta, elapsed);
updateClockHands();
updateCamera();
uiTimer += delta;
labelTimer += delta;
if (uiTimer > 0.25) {
uiTimer = 0;
updateUI();
}
if (labelTimer > 0.3) {
labelTimer = 0;
updateLabels();
}
renderer.render(scene, camera);
}
resetSimulation();
resetCamera();
animate();
</script>
</body>
</html>
```