Prompt specification
Build or customize the Three.js 3D scene "Bridge closure and detour simulation" 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 closure and detour simulation
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/bridge-closure-and-detour-simulation-x1344
Scene Description Prompt:
Please use Three.js from cdnjs for a low-poly scene based on this idea: bridge closure and detour simulation. Let users close one crossing in a river network. Recompute a visible valid route and animate a short detour without allowing travelers to cut across water. Return one self-contained HTML file.
Working Three.js Starter (bridge-closure-and-detour-simulation-x1344):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Bridge Closure & Detour Simulation</title>
<style>
:root {
--ink: #173b37;
--muted: #67817c;
--panel: rgba(250, 252, 247, 0.94);
--line: rgba(31, 83, 76, 0.13);
--green: #22a98e;
--green-dark: #147765;
--cyan: #1dbdac;
--orange: #f0a44a;
--red: #df6256;
--shadow: 0 18px 50px rgba(31, 69, 60, 0.18);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dcece7;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#scene canvas:active {
cursor: grabbing;
}
.panel {
position: fixed;
z-index: 10;
top: 20px;
left: 20px;
width: min(350px, calc(100vw - 40px));
padding: 22px;
overflow: auto;
border: 1px solid rgba(255, 255, 255, 0.78);
border-radius: 24px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(18px) saturate(1.1);
-webkit-backdrop-filter: blur(18px) saturate(1.1);
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 10px;
color: var(--green-dark);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.live-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 0 5px rgba(34, 169, 142, 0.12);
animation: breathe 2s ease-in-out infinite;
}
@keyframes breathe {
50% {
box-shadow: 0 0 0 8px rgba(34, 169, 142, 0.04);
}
}
h1 {
margin: 0;
font-size: clamp(30px, 4vw, 43px);
font-weight: 780;
letter-spacing: -0.055em;
line-height: 0.98;
}
h1 span {
color: var(--green);
}
.intro {
margin: 14px 0 20px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin: 0 0 9px;
color: #55716c;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.section-heading span:last-child {
color: #91a49f;
font-size: 9px;
letter-spacing: 0.08em;
}
.crossing-list {
display: grid;
gap: 8px;
}
.crossing {
display: grid;
grid-template-columns: 38px 1fr auto;
gap: 11px;
align-items: center;
width: 100%;
padding: 11px;
color: var(--ink);
text-align: left;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(255, 255, 255, 0.68);
cursor: pointer;
transition: transform 160ms ease, border-color 160ms ease,
background 160ms ease;
}
.crossing:hover {
transform: translateY(-1px);
border-color: rgba(29, 189, 172, 0.38);
background: white;
}
.crossing.closed {
border-color: rgba(223, 98, 86, 0.3);
background: rgba(255, 245, 242, 0.9);
}
.bridge-icon {
position: relative;
width: 38px;
height: 38px;
border-radius: 11px;
background: #e3f3ec;
}
.bridge-icon::before,
.bridge-icon::after {
content: "";
position: absolute;
left: 7px;
right: 7px;
height: 4px;
border-radius: 3px;
background: var(--green);
}
.bridge-icon::before {
top: 10px;
}
.bridge-icon::after {
bottom: 9px;
background: #80b9ac;
}
.closed .bridge-icon {
background: #f8e4df;
}
.closed .bridge-icon::before,
.closed .bridge-icon::after {
background: var(--red);
}
.crossing-copy {
min-width: 0;
}
.crossing-copy strong {
display: block;
margin-bottom: 2px;
font-size: 13px;
font-weight: 750;
}
.crossing-copy small {
display: block;
overflow: hidden;
color: var(--muted);
font-size: 10px;
text-overflow: ellipsis;
white-space: nowrap;
}
.crossing-state {
text-align: right;
}
.crossing-state b {
display: block;
color: var(--green-dark);
font-size: 10px;
text-transform: uppercase;
}
.crossing-state small {
display: block;
margin-top: 2px;
color: #8ba09b;
font-size: 9px;
}
.closed .crossing-state b {
color: var(--red);
}
.route-card {
margin-top: 18px;
padding: 15px;
border: 1px solid rgba(29, 189, 172, 0.22);
border-radius: 17px;
background: linear-gradient(145deg, rgba(233, 249, 243, 0.96),
rgba(255, 255, 255, 0.9));
}
.route-top {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
}
.route-kicker {
margin-bottom: 4px;
color: var(--green-dark);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.route-title {
font-size: 15px;
font-weight: 760;
}
.route-badge {
flex: 0 0 auto;
padding: 5px 8px;
border-radius: 999px;
color: white;
background: var(--green);
font-size: 8px;
font-weight: 900;
letter-spacing: 0.1em;
}
.route-badge.detour {
background: var(--orange);
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin: 13px 0;
}
.metric {
padding: 10px 11px;
border: 1px solid rgba(31, 83, 76, 0.09);
border-radius: 11px;
background: rgba(255, 255, 255, 0.76);
}
.metric span {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.metric strong {
font-size: 18px;
letter-spacing: -0.03em;
}
.route-path {
color: #54706a;
font-size: 10px;
line-height: 1.55;
}
.validation {
display: flex;
align-items: center;
gap: 8px;
margin-top: 11px;
color: #5c7771;
font-size: 10px;
}
.validation-icon {
display: grid;
width: 18px;
height: 18px;
place-items: center;
flex: 0 0 auto;
border-radius: 50%;
color: white;
background: var(--green);
font-size: 10px;
font-weight: 900;
}
.map-actions {
position: fixed;
z-index: 10;
top: 20px;
right: 20px;
display: flex;
gap: 8px;
}
.map-action {
height: 38px;
padding: 0 13px;
color: var(--ink);
border: 1px solid rgba(255, 255, 255, 0.8);
border-radius: 12px;
background: rgba(250, 252, 247, 0.9);
box-shadow: 0 8px 24px rgba(31, 69, 60, 0.12);
backdrop-filter: blur(12px);
cursor: pointer;
font-size: 11px;
font-weight: 750;
}
.map-action:hover {
background: white;
}
.legend {
position: fixed;
z-index: 9;
right: 20px;
bottom: 20px;
display: grid;
gap: 8px;
min-width: 170px;
padding: 13px 15px;
border: 1px solid rgba(255, 255, 255, 0.75);
border-radius: 15px;
background: rgba(250, 252, 247, 0.86);
box-shadow: 0 10px 30px rgba(31, 69, 60, 0.11);
backdrop-filter: blur(12px);
color: #58736d;
font-size: 10px;
}
.legend-row {
display: flex;
align-items: center;
gap: 9px;
}
.legend-line {
width: 23px;
height: 4px;
border-radius: 4px;
background: var(--cyan);
box-shadow: 0 0 8px rgba(29, 189, 172, 0.55);
}
.legend-water {
width: 23px;
height: 8px;
border-radius: 4px;
background: #65aeba;
}
.legend-closed {
width: 23px;
height: 3px;
background: var(--red);
transform: rotate(-20deg);
}
.hint {
position: fixed;
z-index: 8;
bottom: 20px;
left: 50%;
padding: 9px 14px;
transform: translateX(-50%);
border: 1px solid rgba(255, 255, 255, 0.7);
border-radius: 999px;
background: rgba(250, 252, 247, 0.82);
box-shadow: 0 8px 24px rgba(31, 69, 60, 0.1);
color: #607a74;
font-size: 10px;
white-space: nowrap;
backdrop-filter: blur(10px);
}
#labels {
position: fixed;
z-index: 6;
inset: 0;
overflow: hidden;
pointer-events: none;
}
.world-label {
position: absolute;
display: flex;
align-items: center;
gap: 6px;
min-height: 28px;
padding: 6px 9px;
transform: translate(-50%, -50%);
border: 1px solid rgba(255, 255, 255, 0.85);
border-radius: 10px;
background: rgba(255, 255, 255, 0.9);
box-shadow: 0 5px 16px rgba(31, 69, 60, 0.15);
color: #284e47;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.04em;
pointer-events: auto;
cursor: pointer;
white-space: nowrap;
}
.world-label b {
color: var(--green-dark);
font-size: 7px;
}
.world-label.closed {
color: #a8463c;
background: rgba(255, 245, 242, 0.96);
}
.world-label.closed b {
color: var(--red);
}
.label-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 0 3px rgba(34, 169, 142, 0.14);
}
.world-label.closed .label-dot {
background: var(--red);
box-shadow: 0 0 0 3px rgba(223, 98, 86, 0.13);
}
.place-label {
position: absolute;
padding: 5px 8px;
transform: translate(-50%, -50%);
border-radius: 8px;
background: rgba(23, 59, 55, 0.82);
color: white;
font-size: 8px;
font-weight: 750;
letter-spacing: 0.05em;
white-space: nowrap;
}
#toast {
position: fixed;
z-index: 30;
top: 20px;
left: 50%;
max-width: calc(100vw - 40px);
padding: 11px 16px;
transform: translate(-50%, -90px);
border: 1px solid rgba(255, 255, 255, 0.7);
border-radius: 12px;
background: rgba(23, 59, 55, 0.92);
box-shadow: 0 12px 30px rgba(31, 69, 60, 0.2);
color: white;
font-size: 11px;
opacity: 0;
transition: transform 250ms ease, opacity 250ms ease;
pointer-events: none;
text-align: center;
}
#toast.show {
transform: translate(-50%, 0);
opacity: 1;
}
#loading {
position: fixed;
z-index: 50;
inset: 0;
display: grid;
place-items: center;
background: #dcece7;
color: var(--green-dark);
font-size: 12px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
transition: opacity 350ms ease;
}
#loading.hidden {
opacity: 0;
pointer-events: none;
}
@media (max-width: 720px) {
.panel {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
max-height: 52vh;
padding: 16px;
border-radius: 19px;
}
h1 {
font-size: 31px;
}
.intro {
margin: 10px 0 14px;
}
.map-actions {
top: auto;
right: 10px;
bottom: 56px;
}
.legend,
.hint {
display: none;
}
.route-card {
margin-top: 12px;
}
.world-label {
font-size: 8px;
}
}
</style>
</head>
<body>
<div id="scene" aria-label="Interactive three-dimensional river network"></div>
<div id="labels"></div>
<section class="panel" aria-label="Bridge simulation controls">
<div class="eyebrow">
<span class="live-dot"></span>
Live network simulation
</div>
<h1>Bridge closure<br /><span>& detour.</span></h1>
<p class="intro">
Close a river crossing and the network instantly finds a valid alternative.
Travelers remain on modeled roads and bridges—never across open water.
</p>
<div class="section-heading">
<span>River crossings</span>
<span>Click to change</span>
</div>
<div class="crossing-list">
<button class="crossing closed" id="cedarRow" aria-pressed="true">
<span class="bridge-icon"></span>
<span class="crossing-copy">
<strong>Cedar Bridge</strong>
<small>Central crossing · 23 m</small>
</span>
<span class="crossing-state">
<b>Closed</b>
<small>Reopen</small>
</span>
</button>
<button class="crossing" id="northRow" aria-pressed="false">
<span class="bridge-icon"></span>
<span class="crossing-copy">
<strong>North Bridge</strong>
<small>Northern crossing · 25 m</small>
</span>
<span class="crossing-state">
<b>Open</b>
<small>Close</small>
</span>
</button>
</div>
<div class="route-card">
<div class="route-top">
<div>
<div class="route-kicker">Active route</div>
<div class="route-title" id="routeTitle">Short detour active</div>
</div>
<div class="route-badge detour" id="routeBadge">Detour</div>
</div>
<div class="metrics">
<div class="metric">
<span>Route length</span>
<strong id="routeDistance">—</strong>
</div>
<div class="metric">
<span>Added time</span>
<strong id="routeDelay">—</strong>
</div>
</div>
<div class="route-path" id="routePath">
Riverside Depot → Westbank Road → North Bridge → Eastbank Road → Market District
</div>
</div>
<div class="validation">
<span class="validation-icon">✓</span>
<span id="validationText">Route verified: all segments stay on land or approved bridges.</span>
</div>
</section>
<div class="map-actions">
<button class="map-action" id="pauseButton">Pause traffic</button>
<button class="map-action" id="cameraButton">Reset view</button>
</div>
<div class="legend">
<div class="legend-row"><span class="legend-line"></span> Valid active route</div>
<div class="legend-row"><span class="legend-water"></span> River / no shortcut</div>
<div class="legend-row"><span class="legend-closed"></span> Closed crossing</div>
</div>
<div class="hint">Drag to orbit · Scroll to zoom · Click a bridge to close it</div>
<div id="toast" role="status" aria-live="polite"></div>
<div id="loading">Building river network…</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const sceneContainer = document.getElementById("scene");
const labelLayer = document.getElementById("labels");
const toast = document.getElementById("toast");
// -------------------------------------------------------------------------
// Renderer and camera
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdcece7);
scene.fog = new THREE.Fog(0xdcece7, 92, 180);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
250
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
sceneContainer.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xf8fff9, 0x6f927b, 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff6dc, 3.15);
sun.position.set(-35, 55, 28);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -58;
sun.shadow.camera.right = 58;
sun.shadow.camera.top = 58;
sun.shadow.camera.bottom = -58;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 130;
sun.shadow.bias = -0.0005;
scene.add(sun);
const cameraState = {
theta: 0.56,
phi: 0.96,
radius: 84,
target: new THREE.Vector3(0, 0, 1)
};
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x + cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z + cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
updateCamera();
// -------------------------------------------------------------------------
// Low-poly landscape
// -------------------------------------------------------------------------
let seed = 8173;
function random() {
seed = (seed * 16807) % 2147483647;
return (seed - 1) / 2147483646;
}
const groundGeometry = new THREE.PlaneGeometry(110, 86, 22, 17);
groundGeometry.rotateX(-Math.PI / 2);
const groundPosition = groundGeometry.attributes.position;
const groundColors = [];
for (let i = 0; i < groundPosition.count; i++) {
const x = groundPosition.getX(i);
const z = groundPosition.getZ(i);
groundPosition.setY(i, -0.12 + random() * 0.07);
const patch = random();
const color = new THREE.Color();
if (z < -15) {
color.setHSL(0.31 + patch * 0.025, 0.28, 0.58 + patch * 0.06);
} else {
color.setHSL(0.34 + patch * 0.035, 0.25, 0.56 + patch * 0.07);
}
groundColors.push(color.r, color.g, color.b);
}
groundGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(groundColors, 3)
);
const groundMaterial = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.94,
flatShading: true
});
const ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.receiveShadow = true;
scene.add(ground);
const riverSamples = [
{ z: -43, left: -7.4, right: 4.5 },
{ z: -32, left: -6.1, right: 6.4 },
{ z: -21, left: -5.4, right: 6.0 },
{ z: -10, left: -7.0, right: 5.2 },
{ z: 0, left: -5.1, right: 7.0 },
{ z: 11, left: -6.4, right: 6.0 },
{ z: 23, left: -6.9, right: 5.0 },
{ z: 34, left: -5.4, right: 6.7 },
{ z: 43, left: -7.0, right: 4.9 }
];
function riverBounds(z) {
if (z <= riverSamples[0].z) return riverSamples[0];
if (z >= riverSamples[riverSamples.length - 1].z) {
return riverSamples[riverSamples.length - 1];
}
for (let i = 0; i < riverSamples.length - 1; i++) {
const a = riverSamples[i];
const b = riverSamples[i + 1];
if (z >= a.z && z <= b.z) {
const t = (z - a.z) / (b.z - a.z);
return {
z,
left: THREE.MathUtils.lerp(a.left, b.left, t),
right: THREE.MathUtils.lerp(a.right, b.right, t)
};
}
}
return riverSamples[0];
}
function isInRiver(x, z) {
const bounds = riverBounds(z);
return x > bounds.left && x < bounds.right;
}
const waterPositions = [];
const waterColors = [];
for (let i = 0; i < riverSamples.length - 1; i++) {
const a = riverSamples[i];
const b = riverSamples[i + 1];
const triangles = [
[a.left, a.z, a.right, a.z, b.left, b.z],
[a.right, a.z, b.left, b.z, b.right, b.z]
];
for (const triangle of triangles) {
const shade = 0.49 + random() * 0.055;
const color = new THREE.Color().setHSL(0.52 + random() * 0.018, 0.44, shade);
for (const point of triangle) {
waterPositions.push(point[0], 0.055, point[1]);
waterColors.push(color.r, color.g, color.b);
}
}
}
const waterGeometry = new THREE.BufferGeometry();
waterGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(waterPositions, 3)
);
waterGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(waterColors, 3)
);
waterGeometry.computeVertexNormals();
const waterMaterial = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.3,
metalness: 0.03,
transparent: true,
opacity: 0.93,
flatShading: true,
side: THREE.DoubleSide
});
const water = new THREE.Mesh(waterGeometry, waterMaterial);
water.receiveShadow = true;
scene.add(water);
const bankLineMaterial = new THREE.LineBasicMaterial({
color: 0x9cc8b7,
transparent: true,
opacity: 0.75
});
for (const side of ["left", "right"]) {
const points = riverSamples.map(
(sample) => new THREE.Vector3(sample[side], 0.08, sample.z)
);
const line = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(points),
bankLineMaterial
);
scene.add(line);
}
const waveMaterial = new THREE.MeshBasicMaterial({
color: 0xe8ffff,
transparent: true,
opacity: 0.34,
depthWrite: false
});
for (let i = 0; i < 15; i++) {
const z = -37 + random() * 74;
const bounds = riverBounds(z);
const wave = new THREE.Mesh(
new THREE.PlaneGeometry(1.2 + random() * 2.6, 0.08),
waveMaterial
);
wave.rotation.x = -Math.PI / 2;
wave.rotation.z = (random() - 0.5) * 0.25;
wave.position.set(
THREE.MathUtils.lerp(bounds.left, bounds.right, 0.25 + random() * 0.5),
0.085,
z
);
scene.add(wave);
}
// -------------------------------------------------------------------------
// Road graph. Only bridge edges are permitted to cross the river.
// -------------------------------------------------------------------------
const nodes = {
W0: new THREE.Vector3(-13, 0, -25),
W1: new THREE.Vector3(-11, 0, -6),
W2: new THREE.Vector3(-12, 0, 14),
W3: new THREE.Vector3(-10, 0, 29),
E0: new THREE.Vector3(13, 0, -25),
E1: new THREE.Vector3(11, 0, -5),
E2: new THREE.Vector3(13, 0, 15),
E3: new THREE.Vector3(10, 0, 29)
};
const edges = [
{ id: "w01", a: "W0", b: "W1", road: true },
{ id: "w12", a: "W1", b: "W2", road: true },
{ id: "w23", a: "W2", b: "W3", road: true },
{ id: "e01", a: "E0", b: "E1", road: true },
{ id: "e12", a: "E1", b: "E2", road: true },
{ id: "e23", a: "E2", b: "E3", road: true },
{ id: "cedar", a: "W1", b: "E1", bridge: "cedar" },
{ id: "north", a: "W2", b: "E2", bridge: "north" }
];
const bridges = {
cedar: {
id: "cedar",
name: "Cedar Bridge",
shortName: "Cedar",
a: "W1",
b: "E1",
closedMix: 0,
mark: null,
deckMaterial: null
},
north: {
id: "north",
name: "North Bridge",
shortName: "North",
a: "W2",
b: "E2",
closedMix: 0,
mark: null,
deckMaterial: null
}
};
const adjacency = Object.fromEntries(Object.keys(nodes).map((id) => [id, []]));
for (const edge of edges) {
const distance = Math.hypot(
nodes[edge.a].x - nodes[edge.b].x,
nodes[edge.a].z - nodes[edge.b].z
);
edge.length = distance;
adjacency[edge.a].push({ node: edge.b, edge });
adjacency[edge.b].push({ node: edge.a, edge });
}
const roadMaterial = new THREE.MeshStandardMaterial({
color: 0xe8dfc5,
roughness: 0.93,
flatShading: true
});
const bridgeMaterial = new THREE.MeshStandardMaterial({
color: 0xc99257,
roughness: 0.8,
flatShading: true
});
const railMaterial = new THREE.MeshStandardMaterial({
color: 0x8b6545,
roughness: 0.82
});
const markingMaterial = new THREE.MeshBasicMaterial({
color: 0xfff1bc,
transparent: true,
opacity: 0.78
});
function stripBetween(
ax,
az,
bx,
bz,
width,
height,
y,
material,
parent = scene
) {
const length = Math.hypot(bx - ax, bz - az);
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(length, height, width),
material
);
mesh.position.set((ax + bx) / 2, y, (az + bz) / 2);
mesh.rotation.y = -Math.atan2(bz - az, bx - ax);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
for (const edge of edges.filter((item) => item.road)) {
const a = nodes[edge.a];
const b = nodes[edge.b];
stripBetween(a.x, a.z, b.x, b.z, 1.8, 0.16, 0.12, roadMaterial);
const dx = b.x - a.x;
const dz = b.z - a.z;
const length = Math.hypot(dx, dz);
const angle = -Math.atan2(dz, dx);
for (let t = 0.13; t < 0.9; t += 0.16) {
const dash = new THREE.Mesh(
new THREE.BoxGeometry(0.68, 0.025, 0.08),
markingMaterial
);
dash.position.set(
THREE.MathUtils.lerp(a.x, b.x, t),
0.215,
THREE.MathUtils.lerp(a.z, b.z, t)
);
dash.rotation.y = angle;
scene.add(dash);
}
}
const intersectionMaterial = new THREE.MeshStandardMaterial({
color: 0xddd3b8,
roughness: 0.95,
flatShading: true
});
for (const node of Object.values(nodes)) {
const intersection = new THREE.Mesh(
new THREE.CylinderGeometry(1.12, 1.18, 0.14, 12),
intersectionMaterial
);
intersection.position.set(node.x, 0.12, node.z);
intersection.receiveShadow = true;
scene.add(intersection);
}
const pickMeshes = [];
function createBridge(bridge) {
const a = nodes[bridge.a];
const b = nodes[bridge.b];
const dx = b.x - a.x;
const dz = b.z - a.z;
const length = Math.hypot(dx, dz);
const perpendicularX = -dz / length;
const perpendicularZ = dx / length;
const material = bridgeMaterial.clone();
bridge.deckMaterial = material;
const deck = stripBetween(
a.x,
a.z,
b.x,
b.z,
2.35,
0.28,
0.36,
material
);
deck.userData.bridgeId = bridge.id;
pickMeshes.push(deck);
for (const offset of [-1.04, 1.04]) {
stripBetween(
a.x + perpendicularX * offset,
a.z + perpendicularZ * offset,
b.x + perpendicularX * offset,
b.z + perpendicularZ * offset,
0.12,
0.12,
0.78,
railMaterial
);
}
for (const t of [0.25, 0.5, 0.75]) {
const pillar = new THREE.Mesh(
new THREE.BoxGeometry(0.48, 1.25, 0.5),
railMaterial
);
pillar.position.set(
THREE.MathUtils.lerp(a.x, b.x, t),
0.05,
THREE.MathUtils.lerp(a.z, b.z, t)
);
pillar.castShadow = true;
scene.add(pillar);
}
for (let t = 0.15; t < 0.9; t += 0.18) {
const dash = new THREE.Mesh(
new THREE.BoxGeometry(0.68, 0.025, 0.1),
markingMaterial
);
dash.position.set(
THREE.MathUtils.lerp(a.x, b.x, t),
0.515,
THREE.MathUtils.lerp(a.z, b.z, t)
);
dash.rotation.y = -Math.atan2(dz, dx);
scene.add(dash);
}
const mark = new THREE.Group();
mark.position.set((a.x + b.x) / 2, 2.05, (a.z + b.z) / 2);
mark.scale.setScalar(0.001);
const redMaterial = new THREE.MeshBasicMaterial({
color: 0xe35f52,
depthTest: false,
transparent: true,
opacity: 0.96
});
for (const angle of [-Math.PI / 4, Math.PI / 4]) {
const bar = new THREE.Mesh(
new THREE.BoxGeometry(4.2, 0.22, 0.22),
redMaterial
);
bar.rotation.z = angle;
bar.renderOrder = 20;
mark.add(bar);
}
const ring = new THREE.Mesh(
new THREE.TorusGeometry(2.15, 0.1, 6, 28),
redMaterial
);
ring.renderOrder = 20;
mark.add(ring);
scene.add(mark);
bridge.mark = mark;
}
createBridge(bridges.cedar);
createBridge(bridges.north);
// -------------------------------------------------------------------------
// Trees and small low-poly buildings
// -------------------------------------------------------------------------
const trunkMaterial = new THREE.MeshStandardMaterial({
color: 0x765a3d,
roughness: 1,
flatShading: true
});
const foliageMaterials = [
new THREE.MeshStandardMaterial({ color: 0x3f8060, flatShading: true }),
new THREE.MeshStandardMaterial({ color: 0x4f9169, flatShading: true }),
new THREE.MeshStandardMaterial({ color: 0x2f7357, flatShading: true })
];
function distanceToSegment(x, z, a, b) {
const dx = b.x - a.x;
const dz = b.z - a.z;
const denominator = dx * dx + dz * dz;
const t = denominator
? THREE.MathUtils.clamp(
((x - a.x) * dx + (z - a.z) * dz) / denominator,
0,
1
)
: 0;
const px = a.x + dx * t;
const pz = a.z + dz * t;
return Math.hypot(x - px, z - pz);
}
function addTree(x, z, scale) {
const tree = new THREE.Group();
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.16, 0.23, 1.2, 5),
trunkMaterial
);
trunk.position.y = 0.58;
trunk.castShadow = true;
tree.add(trunk);
const crown = new THREE.Mesh(
new THREE.ConeGeometry(1.05, 2.65, 6),
foliageMaterials[Math.floor(random() * foliageMaterials.length)]
);
crown.position.y = 2.0;
crown.rotation.y = random() * Math.PI;
crown.castShadow = true;
tree.add(crown);
tree.position.set(x, 0, z);
tree.scale.setScalar(scale);
scene.add(tree);
}
let treeCount = 0;
let attempts = 0;
while (treeCount < 42 && attempts < 500) {
attempts++;
const side = random() < 0.5 ? -1 : 1;
const x = side < 0 ? -9 - random() * 29 : 9 + random() * 29;
const z = -37 + random() * 74;
if (isInRiver(x, z)) continue;
const nearRoad = edges
.filter((edge) => edge.road)
.some((edge) => distanceToSegment(x, z, nodes[edge.a], nodes[edge.b]) < 3.4);
if (nearRoad) continue;
addTree(x, z, 0.72 + random() * 0.68);
treeCount++;
}
const wallMaterials = [
0xf3dfb8,
0xe9b88c,
0xe7e7d7,
0xd5b187,
0xc8d7b7
];
const roofMaterials = [
0x8f5748,
0x526f69,
0x6b5d56,
0x3e6f69
];
function addBuilding(x, z, size = 1, rotation = 0) {
const group = new THREE.Group();
const walls = new THREE.Mesh(
new THREE.BoxGeometry(2.6 * size, 2.25 * size, 2.2 * size),
new THREE.MeshStandardMaterial({
color: wallMaterials[Math.floor(random() * wallMaterials.length)],
roughness: 0.9,
flatShading: true
})
);
walls.position.y = 1.12 * size;
walls.castShadow = true;
walls.receiveShadow = true;
group.add(walls);
const roof = new THREE.Mesh(
new THREE.ConeGeometry(2.02 * size, 1.25 * size, 4),
new THREE.MeshStandardMaterial({
color: roofMaterials[Math.floor(random() * roofMaterials.length)],
roughness: 0.9,
flatShading: true
})
);
roof.position.y = 2.85 * size;
roof.rotation.y = Math.PI / 4;
roof.castShadow = true;
group.add(roof);
const door = new THREE.Mesh(
new THREE.BoxGeometry(0.55 * size, 1.1 * size, 0.08),
new THREE.MeshStandardMaterial({ color: 0x4b6259 })
);
door.position.set(0, 0.55 * size, 1.13 * size);
group.add(door);
group.position.set(x, 0, z);
group.rotation.y = rotation;
scene.add(group);
}
[
[-20, -17, 0.95, 0.1],
[-20, 3, 1.1, -0.15],
[-19, 27, 0.86, 0.2],
[20, -19, 1.08, 0.15],
[21, 2, 0.92, -0.1],
[20, 27, 1.15, 0.05],
[-31, -30, 1.25, 0.3],
[31, -28, 1.1, -0.25],
[-30, 11, 0.9, 0.1],
[30, 11, 1.0, -0.2]
].forEach((item) => addBuilding(...item));
addBuilding(-18.4, -26.2, 1.35, -0.08);
addBuilding(18.2, 17.2, 1.38, 0.12);
// -------------------------------------------------------------------------
// Shortest-path computation and route safety validation
// -------------------------------------------------------------------------
function findPath(blockedBridge = null) {
const distance = Object.fromEntries(
Object.keys(nodes).map((id) => [id, Infinity])
);
const previous = {};
const visited = new Set();
distance.W0 = 0;
while (visited.size < Object.keys(nodes).length) {
let current = null;
let smallest = Infinity;
for (const id of Object.keys(nodes)) {
if (!visited.has(id) && distance[id] < smallest) {
smallest = distance[id];
current = id;
}
}
if (current === null) break;
visited.add(current);
for (const connection of adjacency[current]) {
if (connection.edge.bridge && connection.edge.bridge === blockedBridge) {
continue;
}
const candidate = distance[current] + connection.edge.length;
if (candidate < distance[connection.node]) {
distance[connection.node] = candidate;
previous[connection.node] = {
node: current,
edge: connection.edge
};
}
}
}
if (!Number.isFinite(distance.E2)) return null;
const routeEdges = [];
const routeNodes = ["E2"];
let cursor = "E2";
while (cursor !== "W0") {
const step = previous[cursor];
if (!step) return null;
routeEdges.unshift(step.edge);
routeNodes.unshift(step.node);
cursor = step.node;
}
return {
edges: routeEdges,
nodes: routeNodes,
length: distance.E2
};
}
function validateRoute(route) {
if (!route) return false;
for (const edge of route.edges) {
if (edge.bridge) continue;
const a = nodes[edge.a];
const b = nodes[edge.b];
for (let i = 0; i <= 20; i++) {
const t = i / 20;
const x = THREE.MathUtils.lerp(a.x, b.x, t);
const z = THREE.MathUtils.lerp(a.z, b.z, t);
if (isInRiver(x, z)) return false;
}
}
return true;
}
const baseRoute = findPath(null);
const simulationState = {
closedBridge: "cedar",
paused: false
};
let currentRoute = null;
let routeSegments = [];
// -------------------------------------------------------------------------
// Route geometry and moving vehicles
// -------------------------------------------------------------------------
const routeGroup = new THREE.Group();
const routeGlowGroup = new THREE.Group();
scene.add(routeGlowGroup, routeGroup);
function disposeGroup(group) {
while (group.children.length) {
const child = group.children.pop();
child.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
if (Array.isArray(object.material)) {
object.material.forEach((material) => material.dispose());
} else {
object.material.dispose();
}
}
});
}
}
function addRouteCylinder(group, start, end, radius, material) {
const direction = new THREE.Vector3().subVectors(end, start);
const length = direction.length();
if (length < 0.001) return;
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius, length, 8),
material
);
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
group.add(mesh);
}
function rebuildRouteGeometry() {
disposeGroup(routeGroup);
disposeGroup(routeGlowGroup);
if (!currentRoute) {
routeSegments = [];
return;
}
const routeMaterial = new THREE.MeshBasicMaterial({
color: 0x19b9a7,
transparent: true,
opacity: 0.98
});
const glowMaterial = new THREE.MeshBasicMaterial({
color: 0x36e0ca,
transparent: true,
opacity: 0.15,
depthWrite: false
});
let cumulative = 0;
routeSegments = [];
for (const edge of currentRoute.edges) {
const a = nodes[edge.a];
const b = nodes[edge.b];
const length = edge.length;
routeSegments.push({
edge,
start: cumulative,
length,
end: cumulative + length
});
cumulative += length;
const splits = edge.bridge ? [0, 0.2, 0.8, 1] : [0, 1];
for (let i = 0; i < splits.length - 1; i++) {
const t0 = splits[i];
const t1 = splits[i + 1];
const start = new THREE.Vector3(
THREE.MathUtils.lerp(a.x, b.x, t0),
routeHeight(edge, t0),
THREE.MathUtils.lerp(a.z, b.z, t0)
);
const end = new THREE.Vector3(
THREE.MathUtils.lerp(a.x, b.x, t1),
routeHeight(edge, t1),
THREE.MathUtils.lerp(a.z, b.z, t1)
);
addRouteCylinder(routeGroup, start, end, 0.105, routeMaterial);
addRouteCylinder(routeGlowGroup, start, end, 0.24, glowMaterial);
}
}
for (const nodeId of currentRoute.nodes) {
const node = nodes[nodeId];
const marker = new THREE.Mesh(
new THREE.SphereGeometry(0.23, 10, 8),
routeMaterial
);
marker.position.set(node.x, 0.4, node.z);
routeGroup.add(marker);
}
}
function routeHeight(edge, t) {
if (!edge.bridge) return 0.34;
if (t < 0.2) return THREE.MathUtils.lerp(0.34, 0.69, t / 0.2);
if (t > 0.8) return THREE.MathUtils.lerp(0.69, 0.34, (1 - t) / 0.2);
return 0.69;
}
function vehicleSurfaceHeight(edge, t) {
if (!edge.bridge) return 0.235;
if (t < 0.2) return THREE.MathUtils.lerp(0.235, 0.535, t / 0.2);
if (t > 0.8) return THREE.MathUtils.lerp(0.535, 0.235, (1 - t) / 0.2);
return 0.535;
}
const vehicles = [];
const vehicleColors = [0xf4a641, 0xe76f51, 0xf2cf5b, 0x3d8f83, 0xe58b4d];
const cabinMaterial = new THREE.MeshStandardMaterial({
color: 0xf7f4df,
roughness: 0.5,
flatShading: true
});
const wheelMaterial = new THREE.MeshStandardMaterial({
color: 0x26332f,
roughness: 0.95
});
function createVehicle(index) {
const group = new THREE.Group();
const body = new THREE.Mesh(
new THREE.BoxGeometry(1.25, 0.38, 0.68),
new THREE.MeshStandardMaterial({
color: vehicleColors[index],
roughness: 0.55,
flatShading: true
})
);
body.position.y = 0.36;
body.castShadow = true;
group.add(body);
const cabin = new THREE.Mesh(
new THREE.BoxGeometry(0.62, 0.34, 0.58),
cabinMaterial
);
cabin.position.set(-0.08, 0.7, 0);
cabin.castShadow = true;
group.add(cabin);
const glass = new THREE.Mesh(
new THREE.BoxGeometry(0.64, 0.2, 0.6),
new THREE.MeshStandardMaterial({
color: 0x315b62,
roughness: 0.25,
metalness: 0.1,
flatShading: true
})
);
glass.position.set(-0.08, 0.76, 0);
group.add(glass);
for (const x of [-0.4, 0.4]) {
for (const z of [-0.35, 0.35]) {
const wheel = new THREE.Mesh(
new THREE.CylinderGeometry(0.18, 0.18, 0.12, 10),
wheelMaterial
);
wheel.rotation.x = Math.PI / 2;
wheel.position.set(x, 0.18, z);
wheel.castShadow = true;
group.add(wheel);
}
}
group.position.y = 0.235;
scene.add(group);
return {
group,
distance: 0,
speed: 4.6 + random() * 1.1,
spawnDelay: 0
};
}
for (let i = 0; i < 5; i++) vehicles.push(createVehicle(i));
const guidePulse = new THREE.Mesh(
new THREE.SphereGeometry(0.24, 12, 10),
new THREE.MeshBasicMaterial({ color: 0xffffff })
);
scene.add(guidePulse);
function sampleRoute(distance) {
if (!currentRoute || !routeSegments.length) return null;
const length = currentRoute.length;
const wrapped = ((distance % length) + length) % length;
for (const segment of routeSegments) {
if (wrapped >= segment.start && wrapped <= segment.end) {
const t = (wrapped - segment.start) / segment.length;
const a = nodes[segment.edge.a];
const b = nodes[segment.edge.b];
return {
x: THREE.MathUtils.lerp(a.x, b.x, t),
z: THREE.MathUtils.lerp(a.z, b.z, t),
y: vehicleSurfaceHeight(segment.edge, t),
directionX: b.x - a.x,
directionZ: b.z - a.z,
edge: segment.edge
};
}
}
return null;
}
function resetVehicles(reset) {
if (!currentRoute) {
vehicles.forEach((vehicle) => {
vehicle.group.visible = false;
});
return;
}
vehicles.forEach((vehicle, index) => {
vehicle.group.visible = true;
if (reset) {
vehicle.distance = index * 3.5;
vehicle.spawnDelay = index * 0.12;
vehicle.group.scale.setScalar(0.01);
} else {
vehicle.distance = (currentRoute.length / vehicles.length) * index;
vehicle.spawnDelay = 0;
vehicle.group.scale.setScalar(1);
}
});
}
// -------------------------------------------------------------------------
// HTML world labels
// -------------------------------------------------------------------------
function createWorldLabel(type, className, html) {
const element = document.createElement(type);
element.className = className;
element.innerHTML = html;
labelLayer.appendChild(element);
return element;
}
const cedarLabel = createWorldLabel(
"button",
"world-label",
'<span class="label-dot"></span><span>Cedar Bridge</span><b>CLOSED</b>'
);
const northLabel = createWorldLabel(
"button",
"world-label",
'<span class="label-dot"></span><span>North Bridge</span><b>OPEN</b>'
);
const originLabel = createWorldLabel(
"div",
"place-label",
"RIVERSIDE DEPOT"
);
const destinationLabel = createWorldLabel(
"div",
"place-label",
"MARKET DISTRICT"
);
cedarLabel.addEventListener("click", (event) => {
event.stopPropagation();
toggleBridge("cedar");
});
northLabel.addEventListener("click", (event) => {
event.stopPropagation();
toggleBridge("north");
});
const labelPositions = {
cedar: new THREE.Vector3(0, 2.7, -5.5),
north: new THREE.Vector3(0.5, 2.7, 14.5),
origin: new THREE.Vector3(-13, 1.3, -25),
destination: new THREE.Vector3(13, 1.3, 15)
};
function positionLabel(element, position) {
const projected = position.clone().project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.15 &&
Math.abs(projected.y) < 1.15;
element.style.display = visible ? "flex" : "none";
if (!visible) return;
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}
// -------------------------------------------------------------------------
// UI and simulation state
// -------------------------------------------------------------------------
const cedarRow = document.getElementById("cedarRow");
const northRow = document.getElementById("northRow");
const routeTitle = document.getElementById("routeTitle");
const routeBadge = document.getElementById("routeBadge");
const routeDistance = document.getElementById("routeDistance");
const routeDelay = document.getElementById("routeDelay");
const routePath = document.getElementById("routePath");
const validationText = document.getElementById("validationText");
const pauseButton = document.getElementById("pauseButton");
function crossingStateElement(id, closed) {
const row = id === "cedar" ? cedarRow : northRow;
const state = row.querySelector(".crossing-state");
state.querySelector("b").textContent = closed ? "Closed" : "Open";
state.querySelector("small").textContent = closed ? "Reopen" : "Close";
row.classList.toggle("closed", closed);
row.setAttribute("aria-pressed", String(closed));
const label = id === "cedar" ? cedarLabel : northLabel;
label.classList.toggle("closed", closed);
label.querySelector("b").textContent = closed ? "CLOSED" : "OPEN";
}
function updateUI() {
const cedarClosed = simulationState.closedBridge === "cedar";
const northClosed = simulationState.closedBridge === "north";
crossingStateElement("cedar", cedarClosed);
crossingStateElement("north", northClosed);
const valid = validateRoute(currentRoute);
const extraUnits = currentRoute
? Math.max(0, currentRoute.length - baseRoute.length)
: 0;
const kilometers = currentRoute ? currentRoute.length * 0.065 : 0;
const extraMinutes = Math.max(1, Math.round(extraUnits * 0.7));
routeDistance.textContent = `${kilometers.toFixed(1)} km`;
routeDelay.textContent = simulationState.closedBridge
? `+${extraMinutes} min`
: "On time";
const routeBridge = currentRoute?.edges.find((edge) => edge.bridge)?.bridge;
const crossingName = routeBridge ? bridges[routeBridge].name : "no crossing";
if (simulationState.closedBridge) {
routeTitle.textContent = "Short detour active";
routeBadge.textContent = "Detour";
routeBadge.classList.add("detour");
routePath.textContent =
`Riverside Depot → Westbank Road → ${crossingName} → Eastbank Road → Market District`;
} else {
routeTitle.textContent = "Shortest route active";
routeBadge.textContent = "Optimal";
routeBadge.classList.remove("detour");
routePath.textContent =
`Riverside Depot → Westbank Road → ${crossingName} → Eastbank Road → Market District`;
}
validationText.textContent = valid
? "Route verified: all segments stay on land or approved bridges."
: "No valid crossing remains. Reopen a bridge to restore service.";
}
function recomputeRoute(resetTraffic = true) {
currentRoute = findPath(simulationState.closedBridge);
rebuildRouteGeometry();
resetVehicles(resetTraffic);
updateUI();
}
let toastTimer;
function showToast(message) {
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 2600);
}
function toggleBridge(id) {
if (simulationState.closedBridge === id) {
simulationState.closedBridge = null;
showToast(`${bridges[id].name} reopened. The shortest route is restored.`);
} else {
simulationState.closedBridge = id;
showToast(
`${bridges[id].name} closed. Traffic is using the other approved crossing.`
);
}
recomputeRoute(true);
}
cedarRow.addEventListener("click", () => toggleBridge("cedar"));
northRow.addEventListener("click", () => toggleBridge("north"));
function togglePause() {
simulationState.paused = !simulationState.paused;
pauseButton.textContent = simulationState.paused
? "Resume traffic"
: "Pause traffic";
}
pauseButton.addEventListener("click", togglePause);
// -------------------------------------------------------------------------
// Direct camera controls (no addons)
// -------------------------------------------------------------------------
const pointers = new Map();
let dragDistance = 0;
function pinchDistance() {
if (pointers.size < 2) return null;
const values = [...pointers.values()];
return Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
dragDistance = 0;
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointers.has(event.pointerId)) return;
const previous = pointers.get(event.pointerId);
const oldPinch = pinchDistance();
const dx = event.clientX - previous.x;
const dy = event.clientY - previous.y;
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
dragDistance += Math.hypot(dx, dy);
if (pointers.size === 1) {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.52,
1.3
);
} else if (pointers.size === 2) {
const newPinch = pinchDistance();
if (oldPinch && newPinch) {
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * (oldPinch / newPinch),
45,
112
);
}
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
const wasClick = dragDistance < 6;
pointers.delete(event.pointerId);
if (wasClick) pickBridge(event);
});
renderer.domElement.addEventListener("pointercancel", (event) => {
pointers.delete(event.pointerId);
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
45,
112
);
},
{ passive: false }
);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function pickBridge(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hit = raycaster.intersectObjects(pickMeshes, false)[0];
if (hit?.object.userData.bridgeId) {
toggleBridge(hit.object.userData.bridgeId);
}
}
function resetCamera() {
cameraState.theta = 0.56;
cameraState.phi = 0.96;
cameraState.radius = 84;
cameraState.target.set(0, 0, 1);
}
document.getElementById("cameraButton").addEventListener("click", resetCamera);
window.addEventListener("keydown", (event) => {
if (event.code === "Space") {
event.preventDefault();
togglePause();
} else if (event.key.toLowerCase() === "r") {
resetCamera();
} else if (event.key === "1") {
toggleBridge("cedar");
} else if (event.key === "2") {
toggleBridge("north");
}
});
// -------------------------------------------------------------------------
// Resize and animation loop
// -------------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
const clock = new THREE.Clock();
let elapsed = 0;
function animate() {
const delta = Math.min(clock.getDelta(), 0.05);
if (!simulationState.paused) elapsed += delta;
updateCamera();
for (const bridge of Object.values(bridges)) {
const target = simulationState.closedBridge === bridge.id ? 1 : 0;
bridge.closedMix = THREE.MathUtils.lerp(
bridge.closedMix,
target,
1 - Math.exp(-delta * 8)
);
bridge.mark.scale.setScalar(Math.max(0.001, bridge.closedMix));
bridge.mark.visible = bridge.closedMix > 0.01;
const openColor = new THREE.Color(0xc99257);
const closedColor = new THREE.Color(0x80564e);
bridge.deckMaterial.color.copy(openColor).lerp(closedColor, bridge.closedMix);
}
if (currentRoute && routeSegments.length) {
vehicles.forEach((vehicle) => {
if (vehicle.spawnDelay > 0) {
vehicle.spawnDelay -= delta;
vehicle.group.scale.setScalar(0.01);
return;
}
vehicle.group.scale.lerp(
new THREE.Vector3(1, 1, 1),
1 - Math.exp(-delta * 10)
);
vehicle.distance += vehicle.speed * delta;
const sample = sampleRoute(vehicle.distance);
if (sample) {
vehicle.group.position.set(sample.x, sample.y, sample.z);
vehicle.group.rotation.y = -Math.atan2(
sample.directionZ,
sample.directionX
);
}
});
const pulseSample = sampleRoute(elapsed * 4.5);
if (pulseSample) {
guidePulse.visible = true;
guidePulse.position.set(
pulseSample.x,
pulseSample.y + 0.2,
pulseSample.z
);
const pulseScale = 0.9 + Math.sin(elapsed * 6) * 0.18;
guidePulse.scale.setScalar(pulseScale);
}
} else {
guidePulse.visible = false;
}
positionLabel(cedarLabel, labelPositions.cedar);
positionLabel(northLabel, labelPositions.north);
positionLabel(originLabel, labelPositions.origin);
positionLabel(destinationLabel, labelPositions.destination);
renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);
recomputeRoute(false);
document.getElementById("loading").classList.add("hidden");
setTimeout(() => {
showToast("Cedar Bridge is closed. The network is using North Bridge.");
}, 650);
</script>
</body>
</html>
```