Prompt specification
Build or customize the Three.js 3D scene "Inspect connectivity across stairs and roofline levels" 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: Inspect connectivity across stairs and roofline levels
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/inspect-connectivity-across-stairs-and-roofline-levels-x2892
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing the Casbah's terraces and lanes in Algiers. Let users trace permitted ground routes between marked entrances. Keep rooftops visually present but inaccessible unless an explicit modeled stair or passage connects them. Voxel style.
Working Three.js Starter (inspect-connectivity-across-stairs-and-roofline-levels-x2892):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Casbah Route Finder — Algiers</title>
<style>
:root {
--ink: #14343b;
--muted: #5d7275;
--paper: rgba(248, 246, 236, 0.94);
--line: rgba(20, 52, 59, 0.16);
--teal: #087f78;
--gold: #d69a35;
--red: #d6534d;
--green: #16896a;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #b9d5dc;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--ink);
}
canvas {
display: block;
touch-action: none;
}
#panel {
position: fixed;
z-index: 10;
top: 18px;
left: 18px;
width: min(350px, calc(100vw - 36px));
max-height: calc(100vh - 36px);
overflow: auto;
padding: 20px;
border: 1px solid rgba(255, 255, 255, 0.7);
border-radius: 18px;
background: var(--paper);
box-shadow: 0 18px 55px rgba(27, 54, 57, 0.22);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
scrollbar-width: thin;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 6px;
color: var(--teal);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 8px;
height: 8px;
border-radius: 2px;
background: var(--gold);
transform: rotate(45deg);
}
h1 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: 30px;
font-weight: 600;
letter-spacing: -0.035em;
line-height: 1.03;
}
.subtitle {
margin: 8px 0 17px;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.section-title {
display: flex;
justify-content: space-between;
align-items: baseline;
margin: 16px 0 8px;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.section-title span {
color: var(--muted);
font-size: 9px;
font-weight: 650;
letter-spacing: 0.08em;
}
#entranceList {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
}
.entrance {
display: flex;
align-items: center;
gap: 7px;
min-width: 0;
padding: 8px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255, 255, 255, 0.55);
color: var(--ink);
font: inherit;
font-size: 10px;
text-align: left;
cursor: pointer;
transition: background 140ms ease, border-color 140ms ease, transform 140ms ease;
}
.entrance:hover {
transform: translateY(-1px);
border-color: rgba(8, 127, 120, 0.5);
background: white;
}
.entrance .letter {
display: grid;
flex: 0 0 23px;
width: 23px;
height: 23px;
place-items: center;
border-radius: 50%;
background: var(--ink);
color: white;
font-size: 10px;
font-weight: 800;
}
.entrance .name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.entrance.start {
border-color: var(--green);
background: rgba(22, 137, 106, 0.1);
}
.entrance.start .letter {
background: var(--green);
}
.entrance.end {
border-color: var(--red);
background: rgba(214, 83, 77, 0.1);
}
.entrance.end .letter {
background: var(--red);
}
.actions {
display: grid;
grid-template-columns: 1fr auto;
gap: 7px;
margin-top: 14px;
}
button {
font: inherit;
}
.primary,
.secondary {
min-height: 40px;
border-radius: 10px;
cursor: pointer;
transition: transform 140ms ease, filter 140ms ease, opacity 140ms ease;
}
.primary {
border: 0;
background: var(--teal);
color: white;
font-size: 12px;
font-weight: 750;
letter-spacing: 0.03em;
}
.secondary {
padding: 0 12px;
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.65);
color: var(--ink);
font-size: 11px;
font-weight: 700;
}
.primary:hover,
.secondary:hover {
transform: translateY(-1px);
filter: brightness(1.05);
}
.primary:disabled {
opacity: 0.42;
cursor: default;
transform: none;
filter: none;
}
#status {
margin-top: 12px;
padding: 11px 12px;
border-left: 3px solid var(--gold);
border-radius: 4px 9px 9px 4px;
background: rgba(214, 154, 53, 0.11);
font-size: 12px;
line-height: 1.45;
}
#status.success {
border-left-color: var(--teal);
background: rgba(8, 127, 120, 0.1);
}
#status.warning {
border-left-color: var(--red);
background: rgba(214, 83, 77, 0.1);
}
#routeInfo {
min-height: 36px;
margin-top: 9px;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
#routeInfo b {
color: var(--ink);
}
.legend {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px 10px;
margin-top: 14px;
padding-top: 13px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 10px;
}
.legend div {
display: flex;
align-items: center;
gap: 6px;
}
.dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--ink);
}
.dot.start { background: var(--green); }
.dot.end { background: var(--red); }
.dot.route { background: #18bcb3; }
.dot.roof {
border-radius: 2px;
background: #c6b79a;
}
.view-row {
display: flex;
gap: 7px;
margin-top: 12px;
}
.view-row .secondary {
flex: 1;
padding: 0 8px;
}
#compass {
position: fixed;
z-index: 5;
top: 23px;
right: 24px;
display: grid;
width: 48px;
height: 48px;
place-items: center;
border: 1px solid rgba(255, 255, 255, 0.6);
border-radius: 50%;
background: rgba(248, 246, 236, 0.72);
box-shadow: 0 8px 25px rgba(28, 56, 60, 0.12);
color: var(--ink);
font-size: 10px;
font-weight: 800;
pointer-events: none;
}
#compassArrow {
position: absolute;
top: 7px;
width: 0;
height: 0;
border-right: 5px solid transparent;
border-bottom: 15px solid var(--red);
border-left: 5px solid transparent;
transform-origin: 50% 17px;
}
#hint {
position: fixed;
z-index: 5;
right: 20px;
bottom: 18px;
padding: 8px 11px;
border-radius: 9px;
background: rgba(248, 246, 236, 0.78);
color: rgba(20, 52, 59, 0.76);
font-size: 10px;
pointer-events: none;
backdrop-filter: blur(8px);
}
#tooltip {
position: fixed;
z-index: 20;
display: none;
max-width: 230px;
padding: 8px 10px;
border-radius: 8px;
background: rgba(20, 52, 59, 0.93);
color: white;
font-size: 11px;
line-height: 1.35;
pointer-events: none;
box-shadow: 0 8px 20px rgba(20, 52, 59, 0.2);
}
@media (max-width: 650px) {
#panel {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
max-height: 58vh;
padding: 15px;
border-radius: 14px;
}
h1 { font-size: 25px; }
.subtitle { margin-bottom: 11px; }
#entranceList { grid-template-columns: repeat(4, 1fr); }
.entrance { justify-content: center; padding: 7px 4px; }
.entrance .name { display: none; }
#compass { top: auto; right: 12px; bottom: 52px; }
#hint { left: 10px; right: auto; bottom: 10px; }
}
</style>
</head>
<body>
<aside id="panel">
<div class="eyebrow">Algiers · Algeria</div>
<h1>Casbah Route Finder</h1>
<p class="subtitle">
Select two marked ground entrances and trace a permitted route through
the old medina.
</p>
<div class="section-title">
Ground entrances <span>Select start, then destination</span>
</div>
<div id="entranceList"></div>
<div class="actions">
<button id="traceButton" class="primary" type="button">Trace permitted route</button>
<button id="clearButton" class="secondary" type="button">Clear</button>
</div>
<div id="status" role="status" aria-live="polite">
Choose an entrance to begin.
</div>
<div id="routeInfo"></div>
<div class="legend">
<div><span class="dot start"></span> Start entrance</div>
<div><span class="dot end"></span> Destination</div>
<div><span class="dot route"></span> Permitted route</div>
<div><span class="dot roof"></span> Locked rooftop</div>
</div>
<div class="view-row">
<button id="overviewButton" class="secondary" type="button">Overview</button>
<button id="topButton" class="secondary" type="button">Plan view</button>
<button id="resetButton" class="secondary" type="button">Reset picks</button>
</div>
</aside>
<div id="compass" aria-hidden="true">
<span>N</span>
<div id="compassArrow"></div>
</div>
<div id="hint">
Drag to orbit · Shift/right-drag to pan · Scroll to zoom · R to trace
</div>
<div id="tooltip"></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 statusEl = $("#status");
const routeInfoEl = $("#routeInfo");
const tooltipEl = $("#tooltip");
const traceButton = $("#traceButton");
const clearButton = $("#clearButton");
const resetButton = $("#resetButton");
const overviewButton = $("#overviewButton");
const topButton = $("#topButton");
const compassArrow = $("#compassArrow");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xb9d5dc);
scene.fog = new THREE.Fog(0xb9d5dc, 76, 155);
const camera = new THREE.PerspectiveCamera(
42,
innerWidth / innerHeight,
0.1,
260
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
document.body.prepend(renderer.domElement);
const world = new THREE.Group();
scene.add(world);
const hemi = new THREE.HemisphereLight(0xe6f4f5, 0x8c7759, 2.0);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff2d4, 3.1);
sun.position.set(-32, 58, 26);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -52;
sun.shadow.camera.right = 52;
sun.shadow.camera.top = 52;
sun.shadow.camera.bottom = -52;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 140;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xb7d9e5, 0.7);
fill.position.set(30, 18, -35);
scene.add(fill);
const material = {
land: new THREE.MeshStandardMaterial({
color: 0xc8b590, roughness: 1
}),
cliff: new THREE.MeshStandardMaterial({
color: 0xaa9678, roughness: 1
}),
sea: new THREE.MeshStandardMaterial({
color: 0x4c9fac, roughness: 0.52, metalness: 0.05
}),
wave: new THREE.MeshStandardMaterial({
color: 0xb4dce0, roughness: 0.8
}),
lane: new THREE.MeshStandardMaterial({
color: 0xe0cda8, roughness: 1
}),
laneEdge: new THREE.MeshStandardMaterial({
color: 0x9f8e74, roughness: 1
}),
walls: [
new THREE.MeshStandardMaterial({ color: 0xf1ead9, roughness: 0.94 }),
new THREE.MeshStandardMaterial({ color: 0xe7dfcf, roughness: 0.96 }),
new THREE.MeshStandardMaterial({ color: 0xf6efdf, roughness: 0.93 }),
new THREE.MeshStandardMaterial({ color: 0xdcd7c9, roughness: 0.97 })
],
roof: new THREE.MeshStandardMaterial({ color: 0xcfc5ac, roughness: 0.98 }),
terrace: new THREE.MeshStandardMaterial({ color: 0xd8c7a6, roughness: 0.95 }),
parapet: new THREE.MeshStandardMaterial({ color: 0xe9dfca, roughness: 1 }),
window: new THREE.MeshStandardMaterial({ color: 0x294c52, roughness: 0.68 }),
stair: new THREE.MeshStandardMaterial({ color: 0xc5b393, roughness: 1 }),
passage: new THREE.MeshStandardMaterial({ color: 0xd8c9a9, roughness: 0.96 }),
passageWall: new THREE.MeshStandardMaterial({ color: 0xcbb995, roughness: 1 }),
gold: new THREE.MeshStandardMaterial({ color: 0xd39a3a, roughness: 0.75 }),
green: new THREE.MeshStandardMaterial({ color: 0x557d57, roughness: 0.95 })
};
const routeMaterial = new THREE.MeshStandardMaterial({
color: 0x1cc6ba,
emissive: 0x086c67,
emissiveIntensity: 0.85,
roughness: 0.38
});
const travelerMaterial = new THREE.MeshStandardMaterial({
color: 0xffd166,
emissive: 0xd48a17,
emissiveIntensity: 1.25,
roughness: 0.25
});
const UP = new THREE.Vector3(0, 1, 0);
const dummy = new THREE.Object3D();
function seededRandom(seed) {
return function () {
seed = (seed * 1664525 + 1013904223) >>> 0;
return seed / 4294967296;
};
}
const random = seededRandom(41723);
const range = (a, b) => a + (b - a) * random();
/*
Navigation graph:
- Ground lanes are explicitly permitted edges.
- Roof nodes can only be reached through modeled stairs/passages.
- Decorative rooftops are intentionally absent from this graph.
*/
const nodes = new Map();
const nodeData = [
["A", "Harbor Gate", [-25, 0, 17], true],
["B", "Lower Souk", [-17, 0, 8], true],
["C", "Cypress Corner", [-9, 0, -1], true],
["D", "North Steps", [-1, 0, -13], true],
["E", "Citadel Gate", [2, 0, -25], true],
["F", "Sea View", [23, 0, -5], true],
["G", "Market Gate", [10, 0, 14], true],
["H", "South Arch", [-5, 0, 21], true],
["R1", "Sun Terrace", [-4, 3.2, 8], false],
["R2", "Meridian Deck", [5, 5.8, -7], false],
["R3", "Star Roof", [15, 8.5, -22], false]
];
for (const [id, label, position, entrance] of nodeData) {
nodes.set(id, {
id,
label,
entrance,
pos: new THREE.Vector3(...position)
});
}
const edgeData = [
["A", "B", "lane"],
["B", "C", "lane"],
["C", "D", "lane"],
["D", "E", "lane"],
["E", "F", "lane"],
["F", "G", "lane"],
["G", "H", "lane"],
["H", "B", "lane"],
["B", "D", "lane"],
["C", "R1", "stair"],
["R1", "G", "stair"],
["D", "R2", "stair"],
["E", "R3", "stair"],
["R1", "R2", "passage"],
["R2", "R3", "passage"]
];
const edges = edgeData.map(([a, b, type]) => ({
a, b, type
}));
const adjacency = new Map();
for (const id of nodes.keys()) adjacency.set(id, []);
for (const edge of edges) {
adjacency.get(edge.a).push({ to: edge.b, edge });
adjacency.get(edge.b).push({ to: edge.a, edge });
}
function edgeBetween(a, b) {
return edges.find(
(edge) =>
(edge.a === a && edge.b === b) ||
(edge.a === b && edge.b === a)
);
}
// Terrain, sea and quay.
const land = new THREE.Mesh(
new THREE.BoxGeometry(64, 3.2, 64),
material.land
);
land.position.set(0, -1.6, 0);
land.receiveShadow = true;
world.add(land);
const sea = new THREE.Mesh(
new THREE.BoxGeometry(66, 1.2, 94),
material.sea
);
sea.position.set(-65, -3.15, 0);
sea.receiveShadow = true;
world.add(sea);
for (let z = -29; z <= 29; z += 6.5) {
const wall = new THREE.Mesh(
new THREE.BoxGeometry(1.4, range(2.4, 4.0), 6.1),
material.cliff
);
wall.position.set(-31.1, -1.1, z + range(-0.2, 0.2));
wall.castShadow = true;
wall.receiveShadow = true;
world.add(wall);
}
const waveTransforms = [];
for (let i = 0; i < 42; i++) {
waveTransforms.push({
x: range(-89, -35),
z: range(-43, 43),
length: range(1.4, 4.8),
y: -2.52 + range(-0.05, 0.05)
});
}
const waveMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 0.07, 0.16),
material.wave,
waveTransforms.length
);
waveTransforms.forEach((wave, index) => {
dummy.position.set(wave.x, wave.y, wave.z);
dummy.rotation.set(0, range(-0.25, 0.25), 0);
dummy.scale.set(wave.length, 1, 1);
dummy.updateMatrix();
waveMesh.setMatrixAt(index, dummy.matrix);
});
waveMesh.instanceMatrix.needsUpdate = true;
world.add(waveMesh);
const windowTransforms = [];
const parapetTransforms = [];
const roofPropTransforms = [];
const stairTransforms = [];
function pushBox(list, width, height, depth, x, y, z, rotationY = 0) {
dummy.position.set(x, y, z);
dummy.rotation.set(0, rotationY, 0);
dummy.scale.set(width, height, depth);
dummy.updateMatrix();
list.push(dummy.matrix.clone());
}
function createInstancedBoxes(list, mat, castShadow = true) {
if (!list.length) return null;
const mesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
mat,
list.length
);
list.forEach((matrix, index) => mesh.setMatrixAt(index, matrix));
mesh.instanceMatrix.needsUpdate = true;
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
world.add(mesh);
return mesh;
}
function addWindows(x, z, width, depth, height, rotation = 0) {
const floors = Math.max(1, Math.floor((height - 0.4) / 2.45));
for (let floor = 0; floor < floors; floor++) {
const y = 1.15 + floor * 2.45;
if (y > height - 0.45) continue;
const columns = Math.max(1, Math.floor(width / 1.25));
for (let col = 0; col < columns; col++) {
const localX = -width / 2 + ((col + 0.5) * width) / columns;
const localZ = depth / 2 + 0.035;
pushBox(
windowTransforms,
0.48, 0.66, 0.07,
x + localX * Math.cos(rotation) + localZ * Math.sin(rotation),
y,
z - localX * Math.sin(rotation) + localZ * Math.cos(rotation),
rotation
);
pushBox(
windowTransforms,
0.48, 0.66, 0.07,
x - localX * Math.cos(rotation) - localZ * Math.sin(rotation),
y,
z + localX * Math.sin(rotation) - localZ * Math.cos(rotation),
rotation
);
}
const sideColumns = Math.max(1, Math.floor(depth / 1.35));
for (let col = 0; col < sideColumns; col++) {
const localZ = -depth / 2 + ((col + 0.5) * depth) / sideColumns;
const localX = width / 2 + 0.035;
pushBox(
windowTransforms,
0.07, 0.66, 0.48,
x + localX * Math.cos(rotation) + localZ * Math.sin(rotation),
y,
z - localX * Math.sin(rotation) + localZ * Math.cos(rotation),
rotation
);
pushBox(
windowTransforms,
0.07, 0.66, 0.48,
x - localX * Math.cos(rotation) - localZ * Math.sin(rotation),
y,
z + localX * Math.sin(rotation) - localZ * Math.cos(rotation),
rotation
);
}
}
}
const interactiveObjects = [];
const specialFootprints = [];
function addRandomBuilding(x, z, width, depth, height, materialIndex) {
const body = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material.walls[materialIndex]
);
body.position.set(x, height / 2, z);
body.castShadow = true;
body.receiveShadow = true;
world.add(body);
const roof = new THREE.Mesh(
new THREE.BoxGeometry(width + 0.34, 0.28, depth + 0.34),
material.roof
);
roof.position.set(x, height + 0.08, z);
roof.castShadow = true;
roof.receiveShadow = true;
roof.userData.pickType = "roof";
roof.userData.accessible = false;
roof.userData.label = "Unconnected rooftop";
interactiveObjects.push(roof);
world.add(roof);
addWindows(x, z, width, depth, height);
const p = 0.16;
pushBox(parapetTransforms, width + 0.25, 0.55, p, x, height + 0.45, z + depth / 2);
pushBox(parapetTransforms, width + 0.25, 0.55, p, x, height + 0.45, z - depth / 2);
pushBox(parapetTransforms, p, 0.55, depth + 0.25, x + width / 2, height + 0.45, z);
pushBox(parapetTransforms, p, 0.55, depth + 0.25, x - width / 2, height + 0.45, z);
const propX = x + width * 0.22;
const propZ = z - depth * 0.19;
pushBox(roofPropTransforms, 1.15, 0.82, 0.95, propX, height + 0.68, propZ);
pushBox(roofPropTransforms, 0.78, 0.82, 0.78, propX - 0.65, height + 0.76, propZ + 0.25);
pushBox(roofPropTransforms, 0.09, 1.6, 0.09, x - width * 0.27, height + 1.05, z + depth * 0.2);
}
function addAccessibleTerrace(id, width, depth) {
const node = nodes.get(id);
const [x, y, z] = node.pos.toArray();
const bodyHeight = y - 0.24;
const body = new THREE.Mesh(
new THREE.BoxGeometry(width, bodyHeight, depth),
material.walls[2]
);
body.position.set(x, bodyHeight / 2, z);
body.castShadow = true;
body.receiveShadow = true;
world.add(body);
const roof = new THREE.Mesh(
new THREE.BoxGeometry(width + 0.42, 0.24, depth + 0.42),
material.terrace
);
roof.position.set(x, y - 0.12, z);
roof.castShadow = true;
roof.receiveShadow = true;
roof.userData.pickType = "roof";
roof.userData.accessible = true;
roof.userData.label = node.label;
interactiveObjects.push(roof);
world.add(roof);
addWindows(x, z, width, depth, bodyHeight);
const accessDirections = [];
for (const edge of edges) {
if (edge.a === id) {
accessDirections.push(nodes.get(edge.b).pos.clone().sub(node.pos).setY(0).normalize());
} else if (edge.b === id) {
accessDirections.push(nodes.get(edge.a).pos.clone().sub(node.pos).setY(0).normalize());
}
}
function sideIsOpen(normal) {
return accessDirections.some((direction) => direction.dot(normal) > 0.72);
}
const north = new THREE.Vector3(0, 0, 1);
const south = new THREE.Vector3(0, 0, -1);
const east = new THREE.Vector3(1, 0, 0);
const west = new THREE.Vector3(-1, 0, 0);
if (!sideIsOpen(north)) {
pushBox(parapetTransforms, width + 0.3, 0.62, 0.2, x, y + 0.46, z + depth / 2);
}
if (!sideIsOpen(south)) {
pushBox(parapetTransforms, width + 0.3, 0.62, 0.2, x, y + 0.46, z - depth / 2);
}
if (!sideIsOpen(east)) {
pushBox(parapetTransforms, 0.2, 0.62, depth + 0.3, x + width / 2, y + 0.46, z);
}
if (!sideIsOpen(west)) {
pushBox(parapetTransforms, 0.2, 0.62, depth + 0.3, x - width / 2, y + 0.46, z);
}
pushBox(roofPropTransforms, 1.0, 0.7, 0.9, x - width * 0.27, y + 0.58, z + depth * 0.24);
pushBox(roofPropTransforms, 0.75, 0.75, 0.75, x + width * 0.28, y + 0.60, z - depth * 0.2);
specialFootprints.push({
x, z, radius: Math.max(width, depth) * 0.58
});
}
addAccessibleTerrace("R1", 7.0, 7.0);
addAccessibleTerrace("R2", 8.0, 7.2);
addAccessibleTerrace("R3", 7.0, 7.0);
function pointSegmentDistanceXZ(point, a, b) {
const ax = a.x, az = a.z;
const bx = b.x, bz = b.z;
const dx = bx - ax, dz = bz - az;
const lengthSq = dx * dx + dz * dz;
if (!lengthSq) return Math.hypot(point.x - ax, point.z - az);
const t = THREE.MathUtils.clamp(
((point.x - ax) * dx + (point.z - az) * dz) / lengthSq,
0, 1
);
return Math.hypot(
point.x - (ax + t * dx),
point.z - (az + t * dz)
);
}
const groundEdges = edges.filter((edge) => edge.type === "lane");
const passageEdges = edges.filter((edge) => edge.type === "passage");
function canPlaceBuilding(x, z, width, depth) {
const candidateRadius = Math.hypot(width, depth) * 0.48;
const point = new THREE.Vector3(x, 0, z);
for (const edge of groundEdges) {
const a = nodes.get(edge.a).pos;
const b = nodes.get(edge.b).pos;
if (pointSegmentDistanceXZ(point, a, b) < 0.8 + candidateRadius) {
return false;
}
}
for (const edge of passageEdges) {
const a = nodes.get(edge.a).pos;
const b = nodes.get(edge.b).pos;
if (pointSegmentDistanceXZ(point, a, b) < 1.5 + candidateRadius) {
return false;
}
}
for (const footprint of specialFootprints) {
if (
Math.hypot(x - footprint.x, z - footprint.z) <
footprint.radius + candidateRadius + 0.4
) {
return false;
}
}
for (const node of nodes.values()) {
if (!node.entrance) continue;
if (
Math.hypot(x - node.pos.x, z - node.pos.z) <
candidateRadius + 1.3
) {
return false;
}
}
return true;
}
// Dense but irregular white cubic housing.
for (let gx = -23; gx <= 25; gx += 4.25) {
for (let gz = -23; gz <= 25; gz += 4.25) {
const x = gx + range(-0.38, 0.38);
const z = gz + range(-0.38, 0.38);
const width = range(2.65, 3.65);
const depth = range(2.65, 3.65);
if (!canPlaceBuilding(x, z, width, depth)) continue;
const height = range(3.2, 8.8);
addRandomBuilding(
x, z, width, depth, height,
Math.floor(random() * material.walls.length)
);
// Occasional stepped upper volume.
if (random() > 0.62 && height > 5.2) {
const upperWidth = width * range(0.45, 0.68);
const upperDepth = depth * range(0.45, 0.68);
const upperHeight = range(1.3, 2.5);
const upperX = x + range(-0.3, 0.3);
const upperZ = z + range(-0.3, 0.3);
const upper = new THREE.Mesh(
new THREE.BoxGeometry(upperWidth, upperHeight, upperDepth),
material.walls[Math.floor(random() * material.walls.length)]
);
upper.position.set(upperX, height + upperHeight / 2 + 0.2, upperZ);
upper.castShadow = true;
upper.receiveShadow = true;
world.add(upper);
const upperRoof = new THREE.Mesh(
new THREE.BoxGeometry(upperWidth + 0.2, 0.2, upperDepth + 0.2),
material.roof
);
upperRoof.position.set(upperX, height + upperHeight + 0.3, upperZ);
upperRoof.castShadow = true;
upperRoof.receiveShadow = true;
upperRoof.userData.pickType = "roof";
upperRoof.userData.accessible = false;
upperRoof.userData.label = "Unconnected rooftop";
interactiveObjects.push(upperRoof);
world.add(upperRoof);
}
}
}
// Permitted ground lanes.
for (const edge of groundEdges) {
const a = nodes.get(edge.a).pos;
const b = nodes.get(edge.b).pos;
const dx = b.x - a.x, dz = b.z - a.z;
const length = Math.hypot(dx, dz);
const angle = Math.atan2(-dz, dx);
const perpendicular = new THREE.Vector3(-dz / length, 0, dx / length);
const lane = new THREE.Mesh(
new THREE.BoxGeometry(length, 0.14, 1.65),
material.lane
);
lane.position.set((a.x + b.x) / 2, 0.07, (a.z + b.z) / 2);
lane.rotation.y = angle;
lane.receiveShadow = true;
world.add(lane);
for (const side of [-1, 1]) {
const edgeStone = new THREE.Mesh(
new THREE.BoxGeometry(length, 0.16, 0.13),
material.laneEdge
);
edgeStone.position.copy(lane.position);
edgeStone.position.addScaledVector(perpendicular, side * 0.91);
edgeStone.rotation.y = angle;
edgeStone.receiveShadow = true;
world.add(edgeStone);
}
}
function addPrismBetween(start, end, width, thickness, mat) {
const direction = end.clone().sub(start).normalize();
const right = new THREE.Vector3().crossVectors(UP, direction).normalize();
const up = new THREE.Vector3().crossVectors(direction, right).normalize();
const a = [
start.clone().addScaledVector(right, -width / 2).addScaledVector(up, -thickness / 2),
start.clone().addScaledVector(right, width / 2).addScaledVector(up, -thickness / 2),
start.clone().addScaledVector(right, width / 2).addScaledVector(up, thickness / 2),
start.clone().addScaledVector(right, -width / 2).addScaledVector(up, thickness / 2)
];
const b = [
end.clone().addScaledVector(right, -width / 2).addScaledVector(up, -thickness / 2),
end.clone().addScaledVector(right, width / 2).addScaledVector(up, -thickness / 2),
end.clone().addScaledVector(right, width / 2).addScaledVector(up, thickness / 2),
end.clone().addScaledVector(right, -width / 2).addScaledVector(up, thickness / 2)
];
const positions = [];
for (const point of [...a, ...b]) {
positions.push(point.x, point.y, point.z);
}
const indices = [
0, 2, 1, 0, 3, 2,
4, 5, 6, 4, 6, 7,
0, 1, 5, 0, 5, 4,
1, 2, 6, 1, 6, 5,
2, 3, 7, 2, 7, 6,
3, 0, 4, 3, 4, 7
];
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
const mesh = new THREE.Mesh(geometry, mat);
mesh.castShadow = true;
mesh.receiveShadow = true;
world.add(mesh);
return mesh;
}
function addPortal(endpoint, direction) {
const right = new THREE.Vector3().crossVectors(UP, direction).normalize();
const rotationY = Math.atan2(-right.z, right.x);
for (const side of [-1, 1]) {
const pillar = new THREE.Mesh(
new THREE.BoxGeometry(0.3, 1.8, 0.45),
material.passageWall
);
pillar.position.copy(endpoint);
pillar.position.addScaledVector(right, side * 1.02);
pillar.position.y += 0.9;
pillar.rotation.y = rotationY;
pillar.castShadow = true;
world.add(pillar);
}
const lintel = new THREE.Mesh(
new THREE.BoxGeometry(2.45, 0.32, 0.48),
material.passageWall
);
lintel.position.copy(endpoint);
lintel.position.y += 1.88;
lintel.rotation.y = rotationY;
lintel.castShadow = true;
world.add(lintel);
}
function addStairs(edge) {
const a = nodes.get(edge.a).pos.clone();
const b = nodes.get(edge.b).pos.clone();
const horizontal = Math.hypot(b.x - a.x, b.z - a.z);
const steps = Math.max(13, Math.ceil(horizontal / 0.42));
const angle = Math.atan2(b.x - a.x, b.z - a.z);
const perpendicular = new THREE.Vector3(
-(b.z - a.z) / horizontal,
0,
(b.x - a.x) / horizontal
);
for (let i = 0; i < steps; i++) {
const t = (i + 0.5) / steps;
const point = a.clone().lerp(b, t);
pushBox(
stairTransforms,
1.55,
0.24,
horizontal / steps * 1.15,
point.x,
point.y - 0.1,
point.z,
angle
);
}
for (const side of [-1, 1]) {
const railStart = a.clone().addScaledVector(perpendicular, side * 0.87);
const railEnd = b.clone().addScaledVector(perpendicular, side * 0.87);
railStart.y += 0.48;
railEnd.y += 0.48;
addPrismBetween(railStart, railEnd, 0.17, 0.5, material.passageWall);
}
}
function addPassage(edge) {
const a = nodes.get(edge.a).pos.clone();
const b = nodes.get(edge.b).pos.clone();
const direction = b.clone().sub(a).normalize();
const right = new THREE.Vector3().crossVectors(UP, direction).normalize();
const up = new THREE.Vector3().crossVectors(direction, right).normalize();
a.y += 0.04;
b.y += 0.04;
addPrismBetween(a, b, 2.0, 0.28, material.passage);
for (const side of [-1, 1]) {
const wallStart = a.clone().addScaledVector(right, side * 1.03);
const wallEnd = b.clone().addScaledVector(right, side * 1.03);
wallStart.addScaledVector(up, 0.48);
wallEnd.addScaledVector(up, 0.48);
addPrismBetween(wallStart, wallEnd, 0.2, 0.92, material.passageWall);
}
addPortal(a, direction);
addPortal(b, direction.clone().negate());
}
for (const edge of edges) {
if (edge.type === "stair") addStairs(edge);
if (edge.type === "passage") addPassage(edge);
}
createInstancedBoxes(windowTransforms, material.window, false);
createInstancedBoxes(parapetTransforms, material.parapet, true);
createInstancedBoxes(roofPropTransforms, material.roof, true);
createInstancedBoxes(stairTransforms, material.stair, true);
// Small trees and market details.
function addTree(x, z, y = 0, scale = 1) {
const trunk = new THREE.Mesh(
new THREE.BoxGeometry(0.24 * scale, 1.5 * scale, 0.24 * scale),
material.gold
);
trunk.position.set(x, y + 0.75 * scale, z);
trunk.castShadow = true;
world.add(trunk);
const crown = new THREE.Mesh(
new THREE.BoxGeometry(1.35 * scale, 1.15 * scale, 1.35 * scale),
material.green
);
crown.position.set(x, y + 1.8 * scale, z);
crown.castShadow = true;
world.add(crown);
const crownTop = new THREE.Mesh(
new THREE.BoxGeometry(0.9 * scale, 0.75 * scale, 0.9 * scale),
material.green
);
crownTop.position.set(x + 0.12 * scale, y + 2.55 * scale, z - 0.08 * scale);
crownTop.castShadow = true;
world.add(crownTop);
}
[
[-23, -7, 0, 0.85],
[-21, 13, 0, 0.8],
[18, 20, 0, 0.9],
[-10, 25, 0, 0.8],
[25, -17, 0, 0.75],
[-7, -23, 0, 0.7]
].forEach(([x, z, y, scale]) => addTree(x, z, y, scale));
function makeLabelSprite(text, accent = "#163b42", width = 5.2) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
context.fillStyle = "rgba(18, 48, 55, 0.94)";
context.fillRect(0, 0, 512, 128);
context.fillStyle = accent;
context.fillRect(0, 0, 12, 128);
context.strokeStyle = "rgba(255,255,255,0.3)";
context.lineWidth = 3;
context.strokeRect(2, 2, 508, 124);
context.fillStyle = "#fffaf0";
context.font = "700 40px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 262, 67);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(width, width * 0.25, 1);
sprite.renderOrder = 20;
return sprite;
}
const markerGroups = new Map();
for (const node of nodes.values()) {
if (!node.entrance) {
const terraceLabel = makeLabelSprite(node.label.toUpperCase(), "#9c7027", 5.4);
terraceLabel.position.copy(node.pos).add(new THREE.Vector3(0, 2.25, 0));
world.add(terraceLabel);
continue;
}
const group = new THREE.Group();
group.position.copy(node.pos);
group.userData.pickType = "entrance";
group.userData.id = node.id;
const base = new THREE.Mesh(
new THREE.CylinderGeometry(0.46, 0.55, 0.28, 12),
material.laneEdge
);
base.position.y = 0.14;
base.castShadow = true;
group.add(base);
const pin = new THREE.Mesh(
new THREE.BoxGeometry(0.14, 1.5, 0.14),
new THREE.MeshStandardMaterial({ color: 0x173d44, roughness: 0.7 })
);
pin.position.y = 0.9;
pin.castShadow = true;
group.add(pin);
const ringMaterial = new THREE.MeshStandardMaterial({
color: 0x173d44,
emissive: 0x173d44,
emissiveIntensity: 0.12,
roughness: 0.5,
transparent: true,
opacity: 0.92,
side: THREE.DoubleSide
});
const ring = new THREE.Mesh(
new THREE.RingGeometry(0.64, 0.9, 28),
ringMaterial
);
ring.rotation.x = -Math.PI / 2;
ring.position.y = 0.23;
group.add(ring);
const label = makeLabelSprite(
`${node.id} ${node.label.toUpperCase()}`,
"#d69a35",
6.1
);
label.position.y = 2.35;
group.add(label);
markerGroups.set(node.id, { group, ring, pin });
interactiveObjects.push(group);
world.add(group);
}
let selectedStart = null;
let selectedEnd = null;
const entranceButtons = new Map();
for (const node of nodes.values()) {
if (!node.entrance) continue;
const button = document.createElement("button");
button.type = "button";
button.className = "entrance";
button.innerHTML = `
<span class="letter">${node.id}</span>
<span class="name">${node.label}</span>
`;
button.addEventListener("click", () => chooseEntrance(node.id));
$("#entranceList").appendChild(button);
entranceButtons.set(node.id, button);
}
function showStatus(message, tone = "") {
statusEl.textContent = message;
statusEl.className = tone;
}
function updateSelectionUI() {
for (const [id, button] of entranceButtons) {
button.classList.toggle("start", id === selectedStart);
button.classList.toggle("end", id === selectedEnd);
}
for (const [id, marker] of markerGroups) {
const isStart = id === selectedStart;
const isEnd = id === selectedEnd;
const color = isStart ? 0x16896a : isEnd ? 0xd6534d : 0x173d44;
marker.ring.material.color.setHex(color);
marker.ring.material.emissive.setHex(color);
marker.ring.material.emissiveIntensity = isStart || isEnd ? 0.45 : 0.1;
marker.pin.material.color.setHex(color);
}
traceButton.disabled = !(selectedStart && selectedEnd);
if (selectedStart && selectedEnd) {
showStatus(
`Ready to trace from ${nodes.get(selectedStart).label} to ${nodes.get(selectedEnd).label}.`,
"success"
);
} else if (selectedStart) {
showStatus(
`${nodes.get(selectedStart).label} is the start. Choose a destination entrance.`
);
} else {
showStatus("Choose an entrance to begin.");
}
}
function chooseEntrance(id) {
clearRoute(false);
if (id === selectedStart) {
if (selectedEnd) {
selectedStart = selectedEnd;
selectedEnd = null;
} else {
selectedStart = null;
}
} else if (id === selectedEnd) {
selectedEnd = null;
} else if (!selectedStart) {
selectedStart = id;
} else if (!selectedEnd) {
selectedEnd = id;
} else {
selectedStart = id;
selectedEnd = null;
}
updateSelectionUI();
}
function findShortestPath(start, end) {
const distances = new Map();
const previous = new Map();
const visited = new Set();
for (const id of nodes.keys()) distances.set(id, Infinity);
distances.set(start, 0);
while (true) {
let current = null;
let best = Infinity;
for (const [id, distance] of distances) {
if (!visited.has(id) && distance < best) {
current = id;
best = distance;
}
}
if (current === null) break;
if (current === end) break;
visited.add(current);
for (const connection of adjacency.get(current)) {
const a = nodes.get(current).pos;
const b = nodes.get(connection.to).pos;
const distance = a.distanceTo(b);
const typeMultiplier =
connection.edge.type === "stair" ? 1.18 :
connection.edge.type === "passage" ? 1.08 : 1;
const candidate = best + distance * typeMultiplier;
if (candidate < distances.get(connection.to)) {
distances.set(connection.to, candidate);
previous.set(connection.to, {
node: current,
edge: connection.edge
});
}
}
}
if (!Number.isFinite(distances.get(end))) return null;
const path = [end];
const pathEdges = [];
let cursor = end;
while (cursor !== start) {
const record = previous.get(cursor);
if (!record) return null;
pathEdges.unshift(record.edge);
cursor = record.node;
path.unshift(cursor);
}
return { path, pathEdges, cost: distances.get(end) };
}
const routeGroup = new THREE.Group();
world.add(routeGroup);
let routeAnimation = null;
function clearRoute(updateStatus = true) {
routeAnimation = null;
while (routeGroup.children.length) {
const child = routeGroup.children.pop();
if (child.geometry) child.geometry.dispose();
}
routeInfoEl.textContent = "";
if (updateStatus && selectedStart && selectedEnd) {
showStatus(
`Ready to trace from ${nodes.get(selectedStart).label} to ${nodes.get(selectedEnd).label}.`,
"success"
);
}
}
function traceRoute() {
if (!selectedStart || !selectedEnd) return;
if (selectedStart === selectedEnd) {
showStatus("Choose two different entrances.", "warning");
return;
}
const result = findShortestPath(selectedStart, selectedEnd);
if (!result) {
showStatus("No permitted route connects those entrances.", "warning");
return;
}
clearRoute(false);
const segments = [];
let totalLength = 0;
let cumulative = 0;
for (let i = 0; i < result.path.length - 1; i++) {
const from = nodes.get(result.path[i]).pos.clone();
const to = nodes.get(result.path[i + 1]).pos.clone();
from.y += 0.2;
to.y += 0.2;
const direction = to.clone().sub(from);
const length = direction.length();
direction.normalize();
const geometry = new THREE.CylinderGeometry(0.14, 0.14, length, 8);
const mesh = new THREE.Mesh(geometry, routeMaterial);
mesh.quaternion.setFromUnitVectors(UP, direction);
mesh.position.copy(from);
mesh.scale.y = 0.001;
mesh.castShadow = true;
routeGroup.add(mesh);
segments.push({
mesh,
from,
direction,
length,
cumulative
});
cumulative += length;
totalLength += length;
}
const startPoint = nodes.get(result.path[0]).pos.clone();
startPoint.y += 0.25;
const endPoint = nodes.get(result.path[result.path.length - 1]).pos.clone();
endPoint.y += 0.25;
for (const [point, color] of [
[startPoint, 0x16896a],
[endPoint, 0xd6534d]
]) {
const disc = new THREE.Mesh(
new THREE.RingGeometry(0.66, 0.96, 28),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.9,
side: THREE.DoubleSide
})
);
disc.rotation.x = -Math.PI / 2;
disc.position.copy(point);
routeGroup.add(disc);
}
const traveler = new THREE.Mesh(
new THREE.SphereGeometry(0.34, 12, 8),
travelerMaterial
);
traveler.castShadow = true;
traveler.position.copy(startPoint);
routeGroup.add(traveler);
const stairs = result.pathEdges.filter((edge) => edge.type === "stair").length;
const passages = result.pathEdges.filter((edge) => edge.type === "passage").length;
routeInfoEl.innerHTML = `
<b>${totalLength.toFixed(1)} m</b> permitted route ·
${stairs} stair${stairs === 1 ? "" : "s"} ·
${passages} passage${passages === 1 ? "" : "s"}
`;
const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;
routeAnimation = {
segments,
traveler,
totalLength,
elapsed: 0,
duration: reducedMotion ? 0 : Math.max(1.35, totalLength * 0.032),
finished: false
};
showStatus("Tracing the permitted route through the medina…");
}
function updateRoute(delta) {
if (!routeAnimation) return;
const animation = routeAnimation;
if (animation.duration === 0) {
animation.elapsed = animation.totalLength;
} else {
animation.elapsed = Math.min(
animation.totalLength,
animation.elapsed + delta * animation.totalLength / animation.duration
);
}
let travelerPosition = null;
for (const segment of animation.segments) {
const localDistance = THREE.MathUtils.clamp(
animation.elapsed - segment.cumulative,
0,
segment.length
);
const fraction = localDistance / segment.length;
segment.mesh.scale.set(1, Math.max(0.001, fraction), 1);
segment.mesh.position.copy(segment.from).addScaledVector(
segment.direction,
segment.length * fraction * 0.5
);
if (
travelerPosition === null &&
localDistance <= segment.length
) {
travelerPosition = segment.from.clone().addScaledVector(
segment.direction,
localDistance
);
}
}
if (travelerPosition) animation.traveler.position.copy(travelerPosition);
if (
animation.elapsed >= animation.totalLength &&
!animation.finished
) {
animation.finished = true;
animation.traveler.position.copy(
animation.segments[animation.segments.length - 1].from.clone().add(
animation.segments[animation.segments.length - 1].direction.clone()
.multiplyScalar(
animation.segments[animation.segments.length - 1].length
)
)
);
showStatus(
"Permitted route traced. Rooftops were used only through modeled stairs or passages.",
"success"
);
}
}
traceButton.addEventListener("click", traceRoute);
clearButton.addEventListener("click", () => clearRoute(true));
resetButton.addEventListener("click", () => {
clearRoute(false);
selectedStart = null;
selectedEnd = null;
updateSelectionUI();
});
// Direct camera controls: no external controls module.
const controls = {
target: new THREE.Vector3(0, 2.3, 0),
radius: 69,
theta: 0.78,
phi: 0.88
};
function updateCamera() {
const sinPhi = Math.sin(controls.phi);
camera.position.set(
controls.target.x + controls.radius * sinPhi * Math.sin(controls.theta),
controls.target.y + controls.radius * Math.cos(controls.phi),
controls.target.z + controls.radius * sinPhi * Math.cos(controls.theta)
);
camera.lookAt(controls.target);
compassArrow.style.transform = `rotate(${-controls.theta}rad)`;
}
overviewButton.addEventListener("click", () => {
controls.target.set(0, 2.3, 0);
controls.radius = 69;
controls.theta = 0.78;
controls.phi = 0.88;
updateCamera();
});
topButton.addEventListener("click", () => {
controls.target.set(0, 0, 0);
controls.radius = 76;
controls.theta = 0;
controls.phi = 0.16;
updateCamera();
});
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let pointerDown = false;
let pointerMoved = false;
let pointerButton = 0;
let lastPointerX = 0;
let lastPointerY = 0;
function setPointerFromEvent(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 findPick(event) {
setPointerFromEvent(event);
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(interactiveObjects, true);
for (const intersection of intersections) {
let object = intersection.object;
while (object) {
if (object.userData && object.userData.pickType) {
return object.userData;
}
object = object.parent;
}
}
return null;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
pointerDown = true;
pointerMoved = false;
pointerButton = event.button;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
tooltipEl.style.display = "none";
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (pointerDown) {
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
if (Math.abs(dx) + Math.abs(dy) > 2) pointerMoved = true;
if (pointerButton === 2 || event.shiftKey) {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3()
.crossVectors(forward, UP)
.normalize();
const scale = controls.radius * 0.0015;
controls.target.addScaledVector(right, -dx * scale);
controls.target.addScaledVector(forward, -dy * scale);
controls.target.x = THREE.MathUtils.clamp(controls.target.x, -31, 31);
controls.target.z = THREE.MathUtils.clamp(controls.target.z, -31, 31);
} else {
controls.theta -= dx * 0.006;
controls.phi = THREE.MathUtils.clamp(
controls.phi - dy * 0.005,
0.14,
1.34
);
}
lastPointerX = event.clientX;
lastPointerY = event.clientY;
return;
}
const pick = findPick(event);
if (pick) {
renderer.domElement.style.cursor = "pointer";
tooltipEl.style.display = "block";
tooltipEl.style.left = `${event.clientX + 13}px`;
tooltipEl.style.top = `${event.clientY + 13}px`;
if (pick.pickType === "entrance") {
const node = nodes.get(pick.id);
tooltipEl.textContent = `${node.id} · ${node.label} — ground entrance`;
} else if (pick.accessible) {
tooltipEl.textContent = `${pick.label} — connected only by a modeled stair or passage`;
} else {
tooltipEl.textContent = "Locked rooftop — no modeled ground connection";
}
} else {
renderer.domElement.style.cursor = "grab";
tooltipEl.style.display = "none";
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (pointerDown && !pointerMoved && event.button === 0) {
const pick = findPick(event);
if (pick && pick.pickType === "entrance") {
chooseEntrance(pick.id);
} else if (pick && pick.pickType === "roof") {
if (pick.accessible) {
showStatus(
`${pick.label} is reachable only through its modeled stair or passage.`,
"success"
);
} else {
showStatus(
"That rooftop is visually present but locked: it has no modeled ground connection.",
"warning"
);
}
}
}
pointerDown = false;
renderer.domElement.releasePointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = false;
});
renderer.domElement.addEventListener("pointerleave", () => {
if (!pointerDown) tooltipEl.style.display = "none";
});
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("wheel", (event) => {
event.preventDefault();
controls.radius = THREE.MathUtils.clamp(
controls.radius * Math.exp(event.deltaY * 0.001),
28,
112
);
}, { passive: false });
addEventListener("keydown", (event) => {
if (event.key.toLowerCase() === "r") traceRoute();
if (event.key.toLowerCase() === "c") clearRoute(true);
if (event.key === "Escape") {
tooltipEl.style.display = "none";
}
if (event.key === "ArrowLeft") controls.theta += 0.09;
if (event.key === "ArrowRight") controls.theta -= 0.09;
if (event.key === "ArrowUp") controls.phi = Math.max(0.14, controls.phi - 0.06);
if (event.key === "ArrowDown") controls.phi = Math.min(1.34, controls.phi + 0.06);
if (event.key === "+" || event.key === "=") controls.radius = Math.max(28, controls.radius - 4);
if (event.key === "-") controls.radius = Math.min(112, controls.radius + 4);
});
addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
updateSelectionUI();
updateCamera();
let previousTime = performance.now();
function animate(now) {
const delta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
updateCamera();
updateRoute(delta);
for (const marker of markerGroups.values()) {
const pulse = 1 + Math.sin(now * 0.0035 + marker.group.position.x) * 0.055;
marker.ring.scale.setScalar(pulse);
}
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```