Prompt specification
Build or customize the Three.js 3D scene "Compare walking routes across bridges and waterfront paths" 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: Compare walking routes across bridges and waterfront paths
Category: Architecture & Cities · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/compare-walking-routes-across-bridges-and-waterfront-p-x2696
Scene Description Prompt:
Please use Three.js from cdnjs for a low-poly scene based on this idea: Compare walking routes across bridges and waterfront paths. Let users choose destinations in a schematic Recife Antigo fragment. Trace valid routes along modeled crossings and show why apparent proximity across water can still require a detour. Return one self-contained HTML file.
Working Three.js Starter (compare-walking-routes-across-bridges-and-waterfront-p-x2696):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Recife Antigo — Walking Routes Across Water</title>
<style>
:root {
--ink: #102b36;
--panel: rgba(10, 31, 41, 0.94);
--panel-soft: rgba(18, 48, 60, 0.88);
--line: rgba(255, 255, 255, 0.13);
--text: #f5f1e8;
--muted: #a9c0c6;
--quick: #ff704d;
--water: #31d1b7;
--crossing: #f4ca67;
--water-blue: #76cbd0;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #78bfc6;
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, select { font: inherit; }
#scene-wrap,
#scene-wrap canvas,
#labels {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
}
#scene-wrap canvas {
display: block;
outline: none;
cursor: grab;
touch-action: none;
}
#scene-wrap canvas:active { cursor: grabbing; }
#labels {
pointer-events: none;
overflow: hidden;
z-index: 3;
}
#panel {
position: absolute;
z-index: 10;
top: 18px;
left: 18px;
width: 350px;
max-height: calc(100vh - 36px);
overflow-y: auto;
padding: 20px;
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 20px;
background: var(--panel);
box-shadow: 0 22px 70px rgba(7, 35, 43, 0.28);
backdrop-filter: blur(18px);
scrollbar-width: thin;
scrollbar-color: rgba(255, 255, 255, 0.2) transparent;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 7px;
color: #8fded1;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--water);
box-shadow: 0 0 0 5px rgba(49, 209, 183, 0.11);
}
h1 {
margin: 0;
font-size: 26px;
line-height: 1.08;
letter-spacing: -0.035em;
}
.intro {
margin: 10px 0 18px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.field-grid {
display: grid;
grid-template-columns: 1fr 36px 1fr;
gap: 8px;
align-items: end;
}
.field label {
display: block;
margin: 0 0 7px;
color: #9db5bd;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
select {
width: 100%;
height: 42px;
padding: 0 32px 0 11px;
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 10px;
outline: none;
background: #173744;
color: var(--text);
font-size: 12px;
font-weight: 650;
cursor: pointer;
}
select:focus { border-color: var(--water); }
#swap {
display: grid;
place-items: center;
width: 36px;
height: 42px;
padding: 0;
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 10px;
background: #173744;
color: #cde5e5;
cursor: pointer;
transition: 160ms ease;
}
#swap:hover {
color: white;
background: #214957;
transform: translateY(-1px);
}
.rule-note {
display: flex;
align-items: center;
gap: 8px;
margin-top: 10px;
padding: 9px 11px;
border-radius: 9px;
background: rgba(255, 112, 77, 0.09);
color: #ffc0ad;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.035em;
}
.rule-note span {
display: inline-grid;
place-items: center;
width: 17px;
height: 17px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--quick);
color: white;
font-size: 11px;
font-weight: 900;
}
.section-heading {
display: flex;
justify-content: space-between;
align-items: center;
margin: 19px 0 9px;
color: #bad0d5;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.section-heading small {
color: #6f919b;
font-size: 9px;
letter-spacing: 0.04em;
text-transform: none;
}
#route-list {
display: grid;
gap: 7px;
}
.route-card {
position: relative;
width: 100%;
padding: 11px 12px 10px 16px;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.035);
color: var(--text);
text-align: left;
cursor: pointer;
transition: 160ms ease;
}
.route-card::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 4px;
background: var(--route-color);
opacity: 0.65;
}
.route-card:hover {
border-color: rgba(255, 255, 255, 0.25);
background: rgba(255, 255, 255, 0.065);
}
.route-card.selected {
border-color: var(--route-color);
background: rgba(255, 255, 255, 0.075);
box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--route-color), transparent 72%);
}
.route-card.selected::before { opacity: 1; }
.route-top {
display: flex;
justify-content: space-between;
gap: 8px;
align-items: baseline;
}
.route-name {
font-size: 12px;
font-weight: 800;
}
.route-time {
color: white;
font-size: 13px;
font-weight: 800;
white-space: nowrap;
}
.route-meta {
display: flex;
gap: 9px;
margin-top: 5px;
color: var(--muted);
font-size: 10px;
}
.route-meta span + span::before {
content: "·";
margin-right: 9px;
color: #66858f;
}
#insight {
margin-top: 15px;
padding: 14px;
border: 1px solid rgba(118, 203, 208, 0.19);
border-radius: 12px;
background: linear-gradient(145deg, rgba(30, 71, 83, 0.82), rgba(18, 48, 60, 0.65));
}
#insight h2 {
margin: 0 0 8px;
font-size: 13px;
letter-spacing: -0.01em;
}
#insight p {
margin: 0;
color: #bcd0d5;
font-size: 11px;
line-height: 1.55;
}
.stat-strip {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin-top: 12px;
}
.stat {
padding: 8px 7px;
border-radius: 8px;
background: rgba(4, 24, 31, 0.25);
text-align: center;
}
.stat strong {
display: block;
font-size: 13px;
color: white;
}
.stat span {
display: block;
margin-top: 2px;
color: #87a8b1;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.panel-note {
margin: 13px 2px 0;
color: #72929b;
font-size: 9px;
line-height: 1.45;
}
#map-meta {
position: absolute;
z-index: 5;
top: 20px;
right: 20px;
display: flex;
align-items: center;
gap: 10px;
padding: 10px 13px;
border: 1px solid rgba(255, 255, 255, 0.22);
border-radius: 999px;
background: rgba(13, 47, 56, 0.78);
color: #e7f4ef;
box-shadow: 0 8px 25px rgba(11, 47, 56, 0.12);
backdrop-filter: blur(10px);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.live-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--water);
box-shadow: 0 0 0 4px rgba(49, 209, 183, 0.13);
}
#reset {
position: absolute;
z-index: 5;
right: 20px;
bottom: 72px;
width: 39px;
height: 39px;
border: 1px solid rgba(255, 255, 255, 0.25);
border-radius: 50%;
background: rgba(13, 47, 56, 0.82);
color: white;
cursor: pointer;
box-shadow: 0 8px 24px rgba(11, 47, 56, 0.18);
backdrop-filter: blur(8px);
font-size: 19px;
}
#legend {
position: absolute;
z-index: 5;
right: 20px;
bottom: 20px;
display: flex;
gap: 13px;
padding: 9px 12px;
border-radius: 10px;
background: rgba(13, 47, 56, 0.78);
color: #d6e7e7;
backdrop-filter: blur(10px);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.035em;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.legend-line {
width: 16px;
height: 3px;
border-radius: 3px;
background: var(--quick);
}
.legend-line.water { background: var(--water); }
.legend-line.crossing { background: var(--crossing); }
.legend-water {
width: 16px;
height: 8px;
border-radius: 2px;
background: #62bac4;
}
#hint {
position: absolute;
z-index: 5;
left: 390px;
bottom: 20px;
padding: 8px 11px;
border-radius: 8px;
background: rgba(13, 47, 56, 0.7);
color: rgba(235, 246, 245, 0.86);
backdrop-filter: blur(8px);
font-size: 9px;
letter-spacing: 0.035em;
pointer-events: none;
}
.poi-label {
position: absolute;
transform: translate(-50%, calc(-100% - 10px));
padding: 6px 8px;
border: 1px solid rgba(255, 255, 255, 0.54);
border-radius: 7px;
background: rgba(255, 251, 239, 0.91);
color: #183844;
box-shadow: 0 4px 12px rgba(22, 66, 70, 0.14);
font-size: 9px;
font-weight: 800;
white-space: nowrap;
pointer-events: auto;
cursor: pointer;
transition: 140ms ease;
}
.poi-label::after {
content: "";
position: absolute;
left: 50%;
bottom: -5px;
width: 8px;
height: 8px;
border-right: 1px solid rgba(255, 255, 255, 0.54);
border-bottom: 1px solid rgba(255, 255, 255, 0.54);
background: rgba(255, 251, 239, 0.91);
transform: translateX(-50%) rotate(45deg);
}
.poi-label:hover {
z-index: 8;
color: #0c4b54;
transform: translate(-50%, calc(-100% - 13px)) scale(1.04);
}
.poi-label.origin {
border-color: var(--quick);
box-shadow: 0 0 0 2px rgba(255, 112, 77, 0.18);
}
.poi-label.destination {
border-color: var(--water);
box-shadow: 0 0 0 2px rgba(49, 209, 183, 0.18);
}
.crossing-label,
.area-label,
#direct-label {
position: absolute;
transform: translate(-50%, -50%);
pointer-events: none;
white-space: nowrap;
}
.crossing-label {
padding: 3px 6px;
border-radius: 5px;
background: rgba(21, 58, 65, 0.84);
color: #fff4d4;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.04em;
opacity: 0.8;
}
.crossing-label.active {
background: #fff4d4;
color: #26444a;
opacity: 1;
}
.area-label {
color: rgba(255, 255, 255, 0.66);
font-size: 11px;
font-weight: 850;
letter-spacing: 0.16em;
text-shadow: 0 1px 4px rgba(22, 73, 80, 0.24);
}
#direct-label {
padding: 5px 7px;
border: 1px dashed rgba(255, 255, 255, 0.9);
border-radius: 6px;
background: rgba(196, 69, 45, 0.8);
color: white;
font-size: 8px;
font-weight: 850;
letter-spacing: 0.08em;
}
#loading {
position: absolute;
z-index: 30;
inset: 0;
display: grid;
place-items: center;
background: #74bdc4;
color: #173c47;
font-size: 12px;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
transition: opacity 350ms ease;
}
#loading.hidden { opacity: 0; pointer-events: none; }
@media (max-width: 800px) {
#panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 49vh;
padding: 15px;
border-radius: 16px;
}
h1 { font-size: 21px; }
.intro { margin-bottom: 12px; }
#map-meta { top: 10px; right: 10px; }
#hint { display: none; }
#legend { right: 10px; bottom: auto; top: 57px; }
#reset { right: 10px; top: 101px; bottom: auto; }
.poi-label { font-size: 8px; }
}
</style>
</head>
<body>
<div id="scene-wrap">
<canvas id="scene" tabindex="0" aria-label="Interactive schematic map of Recife Antigo"></canvas>
</div>
<div id="labels"></div>
<aside id="panel" aria-label="Walking route controls">
<div class="eyebrow">Schematic route study</div>
<h1>Recife Antigo<br />on foot</h1>
<p class="intro">
Compare connected walking routes across old-town streets, quays, and modeled river crossings.
Click a place label to make it your destination.
</p>
<div class="field-grid">
<div class="field">
<label for="start-select">Start</label>
<select id="start-select"></select>
</div>
<button id="swap" type="button" title="Swap start and destination" aria-label="Swap start and destination">↕</button>
<div class="field">
<label for="end-select">Destination</label>
<select id="end-select"></select>
</div>
</div>
<div class="rule-note">
<span>!</span>
WATER IS NOT WALKABLE — ONLY MODELED CROSSINGS COUNT
</div>
<div class="section-heading">
<span>Compare routes</span>
<small>3 valid paths</small>
</div>
<div id="route-list"></div>
<section id="insight" aria-live="polite">
<h2>Why the route bends</h2>
<p></p>
<div class="stat-strip"></div>
</section>
<p class="panel-note">
Illustrative geometry and route graph, not turn-by-turn navigation. Distances and crossing
names are schematic and intended to explain network distance versus apparent proximity.
</p>
</aside>
<div id="map-meta"><span class="live-dot"></span> Live route graph</div>
<button id="reset" type="button" title="Reset camera" aria-label="Reset camera">⌂</button>
<div id="legend">
<div class="legend-item"><span class="legend-line"></span> Quickest</div>
<div class="legend-item"><span class="legend-line water"></span> Waterfront</div>
<div class="legend-item"><span class="legend-water"></span> Water</div>
</div>
<div id="hint">Drag to orbit · Shift-drag to pan · Scroll to zoom · Click a place to set destination</div>
<div id="loading">Building Recife Antigo…</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (selector) => document.querySelector(selector);
const canvas = $("#scene");
const labelsRoot = $("#labels");
const startSelect = $("#start-select");
const endSelect = $("#end-select");
const routeList = $("#route-list");
const insightTitle = $("#insight h2");
const insightText = $("#insight p");
const statStrip = $("#insight .stat-strip");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x86c8cb);
scene.fog = new THREE.Fog(0x86c8cb, 27, 55);
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraState = {
target: new THREE.Vector3(0.4, 0, 0.4),
desiredTarget: new THREE.Vector3(0.4, 0, 0.4),
theta: 0.72,
desiredTheta: 0.72,
phi: 0.92,
desiredPhi: 0.92,
radius: 25,
desiredRadius: 25
};
function updateCamera(dt = 1) {
const ease = 1 - Math.pow(0.001, dt);
cameraState.theta += (cameraState.desiredTheta - cameraState.theta) * ease;
cameraState.phi += (cameraState.desiredPhi - cameraState.phi) * ease;
cameraState.radius += (cameraState.desiredRadius - cameraState.radius) * ease;
cameraState.target.lerp(cameraState.desiredTarget, ease);
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(1);
const hemi = new THREE.HemisphereLight(0xe8ffff, 0x627f70, 2.25);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff2d2, 3.3);
sun.position.set(-9, 17, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -18;
sun.shadow.camera.right = 18;
sun.shadow.camera.top = 18;
sun.shadow.camera.bottom = -18;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 45;
sun.shadow.bias = -0.0005;
scene.add(sun);
const warmFill = new THREE.DirectionalLight(0xffb88d, 0.7);
warmFill.position.set(12, 7, -12);
scene.add(warmFill);
let randomSeed = 8127;
function random() {
randomSeed |= 0;
randomSeed = (randomSeed + 0x6D2B79F5) | 0;
let t = Math.imul(randomSeed ^ (randomSeed >>> 15), 1 | randomSeed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
const lands = [
{
id: "main",
name: "RECIFE ANTIGO",
points: [
[-9.2, -7.1], [-2.5, -7.1], [-1.2, -4.5], [-1.0, -2.0],
[-1.2, 0.0], [-0.7, 2.2], [-1.8, 4.4], [-3.3, 5.5],
[-8.0, 5.1], [-10.0, 2.0]
]
},
{
id: "island",
name: "BAIRRO DA MOEDA",
points: [
[2.0, -4.2], [7.8, -3.5], [9.0, -0.5], [7.8, 3.4],
[3.1, 4.3], [1.4, 2.4], [1.5, 0.0], [1.5, -2.0]
]
},
{
id: "south",
name: "BOA VIAGEM",
points: [
[-8.0, 6.5], [-3.8, 6.2], [-2.7, 5.6], [-0.6, 5.8],
[0.7, 7.0], [0.4, 9.0], [-7.5, 9.0], [-9.3, 7.5]
]
}
];
const landById = Object.fromEntries(lands.map((land) => [land.id, land]));
function pointInPolygon(x, z, polygon) {
let inside = false;
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
const xi = polygon[i][0], zi = polygon[i][1];
const xj = polygon[j][0], zj = polygon[j][1];
const intersects = ((zi > z) !== (zj > z)) &&
(x < ((xj - xi) * (z - zi)) / (zj - zi) + xi);
if (intersects) inside = !inside;
}
return inside;
}
function distanceToSegment(x, z, ax, az, bx, bz) {
const dx = bx - ax, dz = bz - az;
const denom = dx * dx + dz * dz;
const t = denom ? THREE.MathUtils.clamp(((x - ax) * dx + (z - az) * dz) / denom, 0, 1) : 0;
return Math.hypot(x - (ax + t * dx), z - (az + t * dz));
}
function distanceToLandEdge(x, z, land) {
let distance = Infinity;
for (let i = 0; i < land.points.length; i++) {
const a = land.points[i];
const b = land.points[(i + 1) % land.points.length];
distance = Math.min(distance, distanceToSegment(x, z, a[0], a[1], b[0], b[1]));
}
return distance;
}
const nodes = {
mkt: { name: "Mercado do Recife", x: -7.4, z: -5.2, zone: "main" },
m1: { name: "Rua da Moeda", x: -5.0, z: -5.8, zone: "main" },
m2: { name: "Largo do Recife", x: -3.0, z: -5.2, zone: "main" },
m3: { name: "Travessa do Sol", x: -1.7, z: -4.3, zone: "main" },
marco: { name: "Praça do Marco Zero", x: -1.35, z: -2.3, zone: "main" },
plaza: { name: "Praça da República", x: -4.2, z: -1.0, zone: "main" },
paco: { name: "Paço Alfândega", x: -7.6, z: 1.4, zone: "main" },
p2: { name: "Rua da Moeda", x: -5.0, z: 2.2, zone: "main" },
p3: { name: "Beco do Carnival", x: -3.0, z: 3.4, zone: "main" },
capela:{ name: "Capela dos Remédios", x: -5.4, z: 4.8, zone: "main" },
m4: { name: "Cais de São Francisco",x: -2.2, z: 4.8, zone: "main" },
bR: { name: "West end of bridge", x: -0.75, z: -2.3, zone: "main" },
bE: { name: "South bridge landing", x: -0.65, z: 2.4, zone: "main" },
bS: { name: "South bridge landing", x: -1.0, z: 4.7, zone: "main" },
bR2: { name: "East end of bridge", x: 1.75, z: -2.3, zone: "island" },
moeda: { name: "Rua da Moeda", x: 3.2, z: -2.7, zone: "island" },
remdios:{name: "Remédios waterfront", x: 5.4, z: -3.0, zone: "island" },
museu: { name: "Museu do Carnaval", x: 5.0, z: 0.0, zone: "island" },
ribeira:{name: "Casa da Ribeira", x: 7.4, z: 2.6, zone: "island" },
i2: { name: "Cais da Moeda", x: 3.3, z: 3.5, zone: "island" },
bE2: { name: "North bridge landing", x: 1.6, z: 2.4, zone: "island" },
bS2: { name: "Boa Viagem landing", x: -1.4, z: 6.4, zone: "south" },
s2: { name: "Cais da Praia", x: -3.8, z: 7.5, zone: "south" },
boa: { name: "Mercado da Boa Viagem",x: -6.8, z: 8.0, zone: "south" },
fortim:{ name: "Fortim de Santa Cruz", x: -0.5, z: 8.1, zone: "south" }
};
const poiOrder = [
"marco", "mkt", "paco", "capela", "moeda",
"museu", "ribeira", "boa", "fortim"
];
const edges = [
{ a: "mkt", b: "m1", type: "street" },
{ a: "m1", b: "m2", type: "quay" },
{ a: "m2", b: "m3", type: "quay" },
{ a: "m3", b: "marco", type: "street" },
{ a: "marco", b: "bR", type: "street" },
{ a: "marco", b: "plaza", type: "street" },
{ a: "plaza", b: "mkt", type: "street" },
{ a: "plaza", b: "paco", type: "street" },
{ a: "paco", b: "p2", type: "quay" },
{ a: "p2", b: "plaza", type: "street" },
{ a: "p2", b: "p3", type: "street" },
{ a: "p3", b: "capela", type: "street" },
{ a: "capela", b: "m4", type: "quay" },
{ a: "capela", b: "p3", type: "street" },
{ a: "m4", b: "p3", type: "street" },
{ a: "m4", b: "bS", type: "street" },
{ a: "bE", b: "p2", type: "street" },
{ a: "bR2", b: "moeda", type: "quay" },
{ a: "moeda", b: "remdios", type: "quay" },
{ a: "remdios", b: "museu", type: "quay" },
{ a: "moeda", b: "museu", type: "street" },
{ a: "museu", b: "ribeira", type: "street" },
{ a: "ribeira", b: "i2", type: "quay" },
{ a: "i2", b: "bE2", type: "quay" },
{ a: "bR2", b: "bE2", type: "quay" },
{ a: "bS2", b: "s2", type: "quay" },
{ a: "s2", b: "boa", type: "quay" },
{ a: "boa", b: "fortim", type: "quay" },
{ a: "bS2", b: "fortim", type: "street" },
{
a: "bR", b: "bR2", type: "bridge", name: "Ponte das Janelas"
},
{
a: "bE", b: "bE2", type: "bridge", name: "Ponte da Moeda"
},
{
a: "bS", b: "bS2", type: "bridge", name: "Ponte do Recife"
}
];
const graph = new Map();
for (const edge of edges) {
const a = nodes[edge.a], b = nodes[edge.b];
const length = Math.hypot(a.x - b.x, a.z - b.z);
edge.length = length;
if (!graph.has(edge.a)) graph.set(edge.a, []);
if (!graph.has(edge.b)) graph.set(edge.b, []);
graph.get(edge.a).push({ node: edge.b, edge });
graph.get(edge.b).push({ node: edge.a, edge });
}
function routeWeight(edge, mode) {
if (mode === "water") {
if (edge.type === "street") return edge.length * 1.8;
if (edge.type === "quay") return edge.length * 0.95;
}
if (mode === "crossings") {
return edge.length + (edge.type === "bridge" ? 10000 : 0);
}
return edge.length;
}
function dijkstra(start, end, mode) {
const distances = new Map(Object.keys(nodes).map((id) => [id, Infinity]));
const previous = new Map();
const remaining = new Set(Object.keys(nodes));
distances.set(start, 0);
while (remaining.size) {
let current = null;
let best = Infinity;
for (const id of remaining) {
if (distances.get(id) < best) {
best = distances.get(id);
current = id;
}
}
if (current === null || current === end) break;
remaining.delete(current);
for (const neighbor of graph.get(current) || []) {
const nextDistance = distances.get(current) + routeWeight(neighbor.edge, mode);
if (nextDistance < distances.get(neighbor.node)) {
distances.set(neighbor.node, nextDistance);
previous.set(neighbor.node, {
from: current,
edge: neighbor.edge
});
}
}
}
if (!Number.isFinite(distances.get(end))) return null;
const path = [end];
const pathEdges = [];
let cursor = end;
while (cursor !== start) {
const step = previous.get(cursor);
if (!step) return null;
pathEdges.unshift(step.edge);
cursor = step.from;
path.unshift(cursor);
}
const length = pathEdges.reduce((sum, edge) => sum + edge.length, 0);
const quayLength = pathEdges
.filter((edge) => edge.type === "quay")
.reduce((sum, edge) => sum + edge.length, 0);
const bridgeEdges = pathEdges.filter((edge) => edge.type === "bridge");
return {
path,
edges: pathEdges,
length,
crossings: bridgeEdges.length,
crossingNames: [...new Set(bridgeEdges.map((edge) => edge.name))],
quayPct: length ? Math.round((quayLength / length) * 100) : 0
};
}
// Low-poly water.
const waterGeometry = new THREE.PlaneGeometry(55, 55, 20, 20);
const waterPosition = waterGeometry.attributes.position;
const waterColors = [];
const waterColor = new THREE.Color();
for (let i = 0; i < waterPosition.count; i++) {
const x = waterPosition.getX(i);
const y = waterPosition.getY(i);
waterPosition.setZ(i, (random() - 0.5) * 0.075);
const tint = 0.91 + random() * 0.12;
waterColor.setRGB(0.29 * tint, 0.64 * tint, 0.69 * tint);
waterColors.push(waterColor.r, waterColor.g, waterColor.b);
}
waterGeometry.setAttribute("color", new THREE.Float32BufferAttribute(waterColors, 3));
waterGeometry.computeVertexNormals();
const water = new THREE.Mesh(
waterGeometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.8,
metalness: 0.03,
flatShading: true
})
);
water.rotation.x = -Math.PI / 2;
water.position.y = -0.08;
water.receiveShadow = true;
scene.add(water);
// Extruded land fragments.
const landTopMaterial = new THREE.MeshStandardMaterial({
color: 0xdacda9,
roughness: 0.96,
flatShading: true
});
const landSideMaterial = new THREE.MeshStandardMaterial({
color: 0xa99570,
roughness: 1,
flatShading: true
});
for (const land of lands) {
const shape = new THREE.Shape();
land.points.forEach(([x, z], index) => {
if (index === 0) shape.moveTo(x, -z);
else shape.lineTo(x, -z);
});
shape.closePath();
const geometry = new THREE.ExtrudeGeometry(shape, {
depth: 0.55,
bevelEnabled: false,
steps: 1
});
geometry.rotateX(-Math.PI / 2);
const mesh = new THREE.Mesh(geometry, [landTopMaterial, landSideMaterial]);
mesh.position.y = -0.04;
mesh.receiveShadow = true;
mesh.castShadow = true;
scene.add(mesh);
const outlinePoints = land.points.map(([x, z]) => new THREE.Vector3(x, 0.535, z));
outlinePoints.push(outlinePoints[0].clone());
const outline = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(outlinePoints),
new THREE.LineBasicMaterial({ color: 0xf3e6c7, transparent: true, opacity: 0.9 })
);
scene.add(outline);
}
function orientation(ax, az, bx, bz) {
return Math.atan2(-(bz - az), bx - ax);
}
function addBoxBetween(ax, ay, az, bx, by, bz, width, height, material, yOffset = 0) {
const dx = bx - ax, dz = bz - az;
const length = Math.hypot(dx, dz);
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(length, height, width),
material
);
mesh.position.set((ax + bx) / 2, (ay + by) / 2 + yOffset, (az + bz) / 2);
mesh.rotation.y = orientation(ax, az, bx, bz);
mesh.receiveShadow = true;
mesh.castShadow = true;
scene.add(mesh);
return mesh;
}
const streetMaterial = new THREE.MeshStandardMaterial({
color: 0xf0e3c8,
roughness: 0.95
});
const quayMaterial = new THREE.MeshStandardMaterial({
color: 0xd8ad72,
roughness: 0.95
});
const bridgeMaterial = new THREE.MeshStandardMaterial({
color: 0x8c5c40,
roughness: 0.85
});
const railMaterial = new THREE.MeshStandardMaterial({
color: 0xe0c38c,
roughness: 0.8
});
const supportMaterial = new THREE.MeshStandardMaterial({
color: 0x6b5948,
roughness: 1
});
for (const edge of edges) {
const a = nodes[edge.a], b = nodes[edge.b];
if (edge.type === "bridge") {
addBoxBetween(a.x, 0.68, a.z, b.x, 0.68, b.z, 0.46, 0.13, bridgeMaterial);
const dx = b.x - a.x, dz = b.z - a.z;
const length = Math.hypot(dx, dz);
const nx = -dz / length, nz = dx / length;
for (const side of [-1, 1]) {
const ox = nx * 0.22 * side;
const oz = nz * 0.22 * side;
addBoxBetween(
a.x + ox, 0.84, a.z + oz,
b.x + ox, 0.84, b.z + oz,
0.055, 0.12, railMaterial
);
}
for (const t of [0.25, 0.5, 0.75]) {
const x = THREE.MathUtils.lerp(a.x, b.x, t);
const z = THREE.MathUtils.lerp(a.z, b.z, t);
const support = new THREE.Mesh(
new THREE.BoxGeometry(0.14, 0.72, 0.48),
supportMaterial
);
support.position.set(x, 0.28, z);
support.rotation.y = orientation(a.x, a.z, b.x, b.z);
support.castShadow = true;
scene.add(support);
}
} else {
addBoxBetween(
a.x, 0.555, a.z, b.x, 0.555, b.z,
edge.type === "quay" ? 0.15 : 0.19,
0.035,
edge.type === "quay" ? quayMaterial : streetMaterial
);
}
}
// Deterministic low-poly buildings, kept away from the route graph.
const buildingPalette = [
0xf0e0c2, 0xe8b28e, 0xc97e63, 0xf1c982,
0xb8d0c3, 0xd5dfd4, 0xe9c9ae, 0xb9c9cf
];
const roofPalette = [
0x9f5544, 0x7e5148, 0x607d78, 0xb47c55, 0x556f79
];
function nearGraph(x, z, margin = 0.42) {
return edges.some((edge) => {
const a = nodes[edge.a], b = nodes[edge.b];
return distanceToSegment(x, z, a.x, a.z, b.x, b.z) < margin;
});
}
function nearPOI(x, z, margin = 0.72) {
return poiOrder.some((id) => {
const node = nodes[id];
return Math.hypot(x - node.x, z - node.z) < margin;
});
}
for (const land of lands) {
const xs = land.points.map((point) => point[0]);
const zs = land.points.map((point) => point[1]);
const minX = Math.min(...xs), maxX = Math.max(...xs);
const minZ = Math.min(...zs), maxZ = Math.max(...zs);
let placed = 0;
for (let attempt = 0; attempt < 220 && placed < 22; attempt++) {
const x = THREE.MathUtils.lerp(minX, maxX, random());
const z = THREE.MathUtils.lerp(minZ, maxZ, random());
if (!pointInPolygon(x, z, land.points)) continue;
if (distanceToLandEdge(x, z, land) < 0.38) continue;
if (nearGraph(x, z, 0.44) || nearPOI(x, z, 0.72)) continue;
const width = 0.42 + random() * 0.45;
const depth = 0.4 + random() * 0.43;
const height = 0.3 + random() * 0.8;
const building = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
new THREE.MeshStandardMaterial({
color: buildingPalette[Math.floor(random() * buildingPalette.length)],
roughness: 0.93,
flatShading: true
})
);
building.position.set(x, 0.54 + height / 2, z);
building.rotation.y = (random() - 0.5) * 0.22;
building.castShadow = true;
building.receiveShadow = true;
scene.add(building);
const roof = new THREE.Mesh(
new THREE.ConeGeometry(Math.max(width, depth) * 0.72, 0.24, 4),
new THREE.MeshStandardMaterial({
color: roofPalette[Math.floor(random() * roofPalette.length)],
roughness: 1,
flatShading: true
})
);
roof.position.set(x, 0.54 + height + 0.11, z);
roof.rotation.y = Math.PI / 4 + (random() - 0.5) * 0.25;
roof.castShadow = true;
scene.add(roof);
placed++;
}
}
// Landmark silhouettes.
function addLandmarkBuilding(node, width, depth, height, color, roofColor) {
const building = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
new THREE.MeshStandardMaterial({ color, roughness: 0.92, flatShading: true })
);
building.position.set(node.x, 0.54 + height / 2, node.z);
building.castShadow = true;
building.receiveShadow = true;
scene.add(building);
const roof = new THREE.Mesh(
new THREE.ConeGeometry(Math.max(width, depth) * 0.76, 0.3, 4),
new THREE.MeshStandardMaterial({ color: roofColor, roughness: 1, flatShading: true })
);
roof.position.set(node.x, 0.54 + height + 0.14, node.z);
roof.rotation.y = Math.PI / 4;
roof.castShadow = true;
scene.add(roof);
}
addLandmarkBuilding(nodes.capela, 0.65, 0.48, 0.7, 0xf5e8c7, 0xa6604d);
addLandmarkBuilding(nodes.museu, 0.85, 0.72, 0.78, 0xe28f68, 0x455f65);
addLandmarkBuilding(nodes.mkt, 0.9, 0.72, 0.62, 0xf1c56f, 0x9e5a47);
addLandmarkBuilding(nodes.boa, 0.85, 0.7, 0.6, 0xe6d5b4, 0x7f5245);
const churchTower = new THREE.Mesh(
new THREE.BoxGeometry(0.25, 1.25, 0.25),
new THREE.MeshStandardMaterial({ color: 0xf5e8c7, roughness: 0.9 })
);
churchTower.position.set(nodes.capela.x - 0.48, 1.16, nodes.capela.z);
churchTower.castShadow = true;
scene.add(churchTower);
const churchRoof = new THREE.Mesh(
new THREE.ConeGeometry(0.23, 0.43, 4),
new THREE.MeshStandardMaterial({ color: 0xa6604d, roughness: 1, flatShading: true })
);
churchRoof.position.set(nodes.capela.x - 0.48, 1.98, nodes.capela.z);
churchRoof.rotation.y = Math.PI / 4;
scene.add(churchRoof);
const fort = new THREE.Mesh(
new THREE.BoxGeometry(0.88, 0.42, 0.65),
new THREE.MeshStandardMaterial({ color: 0xc7b38b, roughness: 1, flatShading: true })
);
fort.position.set(nodes.fortim.x, 0.74, nodes.fortim.z);
fort.castShadow = true;
scene.add(fort);
for (let i = 0; i < 4; i++) {
const tower = new THREE.Mesh(
new THREE.CylinderGeometry(0.13, 0.15, 0.62, 6),
new THREE.MeshStandardMaterial({ color: 0xd8c399, roughness: 1, flatShading: true })
);
const x = nodes.fortim.x + (i % 2 ? 0.43 : -0.43);
const z = nodes.fortim.z + (i < 2 ? -0.32 : 0.32);
tower.position.set(x, 0.83, z);
tower.castShadow = true;
scene.add(tower);
}
// Small quayside trees.
const treeTrunkMaterial = new THREE.MeshStandardMaterial({ color: 0x74543c, roughness: 1 });
const treeLeafMaterials = [
new THREE.MeshStandardMaterial({ color: 0x537e62, roughness: 1, flatShading: true }),
new THREE.MeshStandardMaterial({ color: 0x6f9668, roughness: 1, flatShading: true })
];
for (const land of lands) {
let treeCount = 0;
for (let attempt = 0; attempt < 100 && treeCount < 9; attempt++) {
const x = THREE.MathUtils.lerp(
Math.min(...land.points.map((p) => p[0])),
Math.max(...land.points.map((p) => p[0])),
random()
);
const z = THREE.MathUtils.lerp(
Math.min(...land.points.map((p) => p[1])),
Math.max(...land.points.map((p) => p[1])),
random()
);
if (!pointInPolygon(x, z, land.points)) continue;
if (distanceToLandEdge(x, z, land) > 0.5) continue;
if (nearGraph(x, z, 0.36) || nearPOI(x, z, 0.5)) continue;
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.045, 0.065, 0.28, 5),
treeTrunkMaterial
);
trunk.position.set(x, 0.69, z);
scene.add(trunk);
const crown = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.23 + random() * 0.08, 0),
treeLeafMaterials[treeCount % treeLeafMaterials.length]
);
crown.position.set(x, 0.93, z);
crown.scale.y = 1.18;
crown.castShadow = true;
scene.add(crown);
treeCount++;
}
}
// POI labels and projected scene annotations.
const labelEntries = [];
function projectToScreen(position) {
const projected = position.clone().project(camera);
return {
x: (projected.x * 0.5 + 0.5) * window.innerWidth,
y: (-projected.y * 0.5 + 0.5) * window.innerHeight,
visible: projected.z > -1 && projected.z < 1 &&
projected.x > -1.2 && projected.x < 1.2 &&
projected.y > -1.2 && projected.y < 1.2
};
}
for (const id of poiOrder) {
const node = nodes[id];
const element = document.createElement("button");
element.className = "poi-label";
element.type = "button";
element.textContent = node.name;
element.setAttribute("aria-label", `Set ${node.name} as destination`);
element.addEventListener("click", () => {
endSelect.value = id;
updateRoutes();
});
labelsRoot.appendChild(element);
labelEntries.push({
element,
position: new THREE.Vector3(node.x, 1.28, node.z),
type: "poi",
id
});
}
const bridgeLabels = edges
.filter((edge) => edge.type === "bridge")
.map((edge) => {
const a = nodes[edge.a], b = nodes[edge.b];
const element = document.createElement("div");
element.className = "crossing-label";
element.textContent = edge.name;
labelsRoot.appendChild(element);
return {
element,
position: new THREE.Vector3((a.x + b.x) / 2, 1.14, (a.z + b.z) / 2),
type: "bridge",
name: edge.name
};
});
for (const land of lands) {
const center = land.points.reduce(
(sum, point) => ({ x: sum.x + point[0], z: sum.z + point[1] }),
{ x: 0, z: 0 }
);
center.x /= land.points.length;
center.z /= land.points.length;
const element = document.createElement("div");
element.className = "area-label";
element.textContent = land.name;
labelsRoot.appendChild(element);
labelEntries.push({
element,
position: new THREE.Vector3(center.x, 0.68, center.z),
type: "area"
});
}
const directLabel = document.createElement("div");
directLabel.id = "direct-label";
directLabel.textContent = "DIRECT LINE / OVER WATER";
labelsRoot.appendChild(directLabel);
labelEntries.push({
element: directLabel,
position: new THREE.Vector3(),
type: "direct"
});
function updateProjectedLabels() {
for (const entry of labelEntries) {
const screen = projectToScreen(entry.position);
entry.element.style.display = screen.visible ? "" : "none";
entry.element.style.left = `${screen.x}px`;
entry.element.style.top = `${screen.y}px`;
}
}
// Start and destination markers.
function makeEndpointMarker(color) {
const group = new THREE.Group();
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.28, 0.045, 6, 24),
new THREE.MeshBasicMaterial({ color, depthTest: false })
);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.88;
ring.renderOrder = 20;
group.add(ring);
const pin = new THREE.Mesh(
new THREE.OctahedronGeometry(0.13),
new THREE.MeshBasicMaterial({ color, depthTest: false })
);
pin.position.y = 1.13;
pin.renderOrder = 20;
group.add(pin);
scene.add(group);
return group;
}
const originMarker = makeEndpointMarker(0xff704d);
const destinationMarker = makeEndpointMarker(0x31d1b7);
// Route rendering.
const routeRoot = new THREE.Group();
scene.add(routeRoot);
const unitCylinder = new THREE.CylinderGeometry(1, 1, 1, 6, 1, false);
const up = new THREE.Vector3(0, 1, 0);
const variants = [
{
key: "quick",
name: "Quickest walk",
note: "Shortest connected route",
mode: "quick",
color: 0xff704d
},
{
key: "water",
name: "Waterfront",
note: "Prefers modeled quays",
mode: "water",
color: 0x31d1b7
},
{
key: "crossings",
name: "Fewest crossings",
note: "Minimizes river crossings",
mode: "crossings",
color: 0xf4ca67
}
];
let currentRoutes = {};
let selectedVariant = "quick";
let routeAnimations = [];
let directLine = null;
function buildRouteMesh(route, variant) {
const group = new THREE.Group();
const material = new THREE.MeshBasicMaterial({
color: variant.color,
transparent: true,
opacity: 0.98,
depthTest: false,
depthWrite: false
});
const segments = [];
let cumulative = 0;
for (const edge of route.edges) {
const a = nodes[edge.a], b = nodes[edge.b];
const start = new THREE.Vector3(a.x, 0.98, a.z);
const end = new THREE.Vector3(b.x, 0.98, b.z);
const direction = end.clone().sub(start);
const length = direction.length();
direction.normalize();
const mesh = new THREE.Mesh(unitCylinder, material);
mesh.quaternion.setFromUnitVectors(up, direction);
mesh.position.copy(start);
mesh.scale.set(0.075, 0.001, 0.075);
mesh.renderOrder = 30;
mesh.frustumCulled = false;
group.add(mesh);
segments.push({ mesh, start, direction, length, cumulative });
cumulative += length;
}
group.userData = { material, segments, total: cumulative, radius: 0.075 };
routeRoot.add(group);
return group;
}
function disposeRouteMeshes() {
for (const child of [...routeRoot.children]) {
if (child.userData?.material) child.userData.material.dispose();
routeRoot.remove(child);
}
routeAnimations = [];
}
function updateDirectLine(startId, endId) {
if (directLine) {
scene.remove(directLine);
directLine.geometry.dispose();
directLine.material.dispose();
directLine = null;
}
const start = nodes[startId], end = nodes[endId];
if (start.zone === end.zone) {
directLabel.style.display = "none";
return;
}
const geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(start.x, 1.24, start.z),
new THREE.Vector3(end.x, 1.24, end.z)
]);
const material = new THREE.LineDashedMaterial({
color: 0xffc0ae,
dashSize: 0.18,
gapSize: 0.11,
transparent: true,
opacity: 0.95,
depthTest: false,
depthWrite: false
});
directLine = new THREE.Line(geometry, material);
directLine.computeLineDistances();
directLine.renderOrder = 35;
scene.add(directLine);
const directEntry = labelEntries.find((entry) => entry.type === "direct");
directEntry.position.set((start.x + end.x) / 2, 1.37, (start.z + end.z) / 2);
directLabel.style.display = "";
}
function formatDistance(meters) {
if (meters < 1000) return `${Math.round(meters / 5) * 5} m`;
return `${(meters / 1000).toFixed(2)} km`;
}
function renderRouteCards() {
routeList.innerHTML = "";
for (const variant of variants) {
const route = currentRoutes[variant.key];
const card = document.createElement("button");
card.type = "button";
card.className = `route-card${selectedVariant === variant.key ? " selected" : ""}`;
card.style.setProperty("--route-color", `#${variant.color.toString(16).padStart(6, "0")}`);
card.dataset.route = variant.key;
const meters = route.length * 80;
const minutes = Math.max(1, Math.ceil(meters / 75));
const crossingText = route.crossings === 1 ? "1 crossing" : `${route.crossings} crossings`;
card.innerHTML = `
<div class="route-top">
<span class="route-name">${variant.name}</span>
<span class="route-time">${minutes} min</span>
</div>
<div class="route-meta">
<span>${formatDistance(meters)}</span>
<span>${crossingText}</span>
<span>${route.quayPct}% quay</span>
</div>
`;
card.addEventListener("click", () => {
selectedVariant = variant.key;
applyRouteStyles();
renderRouteCards();
updateInsight();
});
routeList.appendChild(card);
}
}
function applyRouteStyles() {
for (const variant of variants) {
const group = routeRoot.children.find(
(child) => child.userData?.variantKey === variant.key
);
if (!group) continue;
const selected = variant.key === selectedVariant;
group.userData.material.opacity = selected ? 0.98 : 0.26;
group.userData.radius = selected ? 0.075 : 0.032;
}
}
function updateInsight() {
const variant = variants.find((item) => item.key === selectedVariant);
const route = currentRoutes[selectedVariant];
const start = nodes[startSelect.value];
const end = nodes[endSelect.value];
const directMeters = Math.hypot(start.x - end.x, start.z - end.z) * 80;
const routeMeters = route.length * 80;
const detourMeters = routeMeters - directMeters;
const detourPct = directMeters ? (detourMeters / directMeters) * 100 : 0;
const acrossWater = start.zone !== end.zone;
if (acrossWater) {
insightTitle.textContent = "Why the route bends";
const crossingPhrase = route.crossingNames.length
? route.crossingNames.join(" + ")
: "a modeled crossing";
insightText.textContent =
`The ${formatDistance(directMeters)} line of sight cuts across the Capibaribe channel. ` +
`Water is not a walking link, so this route must reach ${crossingPhrase}. ` +
`That creates ${detourMeters >= 0 ? "a " + formatDistance(detourMeters) + " network detour" : "a route " + formatDistance(Math.abs(detourMeters)) + " shorter than the straight line"} ` +
`${detourPct >= 0 ? `(+${Math.round(detourPct)}%)` : `(${Math.round(detourPct)}%)`}.`;
} else {
insightTitle.textContent = "Connected street distance";
insightText.textContent =
`Both stops are on the same connected land fragment, so no water crossing is required. ` +
`The ${variant.name.toLowerCase()} still follows the modeled street and quay sequence, ` +
`which can differ from the ${formatDistance(directMeters)} line of sight.`;
}
statStrip.innerHTML = `
<div class="stat"><strong>${formatDistance(directMeters)}</strong><span>Line of sight</span></div>
<div class="stat"><strong>${formatDistance(routeMeters)}</strong><span>Walk route</span></div>
<div class="stat"><strong>${detourMeters >= 0 ? "+" : "−"}${formatDistance(Math.abs(detourMeters))}</strong><span>Network gap</span></div>
`;
}
function updateRoutes() {
const startId = startSelect.value;
const endId = endSelect.value;
disposeRouteMeshes();
for (const variant of variants) {
const route = dijkstra(startId, endId, variant.mode);
if (!route) continue;
currentRoutes[variant.key] = route;
const group = buildRouteMesh(route, variant);
group.userData.variantKey = variant.key;
routeAnimations.push({
group,
elapsed: 0,
duration: Math.max(0.8, route.length * 0.18)
});
}
applyRouteStyles();
renderRouteCards();
updateInsight();
updateDirectLine(startId, endId);
originMarker.position.set(nodes[startId].x, 0, nodes[startId].z);
destinationMarker.position.set(nodes[endId].x, 0, nodes[endId].z);
for (const entry of labelEntries) {
if (entry.type !== "poi") continue;
entry.element.classList.toggle("origin", entry.id === startId);
entry.element.classList.toggle("destination", entry.id === endId);
}
const activeCrossings = new Set(currentRoutes[selectedVariant]?.crossingNames || []);
for (const label of bridgeLabels) {
label.element.classList.toggle("active", activeCrossings.has(label.name));
}
}
// Populate selects.
for (const id of poiOrder) {
for (const select of [startSelect, endSelect]) {
const option = document.createElement("option");
option.value = id;
option.textContent = nodes[id].name;
select.appendChild(option);
}
}
startSelect.value = "marco";
endSelect.value = "museu";
startSelect.addEventListener("change", updateRoutes);
endSelect.addEventListener("change", updateRoutes);
$("#swap").addEventListener("click", () => {
const previousStart = startSelect.value;
startSelect.value = endSelect.value;
endSelect.value = previousStart;
updateRoutes();
});
// Direct camera controls implemented without addons.
const pointers = new Map();
let previousPinchDistance = 0;
let previousPan = null;
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
previousPan = { x: event.clientX, y: event.clientY };
if (pointers.size === 2) {
const values = [...pointers.values()];
previousPinchDistance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
});
canvas.addEventListener("pointermove", (event) => {
if (!pointers.has(event.pointerId)) return;
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 1 && previousPan) {
const dx = event.clientX - previousPan.x;
const dy = event.clientY - previousPan.y;
const pan = event.shiftKey || event.buttons === 2;
if (pan) {
const scale = cameraState.radius * 0.0015;
const right = new THREE.Vector3(
Math.cos(cameraState.theta),
0,
-Math.sin(cameraState.theta)
);
const forward = new THREE.Vector3(
-Math.sin(cameraState.theta),
0,
-Math.cos(cameraState.theta)
);
cameraState.desiredTarget.addScaledVector(right, -dx * scale);
cameraState.desiredTarget.addScaledVector(forward, -dy * scale);
} else {
cameraState.desiredTheta -= dx * 0.006;
cameraState.desiredPhi = THREE.MathUtils.clamp(
cameraState.desiredPhi - dy * 0.005,
0.34,
1.38
);
}
} else if (pointers.size === 2) {
const values = [...pointers.values()];
const distance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
if (previousPinchDistance > 0) {
cameraState.desiredRadius = THREE.MathUtils.clamp(
cameraState.desiredRadius * (previousPinchDistance / distance),
11,
42
);
}
previousPinchDistance = distance;
}
previousPan = { x: event.clientX, y: event.clientY };
});
function endPointer(event) {
pointers.delete(event.pointerId);
previousPan = null;
previousPinchDistance = 0;
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener("wheel", (event) => {
event.preventDefault();
cameraState.desiredRadius = THREE.MathUtils.clamp(
cameraState.desiredRadius * Math.exp(event.deltaY * 0.001),
11,
42
);
}, { passive: false });
canvas.addEventListener("keydown", (event) => {
const step = event.shiftKey ? 0.16 : 0.08;
if (event.key === "ArrowLeft") cameraState.desiredTheta += step;
if (event.key === "ArrowRight") cameraState.desiredTheta -= step;
if (event.key === "ArrowUp") cameraState.desiredPhi = Math.max(0.34, cameraState.desiredPhi - step);
if (event.key === "ArrowDown") cameraState.desiredPhi = Math.min(1.38, cameraState.desiredPhi + step);
if (event.key === "+" || event.key === "=") cameraState.desiredRadius = Math.max(11, cameraState.desiredRadius - 1);
if (event.key === "-") cameraState.desiredRadius = Math.min(42, cameraState.desiredRadius + 1);
});
function resetCamera() {
cameraState.desiredTheta = 0.72;
cameraState.desiredPhi = 0.92;
cameraState.desiredRadius = 25;
cameraState.desiredTarget.set(0.4, 0, 0.4);
}
$("#reset").addEventListener("click", resetCamera);
canvas.addEventListener("dblclick", resetCamera);
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();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
updateCamera(dt);
for (const animation of routeAnimations) {
animation.elapsed = Math.min(animation.duration, animation.elapsed + dt);
const progress = animation.elapsed / animation.duration;
const reveal = progress * animation.group.userData.total;
const group = animation.group;
for (const segment of group.userData.segments) {
const visibleLength = THREE.MathUtils.clamp(
reveal - segment.cumulative,
0,
segment.length
);
segment.mesh.position.copy(segment.start).addScaledVector(
segment.direction,
visibleLength / 2
);
segment.mesh.scale.set(
group.userData.radius,
Math.max(visibleLength, 0.001),
group.userData.radius
);
}
}
originMarker.rotation.y += dt * 0.7;
destinationMarker.rotation.y -= dt * 0.7;
updateProjectedLabels();
renderer.render(scene, camera);
}
updateRoutes();
animate();
requestAnimationFrame(() => {
$("#loading").classList.add("hidden");
});
</script>
</body>
</html>
```