Prompt specification
Build or customize the Three.js 3D scene "Compare pedestrian access across a busy junction" 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 pedestrian access across a busy junction
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/compare-pedestrian-access-across-a-busy-junction-x2888
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing the Piazza district of Addis Ababa. Let users place fictional crossing points in a schematic junction model. Show route lengths and conflicts with vehicle paths while keeping the surrounding urban geometry fixed. Voxel style.
Working Three.js Starter (compare-pedestrian-access-across-a-busy-junction-x2888):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#142329" />
<title>Piazza Crossing Lab — Addis Ababa</title>
<style>
:root {
--ink: #142329;
--ink-2: #1d3037;
--paper: #f5f2e9;
--paper-2: #e9e5da;
--line: rgba(20, 35, 41, 0.14);
--muted: #66777b;
--cyan: #23c4c4;
--cyan-dark: #087d83;
--orange: #ffad32;
--red: #ef476f;
--green: #87c94a;
--shadow: 0 12px 35px rgba(10, 24, 29, 0.15);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--ink);
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button {
font: inherit;
}
.app {
width: 100%;
height: 100%;
display: grid;
grid-template-rows: 70px minmax(0, 1fr);
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 0 22px;
background: var(--ink);
color: white;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
z-index: 20;
}
.brand {
display: flex;
align-items: center;
min-width: 250px;
gap: 12px;
}
.brand-mark {
width: 37px;
height: 37px;
position: relative;
flex: 0 0 auto;
background: var(--cyan);
box-shadow:
8px 0 0 rgba(35, 196, 196, 0.35),
0 8px 0 rgba(35, 196, 196, 0.28);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
background: var(--ink);
}
.brand-mark::before {
width: 22px;
height: 5px;
left: 7px;
top: 9px;
}
.brand-mark::after {
width: 5px;
height: 22px;
left: 9px;
top: 8px;
}
.brand h1 {
margin: 0;
font-size: 15px;
line-height: 1.1;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.brand p {
margin: 5px 0 0;
color: #9eb1b6;
font-size: 11px;
letter-spacing: 0.04em;
}
.top-actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 8px;
flex-wrap: wrap;
}
.btn {
appearance: none;
border: 1px solid rgba(255, 255, 255, 0.15);
background: rgba(255, 255, 255, 0.06);
color: white;
min-height: 38px;
padding: 0 13px;
border-radius: 4px;
cursor: pointer;
font-size: 12px;
font-weight: 700;
letter-spacing: 0.025em;
transition:
background 150ms ease,
transform 150ms ease,
border-color 150ms ease;
}
.btn:hover {
background: rgba(255, 255, 255, 0.13);
border-color: rgba(255, 255, 255, 0.28);
}
.btn:active {
transform: translateY(1px);
}
.btn.primary {
color: #09272a;
background: var(--cyan);
border-color: var(--cyan);
}
.btn.primary:hover {
background: #52dbd7;
}
.btn.active {
color: #09272a;
background: var(--orange);
border-color: var(--orange);
}
.btn.danger {
color: #ffc4d2;
}
.eat-clock {
padding: 7px 10px;
color: #a9bcc0;
border-left: 1px solid rgba(255, 255, 255, 0.12);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 11px;
white-space: nowrap;
}
main {
min-height: 0;
display: grid;
grid-template-columns: minmax(0, 1fr) 370px;
}
#viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #cbd4d0;
}
.scene-canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
}
.scene-top {
position: absolute;
top: 18px;
left: 18px;
right: 18px;
z-index: 4;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
pointer-events: none;
}
.mode-card,
.fixed-badge {
background: rgba(245, 242, 233, 0.92);
border: 1px solid rgba(20, 35, 41, 0.13);
box-shadow: var(--shadow);
backdrop-filter: blur(10px);
border-radius: 5px;
}
.mode-card {
max-width: 420px;
padding: 12px 14px;
}
.mode-line {
display: flex;
align-items: center;
gap: 8px;
color: var(--cyan-dark);
font-size: 10px;
font-weight: 900;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.mode-dot {
width: 8px;
height: 8px;
background: var(--cyan);
box-shadow: 0 0 0 4px rgba(35, 196, 196, 0.15);
}
.mode-card p {
margin: 7px 0 0;
font-size: 12px;
line-height: 1.45;
color: #40545a;
}
.fixed-badge {
padding: 10px 12px;
display: flex;
align-items: center;
gap: 8px;
font-size: 10px;
font-weight: 900;
letter-spacing: 0.09em;
white-space: nowrap;
}
.lock {
width: 12px;
height: 11px;
border: 2px solid var(--cyan-dark);
border-radius: 1px;
position: relative;
}
.lock::before {
content: "";
position: absolute;
width: 7px;
height: 7px;
border: 2px solid var(--cyan-dark);
border-bottom: 0;
left: 1px;
top: -7px;
}
.legend {
position: absolute;
left: 18px;
bottom: 18px;
z-index: 4;
min-width: 188px;
padding: 12px 14px;
border-radius: 5px;
color: white;
background: rgba(20, 35, 41, 0.89);
border: 1px solid rgba(255, 255, 255, 0.12);
box-shadow: var(--shadow);
backdrop-filter: blur(8px);
pointer-events: none;
}
.legend-title {
margin-bottom: 9px;
font-size: 9px;
font-weight: 900;
letter-spacing: 0.15em;
text-transform: uppercase;
color: #a8bbc0;
}
.legend-row {
display: flex;
align-items: center;
gap: 9px;
margin-top: 7px;
font-size: 11px;
color: #e7eeee;
}
.swatch {
width: 15px;
height: 8px;
flex: 0 0 auto;
border-radius: 1px;
}
.swatch.route {
background: var(--orange);
}
.swatch.pad {
background: var(--cyan);
}
.swatch.conflict {
background: var(--red);
}
.swatch.fixed {
background: #d8cbb4;
}
.north {
position: absolute;
right: 20px;
bottom: 20px;
z-index: 4;
width: 45px;
height: 45px;
display: grid;
place-items: center;
color: var(--ink);
background: rgba(245, 242, 233, 0.9);
border: 1px solid rgba(20, 35, 41, 0.15);
border-radius: 50%;
box-shadow: var(--shadow);
font-size: 10px;
font-weight: 900;
pointer-events: none;
}
.north::before {
content: "";
position: absolute;
top: 6px;
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 10px solid var(--ink);
}
#tooltip {
position: absolute;
z-index: 8;
display: none;
pointer-events: none;
max-width: 240px;
padding: 9px 11px;
color: white;
background: rgba(20, 35, 41, 0.95);
border-left: 3px solid var(--cyan);
border-radius: 3px;
box-shadow: var(--shadow);
font-size: 11px;
line-height: 1.45;
}
#tooltip strong {
display: block;
color: #77e4df;
margin-bottom: 2px;
}
#toast {
position: absolute;
z-index: 9;
left: 50%;
bottom: 24px;
transform: translate(-50%, 16px);
opacity: 0;
pointer-events: none;
max-width: min(90%, 460px);
padding: 10px 14px;
color: white;
background: rgba(20, 35, 41, 0.94);
border: 1px solid rgba(255, 255, 255, 0.14);
border-radius: 4px;
box-shadow: var(--shadow);
font-size: 12px;
transition:
opacity 180ms ease,
transform 180ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
aside {
min-height: 0;
overflow: auto;
background: var(--paper);
border-left: 1px solid rgba(20, 35, 41, 0.13);
scrollbar-width: thin;
scrollbar-color: #b6bcb6 transparent;
}
.panel {
padding: 18px 20px;
border-bottom: 1px solid var(--line);
}
.eyebrow {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 10px;
color: var(--muted);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.eyebrow .step {
color: var(--cyan-dark);
}
.selected-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
}
.selected-heading h2 {
margin: 0;
font-size: 21px;
line-height: 1.15;
letter-spacing: -0.025em;
}
.selected-heading p {
margin: 5px 0 0;
color: var(--muted);
font-size: 11px;
}
.point-id {
padding: 6px 8px;
flex: 0 0 auto;
color: var(--cyan-dark);
background: rgba(35, 196, 196, 0.11);
border: 1px solid rgba(8, 125, 131, 0.18);
border-radius: 3px;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
font-weight: 900;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin: 15px 0 10px;
}
.metric {
min-height: 87px;
padding: 12px;
background: #fffdf8;
border: 1px solid var(--line);
border-radius: 4px;
}
.metric strong {
display: block;
font-size: 25px;
line-height: 1;
letter-spacing: -0.04em;
font-variant-numeric: tabular-nums;
}
.metric span {
display: block;
margin-top: 7px;
color: var(--muted);
font-size: 10px;
line-height: 1.3;
}
.metric.route strong {
color: #b56500;
}
.metric.conflict strong {
color: #d43155;
}
.detail-row {
display: flex;
justify-content: space-between;
gap: 14px;
padding: 7px 0;
border-bottom: 1px dashed rgba(20, 35, 41, 0.12);
font-size: 11px;
}
.detail-row:last-child {
border-bottom: 0;
}
.detail-row span:first-child {
color: var(--muted);
}
.detail-row span:last-child {
text-align: right;
font-weight: 700;
}
.risk {
display: inline-flex;
align-items: center;
gap: 6px;
}
.risk::before {
content: "";
width: 7px;
height: 7px;
background: currentColor;
}
.risk.high {
color: #cf2f50;
}
.risk.medium {
color: #bd7100;
}
.risk.low {
color: #508327;
}
.risk.none {
color: var(--muted);
}
.conflict-list {
display: grid;
gap: 6px;
margin-top: 10px;
}
.conflict-item {
display: flex;
align-items: center;
gap: 9px;
padding: 8px 9px;
background: rgba(20, 35, 41, 0.045);
border-radius: 3px;
font-size: 10px;
}
.route-dot {
width: 8px;
height: 8px;
flex: 0 0 auto;
border-radius: 50%;
}
.conflict-item .route-name {
flex: 1;
font-weight: 750;
}
.conflict-item .route-meta {
color: var(--muted);
}
.side-buttons {
display: flex;
gap: 8px;
margin-top: 13px;
}
.side-buttons button {
flex: 1;
min-height: 35px;
border: 1px solid var(--line);
border-radius: 3px;
background: transparent;
color: var(--ink);
cursor: pointer;
font-size: 10px;
font-weight: 800;
}
.side-buttons button:hover {
background: white;
}
.side-buttons button:disabled {
opacity: 0.4;
cursor: default;
}
.point-list {
display: grid;
gap: 7px;
}
.point-row {
width: 100%;
display: grid;
grid-template-columns: 48px minmax(0, 1fr) auto;
align-items: center;
gap: 10px;
padding: 9px 10px;
text-align: left;
color: var(--ink);
background: rgba(255, 255, 255, 0.48);
border: 1px solid var(--line);
border-radius: 3px;
cursor: pointer;
}
.point-row:hover,
.point-row.active {
border-color: rgba(8, 125, 131, 0.42);
background: white;
}
.point-row.active {
box-shadow: inset 3px 0 0 var(--cyan);
}
.point-code {
color: var(--cyan-dark);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
font-weight: 900;
}
.point-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 11px;
font-weight: 750;
}
.point-sub {
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.point-conflicts {
color: #d43155;
font-size: 10px;
font-weight: 900;
white-space: nowrap;
}
.traffic-list {
display: grid;
gap: 7px;
}
.traffic-row {
display: grid;
grid-template-columns: 9px minmax(0, 1fr) auto;
align-items: center;
gap: 9px;
font-size: 10px;
}
.traffic-bar {
width: 9px;
height: 23px;
}
.traffic-name {
font-weight: 750;
}
.traffic-sub {
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.traffic-length {
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9px;
}
.note {
margin: 0;
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
.note strong {
color: var(--ink);
}
@media (max-width: 980px) {
main {
grid-template-columns: minmax(0, 1fr) 330px;
}
.topbar {
padding: 0 14px;
}
.eat-clock {
display: none;
}
.brand p {
display: none;
}
}
@media (max-width: 760px) {
html,
body {
overflow: auto;
}
.app {
height: auto;
min-height: 100%;
grid-template-rows: auto auto;
}
.topbar {
min-height: 66px;
align-items: flex-start;
padding: 12px;
flex-direction: column;
gap: 10px;
}
.top-actions {
width: 100%;
justify-content: flex-start;
}
.top-actions .btn {
padding: 0 9px;
font-size: 10px;
}
main {
display: block;
}
#viewport {
height: 62vh;
min-height: 430px;
}
aside {
max-height: none;
border-left: 0;
border-top: 1px solid var(--line);
}
.fixed-badge {
display: none;
}
.mode-card {
max-width: calc(100% - 20px);
}
.legend {
bottom: 12px;
left: 12px;
}
.north {
bottom: 12px;
right: 12px;
}
}
</style>
</head>
<body>
<div class="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>Piazza Crossing Lab</h1>
<p>Addis Ababa · schematic district model</p>
</div>
</div>
<div class="top-actions">
<button class="btn primary" id="addButton">+ Place crossing</button>
<button class="btn" id="trafficButton">Traffic: on</button>
<button class="btn" id="clearButton">Clear added</button>
<button class="btn" id="resetButton">Reset view</button>
<div class="eat-clock" id="eatClock">EAT --:--</div>
</div>
</header>
<main>
<section id="viewport" aria-label="Interactive 3D model of the Piazza district">
<div class="scene-top">
<div class="mode-card">
<div class="mode-line">
<span class="mode-dot"></span>
<span id="modeLabel">Explore mode</span>
</div>
<p id="modeHelp">
Drag to orbit, right-drag to pan, and scroll to zoom. Select a crossing marker to inspect it.
</p>
</div>
<div class="fixed-badge">
<span class="lock"></span>
Fixed urban context
</div>
</div>
<div class="legend">
<div class="legend-title">Map key</div>
<div class="legend-row"><span class="swatch route"></span> Walking route</div>
<div class="legend-row"><span class="swatch pad"></span> Placement pad</div>
<div class="legend-row"><span class="swatch conflict"></span> Vehicle conflict</div>
<div class="legend-row"><span class="swatch fixed"></span> Fixed building</div>
</div>
<div class="north" title="North">N</div>
<div id="tooltip"></div>
<div id="toast"></div>
</section>
<aside>
<section class="panel">
<div class="eyebrow">
<span><span class="step">01</span> / Selected crossing</span>
<span id="liveRisk">Live: 0</span>
</div>
<div class="selected-heading">
<div>
<h2 id="selectedName">No crossing selected</h2>
<p id="selectedSubtitle">Choose a marker in the model</p>
</div>
<span class="point-id" id="selectedId">—</span>
</div>
<div class="metric-grid">
<div class="metric route">
<strong id="routeLength">—</strong>
<span>m walking route to Piazza Square</span>
</div>
<div class="metric conflict">
<strong id="conflictCount">—</strong>
<span>vehicle paths cross this point</span>
</div>
</div>
<div class="detail-row">
<span>Crossing width</span>
<span id="crossingWidth">—</span>
</div>
<div class="detail-row">
<span>Control context</span>
<span id="signalType">—</span>
</div>
<div class="detail-row">
<span>Exposure rating</span>
<span id="riskRating" class="risk none">—</span>
</div>
<div class="conflict-list" id="conflictList"></div>
<div class="side-buttons">
<button id="removeButton" disabled>Remove selected point</button>
</div>
</section>
<section class="panel">
<div class="eyebrow">
<span><span class="step">02</span> / Fictional crossing points</span>
<span id="pointCount">0 points</span>
</div>
<div class="point-list" id="pointList"></div>
</section>
<section class="panel">
<div class="eyebrow">
<span><span class="step">03</span> / Fixed vehicle paths</span>
<span>Schematic</span>
</div>
<div class="traffic-list" id="trafficList"></div>
</section>
<section class="panel">
<p class="note">
<strong>Planning model only.</strong> Buildings, streets, landmarks, and vehicle paths
remain fixed. Crossing points and their names are fictional. Distances are schematic
estimates and must not be used for engineering or navigation decisions.
</p>
</section>
</aside>
</main>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const viewport = $("viewport");
// -------------------------------------------------------------------------
// Renderer, camera, lighting
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xcbd4d0);
scene.fog = new THREE.Fog(0xcbd4d0, 255, 420);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.75));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.className = "scene-canvas";
renderer.domElement.tabIndex = 0;
viewport.prepend(renderer.domElement);
const camera = new THREE.OrthographicCamera(-140, 140, 100, -100, 0.1, 650);
const worldGroup = new THREE.Group();
const dynamicGroup = new THREE.Group();
const trafficGroup = new THREE.Group();
const overlayGroup = new THREE.Group();
scene.add(worldGroup, dynamicGroup, trafficGroup, overlayGroup);
const hemisphere = new THREE.HemisphereLight(0xeaf8f3, 0x7a6553, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff0d1, 3.1);
sun.position.set(-90, 135, 80);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -150;
sun.shadow.camera.right = 150;
sun.shadow.camera.top = 130;
sun.shadow.camera.bottom = -130;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 350;
sun.shadow.bias = -0.00025;
scene.add(sun);
const cameraState = {
target: new THREE.Vector3(0, 0, 4),
azimuth: 0.72,
polar: 0.72,
radius: 230
};
function updateCamera() {
const s = Math.sin(cameraState.polar);
camera.position.set(
cameraState.target.x + cameraState.radius * s * Math.cos(cameraState.azimuth),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.polar),
cameraState.target.z + cameraState.radius * s * Math.sin(cameraState.azimuth)
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.target.set(0, 0, 4);
cameraState.azimuth = 0.72;
cameraState.polar = 0.72;
cameraState.radius = 230;
updateCamera();
}
function resize() {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
const aspect = width / Math.max(1, height);
const halfHeight = Math.max(90, 112 / aspect);
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
}
new ResizeObserver(resize).observe(viewport);
resize();
updateCamera();
// -------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------
function addBox(parent, width, height, depth, x, y, z, color, options = {}) {
const material =
color && color.isMaterial
? color
: new THREE.MeshStandardMaterial({
color,
roughness: options.roughness ?? 0.88,
metalness: options.metalness ?? 0,
emissive: options.emissive ?? 0x000000,
emissiveIntensity: options.emissiveIntensity ?? 0,
transparent: options.transparent ?? false,
opacity: options.opacity ?? 1,
flatShading: true
});
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = options.castShadow ?? true;
mesh.receiveShadow = options.receiveShadow ?? true;
if (options.rotationY !== undefined) {
mesh.rotation.y = options.rotationY;
}
parent.add(mesh);
return mesh;
}
function textSprite(text, color = "#f5f2e9", scale = 14) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 96;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(20,35,41,0.88)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = color;
ctx.fillRect(0, 0, 7, canvas.height);
ctx.fillStyle = "#ffffff";
ctx.font = "900 27px monospace";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 258, 49);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(scale, scale * 0.1875, 1);
sprite.renderOrder = 20;
return sprite;
}
function disposeGroup(group) {
while (group.children.length) {
const child = group.children.pop();
child.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const materials = Array.isArray(object.material)
? object.material
: [object.material];
materials.forEach((material) => material.dispose());
}
});
}
}
const nodePositions = {
NW: new THREE.Vector3(-70, 0, -50),
N: new THREE.Vector3(10, 0, -55),
NE: new THREE.Vector3(75, 0, -50),
W: new THREE.Vector3(-70, 0, 15),
C: new THREE.Vector3(10, 0, 15),
E: new THREE.Vector3(85, 0, 15),
S: new THREE.Vector3(10, 0, 65),
SE: new THREE.Vector3(75, 0, 65)
};
const roads = [
{ id: "wc", a: "W", b: "C", width: 11, name: "Meskel Street" },
{ id: "ce", a: "C", b: "E", width: 12, name: "Piazza Avenue" },
{ id: "nc", a: "N", b: "C", width: 12, name: "Meridian Avenue" },
{ id: "cs", a: "C", b: "S", width: 11, name: "Cathedral Street" },
{ id: "nww", a: "NW", b: "W", width: 9, name: "West Link" },
{ id: "nwn", a: "NW", b: "N", width: 9, name: "Northwest Link" },
{ id: "nne", a: "N", b: "NE", width: 9, name: "Northeast Link" },
{ id: "nee", a: "NE", b: "E", width: 9, name: "Museum Link" },
{ id: "ese", a: "E", b: "SE", width: 9, name: "Eastern Link" },
{ id: "css", a: "C", b: "SE", width: 10, name: "Piazza Diagonal" },
{ id: "sse", a: "S", b: "SE", width: 9, name: "Southern Link" }
];
const roadById = new Map(roads.map((road) => [road.id, road]));
function roadData(road) {
const a = nodePositions[road.a];
const b = nodePositions[road.b];
const dx = b.x - a.x;
const dz = b.z - a.z;
const length = Math.hypot(dx, dz);
const tangent = new THREE.Vector3(dx / length, 0, dz / length);
const normal = new THREE.Vector3(-tangent.z, 0, tangent.x);
const angle = Math.atan2(dz, dx);
return { a, b, dx, dz, length, tangent, normal, angle };
}
function pointOnRoad(road, t, lateral = 0) {
const data = roadData(road);
return new THREE.Vector3(
data.a.x + data.dx * t + data.normal.x * lateral,
0,
data.a.z + data.dz * t + data.normal.z * lateral
);
}
function edgeBetween(a, b) {
return roads.find(
(road) =>
(road.a === a && road.b === b) ||
(road.a === b && road.b === a)
);
}
// -------------------------------------------------------------------------
// Fixed city geometry
// -------------------------------------------------------------------------
addBox(worldGroup, 210, 1.3, 180, 0, -0.8, 4, 0xc9b99c, {
receiveShadow: true
});
// Low block plinths create the characteristic voxel-map silhouette.
addBox(worldGroup, 58, 0.45, 42, -34, -0.05, -25, 0xb9ac96);
addBox(worldGroup, 48, 0.45, 42, 43, -0.05, -25, 0xb9ac96);
addBox(worldGroup, 60, 0.45, 34, -35, -0.05, 42, 0xb9ac96);
addBox(worldGroup, 47, 0.45, 35, 46, -0.05, 48, 0xb9ac96);
function drawRoad(road) {
const data = roadData(road);
const mid = data.a.clone().add(data.b).multiplyScalar(0.5);
const rotation = -data.angle;
addBox(
worldGroup,
data.length + 2.5,
0.28,
road.width + 7,
mid.x,
0.02,
mid.z,
0xded8ca,
{ rotationY: rotation, castShadow: false }
);
addBox(
worldGroup,
data.length + 1.2,
0.3,
road.width,
mid.x,
0.16,
mid.z,
0x46545a,
{ rotationY: rotation, castShadow: false }
);
const dashCount = Math.floor(data.length / 10);
for (let i = 1; i < dashCount; i++) {
const t = i / dashCount;
const p = pointOnRoad(road, t);
addBox(worldGroup, 3.1, 0.08, 0.32, p.x, 0.36, p.z, 0xe9dfbd, {
rotationY: rotation,
castShadow: false
});
}
}
roads.forEach(drawRoad);
function makeBuilding(x, z, width, depth, height, color, roofColor = 0x6d6254) {
const group = new THREE.Group();
group.position.set(x, 0, z);
worldGroup.add(group);
addBox(group, width, height, depth, 0, height / 2, 0, color);
addBox(
group,
width + 0.8,
0.65,
depth + 0.8,
0,
height + 0.3,
0,
roofColor
);
if (height > 11) {
addBox(group, width * 0.35, 1.1, depth * 0.35, 0, height + 1, 0, roofColor);
}
const windowMaterial = new THREE.MeshStandardMaterial({
color: 0x9dc9c5,
emissive: 0x31595b,
emissiveIntensity: 0.18,
roughness: 0.55
});
const floors = Math.max(1, Math.floor((height - 2) / 3.2));
const columns = Math.max(2, Math.floor(width / 4));
for (let floor = 0; floor < floors; floor++) {
const y = 2.4 + floor * 3.15;
for (let column = 0; column < columns; column++) {
const wx = -width / 2 + ((column + 1) * width) / (columns + 1);
addBox(group, 1.15, 1.05, 0.13, wx, y, depth / 2 + 0.08, windowMaterial);
addBox(group, 1.15, 1.05, 0.13, wx, y, -depth / 2 - 0.08, windowMaterial);
}
}
}
const buildings = [
[-48, -30, 17, 13, 13, 0xc87958, 0x765345],
[-27, -27, 13, 18, 17, 0xd7b77b, 0x826548],
[-47, -9, 22, 12, 18, 0x77968c, 0x52625d],
[-19, -8, 14, 11, 10, 0xb9c0ad, 0x73786e],
[30, -31, 16, 17, 14, 0x748b99, 0x4f5e68],
[51, -30, 19, 14, 18, 0xd18a62, 0x77503f],
[28, -10, 17, 10, 9, 0xc4b28a, 0x776b59],
[55, -9, 13, 12, 13, 0x91a68d, 0x5e6f5c],
[-48, 35, 20, 14, 16, 0x8d9b87, 0x5f695a],
[-43, 55, 23, 10, 10, 0xca8a66, 0x79523f],
[28, 54, 17, 10, 12, 0x76979a, 0x4e6768],
[59, 54, 14, 14, 17, 0xc6aa7b, 0x776448],
[-18, 52, 16, 12, 13, 0xa86f5e, 0x684b40],
[62, 34, 10, 15, 12, 0x78918a, 0x50625d]
];
buildings.forEach((building) => makeBuilding(...building));
// Piazza Square and its voxel monument.
addBox(worldGroup, 28, 0.4, 18, 45, 0.28, 25, 0xe8dfc9, {
castShadow: false
});
for (let x = 34; x <= 56; x += 4) {
addBox(worldGroup, 0.12, 0.06, 16, x, 0.52, 25, 0xcdbb9c, {
castShadow: false
});
}
for (let z = 19; z <= 31; z += 4) {
addBox(worldGroup, 26, 0.06, 0.12, 45, 0.53, z, 0xcdbb9c, {
castShadow: false
});
}
addBox(worldGroup, 5.5, 0.8, 4.5, 47, 0.85, 25, 0x8b7760);
addBox(worldGroup, 3.5, 4.8, 3.2, 47, 3.6, 25, 0xb99a67);
addBox(worldGroup, 4.6, 0.65, 4.2, 47, 6.3, 25, 0xd2b27b);
addBox(worldGroup, 1.2, 2.5, 1.2, 47, 8.6, 25, 0xd2b27b);
// St. George Cathedral: stepped red-brick mass and twin towers.
const cathedral = new THREE.Group();
cathedral.position.set(-20, 0, 36);
worldGroup.add(cathedral);
addBox(cathedral, 23, 9, 14, 0, 4.5, 0, 0x8d493b);
addBox(cathedral, 18, 2, 11, 0, 10, 0, 0xa65a47);
addBox(cathedral, 12, 2, 8, 0, 12, 0, 0xb66b52);
[-8, 8].forEach((tx) => {
addBox(cathedral, 5, 17, 5, tx, 8.5, -4.5, 0x9d5140);
addBox(cathedral, 6, 1, 6, tx, 17.5, -4.5, 0xc27a58);
addBox(cathedral, 0.65, 4, 0.65, tx, 20.5, -4.5, 0xe0c48f);
addBox(cathedral, 2.8, 0.65, 0.65, tx, 21.5, -4.5, 0xe0c48f);
});
// Holy Trinity Cathedral: pale masonry and a central bell tower.
const trinity = new THREE.Group();
trinity.position.set(-25, 0, -20);
worldGroup.add(trinity);
addBox(trinity, 24, 8, 13, 0, 4, 0, 0xc9b58b);
addBox(trinity, 19, 2, 10, 0, 9, 0, 0xd8c79f);
addBox(trinity, 7, 14, 7, 0, 7, 0, 0xbaa37a);
addBox(trinity, 8, 1, 8, 0, 14.5, 0, 0xe0cea1);
addBox(trinity, 0.65, 4, 0.65, 0, 17.5, 0, 0xe8d49d);
// Museum: broad stepped institutional block.
const museum = new THREE.Group();
museum.position.set(45, 0, -24);
worldGroup.add(museum);
addBox(museum, 23, 10, 15, 0, 5, 0, 0xd4c5a3);
addBox(museum, 19, 2, 12, 0, 11, 0, 0xbcab88);
addBox(museum, 11, 2, 8, 0, 13, 0, 0xd8c9a6);
addBox(museum, 4, 4, 0.25, 0, 5, 7.65, 0x54726e);
function makeTree(x, z, scale = 1) {
addBox(worldGroup, 0.8 * scale, 3.2 * scale, 0.8 * scale, x, 1.6 * scale, z, 0x70583f);
addBox(worldGroup, 4.5 * scale, 2.6 * scale, 4.5 * scale, x, 4.2 * scale, z, 0x547b51);
addBox(worldGroup, 3.2 * scale, 2.3 * scale, 3.2 * scale, x, 6.1 * scale, z, 0x668f59);
addBox(worldGroup, 1.8 * scale, 1.7 * scale, 1.8 * scale, x + 0.5, 7.5 * scale, z, 0x769e61);
}
[
[-57, -38, 1], [-32, -39, 0.85], [-58, 3, 0.9], [-57, 26, 1],
[-33, 48, 0.9], [-4, 46, 0.8], [23, 45, 0.8], [63, 46, 0.9],
[67, -39, 0.85], [65, 3, 0.85], [22, -42, 0.9], [16, 4, 0.8],
[4, -43, 0.8], [4, 57, 0.85]
].forEach((tree) => makeTree(...tree));
const labels = [
["PIAZZA SQUARE", 45, 13, 27, 16, "#62e4df"],
["ST. GEORGE CATHEDRAL", -20, 26, 45, 28, "#f0b58e"],
["HOLY TRINITY CATHEDRAL", -25, -33, 22, 24, "#f1d69f"],
["NATIONAL MUSEUM", 45, -37, 22, 21, "#acd8d1"]
];
labels.forEach(([text, x, y, z, scale, color]) => {
const sprite = textSprite(text, color, scale);
sprite.position.set(x, y, z);
worldGroup.add(sprite);
});
// -------------------------------------------------------------------------
// Fixed vehicle paths
// -------------------------------------------------------------------------
const routeDefinitions = [
{
id: "taxi",
name: "Blue Taxi Circuit",
nodes: ["NW", "N", "C", "E", "SE"],
color: 0x20bfd0
},
{
id: "minibus",
name: "Meridian Minibus",
nodes: ["N", "C", "E", "NE"],
color: 0xf4a261
},
{
id: "shared",
name: "Green Shared Taxi",
nodes: ["W", "C", "SE", "E"],
color: 0x8bd450
},
{
id: "loop",
name: "Piazza Purple Loop",
nodes: ["NW", "N", "NE", "E", "SE", "S", "C", "W"],
color: 0xc77dff
},
{
id: "service",
name: "Red Service Bus",
nodes: ["S", "C", "E", "SE"],
color: 0xef476f
}
];
const routes = routeDefinitions.map((definition) => {
const segments = [];
let total = 0;
for (let i = 0; i < definition.nodes.length - 1; i++) {
const a = definition.nodes[i];
const b = definition.nodes[i + 1];
const edge = edgeBetween(a, b);
const length = nodePositions[a].distanceTo(nodePositions[b]);
segments.push({
a,
b,
edgeId: edge.id,
length,
start: total
});
total += length;
}
return { ...definition, segments, total };
});
function routePoint(route, distance) {
const d = ((distance % route.total) + route.total) % route.total;
const segment =
route.segments.find((item) => d <= item.start + item.length) ??
route.segments[route.segments.length - 1];
const t = (d - segment.start) / segment.length;
const a = nodePositions[segment.a];
const b = nodePositions[segment.b];
return {
segment,
position: a.clone().lerp(b, t)
};
}
const cars = [];
routes.forEach((route, routeIndex) => {
const points = route.nodes.map((id) => nodePositions[id].clone().setY(0.48));
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const line = new THREE.Line(
geometry,
new THREE.LineBasicMaterial({
color: route.color,
transparent: true,
opacity: 0.46
})
);
trafficGroup.add(line);
const count = routeIndex === 3 ? 5 : 3;
for (let i = 0; i < count; i++) {
const car = new THREE.Group();
const body = addBox(car, 3.7, 1.15, 1.9, 0, 0.75, 0, route.color);
const cabin = addBox(
car,
1.9,
0.8,
1.55,
-0.15,
1.6,
0,
0x294047
);
const wheelMaterial = new THREE.MeshStandardMaterial({
color: 0x202729,
roughness: 1
});
[-1.1, 1.1].forEach((wx) => {
addBox(car, 0.5, 0.55, 2.05, wx, 0.35, 0, wheelMaterial);
});
trafficGroup.add(car);
cars.push({
group: car,
body,
cabin,
route,
routeIndex,
offset: (i + 0.35) / count,
speed: 6.2 + routeIndex * 0.55,
segment: null,
position: new THREE.Vector3()
});
}
});
// -------------------------------------------------------------------------
// Candidate crossing locations and pedestrian graph
// -------------------------------------------------------------------------
const candidateDefinitions = [
{ id: "west-north", edge: "wc", t: 0.32, side: -1, label: "Meskel North", width: 14, signal: "Unsignalized" },
{ id: "west-south", edge: "wc", t: 0.68, side: 1, label: "Meskel South", width: 14, signal: "Unsignalized" },
{ id: "avenue-north-a", edge: "ce", t: 0.18, side: -1, label: "Square North", width: 16, signal: "Signalized" },
{ id: "avenue-south-a", edge: "ce", t: 0.52, side: 1, label: "Square South", width: 16, signal: "Signalized" },
{ id: "meridian-east-a", edge: "nc", t: 0.32, side: -1, label: "Meridian East", width: 16, signal: "Signalized" },
{ id: "meridian-west-a", edge: "nc", t: 0.66, side: 1, label: "Meridian West", width: 16, signal: "Unsignalized" },
{ id: "cathedral-west-a", edge: "cs", t: 0.26, side: 1, label: "Cathedral West", width: 14, signal: "Unsignalized" },
{ id: "cathedral-east-a", edge: "cs", t: 0.58, side: -1, label: "Cathedral East", width: 14, signal: "Signalized" },
{ id: "west-link", edge: "nww", t: 0.45, side: 1, label: "West Garden", width: 12, signal: "Unsignalized" },
{ id: "northwest-link", edge: "nwn", t: 0.38, side: 1, label: "Northwest Walk", width: 12, signal: "Unsignalized" },
{ id: "northeast-a", edge: "nne", t: 0.45, side: 1, label: "North Garden", width: 12, signal: "Unsignalized" },
{ id: "northeast-b", edge: "nne", t: 0.72, side: -1, label: "Museum Road", width: 12, signal: "Unsignalized" },
{ id: "museum-west", edge: "nee", t: 0.42, side: 1, label: "Museum West", width: 12, signal: "Unsignalized" },
{ id: "east-link-a", edge: "ese", t: 0.38, side: 1, label: "East Gardens", width: 12, signal: "Unsignalized" },
{ id: "east-link-b", edge: "ese", t: 0.72, side: -1, label: "Eastern Market", width: 12, signal: "Signalized" },
{ id: "diagonal-square", edge: "css", t: 0.34, side: -1, label: "Square Diagonal", width: 15, signal: "Signalized" },
{ id: "diagonal-south", edge: "css", t: 0.62, side: 1, label: "Diagonal South", width: 15, signal: "Unsignalized" },
{ id: "southern-link", edge: "sse", t: 0.45, side: 1, label: "Southern Link", width: 12, signal: "Unsignalized" }
];
const candidates = candidateDefinitions.map((definition) => {
const road = roadById.get(definition.edge);
const data = roadData(road);
const offset = road.width / 2 + 2;
const plus = pointOnRoad(road, definition.t, offset);
const minus = pointOnRoad(road, definition.t, -offset);
return {
...definition,
road,
roadData: data,
plus,
minus,
point: definition.side === 1 ? plus : minus,
nodePlus: null,
nodeMinus: null,
conflicts: routes.filter((route) =>
route.segments.some((segment) => segment.edgeId === definition.edge)
)
};
});
const pedNodes = new Map();
const adjacency = new Map();
function addPedNode(id, point) {
const node = { id, position: point.clone().setY(0) };
pedNodes.set(id, node);
adjacency.set(id, []);
return node;
}
function connectPed(a, b) {
if (!adjacency.has(a) || !adjacency.has(b)) return;
const na = pedNodes.get(a);
const nb = pedNodes.get(b);
const length = na.position.distanceTo(nb.position);
adjacency.get(a).push({ id: b, length });
adjacency.get(b).push({ id: a, length });
}
function endpointId(road, side, end) {
return `${road.id}-${side > 0 ? "plus" : "minus"}-${end}`;
}
roads.forEach((road) => {
const offset = road.width / 2 + 2;
[-1, 1].forEach((side) => {
const start = pointOnRoad(road, 0, side * offset);
const end = pointOnRoad(road, 1, side * offset);
addPedNode(endpointId(road, side, 0), start);
addPedNode(endpointId(road, side, 1), end);
});
});
candidates.forEach((candidate) => {
candidate.nodePlus = `${candidate.id}-plus`;
candidate.nodeMinus = `${candidate.id}-minus`;
addPedNode(candidate.nodePlus, candidate.plus);
addPedNode(candidate.nodeMinus, candidate.minus);
});
// Sidewalk chains are split at every candidate location.
roads.forEach((road) => {
[-1, 1].forEach((side) => {
const entries = [
{ t: 0, id: endpointId(road, side, 0) },
{ t: 1, id: endpointId(road, side, 1) }
];
candidates
.filter((candidate) => candidate.edge === road.id)
.forEach((candidate) => {
entries.push({
t: candidate.t,
id: side === 1 ? candidate.nodePlus : candidate.nodeMinus
});
});
entries.sort((a, b) => a.t - b.t);
for (let i = 0; i < entries.length - 1; i++) {
connectPed(entries[i].id, entries[i + 1].id);
}
});
});
// Connect nearby sidewalk corners at fixed junctions.
Object.keys(nodePositions).forEach((junctionId) => {
const endpointNodes = [];
roads.forEach((road) => {
const end = road.a === junctionId ? 0 : road.b === junctionId ? 1 : null;
if (end === null) return;
[-1, 1].forEach((side) => {
endpointNodes.push(endpointId(road, side, end));
});
});
for (let i = 0; i < endpointNodes.length; i++) {
for (let j = i + 1; j < endpointNodes.length; j++) {
const a = pedNodes.get(endpointNodes[i]);
const b = pedNodes.get(endpointNodes[j]);
if (a.position.distanceTo(b.position) < 22) {
connectPed(a.id, b.id);
}
}
}
});
const destinationId = "piazza-square";
const destinationPoint = new THREE.Vector3(45, 0, 25);
addPedNode(destinationId, destinationPoint);
const nearestDestinationNodes = [...pedNodes.values()]
.filter((node) => node.id !== destinationId)
.map((node) => ({
node,
distance: node.position.distanceTo(destinationPoint)
}))
.filter((entry) => entry.distance < 19)
.sort((a, b) => a.distance - b.distance)
.slice(0, 5);
nearestDestinationNodes.forEach((entry) => {
connectPed(destinationId, entry.node.id);
});
function dijkstra(startId) {
const distances = new Map();
const previous = new Map();
const unvisited = new Set(adjacency.keys());
[...unvisited].forEach((id) => distances.set(id, Infinity));
distances.set(startId, 0);
while (unvisited.size) {
let current = null;
let currentDistance = Infinity;
unvisited.forEach((id) => {
const distance = distances.get(id);
if (distance < currentDistance) {
current = id;
currentDistance = distance;
}
});
if (current === null) break;
if (current === destinationId) break;
unvisited.delete(current);
adjacency.get(current).forEach((neighbor) => {
if (!unvisited.has(neighbor.id)) return;
const nextDistance = currentDistance + neighbor.length;
if (nextDistance < distances.get(neighbor.id)) {
distances.set(neighbor.id, nextDistance);
previous.set(neighbor.id, current);
}
});
}
if (!distances.has(destinationId) || !Number.isFinite(distances.get(destinationId))) {
return { ids: [], distance: Infinity };
}
const ids = [destinationId];
let cursor = destinationId;
while (cursor !== startId) {
cursor = previous.get(cursor);
if (!cursor) return { ids: [], distance: Infinity };
ids.unshift(cursor);
}
return { ids, distance: distances.get(destinationId) };
}
const WORLD_METERS = 2.15;
candidates.forEach((candidate) => {
const start = candidate.side === 1 ? candidate.nodePlus : candidate.nodeMinus;
const result = dijkstra(start);
candidate.routeIds = result.ids;
candidate.routeLengthMeters = result.distance * WORLD_METERS;
});
// -------------------------------------------------------------------------
// Placement pads
// -------------------------------------------------------------------------
const candidatePads = [];
const candidateById = new Map(candidates.map((candidate) => [candidate.id, candidate]));
candidates.forEach((candidate) => {
const material = new THREE.MeshStandardMaterial({
color: 0x23c4c4,
emissive: 0x0b777b,
emissiveIntensity: 0.55,
transparent: true,
opacity: 0.82,
roughness: 0.5
});
const pad = addBox(
dynamicGroup,
3.1,
0.22,
3.1,
candidate.point.x,
0.64,
candidate.point.z,
material,
{ castShadow: false }
);
pad.userData.candidateId = candidate.id;
pad.visible = false;
candidatePads.push(pad);
});
// -------------------------------------------------------------------------
// Crossing point data and visuals
// -------------------------------------------------------------------------
const crossings = [];
const crossingVisuals = new Map();
let selectedCrossingId = null;
let crossingCounter = 0;
let placementMode = false;
let hoveredCandidate = null;
function conflictRisk(conflictCount, signal) {
if (conflictCount === 0) return { label: "None", className: "none" };
if (conflictCount >= 3 || (conflictCount >= 2 && signal === "Unsignalized")) {
return { label: "High", className: "high" };
}
if (conflictCount === 2) return { label: "Moderate", className: "medium" };
return { label: "Low", className: "low" };
}
function makeCrossingVisual(crossing) {
const group = new THREE.Group();
group.position.copy(crossing.candidate.point);
group.position.y = 0.48;
const baseMaterial = new THREE.MeshStandardMaterial({
color: 0xf3efe6,
roughness: 0.72
});
const base = addBox(group, 2.6, 0.55, 2.6, 0, 0.2, 0, baseMaterial);
addBox(group, 0.7, 3.8, 0.7, -0.75, 2.1, 0, 0xe4d6b8);
addBox(group, 0.7, 3.8, 0.7, 0.75, 2.1, 0, 0xe4d6b8);
addBox(group, 2.4, 0.65, 0.8, 0, 4.0, 0, baseMaterial);
const beacon = addBox(
group,
1.0,
1.0,
1.0,
0,
4.8,
0,
new THREE.MeshStandardMaterial({
color: 0x23c4c4,
emissive: 0x23c4c4,
emissiveIntensity: 0.7,
roughness: 0.45
})
);
const label = textSprite(crossing.id, "#77e4df", 7.5);
label.position.set(0, 7.3, 0);
group.add(label);
group.userData.crossingId = crossing.id;
group.traverse((object) => {
object.userData.crossingId = crossing.id;
});
dynamicGroup.add(group);
crossingVisuals.set(crossing.id, { group, base, beacon, label });
}
function addCrossing(candidateId, name, isUser = false) {
const candidate = candidateById.get(candidateId);
if (!candidate) return null;
if (crossings.some((crossing) => crossing.candidateId === candidateId)) {
showToast("That crossing pad is already occupied.");
return null;
}
crossingCounter += 1;
const crossing = {
id: `CP-${String(crossingCounter).padStart(2, "0")}`,
name: name || `${candidate.label} Point`,
candidateId,
candidate,
isUser,
routeLengthMeters: candidate.routeLengthMeters,
crossingLengthMeters: candidate.width,
signal: candidate.signal,
conflicts: candidate.conflicts
};
crossings.push(crossing);
makeCrossingVisual(crossing);
selectCrossing(crossing.id);
refreshPointList();
return crossing;
}
function removeCrossing(id) {
const index = crossings.findIndex((crossing) => crossing.id === id);
if (index === -1) return;
const visual = crossingVisuals.get(id);
if (visual) {
dynamicGroup.remove(visual.group);
visual.group.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) object.material.dispose();
});
crossingVisuals.delete(id);
}
crossings.splice(index, 1);
if (selectedCrossingId === id) {
selectedCrossingId = crossings.at(-1)?.id ?? null;
if (selectedCrossingId) selectCrossing(selectedCrossingId);
else clearSelection();
}
refreshPointList();
}
function clearSelection() {
selectedCrossingId = null;
disposeGroup(overlayGroup);
$("selectedName").textContent = "No crossing selected";
$("selectedSubtitle").textContent = "Choose a marker in the model";
$("selectedId").textContent = "—";
$("routeLength").textContent = "—";
$("conflictCount").textContent = "—";
$("crossingWidth").textContent = "—";
$("signalType").textContent = "—";
$("riskRating").className = "risk none";
$("riskRating").textContent = "—";
$("conflictList").innerHTML = "";
$("removeButton").disabled = true;
$("liveRisk").textContent = "Live: 0";
}
function selectCrossing(id) {
const crossing = crossings.find((item) => item.id === id);
if (!crossing) return;
selectedCrossingId = id;
crossingVisuals.forEach((visual, visualId) => {
const selected = visualId === id;
visual.base.material.color.set(selected ? 0x23c4c4 : 0xf3efe6);
visual.beacon.material.color.set(selected ? 0xffad32 : 0xe4d6b8);
visual.beacon.material.emissive.set(selected ? 0xff7b00 : 0x000000);
visual.beacon.material.emissiveIntensity = selected ? 0.85 : 0;
});
buildSelectedOverlays(crossing);
updateCrossingDetails(crossing);
refreshPointList();
}
let conflictMarkers = [];
function buildSelectedOverlays(crossing) {
disposeGroup(overlayGroup);
conflictMarkers = [];
const candidate = crossing.candidate;
const road = candidate.road;
const data = candidate.roadData;
const center = pointOnRoad(road, candidate.t);
center.y = 0.68;
// Proposed crossing bars across the fixed vehicle lane.
for (let i = -3; i <= 3; i++) {
const p = center.clone().addScaledVector(data.tangent, i * 1.55);
addBox(
overlayGroup,
0.85,
0.13,
road.width - 1.5,
p.x,
0.53,
p.z,
0xf8f1d6,
{
rotationY: -data.angle,
castShadow: false
}
);
}
crossing.conflicts.forEach((route, index) => {
const lateral = index % 2 === 0 ? -2.2 : 2.2;
const p = center
.clone()
.addScaledVector(data.tangent, (index - 1) * 3.1)
.addScaledVector(data.normal, lateral);
const marker = addBox(
overlayGroup,
1.6,
1.3,
1.6,
p.x,
1.1,
p.z,
new THREE.MeshStandardMaterial({
color: route.color,
emissive: route.color,
emissiveIntensity: 0.35,
roughness: 0.55
})
);
marker.rotation.y = Math.PI / 4;
marker.userData.routeId = route.id;
conflictMarkers.push(marker);
});
// Walking route from the selected sidewalk to Piazza Square.
const routeIds = candidate.routeIds;
const routePoints = routeIds.map((id) =>
pedNodes.get(id).position.clone().setY(0.75)
);
if (routePoints.length > 1) {
const line = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(routePoints),
new THREE.LineBasicMaterial({ color: 0xffad32 })
);
overlayGroup.add(line);
}
const routeMaterial = new THREE.MeshStandardMaterial({
color: 0xffad32,
emissive: 0x8c4d00,
emissiveIntensity: 0.35,
roughness: 0.55
});
for (let i = 0; i < routePoints.length - 1; i++) {
const a = routePoints[i];
const b = routePoints[i + 1];
const segmentLength = a.distanceTo(b);
const steps = Math.max(1, Math.ceil(segmentLength / 2.5));
for (let step = 0; step < steps; step++) {
const t = (step + 0.5) / steps;
const p = a.clone().lerp(b, t);
const direction = b.clone().sub(a);
const angle = Math.atan2(direction.z, direction.x);
addBox(
overlayGroup,
1.15,
0.42,
1.15,
p.x,
0.68,
p.z,
routeMaterial,
{ rotationY: -angle, castShadow: false }
);
}
}
addBox(
overlayGroup,
3.2,
0.65,
3.2,
destinationPoint.x,
0.75,
destinationPoint.z,
new THREE.MeshStandardMaterial({
color: 0x87c94a,
emissive: 0x477c20,
emissiveIntensity: 0.4
}),
{ castShadow: false }
);
}
function updateCrossingDetails(crossing) {
const risk = conflictRisk(crossing.conflicts.length, crossing.signal);
$("selectedName").textContent = crossing.name;
$("selectedSubtitle").textContent =
`${crossing.candidate.road.name} · ${crossing.isUser ? "Added point" : "Seed scenario"}`;
$("selectedId").textContent = crossing.id;
$("routeLength").textContent = Math.round(crossing.routeLengthMeters).toLocaleString();
$("conflictCount").textContent = crossing.conflicts.length;
$("crossingWidth").textContent = `${crossing.crossingLengthMeters} m`;
$("signalType").textContent = crossing.signal;
$("riskRating").className = `risk ${risk.className}`;
$("riskRating").textContent = risk.label;
$("removeButton").disabled = false;
$("conflictList").innerHTML = crossing.conflicts.length
? crossing.conflicts
.map((route) => {
const length = Math.round(route.total * WORLD_METERS);
return `
<div class="conflict-item">
<span class="route-dot" style="background:#${route.color.toString(16).padStart(6, "0")}"></span>
<span class="route-name">${route.name}</span>
<span class="route-meta">${length} m path</span>
</div>
`;
})
.join("")
: `<div class="conflict-item">No fixed vehicle path uses this road segment.</div>`;
}
function refreshPointList() {
$("pointCount").textContent = `${crossings.length} point${crossings.length === 1 ? "" : "s"}`;
if (!crossings.length) {
$("pointList").innerHTML = `<p class="note">No crossing points yet. Use “Place crossing” and select a turquoise sidewalk pad.</p>`;
return;
}
$("pointList").innerHTML = crossings
.map(
(crossing) => `
<button class="point-row ${crossing.id === selectedCrossingId ? "active" : ""}" data-id="${crossing.id}">
<span class="point-code">${crossing.id}</span>
<span>
<span class="point-name">${crossing.name}</span>
<span class="point-sub">${Math.round(crossing.routeLengthMeters)} m walk · ${crossing.signal}</span>
</span>
<span class="point-conflicts">${crossing.conflicts.length} conflict${crossing.conflicts.length === 1 ? "" : "s"}</span>
</button>
`
)
.join("");
}
function refreshTrafficList() {
$("trafficList").innerHTML = routes
.map((route) => {
const color = `#${route.color.toString(16).padStart(6, "0")}`;
return `
<div class="traffic-row">
<span class="traffic-bar" style="background:${color}"></span>
<span>
<span class="traffic-name">${route.name}</span>
<span class="traffic-sub">${route.segments.length} fixed segments</span>
</span>
<span class="traffic-length">${Math.round(route.total * WORLD_METERS)} m</span>
</div>
`;
})
.join("");
}
// -------------------------------------------------------------------------
// Interaction and custom camera controls
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const tooltip = $("tooltip");
let pointerDown = false;
let pointerMoved = false;
let lastX = 0;
let lastY = 0;
let panning = false;
function updatePointer(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;
}
function hitCandidate() {
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(candidatePads, false);
return hits.length ? candidateById.get(hits[0].object.userData.candidateId) : null;
}
function hitCrossing() {
raycaster.setFromCamera(pointer, camera);
const groups = [...crossingVisuals.values()].map((visual) => visual.group);
const hits = raycaster.intersectObjects(groups, true);
if (!hits.length) return null;
let object = hits[0].object;
while (object && !object.userData.crossingId) object = object.parent;
return object?.userData.crossingId ?? null;
}
function setPlacementMode(enabled) {
placementMode = enabled;
candidatePads.forEach((pad) => {
pad.visible = enabled;
if (!enabled) pad.scale.setScalar(1);
});
$("addButton").classList.toggle("active", enabled);
$("addButton").textContent = enabled ? "✓ Finish placing" : "+ Place crossing";
$("modeLabel").textContent = enabled ? "Placement mode" : "Explore mode";
$("modeHelp").textContent = enabled
? "Select a turquoise sidewalk pad to place a fictional crossing. The fixed district remains unchanged."
: "Drag to orbit, right-drag to pan, and scroll to zoom. Select a crossing marker to inspect it.";
renderer.domElement.style.cursor = enabled ? "crosshair" : "grab";
tooltip.style.display = "none";
}
renderer.domElement.addEventListener("pointerdown", (event) => {
pointerDown = true;
pointerMoved = false;
lastX = event.clientX;
lastY = event.clientY;
panning = event.button === 2 || event.shiftKey;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
updatePointer(event);
if (pointerDown) {
const dx = event.clientX - lastX;
const dy = event.clientY - lastY;
if (Math.abs(dx) + Math.abs(dy) > 2) pointerMoved = true;
if (panning) {
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0);
right.y = 0;
right.normalize();
const forward = cameraState.target.clone().sub(camera.position);
forward.y = 0;
forward.normalize();
const scale = cameraState.radius * 0.0014;
cameraState.target.addScaledVector(right, dx * scale);
cameraState.target.addScaledVector(forward, dy * scale);
cameraState.target.x = THREE.MathUtils.clamp(cameraState.target.x, -75, 75);
cameraState.target.z = THREE.MathUtils.clamp(cameraState.target.z, -65, 75);
updateCamera();
} else {
cameraState.azimuth -= dx * 0.005;
cameraState.polar = THREE.MathUtils.clamp(
cameraState.polar + dy * 0.004,
0.35,
1.22
);
updateCamera();
}
lastX = event.clientX;
lastY = event.clientY;
}
if (placementMode) {
const candidate = hitCandidate();
if (candidate !== hoveredCandidate) {
hoveredCandidate = candidate;
candidatePads.forEach((pad) => {
const active = pad.userData.candidateId === candidate?.id;
pad.scale.setScalar(active ? 1.35 : 1);
pad.material.emissiveIntensity = active ? 1.2 : 0.55;
});
}
if (candidate) {
const rect = viewport.getBoundingClientRect();
tooltip.innerHTML = `
<strong>${candidate.label}</strong>
Click to place · ${candidate.conflicts.length} vehicle path conflict${candidate.conflicts.length === 1 ? "" : "s"}<br>
Approx. ${Math.round(candidate.routeLengthMeters)} m walk to Piazza Square
`;
tooltip.style.display = "block";
tooltip.style.left = `${Math.min(event.clientX - rect.left + 15, rect.width - 245)}px`;
tooltip.style.top = `${Math.max(8, event.clientY - rect.top - 70)}px`;
} else {
tooltip.style.display = "none";
}
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (!pointerDown) return;
updatePointer(event);
if (!pointerMoved) {
if (placementMode) {
const candidate = hitCandidate();
if (candidate) {
const crossing = addCrossing(candidate.id, `${candidate.label} Crossing`, true);
if (crossing) {
showToast(`${crossing.id} placed at ${candidate.label}.`);
}
}
} else {
const crossingId = hitCrossing();
if (crossingId) selectCrossing(crossingId);
}
}
pointerDown = false;
panning = false;
});
renderer.domElement.addEventListener("pointerleave", () => {
pointerDown = false;
panning = false;
tooltip.style.display = "none";
});
renderer.domElement.addEventListener("wheel", (event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
105,
330
);
updateCamera();
}, { passive: false });
renderer.domElement.addEventListener("contextmenu", (event) => event.preventDefault());
// -------------------------------------------------------------------------
// UI actions
// -------------------------------------------------------------------------
let toastTimer;
function showToast(message) {
const toast = $("toast");
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 2600);
}
$("addButton").addEventListener("click", () => {
setPlacementMode(!placementMode);
});
$("trafficButton").addEventListener("click", () => {
trafficGroup.visible = !trafficGroup.visible;
$("trafficButton").textContent = `Traffic: ${trafficGroup.visible ? "on" : "off"}`;
$("trafficButton").classList.toggle("active", !trafficGroup.visible);
});
$("clearButton").addEventListener("click", () => {
const userCrossings = crossings.filter((crossing) => crossing.isUser);
userCrossings.forEach((crossing) => removeCrossing(crossing.id));
refreshPointList();
showToast(`${userCrossings.length} added crossing point${userCrossings.length === 1 ? "" : "s"} cleared.`);
});
$("resetButton").addEventListener("click", () => {
resetCamera();
showToast("Camera reset. Fixed district unchanged.");
});
$("removeButton").addEventListener("click", () => {
if (!selectedCrossingId) return;
const id = selectedCrossingId;
removeCrossing(id);
showToast(`${id} removed.`);
});
$("pointList").addEventListener("click", (event) => {
const button = event.target.closest(".point-row");
if (!button) return;
selectCrossing(button.dataset.id);
});
// -------------------------------------------------------------------------
// Seed scenario
// -------------------------------------------------------------------------
refreshTrafficList();
addCrossing("avenue-south-a", "Lazarus Gate", false);
addCrossing("diagonal-square", "Meridian Steps", false);
clearSelection();
selectCrossing("CP-01");
refreshPointList();
// -------------------------------------------------------------------------
// Animation and live conflict feedback
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function updateTraffic(elapsed) {
const liveRouteIds = new Set();
cars.forEach((car) => {
const distance = elapsed * car.speed + car.offset * car.route.total;
const state = routePoint(car.route, distance);
const segment = state.segment;
const a = nodePositions[segment.a];
const b = nodePositions[segment.b];
const angle = Math.atan2(b.z - a.z, b.x - a.x);
car.group.position.copy(state.position);
car.group.position.y = 0.48;
car.group.rotation.y = -angle;
car.segment = segment;
car.position.copy(state.position);
if (!selectedCrossingId) return;
const crossing = crossings.find((item) => item.id === selectedCrossingId);
if (!crossing) return;
const candidate = crossing.candidate;
const center = pointOnRoad(candidate.road, candidate.t);
if (
segment.edgeId === candidate.edge &&
state.position.distanceTo(center) < 22
) {
liveRouteIds.add(car.route.id);
}
});
conflictMarkers.forEach((marker) => {
const routeId = marker.userData.routeId;
const active = liveRouteIds.has(routeId);
marker.scale.setScalar(active ? 1.65 : 0.82);
marker.material.color.set(active ? 0xef476f : routes.find((route) => route.id === routeId).color);
marker.material.emissive.set(active ? 0xef476f : routes.find((route) => route.id === routeId).color);
marker.material.emissiveIntensity = active ? 1.2 : 0.25;
});
$("liveRisk").textContent = `Live: ${liveRouteIds.size}`;
}
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
updateTraffic(elapsed);
crossingVisuals.forEach((visual, id) => {
if (id === selectedCrossingId) {
visual.beacon.rotation.y = elapsed * 1.8;
visual.beacon.position.y = 4.8 + Math.sin(elapsed * 3.2) * 0.25;
}
});
renderer.render(scene, camera);
}
animate();
// Fixed East Africa Time display: UTC+3.
function updateClock() {
const now = new Date();
const eat = new Date(now.getTime() + (3 * 60 + now.getTimezoneOffset()) * 60000);
$("eatClock").textContent = `EAT ${eat.toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
hour12: false
})}`;
}
updateClock();
setInterval(updateClock, 30000);
</script>
</body>
</html>
```