Prompt specification
Build or customize the Three.js 3D scene "Signal Timing and Queue Tradeoff" 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: Signal Timing and Queue Tradeoff
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/signal-timing-and-queue-tradeoff-x2108
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring conflicting vehicle routes at an intersection. Compare two declared signal schedules under the same fictional arrivals. Display queue lengths and pedestrian waits without presenting the model as real traffic-engineering guidance. Voxel style.
Working Three.js Starter (signal-timing-and-queue-tradeoff-x2108):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Intersection Conflict Lab</title>
<style>
:root {
--ink: #17212b;
--muted: #63717d;
--paper: rgba(250, 252, 249, 0.94);
--line: rgba(23, 33, 43, 0.12);
--ns: #2fc4a1;
--ew: #547eea;
--left: #9b6dff;
--red: #ef6b61;
--amber: #f3bb45;
--blue: #5b8def;
--shadow: 0 12px 35px rgba(28, 45, 55, 0.13);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #cfe0da;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
select {
font: inherit;
}
#stage {
position: fixed;
inset: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#stage canvas:active {
cursor: grabbing;
}
.topbar {
position: fixed;
z-index: 20;
top: 0;
left: 0;
right: 0;
min-height: 78px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
padding: 12px 18px;
background: linear-gradient(
180deg,
rgba(248, 251, 248, 0.98),
rgba(248, 251, 248, 0.88)
);
border-bottom: 1px solid rgba(23, 33, 43, 0.1);
backdrop-filter: blur(12px);
}
.brand {
min-width: 0;
}
.eyebrow {
margin: 0 0 3px;
color: #557168;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(18px, 2.1vw, 27px);
line-height: 1.05;
letter-spacing: -0.04em;
}
.subtitle {
margin: 5px 0 0;
color: var(--muted);
font-size: 12px;
}
.controls {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 7px;
flex-wrap: wrap;
}
.control-button,
.speed-select {
height: 34px;
border: 1px solid rgba(23, 33, 43, 0.14);
border-radius: 9px;
background: #fff;
color: var(--ink);
box-shadow: 0 2px 7px rgba(30, 44, 50, 0.06);
cursor: pointer;
}
.control-button {
padding: 0 12px;
font-size: 12px;
font-weight: 700;
}
.control-button:hover,
.speed-select:hover {
background: #f2f6f3;
}
.control-button.primary {
color: #fff;
background: #21352f;
border-color: #21352f;
}
.speed-select {
padding: 0 9px;
font-size: 12px;
}
.disclaimer {
position: fixed;
z-index: 19;
top: 87px;
left: 50%;
width: min(690px, calc(100% - 28px));
transform: translateX(-50%);
padding: 8px 12px;
border: 1px solid rgba(180, 120, 25, 0.24);
border-radius: 9px;
background: rgba(255, 248, 226, 0.94);
color: #6f5827;
box-shadow: 0 5px 16px rgba(75, 58, 21, 0.08);
text-align: center;
font-size: 11px;
line-height: 1.35;
pointer-events: none;
}
.plan-panel {
position: fixed;
z-index: 10;
top: 132px;
width: calc(50% - 34px);
max-width: 660px;
padding: 13px;
border: 1px solid rgba(255, 255, 255, 0.72);
border-radius: 14px;
background: var(--paper);
box-shadow: var(--shadow);
backdrop-filter: blur(13px);
pointer-events: none;
}
#planA {
left: 17px;
}
#planB {
left: calc(50% + 17px);
}
.plan-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
}
.plan-id {
display: inline-flex;
align-items: center;
gap: 7px;
color: #3d7466;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.plan-badge {
display: inline-grid;
width: 24px;
height: 24px;
place-items: center;
border-radius: 7px;
color: #fff;
background: #2b8f79;
font-size: 12px;
letter-spacing: 0;
}
#planB .plan-badge {
background: #7053bb;
}
.plan-heading h2 {
margin: 5px 0 2px;
font-size: 17px;
letter-spacing: -0.025em;
}
.plan-description {
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 1.4;
}
.phase-now {
flex: 0 0 auto;
max-width: 47%;
padding: 6px 9px;
border-radius: 8px;
background: #edf3ef;
color: #355249;
text-align: right;
font-size: 10px;
font-weight: 800;
}
.phase-now span {
display: block;
margin-top: 2px;
color: #7a8881;
font-size: 9px;
font-weight: 650;
}
.timeline {
display: flex;
height: 15px;
gap: 2px;
margin: 11px 0 10px;
overflow: hidden;
border-radius: 5px;
background: #dfe5e1;
}
.timeline-segment {
position: relative;
min-width: 3px;
opacity: 0.55;
transition: opacity 120ms ease, filter 120ms ease;
}
.timeline-segment.active {
z-index: 1;
opacity: 1;
filter: brightness(1.12);
box-shadow: inset 0 0 0 2px rgba(255, 255, 255, 0.9);
}
.stats {
display: grid;
grid-template-columns: 1.25fr repeat(4, 1fr);
gap: 6px;
}
.stat {
min-width: 0;
padding: 8px 9px;
border: 1px solid rgba(23, 33, 43, 0.08);
border-radius: 9px;
background: rgba(255, 255, 255, 0.8);
}
.stat span {
display: block;
overflow: hidden;
color: #738079;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.04em;
text-transform: uppercase;
text-overflow: ellipsis;
white-space: nowrap;
}
.stat strong {
display: inline-block;
margin-top: 3px;
font-size: 18px;
letter-spacing: -0.04em;
}
.stat small {
display: block;
margin-top: 1px;
color: #8a948f;
font-size: 9px;
}
.stat.primary-stat {
border-color: rgba(47, 196, 161, 0.24);
background: #eff9f4;
}
#planB .stat.primary-stat {
border-color: rgba(155, 109, 255, 0.24);
background: #f5f0ff;
}
.comparison {
position: fixed;
z-index: 15;
left: 50%;
bottom: 14px;
width: min(860px, calc(100% - 28px));
transform: translateX(-50%);
padding: 10px 13px;
border: 1px solid rgba(255, 255, 255, 0.75);
border-radius: 12px;
background: rgba(248, 251, 248, 0.95);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
pointer-events: none;
}
#comparisonText {
margin: 0;
text-align: center;
font-size: 12px;
font-weight: 700;
}
.legend {
display: flex;
align-items: center;
justify-content: center;
gap: 14px;
flex-wrap: wrap;
margin-top: 7px;
color: #6f7c76;
font-size: 9px;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 5px;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 2px;
background: var(--color);
}
.divider {
position: fixed;
z-index: 5;
top: 122px;
bottom: 83px;
left: 50%;
width: 1px;
background: rgba(255, 255, 255, 0.75);
box-shadow: 0 0 0 1px rgba(23, 33, 43, 0.06);
pointer-events: none;
}
.camera-help {
position: fixed;
z-index: 12;
right: 18px;
bottom: 92px;
padding: 6px 9px;
border-radius: 7px;
background: rgba(29, 42, 45, 0.72);
color: rgba(255, 255, 255, 0.83);
font-size: 9px;
pointer-events: none;
}
@media (max-width: 1050px) {
.stats {
grid-template-columns: repeat(3, 1fr);
}
.stat:nth-child(4),
.stat:nth-child(5) {
display: none;
}
}
@media (max-width: 760px) {
.topbar {
min-height: 100px;
align-items: flex-start;
padding: 10px 12px;
}
.subtitle {
max-width: 48vw;
font-size: 10px;
}
.controls {
max-width: 48vw;
}
.control-button,
.speed-select {
height: 30px;
padding: 0 8px;
font-size: 10px;
}
.disclaimer {
top: 105px;
font-size: 9px;
padding: 6px 8px;
}
.plan-panel {
top: 145px;
width: calc(100% - 24px);
padding: 9px;
}
#planA {
left: 12px;
}
#planB {
top: calc(50% + 6px);
left: 12px;
}
.plan-description,
.phase-now span {
display: none;
}
.plan-heading h2 {
font-size: 14px;
}
.phase-now {
max-width: 55%;
font-size: 9px;
}
.stats {
grid-template-columns: repeat(3, 1fr);
}
.stat {
padding: 5px 7px;
}
.stat strong {
font-size: 14px;
}
.stat:nth-child(4),
.stat:nth-child(5) {
display: none;
}
.divider {
top: 50%;
bottom: auto;
left: 0;
right: 0;
width: auto;
height: 1px;
}
.comparison {
bottom: 7px;
padding: 7px 9px;
}
#comparisonText {
font-size: 10px;
}
.legend {
display: none;
}
.camera-help {
display: none;
}
}
</style>
</head>
<body>
<div id="stage" aria-label="Two three-dimensional simulated intersections"></div>
<header class="topbar">
<div class="brand">
<p class="eyebrow">Fictional control room · shared seed 731</p>
<h1>Intersection Conflict Lab</h1>
<p class="subtitle">Two declared signal plans · identical fictional arrivals</p>
</div>
<div class="controls">
<button id="playButton" class="control-button primary" type="button">
Pause
</button>
<button id="resetButton" class="control-button" type="button">
Restart
</button>
<select id="speedSelect" class="speed-select" aria-label="Simulation 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>
<button id="viewButton" class="control-button" type="button">
Reset view
</button>
</div>
</header>
<div class="disclaimer">
Concept model only — not real traffic-engineering guidance.
No capacity, safety, emissions, accessibility, or compliance conclusions.
</div>
<section id="planA" class="plan-panel" aria-label="Plan A results">
<div class="plan-heading">
<div>
<span class="plan-id">
<span class="plan-badge">A</span>
Permissive lefts
</span>
<h2>Compact alternating cycle</h2>
<p class="plan-description">
18s N/S · 2s all-red · 18s E/W · 2s all-red. Left turns use the
parallel green and cross opposing through traffic.
</p>
</div>
<div class="phase-now">
<strong id="aPhase">N/S through</strong>
<span id="aClock">t = 0.0s</span>
</div>
</div>
<div id="aTimeline" class="timeline"></div>
<div class="stats" aria-live="polite">
<div class="stat primary-stat">
<span>Total queue</span>
<strong id="aQueue">0</strong>
<small>vehicles</small>
</div>
<div class="stat">
<span>N/S queue</span>
<strong id="aNS">0</strong>
<small id="aEWLabel">E/W 0</small>
</div>
<div class="stat">
<span>Ped wait avg</span>
<strong id="aPedWait">0.0s</strong>
<small id="aPedCount">0 waiting</small>
</div>
<div class="stat">
<span>Left queue</span>
<strong id="aLeft">0</strong>
<small id="aDelay">avg delay 0s</small>
</div>
<div class="stat">
<span>Overlap windows</span>
<strong id="aConflict">0</strong>
<small>fictional conflict windows</small>
</div>
</div>
</section>
<section id="planB" class="plan-panel" aria-label="Plan B results">
<div class="plan-heading">
<div>
<span class="plan-id">
<span class="plan-badge">B</span>
Protected turns
</span>
<h2>Longer protected-turn cycle</h2>
<p class="plan-description">
16s N/S · 2s all-red · 8s protected N/S left · 2s all-red ·
18s E/W · 2s all-red · 8s protected E/W left · 2s all-red.
</p>
</div>
<div class="phase-now">
<strong id="bPhase">N/S through</strong>
<span id="bClock">t = 0.0s</span>
</div>
</div>
<div id="bTimeline" class="timeline"></div>
<div class="stats" aria-live="polite">
<div class="stat primary-stat">
<span>Total queue</span>
<strong id="bQueue">0</strong>
<small>vehicles</small>
</div>
<div class="stat">
<span>N/S queue</span>
<strong id="bNS">0</strong>
<small id="bEWLabel">E/W 0</small>
</div>
<div class="stat">
<span>Ped wait avg</span>
<strong id="bPedWait">0.0s</strong>
<small id="bPedCount">0 waiting</small>
</div>
<div class="stat">
<span>Left queue</span>
<strong id="bLeft">0</strong>
<small id="bDelay">avg delay 0s</small>
</div>
<div class="stat">
<span>Overlap windows</span>
<strong id="bConflict">0</strong>
<small>fictional conflict windows</small>
</div>
</div>
</section>
<div class="divider"></div>
<div class="camera-help">Drag to orbit · wheel to zoom · double-click to reset</div>
<footer class="comparison">
<p id="comparisonText">Both plans are running on the same fictional arrival stream.</p>
<div class="legend">
<span class="legend-item"><i class="swatch" style="--color:#ef6b61"></i>North approach</span>
<span class="legend-item"><i class="swatch" style="--color:#2fc4a1"></i>South approach</span>
<span class="legend-item"><i class="swatch" style="--color:#f3bb45"></i>East approach</span>
<span class="legend-item"><i class="swatch" style="--color:#5b8def"></i>West approach</span>
<span class="legend-item"><i class="swatch" style="--color:#f3bb45"></i>Amber roof = left-turn route</span>
</div>
</footer>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Declared fictional schedules
// -------------------------------------------------------------------------
const PHASE_COLORS = {
ns: "#2fc4a1",
ew: "#547eea",
all: "#66727a",
leftNS: "#9b6dff",
leftEW: "#9b6dff"
};
const SCHEDULES = {
A: {
key: "A",
cycle: 40,
phases: [
{ start: 0, end: 18, type: "ns", label: "N/S through" },
{ start: 18, end: 20, type: "all", label: "All red" },
{ start: 20, end: 38, type: "ew", label: "E/W through" },
{ start: 38, end: 40, type: "all", label: "All red" }
]
},
B: {
key: "B",
cycle: 60,
phases: [
{ start: 0, end: 16, type: "ns", label: "N/S through" },
{ start: 16, end: 18, type: "all", label: "All red" },
{ start: 18, end: 26, type: "leftNS", label: "Protected N/S left" },
{ start: 26, end: 28, type: "all", label: "All red" },
{ start: 28, end: 46, type: "ew", label: "E/W through" },
{ start: 46, end: 48, type: "all", label: "All red" },
{ start: 48, end: 56, type: "leftEW", label: "Protected E/W left" },
{ start: 56, end: 60, type: "all", label: "All red" }
]
}
};
function getPhase(schedule, time) {
const local = ((time % schedule.cycle) + schedule.cycle) % schedule.cycle;
for (let i = 0; i < schedule.phases.length; i++) {
const phase = schedule.phases[i];
if (local >= phase.start && local < phase.end) {
return {
...phase,
index: i,
elapsed: local - phase.start,
local
};
}
}
const phase = schedule.phases[schedule.phases.length - 1];
return {
...phase,
index: schedule.phases.length - 1,
elapsed: local - phase.start,
local
};
}
// -------------------------------------------------------------------------
// Shared deterministic fictional arrivals
// -------------------------------------------------------------------------
function mulberry32(seed) {
return function random() {
let t = seed += 0x6D2B79F5;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function generateSharedData(seed) {
const random = mulberry32(seed);
const approaches = ["N", "S", "E", "W"];
const vehicles = [];
const pedestrians = [];
let time = 0.2;
while (time < 3600) {
time += 0.9 + random() * 1.4;
const approach = approaches[Math.floor(random() * approaches.length)];
const route = random() < 0.36 ? "left" : "through";
vehicles.push({ time, approach, route });
}
for (const crossing of ["ns", "ew"]) {
let t = crossing === "ns" ? 4.5 : 10;
while (t < 3600) {
pedestrians.push({ time: t, crossing });
t += 9.5 + random() * 5.5;
}
}
return { vehicles, pedestrians };
}
const SHARED_DATA = generateSharedData(731);
// -------------------------------------------------------------------------
// Voxel route geometry
// -------------------------------------------------------------------------
class RoutePath {
constructor(points, stopDistance) {
this.points = points.map((p) => new THREE.Vector3(...p));
this.cumulative = [0];
for (let i = 1; i < this.points.length; i++) {
this.cumulative.push(
this.cumulative[i - 1] +
this.points[i].distanceTo(this.points[i - 1])
);
}
this.total = this.cumulative[this.cumulative.length - 1];
this.stopDistance = stopDistance;
}
sample(distance) {
const d = THREE.MathUtils.clamp(distance, 0, this.total);
let segment = this.cumulative.length - 2;
for (let i = 0; i < this.cumulative.length - 1; i++) {
if (d <= this.cumulative[i + 1]) {
segment = i;
break;
}
}
const a = this.points[segment];
const b = this.points[segment + 1];
const segmentStart = this.cumulative[segment];
const segmentLength = this.cumulative[segment + 1] - segmentStart;
const t = segmentLength > 0 ? (d - segmentStart) / segmentLength : 0;
const position = new THREE.Vector3().lerpVectors(a, b, t);
const tangent = new THREE.Vector3().subVectors(b, a).normalize();
return { position, tangent };
}
}
function pathFor(approach, route) {
if (route === "through") {
const paths = {
N: [[-2.6, 0, 27], [-2.6, 0, -27]],
S: [[ 2.6, 0,-27], [ 2.6, 0, 27]],
E: [[ 27, 0,-2.6], [-27, 0,-2.6]],
W: [[-27, 0, 2.6], [ 27, 0, 2.6]]
};
return new RoutePath(paths[approach], 22);
}
const paths = {
N: [
[ 2.6, 0, 21], [2.6, 0, 7], [3.8, 0, 3.8],
[ 8.0, 0, 2.6], [27, 0, 2.6]
],
S: [
[-2.6, 0,-21], [-2.6, 0,-7], [-3.8, 0,-3.8],
[-8.0, 0,-2.6], [-27, 0,-2.6]
],
E: [
[21, 0, 2.6], [7, 0, 2.6], [3.8, 0, 3.8],
[2.6, 0, 8.0], [2.6, 0, 27]
],
W: [
[-21, 0,-2.6], [-7, 0,-2.6], [-3.8, 0,-3.8],
[-2.6, 0,-8.0], [-2.6, 0,-27]
]
};
return new RoutePath(paths[approach], 14);
}
// -------------------------------------------------------------------------
// Deterministic traffic simulation
// -------------------------------------------------------------------------
const OPPOSITE = { N: "S", S: "N", E: "W", W: "E" };
const GROUP = { N: "ns", S: "ns", E: "ew", W: "ew" };
class Simulation {
constructor(schedule) {
this.schedule = schedule;
this.time = 0;
this.vehicleId = 0;
this.pedId = 0;
this.arrivalIndex = 0;
this.pedArrivalIndex = 0;
this.vehicles = [];
this.pedestrians = [];
this.completedVehicleDelays = [];
this.completedPedWaits = [];
this.conflictOverlaps = 0;
this.nextConflictCheck = 0;
this.lanes = new Map();
for (const approach of ["N", "S", "E", "W"]) {
for (const route of ["through", "left"]) {
const key = `${approach}-${route}`;
this.lanes.set(key, {
key,
approach,
route,
path: pathFor(approach, route),
queue: [],
nextRelease: 0
});
}
}
}
spawnDueArrivals() {
while (
this.arrivalIndex < SHARED_DATA.vehicles.length &&
SHARED_DATA.vehicles[this.arrivalIndex].time <= this.time
) {
const arrival = SHARED_DATA.vehicles[this.arrivalIndex++];
const lane = this.lanes.get(`${arrival.approach}-${arrival.route}`);
const vehicle = {
id: this.vehicleId++,
approach: arrival.approach,
route: arrival.route,
arrival: arrival.time,
state: "queued",
distance: 0,
speed: 0,
speedLimit: arrival.route === "left" ? 5.2 : 7.2,
path: lane.path,
active: true,
releasedAt: null
};
lane.queue.push(vehicle);
this.vehicles.push(vehicle);
}
while (
this.pedArrivalIndex < SHARED_DATA.pedestrians.length &&
SHARED_DATA.pedestrians[this.pedArrivalIndex].time <= this.time
) {
const arrival = SHARED_DATA.pedestrians[this.pedArrivalIndex++];
this.pedestrians.push({
id: this.pedId++,
crossing: arrival.crossing,
arrival: arrival.time,
state: "waiting",
start: null,
active: true
});
}
}
phaseAllows(approach, route, phase) {
const group = GROUP[approach];
if (route === "through") {
return phase.type === group;
}
if (this.schedule.key === "A") {
// Permissive left: served during the parallel through phase.
return phase.type === group;
}
// Protected left: each turning group receives a distinct phase.
return (
(group === "ns" && phase.type === "leftNS") ||
(group === "ew" && phase.type === "leftEW")
);
}
releaseVehicles(phase) {
for (const lane of this.lanes.values()) {
if (lane.queue.length === 0 || this.time < lane.nextRelease) {
continue;
}
if (!this.phaseAllows(lane.approach, lane.route, phase)) {
continue;
}
const vehicle = lane.queue.shift();
vehicle.state = "moving";
vehicle.speed = 0;
vehicle.distance = Math.max(
vehicle.distance,
lane.path.stopDistance - 0.25
);
vehicle.releasedAt = this.time;
lane.nextRelease = this.time + 1.2;
}
}
updateQueuedPositions() {
for (const lane of this.lanes.values()) {
lane.queue.forEach((vehicle, index) => {
vehicle.distance = Math.max(
0,
lane.path.stopDistance - index * 3.15
);
});
}
}
updateVehicles(dt) {
for (const vehicle of this.vehicles) {
if (vehicle.state !== "moving") continue;
vehicle.speed = Math.min(
vehicle.speed + 4.2 * dt,
vehicle.speedLimit
);
vehicle.distance += vehicle.speed * dt;
if (vehicle.distance >= vehicle.path.total) {
vehicle.active = false;
if (vehicle.releasedAt !== null) {
this.completedVehicleDelays.push(
vehicle.releasedAt - vehicle.arrival
);
}
}
}
this.vehicles = this.vehicles.filter((vehicle) => vehicle.active);
}
checkPermissiveOverlaps() {
if (this.schedule.key !== "A" || this.time < this.nextConflictCheck) {
return;
}
this.nextConflictCheck = this.time + 0.4;
const moving = this.vehicles.filter(
(vehicle) => vehicle.state === "moving"
);
for (const left of moving) {
if (left.route !== "left") continue;
const leftInConflict =
left.distance >= left.path.stopDistance - 1 &&
left.distance <= left.path.stopDistance + 7;
if (!leftInConflict) continue;
const opposing = moving.find(
(vehicle) =>
vehicle.route === "through" &&
vehicle.approach === OPPOSITE[left.approach] &&
vehicle.distance >= vehicle.path.stopDistance - 1 &&
vehicle.distance <= vehicle.path.stopDistance + 7
);
if (opposing) {
this.conflictOverlaps++;
}
}
}
pedestrianWalkAllowed(crossing, phase) {
const inWalkWindow = phase.elapsed < 15;
if (crossing === "ns") {
return phase.type === "ns" && inWalkWindow;
}
return phase.type === "ew" && inWalkWindow;
}
updatePedestrians(dt, phase) {
for (const pedestrian of this.pedestrians) {
if (
pedestrian.state === "waiting" &&
this.pedestrianWalkAllowed(pedestrian.crossing, phase)
) {
pedestrian.state = "walking";
pedestrian.start = this.time;
}
if (pedestrian.state === "walking") {
const progress = (this.time - pedestrian.start) / 6.8;
if (progress >= 1) {
pedestrian.state = "done";
pedestrian.active = false;
this.completedPedWaits.push(
pedestrian.start - pedestrian.arrival
);
}
}
}
this.pedestrians = this.pedestrians.filter(
(pedestrian) => pedestrian.active
);
}
update(dt) {
this.time += dt;
this.spawnDueArrivals();
this.updateQueuedPositions();
const phase = getPhase(this.schedule, this.time);
this.releaseVehicles(phase);
this.updateVehicles(dt);
this.checkPermissiveOverlaps();
this.updatePedestrians(dt, phase);
}
queueCount(group = null) {
let count = 0;
for (const lane of this.lanes.values()) {
if (!group || GROUP[lane.approach] === group) {
count += lane.queue.length;
}
}
return count;
}
leftQueueCount() {
let count = 0;
for (const lane of this.lanes.values()) {
if (lane.route === "left") {
count += lane.queue.length;
}
}
return count;
}
average(values) {
if (!values.length) return 0;
return values.reduce((sum, value) => sum + value, 0) / values.length;
}
averagePedWait() {
return this.average(this.completedPedWaits);
}
currentPedWait() {
const waiting = this.pedestrians.filter(
(pedestrian) => pedestrian.state === "waiting"
);
if (!waiting.length) return 0;
return this.average(
waiting.map((pedestrian) => this.time - pedestrian.arrival)
);
}
waitingPedCount() {
return this.pedestrians.filter(
(pedestrian) => pedestrian.state === "waiting"
).length;
}
averageVehicleDelay() {
return this.average(this.completedVehicleDelays);
}
}
// -------------------------------------------------------------------------
// Voxel scene construction
// -------------------------------------------------------------------------
const APPROACH_COLORS = {
N: 0xef6b61,
S: 0x2fc4a1,
E: 0xf3bb45,
W: 0x5b8def
};
function standard(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.86,
metalness: 0,
...options
});
}
class WorldView {
constructor(schedule) {
this.schedule = schedule;
this.scene = new THREE.Scene();
this.scene.background = new THREE.Color(0xcfe0da);
this.scene.fog = new THREE.Fog(0xcfe0da, 68, 125);
this.unitBox = new THREE.BoxGeometry(1, 1, 1);
this.dynamic = new THREE.Group();
this.scene.add(this.dynamic);
this.materials = {
ground: standard(0xc7d9ce),
road: standard(0x3d4850),
curb: standard(0xdce3dc),
stripe: standard(0xf2f1df),
center: standard(0xe7c04e),
dark: standard(0x26323a),
glass: standard(0x335462, { roughness: 0.42 }),
skin: standard(0xf2c7a5),
pedestrian: standard(0xef8b72),
pedestrianAlt: standard(0x6e83d8),
amber: standard(0xf3bb45, {
emissive: 0x7a4c00,
emissiveIntensity: 0.22
}),
window: standard(0xbfe6dc, {
emissive: 0x6ea394,
emissiveIntensity: 0.28
})
};
this.carMaterials = {
N: standard(APPROACH_COLORS.N),
S: standard(APPROACH_COLORS.S),
E: standard(APPROACH_COLORS.E),
W: standard(APPROACH_COLORS.W)
};
this.vehicleMeshes = new Map();
this.pedestrianMeshes = new Map();
this.setupLights();
this.buildWorld();
this.buildSignals();
}
box(
width,
height,
depth,
material,
x,
y,
z,
parent = this.scene
) {
const mesh = new THREE.Mesh(this.unitBox, material);
mesh.scale.set(width, height, depth);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
setupLights() {
const hemisphere = new THREE.HemisphereLight(
0xf6fff8,
0x7f8d87,
2.15
);
this.scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff5dc, 3.3);
sun.position.set(-24, 42, 18);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.camera.left = -48;
sun.shadow.camera.right = 48;
sun.shadow.camera.top = 48;
sun.shadow.camera.bottom = -48;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 100;
sun.shadow.bias = -0.0008;
this.scene.add(sun);
const fill = new THREE.DirectionalLight(0x9fc5ff, 0.8);
fill.position.set(28, 18, -25);
this.scene.add(fill);
}
buildWorld() {
this.box(88, 0.6, 88, this.materials.ground, 0, -0.58, 0);
// Main roads.
this.box(16, 0.18, 78, this.materials.road, 0, -0.08, 0);
this.box(78, 0.18, 16, this.materials.road, 0, -0.075, 0);
// Raised sidewalk blocks in the four corners.
for (const x of [-24, 24]) {
for (const z of [-24, 24]) {
this.box(
30,
0.32,
30,
this.materials.curb,
x,
0.02,
z
);
}
}
// Curb edges.
for (const side of [-1, 1]) {
for (const offset of [8.35, -8.35]) {
this.box(
0.38,
0.28,
76,
this.materials.curb,
offset,
0.03,
side * 38
);
this.box(
76,
0.28,
0.38,
this.materials.curb,
side * 38,
0.03,
offset
);
}
}
// Dashed center lines.
for (let p = -35; p <= 35; p += 6) {
if (Math.abs(p) > 11) {
this.box(
0.17,
0.035,
2.7,
this.materials.center,
0,
0.035,
p
);
this.box(
2.7,
0.035,
0.17,
this.materials.center,
p,
0.035,
0
);
}
}
// White road edge lines.
for (const offset of [-7.2, 7.2]) {
for (const segment of [-25, 25]) {
this.box(
0.12,
0.035,
24,
this.materials.stripe,
offset,
0.035,
segment
);
this.box(
24,
0.035,
0.12,
this.materials.stripe,
segment,
0.035,
offset
);
}
}
// Crosswalks: one pair across the N/S road and one across the E/W road.
for (const x of [-7.3, -6.1, -4.9, 4.9, 6.1, 7.3]) {
this.box(
0.42,
0.035,
2.7,
this.materials.stripe,
x,
0.04,
0
);
}
for (const z of [-7.3, -6.1, -4.9, 4.9, 6.1, 7.3]) {
this.box(
2.7,
0.035,
0.42,
this.materials.stripe,
0,
0.04,
z
);
}
// Translucent conflict-zone markers.
const conflictMaterial = new THREE.MeshBasicMaterial({
color: this.schedule.key === "A" ? 0xf3bb45 : 0x9b6dff,
transparent: true,
opacity: this.schedule.key === "A" ? 0.28 : 0.18,
depthWrite: false
});
for (const x of [-3.4, 3.4]) {
for (const z of [-3.4, 3.4]) {
const marker = new THREE.Mesh(
new THREE.PlaneGeometry(3.1, 3.1),
conflictMaterial
);
marker.rotation.x = -Math.PI / 2;
marker.position.set(x, 0.07, z);
this.scene.add(marker);
}
}
this.buildBuilding(18, 20, 8, 10, 7.5, 0xe7a58d);
this.buildBuilding(-20, 18, 9, 9, 10.5, 0x86b8c7);
this.buildBuilding(20, -21, 10, 9, 6.8, 0xc1a5d7);
this.buildBuilding(-19, -20, 8, 11, 8.8, 0x91b990);
this.buildBuilding(30, 19, 7, 7, 12, 0xd9c47f);
this.buildBuilding(-30, -18, 7, 8, 10.5, 0x7ea8a4);
this.buildTree(13, 13, 0.95);
this.buildTree(-13, 14, 0.8);
this.buildTree(13, -14, 0.86);
this.buildTree(-13, -13, 1.05);
this.buildTree(31, -11, 0.9);
this.buildTree(-31, 11, 0.9);
this.buildTree(11, 31, 0.78);
this.buildTree(-11, -31, 0.95);
// Small roadside utility blocks.
for (const [x, z] of [[10, 10], [-10, 10], [10, -10], [-10, -10]]) {
this.box(
1.1,
1.2,
1.1,
this.materials.curb,
x,
0.78,
z
);
this.box(
0.7,
0.15,
0.7,
this.materials.amber,
x,
1.42,
z
);
}
}
buildBuilding(x, z, width, depth, height, color) {
const material = standard(color);
const roofMaterial = standard(0x56636a);
this.box(
width,
height,
depth,
material,
x,
height / 2 + 0.18,
z
);
this.box(
width + 0.45,
0.38,
depth + 0.45,
roofMaterial,
x,
height + 0.34,
z
);
const windowCount = Math.max(2, Math.floor(width / 2.2));
for (let i = 0; i < windowCount; i++) {
const wx = x - width / 2 + 1.25 + i * ((width - 2.5) / (windowCount - 1));
for (const wy of [2.2, height - 1.4]) {
const sideX = x > 0 ? x - width / 2 - 0.04 : x + width / 2 + 0.04;
this.box(
0.08,
0.65,
0.75,
this.materials.window,
sideX,
wy,
wx
);
}
}
}
buildTree(x, z, scale) {
const trunk = standard(0x86684d);
const leaves = standard(0x6f9d77);
this.box(
0.55 * scale,
2.2 * scale,
0.55 * scale,
trunk,
x,
1.1 * scale,
z
);
this.box(
2.5 * scale,
2.0 * scale,
2.5 * scale,
leaves,
x,
2.8 * scale,
z
);
this.box(
1.8 * scale,
1.4 * scale,
1.8 * scale,
leaves,
x + 0.35 * scale,
3.6 * scale,
z - 0.2 * scale
);
}
buildSignals() {
this.signals = {};
this.pedestrianSignals = {};
const positions = {
N: [6.2, 10.2],
S: [-6.2, -10.2],
E: [10.2, -6.2],
W: [-10.2, 6.2]
};
const poleMaterial = standard(0x465157);
for (const [approach, [x, z]] of Object.entries(positions)) {
const group = new THREE.Group();
group.position.set(x, 0.18, z);
this.scene.add(group);
this.box(0.28, 2.8, 0.28, poleMaterial, 0, 1.4, 0, group);
this.box(1.3, 0.65, 0.48, poleMaterial, 0, 2.85, 0, group);
const red = standard(0x702c2c, {
emissive: 0x5d1010,
emissiveIntensity: 0.18
});
const yellow = standard(0x6d5c29, {
emissive: 0x5a4200,
emissiveIntensity: 0.14
});
const green = standard(0x285d47, {
emissive: 0x0b5a36,
emissiveIntensity: 0.14
});
const arrow = standard(0x413d50, {
emissive: 0x23163f,
emissiveIntensity: 0.1
});
this.box(0.27, 0.27, 0.18, red, -0.42, 2.85, 0.27, group);
this.box(0.27, 0.27, 0.18, yellow, 0, 2.85, 0.27, group);
this.box(0.27, 0.27, 0.18, green, 0.42, 2.85, 0.27, group);
const arrowMesh = this.box(
0.62,
0.22,
0.18,
arrow,
0,
3.32,
0.27,
group
);
this.signals[approach] = {
red,
yellow,
green,
arrow,
arrowMesh
};
}
const pedNS = standard(0x31443f);
const pedEW = standard(0x31443f);
this.pedestrianSignals.ns = this.box(
0.35,
0.55,
0.35,
pedNS,
-6.5,
1.2,
9.1
);
this.pedestrianSignals.ew = this.box(
0.35,
0.55,
0.35,
pedEW,
-9.1,
1.2,
6.5
);
}
createVehicle(vehicle) {
const group = new THREE.Group();
const bodyMaterial = this.carMaterials[vehicle.approach];
this.box(
1.55,
0.48,
2.65,
bodyMaterial,
0,
0.58,
0,
group
);
this.box(
1.28,
0.43,
1.3,
this.materials.glass,
0,
0.96,
-0.18,
group
);
this.box(
1.22,
0.12,
1.18,
bodyMaterial,
0,
1.2,
-0.18,
group
);
for (const x of [-0.78, 0.78]) {
for (const z of [-0.82, 0.82]) {
this.box(
0.24,
0.42,
0.45,
this.materials.dark,
x,
0.27,
z,
group
);
}
}
this.box(
0.4,
0.16,
0.16,
this.materials.stripe,
-0.45,
0.56,
1.34,
group
);
this.box(
0.4,
0.16,
0.16,
this.materials.stripe,
0.45,
0.56,
1.34,
group
);
if (vehicle.route === "left") {
this.box(
0.42,
0.18,
0.42,
this.materials.amber,
0,
1.38,
-0.18,
group
);
}
this.dynamic.add(group);
return group;
}
createPedestrian(pedestrian) {
const group = new THREE.Group();
const bodyMaterial =
pedestrian.id % 2 === 0
? this.materials.pedestrian
: this.materials.pedestrianAlt;
this.box(
0.42,
0.72,
0.34,
bodyMaterial,
0,
0.76,
0,
group
);
this.box(
0.38,
0.38,
0.38,
this.materials.skin,
0,
1.28,
0,
group
);
this.box(
0.16,
0.35,
0.18,
this.materials.dark,
-0.11,
0.25,
0,
group
);
this.box(
0.16,
0.35,
0.18,
this.materials.dark,
0.11,
0.25,
0,
group
);
this.dynamic.add(group);
return group;
}
setLamp(material, active, activeColor, inactiveColor) {
material.color.set(active ? activeColor : inactiveColor);
material.emissive.set(active ? activeColor : inactiveColor);
material.emissiveIntensity = active ? 1.8 : 0.08;
}
updateSignals(simulation) {
const phase = getPhase(simulation.schedule, simulation.time);
for (const approach of ["N", "S", "E", "W"]) {
const signal = this.signals[approach];
const group = GROUP[approach];
const throughOn =
phase.type === "ns" && group === "ns" ||
phase.type === "ew" && group === "ew";
const leftOn = simulation.schedule.key === "A"
? throughOn
: (
group === "ns" && phase.type === "leftNS"
) || (
group === "ew" && phase.type === "leftEW"
);
this.setLamp(signal.red, !throughOn && !leftOn, 0xff4f45, 0x4c2424);
this.setLamp(signal.yellow, false, 0xffc24a, 0x4a4028);
this.setLamp(signal.green, throughOn, 0x4df09d, 0x234b3b);
const arrowColor =
simulation.schedule.key === "A" ? 0xf3bb45 : 0x8cff72;
this.setLamp(
signal.arrow,
leftOn,
arrowColor,
simulation.schedule.key === "A" ? 0x4a4028 : 0x313a33
);
}
const nsWalk =
phase.type === "ns" && phase.elapsed < 15;
const ewWalk =
phase.type === "ew" && phase.elapsed < 15;
this.setLamp(
this.pedestrianSignals.ns.material,
nsWalk,
0x62f5b0,
0x503c3c
);
this.setLamp(
this.pedestrianSignals.ew.material,
ewWalk,
0x62f5b0,
0x503c3c
);
}
sync(simulation) {
const liveVehicles = new Set();
for (const vehicle of simulation.vehicles) {
liveVehicles.add(vehicle.id);
let mesh = this.vehicleMeshes.get(vehicle.id);
if (!mesh) {
mesh = this.createVehicle(vehicle);
this.vehicleMeshes.set(vehicle.id, mesh);
}
const sample = vehicle.path.sample(vehicle.distance);
mesh.position.copy(sample.position);
mesh.rotation.y = Math.atan2(
sample.tangent.x,
sample.tangent.z
);
}
for (const [id, mesh] of this.vehicleMeshes) {
if (!liveVehicles.has(id)) {
this.dynamic.remove(mesh);
this.vehicleMeshes.delete(id);
}
}
const livePedestrians = new Set();
for (const pedestrian of simulation.pedestrians) {
livePedestrians.add(pedestrian.id);
let mesh = this.pedestrianMeshes.get(pedestrian.id);
if (!mesh) {
mesh = this.createPedestrian(pedestrian);
this.pedestrianMeshes.set(pedestrian.id, mesh);
}
const offset = ((pedestrian.id % 3) - 1) * 0.55;
if (pedestrian.crossing === "ns") {
if (pedestrian.state === "walking") {
const progress = THREE.MathUtils.clamp(
(simulation.time - pedestrian.start) / 6.8,
0,
1
);
mesh.position.set(-6.4, 0.18, 9.3 - 18.6 * progress);
} else {
mesh.position.set(
-6.4 + offset,
0.18,
9.35
);
}
} else {
if (pedestrian.state === "walking") {
const progress = THREE.MathUtils.clamp(
(simulation.time - pedestrian.start) / 6.8,
0,
1
);
mesh.position.set(-9.3 + 18.6 * progress, 0.18, 6.4);
} else {
mesh.position.set(
-9.35,
0.18,
6.4 + offset
);
}
}
}
for (const [id, mesh] of this.pedestrianMeshes) {
if (!livePedestrians.has(id)) {
this.dynamic.remove(mesh);
this.pedestrianMeshes.delete(id);
}
}
this.updateSignals(simulation);
}
}
// -------------------------------------------------------------------------
// Renderer, scenes, and direct camera controls
// -------------------------------------------------------------------------
const stage = document.getElementById("stage");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.75));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.id = "sceneCanvas";
stage.appendChild(renderer.domElement);
const viewA = new WorldView(SCHEDULES.A);
const viewB = new WorldView(SCHEDULES.B);
let simulationA = new Simulation(SCHEDULES.A);
let simulationB = new Simulation(SCHEDULES.B);
const camera = new THREE.OrthographicCamera(-30, 30, 30, -30, 0.1, 180);
const cameraTarget = new THREE.Vector3(0, 0, 0);
let yaw = 0.73;
let pitch = 0.76;
let zoom = 1;
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
function resetCamera() {
yaw = 0.73;
pitch = 0.76;
zoom = 1;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
yaw -= dx * 0.006;
pitch = THREE.MathUtils.clamp(pitch + dy * 0.005, 0.38, 1.2);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
});
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(
"wheel",
(event) => {
event.preventDefault();
zoom = THREE.MathUtils.clamp(
zoom * Math.exp(-event.deltaY * 0.001),
0.7,
1.8
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
function updateCamera(aspect) {
const halfHeight = 29.5 / zoom;
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.updateProjectionMatrix();
const radius = 66;
camera.position.set(
Math.sin(yaw) * Math.cos(pitch) * radius,
Math.sin(pitch) * radius,
Math.cos(yaw) * Math.cos(pitch) * radius
);
camera.lookAt(cameraTarget);
}
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
function buildTimeline(id, schedule) {
const container = document.getElementById(id);
container.innerHTML = "";
for (const phase of schedule.phases) {
const segment = document.createElement("div");
segment.className = "timeline-segment";
segment.style.flexGrow = String(phase.end - phase.start);
segment.style.background = PHASE_COLORS[phase.type];
segment.title = `${phase.label}: ${phase.end - phase.start}s`;
container.appendChild(segment);
}
}
buildTimeline("aTimeline", SCHEDULES.A);
buildTimeline("bTimeline", SCHEDULES.B);
function updatePanel(prefix, simulation) {
const phase = getPhase(simulation.schedule, simulation.time);
const queue = simulation.queueCount();
const nsQueue = simulation.queueCount("ns");
const ewQueue = simulation.queueCount("ew");
document.getElementById(`${prefix}Phase`).textContent = phase.label;
document.getElementById(`${prefix}Clock`).textContent =
`t = ${simulation.time.toFixed(1)}s`;
document.getElementById(`${prefix}Queue`).textContent = String(queue);
document.getElementById(`${prefix}NS`).textContent = String(nsQueue);
document.getElementById(`${prefix}EWLabel`).textContent =
`E/W ${ewQueue}`;
document.getElementById(`${prefix}PedWait`).textContent =
`${simulation.averagePedWait().toFixed(1)}s`;
document.getElementById(`${prefix}PedCount`).textContent =
`${simulation.waitingPedCount()} waiting · current ${simulation.currentPedWait().toFixed(1)}s`;
document.getElementById(`${prefix}Left`).textContent =
String(simulation.leftQueueCount());
document.getElementById(`${prefix}Delay`).textContent =
`avg delay ${simulation.averageVehicleDelay().toFixed(1)}s`;
document.getElementById(`${prefix}Conflict`).textContent =
String(simulation.conflictOverlaps);
const segments = document
.getElementById(`${prefix}Timeline`)
.children;
for (let i = 0; i < segments.length; i++) {
segments[i].classList.toggle("active", i === phase.index);
}
}
function updateComparison() {
const time = Math.min(simulationA.time, simulationB.time);
document.getElementById("comparisonText").textContent =
`At ${time.toFixed(1)}s — ` +
`A: ${simulationA.queueCount()} queued, ` +
`${simulationA.averagePedWait().toFixed(1)}s mean pedestrian wait, ` +
`${simulationA.conflictOverlaps} overlap windows · ` +
`B: ${simulationB.queueCount()} queued, ` +
`${simulationB.averagePedWait().toFixed(1)}s mean pedestrian wait, ` +
`${simulationB.conflictOverlaps} overlap windows. ` +
`Illustrative snapshot only.`;
}
let running = true;
let speed = 1;
const playButton = document.getElementById("playButton");
playButton.addEventListener("click", () => {
running = !running;
playButton.textContent = running ? "Pause" : "Play";
});
document.getElementById("resetButton").addEventListener("click", () => {
simulationA = new Simulation(SCHEDULES.A);
simulationB = new Simulation(SCHEDULES.B);
viewA.sync(simulationA);
viewB.sync(simulationB);
updatePanel("a", simulationA);
updatePanel("b", simulationB);
updateComparison();
});
document.getElementById("viewButton").addEventListener("click", resetCamera);
document.getElementById("speedSelect").addEventListener("change", (event) => {
speed = Number(event.target.value);
});
// -------------------------------------------------------------------------
// Render loop
// -------------------------------------------------------------------------
let width = 0;
let height = 0;
function resize() {
width = Math.max(1, stage.clientWidth);
height = Math.max(1, stage.clientHeight);
renderer.setSize(width, height, false);
}
window.addEventListener("resize", resize);
resize();
let lastTime = performance.now();
let lastUiUpdate = 0;
function animate(now) {
const dt = Math.min(0.05, (now - lastTime) / 1000);
lastTime = now;
if (running) {
const simulationDt = dt * speed;
simulationA.update(simulationDt);
simulationB.update(simulationDt);
}
viewA.sync(simulationA);
viewB.sync(simulationB);
const stacked = width < 760;
renderer.setScissorTest(true);
if (stacked) {
const topHeight = Math.floor(height / 2);
const bottomHeight = height - topHeight;
updateCamera(width / topHeight);
renderer.setViewport(0, bottomHeight, width, topHeight);
renderer.setScissor(0, bottomHeight, width, topHeight);
renderer.render(viewA.scene, camera);
renderer.setViewport(0, 0, width, bottomHeight);
renderer.setScissor(0, 0, width, bottomHeight);
renderer.render(viewB.scene, camera);
} else {
const leftWidth = Math.floor(width / 2);
const rightWidth = width - leftWidth;
updateCamera(leftWidth / height);
renderer.setViewport(0, 0, leftWidth, height);
renderer.setScissor(0, 0, leftWidth, height);
renderer.render(viewA.scene, camera);
updateCamera(rightWidth / height);
renderer.setViewport(leftWidth, 0, rightWidth, height);
renderer.setScissor(leftWidth, 0, rightWidth, height);
renderer.render(viewB.scene, camera);
}
renderer.setScissorTest(false);
if (now - lastUiUpdate > 120) {
updatePanel("a", simulationA);
updatePanel("b", simulationB);
updateComparison();
lastUiUpdate = now;
}
requestAnimationFrame(animate);
}
updatePanel("a", simulationA);
updatePanel("b", simulationB);
updateComparison();
requestAnimationFrame(animate);
</script>
</body>
</html>
```