Prompt specification
Build or customize the Three.js 3D scene "Bridge repair shifts an urban delivery route" 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: Bridge repair shifts an urban delivery route
Category: Art & Culture · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/bridge-repair-shifts-an-urban-delivery-route-x2392
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts urban waterways in Song-dynasty China. Let users close one bridge in a fictional canal neighborhood. Reroute walkers and goods through available crossings, keeping the geographic and period framing separate from invented events. Low-poly.
Working Three.js Starter (bridge-repair-shifts-an-urban-delivery-route-x2392):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#d6d0bd">
<title>The Working Waterway — Fictional Song Canal Ward</title>
<style>
:root {
--ink: #282c28;
--muted: #64675f;
--paper: rgba(246, 240, 221, 0.91);
--paper-strong: #f3ecd9;
--line: rgba(61, 62, 53, 0.17);
--cinnabar: #a84632;
--jade: #527568;
--gold: #ba7a32;
--shadow: 0 16px 45px rgba(49, 42, 28, 0.14);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #d6d0bd;
color: var(--ink);
font-family: Inter, "Noto Sans", "PingFang SC", "Microsoft YaHei", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#scene,
#scene canvas,
#labels {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
}
#scene canvas {
display: block;
outline: none;
cursor: grab;
}
#scene canvas:active {
cursor: grabbing;
}
#labels {
pointer-events: none;
overflow: hidden;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 50% 42%, transparent 52%, rgba(55, 47, 31, 0.11) 100%),
linear-gradient(180deg, rgba(241, 235, 216, 0.14), transparent 30%);
}
.panel {
position: fixed;
z-index: 5;
border: 1px solid rgba(68, 66, 53, 0.16);
border-radius: 15px;
background: var(--paper);
box-shadow: var(--shadow);
backdrop-filter: blur(13px) saturate(0.9);
-webkit-backdrop-filter: blur(13px) saturate(0.9);
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
color: var(--cinnabar);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
.eyebrow::before {
width: 17px;
height: 2px;
content: "";
background: currentColor;
}
.brand {
top: 20px;
left: 20px;
width: 355px;
padding: 19px 20px 17px;
}
.brand-row {
display: flex;
align-items: center;
gap: 13px;
}
.seal {
display: grid;
flex: 0 0 48px;
height: 48px;
place-items: center;
border-radius: 8px;
background: var(--cinnabar);
color: #f7edd6;
font-family: "Songti SC", SimSun, serif;
font-size: 27px;
line-height: 1;
box-shadow: inset 0 0 0 2px rgba(255, 245, 220, 0.25);
}
h1 {
margin: 3px 0 2px;
font-family: Georgia, "Songti SC", SimSun, serif;
font-size: 25px;
font-weight: 500;
letter-spacing: -0.025em;
}
.subtitle {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.brand-note {
display: flex;
align-items: center;
gap: 8px;
margin-top: 13px;
padding-top: 11px;
border-top: 1px solid var(--line);
color: #77776c;
font-size: 10px;
}
.brand-note strong {
color: var(--ink);
font-weight: 700;
}
.controls {
top: 188px;
left: 20px;
width: 310px;
padding: 17px;
max-height: calc(100vh - 220px);
overflow: auto;
scrollbar-width: thin;
}
.section-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 11px;
}
.section-head h2 {
margin: 0;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.section-head span {
color: var(--muted);
font-size: 10px;
}
.bridge-list {
display: grid;
gap: 7px;
}
.bridge-card {
display: grid;
grid-template-columns: 10px 1fr auto;
align-items: center;
gap: 10px;
width: 100%;
padding: 10px 11px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.34);
text-align: left;
cursor: pointer;
transition: border-color 150ms, background 150ms, transform 150ms;
}
.bridge-card:hover {
transform: translateX(2px);
border-color: rgba(168, 70, 50, 0.42);
}
.bridge-card.selected {
border-color: var(--cinnabar);
background: rgba(168, 70, 50, 0.075);
box-shadow: inset 3px 0 0 var(--cinnabar);
}
.bridge-card.closed {
background: rgba(77, 67, 55, 0.08);
}
.bridge-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--jade);
box-shadow: 0 0 0 3px rgba(82, 117, 104, 0.12);
}
.bridge-card.closed .bridge-dot {
background: var(--cinnabar);
box-shadow: 0 0 0 3px rgba(168, 70, 50, 0.13);
}
.bridge-name {
display: block;
font-size: 12px;
font-weight: 750;
}
.bridge-place {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.bridge-state {
color: var(--jade);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
}
.closed .bridge-state {
color: var(--cinnabar);
}
.primary,
.secondary {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 7px;
min-height: 37px;
border-radius: 9px;
cursor: pointer;
transition: transform 120ms, background 120ms, opacity 120ms;
}
.primary:hover,
.secondary:hover {
transform: translateY(-1px);
}
.primary:active,
.secondary:active {
transform: translateY(0);
}
.primary {
width: 100%;
margin-top: 11px;
border: 1px solid #913b2c;
background: var(--cinnabar);
color: #fff7e7;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.025em;
box-shadow: 0 5px 14px rgba(132, 50, 35, 0.17);
}
.primary.reopen {
border-color: var(--jade);
background: var(--jade);
}
.primary:disabled {
opacity: 0.45;
cursor: default;
transform: none;
}
.divider {
height: 1px;
margin: 15px 0;
background: var(--line);
}
.slider-row {
margin: 12px 0;
}
.slider-label {
display: flex;
justify-content: space-between;
margin-bottom: 6px;
font-size: 10px;
font-weight: 700;
}
.slider-label span:last-child {
color: var(--muted);
font-weight: 600;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
border-radius: 4px;
accent-color: var(--cinnabar);
cursor: pointer;
}
.check-row {
display: flex;
align-items: center;
justify-content: space-between;
margin: 10px 0;
font-size: 11px;
}
.check-row label {
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
}
input[type="checkbox"] {
accent-color: var(--jade);
}
.action-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-top: 12px;
}
.secondary {
min-height: 32px;
padding: 6px 8px;
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.4);
font-size: 9px;
font-weight: 750;
}
.stats {
top: 20px;
right: 20px;
width: 272px;
padding: 17px;
}
.live {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--jade);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.live::before {
width: 7px;
height: 7px;
border-radius: 50%;
content: "";
background: #5f9b7c;
box-shadow: 0 0 0 4px rgba(95, 155, 124, 0.13);
animation: pulse 2s infinite;
}
@keyframes pulse {
50% { box-shadow: 0 0 0 7px rgba(95, 155, 124, 0.03); }
}
.big-stat {
display: flex;
align-items: baseline;
gap: 8px;
margin: 8px 0 15px;
}
.big-stat strong {
font-family: Georgia, serif;
font-size: 39px;
font-weight: 500;
line-height: 1;
}
.big-stat span {
color: var(--muted);
font-size: 11px;
}
.metric-list {
display: grid;
gap: 9px;
}
.metric {
display: flex;
align-items: center;
justify-content: space-between;
padding-bottom: 8px;
border-bottom: 1px solid var(--line);
font-size: 10px;
}
.metric span {
color: var(--muted);
}
.metric strong {
font-size: 12px;
}
.route-note {
margin-top: 13px;
padding: 11px 12px;
border-left: 3px solid var(--gold);
border-radius: 0 8px 8px 0;
background: rgba(186, 122, 50, 0.08);
color: #5f594d;
font-size: 10px;
line-height: 1.55;
}
.route-note.closed {
border-left-color: var(--cinnabar);
background: rgba(168, 70, 50, 0.07);
}
.framing {
right: 20px;
bottom: 20px;
width: 548px;
padding: 0 17px 15px;
overflow: hidden;
}
.framing summary {
display: flex;
align-items: center;
justify-content: space-between;
padding: 14px 0 11px;
cursor: pointer;
font-size: 11px;
font-weight: 800;
list-style: none;
}
.framing summary::-webkit-details-marker {
display: none;
}
.framing summary::after {
content: "−";
color: var(--muted);
font-size: 15px;
}
.framing:not([open]) summary::after {
content: "+";
}
.framing-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 11px;
}
.frame-box {
padding: 12px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.3);
}
.frame-box.fiction {
background: rgba(168, 70, 50, 0.045);
}
.frame-tag {
display: inline-block;
margin-bottom: 7px;
color: var(--jade);
font-size: 8px;
font-weight: 900;
letter-spacing: 0.15em;
}
.fiction .frame-tag {
color: var(--cinnabar);
}
.frame-box h3 {
margin: 0 0 6px;
font-family: Georgia, "Songti SC", SimSun, serif;
font-size: 14px;
font-weight: 600;
}
.frame-box p {
margin: 0;
color: #66665c;
font-size: 9px;
line-height: 1.55;
}
.hint {
position: fixed;
bottom: 22px;
left: 20px;
z-index: 4;
display: flex;
align-items: center;
gap: 12px;
padding: 9px 12px;
border: 1px solid rgba(68, 66, 53, 0.13);
border-radius: 10px;
background: rgba(246, 240, 221, 0.78);
color: #6f7066;
font-size: 9px;
backdrop-filter: blur(8px);
}
.hint b {
color: var(--ink);
}
.key {
padding: 2px 5px;
border: 1px solid rgba(64, 64, 55, 0.2);
border-bottom-width: 2px;
border-radius: 4px;
background: rgba(255, 255, 255, 0.55);
color: #4c514b;
font-size: 8px;
font-weight: 800;
}
.world-label {
position: absolute;
top: 0;
left: 0;
padding: 4px 7px;
border: 1px solid rgba(56, 56, 48, 0.2);
border-radius: 5px;
background: rgba(247, 241, 224, 0.86);
box-shadow: 0 4px 12px rgba(44, 37, 26, 0.11);
color: #494c43;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.045em;
white-space: nowrap;
transform: translate(-50%, -50%);
transition: border-color 150ms, color 150ms;
}
.world-label.closed {
border-color: rgba(168, 70, 50, 0.65);
color: var(--cinnabar);
}
.loading {
position: fixed;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
background: #d6d0bd;
color: #5e5b50;
font-family: Georgia, serif;
font-size: 15px;
transition: opacity 400ms;
}
.loading.hidden {
opacity: 0;
pointer-events: none;
}
@media (max-width: 1050px) {
.framing {
right: 20px;
left: 20px;
bottom: 20px;
width: auto;
}
.hint {
display: none;
}
}
@media (max-width: 760px) {
.brand {
top: 10px;
right: 10px;
left: 10px;
width: auto;
padding: 12px 14px;
}
.seal {
flex-basis: 39px;
height: 39px;
font-size: 23px;
}
h1 {
font-size: 20px;
}
.subtitle,
.brand-note {
display: none;
}
.controls {
top: 97px;
left: 10px;
width: 270px;
max-height: 39vh;
padding: 13px;
}
.stats {
top: 97px;
right: 10px;
width: 180px;
padding: 13px;
}
.big-stat strong {
font-size: 30px;
}
.metric-list {
display: none;
}
.framing {
right: 10px;
bottom: 10px;
left: 10px;
padding: 0 13px 12px;
}
.framing-grid {
grid-template-columns: 1fr;
max-height: 33vh;
overflow: auto;
}
}
@media (max-width: 480px) {
.stats {
display: none;
}
.controls {
width: calc(100% - 20px);
}
.bridge-list {
grid-template-columns: 1fr;
}
}
</style>
</head>
<body>
<div id="scene" aria-label="Interactive low-poly Song-dynasty canal neighborhood"></div>
<div id="labels" aria-hidden="true"></div>
<div class="vignette"></div>
<header class="panel brand">
<div class="brand-row">
<div class="seal" aria-hidden="true">渠</div>
<div>
<div class="eyebrow">Fictional canal neighborhood</div>
<h1>The Working Waterway</h1>
<p class="subtitle">An interpretive Song-dynasty street-and-water scene, set around 1100.</p>
</div>
</div>
<div class="brand-note">
<strong>Jiangnan-inspired</strong>
<span>•</span>
<span>Low-poly interpretation, not a surveyed reconstruction</span>
</div>
</header>
<aside class="panel controls" aria-label="Scene controls">
<div class="section-head">
<h2>Crossing network</h2>
<span>Select, then close</span>
</div>
<div id="bridgeList" class="bridge-list"></div>
<button id="closeBridge" class="primary" type="button">Close Bell Market Bridge</button>
<div class="divider"></div>
<div class="section-head">
<h2>Street activity</h2>
<span>Live simulation</span>
</div>
<div class="slider-row">
<label class="slider-label" for="walkers">
<span>Walkers</span>
<span id="walkersValue">32</span>
</label>
<input id="walkers" type="range" min="0" max="60" value="32">
</div>
<div class="slider-row">
<label class="slider-label" for="carts">
<span>Goods carts</span>
<span id="cartsValue">9</span>
</label>
<input id="carts" type="range" min="0" max="20" value="9">
</div>
<div class="check-row">
<label for="showRoutes">
<input id="showRoutes" type="checkbox" checked>
Show representative routes
</label>
</div>
<div class="action-grid">
<button id="pause" class="secondary" type="button">Pause movement</button>
<button id="resetFlow" class="secondary" type="button">Reset traffic</button>
<button id="resetView" class="secondary" type="button">Reset camera</button>
<button id="openAll" class="secondary" type="button">Open all bridges</button>
</div>
</aside>
<aside class="panel stats" aria-label="Live network statistics">
<div class="live">Live routing</div>
<div class="big-stat">
<strong id="openCount">3</strong>
<span>of 3 crossings open</span>
</div>
<div class="metric-list">
<div class="metric">
<span>People moving</span>
<strong id="walkerCount">32</strong>
</div>
<div class="metric">
<span>Goods carts moving</span>
<strong id="cartCount">9</strong>
</div>
<div class="metric">
<span>Selected crossing users</span>
<strong id="selectedTraffic">0</strong>
</div>
<div class="metric">
<span>Routes recalculated</span>
<strong id="rerouteCount">0</strong>
</div>
</div>
<div id="routeNote" class="route-note" aria-live="polite">
All three crossings are open. Select a bridge and close it to test how people and goods find another way.
</div>
</aside>
<details class="panel framing" open>
<summary>Framing: historical context and fictional scenario are separate</summary>
<div class="framing-grid">
<section class="frame-box">
<span class="frame-tag">HISTORICAL / GEOGRAPHIC FRAME</span>
<h3>Song China, 960–1279</h3>
<p>
This scene uses broad visual and social references associated with Jiangnan-style
canal districts: water transport, quays, market lanes, timber-fronted buildings,
arched crossings, and street–river exchange. It is an interpretive vignette,
not a reconstruction of a specific surveyed neighborhood.
</p>
</section>
<section class="frame-box fiction">
<span class="frame-tag">FICTIONAL EVENT LAYER</span>
<h3>The bridge-closure test</h3>
<p>
“Willow Bend,” “Bell Market,” “Reed Gate,” their residents, traffic volumes,
cargo, and the closure order are invented for this interactive. The routing
simulation demonstrates a modern network-model idea inside the historical visual
frame; it does not claim that this particular event occurred.
</p>
</section>
</div>
</details>
<div class="hint">
<span><b>Drag</b> to orbit</span>
<span class="key">Shift + drag</span><span>pan</span>
<span class="key">Wheel</span><span>zoom</span>
<span><b>Click a bridge</b> to select it</span>
</div>
<div id="loading" class="loading">Preparing the canal ward…</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 $ = (selector) => document.querySelector(selector);
const sceneHost = $("#scene");
const labelHost = $("#labels");
const loading = $("#loading");
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute("aria-label", "Three-dimensional canal neighborhood");
sceneHost.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xd7d1be);
scene.fog = new THREE.Fog(0xd7d1be, 45, 92);
const viewHeight = 23;
const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 150);
const cameraTarget = new THREE.Vector3(0, 0.4, 0);
let cameraTheta = 0.69;
let cameraPhi = 0.82;
let cameraZoom = 1;
function updateCamera() {
const aspect = window.innerWidth / window.innerHeight;
const vertical = aspect < 0.75 ? 31 : viewHeight;
camera.left = -vertical * aspect;
camera.right = vertical * aspect;
camera.top = vertical;
camera.bottom = -vertical;
camera.zoom = cameraZoom;
camera.updateProjectionMatrix();
const radius = 62;
camera.position.set(
cameraTarget.x + radius * Math.sin(cameraPhi) * Math.sin(cameraTheta),
cameraTarget.y + radius * Math.cos(cameraPhi),
cameraTarget.z + radius * Math.sin(cameraPhi) * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraTheta = 0.69;
cameraPhi = 0.82;
cameraZoom = 1;
cameraTarget.set(0, 0.4, 0);
updateCamera();
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xf8f1d7, 0x657468, 2.05);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff0cd, 3.0);
sun.position.set(-18, 31, 17);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -29;
sun.shadow.camera.right = 29;
sun.shadow.camera.top = 31;
sun.shadow.camera.bottom = -31;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 75;
sun.shadow.bias = -0.00045;
scene.add(sun);
// -------------------------------------------------------------------------
// Materials and geometry helpers
// -------------------------------------------------------------------------
function material(color, extra = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.88,
metalness: 0,
flatShading: true,
...extra
});
}
const materials = {
earth: material(0xc7b58d),
bank: material(0xd8c7a0),
road: material(0xc5b188),
paving: material(0xb8a581),
water: material(0x668f8d, {
roughness: 0.34,
metalness: 0.05,
transparent: true,
opacity: 0.94
}),
waterDark: material(0x527a78),
wall: material(0x9d927a),
wallAlt: material(0xaaa086),
timber: material(0x59483a),
timberLight: material(0x7a5f45),
roof: material(0x414b4b),
roofWarm: material(0x6d5143),
plaster: material(0xd9c9a6),
plasterWhite: material(0xe4d8b9),
door: material(0x4a3a30),
window: material(0x536565),
red: material(0xa84532),
redDark: material(0x78382d),
leaf: material(0x617b55),
leafLight: material(0x7e9161),
trunk: material(0x685140),
clothBlue: material(0x55717a),
clothOchre: material(0xb38745),
clothCream: material(0xd9c799),
clothRed: material(0xa45a43),
cargo: material(0x997044),
black: material(0x333530)
};
function box(parent, width, height, depth, x, y, z, mat, cast = true) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(width, height, depth), mat);
mesh.position.set(x, y, z);
mesh.castShadow = cast;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function cylinderBetween(parent, a, b, radius, mat, radialSegments = 6) {
const direction = new THREE.Vector3().subVectors(b, a);
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius, direction.length(), radialSegments),
mat
);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.clone().normalize()
);
mesh.castShadow = true;
parent.add(mesh);
return mesh;
}
function roofGeometry(width, depth, baseY, rise) {
const w = width / 2;
const d = depth / 2;
const positions = new Float32Array([
-w, baseY, -d, w, baseY, -d, 0, baseY + rise, -d,
-w, baseY, d, w, baseY, d, 0, baseY + rise, d
]);
const indices = [
0, 2, 1,
3, 4, 5,
0, 3, 5, 0, 5, 2,
1, 2, 5, 1, 5, 4,
0, 1, 4, 0, 4, 3
];
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
geometry.setIndex(indices);
geometry.computeVertexNormals();
return geometry;
}
// -------------------------------------------------------------------------
// Ground, canal, embankments, buildings, trees and market furniture
// -------------------------------------------------------------------------
box(scene, 41, 0.65, 55, 0, -0.45, 0, materials.earth);
box(scene, 8.3, 0.18, 51, 0, 0.12, 0, materials.waterDark);
const water = new THREE.Mesh(new THREE.PlaneGeometry(8, 51, 5, 30), materials.water);
water.rotation.x = -Math.PI / 2;
water.position.y = 0.49;
water.receiveShadow = true;
scene.add(water);
for (const side of [-1, 1]) {
box(scene, 15.7, 0.7, 51, side * 12.25, 0.18, 0, materials.bank);
box(scene, 3.25, 0.055, 49, side * 6.45, 0.56, 0, materials.road);
for (let z = -24.5; z <= 24.5; z += 2) {
const mat = Math.round(z * 10) % 4 === 0 ? materials.wallAlt : materials.wall;
box(scene, 0.52, 0.82, 1.86, side * 4.22, 0.22, z, mat);
}
for (let z = -23; z < 25; z += 4) {
box(scene, 0.08, 0.015, 3.1, side * 5.05, 0.595, z, materials.paving, false);
}
}
function createBuilding(x, z, width, depth, height, roofMat, wallMat) {
const group = new THREE.Group();
group.position.set(x, 0.54, z);
scene.add(group);
box(group, width, height, depth, 0, height / 2, 0, wallMat);
const roof = new THREE.Mesh(
roofGeometry(width + 0.55, depth + 0.6, height + 0.04, 1.15),
roofMat
);
roof.castShadow = true;
roof.receiveShadow = true;
group.add(roof);
box(group, width + 0.62, 0.12, 0.14, 0, height + 0.05, -depth / 2 - 0.28, roofMat);
box(group, width + 0.62, 0.12, 0.14, 0, height + 0.05, depth / 2 + 0.28, roofMat);
const inward = x < 0 ? 1 : -1;
const faceX = inward * (width / 2 + 0.025);
box(group, 0.055, 1.35, 1.12, faceX, 0.68, 0, materials.door);
box(group, 0.065, 0.11, 1.52, faceX + inward * 0.015, 1.45, 0, materials.timber);
for (const localZ of [-depth * 0.29, depth * 0.29]) {
box(group, 0.055, 0.72, 0.74, faceX, height * 0.58, localZ, materials.window);
box(group, 0.07, 0.08, 0.88, faceX, height * 0.58, localZ, materials.timber);
}
box(group, 0.08, 0.09, depth * 0.75, faceX + inward * 0.04, height * 0.82, 0, materials.timber);
return group;
}
const buildings = [
[-11.2, -19, 5.4, 5.6, 3.2, materials.roof, materials.plaster],
[-11.4, -9.5, 5.8, 6.5, 3.7, materials.roofWarm, materials.plasterWhite],
[-11.3, 5.2, 5.5, 6.1, 3.35, materials.roof, materials.plaster],
[-11.6, 18.2, 5.4, 6.3, 3.55, materials.roofWarm, materials.plasterWhite],
[11.3, -19, 5.6, 5.8, 3.3, materials.roofWarm, materials.plaster],
[11.4, -8.5, 5.5, 6.7, 3.85, materials.roof, materials.plasterWhite],
[11.1, 5.6, 5.8, 6.4, 3.45, materials.roof, materials.plaster],
[11.5, 18.4, 5.6, 6.2, 3.55, materials.roofWarm, materials.plasterWhite]
];
for (const args of buildings) createBuilding(...args);
function createTree(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0.55, z);
group.scale.setScalar(scale);
scene.add(group);
const trunk = new THREE.Mesh(new THREE.CylinderGeometry(0.13, 0.2, 2.5, 6), materials.trunk);
trunk.position.y = 1.25;
trunk.castShadow = true;
group.add(trunk);
const crownA = new THREE.Mesh(new THREE.IcosahedronGeometry(1.25, 0), materials.leaf);
crownA.position.set(-0.35, 2.75, 0.05);
crownA.scale.set(1.1, 0.85, 1);
crownA.castShadow = true;
group.add(crownA);
const crownB = new THREE.Mesh(new THREE.IcosahedronGeometry(1.05, 0), materials.leafLight);
crownB.position.set(0.5, 3.05, -0.1);
crownB.scale.set(1.05, 0.85, 0.95);
crownB.castShadow = true;
group.add(crownB);
const crownC = new THREE.Mesh(new THREE.IcosahedronGeometry(0.82, 0), materials.leaf);
crownC.position.set(0.1, 3.65, 0.05);
crownC.castShadow = true;
group.add(crownC);
}
for (const [x, z, s] of [
[-8.3, -23, 1.1], [-8.1, -3, 0.9], [-8.4, 11.8, 1.0], [-8.5, 23, 1.15],
[8.2, -22.5, 1.0], [8.4, -3.6, 1.12], [8.0, 12, 0.95], [8.4, 23.2, 1.05]
]) createTree(x, z, s);
function createStall(x, z, clothMat, rotation = 0) {
const group = new THREE.Group();
group.position.set(x, 0.56, z);
group.rotation.y = rotation;
scene.add(group);
for (const px of [-0.95, 0.95]) {
for (const pz of [-0.72, 0.72]) {
box(group, 0.1, 1.55, 0.1, px, 0.78, pz, materials.timber);
}
}
const canopy = new THREE.Mesh(roofGeometry(2.45, 1.9, 1.55, 0.48), clothMat);
canopy.castShadow = true;
group.add(canopy);
box(group, 1.85, 0.12, 0.78, 0, 0.78, 0, materials.timberLight);
for (let i = 0; i < 4; i++) {
const px = -0.65 + i * 0.43;
box(group, 0.3, 0.28, 0.38, px, 1.0, 0.03, i % 2 ? materials.cargo : materials.clothOchre);
}
}
createStall(-7.8, 3.1, materials.clothOchre, Math.PI / 2);
createStall(-7.8, 5.1, materials.clothBlue, Math.PI / 2);
createStall(7.9, -4.8, materials.clothRed, -Math.PI / 2);
createStall(7.9, -2.8, materials.clothCream, -Math.PI / 2);
// -------------------------------------------------------------------------
// Bridges
// -------------------------------------------------------------------------
const bridgeDefinitions = [
{
key: "north",
id: "b-north",
name: "Willow Bend Bridge",
place: "Northern canal crossing",
z: -14,
label: "WILLOW BEND"
},
{
key: "middle",
id: "b-middle",
name: "Bell Market Bridge",
place: "Central market crossing",
z: 0,
label: "BELL MARKET"
},
{
key: "south",
id: "b-south",
name: "Reed Gate Bridge",
place: "Southern canal crossing",
z: 14,
label: "REED GATE"
}
];
const bridgeById = new Map();
const pickables = [];
const worldLabels = [];
function archY(x) {
const t = THREE.MathUtils.clamp((x + 6.5) / 13, 0, 1);
return 0.72 + 1.92 * Math.pow(Math.sin(Math.PI * t), 0.84);
}
function createBridge(definition) {
const group = new THREE.Group();
group.position.z = definition.z;
scene.add(group);
const deckMat = material(0xa69a80);
const railMat = material(0x6a5947);
const segments = 14;
const segmentLength = 13 / segments;
for (let i = 0; i < segments; i++) {
const x = -6.5 + segmentLength * (i + 0.5);
const y = archY(x);
const nextX = x + segmentLength * 0.45;
const angle = Math.atan2(archY(nextX) - y, segmentLength * 0.9);
const deck = box(
group,
segmentLength * 1.08,
0.28,
2.05,
x,
y - 0.13,
0,
deckMat
);
deck.userData.bridgeKey = definition.key;
pickables.push(deck);
if (i % 2 === 0) {
for (const side of [-1, 1]) {
const post = box(group, 0.12, 0.72, 0.12, x, y + 0.39, side * 1.09, railMat);
post.userData.bridgeKey = definition.key;
pickables.push(post);
}
}
}
for (const side of [-1, 1]) {
for (let i = 0; i < segments - 1; i += 2) {
const x1 = -6.5 + i * segmentLength;
const x2 = -6.5 + (i + 2) * segmentLength;
const rail = cylinderBetween(
group,
new THREE.Vector3(x1, archY(x1) + 0.75, side * 1.09),
new THREE.Vector3(x2, archY(x2) + 0.75, side * 1.09),
0.055,
railMat
);
rail.userData.bridgeKey = definition.key;
pickables.push(rail);
}
}
const barrier = new THREE.Group();
group.add(barrier);
for (const x of [-4.65, 4.65]) {
box(barrier, 0.18, 1.05, 0.18, x, 0.85, -0.95, materials.redDark);
box(barrier, 0.18, 1.05, 0.18, x, 0.85, 0.95, materials.redDark);
box(barrier, 0.2, 0.19, 2.35, x, 1.1, 0, materials.red);
}
barrier.visible = false;
for (const x of [-4.2, 4.2]) {
const pole = new THREE.Mesh(new THREE.CylinderGeometry(0.045, 0.045, 1.7, 6), materials.timber);
pole.position.set(x, 1.3, 1.45);
pole.castShadow = true;
group.add(pole);
const lantern = new THREE.Mesh(new THREE.SphereGeometry(0.22, 8, 6), materials.red);
lantern.scale.y = 1.25;
lantern.position.set(x, 2.05, 1.45);
lantern.castShadow = true;
group.add(lantern);
}
const label = document.createElement("div");
label.className = "world-label";
label.textContent = definition.label;
labelHost.appendChild(label);
worldLabels.push({ element: label, z: definition.z });
const bridge = {
...definition,
group,
deckMat,
railMat,
barrier,
baseColor: deckMat.color.getHex(),
label
};
bridgeById.set(definition.id, bridge);
return bridge;
}
bridgeDefinitions.forEach(createBridge);
// -------------------------------------------------------------------------
// Navigation graph and shortest-path routing
// -------------------------------------------------------------------------
const nodes = new Map();
const edges = [];
const adjacency = new Map();
function addNode(id, x, z) {
nodes.set(id, { id, x, z, y: 0.72 });
adjacency.set(id, []);
}
function addEdge(a, b, id, bridgeId = null) {
const length = Math.hypot(nodes.get(a).x - nodes.get(b).x, nodes.get(a).z - nodes.get(b).z);
const edge = { a, b, id, bridgeId, length };
edges.push(edge);
adjacency.get(a).push({ node: b, edge });
adjacency.get(b).push({ node: a, edge });
return edge;
}
const bankChain = [
{ key: "0", z: -20 },
{ key: "N", z: -14 },
{ key: "1", z: -10 },
{ key: "M", z: 0 },
{ key: "3", z: 10 },
{ key: "S", z: 14 },
{ key: "4", z: 20 }
];
for (const side of ["W", "E"]) {
const x = side === "W" ? -6.5 : 6.5;
for (const point of bankChain) {
addNode(`${side}${point.key}`, x, point.z);
}
for (let i = 0; i < bankChain.length - 1; i++) {
addEdge(`${side}${bankChain[i].key}`, `${side}${bankChain[i + 1].key}`, `bank-${side}-${i}`);
}
}
for (const definition of bridgeDefinitions) {
const bankKey = bankChain.find((point) => point.z === definition.z).key;
addEdge("W" + bankKey, "E" + bankKey, definition.id, definition.id);
}
function edgeBetween(a, b) {
return adjacency.get(a)?.find((item) => item.node === b)?.edge || null;
}
function routeBetween(start, end) {
if (start === end) return { nodes: [start], edges: [] };
const distances = new Map();
const previous = new Map();
const visited = new Set();
for (const id of nodes.keys()) distances.set(id, Infinity);
distances.set(start, 0);
while (visited.size < nodes.size) {
let current = null;
let best = Infinity;
for (const [id, distance] of distances) {
if (!visited.has(id) && distance < best) {
best = distance;
current = id;
}
}
if (current === null) break;
if (current === end) break;
visited.add(current);
for (const { node, edge } of adjacency.get(current)) {
if (visited.has(node)) continue;
if (edge.bridgeId && closedBridgeId === edge.bridgeId) continue;
const candidate = best + edge.length;
if (candidate < distances.get(node)) {
distances.set(node, candidate);
previous.set(node, { node: current, edge });
}
}
}
if (!Number.isFinite(distances.get(end))) return { nodes: [start], edges: [] };
const routeNodes = [end];
const routeEdges = [];
let cursor = end;
while (cursor !== start) {
const step = previous.get(cursor);
if (!step) break;
routeEdges.unshift(step.edge);
routeNodes.unshift(step.node);
cursor = step.node;
}
return { nodes: routeNodes, edges: routeEdges };
}
function edgePoint(edge, t) {
const a = nodes.get(edge.a);
const b = nodes.get(edge.b);
if (edge.bridgeId) {
const x = THREE.MathUtils.lerp(a.x, b.x, t);
return new THREE.Vector3(x, archY(x) + 0.06, THREE.MathUtils.lerp(a.z, b.z, t));
}
return new THREE.Vector3(
THREE.MathUtils.lerp(a.x, b.x, t),
0.72,
THREE.MathUtils.lerp(a.z, b.z, t)
);
}
function actualEdgeLength(edge) {
if (!edge.bridgeId) return edge.length;
let length = 0;
let previous = edgePoint(edge, 0);
for (let i = 1; i <= 16; i++) {
const next = edgePoint(edge, i / 16);
length += next.distanceTo(previous);
previous = next;
}
return length;
}
for (const edge of edges) edge.actualLength = actualEdgeLength(edge);
// -------------------------------------------------------------------------
// Boats, water glints and other ambient movement
// -------------------------------------------------------------------------
const boats = [];
function createBoat(z, withSail = false) {
const group = new THREE.Group();
group.position.set(0, 0.58, z);
scene.add(group);
const hull = new THREE.Mesh(new THREE.CylinderGeometry(0.56, 0.34, 3.2, 6), materials.timber);
hull.rotation.x = Math.PI / 2;
hull.scale.x = 0.92;
hull.castShadow = true;
group.add(hull);
box(group, 0.92, 0.1, 2.55, 0, 0.25, 0, materials.timberLight);
box(group, 0.72, 0.48, 0.75, 0, 0.47, -0.3, materials.cargo);
box(group, 0.52, 0.38, 0.55, 0.18, 0.43, 0.55, materials.clothOchre);
const pole = new THREE.Mesh(new THREE.CylinderGeometry(0.035, 0.035, 3.1, 5), materials.timber);
pole.position.set(-0.12, 1.45, 0.1);
pole.rotation.z = -0.16;
pole.castShadow = true;
group.add(pole);
if (withSail) {
const sail = box(group, 1.35, 1.55, 0.055, 0.25, 1.75, 0.08, materials.clothCream);
sail.rotation.y = 0.12;
}
boats.push({ group, speed: 0.18 + Math.random() * 0.11, offset: Math.random() * 6 });
}
createBoat(-23, true);
createBoat(-6.4, false);
createBoat(7.3, true);
createBoat(22.3, false);
const glints = [];
const glintGeometry = new THREE.PlaneGeometry(0.65, 0.08);
for (let i = 0; i < 38; i++) {
const mesh = new THREE.Mesh(
glintGeometry,
new THREE.MeshBasicMaterial({
color: 0xc8ddd4,
transparent: true,
opacity: 0.18 + Math.random() * 0.16,
depthWrite: false
})
);
mesh.rotation.x = -Math.PI / 2;
mesh.position.set(
-3.6 + Math.random() * 7.2,
0.535,
-24 + Math.random() * 48
);
scene.add(mesh);
glints.push({ mesh, speed: 0.08 + Math.random() * 0.15 });
}
// -------------------------------------------------------------------------
// Walkers and goods carts
// -------------------------------------------------------------------------
const agents = [];
const walkerMaterials = [
material(0x566b70),
material(0x9a7650),
material(0x7c8664),
material(0xc4b18d),
material(0x76565a)
];
function createWalkerMesh() {
const group = new THREE.Group();
const robeMat = walkerMaterials[Math.floor(Math.random() * walkerMaterials.length)];
const robe = new THREE.Mesh(new THREE.CylinderGeometry(0.14, 0.27, 0.75, 6), robeMat);
robe.position.y = 0.48;
robe.castShadow = true;
group.add(robe);
const head = new THREE.Mesh(new THREE.SphereGeometry(0.14, 7, 5), material(0xc49b73));
head.position.y = 0.97;
head.castShadow = true;
group.add(head);
const hat = new THREE.Mesh(new THREE.ConeGeometry(0.23, 0.18, 6), materials.timberLight);
hat.position.y = 1.12;
hat.castShadow = true;
group.add(hat);
const arm = box(group, 0.1, 0.52, 0.1, 0.19, 0.55, 0, robeMat);
arm.rotation.z = -0.16;
return group;
}
function createCartMesh() {
const group = new THREE.Group();
box(group, 0.88, 0.3, 1.3, 0, 0.52, 0, materials.timber);
box(group, 0.76, 0.52, 0.7, 0, 0.92, -0.12, materials.cargo);
box(group, 0.58, 0.42, 0.52, 0, 0.86, 0.48, materials.clothOchre);
for (const x of [-0.5, 0.5]) {
for (const z of [-0.43, 0.43]) {
const wheel = new THREE.Mesh(new THREE.CylinderGeometry(0.23, 0.23, 0.1, 8), materials.black);
wheel.rotation.z = Math.PI / 2;
wheel.position.set(x, 0.27, z);
wheel.castShadow = true;
group.add(wheel);
}
}
for (const x of [-0.32, 0.32]) {
box(group, 0.07, 0.07, 0.95, x, 0.65, 0.95, materials.timberLight);
}
return group;
}
const bankNodeIds = {
W: ["W0", "WN", "W1", "WM", "W3", "WS", "W4"],
E: ["E0", "EN", "E1", "EM", "E3", "ES", "E4"]
};
function randomStartAndDestination() {
const startSide = Math.random() < 0.5 ? "W" : "E";
const endSide = startSide === "W" ? "E" : "W";
const startChoices = bankNodeIds[startSide];
const endChoices = bankNodeIds[endSide];
return {
start: startChoices[Math.floor(Math.random() * startChoices.length)],
end: endChoices[Math.floor(Math.random() * endChoices.length)]
};
}
function createAgent(type) {
const { start, end } = randomStartAndDestination();
const route = routeBetween(start, end);
const mesh = type === "walker" ? createWalkerMesh() : createCartMesh();
scene.add(mesh);
const agent = {
type,
mesh,
routeNodes: route.nodes,
routeEdges: route.edges,
edgeIndex: 0,
progress: 0,
destination: end,
speed: type === "walker"
? 1.65 + Math.random() * 0.9
: 0.82 + Math.random() * 0.48,
wait: 0
};
agents.push(agent);
return agent;
}
function resetAgent(agent) {
const { start, end } = randomStartAndDestination();
const route = routeBetween(start, end);
agent.routeNodes = route.nodes;
agent.routeEdges = route.edges;
agent.edgeIndex = 0;
agent.progress = 0;
agent.destination = end;
agent.wait = 0;
agent.mesh.visible = true;
}
function routeSignature(route) {
return route.edges.map((edge) => edge.id).join("|");
}
function recomputeAgentRoute(agent, countAsReroute) {
if (!agent.routeEdges.length) return false;
const oldSignature = routeSignature({
nodes: agent.routeNodes,
edges: agent.routeEdges
});
if (agent.edgeIndex >= agent.routeEdges.length) {
resetAgent(agent);
return false;
}
const currentEdge = agent.routeEdges[agent.edgeIndex];
const currentNode = agent.routeNodes[agent.edgeIndex];
const nextNode = agent.routeNodes[agent.edgeIndex + 1];
if (currentEdge.bridgeId && closedBridgeId === currentEdge.bridgeId) {
const endpoint = agent.progress < 0.5 ? currentNode : nextNode;
const newRoute = routeBetween(endpoint, agent.destination);
agent.routeNodes = [endpoint, ...newRoute.nodes.slice(1)];
agent.routeEdges = newRoute.edges;
agent.edgeIndex = 0;
agent.progress = 0;
agent.mesh.position.copy(edgePoint(newRoute.edges[0], 0));
} else {
const newRoute = routeBetween(nextNode, agent.destination);
agent.routeNodes = [currentNode, nextNode, ...newRoute.nodes.slice(1)];
agent.routeEdges = [currentEdge, ...newRoute.edges];
agent.edgeIndex = 0;
}
const newSignature = routeSignature({
nodes: agent.routeNodes,
edges: agent.routeEdges
});
const changed = oldSignature !== newSignature;
if (changed && countAsReroute) reroutedCount++;
return changed;
}
function updateAgent(agent, dt) {
if (agent.wait > 0) {
agent.wait -= dt;
if (agent.wait <= 0) resetAgent(agent);
return;
}
if (!agent.routeEdges.length) {
resetAgent(agent);
return;
}
let edge = agent.routeEdges[agent.edgeIndex];
agent.progress += agent.speed * dt / edge.actualLength;
while (agent.progress >= 1) {
agent.progress -= 1;
agent.edgeIndex++;
if (agent.edgeIndex >= agent.routeEdges.length) {
agent.mesh.visible = false;
agent.wait = 0.8 + Math.random() * 2.1;
return;
}
edge = agent.routeEdges[agent.edgeIndex];
}
const position = edgePoint(edge, agent.progress);
const ahead = edgePoint(edge, Math.min(1, agent.progress + 0.012));
agent.mesh.position.copy(position);
if (agent.type === "cart") {
agent.mesh.rotation.y = Math.atan2(ahead.x - position.x, ahead.z - position.z);
agent.mesh.children.forEach((child) => {
if (child.geometry?.type === "CylinderGeometry") {
child.rotation.x += agent.speed * dt * 2.4;
}
});
}
}
// -------------------------------------------------------------------------
// Representative route overlays
// -------------------------------------------------------------------------
const routeOverlays = [];
const flowDefinitions = [
{ start: "W1", end: "E3", color: 0xc97845 },
{ start: "W0", end: "E3", color: 0x477e76 },
{ start: "W3", end: "E4", color: 0x765c79 }
];
for (const flow of flowDefinitions) {
const line = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineDashedMaterial({
color: flow.color,
transparent: true,
opacity: 0.78,
dashSize: 0.7,
gapSize: 0.38,
depthTest: false
})
);
line.renderOrder = 5;
scene.add(line);
routeOverlays.push({ ...flow, line });
}
function updateRouteOverlays() {
for (const overlay of routeOverlays) {
const route = routeBetween(overlay.start, overlay.end);
const points = [new THREE.Vector3().copy(nodes.get(overlay.start))];
points[0].y += 0.32;
for (const edge of route.edges) {
const samples = edge.bridgeId ? 15 : 1;
for (let i = 1; i <= samples; i++) {
const point = edgePoint(edge, i / samples);
point.y += 0.32;
points.push(point);
}
}
overlay.line.geometry.dispose();
overlay.line.geometry = new THREE.BufferGeometry().setFromPoints(points);
overlay.line.computeLineDistances();
overlay.line.visible = $("#showRoutes").checked;
}
}
// -------------------------------------------------------------------------
// UI state and bridge behavior
// -------------------------------------------------------------------------
let selectedBridgeId = "b-middle";
let closedBridgeId = null;
let reroutedCount = 0;
let paused = false;
const bridgeCardRefs = new Map();
for (const bridge of bridgeDefinitions) {
const button = document.createElement("button");
button.type = "button";
button.className = "bridge-card";
button.innerHTML = `
<span class="bridge-dot"></span>
<span>
<span class="bridge-name">${bridge.name}</span>
<span class="bridge-place">${bridge.place}</span>
</span>
<span class="bridge-state">OPEN</span>
`;
button.addEventListener("click", () => {
selectedBridgeId = bridge.id;
updateBridgeStates();
updateUI();
});
$("#bridgeList").appendChild(button);
bridgeCardRefs.set(bridge.id, button);
}
function updateBridgeStates() {
for (const bridge of bridgeById.values()) {
const selected = bridge.id === selectedBridgeId;
const closed = bridge.id === closedBridgeId;
const card = bridgeCardRefs.get(bridge.id);
card.classList.toggle("selected", selected);
card.classList.toggle("closed", closed);
card.querySelector(".bridge-state").textContent = closed ? "CLOSED" : "OPEN";
card.setAttribute("aria-pressed", String(selected));
bridge.barrier.visible = closed;
bridge.deckMat.color.setHex(closed ? 0x817664 : bridge.baseColor);
bridge.deckMat.emissive.setHex(selected ? 0x5b2e16 : 0x000000);
bridge.deckMat.emissiveIntensity = selected ? 0.34 : 0;
bridge.label.classList.toggle("closed", closed);
}
const selected = bridgeById.get(selectedBridgeId);
const closeButton = $("#closeBridge");
closeButton.textContent = closedBridgeId === selectedBridgeId
? `Reopen ${selected.name}`
: `Close ${selected.name}`;
closeButton.classList.toggle("reopen", closedBridgeId === selectedBridgeId);
}
function closeOrReopenSelected() {
if (closedBridgeId === selectedBridgeId) {
closedBridgeId = null;
reroutedCount = 0;
for (const agent of agents) recomputeAgentRoute(agent, false);
} else {
closedBridgeId = selectedBridgeId;
reroutedCount = 0;
for (const agent of agents) recomputeAgentRoute(agent, true);
}
updateBridgeStates();
updateRouteOverlays();
updateUI();
}
function updateUI() {
const walkers = agents.filter((agent) => agent.type === "walker").length;
const carts = agents.filter((agent) => agent.type === "cart").length;
const open = 3 - (closedBridgeId ? 1 : 0);
$("#openCount").textContent = String(open);
$("#walkerCount").textContent = String(walkers);
$("#cartCount").textContent = String(carts);
$("#rerouteCount").textContent = String(reroutedCount);
const selectedBridge = bridgeById.get(selectedBridgeId);
const selectedTraffic = agents.filter((agent) =>
agent.routeEdges.some((edge) => edge.bridgeId === selectedBridgeId)
).length;
$("#selectedTraffic").textContent = String(selectedTraffic);
const note = $("#routeNote");
note.classList.toggle("closed", Boolean(closedBridgeId));
if (!closedBridgeId) {
note.textContent =
"All three crossings are open. Select a bridge and close it to test how people and goods find another way.";
} else {
const usage = {};
for (const agent of agents) {
for (const edge of agent.routeEdges) {
if (edge.bridgeId && edge.bridgeId !== closedBridgeId) {
usage[edge.bridgeId] = (usage[edge.bridgeId] || 0) + 1;
}
}
}
const alternatives = bridgeDefinitions
.filter((bridge) => bridge.id !== closedBridgeId)
.map((bridge) => ({
name: bridge.name.replace(" Bridge", ""),
count: usage[bridge.id] || 0
}))
.sort((a, b) => b.count - a.count);
const closedName = bridgeById.get(closedBridgeId).name.replace(" Bridge", "");
note.textContent =
`${closedName} is closed. ${reroutedCount} ${reroutedCount === 1 ? "route was" : "routes were"} recalculated. ` +
`Current crossings favor ${alternatives[0].name} (${alternatives[0].count}) and ${alternatives[1].name} (${alternatives[1].count}).`;
}
}
function reconcileAgentCounts() {
const desiredWalkers = Number($("#walkers").value);
const desiredCarts = Number($("#carts").value);
$("#walkersValue").textContent = String(desiredWalkers);
$("#cartsValue").textContent = String(desiredCarts);
let walkers = agents.filter((agent) => agent.type === "walker");
let carts = agents.filter((agent) => agent.type === "cart");
while (walkers.length < desiredWalkers) {
const agent = createAgent("walker");
walkers.push(agent);
}
while (walkers.length > desiredWalkers) {
const agent = walkers.pop();
scene.remove(agent.mesh);
}
while (carts.length < desiredCarts) {
const agent = createAgent("cart");
carts.push(agent);
}
while (carts.length > desiredCarts) {
const agent = carts.pop();
scene.remove(agent.mesh);
}
updateUI();
}
$("#closeBridge").addEventListener("click", closeOrReopenSelected);
$("#walkers").addEventListener("input", reconcileAgentCounts);
$("#carts").addEventListener("input", reconcileAgentCounts);
$("#showRoutes").addEventListener("change", (event) => {
for (const overlay of routeOverlays) overlay.line.visible = event.target.checked;
});
$("#pause").addEventListener("click", () => {
paused = !paused;
$("#pause").textContent = paused ? "Resume movement" : "Pause movement";
});
$("#resetFlow").addEventListener("click", () => {
for (const agent of agents) scene.remove(agent.mesh);
agents.length = 0;
reroutedCount = 0;
reconcileAgentCounts();
});
$("#resetView").addEventListener("click", resetCamera);
$("#openAll").addEventListener("click", () => {
closedBridgeId = null;
reroutedCount = 0;
for (const agent of agents) recomputeAgentRoute(agent, false);
updateBridgeStates();
updateRouteOverlays();
updateUI();
});
// -------------------------------------------------------------------------
// Custom camera controls and bridge picking
// -------------------------------------------------------------------------
const pointer = {
down: false,
moved: false,
button: 0,
x: 0,
y: 0,
lastX: 0,
lastY: 0
};
const raycaster = new THREE.Raycaster();
const pointerNDC = new THREE.Vector2();
renderer.domElement.addEventListener("pointerdown", (event) => {
pointer.down = true;
pointer.moved = false;
pointer.button = event.button;
pointer.x = pointer.lastX = event.clientX;
pointer.y = pointer.lastY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointer.down) return;
const dx = event.clientX - pointer.lastX;
const dy = event.clientY - pointer.lastY;
if (Math.abs(event.clientX - pointer.x) + Math.abs(event.clientY - pointer.y) > 4) {
pointer.moved = true;
}
if (event.shiftKey || pointer.button === 2) {
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));
const scale = (viewHeight * 2) / window.innerHeight / cameraZoom;
cameraTarget.addScaledVector(right, -dx * scale);
cameraTarget.addScaledVector(forward, dy * scale);
} else {
cameraTheta -= dx * 0.006;
cameraPhi = THREE.MathUtils.clamp(cameraPhi + dy * 0.005, 0.42, 1.22);
}
pointer.lastX = event.clientX;
pointer.lastY = event.clientY;
updateCamera();
});
renderer.domElement.addEventListener("pointerup", (event) => {
pointer.down = false;
if (pointer.moved || pointer.button !== 0) return;
pointerNDC.x = (event.clientX / window.innerWidth) * 2 - 1;
pointerNDC.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(pointerNDC, camera);
const hits = raycaster.intersectObjects(pickables, false);
if (hits.length) {
const key = hits[0].object.userData.bridgeKey;
const bridge = bridgeDefinitions.find((item) => item.key === key);
if (bridge) {
selectedBridgeId = bridge.id;
updateBridgeStates();
updateUI();
}
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointer.down = false;
});
renderer.domElement.addEventListener("contextmenu", (event) => event.preventDefault());
renderer.domElement.addEventListener("wheel", (event) => {
event.preventDefault();
cameraZoom = THREE.MathUtils.clamp(cameraZoom * Math.exp(-event.deltaY * 0.001), 0.62, 2.4);
updateCamera();
}, { passive: false });
// -------------------------------------------------------------------------
// Labels and animation
// -------------------------------------------------------------------------
const projected = new THREE.Vector3();
function updateWorldLabels() {
for (const label of worldLabels) {
projected.set(0, 3.55, label.z).project(camera);
const visible = projected.z < 1 && Math.abs(projected.x) < 1.08 && Math.abs(projected.y) < 1.08;
label.element.style.display = visible ? "block" : "none";
if (!visible) continue;
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
label.element.style.left = `${x}px`;
label.element.style.top = `${y}px`;
}
}
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
const time = clock.elapsedTime;
if (!paused) {
for (const agent of agents) updateAgent(agent, dt);
for (const boat of boats) {
boat.group.position.z += boat.speed * dt;
boat.group.position.x = Math.sin(time * 0.23 + boat.offset) * 0.18;
boat.group.rotation.z = Math.sin(time * 0.6 + boat.offset) * 0.012;
if (boat.group.position.z > 26) boat.group.position.z = -26;
}
for (const glint of glints) {
glint.mesh.position.x += glint.speed * dt;
glint.mesh.material.opacity =
0.08 + (Math.sin(time * 1.4 + glint.mesh.position.z) + 1) * 0.08;
if (glint.mesh.position.x > 3.7) glint.mesh.position.x = -3.7;
}
}
updateWorldLabels();
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
updateCamera();
});
// Initialize.
reconcileAgentCounts();
updateBridgeStates();
updateRouteOverlays();
updateUI();
animate();
requestAnimationFrame(() => {
loading.classList.add("hidden");
setTimeout(() => loading.remove(), 450);
});
</script>
</body>
</html>
```