Prompt specification
Build or customize the Three.js 3D scene "Dispatch Rule Comparison in a Toy Building" 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: Dispatch Rule Comparison in a Toy Building
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/dispatch-rule-comparison-in-a-toy-building-x2096
Scene Description Prompt:
Compare two explicit elevator dispatch rules under identical fictional requests. Display waits and travel distance while clearly limiting the result to the simplified model. Use Three.js from cdnjs in a single HTML file, with visible voxel blocks.
Working Three.js Starter (dispatch-rule-comparison-in-a-toy-building-x2096):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Elevator Dispatch Comparison</title>
<style>
:root {
color-scheme: dark;
--bg: #07101d;
--panel: #101c2d;
--panel-2: #15243a;
--line: #273953;
--text: #e8f0fb;
--muted: #96a8c2;
--a: #2dd4bf;
--b: #a78bfa;
--amber: #f59e0b;
--green: #22c55e;
--red: #fb7185;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-height: 100vh;
background:
radial-gradient(circle at 15% 0%, rgba(45, 212, 191, 0.10), transparent 30rem),
radial-gradient(circle at 85% 0%, rgba(167, 139, 250, 0.10), transparent 32rem),
var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
select {
font: inherit;
}
.app {
width: min(1580px, 100%);
margin: 0 auto;
padding: 26px 22px 34px;
}
.hero {
display: flex;
justify-content: space-between;
gap: 24px;
align-items: flex-end;
margin-bottom: 18px;
}
.eyebrow {
margin: 0 0 7px;
color: var(--a);
font-size: 0.75rem;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
h1 {
margin: 0;
max-width: 850px;
font-size: clamp(1.8rem, 3.6vw, 3.15rem);
line-height: 1.05;
letter-spacing: -0.04em;
}
.hero p {
max-width: 740px;
margin: 11px 0 0;
color: var(--muted);
line-height: 1.55;
}
.model-stamp {
flex: 0 0 auto;
max-width: 270px;
padding: 11px 13px;
border: 1px solid #725326;
border-radius: 10px;
background: rgba(245, 158, 11, 0.08);
color: #f9d58b;
font-size: 0.78rem;
line-height: 1.45;
}
.controls {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 9px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(16, 28, 45, 0.86);
}
.controls button,
.controls select {
min-height: 38px;
border: 1px solid #344968;
border-radius: 9px;
background: #192a42;
color: var(--text);
padding: 0 13px;
}
.controls button {
cursor: pointer;
font-weight: 750;
}
.controls button:hover {
border-color: #58749d;
background: #20344f;
}
.controls button.primary {
border-color: transparent;
background: var(--a);
color: #06201c;
}
.controls button.primary:hover {
background: #5eead4;
}
.controls label {
display: flex;
align-items: center;
gap: 7px;
margin-left: auto;
color: var(--muted);
font-size: 0.85rem;
}
.run-state {
min-width: 175px;
color: var(--muted);
font-size: 0.84rem;
font-variant-numeric: tabular-nums;
}
.verdict {
display: flex;
align-items: center;
gap: 11px;
min-height: 48px;
margin: 12px 0;
padding: 10px 14px;
border: 1px solid var(--line);
border-radius: 12px;
background: #0d1828;
color: var(--muted);
font-size: 0.9rem;
line-height: 1.45;
}
.verdict::before {
content: "";
width: 9px;
height: 9px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--amber);
box-shadow: 0 0 12px rgba(245, 158, 11, 0.5);
}
.verdict.complete::before {
background: var(--green);
box-shadow: 0 0 12px rgba(34, 197, 94, 0.5);
}
.layout {
display: grid;
grid-template-columns: minmax(0, 1fr) 370px;
gap: 14px;
align-items: start;
}
.stage-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
}
.rule-card,
.panel {
border: 1px solid var(--line);
border-radius: 15px;
background: linear-gradient(180deg, rgba(18, 31, 49, 0.98), rgba(12, 22, 36, 0.98));
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.16);
overflow: hidden;
}
.rule-head {
display: flex;
justify-content: space-between;
gap: 12px;
padding: 14px 15px 12px;
border-bottom: 1px solid var(--line);
}
.rule-title {
display: flex;
align-items: center;
gap: 9px;
font-weight: 850;
letter-spacing: -0.015em;
}
.rule-letter {
display: grid;
place-items: center;
width: 29px;
height: 29px;
border-radius: 8px;
color: #071421;
font-weight: 900;
}
.rule-a .rule-letter {
background: var(--a);
}
.rule-b .rule-letter {
background: var(--b);
}
.rule-description {
margin: 5px 0 0;
color: var(--muted);
font-size: 0.78rem;
line-height: 1.4;
}
.rule-status {
align-self: flex-start;
color: var(--muted);
font-size: 0.72rem;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.viewport {
position: relative;
height: clamp(370px, 50vh, 560px);
overflow: hidden;
background: #08111f;
}
.viewport canvas {
position: absolute;
inset: 0;
z-index: 0;
width: 100%;
height: 100%;
display: block;
cursor: grab;
touch-action: none;
}
.viewport canvas:active {
cursor: grabbing;
}
.view-badge,
.legend,
.view-help {
position: absolute;
z-index: 2;
pointer-events: none;
}
.view-badge {
top: 12px;
left: 12px;
padding: 6px 9px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 7px;
background: rgba(5, 12, 23, 0.74);
color: #dce8f8;
font-size: 0.72rem;
font-weight: 750;
backdrop-filter: blur(7px);
}
.legend {
right: 10px;
bottom: 10px;
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 8px;
max-width: 220px;
font-size: 0.66rem;
color: #b7c6da;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 4px;
}
.legend i {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 2px;
}
.view-help {
left: 12px;
bottom: 11px;
color: #8498b4;
font-size: 0.66rem;
}
.metrics {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 1px;
background: var(--line);
}
.metric {
min-height: 88px;
padding: 12px 14px;
background: #0e1929;
}
.metric > span {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 0.7rem;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.metric strong {
display: block;
font-size: 1.35rem;
line-height: 1.1;
font-variant-numeric: tabular-nums;
}
.metric small {
display: block;
margin-top: 5px;
color: #7f93ae;
font-size: 0.68rem;
line-height: 1.3;
}
.side {
display: grid;
gap: 14px;
}
.panel {
padding: 15px;
}
.panel h2 {
margin: 0;
font-size: 1rem;
letter-spacing: -0.01em;
}
.panel-intro {
margin: 5px 0 12px;
color: var(--muted);
font-size: 0.78rem;
line-height: 1.45;
}
.scenario-pills {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 13px;
}
.scenario-pills span {
padding: 4px 7px;
border: 1px solid #314767;
border-radius: 999px;
color: #b9c9dc;
font-size: 0.68rem;
}
.table-wrap {
overflow-x: auto;
border: 1px solid var(--line);
border-radius: 10px;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 0.72rem;
}
th,
td {
padding: 8px 8px;
border-bottom: 1px solid #213149;
text-align: left;
white-space: nowrap;
}
th {
background: #142238;
color: #9fb1c9;
font-size: 0.63rem;
letter-spacing: 0.04em;
text-transform: uppercase;
}
tbody tr:last-child td {
border-bottom: 0;
}
td {
color: #cbd7e7;
font-variant-numeric: tabular-nums;
}
td strong {
color: #f5f8fc;
}
.req-id {
display: inline-flex;
align-items: center;
gap: 5px;
font-weight: 800;
}
.req-dot {
width: 7px;
height: 7px;
border-radius: 2px;
background: var(--amber);
}
.request-state {
display: block;
margin-top: 2px;
color: #8094af;
font-size: 0.62rem;
font-weight: 500;
}
.request-state.done {
color: #67df92;
}
.request-state.waiting {
color: #f6bd52;
}
.request-state.active {
color: #71c8ff;
}
details {
border-top: 1px solid var(--line);
margin-top: 13px;
padding-top: 12px;
}
summary {
cursor: pointer;
font-size: 0.82rem;
font-weight: 800;
}
details ul {
margin: 10px 0 0;
padding-left: 18px;
color: var(--muted);
font-size: 0.74rem;
line-height: 1.55;
}
details li + li {
margin-top: 5px;
}
.caution {
margin-top: 12px;
padding: 10px;
border: 1px solid #684f25;
border-radius: 9px;
background: rgba(245, 158, 11, 0.07);
color: #e9c780;
font-size: 0.72rem;
line-height: 1.45;
}
footer {
margin-top: 17px;
color: #7287a2;
font-size: 0.72rem;
line-height: 1.5;
text-align: center;
}
@media (max-width: 1180px) {
.layout {
grid-template-columns: 1fr;
}
.side {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 760px) {
.app {
padding: 18px 12px 28px;
}
.hero {
display: block;
}
.model-stamp {
max-width: none;
margin-top: 13px;
}
.stage-grid,
.side {
grid-template-columns: 1fr;
}
.controls label {
margin-left: 0;
}
.run-state {
width: 100%;
}
.viewport {
height: 430px;
}
}
</style>
</head>
<body>
<div class="app">
<header class="hero">
<div>
<p class="eyebrow">Dispatch rules under one workload</p>
<h1>Same elevator calls. Two different decisions.</h1>
<p>
Both simulations receive the same eight fictional requests. Compare
passenger wait and elevator travel while watching the voxel elevators
move through a six-floor cutaway.
</p>
</div>
<div class="model-stamp">
<strong>Model-bounded result</strong><br>
One fictional request set and a deliberately simplified elevator model.
This is not a general building-performance comparison.
</div>
</header>
<section class="controls" aria-label="Simulation controls">
<button id="run" class="primary" type="button">Run comparison</button>
<button id="reset" type="button">Reset</button>
<button id="finish" type="button">Finish</button>
<label for="speed">
Playback
<select id="speed">
<option value="1">1×</option>
<option value="4" selected>4×</option>
<option value="12">12×</option>
</select>
</label>
<div id="runState" class="run-state" aria-live="polite">Paused at 0.0 tu</div>
</section>
<div id="verdict" class="verdict" aria-live="polite">
Run the comparison to calculate waits, loaded travel, and repositioning distance.
</div>
<main class="layout">
<section class="stage-grid" aria-label="Side-by-side elevator simulations">
<article class="rule-card rule-a">
<header class="rule-head">
<div>
<div class="rule-title">
<span class="rule-letter">A</span>
FIFO + nearest free car
</div>
<p class="rule-description">
The oldest waiting call goes first. The nearest idle elevator takes it.
</p>
</div>
<div id="a-status" class="rule-status">0 / 8 done</div>
</header>
<div id="viewA" class="viewport">
<div class="view-badge">Rule A · oldest call first</div>
<div class="view-help">Drag to orbit · wheel/pinch to zoom</div>
<div class="legend">
<span><i style="background:#f59e0b"></i>waiting</span>
<span><i style="background:#38bdf8"></i>assigned</span>
<span><i style="background:#a78bfa"></i>riding</span>
<span><i style="background:#22c55e"></i>done</span>
</div>
</div>
<div class="metrics">
<div class="metric">
<span>Average wait</span>
<strong id="a-avg">—</strong>
<small>model time units</small>
</div>
<div class="metric">
<span>Maximum wait</span>
<strong id="a-max">—</strong>
<small>model time units</small>
</div>
<div class="metric">
<span>Car travel</span>
<strong id="a-travel">—</strong>
<small id="a-travel-detail">loaded + repositioning floor-units</small>
</div>
<div class="metric">
<span>Repositioning</span>
<strong id="a-deadhead">—</strong>
<small>floor-units before pickup</small>
</div>
</div>
</article>
<article class="rule-card rule-b">
<header class="rule-head">
<div>
<div class="rule-title">
<span class="rule-letter">B</span>
Greedy least-work
</div>
<p class="rule-description">
Pick the waiting call and free car with the least deadhead plus trip distance.
</p>
</div>
<div id="b-status" class="rule-status">0 / 8 done</div>
</header>
<div id="viewB" class="viewport">
<div class="view-badge">Rule B · least estimated work</div>
<div class="view-help">Drag to orbit · wheel/pinch to zoom</div>
<div class="legend">
<span><i style="background:#f59e0b"></i>waiting</span>
<span><i style="background:#38bdf8"></i>assigned</span>
<span><i style="background:#a78bfa"></i>riding</span>
<span><i style="background:#22c55e"></i>done</span>
</div>
</div>
<div class="metrics">
<div class="metric">
<span>Average wait</span>
<strong id="b-avg">—</strong>
<small>model time units</small>
</div>
<div class="metric">
<span>Maximum wait</span>
<strong id="b-max">—</strong>
<small>model time units</small>
</div>
<div class="metric">
<span>Car travel</span>
<strong id="b-travel">—</strong>
<small id="b-travel-detail">loaded + repositioning floor-units</small>
</div>
<div class="metric">
<span>Repositioning</span>
<strong id="b-deadhead">—</strong>
<small>floor-units before pickup</small>
</div>
</div>
</article>
</section>
<aside class="side">
<section class="panel">
<h2>Identical request set</h2>
<p class="panel-intro">
Each rule receives these calls in the same order. “tu” means an arbitrary
model time unit, not real building seconds.
</p>
<div class="scenario-pills">
<span>8 calls</span>
<span>6 floors</span>
<span>2 elevators</span>
<span>Starts at 1F and 4F</span>
</div>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Call</th>
<th>At</th>
<th>Route</th>
<th>A wait</th>
<th>B wait</th>
</tr>
</thead>
<tbody id="requestRows"></tbody>
</table>
</div>
<details open>
<summary>Model assumptions</summary>
<ul>
<li>One elevator serves one request per trip; no batching.</li>
<li>One floor takes one time unit to travel.</li>
<li>Pickup and drop-off each use 0.4 time units.</li>
<li>No passenger walking, transfers, capacity limits, or door direction logic.</li>
<li>Wait ends when an elevator reaches the pickup floor.</li>
<li>Rule B may serve a newer call before an older one.</li>
</ul>
</details>
<div class="caution">
Only this fictional request set and simplified model are represented.
No claim is made about general efficiency, passenger satisfaction,
fairness under sustained demand, or real-world elevator performance.
</div>
</section>
<section class="panel">
<h2>How to read the result</h2>
<p class="panel-intro">
<strong>Car travel</strong> includes both loaded passenger trips and
repositioning to pickup floors. Because every request is eventually
carried, the loaded distance is the same across the completed rules;
the comparison mainly exposes different deadhead and waiting costs.
</p>
<p class="panel-intro">
Rule A prioritizes age. Rule B greedily minimizes
<code>|car − pickup| + |pickup − destination|</code> for the current
waiting-call/free-car pair.
</p>
</section>
</aside>
</main>
<footer>
Simplified illustrative model · arbitrary time and distance units ·
Three.js core only · no external controls or addons
</footer>
</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 FLOORS = 6;
const LEVEL = 1.12;
const DOOR_TIME = 0.4;
const EPS = 1e-7;
const REQUESTS = [
{ id: "R1", at: 0.0, from: 1, to: 6 },
{ id: "R2", at: 0.5, from: 4, to: 2 },
{ id: "R3", at: 1.0, from: 6, to: 1 },
{ id: "R4", at: 1.5, from: 2, to: 5 },
{ id: "R5", at: 4.0, from: 5, to: 3 },
{ id: "R6", at: 6.0, from: 3, to: 6 },
{ id: "R7", at: 9.0, from: 1, to: 4 },
{ id: "R8", at: 12.0, from: 6, to: 2 }
];
const COLORS = {
waiting: 0xf59e0b,
assigned: 0x38bdf8,
riding: 0xa78bfa,
completed: 0x22c55e,
future: 0x46566d
};
class DispatchSimulation {
constructor(rule) {
this.rule = rule;
this.reset();
}
reset() {
this.time = 0;
this.requests = REQUESTS.map((request) => ({
...request,
status: "future",
assignedAt: null,
pickedUpAt: null,
completedAt: null,
wait: null
}));
this.cars = [1, 4].map((floor, id) => ({
id,
floor,
state: "idle",
target: floor,
requestId: null,
phase: 0,
loadedTravel: 0,
deadheadTravel: 0
}));
this.markArrivals();
this.dispatch();
}
get done() {
return this.requests.every((request) => request.status === "completed");
}
getRequest(id) {
return this.requests.find((request) => request.id === id);
}
markArrivals() {
for (const request of this.requests) {
if (request.status === "future" && request.at <= this.time + EPS) {
request.status = "waiting";
}
}
}
dispatch() {
let waiting = this.requests.filter((request) => request.status === "waiting");
if (!waiting.length) {
return;
}
if (this.rule === "fifo") {
while (waiting.length) {
const idleCars = this.cars.filter((car) => car.state === "idle");
if (!idleCars.length) break;
waiting.sort(
(a, b) => a.at - b.at || a.id.localeCompare(b.id)
);
const request = waiting.shift();
idleCars.sort(
(a, b) =>
Math.abs(a.floor - request.from) -
Math.abs(b.floor - request.from) ||
a.id - b.id
);
this.assign(idleCars[0], request);
}
return;
}
// Rule B: greedy least-work pairing.
while (waiting.length) {
const idleCars = this.cars.filter((car) => car.state === "idle");
if (!idleCars.length) break;
let best = null;
for (const request of waiting) {
for (const car of idleCars) {
const deadhead = Math.abs(car.floor - request.from);
const loaded = Math.abs(request.to - request.from);
const score = deadhead + loaded;
if (
!best ||
score < best.score - EPS ||
(Math.abs(score - best.score) <= EPS &&
(request.at < best.request.at - EPS ||
(Math.abs(request.at - best.request.at) <= EPS &&
(request.id < best.request.id ||
(request.id === best.request.id && car.id < best.car.id)))))
) {
best = { car, request, score };
}
}
}
waiting = waiting.filter((request) => request !== best.request);
this.assign(best.car, best.request);
}
}
assign(car, request) {
car.requestId = request.id;
car.target = request.from;
request.status = "assigned";
request.assignedAt = this.time;
if (Math.abs(car.floor - request.from) <= EPS) {
car.state = "loading";
car.phase = DOOR_TIME;
} else {
car.state = "toPickup";
}
}
tick(dt) {
if (this.done) return;
this.time += dt;
this.markArrivals();
for (const car of this.cars) {
this.updateCar(car, dt);
}
this.dispatch();
}
updateCar(car, dt) {
let remaining = dt;
while (remaining > EPS && car.state !== "idle") {
if (car.state === "toPickup" || car.state === "toDestination") {
const distance = Math.abs(car.target - car.floor);
const step = Math.min(remaining, distance);
if (step > EPS) {
const direction = Math.sign(car.target - car.floor);
car.floor += direction * step;
if (car.state === "toPickup") {
car.deadheadTravel += step;
} else {
car.loadedTravel += step;
}
remaining -= step;
}
if (Math.abs(car.target - car.floor) <= EPS) {
car.floor = car.target;
const eventTime = this.time - remaining;
if (car.state === "toPickup") {
const request = this.getRequest(car.requestId);
request.wait = eventTime - request.at;
request.pickedUpAt = eventTime;
car.state = "loading";
car.phase = DOOR_TIME;
} else {
car.state = "unloading";
car.phase = DOOR_TIME;
}
} else {
break;
}
} else if (car.state === "loading") {
const used = Math.min(remaining, car.phase);
car.phase -= used;
remaining -= used;
if (car.phase <= EPS) {
const request = this.getRequest(car.requestId);
request.status = "riding";
car.state = "toDestination";
car.target = request.to;
} else {
break;
}
} else if (car.state === "unloading") {
const used = Math.min(remaining, car.phase);
car.phase -= used;
remaining -= used;
if (car.phase <= EPS) {
const request = this.getRequest(car.requestId);
const eventTime = this.time - remaining;
request.status = "completed";
request.completedAt = eventTime;
car.state = "idle";
car.requestId = null;
car.target = car.floor;
} else {
break;
}
} else {
break;
}
}
}
summary() {
const completed = this.requests.filter(
(request) => request.status === "completed"
);
const waits = completed
.map((request) => request.wait)
.filter((wait) => wait !== null);
const loadedTravel = this.cars.reduce(
(sum, car) => sum + car.loadedTravel,
0
);
const deadheadTravel = this.cars.reduce(
(sum, car) => sum + car.deadheadTravel,
0
);
return {
avgWait: waits.length
? waits.reduce((sum, wait) => sum + wait, 0) / waits.length
: 0,
maxWait: waits.length ? Math.max(...waits) : 0,
loadedTravel,
deadheadTravel,
totalTravel: loadedTravel + deadheadTravel,
completed: completed.length,
pending: this.requests.length - completed.length,
time: this.time
};
}
}
function makeLabel(text, color = "#e8f0fb", background = "#111d2e") {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 64;
const context = canvas.getContext("2d");
context.fillStyle = background;
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = "rgba(255,255,255,0.18)";
context.lineWidth = 3;
context.strokeRect(2, 2, canvas.width - 4, canvas.height - 4);
context.fillStyle = color;
context.font = "700 30px ui-monospace, SFMono-Regular, Menlo, monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2, canvas.height / 2 + 1);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(1.35, 0.34, 1);
sprite.renderOrder = 10;
return sprite;
}
class BuildingView {
constructor(host, simulation, accent) {
this.host = host;
this.simulation = simulation;
this.accent = accent;
this.scene = new THREE.Scene();
this.scene.background = new THREE.Color(0x08111f);
this.scene.fog = new THREE.Fog(0x08111f, 20, 42);
this.camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
this.orbit = {
azimuth: 0.28,
elevation: 0.42,
radius: 16.5,
target: new THREE.Vector3(0.25, 3.1, 0)
};
this.renderer = new THREE.WebGLRenderer({ antialias: true });
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
this.renderer.outputColorSpace = THREE.SRGBColorSpace;
this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
this.renderer.toneMappingExposure = 1.15;
this.renderer.shadowMap.enabled = true;
this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
this.renderer.domElement.setAttribute(
"aria-label",
"Interactive three-dimensional voxel elevator simulation"
);
this.renderer.domElement.tabIndex = 0;
host.prepend(this.renderer.domElement);
this.createLights();
this.createBuilding();
this.createCars();
this.createRequestMarkers();
this.installControls();
this.resizeObserver = new ResizeObserver(() => this.resize());
this.resizeObserver.observe(host);
this.resize();
this.updateCamera();
}
createLights() {
const hemisphere = new THREE.HemisphereLight(0xc9e7ff, 0x172033, 2.2);
this.scene.add(hemisphere);
const key = new THREE.DirectionalLight(0xffffff, 3.0);
key.position.set(7, 12, 9);
key.castShadow = true;
key.shadow.mapSize.set(1024, 1024);
key.shadow.camera.left = -10;
key.shadow.camera.right = 10;
key.shadow.camera.top = 12;
key.shadow.camera.bottom = -5;
key.shadow.bias = -0.0005;
this.scene.add(key);
const rim = new THREE.DirectionalLight(0x7dd3fc, 1.4);
rim.position.set(-8, 6, -7);
this.scene.add(rim);
const accentLight = new THREE.PointLight(this.accent, 18, 18, 2);
accentLight.position.set(1, 5, 5);
this.scene.add(accentLight);
}
createBuilding() {
const tileGeometry = new THREE.BoxGeometry(1.12, 0.14, 0.9);
const tileMaterial = new THREE.MeshStandardMaterial({
color: 0x60758e,
roughness: 0.82,
metalness: 0.06
});
const matrices = [];
const dummy = new THREE.Object3D();
const tileCount = FLOORS * 6 * 3;
this.tiles = new THREE.InstancedMesh(
tileGeometry,
tileMaterial,
tileCount
);
let instance = 0;
for (let floor = 0; floor < FLOORS; floor++) {
for (let x = 0; x < 6; x++) {
for (let z = 0; z < 3; z++) {
dummy.position.set(
-3.2 + x * 1.28,
floor * LEVEL,
-1.35 + z * 1.05
);
dummy.updateMatrix();
this.tiles.setMatrixAt(instance, dummy.matrix);
const shade = 0.72 + ((x + z + floor) % 4) * 0.055;
this.tiles.setColorAt(
instance,
new THREE.Color().setRGB(
shade * 0.39,
shade * 0.51,
shade * 0.64
)
);
instance++;
}
}
}
this.tiles.instanceMatrix.needsUpdate = true;
if (this.tiles.instanceColor) {
this.tiles.instanceColor.needsUpdate = true;
}
this.tiles.castShadow = true;
this.tiles.receiveShadow = true;
this.scene.add(this.tiles);
const ground = new THREE.Mesh(
new THREE.BoxGeometry(15, 0.22, 7.5),
new THREE.MeshStandardMaterial({
color: 0x0d1929,
roughness: 0.94,
metalness: 0.02
})
);
ground.position.y = -0.28;
ground.receiveShadow = true;
this.scene.add(ground);
const columnMaterial = new THREE.MeshStandardMaterial({
color: 0x334a67,
roughness: 0.72,
metalness: 0.12
});
for (const x of [-4.25, 4.25]) {
for (let floor = 0; floor < FLOORS; floor++) {
const block = new THREE.Mesh(
new THREE.BoxGeometry(0.24, 0.98, 0.24),
columnMaterial
);
block.position.set(x, floor * LEVEL + 0.05, -1.85);
block.castShadow = true;
this.scene.add(block);
}
}
const doorMaterial = new THREE.MeshStandardMaterial({
color: 0x1d3048,
emissive: 0x0b1828,
emissiveIntensity: 0.45,
roughness: 0.58,
metalness: 0.3
});
for (const x of [-3.35, -1.75]) {
for (let floor = 0; floor < FLOORS; floor++) {
const door = new THREE.Mesh(
new THREE.BoxGeometry(1.03, 0.75, 0.08),
doorMaterial.clone()
);
door.position.set(x, floor * LEVEL + 0.42, 1.5);
this.scene.add(door);
}
}
for (let floor = 0; floor < FLOORS; floor++) {
const label = makeLabel(`${floor + 1}F`, "#9fb4cf");
label.position.set(-4.75, floor * LEVEL + 0.2, 0.75);
label.scale.set(0.9, 0.225, 1);
this.scene.add(label);
}
}
createCars() {
this.carViews = [];
const carColors = [0x2dd4bf, 0xa78bfa];
const carXs = [-3.35, -1.75];
for (let id = 0; id < 2; id++) {
const group = new THREE.Group();
group.position.set(carXs[id], 0.08, 2.18);
const color = carColors[id];
const base = new THREE.Mesh(
new THREE.BoxGeometry(1.27, 0.18, 1.02),
new THREE.MeshStandardMaterial({
color,
roughness: 0.52,
metalness: 0.25
})
);
base.position.y = 0.16;
base.castShadow = true;
group.add(base);
const body = new THREE.Mesh(
new THREE.BoxGeometry(1.06, 0.72, 0.84),
new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.25,
roughness: 0.3,
metalness: 0.18,
transparent: true,
opacity: 0.92
})
);
body.position.y = 0.62;
body.castShadow = true;
group.add(body);
const roof = new THREE.Mesh(
new THREE.BoxGeometry(1.22, 0.13, 0.98),
new THREE.MeshStandardMaterial({
color: 0xdce9f8,
roughness: 0.45,
metalness: 0.15
})
);
roof.position.y = 1.04;
roof.castShadow = true;
group.add(roof);
const windowMaterial = new THREE.MeshBasicMaterial({
color: 0xdff8ff
});
const frontWindow = new THREE.Mesh(
new THREE.BoxGeometry(0.76, 0.27, 0.045),
windowMaterial
);
frontWindow.position.set(0, 0.7, 0.435);
group.add(frontWindow);
for (const x of [-0.53, 0.53]) {
const sideWindow = new THREE.Mesh(
new THREE.BoxGeometry(0.035, 0.27, 0.55),
windowMaterial
);
sideWindow.position.set(x, 0.7, 0);
group.add(sideWindow);
}
const label = makeLabel(
id === 0 ? "A" : "B",
id === 0 ? "#5eead4" : "#c4b5fd",
"#0a1422"
);
label.position.set(0, 1.38, 0);
label.scale.set(0.63, 0.16, 1);
group.add(label);
this.scene.add(group);
this.carViews.push({ group, body });
}
}
createRequestMarkers() {
this.requestViews = [];
for (const request of REQUESTS) {
const group = new THREE.Group();
group.position.set(5.25, 0, 0.3);
const fromY = (request.from - 1) * LEVEL + 0.35;
const toY = (request.to - 1) * LEVEL + 0.35;
const routeHeight = Math.max(0.08, Math.abs(toY - fromY));
const mainMaterial = new THREE.MeshStandardMaterial({
color: COLORS.waiting,
emissive: COLORS.waiting,
emissiveIntensity: 0.5,
roughness: 0.35,
metalness: 0.15
});
const main = new THREE.Mesh(
new THREE.BoxGeometry(0.28, 0.28, 0.28),
mainMaterial
);
main.position.set(0, fromY, 0);
main.castShadow = true;
group.add(main);
const destinationMaterial = new THREE.MeshStandardMaterial({
color: COLORS.future,
emissive: COLORS.future,
emissiveIntensity: 0.2,
roughness: 0.55
});
const destination = new THREE.Mesh(
new THREE.BoxGeometry(0.2, 0.2, 0.2),
destinationMaterial
);
destination.position.set(0.76, toY, 0);
group.add(destination);
const connectorMaterial = new THREE.MeshBasicMaterial({
color: COLORS.waiting,
transparent: true,
opacity: 0.42
});
const connector = new THREE.Mesh(
new THREE.BoxGeometry(0.055, routeHeight, 0.055),
connectorMaterial
);
connector.position.set(0.38, (fromY + toY) / 2, 0);
group.add(connector);
const label = makeLabel(request.id, "#d9e8fa", "#0b1625");
label.position.set(-0.5, fromY + 0.42, 0);
label.scale.set(0.78, 0.195, 1);
group.add(label);
this.scene.add(group);
this.requestViews.push({
group,
main,
destination,
connector,
label,
fromY
});
}
}
installControls() {
const canvas = this.renderer.domElement;
let dragging = false;
let previousX = 0;
let previousY = 0;
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
this.orbit.azimuth -= dx * 0.006;
this.orbit.elevation = THREE.MathUtils.clamp(
this.orbit.elevation + dy * 0.0045,
0.14,
1.12
);
this.updateCamera();
});
const stopDragging = (event) => {
dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
};
canvas.addEventListener("pointerup", stopDragging);
canvas.addEventListener("pointercancel", stopDragging);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
this.orbit.radius = THREE.MathUtils.clamp(
this.orbit.radius * Math.exp(event.deltaY * 0.001),
8.5,
25
);
this.updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", () => {
this.orbit.azimuth = 0.28;
this.orbit.elevation = 0.42;
this.orbit.radius = 16.5;
this.updateCamera();
});
canvas.addEventListener("keydown", (event) => {
let handled = true;
if (event.key === "ArrowLeft") this.orbit.azimuth -= 0.09;
else if (event.key === "ArrowRight") this.orbit.azimuth += 0.09;
else if (event.key === "ArrowUp") {
this.orbit.elevation = THREE.MathUtils.clamp(
this.orbit.elevation + 0.07,
0.14,
1.12
);
} else if (event.key === "ArrowDown") {
this.orbit.elevation = THREE.MathUtils.clamp(
this.orbit.elevation - 0.07,
0.14,
1.12
);
} else if (event.key === "+" || event.key === "=") {
this.orbit.radius = Math.max(8.5, this.orbit.radius - 1);
} else if (event.key === "-") {
this.orbit.radius = Math.min(25, this.orbit.radius + 1);
} else {
handled = false;
}
if (handled) {
event.preventDefault();
this.updateCamera();
}
});
}
updateCamera() {
const { azimuth, elevation, radius, target } = this.orbit;
this.camera.position.set(
target.x + radius * Math.sin(azimuth) * Math.cos(elevation),
target.y + radius * Math.sin(elevation),
target.z + radius * Math.cos(azimuth) * Math.cos(elevation)
);
this.camera.lookAt(target);
}
resize() {
const width = Math.max(1, this.host.clientWidth);
const height = Math.max(1, this.host.clientHeight);
this.renderer.setSize(width, height, false);
this.camera.aspect = width / height;
this.camera.updateProjectionMatrix();
}
update(wallTime) {
const simulation = this.simulation;
for (let i = 0; i < simulation.cars.length; i++) {
const car = simulation.cars[i];
const view = this.carViews[i];
view.group.position.y = car.floor * LEVEL + 0.08;
const moving =
car.state === "toPickup" || car.state === "toDestination";
const stopped =
car.state === "loading" || car.state === "unloading";
view.body.material.emissiveIntensity = moving
? 0.9
: stopped
? 0.55
: 0.18;
}
for (let i = 0; i < simulation.requests.length; i++) {
const request = simulation.requests[i];
const view = this.requestViews[i];
view.group.visible = request.status !== "future";
const statusColor = COLORS[request.status] || COLORS.future;
const bob =
request.status === "waiting"
? Math.sin(wallTime * 3.2 + i) * 0.07
: 0;
view.main.position.y = view.fromY + bob;
view.label.position.y = view.fromY + bob + 0.42;
view.main.material.color.setHex(statusColor);
view.main.material.emissive.setHex(statusColor);
view.main.material.emissiveIntensity =
request.status === "completed" ? 0.32 : 0.72;
view.destination.material.color.setHex(statusColor);
view.destination.material.emissive.setHex(statusColor);
view.destination.material.emissiveIntensity = 0.3;
view.connector.material.color.setHex(statusColor);
view.connector.material.opacity =
request.status === "completed" ? 0.2 : 0.48;
}
}
render() {
this.renderer.render(this.scene, this.camera);
}
}
const simulationA = new DispatchSimulation("fifo");
const simulationB = new DispatchSimulation("least");
const viewA = new BuildingView($("viewA"), simulationA, 0x2dd4bf);
const viewB = new BuildingView($("viewB"), simulationB, 0xa78bfa);
let running = false;
let finalized = false;
function resetSimulations() {
simulationA.reset();
simulationB.reset();
running = false;
finalized = false;
$("verdict").classList.remove("complete");
$("verdict").textContent =
"Run the comparison to calculate waits, loaded travel, and repositioning distance.";
updateUI();
}
function format(value, digits = 1) {
return Number(value).toFixed(digits);
}
function requestCell(simulation, request) {
if (request.status === "completed") {
return `
<strong>${format(request.wait)} tu</strong>
<span class="request-state done">completed</span>
`;
}
if (request.status === "waiting") {
return `
<strong>${format(simulation.time - request.at)} tu</strong>
<span class="request-state waiting">still waiting</span>
`;
}
if (request.wait !== null) {
const state =
request.status === "riding" ? "riding" : "at pickup";
return `
<strong>${format(request.wait)} tu</strong>
<span class="request-state active">${state}</span>
`;
}
if (request.status === "assigned") {
return `
<span class="request-state active">en route to pickup</span>
`;
}
return `<span class="request-state">not yet released</span>`;
}
function updateLedger() {
$("requestRows").innerHTML = simulationA.requests
.map((request, index) => {
const requestB = simulationB.requests[index];
return `
<tr>
<td><span class="req-id"><i class="req-dot"></i>${request.id}</span></td>
<td>${format(request.at)}</td>
<td>${request.from}F → ${request.to}F</td>
<td>${requestCell(simulationA, request)}</td>
<td>${requestCell(simulationB, requestB)}</td>
</tr>
`;
})
.join("");
}
function updateMetrics(prefix, simulation) {
const summary = simulation.summary();
$(`${prefix}-avg`).textContent = summary.completed
? `${format(summary.avgWait)} tu`
: "—";
$(`${prefix}-max`).textContent = summary.completed
? `${format(summary.maxWait)} tu`
: "—";
$(`${prefix}-travel`).textContent = `${format(summary.totalTravel)} fu`;
$(`${prefix}-travel-detail`).textContent =
`loaded ${format(summary.loadedTravel)} + ` +
`reposition ${format(summary.deadheadTravel)} floor-units`;
$(`${prefix}-deadhead`).textContent = `${format(summary.deadheadTravel)} fu`;
$(`${prefix}-status`).textContent =
`${summary.completed} / ${REQUESTS.length} done`;
}
function updateUI() {
updateMetrics("a", simulationA);
updateMetrics("b", simulationB);
updateLedger();
const time = Math.max(simulationA.time, simulationB.time);
$("runState").textContent = running
? `Running at ${format(time)} tu`
: simulationA.done && simulationB.done
? `Complete at ${format(time)} tu`
: `Paused at ${format(time)} tu`;
$("run").textContent = running
? "Pause"
: simulationA.done && simulationB.done
? "Replay"
: "Run comparison";
}
function finalizeVerdict() {
if (finalized) return;
finalized = true;
const a = simulationA.summary();
const b = simulationB.summary();
const waitDifference = a.avgWait - b.avgWait;
const travelDifference = b.totalTravel - a.totalTravel;
let waitText;
if (Math.abs(waitDifference) < 0.05) {
waitText =
`Both rules produced the same average wait (${format(a.avgWait)} tu)`;
} else if (waitDifference > 0) {
waitText =
`Rule B reduced average wait by ${format(waitDifference)} tu ` +
`(A: ${format(a.avgWait)} → B: ${format(b.avgWait)})`;
} else {
waitText =
`Rule B increased average wait by ${format(-waitDifference)} tu ` +
`(A: ${format(a.avgWait)} → B: ${format(b.avgWait)})`;
}
let travelText;
if (Math.abs(travelDifference) < 0.05) {
travelText = "and used the same total car travel";
} else if (travelDifference > 0) {
travelText =
`but used ${format(travelDifference)} more floor-units of car travel`;
} else {
travelText =
`and used ${format(-travelDifference)} fewer floor-units of car travel`;
}
$("verdict").classList.add("complete");
$("verdict").textContent =
`${waitText}, ${travelText}. ` +
`This conclusion applies only to the eight fictional calls and the stated simplified model.`;
updateUI();
}
$("run").addEventListener("click", () => {
if (simulationA.done && simulationB.done) {
resetSimulations();
running = true;
} else {
running = !running;
}
updateUI();
});
$("reset").addEventListener("click", resetSimulations);
$("finish").addEventListener("click", () => {
running = false;
let guard = 0;
while (
!(simulationA.done && simulationB.done) &&
guard < 12000
) {
simulationA.tick(0.05);
simulationB.tick(0.05);
guard++;
}
finalizeVerdict();
updateUI();
});
let previousTime = performance.now();
let uiTimer = 0;
function animate(now) {
const realDelta = Math.min(0.05, (now - previousTime) / 1000);
previousTime = now;
if (running) {
let modelDelta = realDelta * Number($("speed").value);
while (
modelDelta > EPS &&
!(simulationA.done && simulationB.done)
) {
const step = Math.min(modelDelta, 0.025);
simulationA.tick(step);
simulationB.tick(step);
modelDelta -= step;
}
if (simulationA.done && simulationB.done) {
running = false;
finalizeVerdict();
}
}
viewA.update(now / 1000);
viewB.update(now / 1000);
viewA.render();
viewB.render();
uiTimer += realDelta;
if (uiTimer >= 0.08) {
updateUI();
uiTimer = 0;
}
requestAnimationFrame(animate);
}
updateUI();
requestAnimationFrame(animate);
</script>
</body>
</html>
```