Prompt specification
Build or customize the Three.js 3D scene "Schedule two ferry arrivals through one entrance zone" 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: Schedule two ferry arrivals through one entrance zone
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/schedule-two-ferry-arrivals-through-one-entrance-zone-x2784
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring San Francisco's Ferry Building and Embarcadero. Let users vary fictional arrival spacing and inspect pedestrian flow at the terminal edge. Show crowding geometrically using stated movement rules rather than real passenger forecasts. Voxel style.
Working Three.js Starter (schedule-two-ferry-arrivals-through-one-entrance-zone-x2784):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ferry Building — Embarcadero Flow Study</title>
<style>
:root {
--ink: #eef5f4;
--muted: #aabbbc;
--panel: rgba(13, 29, 37, 0.91);
--line: rgba(207, 231, 229, 0.18);
--green: #31b67a;
--amber: #f1b84b;
--coral: #ee654d;
--water: #79b9c7;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #a9d1d7;
color: var(--ink);
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
"Liberation Mono", monospace;
}
button, input { font: inherit; }
#viewport,
#viewport canvas {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
}
#viewport canvas {
cursor: grab;
touch-action: none;
}
#viewport canvas.dragging { cursor: grabbing; }
.brand {
position: fixed;
z-index: 4;
top: 18px;
left: 20px;
max-width: 440px;
pointer-events: none;
text-shadow: 0 2px 12px rgba(0, 0, 0, 0.45);
}
.brand .eyebrow {
display: inline-block;
margin-bottom: 7px;
padding: 5px 8px;
color: #10252d;
background: #f0d99c;
font-size: 11px;
font-weight: 900;
letter-spacing: 0.12em;
}
.brand h1 {
margin: 0;
font-size: clamp(22px, 3vw, 39px);
line-height: 0.98;
letter-spacing: -0.055em;
}
.brand p {
margin: 9px 0 0;
color: #e0eeee;
font-size: 12px;
}
.panel {
position: fixed;
z-index: 5;
border: 1px solid var(--line);
border-radius: 3px;
background: var(--panel);
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.22);
backdrop-filter: blur(12px);
}
.controls {
left: 20px;
bottom: 20px;
width: 326px;
max-height: calc(100vh - 145px);
overflow: auto;
padding: 14px;
}
.inspector {
right: 20px;
bottom: 20px;
width: 340px;
padding: 14px;
max-height: calc(100vh - 38px);
overflow: auto;
}
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 12px;
color: #f1dca4;
font-size: 12px;
font-weight: 900;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.panel-title .tag {
color: var(--muted);
font-size: 9px;
letter-spacing: 0.04em;
text-transform: none;
}
.button-row {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 6px;
margin-bottom: 13px;
}
button {
min-height: 34px;
padding: 7px 8px;
border: 1px solid rgba(230, 242, 240, 0.24);
border-radius: 2px;
color: var(--ink);
background: #223b45;
cursor: pointer;
font-size: 10px;
font-weight: 800;
}
button:hover { background: #31515d; }
button:active { transform: translateY(1px); }
button.primary { background: #e5cb86; color: #14252c; }
button.primary:hover { background: #f2dda7; }
.control {
margin: 0 0 13px;
padding-bottom: 11px;
border-bottom: 1px solid rgba(220, 235, 234, 0.1);
}
.control:last-of-type { border-bottom: 0; }
.control label {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 8px;
color: #d6e1df;
font-size: 11px;
}
.control output {
color: #f4dda0;
font-weight: 900;
white-space: nowrap;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 4px 0;
accent-color: #edcf85;
cursor: pointer;
}
.range-ends {
display: flex;
justify-content: space-between;
margin-top: 5px;
color: #7f989c;
font-size: 9px;
}
.check-row {
display: flex;
align-items: center;
gap: 9px;
margin: 9px 0;
color: #d4e1df;
font-size: 11px;
}
.check-row input {
width: 15px;
height: 15px;
accent-color: #edcf85;
}
details {
margin-top: 13px;
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.025);
}
summary {
padding: 9px 10px;
color: #f1dca4;
cursor: pointer;
font-size: 10px;
font-weight: 900;
letter-spacing: 0.06em;
text-transform: uppercase;
}
details ul {
margin: 0;
padding: 0 13px 12px 25px;
color: #b9cbca;
font-size: 10px;
line-height: 1.48;
}
details li { margin: 5px 0; }
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin-bottom: 12px;
}
.metric {
min-height: 62px;
padding: 8px;
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.035);
}
.metric span {
display: block;
margin-bottom: 6px;
color: #91a8a9;
font-size: 8px;
line-height: 1.2;
text-transform: uppercase;
}
.metric strong {
color: #f6e7bd;
font-size: 18px;
}
#map {
display: block;
width: 100%;
height: auto;
margin: 8px 0 7px;
border: 1px solid var(--line);
background: #15323d;
cursor: crosshair;
}
.map-caption {
color: #82999c;
font-size: 9px;
line-height: 1.45;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 7px 12px;
margin-top: 10px;
color: #b9cbca;
font-size: 9px;
}
.legend span {
display: flex;
align-items: center;
gap: 5px;
}
.swatch {
display: inline-block;
width: 10px;
height: 10px;
background: #455a5d;
}
.swatch.green { background: var(--green); }
.swatch.amber { background: var(--amber); }
.swatch.coral { background: var(--coral); }
.swatch.blue { background: #2a6f89; }
.swatch.rust { background: #8c4f48; }
.detail-box {
margin-top: 12px;
padding: 10px;
border-left: 3px solid #e5cb86;
background: rgba(255, 255, 255, 0.035);
color: #b9cbca;
font-size: 10px;
line-height: 1.55;
}
.detail-box strong { color: #f0e4c0; }
.hint {
margin-top: 10px;
color: #789195;
font-size: 9px;
line-height: 1.45;
}
#loading {
position: fixed;
z-index: 20;
inset: 0;
display: grid;
place-items: center;
color: #10252d;
background: #a9d1d7;
font-weight: 900;
letter-spacing: 0.08em;
}
@media (max-width: 900px) {
.brand { max-width: 330px; }
.brand p { display: none; }
.controls { width: 292px; }
.inspector { width: 286px; }
}
@media (max-width: 660px) {
.brand { top: 10px; left: 10px; }
.brand h1 { font-size: 23px; }
.controls {
left: 10px;
bottom: 10px;
width: calc(100% - 20px);
max-height: 43vh;
}
.inspector {
top: 98px;
right: 10px;
bottom: auto;
width: 260px;
max-height: 36vh;
}
.metrics { grid-template-columns: repeat(3, 1fr); }
.metric { padding: 6px; }
.metric strong { font-size: 15px; }
}
</style>
</head>
<body>
<div id="viewport"></div>
<header class="brand">
<div class="eyebrow">SAN FRANCISCO · VOXEL STUDY</div>
<h1>Ferry Building / Embarcadero</h1>
<p>A geometric, fictional pedestrian-flow model at the terminal edge.</p>
</header>
<section class="panel controls">
<div class="panel-title">
<span>Flow controls</span>
<span class="tag">synthetic inputs</span>
</div>
<div class="button-row">
<button id="overview">Overview</button>
<button id="edge">Edge</button>
<button id="pause">Pause</button>
<button id="reset">Reset</button>
</div>
<div class="control">
<label for="spacing">
Arrival spacing
<output id="spacingValue">2.4 s</output>
</label>
<input id="spacing" type="range" min="0.6" max="8" step="0.1" value="2.4">
<div class="range-ends"><span>dense releases</span><span>wide releases</span></div>
</div>
<div class="control">
<label for="groupSize">
People per arrival group
<output id="groupValue">4 people</output>
</label>
<input id="groupSize" type="range" min="1" max="12" step="1" value="4">
</div>
<div class="control">
<label for="outbound">
Outbound people per arrival group
<output id="outboundValue">0.75</output>
</label>
<input id="outbound" type="range" min="0" max="2" step="0.25" value="0.75">
<div class="range-ends"><span>no outbound</span><span>two outbound</span></div>
</div>
<div class="control">
<label for="speed">
Preferred walking speed
<output id="speedValue">1.15 m/s</output>
</label>
<input id="speed" type="range" min="0.6" max="1.8" step="0.05" value="1.15">
</div>
<label class="check-row">
<input id="showDensity" type="checkbox" checked>
Show 2 × 2 m density cells
</label>
<label class="check-row">
<input id="showFlow" type="checkbox" checked>
Show aggregate flow vectors
</label>
<details open>
<summary>Movement rules — fictional</summary>
<ul>
<li>Arrival groups appear at the five ferry gates at the selected interval.</li>
<li>Outbound pedestrians are generated at the selected ratio per arrival group.</li>
<li>Each gate admits one pedestrian at a time. Waiters hold about 1.8 m before it.</li>
<li>Walkers seek an assigned target at their preferred speed, with ±10% variation.</li>
<li>Within 1.5 m, walkers slow and separate. A 0.68 m minimum center distance is enforced.</li>
<li>Density is cell occupancy divided by 4 m²: green <1.5, amber 1.5–<3, coral ≥3 people/m².</li>
<li>No passenger forecast, timetable, capacity claim, or safety threshold is represented.</li>
</ul>
</details>
</section>
<section class="panel inspector">
<div class="panel-title">
<span>Terminal edge</span>
<span class="tag">click a walker or cell</span>
</div>
<div class="metrics">
<div class="metric">
<span>People in edge zone</span>
<strong id="edgeCount">0</strong>
</div>
<div class="metric">
<span>Densest cell</span>
<strong id="peakDensity">0.0</strong>
</div>
<div class="metric">
<span>Gate crossings</span>
<strong id="crossingCount">0</strong>
</div>
</div>
<canvas id="map" width="600" height="250"></canvas>
<div class="map-caption">
Edge zone: 96 × 10 m. Building is above, ferry gates and water below.
Arrow length represents the average cell velocity.
</div>
<div class="legend">
<span><i class="swatch green"></i><1.5/m²</span>
<span><i class="swatch amber"></i>1.5–<3/m²</span>
<span><i class="swatch coral"></i>≥3/m²</span>
<span><i class="swatch blue"></i>inbound</span>
<span><i class="swatch rust"></i>outbound</span>
</div>
<div class="detail-box" id="detailBox">
<strong>No walker selected.</strong><br>
Click a voxel pedestrian to inspect direction, speed, local density, and gate state.
Click the map to focus a density cell.
</div>
<div class="hint">
Drag: orbit · Shift/right-drag: pan · Wheel: zoom<br>
Space: pause · R: reset · O: overview · E: terminal edge
</div>
</section>
<div id="loading">BUILDING EMBARCADERO…</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// DOM and renderer
// -------------------------------------------------------------------------
const viewport = document.getElementById("viewport");
const loading = document.getElementById("loading");
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.75));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
viewport.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xa9d1d7);
scene.fog = new THREE.Fog(0xa9d1d7, 145, 330);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
600
);
// -------------------------------------------------------------------------
// Camera controls, implemented directly without addons
// -------------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 4, -7);
const desiredTarget = cameraTarget.clone();
const desiredRadius = 140;
const desiredTheta = 0.78;
const desiredPhi = 0.91;
const pointer = new THREE.Vector2();
const raycaster = new THREE.Raycaster();
let dragging = false;
let dragButton = 0;
let dragMoved = false;
let lastPointerX = 0;
let lastPointerY = 0;
function updateCamera() {
const spherical = new THREE.Spherical(
desiredRadius,
desiredPhi,
desiredTheta
);
const offset = new THREE.Vector3().setFromSpherical(spherical);
camera.position.copy(desiredTarget).add(offset);
camera.lookAt(desiredTarget);
}
function focusArea(target, radius, theta = desiredTheta, phi = desiredPhi) {
desiredTarget.copy(target);
desiredRadius = radius;
desiredTheta = theta;
desiredPhi = phi;
}
renderer.domElement.addEventListener("contextmenu", event => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
dragButton = event.button;
dragMoved = false;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.classList.add("dragging");
});
renderer.domElement.addEventListener("pointermove", event => {
pointer.x = (event.clientX / window.innerWidth) * 2 - 1;
pointer.y = -(event.clientY / window.innerHeight) * 2 + 1;
if (!dragging) return;
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
if (Math.abs(dx) + Math.abs(dy) > 2) dragMoved = true;
if (dragButton === 2 || event.shiftKey) {
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 scale = desiredRadius * 0.0015;
desiredTarget
.addScaledVector(right, -dx * scale)
.addScaledVector(forward, dy * scale);
} else {
desiredTheta -= dx * 0.005;
desiredPhi = THREE.MathUtils.clamp(
desiredPhi - dy * 0.005,
0.25,
1.43
);
}
lastPointerX = event.clientX;
lastPointerY = event.clientY;
});
renderer.domElement.addEventListener("pointerup", event => {
dragging = false;
renderer.domElement.releasePointerCapture(event.pointerId);
renderer.domElement.classList.remove("dragging");
if (!dragMoved) selectUnderPointer(event);
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
desiredRadius = THREE.MathUtils.clamp(
desiredRadius * Math.exp(event.deltaY * 0.001),
24,
220
);
}, { passive: false });
// -------------------------------------------------------------------------
// Lighting and materials
// -------------------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0xe4f5ff, 0x76634d, 2.0));
const sun = new THREE.DirectionalLight(0xffe7bd, 3.3);
sun.position.set(-65, 105, 55);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -110;
sun.shadow.camera.right = 110;
sun.shadow.camera.top = 100;
sun.shadow.camera.bottom = -90;
sun.shadow.camera.near = 5;
sun.shadow.camera.far = 260;
sun.shadow.bias = -0.0006;
scene.add(sun);
const material = (color, options = {}) => new THREE.MeshStandardMaterial({
color,
roughness: 0.85,
metalness: 0.0,
...options
});
const mats = {
ground: material(0x89927d),
quay: material(0xaaa997),
sidewalk: material(0xbebca8),
road: material(0x3c474b),
rail: material(0x687276, { metalness: 0.45, roughness: 0.55 }),
building: material(0xd6c49f),
trim: material(0xf0dfb8),
roof: material(0x52666a),
glass: material(0x244956, { roughness: 0.35, metalness: 0.1 }),
dark: material(0x25383d),
pier: material(0x9b9887),
piling: material(0x5e5a4c),
yellow: material(0xe0b655),
water: material(0x4f9fb1, { roughness: 0.36, metalness: 0.05 }),
wave: material(0xa4d3da, {
transparent: true,
opacity: 0.38,
roughness: 0.5
}),
foliage: material(0x526e45),
trunk: material(0x6b5742)
};
function addBox(w, h, d, x, y, z, mat, parent = scene, cast = true) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), mat);
mesh.position.set(x, y, z);
mesh.castShadow = cast;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeLabel(text, width = 8, height = 2, background = "#183740", color = "#f2d99c") {
const canvas = document.createElement("canvas");
canvas.width = 1024;
canvas.height = 160;
const ctx = canvas.getContext("2d");
ctx.fillStyle = background;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = color;
ctx.font = "900 84px monospace";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, canvas.width / 2, canvas.height / 2 + 4);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.NearestFilter;
return new THREE.Mesh(
new THREE.PlaneGeometry(width, height),
new THREE.MeshBasicMaterial({
map: texture,
transparent: true,
toneMapped: false,
side: THREE.DoubleSide
})
);
}
// -------------------------------------------------------------------------
// Ground, water, Embarcadero and streetcar
// -------------------------------------------------------------------------
addBox(160, 1, 88, 0, -0.62, -34, mats.ground);
addBox(300, 0.8, 210, 0, -0.56, 115, mats.water, scene, false);
// Ferry Building terminal apron.
addBox(106, 0.16, 15, 0, -0.03, 2.5, mats.sidewalk);
// Quay wall.
addBox(160, 2.2, 1.2, 0, -0.8, 9.2, mats.quay);
// Embarcadero roadway, tracks and sidewalk.
addBox(160, 0.16, 18, 0, -0.05, -48, mats.road);
addBox(160, 0.18, 5, 0, 0.0, -36, mats.sidewalk);
addBox(160, 0.16, 0.16, 0, 0.07, -52.5, mats.rail);
addBox(160, 0.16, 0.16, 0, 0.07, -54.3, mats.rail);
for (let x = -75; x <= 75; x += 9) {
addBox(4.2, 0.025, 0.16, x, 0.055, -45.5, mats.trim, scene, false);
}
// Voxel streetcar.
const streetcar = new THREE.Group();
streetcar.position.set(-55, 0, -53.4);
scene.add(streetcar);
addBox(22, 3.2, 4.0, 0, 2.15, 0, mats.trim, streetcar);
addBox(21, 0.35, 3.8, 0, 3.9, 0, mats.roof, streetcar);
addBox(8, 0.55, 2.0, 0, 4.25, 0, mats.dark, streetcar);
for (let x = -8.7; x <= 8.7; x += 2.9) {
addBox(2.05, 1.25, 0.08, x, 2.65, 2.03, mats.glass, streetcar);
addBox(2.05, 1.25, 0.08, x, 2.65, -2.03, mats.glass, streetcar);
}
for (const x of [-7, 7]) {
addBox(1.1, 0.8, 4.3, x, 0.35, 0, mats.dark, streetcar);
}
// -------------------------------------------------------------------------
// Ferry Building
// -------------------------------------------------------------------------
const building = new THREE.Group();
scene.add(building);
// Main hall and layered roof.
addBox(100, 9, 24, 0, 4.45, -22, mats.building, building);
addBox(102, 0.65, 25.5, 0, 9.25, -22, mats.trim, building);
addBox(96, 0.55, 23.5, 0, 9.75, -22, mats.roof, building);
// Central clock tower.
addBox(14, 20, 14, 0, 19.0, -21, mats.building, building);
addBox(15.2, 0.75, 15.2, 0, 29.3, -21, mats.trim, building);
addBox(12.8, 0.55, 12.8, 0, 29.95, -21, mats.roof, building);
addBox(9.5, 0.7, 9.5, 0, 30.55, -21, mats.trim, building);
addBox(6.8, 0.7, 6.8, 0, 31.2, -21, mats.roof, building);
// Clock face: a square, voxel interpretation.
addBox(5.6, 5.6, 0.35, 0, 24.2, -13.75, mats.dark, building);
addBox(4.7, 4.7, 0.18, 0, 24.2, -13.52, mats.trim, building);
for (const [x, y, w, h] of [
[0, 2.0, 0.18, 0.55],
[0, -2.0, 0.18, 0.55],
[2.0, 0, 0.55, 0.18],
[-2.0, 0, 0.55, 0.18]
]) {
addBox(w, h, 0.1, x, 24.2 + y, -13.36, mats.dark, building, false);
}
addBox(0.18, 1.75, 0.12, 0.28, 24.55, -13.24, mats.dark, building, false);
addBox(1.35, 0.18, 0.12, -0.35, 24.12, -13.22, mats.dark, building, false);
addBox(0.5, 0.5, 0.25, 0, 24.2, -13.1, mats.dark, building, false);
// End towers.
for (const x of [-44, 44]) {
addBox(10, 13, 15, x, 15.0, -22, mats.building, building);
addBox(11, 0.65, 16, x, 21.8, -22, mats.trim, building);
addBox(9, 0.65, 14, x, 22.5, -22, mats.roof, building);
}
// Front arcade: dark recessed windows and square columns.
const doorXs = [-40, -24, -12, 0, 12, 24, 40];
for (let x = -42; x <= 42; x += 6) {
if (Math.abs(x) < 5) continue;
addBox(4.2, 5.0, 0.25, x, 4.7, -9.86, mats.glass, building, false);
addBox(0.9, 8.4, 1.25, x + 3.0, 4.15, -9.48, mats.trim, building);
addBox(3.6, 1.15, 0.28, x, 7.85, -9.68, mats.glass, building, false);
}
// Building doors and upper windows.
for (const x of doorXs) {
addBox(3.0, 4.2, 0.35, x, 2.1, -9.74, mats.glass, building, false);
addBox(3.6, 0.45, 1.2, x, 4.45, -9.5, mats.trim, building);
}
for (let x = -45; x <= 45; x += 6) {
if (Math.abs(x) < 7) continue;
addBox(2.2, 1.1, 0.2, x, 8.0, -9.72, mats.glass, building, false);
}
const ferrySign = makeLabel("FERRY BUILDING", 34, 4.2);
ferrySign.position.set(-25, 8.0, -9.55);
building.add(ferrySign);
const towerSign = makeLabel("FERRY", 8.4, 2.0);
towerSign.position.set(0, 16.3, -13.9);
building.add(towerSign);
// -------------------------------------------------------------------------
// Gates, piers and voxel ferries
// -------------------------------------------------------------------------
const gateXs = [-36, -18, 0, 18, 36];
const gates = gateXs.map((x, index) => {
addBox(6.2, 0.55, 26, x, 0.25, 22, mats.pier);
addBox(6.8, 0.35, 0.8, x, 0.55, 35.1, mats.trim);
for (const px of [-2.45, 2.45]) {
for (const pz of [12, 23, 33]) {
addBox(0.6, 4.0, 0.6, x + px, 0.2, pz, mats.piling);
}
}
// Gate frame.
addBox(0.45, 4.6, 0.45, x - 2.15, 2.4, 7.5, mats.yellow);
addBox(0.45, 4.6, 0.45, x + 2.15, 2.4, 7.5, mats.yellow);
addBox(4.8, 0.5, 0.55, x, 4.6, 7.5, mats.yellow);
const label = makeLabel(String(index + 1), 1.1, 1.1);
label.position.set(x, 4.58, 7.79);
scene.add(label);
return {
index,
x,
z: 7.5,
occupant: null,
cooldown: 0
};
});
function makeFerry(x, z, hullColor) {
const ferry = new THREE.Group();
ferry.position.set(x, 0, z);
scene.add(ferry);
const hullMat = material(hullColor);
addBox(12, 1.8, 20, 0, 0.4, 0, hullMat, ferry);
addBox(10.5, 3.0, 12.5, 0, 2.7, -1.0, mats.trim, ferry);
addBox(11.0, 0.45, 13.0, 0, 4.4, -1.0, mats.roof, ferry);
for (const side of [-5.28, 5.28]) {
for (let zz = -5.5; zz <= 4; zz += 2.4) {
addBox(0.1, 1.0, 1.7, side, 3.0, zz, mats.glass, ferry, false);
}
}
addBox(3.2, 1.5, 3.0, 0, 5.2, -1.8, mats.dark, ferry);
addBox(0.45, 4.2, 0.45, 0, 7.3, -1.8, mats.yellow, ferry);
return ferry;
}
const ferries = [
makeFerry(-18, 46, 0x284f61),
makeFerry(18, 49, 0x8a4d43)
];
// Small waterfront trees and lamps.
for (const x of [-57, -50, 50, 57]) {
addBox(1.0, 3.5, 1.0, x, 1.5, -6.5, mats.trunk);
addBox(4.0, 3.0, 4.0, x, 4.2, -6.5, mats.foliage);
addBox(3.0, 1.4, 3.0, x, 6.1, -6.5, mats.foliage);
}
for (const x of [-44, -8, 8, 44]) {
addBox(0.25, 5.0, 0.25, x, 2.5, -5.5, mats.dark);
addBox(1.1, 0.35, 1.1, x, 5.0, -5.5, mats.trim);
}
// -------------------------------------------------------------------------
// Animated water strips
// -------------------------------------------------------------------------
const waveCount = 95;
const waveGeometry = new THREE.BoxGeometry(2.0, 0.035, 0.35);
const waveMesh = new THREE.InstancedMesh(waveGeometry, mats.wave, waveCount);
waveMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
waveMesh.receiveShadow = false;
scene.add(waveMesh);
const waveData = [];
const waveDummy = new THREE.Object3D();
for (let i = 0; i < waveCount; i++) {
waveData.push({
x: (Math.random() - 0.5) * 280,
z: 16 + Math.random() * 180,
phase: Math.random() * Math.PI * 2,
scale: 0.5 + Math.random() * 1.9
});
}
// -------------------------------------------------------------------------
// Simulation state
// -------------------------------------------------------------------------
const MAX_AGENTS = 300;
let agents = [];
const agentSlots = new Array(MAX_AGENTS).fill(null);
let simTime = 0;
let arrivalTimer = 0;
let outboundCredit = 0;
let crossingCount = 0;
let crossingTimes = [];
let arrivalSpacing = 2.4;
let groupSize = 4;
let outboundRatio = 0.75;
let preferredSpeed = 1.15;
let paused = false;
let selectedAgent = null;
let selectedCell = null;
const agentBodyColors = {
inbound: new THREE.Color(0x2a6f89),
outbound: new THREE.Color(0x8c4f48)
};
const skinColors = [
new THREE.Color(0xf0c39e),
new THREE.Color(0xc98f67),
new THREE.Color(0x8d5a42),
new THREE.Color(0xe0aa80),
new THREE.Color(0x5f4034)
];
const densityColors = [
new THREE.Color(0x31b67a),
new THREE.Color(0xf1b84b),
new THREE.Color(0xee654d)
];
function densityColor(density, target = new THREE.Color()) {
if (density < 1.5) return target.copy(densityColors[0]);
if (density < 3.0) return target.copy(densityColors[1]);
return target.copy(densityColors[2]);
}
// -------------------------------------------------------------------------
// Instanced voxel pedestrians
// -------------------------------------------------------------------------
function createInstancedMesh(geometry, mat, count = MAX_AGENTS) {
const mesh = new THREE.InstancedMesh(geometry, mat, count);
mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
return mesh;
}
const bodyMesh = createInstancedMesh(
new THREE.BoxGeometry(0.58, 0.78, 0.42),
material(0xffffff)
);
const headMesh = createInstancedMesh(
new THREE.BoxGeometry(0.42, 0.42, 0.42),
material(0xffffff)
);
const leftLegMesh = createInstancedMesh(
new THREE.BoxGeometry(0.22, 0.68, 0.25),
material(0x26363d)
);
const rightLegMesh = createInstancedMesh(
new THREE.BoxGeometry(0.22, 0.68, 0.25),
material(0x26363d)
);
const badgeMesh = createInstancedMesh(
new THREE.BoxGeometry(0.22, 0.22, 0.10),
new THREE.MeshBasicMaterial({ toneMapped: false })
);
badgeMesh.castShadow = false;
// Selected-agent square marker.
const selectionMarker = new THREE.Group();
scene.add(selectionMarker);
selectionMarker.visible = false;
for (let i = 0; i < 4; i++) {
const bar = addBox(
i % 2 === 0 ? 1.0 : 0.12,
0.08,
i % 2 === 0 ? 0.12 : 1.0,
0,
0.18,
0,
new THREE.MeshBasicMaterial({ color: 0xfff2b8 }),
selectionMarker,
false
);
bar.position.x = i < 2 ? (i === 0 ? -0.44 : 0.44) : 0;
bar.position.z = i < 2 ? 0 : (i === 2 ? -0.44 : 0.44);
}
// -------------------------------------------------------------------------
// Density cells and flow arrows
// -------------------------------------------------------------------------
const CELL_SIZE = 2;
const GRID_X = 24;
const GRID_Z = 5;
const CELL_COUNT = GRID_X * GRID_Z;
const cells = Array.from({ length: CELL_COUNT }, () => ({
count: 0,
inbound: 0,
outbound: 0,
vx: 0,
vz: 0,
speedSum: 0
}));
const densityMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1.86, 0.055, 1.86),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0.52,
depthWrite: false,
toneMapped: false
}),
CELL_COUNT
);
densityMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
densityMesh.renderOrder = 2;
scene.add(densityMesh);
const arrowShape = new THREE.Shape();
arrowShape.moveTo(-0.12, -0.55);
arrowShape.lineTo(0.12, -0.55);
arrowShape.lineTo(0.12, 0.08);
arrowShape.lineTo(0.42, 0.08);
arrowShape.lineTo(0, 0.70);
arrowShape.lineTo(-0.42, 0.08);
arrowShape.lineTo(-0.12, 0.08);
arrowShape.closePath();
const arrowGeometry = new THREE.ShapeGeometry(arrowShape);
arrowGeometry.rotateX(Math.PI / 2);
const flowMesh = new THREE.InstancedMesh(
arrowGeometry,
new THREE.MeshBasicMaterial({
color: 0xf7f1ce,
transparent: true,
opacity: 0.82,
depthWrite: false,
side: THREE.DoubleSide,
toneMapped: false
}),
CELL_COUNT
);
flowMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
flowMesh.renderOrder = 3;
scene.add(flowMesh);
function cellIndexFor(x, z) {
const col = Math.floor((x + 48) / CELL_SIZE);
const row = Math.floor(z / CELL_SIZE);
if (col < 0 || col >= GRID_X || row < 0 || row >= GRID_Z) {
return -1;
}
return row * GRID_X + col;
}
function cellCenter(index) {
const row = Math.floor(index / GRID_X);
const col = index % GRID_X;
return {
x: -48 + (col + 0.5) * CELL_SIZE,
z: (row + 0.5) * CELL_SIZE
};
}
// -------------------------------------------------------------------------
// Spawning
// -------------------------------------------------------------------------
function spawnAgent(options) {
let slot = -1;
for (let i = 0; i < MAX_AGENTS; i++) {
if (!agentSlots[i]) {
slot = i;
break;
}
}
if (slot < 0) return null;
const id = agentSlots.reduce((unused, value, index) => {
return value === null ? index : unused;
}, -1);
const agent = {
slot,
id: slot + 1,
alive: true,
direction: options.direction,
stage: options.direction === "inbound" ? "toBuilding" : "toGate",
gateIndex: options.gateIndex,
x: options.x,
z: options.z,
vx: 0,
vz: 0,
speed: options.speed,
targetX: options.targetX,
targetZ: options.targetZ,
granted: false,
waiting: false,
walkPhase: Math.random() * Math.PI * 2,
localDensity: 0,
skin: skinColors[slot % skinColors.length]
};
agentSlots[slot] = agent;
agents.push(agent);
return agent;
}
function spawnInboundGroup(count = groupSize) {
for (let i = 0; i < count; i++) {
const gateIndex = Math.floor(Math.random() * gates.length);
const gate = gates[gateIndex];
// Choose a building door roughly aligned with the arrival gate.
let nearestDoor = doorXs[0];
let nearestDistance = Infinity;
for (const door of doorXs) {
const d = Math.abs(door - gate.x);
if (d < nearestDistance) {
nearestDistance = d;
nearestDoor = door;
}
}
spawnAgent({
direction: "inbound",
gateIndex,
x: gate.x + (Math.random() - 0.5) * 1.3,
z: 10.1 + Math.random() * 0.8,
speed: preferredSpeed * (0.9 + Math.random() * 0.2),
targetX: nearestDoor,
targetZ: -10.5
});
}
}
function chooseOutboundGate(x) {
let bestIndex = 0;
let bestScore = Infinity;
for (let i = 0; i < gates.length; i++) {
const queue = agents.filter(agent =>
agent.alive &&
agent.direction === "outbound" &&
agent.gateIndex === i &&
agent.stage === "toGate"
).length;
const distance = Math.abs(gates[i].x - x);
const score = distance + queue * 2.2;
if (score < bestScore) {
bestScore = score;
bestIndex = i;
}
}
return bestIndex;
}
function spawnOutbound() {
const doorX = doorXs[Math.floor(Math.random() * doorXs.length)];
const gateIndex = chooseOutboundGate(doorX);
const gate = gates[gateIndex];
spawnAgent({
direction: "outbound",
gateIndex,
x: doorX + (Math.random() - 0.5) * 1.2,
z: -9.0 + Math.random() * 0.4,
speed: preferredSpeed * (0.9 + Math.random() * 0.2),
targetX: gate.x,
targetZ: gate.z
});
}
function retireAgent(agent) {
agent.alive = false;
const gate = gates[agent.gateIndex];
if (gate && gate.occupant === agent.id) {
gate.occupant = null;
gate.cooldown = 0.18;
}
if (selectedAgent === agent) {
selectedAgent = null;
selectionMarker.visible = false;
}
}
// -------------------------------------------------------------------------
// Movement rules and collision resolution
// -------------------------------------------------------------------------
function updateSimulation(dt) {
simTime += dt;
arrivalTimer -= dt;
if (arrivalTimer <= 0) {
spawnInboundGroup(groupSize);
outboundCredit += outboundRatio;
while (outboundCredit >= 1) {
spawnOutbound();
outboundCredit -= 1;
}
arrivalTimer += arrivalSpacing;
}
for (const gate of gates) {
gate.cooldown = Math.max(0, gate.cooldown - dt);
}
// Desired movement and local interaction.
for (const agent of agents) {
if (!agent.alive) continue;
const gate = gates[agent.gateIndex];
const gateDistance = Math.hypot(agent.x - gate.x, agent.z - gate.z);
let targetX = agent.targetX;
let targetZ = agent.targetZ;
let speedFactor = 1;
agent.waiting = false;
// One-person gate capacity, with a short geometric waiting area.
if (!agent.granted && gateDistance < 4.5) {
if (gate.occupant === null && gate.cooldown <= 0) {
gate.occupant = agent.id;
agent.granted = true;
} else {
agent.waiting = true;
speedFactor = 0.035;
const side = agent.id % 2 === 0 ? -0.6 : 0.6;
targetX = gate.x + side;
targetZ = gate.z + (agent.direction === "inbound" ? 1.8 : -1.8);
}
}
// Inbound walkers need to clear the gate before it can be reused.
if (agent.granted && agent.direction === "inbound" && agent.z < gate.z - 0.9) {
gate.occupant = null;
gate.cooldown = 0.18;
agent.granted = false;
agent.stage = "toBuilding";
}
// Outbound walkers cross outward and continue down the pier.
if (agent.granted && agent.direction === "outbound" && agent.z > gate.z + 0.9) {
gate.occupant = null;
gate.cooldown = 0.18;
agent.granted = false;
agent.stage = "toPier";
agent.targetX = gate.x;
agent.targetZ = 24.0;
}
let dx = targetX - agent.x;
let dz = targetZ - agent.z;
let distance = Math.hypot(dx, dz);
if (distance < 0.05) {
dx = 0;
dz = 0;
distance = 1;
}
let desiredVX = (dx / distance) * agent.speed * speedFactor;
let desiredVZ = (dz / distance) * agent.speed * speedFactor;
let nearby = 0;
let separationX = 0;
let separationZ = 0;
let averageVX = 0;
let averageVZ = 0;
for (const other of agents) {
if (!other.alive || other === agent) continue;
const ox = agent.x - other.x;
const oz = agent.z - other.z;
const d = Math.hypot(ox, oz);
if (d < 2.5) {
nearby++;
averageVX += other.vx;
averageVZ += other.vz;
}
if (d < 1.5 && d > 0.0001) {
const force = (1.5 - d) / 1.5;
separationX += (ox / d) * force;
separationZ += (oz / d) * force;
}
}
// Slow down in the local crowd and add a small alignment component.
const slowFactor = 1 / (1 + Math.max(0, nearby - 1) * 0.22);
desiredVX = desiredVX * slowFactor + separationX * 0.95;
desiredVZ = desiredVZ * slowFactor + separationZ * 0.95;
if (nearby > 0) {
desiredVX += (averageVX / nearby - desiredVX) * 0.08;
desiredVZ += (averageVZ / nearby - desiredVZ) * 0.08;
}
const acceleration = Math.min(1, dt * 5.5);
agent.vx += (desiredVX - agent.vx) * acceleration;
agent.vz += (desiredVZ - agent.vz) * acceleration;
agent.x += agent.vx * dt;
agent.z += agent.vz * dt;
agent.walkPhase += dt * (2.2 + Math.hypot(agent.vx, agent.vz) * 3.0);
// Finish or retire.
if (agent.direction === "inbound" && agent.z < -10.8) {
retireAgent(agent);
continue;
}
if (agent.direction === "outbound" && agent.z > 23.5) {
retireAgent(agent);
continue;
}
}
// Hard center-to-center separation: pedestrians cannot occupy the same voxel.
for (let iteration = 0; iteration < 2; iteration++) {
for (let i = 0; i < agents.length; i++) {
const a = agents[i];
if (!a.alive) continue;
for (let j = i + 1; j < agents.length; j++) {
const b = agents[j];
if (!b.alive) continue;
let dx = a.x - b.x;
let dz = a.z - b.z;
let distance = Math.hypot(dx, dz);
if (distance < 0.0001) {
dx = 0.01 * (i % 2 === 0 ? 1 : -1);
dz = 0.01;
distance = Math.hypot(dx, dz);
}
if (distance < 0.68) {
const correction = (0.68 - distance) * 0.5;
const nx = dx / distance;
const nz = dz / distance;
a.x += nx * correction;
a.z += nz * correction;
b.x -= nx * correction;
b.z -= nz * correction;
}
}
}
}
// Keep walkers on the apron or their assigned pier.
for (const agent of agents) {
if (!agent.alive) continue;
agent.x = THREE.MathUtils.clamp(agent.x, -68, 68);
if (agent.z > 9.0) {
const gate = gates[agent.gateIndex];
if (Math.abs(agent.x - gate.x) > 2.6) {
agent.z = 9.0;
}
}
if (agent.z < -11.5) agent.z = -11.5;
}
agents = agents.filter(agent => agent.alive);
}
// -------------------------------------------------------------------------
// Density computation, visual overlays and inspector map
// -------------------------------------------------------------------------
const mapCanvas = document.getElementById("map");
const mapCtx = mapCanvas.getContext("2d");
const mapRect = { x: 20, y: 24, w: 560, h: 202 };
function updateDensityGrid() {
for (const cell of cells) {
cell.count = 0;
cell.inbound = 0;
cell.outbound = 0;
cell.vx = 0;
cell.vz = 0;
cell.speedSum = 0;
}
for (const agent of agents) {
if (!agent.alive) continue;
const index = cellIndexFor(agent.x, agent.z);
if (index < 0) continue;
const cell = cells[index];
cell.count++;
if (agent.direction === "inbound") cell.inbound++;
else cell.outbound++;
cell.vx += agent.vx;
cell.vz += agent.vz;
cell.speedSum += Math.hypot(agent.vx, agent.vz);
}
const dummy = new THREE.Object3D();
const color = new THREE.Color();
for (let i = 0; i < CELL_COUNT; i++) {
const cell = cells[i];
const center = cellCenter(i);
const density = cell.count / (CELL_SIZE * CELL_SIZE);
dummy.position.set(center.x, 0.08, center.z);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(cell.count ? 1 : 0.001, 1, cell.count ? 1 : 0.001);
dummy.updateMatrix();
densityMesh.setMatrixAt(i, dummy.matrix);
densityColor(density, color);
densityMesh.setColorAt(i, color);
if (cell.count > 0) {
const vx = cell.vx / cell.count;
const vz = cell.vz / cell.count;
const speed = Math.hypot(vx, vz);
const yaw = Math.atan2(vx, vz);
const scale = THREE.MathUtils.clamp(0.5 + speed * 0.75, 0.55, 1.45);
dummy.position.set(center.x, 0.15, center.z);
dummy.rotation.set(0, yaw, 0);
dummy.scale.set(scale, scale, scale);
} else {
dummy.position.set(center.x, -5, center.z);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(0.001, 0.001, 0.001);
}
dummy.updateMatrix();
flowMesh.setMatrixAt(i, dummy.matrix);
}
densityMesh.instanceMatrix.needsUpdate = true;
densityMesh.instanceColor.needsUpdate = true;
flowMesh.instanceMatrix.needsUpdate = true;
// Attach each agent's current cell density to its chest badge.
for (const agent of agents) {
const index = cellIndexFor(agent.x, agent.z);
agent.localDensity = index >= 0 ? cells[index].count / 4 : 0;
}
drawInspectorMap();
updateMetrics();
}
function drawInspectorMap() {
const ctx = mapCtx;
ctx.clearRect(0, 0, mapCanvas.width, mapCanvas.height);
ctx.fillStyle = "#15323d";
ctx.fillRect(0, 0, mapCanvas.width, mapCanvas.height);
const cellW = mapRect.w / GRID_X;
const cellH = mapRect.h / GRID_Z;
for (let i = 0; i < CELL_COUNT; i++) {
const row = Math.floor(i / GRID_X);
const col = i % GRID_X;
const cell = cells[i];
const density = cell.count / 4;
const x = mapRect.x + col * cellW;
const y = mapRect.y + row * cellH;
if (cell.count > 0) {
const color = density < 1.5
? "rgba(49,182,122,0.82)"
: density < 3
? "rgba(241,184,75,0.86)"
: "rgba(238,101,77,0.9)";
ctx.fillStyle = color;
ctx.fillRect(x + 1, y + 1, cellW - 2, cellH - 2);
} else {
ctx.fillStyle = "rgba(112,145,151,0.11)";
ctx.fillRect(x + 1, y + 1, cellW - 2, cellH - 2);
}
if (selectedCell === i) {
ctx.strokeStyle = "#fff0ae";
ctx.lineWidth = 3;
ctx.strokeRect(x + 2, y + 2, cellW - 4, cellH - 4);
}
}
// Gate positions.
ctx.strokeStyle = "rgba(245,220,151,0.75)";
ctx.lineWidth = 2;
for (const gate of gates) {
const mapX = mapRect.x + ((gate.x + 48) / 96) * mapRect.w;
ctx.beginPath();
ctx.moveTo(mapX, mapRect.y + mapRect.h - 10);
ctx.lineTo(mapX, mapRect.y + mapRect.h);
ctx.stroke();
}
// Flow vectors.
ctx.strokeStyle = "rgba(255,255,240,0.92)";
ctx.fillStyle = "rgba(255,255,240,0.92)";
ctx.lineWidth = 2;
for (let i = 0; i < CELL_COUNT; i++) {
const cell = cells[i];
if (!cell.count) continue;
const row = Math.floor(i / GRID_X);
const col = i % GRID_X;
const x = mapRect.x + (col + 0.5) * cellW;
const y = mapRect.y + (row + 0.5) * cellH;
const vx = cell.vx / cell.count;
const vz = cell.vz / cell.count;
const magnitude = Math.hypot(vx, vz);
if (magnitude < 0.025) continue;
const length = Math.min(23, 6 + magnitude * 18);
const ux = vx / magnitude;
const uy = vz / magnitude;
const ex = x + ux * length;
const ey = y + uy * length;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(ex, ey);
ctx.stroke();
const wing = 6;
ctx.beginPath();
ctx.moveTo(ex, ey);
ctx.lineTo(ex - ux * wing - uy * wing * 0.5, ey - uy * wing + ux * wing * 0.5);
ctx.lineTo(ex - ux * wing + uy * wing * 0.5, ey - uy * wing - ux * wing * 0.5);
ctx.closePath();
ctx.fill();
}
// Selected pedestrian.
if (selectedAgent && selectedAgent.alive) {
const x = mapRect.x + ((selectedAgent.x + 48) / 96) * mapRect.w;
const y = mapRect.y + (selectedAgent.z / 10) * mapRect.h;
ctx.strokeStyle = "#fff2b8";
ctx.lineWidth = 2;
ctx.strokeRect(x - 5, y - 5, 10, 10);
}
ctx.fillStyle = "#9fb5b5";
ctx.font = "bold 12px monospace";
ctx.textAlign = "left";
ctx.fillText("BUILDING", 20, 16);
ctx.textAlign = "right";
ctx.fillText("WATER / GATES", 580, 241);
ctx.strokeStyle = "rgba(220,235,234,0.25)";
ctx.lineWidth = 1;
ctx.strokeRect(mapRect.x, mapRect.y, mapRect.w, mapRect.h);
}
function updateMetrics() {
let edgePeople = 0;
let peak = 0;
for (const agent of agents) {
if (agent.alive && agent.z >= 0 && agent.z <= 10 && Math.abs(agent.x) <= 48) {
edgePeople++;
}
}
for (const cell of cells) {
peak = Math.max(peak, cell.count / 4);
}
document.getElementById("edgeCount").textContent = edgePeople;
document.getElementById("peakDensity").textContent = peak.toFixed(1);
document.getElementById("crossingCount").textContent = crossingCount;
updateDetailBox();
}
function updateDetailBox() {
const box = document.getElementById("detailBox");
if (selectedAgent && selectedAgent.alive) {
const a = selectedAgent;
const direction = a.direction === "inbound"
? "Inbound: ferry gate → building"
: "Outbound: building → ferry gate";
const gateState = a.granted
? "gate passage granted"
: a.waiting
? "waiting for gate"
: a.stage === "toPier"
? "past gate, moving to pier"
: "approaching gate";
box.innerHTML = `
<strong>Walker ${a.id}</strong><br>
${direction}<br>
Speed: <strong>${Math.hypot(a.vx, a.vz).toFixed(2)} m/s</strong><br>
Local density: <strong>${a.localDensity.toFixed(2)} people/m²</strong><br>
Gate ${a.gateIndex + 1}: ${gateState}<br>
Position: ${a.x.toFixed(1)}, ${a.z.toFixed(1)} m
`;
} else if (selectedCell !== null) {
const cell = cells[selectedCell];
const density = cell.count / 4;
const vx = cell.count ? cell.vx / cell.count : 0;
const vz = cell.count ? cell.vz / cell.count : 0;
const center = cellCenter(selectedCell);
box.innerHTML = `
<strong>Density cell ${selectedCell}</strong><br>
Center: ${center.x.toFixed(0)}, ${center.z.toFixed(0)} m<br>
Occupancy: <strong>${cell.count} people / 4 m²</strong><br>
Density: <strong>${density.toFixed(2)} people/m²</strong><br>
Inbound / outbound: ${cell.inbound} / ${cell.outbound}<br>
Mean flow: ${vx.toFixed(2)}, ${vz.toFixed(2)} m/s
`;
} else {
box.innerHTML = `
<strong>No walker selected.</strong><br>
Click a voxel pedestrian to inspect direction, speed, local density,
and gate state. Click the map to focus a density cell.
`;
}
}
// -------------------------------------------------------------------------
// Rendering pedestrians
// -------------------------------------------------------------------------
const renderDummy = new THREE.Object3D();
const renderColor = new THREE.Color();
function renderAgents() {
for (let slot = 0; slot < MAX_AGENTS; slot++) {
const agent = agentSlots[slot];
if (!agent || !agent.alive) {
renderDummy.position.set(0, -20, 0);
renderDummy.rotation.set(0, 0, 0);
renderDummy.scale.setScalar(0.001);
renderDummy.updateMatrix();
bodyMesh.setMatrixAt(slot, renderDummy.matrix);
headMesh.setMatrixAt(slot, renderDummy.matrix);
leftLegMesh.setMatrixAt(slot, renderDummy.matrix);
rightLegMesh.setMatrixAt(slot, renderDummy.matrix);
badgeMesh.setMatrixAt(slot, renderDummy.matrix);
continue;
}
const speed = Math.hypot(agent.vx, agent.vz);
const bob = speed > 0.04 ? Math.abs(Math.sin(agent.walkPhase)) * 0.055 : 0;
const stride = speed > 0.04 ? Math.sin(agent.walkPhase) * 0.15 : 0;
renderDummy.rotation.set(0, 0, 0);
renderDummy.scale.set(1, 1, 1);
renderDummy.position.set(agent.x, 1.03 + bob, agent.z);
renderDummy.updateMatrix();
bodyMesh.setMatrixAt(slot, renderDummy.matrix);
bodyMesh.setColorAt(slot, agentBodyColors[agent.direction]);
renderDummy.position.set(agent.x, 1.65 + bob, agent.z);
renderDummy.updateMatrix();
headMesh.setMatrixAt(slot, renderDummy.matrix);
headMesh.setColorAt(slot, agent.skin);
renderDummy.position.set(agent.x - 0.17, 0.37, agent.z + stride);
renderDummy.updateMatrix();
leftLegMesh.setMatrixAt(slot, renderDummy.matrix);
renderDummy.position.set(agent.x + 0.17, 0.37, agent.z - stride);
renderDummy.updateMatrix();
rightLegMesh.setMatrixAt(slot, renderDummy.matrix);
const badgeIndex = cellIndexFor(agent.x, agent.z);
if (badgeIndex >= 0) {
renderDummy.position.set(agent.x, 1.17 + bob, agent.z + 0.255);
renderDummy.updateMatrix();
badgeMesh.setMatrixAt(slot, renderDummy.matrix);
densityColor(agent.localDensity, renderColor);
badgeMesh.setColorAt(slot, renderColor);
} else {
renderDummy.position.set(0, -20, 0);
renderDummy.scale.setScalar(0.001);
renderDummy.updateMatrix();
badgeMesh.setMatrixAt(slot, renderDummy.matrix);
renderDummy.scale.set(1, 1, 1);
}
}
bodyMesh.instanceMatrix.needsUpdate = true;
bodyMesh.instanceColor.needsUpdate = true;
headMesh.instanceMatrix.needsUpdate = true;
headMesh.instanceColor.needsUpdate = true;
leftLegMesh.instanceMatrix.needsUpdate = true;
rightLegMesh.instanceMatrix.needsUpdate = true;
badgeMesh.instanceMatrix.needsUpdate = true;
badgeMesh.instanceColor.needsUpdate = true;
if (selectedAgent && selectedAgent.alive) {
selectionMarker.visible = true;
selectionMarker.position.set(selectedAgent.x, 0, selectedAgent.z);
const pulse = 1 + Math.sin(performance.now() * 0.006) * 0.08;
selectionMarker.scale.set(pulse, 1, pulse);
} else {
selectionMarker.visible = false;
}
}
// -------------------------------------------------------------------------
// Picking and map interaction
// -------------------------------------------------------------------------
function selectUnderPointer(event) {
pointer.x = (event.clientX / window.innerWidth) * 2 - 1;
pointer.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects([bodyMesh, headMesh], false);
if (hits.length) {
const instanceId = hits[0].instanceId;
const agent = agentSlots[instanceId];
if (agent && agent.alive) {
selectedAgent = agent;
selectedCell = cellIndexFor(agent.x, agent.z);
updateDetailBox();
drawInspectorMap();
return;
}
}
selectedAgent = null;
updateDetailBox();
drawInspectorMap();
}
mapCanvas.addEventListener("click", event => {
const rect = mapCanvas.getBoundingClientRect();
const x = (event.clientX - rect.left) / rect.width * mapCanvas.width;
const y = (event.clientY - rect.top) / rect.height * mapCanvas.height;
if (
x < mapRect.x || x > mapRect.x + mapRect.w ||
y < mapRect.y || y > mapRect.y + mapRect.h
) return;
const col = Math.floor((x - mapRect.x) / (mapRect.w / GRID_X));
const row = Math.floor((y - mapRect.y) / (mapRect.h / GRID_Z));
if (col < 0 || col >= GRID_X || row < 0 || row >= GRID_Z) return;
selectedCell = row * GRID_X + col;
selectedAgent = null;
const center = cellCenter(selectedCell);
focusArea(
new THREE.Vector3(center.x, 0.5, center.z),
30,
0.78,
0.88
);
updateDetailBox();
drawInspectorMap();
});
// -------------------------------------------------------------------------
// Controls and reset
// -------------------------------------------------------------------------
const spacingInput = document.getElementById("spacing");
const groupInput = document.getElementById("groupSize");
const outboundInput = document.getElementById("outbound");
const speedInput = document.getElementById("speed");
const spacingValue = document.getElementById("spacingValue");
const groupValue = document.getElementById("groupValue");
const outboundValue = document.getElementById("outboundValue");
const speedValue = document.getElementById("speedValue");
spacingInput.addEventListener("input", () => {
arrivalSpacing = Number(spacingInput.value);
spacingValue.textContent = `${arrivalSpacing.toFixed(1)} s`;
});
groupInput.addEventListener("input", () => {
groupSize = Number(groupInput.value);
groupValue.textContent = `${groupSize} ${groupSize === 1 ? "person" : "people"}`;
});
outboundInput.addEventListener("input", () => {
outboundRatio = Number(outboundInput.value);
outboundValue.textContent = outboundRatio.toFixed(2);
});
speedInput.addEventListener("input", () => {
preferredSpeed = Number(speedInput.value);
speedValue.textContent = `${preferredSpeed.toFixed(2)} m/s`;
});
document.getElementById("showDensity").addEventListener("change", event => {
densityMesh.visible = event.target.checked;
});
document.getElementById("showFlow").addEventListener("change", event => {
flowMesh.visible = event.target.checked;
});
function resetSimulation() {
agents = [];
agentSlots.fill(null);
simTime = 0;
arrivalTimer = 0;
outboundCredit = 0;
crossingCount = 0;
crossingTimes = [];
selectedAgent = null;
selectedCell = null;
for (const gate of gates) {
gate.occupant = null;
gate.cooldown = 0;
}
// Pre-roll 18 simulated seconds so the terminal begins with visible flow.
for (let i = 0; i < 540; i++) {
updateSimulation(1 / 30);
}
updateDensityGrid();
}
document.getElementById("reset").addEventListener("click", resetSimulation);
document.getElementById("pause").addEventListener("click", () => {
paused = !paused;
document.getElementById("pause").textContent = paused ? "Resume" : "Pause";
document.getElementById("pause").classList.toggle("primary", paused);
});
document.getElementById("overview").addEventListener("click", () => {
focusArea(
new THREE.Vector3(0, 4, -7),
140,
0.78,
0.91
);
});
document.getElementById("edge").addEventListener("click", () => {
focusArea(
new THREE.Vector3(0, 0.7, 4.5),
58,
0.82,
0.85
);
});
window.addEventListener("keydown", event => {
if (event.target instanceof HTMLInputElement) return;
if (event.code === "Space") {
event.preventDefault();
document.getElementById("pause").click();
} else if (event.key.toLowerCase() === "r") {
resetSimulation();
} else if (event.key.toLowerCase() === "o") {
document.getElementById("overview").click();
} else if (event.key.toLowerCase() === "e") {
document.getElementById("edge").click();
}
});
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
let previousTime = performance.now();
let fixedAccumulator = 0;
let visualTime = 0;
let overlayTimer = 0;
const fixedStep = 1 / 60;
function animate(now) {
const realDelta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
visualTime += realDelta;
if (!paused) {
fixedAccumulator += realDelta;
let steps = 0;
while (fixedAccumulator >= fixedStep && steps < 5) {
updateSimulation(fixedStep);
fixedAccumulator -= fixedStep;
steps++;
}
}
// Streetcar movement.
streetcar.position.x = ((visualTime * 4.2 + 95) % 190) - 95;
// Ferry bobbing.
ferries.forEach((ferry, index) => {
ferry.position.y = Math.sin(visualTime * 0.75 + index * 1.8) * 0.10;
ferry.rotation.z = Math.sin(visualTime * 0.5 + index) * 0.004;
});
// Water strips.
waveData.forEach((wave, index) => {
waveDummy.position.set(
wave.x,
-0.115 + Math.sin(visualTime * 0.8 + wave.phase) * 0.025,
wave.z
);
waveDummy.rotation.set(0, 0, 0);
waveDummy.scale.set(wave.scale, 1, wave.scale);
waveDummy.updateMatrix();
waveMesh.setMatrixAt(index, waveDummy.matrix);
});
waveMesh.instanceMatrix.needsUpdate = true;
overlayTimer += realDelta;
if (overlayTimer > 0.20) {
overlayTimer = 0;
updateDensityGrid();
}
renderAgents();
updateCamera();
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.75));
});
// Initial state.
updateCamera();
resetSimulation();
renderer.setAnimationLoop(animate);
loading.remove();
</script>
</body>
</html>
```