Prompt specification
Build or customize the Three.js 3D scene "Compare shaded and exposed routes to the waterfront" 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 shaded and exposed routes to the waterfront
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/compare-shaded-and-exposed-routes-to-the-waterfront-x2944
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts Mombasa Old Town's lanes and harbor approaches. Let users inspect two schematic paths under a fixed sun position. Display geometric shade and distance separately without claiming a complete thermal-comfort assessment. Voxel style.
Working Three.js Starter (compare-shaded-and-exposed-routes-to-the-waterfront-x2944):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Mombasa Old Town — Voxel Path Study</title>
<style>
:root {
--ink: #18333a;
--muted: #60747a;
--paper: rgba(250, 246, 235, 0.94);
--line: rgba(24, 51, 58, 0.16);
--coral: #d75f46;
--blue: #527f9e;
--teal: #138b83;
--gold: #e9bd55;
--purple: #7756a6;
--shadow: 0 12px 35px rgba(32, 54, 58, 0.18);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #cbdedf;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene.dragging {
cursor: grabbing;
}
.glass {
background: var(--paper);
border: 1px solid rgba(255, 255, 255, 0.7);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
}
#brand {
position: fixed;
z-index: 10;
top: 18px;
left: 18px;
width: min(410px, calc(100vw - 36px));
padding: 16px 18px 15px;
border-radius: 16px;
pointer-events: none;
}
.eyebrow {
margin: 0 0 5px;
color: var(--coral);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(23px, 3vw, 34px);
line-height: 1.02;
letter-spacing: -0.045em;
}
.subtitle {
margin: 9px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
#sun-card {
position: fixed;
z-index: 10;
top: 18px;
right: 18px;
width: 264px;
padding: 13px 15px;
border-radius: 15px;
pointer-events: none;
}
.sun-row {
display: flex;
align-items: center;
gap: 11px;
}
.sun-icon {
width: 36px;
height: 36px;
display: grid;
place-items: center;
flex: 0 0 auto;
color: #7f5b13;
background: #f7d979;
box-shadow: 0 0 0 7px rgba(247, 217, 121, 0.22);
font-size: 20px;
}
#sun-card strong {
display: block;
font-size: 12px;
letter-spacing: 0.06em;
text-transform: uppercase;
}
#sun-card p {
margin: 3px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.4;
}
#inspector {
position: fixed;
z-index: 10;
top: 126px;
right: 18px;
width: 304px;
max-height: calc(100vh - 144px);
overflow: auto;
padding: 16px;
border-radius: 16px;
scrollbar-width: thin;
}
.section-label {
margin: 0 0 9px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.path-tabs {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-bottom: 13px;
}
.path-tab {
min-height: 57px;
padding: 9px 10px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.52);
color: var(--ink);
text-align: left;
cursor: pointer;
transition: 150ms ease;
}
.path-tab:hover {
transform: translateY(-1px);
border-color: rgba(24, 51, 58, 0.35);
}
.path-tab[aria-pressed="true"] {
border-color: var(--coral);
background: #fff8ed;
box-shadow: inset 0 0 0 1px var(--coral);
}
.path-tab b {
display: block;
font-size: 12px;
}
.path-tab span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.metric {
padding: 12px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.48);
}
.metric + .metric {
margin-top: 9px;
}
.metric-title {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.metric-value {
display: block;
margin: 5px 0 3px;
font-size: 28px;
font-weight: 780;
letter-spacing: -0.045em;
}
.metric-detail {
margin: 0;
color: var(--muted);
font-size: 10px;
line-height: 1.4;
}
.shade-bar {
height: 5px;
margin-top: 9px;
overflow: hidden;
border-radius: 99px;
background: #eadba9;
}
#shade-fill {
width: 0;
height: 100%;
background: var(--teal);
transition: width 250ms ease;
}
.toggle-list {
display: grid;
gap: 7px;
margin: 13px 0;
padding: 11px 0;
border-top: 1px solid var(--line);
border-bottom: 1px solid var(--line);
}
.toggle {
display: flex;
align-items: center;
gap: 8px;
color: var(--ink);
font-size: 11px;
cursor: pointer;
}
.toggle input {
accent-color: var(--teal);
}
.camera-row {
display: grid;
grid-template-columns: 1fr auto auto auto;
gap: 6px;
}
button.small {
min-width: 34px;
height: 31px;
padding: 0 9px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255, 255, 255, 0.72);
color: var(--ink);
font: inherit;
font-size: 11px;
cursor: pointer;
}
button.small:hover {
background: white;
border-color: rgba(24, 51, 58, 0.35);
}
.method-note {
margin: 12px 0 0;
color: var(--muted);
font-size: 9.5px;
line-height: 1.48;
}
.method-note strong {
color: var(--ink);
}
#legend {
position: fixed;
z-index: 10;
left: 18px;
bottom: 18px;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px 15px;
max-width: min(610px, calc(100vw - 36px));
padding: 11px 14px;
border-radius: 14px;
pointer-events: none;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
color: var(--muted);
font-size: 10px;
white-space: nowrap;
}
.swatch {
display: inline-block;
width: 13px;
height: 13px;
flex: 0 0 auto;
}
.swatch.route {
width: 21px;
height: 4px;
border-radius: 4px;
background: var(--coral);
}
.swatch.shaded {
background: var(--teal);
transform: rotate(45deg);
}
.swatch.exposed {
background: var(--gold);
transform: rotate(45deg);
}
.swatch.distance {
width: 4px;
height: 15px;
background: var(--purple);
}
#help {
position: fixed;
z-index: 8;
left: 50%;
bottom: 23px;
transform: translateX(-50%);
padding: 7px 11px;
border-radius: 99px;
background: rgba(24, 51, 58, 0.78);
color: #f8f5e9;
font-size: 10px;
pointer-events: none;
white-space: nowrap;
}
#label-layer {
position: fixed;
z-index: 4;
inset: 0;
overflow: hidden;
pointer-events: none;
}
.world-label {
position: absolute;
top: 0;
left: 0;
padding: 4px 7px;
border: 1px solid rgba(255, 255, 255, 0.68);
border-radius: 6px;
background: rgba(24, 51, 58, 0.82);
color: #fff9e9;
box-shadow: 0 3px 12px rgba(0, 0, 0, 0.16);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.07em;
text-transform: uppercase;
white-space: nowrap;
will-change: transform;
}
.world-label.landmark {
background: rgba(250, 246, 235, 0.9);
color: var(--ink);
}
.world-label.route-label {
border-color: rgba(215, 95, 70, 0.75);
background: rgba(255, 248, 237, 0.92);
color: #9b3e2f;
}
#hover-tip {
position: fixed;
z-index: 20;
display: none;
padding: 5px 8px;
border-radius: 6px;
background: var(--ink);
color: white;
font-size: 10px;
pointer-events: none;
}
#loading {
position: fixed;
z-index: 50;
inset: 0;
display: grid;
place-items: center;
background: #cbdedf;
color: var(--ink);
font-size: 12px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
@media (max-width: 900px) {
#brand {
width: 330px;
}
#sun-card {
width: 230px;
}
#inspector {
width: 280px;
}
#help {
display: none;
}
}
@media (max-width: 680px) {
#brand {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 12px 14px;
}
#sun-card {
top: 112px;
right: 10px;
width: 220px;
}
#inspector {
top: auto;
right: 10px;
bottom: 10px;
width: calc(100vw - 20px);
max-height: 43vh;
padding: 12px;
}
#legend {
left: 10px;
bottom: auto;
top: 195px;
max-width: calc(100vw - 245px);
gap: 7px 10px;
padding: 8px;
}
.legend-item {
font-size: 8px;
}
.swatch {
width: 10px;
height: 10px;
}
#help {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel model of Mombasa Old Town and its harbor"></canvas>
<header id="brand" class="glass">
<p class="eyebrow">Mombasa · East African coast</p>
<h1>Old Town / Harbor Walk</h1>
<p class="subtitle">
A schematic voxel study of narrow coral-stone lanes and harbor approaches.
Not to scale and not for navigation.
</p>
</header>
<section id="sun-card" class="glass" aria-label="Fixed sun information">
<div class="sun-row">
<div class="sun-icon">☀</div>
<div>
<strong>Fixed schematic sun</strong>
<p>48° altitude · 82° azimuth from scene north</p>
<p>Held constant; no date, time, or solar ephemeris is modeled.</p>
</div>
</div>
</section>
<aside id="inspector" class="glass" aria-label="Path inspector">
<p class="section-label">Inspect a schematic path</p>
<div class="path-tabs">
<button class="path-tab" data-path="A" aria-pressed="true">
<b>Path A</b>
<span>Old Town lanes</span>
</button>
<button class="path-tab" data-path="B" aria-pressed="false">
<b>Path B</b>
<span>Harbor approaches</span>
</button>
</div>
<section class="metric" aria-live="polite">
<div class="metric-title">Geometric shade only</div>
<strong id="shade-value" class="metric-value">—</strong>
<p id="shade-detail" class="metric-detail"></p>
<div class="shade-bar" aria-hidden="true">
<div id="shade-fill"></div>
</div>
</section>
<section class="metric" aria-live="polite">
<div class="metric-title">Modelled distance only</div>
<strong id="distance-value" class="metric-value">—</strong>
<p id="distance-detail" class="metric-detail"></p>
</section>
<div class="toggle-list">
<label class="toggle">
<input id="shade-toggle" type="checkbox" checked>
Show geometric-shade sample markers
</label>
<label class="toggle">
<input id="distance-toggle" type="checkbox" checked>
Show 100 m distance ticks
</label>
</div>
<p class="section-label">Camera</p>
<div class="camera-row">
<button id="home-view" class="small">Reset view</button>
<button id="zoom-out" class="small" aria-label="Zoom out">−</button>
<button id="zoom-in" class="small" aria-label="Zoom in">+</button>
<button id="rotate-left" class="small" aria-label="Rotate left">↶</button>
</div>
<p class="method-note">
<strong>Method:</strong> shade is a ray test from sampled route points toward
the fixed sun against solid voxel building masses. Distance is the separate
length of the schematic polyline. These are screening cues only, not a
complete thermal-comfort assessment. Humidity, wind, material temperature,
radiant conditions, occupancy, and changing shade are not evaluated.
</p>
</aside>
<section id="legend" class="glass" aria-label="Map legend">
<div class="legend-item"><span class="swatch route"></span>Selected route</div>
<div class="legend-item"><span class="swatch shaded"></span>In building-shadow ray</div>
<div class="legend-item"><span class="swatch exposed"></span>Sun-exposed ray</div>
<div class="legend-item"><span class="swatch distance"></span>Distance tick</div>
</section>
<div id="help">Drag: orbit · Shift-drag: pan · Wheel: zoom · Click a route</div>
<div id="label-layer"></div>
<div id="hover-tip"></div>
<div id="loading">Building Mombasa voxel study…</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------
// Core setup
// ---------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color("#cbdedf");
scene.fog = new THREE.Fog("#cbdedf", 155, 285);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
400
);
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const materialCache = new Map();
const shadeMeshes = [];
const waterTiles = [];
const boats = [];
const routeMeshes = [];
const worldLabels = [];
function standardMaterial(color) {
if (!materialCache.has(color)) {
materialCache.set(
color,
new THREE.MeshStandardMaterial({
color,
roughness: 0.88,
metalness: 0
})
);
}
return materialCache.get(color);
}
function box(
parent,
size,
color,
position,
options = {}
) {
const material =
typeof color === "string" ? standardMaterial(color) : color;
const mesh = new THREE.Mesh(unitBox, material);
mesh.scale.set(size[0], size[1], size[2]);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = options.cast ?? true;
mesh.receiveShadow = options.receive ?? true;
parent.add(mesh);
return mesh;
}
function seededRandom(seed) {
let value = seed % 2147483647;
return () => {
value = (value * 16807) % 2147483647;
return (value - 1) / 2147483646;
};
}
const random = seededRandom(1904);
// ---------------------------------------------------------------------
// Lighting and fixed sun
//
// Scene north is -Z, east is +X. The sun direction is fixed and is used
// both by the renderer and by the separate geometric-shade ray tests.
// ---------------------------------------------------------------------
const sunAltitude = THREE.MathUtils.degToRad(48);
const sunAzimuth = THREE.MathUtils.degToRad(82);
const sunDirection = new THREE.Vector3(
Math.sin(sunAzimuth) * Math.cos(sunAltitude),
Math.sin(sunAltitude),
-Math.cos(sunAzimuth) * Math.cos(sunAltitude)
).normalize();
const lightTarget = new THREE.Object3D();
lightTarget.position.set(-5, 0, -3);
scene.add(lightTarget);
const sunPosition = lightTarget.position.clone().addScaledVector(sunDirection, 130);
const sunlight = new THREE.DirectionalLight("#fff1c8", 3.25);
sunlight.position.copy(sunPosition);
sunlight.target = lightTarget;
sunlight.castShadow = true;
sunlight.shadow.mapSize.set(2048, 2048);
sunlight.shadow.camera.left = -105;
sunlight.shadow.camera.right = 105;
sunlight.shadow.camera.top = 105;
sunlight.shadow.camera.bottom = -105;
sunlight.shadow.camera.near = 1;
sunlight.shadow.camera.far = 300;
sunlight.shadow.bias = -0.00035;
sunlight.shadow.normalBias = 0.025;
scene.add(sunlight);
const hemisphere = new THREE.HemisphereLight("#d8eff2", "#8e765b", 2.0);
scene.add(hemisphere);
const fillLight = new THREE.DirectionalLight("#b9dce5", 0.65);
fillLight.position.set(-70, 45, 70);
scene.add(fillLight);
// A voxel sun marker in the same direction as the directional light.
const sunMarker = new THREE.Group();
sunMarker.position.copy(sunPosition);
const sunMaterial = new THREE.MeshStandardMaterial({
color: "#ffd966",
emissive: "#f0ad32",
emissiveIntensity: 1.2,
roughness: 0.5
});
box(sunMarker, [5, 5, 5], sunMaterial, [0, 0, 0], { cast: false, receive: false });
box(sunMarker, [8, 1.6, 1.6], sunMaterial, [0, 0, 0], { cast: false, receive: false });
box(sunMarker, [1.6, 8, 1.6], sunMaterial, [0, 0, 0], { cast: false, receive: false });
scene.add(sunMarker);
// ---------------------------------------------------------------------
// Land, harbor, lanes and quays
// ---------------------------------------------------------------------
// Old Town land: x = -60 ... 25, z = -50 ... 50.
box(scene, [85, 3, 100], "#c6ac83", [-17.5, -1.5, 0], {
cast: false
});
// Harbor water.
box(scene, [60, 3, 100], "#438fa5", [55, -1.5, 0], {
cast: false
});
// Slightly offset voxel water tiles.
let tileIndex = 0;
for (let x = 28; x <= 82; x += 8) {
for (let z = -48; z <= 48; z += 8) {
const color = tileIndex % 3 === 0 ? "#5ca7b5" : "#4e9daf";
const tile = box(
scene,
[7.5, 0.08, 7.5],
color,
[x, 0.035, z],
{ cast: false }
);
waterTiles.push({
mesh: tile,
baseY: 0.035,
phase: random() * Math.PI * 2
});
tileIndex++;
}
}
// Broad raised quay and promenade.
box(scene, [6, 0.65, 92], "#d1b98f", [26.5, 0.15, 0], {
cast: false
});
box(scene, [1.0, 0.85, 92], "#987b5f", [23.7, 0.25, 0]);
// Old Town lane strips.
const laneMaterial = new THREE.MeshStandardMaterial({
color: "#b59b76",
roughness: 1
});
const horizontalLanes = [
{ z: 27, x1: -52, x2: 22 },
{ z: 14, x1: -42, x2: 4 },
{ z: 4, x1: -32, x2: 20 },
{ z: -9, x1: -24, x2: 22 },
{ z: -20, x1: -6, x2: 22 }
];
const verticalLanes = [
{ x: -35, z1: 14, z2: 30 },
{ x: -22, z1: 4, z2: 14 },
{ x: -10, z1: -9, z2: 4 },
{ x: 0, z1: -20, z2: -9 },
{ x: 18, z1: -20, z2: 30 }
];
horizontalLanes.forEach(({ z, x1, x2 }) => {
box(
scene,
[x2 - x1, 0.08, 3.2],
laneMaterial,
[(x1 + x2) / 2, 0.055, z],
{ cast: false }
);
});
verticalLanes.forEach(({ x, z1, z2 }) => {
box(
scene,
[3.2, 0.08, z2 - z1],
laneMaterial,
[x, 0.058, (z1 + z2) / 2],
{ cast: false }
);
});
// Small stone edge blocks give the lanes a block-built character.
for (const lane of horizontalLanes) {
for (let x = lane.x1 + 1; x < lane.x2; x += 4.5) {
box(scene, [0.7, 0.28, 0.7], "#d5bc91", [x, 0.16, lane.z - 1.65], {
cast: false
});
box(scene, [0.7, 0.28, 0.7], "#d5bc91", [x, 0.16, lane.z + 1.65], {
cast: false
});
}
}
// Harbor piers and mole.
box(scene, [13, 0.55, 2.8], "#b4976d", [32.5, 0.27, 12], {
cast: false
});
box(scene, [2.8, 0.55, 20], "#b4976d", [38, 0.27, 2], {
cast: false
});
box(scene, [5.5, 0.55, 2.8], "#b4976d", [40.5, 0.27, -8], {
cast: false
});
box(scene, [19, 0.65, 4.2], "#ad9169", [34, 0.32, -27], {
cast: false
});
// Pier piles.
[
[31, 10.6], [34, 13.4], [37, 10.6],
[36.6, -6.6], [39.4, -9.4],
[28, -28.5], [34, -25.5], [40, -28.5]
].forEach(([x, z]) => {
box(scene, [0.55, 2.2, 0.55], "#705d4a", [x, -0.55, z]);
box(scene, [0.9, 0.28, 0.9], "#d2b58a", [x, 0.58, z]);
});
// Mooring posts.
for (let z = -37; z <= 37; z += 9) {
box(scene, [0.45, 1.4, 0.45], "#6f5946", [29.1, 0.95, z]);
box(scene, [0.7, 0.25, 0.7], "#d6bd91", [29.1, 1.7, z]);
}
// ---------------------------------------------------------------------
// Voxel buildings
// ---------------------------------------------------------------------
const buildingPalette = [
"#d59a72",
"#c98262",
"#e0ad7c",
"#b9785e",
"#d6a17a",
"#c88d68",
"#e5bb88"
];
function createBuilding(x, z, width, depth, height, color) {
const group = new THREE.Group();
scene.add(group);
const body = box(
group,
[width, height, depth],
color,
[x, height / 2, z]
);
shadeMeshes.push(body);
const plinth = box(
group,
[width + 0.3, 0.45, depth + 0.3],
"#936d55",
[x, 0.22, z]
);
shadeMeshes.push(plinth);
const roof = box(
group,
[width + 0.4, 0.32, depth + 0.4],
"#e8d2a8",
[x, height + 0.16, z]
);
shadeMeshes.push(roof);
// Setback upper storey on taller houses.
if (height > 5.1) {
const upperHeight = 1.25 + random() * 0.9;
const upper = box(
group,
[width * 0.68, upperHeight, depth * 0.62],
color,
[x + (random() - 0.5) * 0.4, height + 0.3 + upperHeight / 2, z]
);
shadeMeshes.push(upper);
const upperRoof = box(
group,
[width * 0.73, 0.26, depth * 0.68],
"#ead5ad",
[
x + (random() - 0.5) * 0.4,
height + 0.3 + upperHeight + 0.13,
z
]
);
shadeMeshes.push(upperRoof);
}
// Decorative front doors and small windows. These do not participate
// in the geometric-shade calculation.
const doorColors = ["#244d5d", "#70463d", "#315e65", "#9b493d"];
const doorColor = doorColors[Math.floor(random() * doorColors.length)];
box(
group,
[1.45, 2.25, 0.16],
doorColor,
[x, 1.16, z + depth / 2 + 0.09],
{ cast: false }
);
const windowCount = Math.max(1, Math.floor(width / 3.2));
for (let i = 0; i < windowCount; i++) {
const wx = x - width * 0.33 + (i * width * 0.66) / Math.max(1, windowCount - 1);
box(
group,
[0.65, 0.85, 0.13],
"#345663",
[wx, height * 0.62, z + depth / 2 + 0.09],
{ cast: false }
);
}
}
// Cells are deliberately separated by the lane network.
const xCells = [
[-56, -46], [-43, -36], [-33, -23],
[-20, -11], [-8, 1], [2, 17]
];
const zCells = [
[31, 39], [16, 26], [6, 13],
[-7, 3], [-18, -10], [-37, -21]
];
for (let ix = 0; ix < xCells.length; ix++) {
for (let iz = 0; iz < zCells.length; iz++) {
// Reserve the southern eastern block for the Old Fort.
if (ix >= 4 && iz === 5) continue;
// Leave a few courtyards and market-like gaps.
if ((ix + iz * 2) % 7 === 3) continue;
const [x1, x2] = xCells[ix];
const [z1, z2] = zCells[iz];
const availableWidth = x2 - x1;
const availableDepth = z2 - z1;
const width = Math.max(4.6, availableWidth - 1.7 - random() * 1.2);
const depth = Math.max(4.3, availableDepth - 1.8 - random() * 1.2);
const height = 3.4 + random() * 4.4;
const x = (x1 + x2) / 2 + (random() - 0.5) * 0.6;
const z = (z1 + z2) / 2 + (random() - 0.5) * 0.4;
createBuilding(
x,
z,
width,
depth,
height,
buildingPalette[Math.floor(random() * buildingPalette.length)]
);
}
}
// ---------------------------------------------------------------------
// Old Fort and Fort Jesus
// ---------------------------------------------------------------------
function addShadeBox(parent, size, color, position) {
const mesh = box(parent, size, color, position);
shadeMeshes.push(mesh);
return mesh;
}
const oldFort = new THREE.Group();
scene.add(oldFort);
addShadeBox(oldFort, [18, 4.6, 12], "#d6c29c", [10, 2.3, -28]);
addShadeBox(oldFort, [19, 0.4, 13], "#eee0bf", [10, 4.8, -28]);
[
[3, -23], [17, -23], [3, -33], [17, -33]
].forEach(([x, z]) => {
addShadeBox(oldFort, [3.4, 6.2, 3.4], "#cbb38d", [x, 3.1, z]);
addShadeBox(oldFort, [3.9, 0.45, 3.9], "#e9d9b4", [x, 6.4, z]);
});
addShadeBox(oldFort, [3.5, 3.2, 1.1], "#c7ad86", [10, 3.8, -21.7]);
box(oldFort, [1.7, 2.3, 0.18], "#294f5e", [10, 1.18, -21.08], {
cast: false
});
// Fort Jesus on the opposite side of the harbor.
const fortIsland = new THREE.Group();
scene.add(fortIsland);
box(fortIsland, [29, 0.65, 26], "#bda57d", [54, 0.3, -27], {
cast: false
});
addShadeBox(fortIsland, [22, 3.3, 18], "#d0b98f", [54, 2.25, -28]);
addShadeBox(fortIsland, [23, 0.45, 19], "#ead8b2", [54, 4.12, -28]);
[
[45, -21], [63, -21], [45, -35], [63, -35]
].forEach(([x, z]) => {
addShadeBox(fortIsland, [3.4, 5.0, 3.4], "#c4aa80", [x, 3.1, z]);
addShadeBox(fortIsland, [3.9, 0.42, 3.9], "#e5d0a7", [x, 5.78, z]);
});
box(fortIsland, [1.8, 2.5, 0.18], "#31505a", [44.85, 1.3, -28], {
cast: false
});
// ---------------------------------------------------------------------
// Harbor details, palms and dhows
// ---------------------------------------------------------------------
function createPalm(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.scale.setScalar(scale);
scene.add(group);
const trunk = new THREE.MeshStandardMaterial({
color: "#856344",
roughness: 1
});
box(group, [0.45, 4.5, 0.45], trunk, [0, 2.25, 0], {
cast: false
});
box(group, [0.42, 0.45, 0.42], trunk, [0, 4.45, 0], {
cast: false
});
const frondMaterial = new THREE.MeshStandardMaterial({
color: "#4d7d58",
roughness: 1
});
box(group, [4.0, 0.25, 0.65], frondMaterial, [0, 4.75, 0], {
cast: false
});
box(group, [0.65, 0.25, 4.0], frondMaterial, [0, 4.75, 0], {
cast: false
});
box(group, [2.3, 0.22, 0.5], frondMaterial, [1.1, 5.05, 0.45], {
cast: false
});
box(group, [0.5, 0.22, 2.3], frondMaterial, [-0.45, 5.05, 1.1], {
cast: false
});
}
[
[28, 34], [28, 25], [28, 4], [28, -14], [21, 35],
[20, -29], [-56, -37], [-54, 36]
].forEach(([x, z], index) => createPalm(x, z, 0.8 + (index % 3) * 0.1));
function createDhow(x, z, rotation, scale) {
const group = new THREE.Group();
group.position.set(x, 0.05, z);
group.rotation.y = rotation;
group.scale.setScalar(scale);
scene.add(group);
box(group, [5.5, 0.7, 2.0], "#704a36", [0, 0.35, 0], { cast: false });
box(group, [4.0, 0.65, 2.3], "#8f6243", [-0.2, 0.75, 0], { cast: false });
box(group, [0.22, 5.8, 0.22], "#6b4b35", [0.3, 3.2, 0], { cast: false });
box(group, [3.0, 3.0, 0.14], "#efe4c8", [-0.65, 3.45, 0], { cast: false });
box(group, [0.16, 2.1, 2.7], "#d9ccb2", [0.28, 3.15, 0.7], { cast: false });
boats.push({
group,
baseY: 0.05,
phase: random() * Math.PI * 2
});
}
createDhow(49, 8, -0.4, 1.0);
createDhow(62, 26, 0.7, 0.85);
createDhow(40, -40, 2.3, 0.8);
// A compact voxel quay crane.
box(scene, [1.1, 9, 1.1], "#d7a63c", [29, 4.5, -15]);
box(scene, [7.5, 0.8, 0.9], "#d7a63c", [31.8, 8.7, -15]);
box(scene, [0.16, 4.0, 0.16], "#4d5555", [35.1, 6.6, -15]);
box(scene, [1.2, 0.7, 1.2], "#4d5555", [35.1, 4.45, -15]);
// Voxel north arrow, scene north = -Z.
box(scene, [0.65, 0.35, 7], "#315f54", [-56, 0.18, -41], {
cast: false
});
box(scene, [2.2, 0.35, 0.7], "#315f54", [-56, 0.18, -44], {
cast: false
});
box(scene, [0.7, 0.35, 2.2], "#315f54", [-56, 0.18, -45], {
cast: false
});
// ---------------------------------------------------------------------
// Paths
// ---------------------------------------------------------------------
const METERS_PER_UNIT = 5.5;
const pathDefinitions = {
A: {
id: "A",
name: "Old Town lanes",
color: "#d75f46",
points: [
[-44, 27],
[-35, 27],
[-35, 14],
[-22, 14],
[-22, 4],
[-10, 4],
[-10, -9],
[0, -9],
[0, -20],
[10, -20]
].map(([x, z]) => new THREE.Vector3(x, 0.34, z)),
landmarks: [
{ text: "Market corner", position: [-44, 2.2, 27] },
{ text: "Carved-door lane", position: [-35, 2.2, 14] },
{ text: "Coral-stone court", position: [-22, 2.2, 4] },
{ text: "Timber-door row", position: [-10, 2.2, -9] },
{ text: "Old Fort gate", position: [10, 2.2, -20] }
]
},
B: {
id: "B",
name: "Harbor approaches",
color: "#527f9e",
points: [
[18, 30],
[26, 30],
[26, 12],
[38, 12],
[38, -8],
[43, -8],
[43, -27]
].map(([x, z]) => new THREE.Vector3(x, 0.34, z)),
landmarks: [
{ text: "Old Town gate", position: [18, 2.2, 30] },
{ text: "Quayside", position: [26, 2.2, 12] },
{ text: "Customs jetty", position: [38, 2.2, 12] },
{ text: "Harbor mole", position: [38, 2.2, -8] },
{ text: "Fort Jesus gate", position: [43, 2.2, -27] }
]
}
};
const routeGroups = {};
const routeMaterials = {};
function createRoute(def) {
const group = new THREE.Group();
scene.add(group);
routeGroups[def.id] = group;
const material = new THREE.MeshStandardMaterial({
color: def.color,
roughness: 0.7,
transparent: true,
opacity: 1
});
routeMaterials[def.id] = material;
for (let i = 0; i < def.points.length - 1; i++) {
const a = def.points[i];
const b = def.points[i + 1];
const length = a.distanceTo(b);
const midpoint = a.clone().add(b).multiplyScalar(0.5);
const segment = box(
group,
[length + 0.18, 0.26, 0.78],
material,
[midpoint.x, midpoint.y, midpoint.z],
{ cast: false }
);
segment.rotation.y = -Math.atan2(b.z - a.z, b.x - a.x);
segment.userData.pathId = def.id;
routeMeshes.push(segment);
}
}
Object.values(pathDefinitions).forEach(createRoute);
function pathLength(def) {
let length = 0;
for (let i = 0; i < def.points.length - 1; i++) {
length += def.points[i].distanceTo(def.points[i + 1]);
}
return length;
}
function pointAtDistance(def, targetDistance) {
let traversed = 0;
for (let i = 0; i < def.points.length - 1; i++) {
const a = def.points[i];
const b = def.points[i + 1];
const length = a.distanceTo(b);
if (targetDistance <= traversed + length) {
const t = (targetDistance - traversed) / length;
return a.clone().lerp(b, t);
}
traversed += length;
}
return def.points[def.points.length - 1].clone();
}
// ---------------------------------------------------------------------
// Separate shade and distance layers
// ---------------------------------------------------------------------
const shadeLayer = new THREE.Group();
const distanceLayer = new THREE.Group();
scene.add(shadeLayer, distanceLayer);
const shadedMarkerMaterial = new THREE.MeshStandardMaterial({
color: "#138b83",
roughness: 0.65
});
const exposedMarkerMaterial = new THREE.MeshStandardMaterial({
color: "#e9bd55",
roughness: 0.65
});
const distanceMarkerMaterial = new THREE.MeshStandardMaterial({
color: "#7756a6",
roughness: 0.65
});
const shadeRaycaster = new THREE.Raycaster();
shadeRaycaster.near = 0.02;
shadeRaycaster.far = 150;
let selectedPathId = "A";
let currentShadeSamples = [];
function clearShadeLayer() {
while (shadeLayer.children.length) {
shadeLayer.remove(shadeLayer.children[shadeLayer.children.length - 1]);
}
currentShadeSamples = [];
}
function clearDistanceLayer() {
for (const child of [...distanceLayer.children]) {
if (child.material) {
if (child.material.map) child.material.map.dispose();
child.material.dispose();
}
if (child.geometry) child.geometry.dispose();
distanceLayer.remove(child);
}
}
function makeTextSprite(text) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 256;
labelCanvas.height = 64;
const context = labelCanvas.getContext("2d");
context.fillStyle = "#7756a6";
context.fillRect(0, 0, 256, 64);
context.strokeStyle = "rgba(255,255,255,0.75)";
context.lineWidth = 4;
context.strokeRect(2, 2, 252, 60);
context.fillStyle = "#ffffff";
context.font = "700 28px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 128, 33);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(8.2, 2.05, 1);
sprite.renderOrder = 20;
return sprite;
}
function rebuildShadeLayer(def) {
clearShadeLayer();
scene.updateMatrixWorld(true);
const samples = [];
let shadedCount = 0;
for (let i = 0; i < def.points.length - 1; i++) {
const a = def.points[i];
const b = def.points[i + 1];
const segmentLength = a.distanceTo(b);
const sampleCount = Math.max(1, Math.ceil(segmentLength / 1.35));
for (let sampleIndex = 0; sampleIndex < sampleCount; sampleIndex++) {
if (sampleIndex === 0 && i > 0) continue;
const t = sampleIndex / sampleCount;
const point = a.clone().lerp(b, t);
const origin = point.clone();
origin.y = 0.58;
shadeRaycaster.set(origin, sunDirection);
const intersections = shadeRaycaster.intersectObjects(shadeMeshes, false);
const isShaded = intersections.length > 0;
if (isShaded) shadedCount++;
samples.push({ point, isShaded });
const marker = box(
shadeLayer,
[0.68, 0.38, 0.68],
isShaded ? shadedMarkerMaterial : exposedMarkerMaterial,
[point.x, 0.62, point.z],
{ cast: false }
);
marker.rotation.y = Math.PI * 0.25;
}
}
currentShadeSamples = samples;
const ratio = samples.length ? shadedCount / samples.length : 0;
document.querySelector("#shade-value").textContent =
`${Math.round(ratio * 100)}%`;
document.querySelector("#shade-detail").textContent =
`${shadedCount} of ${samples.length} route samples intersect solid building geometry.`;
document.querySelector("#shade-fill").style.width =
`${Math.round(ratio * 100)}%`;
}
function rebuildDistanceLayer(def) {
clearDistanceLayer();
const length = pathLength(def);
const totalMeters = length * METERS_PER_UNIT;
document.querySelector("#distance-value").textContent =
`${Math.round(totalMeters / 10) * 10} m`;
document.querySelector("#distance-detail").textContent =
`${def.points.length - 1} schematic legs; route length only, independent of shade.`;
for (let meters = 100; meters < totalMeters; meters += 100) {
const point = pointAtDistance(def, meters / METERS_PER_UNIT);
box(
distanceLayer,
[0.28, 1.2, 0.28],
distanceMarkerMaterial,
[point.x, 0.9, point.z],
{ cast: false }
);
const sprite = makeTextSprite(`${meters} m`);
sprite.position.set(point.x, 2.35, point.z);
distanceLayer.add(sprite);
}
}
// ---------------------------------------------------------------------
// World labels
// ---------------------------------------------------------------------
function createWorldLabel(text, position, className = "landmark", pathId = null) {
const element = document.createElement("div");
element.className = `world-label ${className}`;
element.textContent = text;
const label = {
element,
position: new THREE.Vector3(...position),
className,
pathId,
active: true
};
worldLabels.push(label);
document.querySelector("#label-layer").appendChild(element);
return label;
}
createWorldLabel("Mombasa Old Town", [-36, 5.5, 34]);
createWorldLabel("Old Fort", [10, 8.0, -28]);
createWorldLabel("Fort Jesus", [54, 8.2, -28]);
createWorldLabel("Mombasa Harbour", [51, 2.2, 17]);
createWorldLabel("Indian Ocean", [75, 1.8, 42]);
for (const def of Object.values(pathDefinitions)) {
for (const landmark of def.landmarks) {
createWorldLabel(
landmark.text,
landmark.position,
"route-label",
def.id
);
}
}
function updateWorldLabels() {
const width = window.innerWidth;
const height = window.innerHeight;
for (const label of worldLabels) {
const routeIsActive =
!label.pathId || label.pathId === selectedPathId;
if (!routeIsActive || !label.active) {
label.element.style.display = "none";
continue;
}
const projected = label.position.clone().project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
projected.x > -1.12 &&
projected.x < 1.12 &&
projected.y > -1.12 &&
projected.y < 1.12;
if (!visible) {
label.element.style.display = "none";
continue;
}
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
label.element.style.display = "block";
label.element.style.transform =
`translate(${x}px, ${y}px) translate(-50%, -50%)`;
}
}
// ---------------------------------------------------------------------
// Inspector behavior
// ---------------------------------------------------------------------
function selectPath(id) {
selectedPathId = id;
document.querySelectorAll(".path-tab").forEach((button) => {
button.setAttribute(
"aria-pressed",
String(button.dataset.path === id)
);
});
for (const [pathId, material] of Object.entries(routeMaterials)) {
const selected = pathId === id;
material.color.set(selected ? pathDefinitions[pathId].color : "#98a5a4");
material.opacity = selected ? 1 : 0.34;
}
const def = pathDefinitions[id];
rebuildShadeLayer(def);
rebuildDistanceLayer(def);
shadeLayer.visible = document.querySelector("#shade-toggle").checked;
distanceLayer.visible = document.querySelector("#distance-toggle").checked;
}
document.querySelectorAll(".path-tab").forEach((button) => {
button.addEventListener("click", () => selectPath(button.dataset.path));
});
document.querySelector("#shade-toggle").addEventListener("change", (event) => {
shadeLayer.visible = event.target.checked;
});
document.querySelector("#distance-toggle").addEventListener("change", (event) => {
distanceLayer.visible = event.target.checked;
});
// ---------------------------------------------------------------------
// Custom camera controls: orbit, pan and zoom
// ---------------------------------------------------------------------
const orbit = {
radius: 126,
theta: 0.70,
phi: 1.02,
target: new THREE.Vector3(-5, 0, -3)
};
const defaultOrbit = {
radius: 126,
theta: 0.70,
phi: 1.02,
target: new THREE.Vector3(-5, 0, -3)
};
function updateCamera() {
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + orbit.radius * sinPhi * Math.sin(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + orbit.radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(orbit.target);
}
function resetCamera() {
orbit.radius = defaultOrbit.radius;
orbit.theta = defaultOrbit.theta;
orbit.phi = defaultOrbit.phi;
orbit.target.copy(defaultOrbit.target);
updateCamera();
}
document.querySelector("#home-view").addEventListener("click", resetCamera);
document.querySelector("#zoom-in").addEventListener("click", () => {
orbit.radius = THREE.MathUtils.clamp(orbit.radius * 0.84, 45, 220);
});
document.querySelector("#zoom-out").addEventListener("click", () => {
orbit.radius = THREE.MathUtils.clamp(orbit.radius * 1.18, 45, 220);
});
document.querySelector("#rotate-left").addEventListener("click", () => {
orbit.theta -= 0.16;
});
const pointer = {
down: false,
moved: false,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0,
shift: false
};
const pickRaycaster = new THREE.Raycaster();
const pointerNDC = new THREE.Vector2();
const hoverTip = document.querySelector("#hover-tip");
function pickRoute(clientX, clientY) {
const rect = canvas.getBoundingClientRect();
pointerNDC.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointerNDC.y = -((clientY - rect.top) / rect.height) * 2 + 1;
pickRaycaster.setFromCamera(pointerNDC, camera);
const hits = pickRaycaster.intersectObjects(routeMeshes, false);
return hits.length ? hits[0].object.userData.pathId : null;
}
canvas.addEventListener("pointerdown", (event) => {
pointer.down = true;
pointer.moved = false;
pointer.startX = pointer.lastX = event.clientX;
pointer.startY = pointer.lastY = event.clientY;
pointer.shift = event.shiftKey;
canvas.setPointerCapture(event.pointerId);
canvas.classList.add("dragging");
hoverTip.style.display = "none";
});
canvas.addEventListener("pointermove", (event) => {
if (pointer.down) {
const dx = event.clientX - pointer.lastX;
const dy = event.clientY - pointer.lastY;
pointer.lastX = event.clientX;
pointer.lastY = event.clientY;
const totalDistance = Math.hypot(
event.clientX - pointer.startX,
event.clientY - pointer.startY
);
if (totalDistance > 4) pointer.moved = true;
if (pointer.shift || event.shiftKey) {
const forward = camera.getWorldDirection(new THREE.Vector3());
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3()
.crossVectors(forward, camera.up)
.normalize();
const scale = orbit.radius * 0.0016;
orbit.target.addScaledVector(right, -dx * scale);
orbit.target.addScaledVector(forward, -dy * scale);
} else {
orbit.theta -= dx * 0.006;
orbit.phi = THREE.MathUtils.clamp(
orbit.phi - dy * 0.005,
0.24,
1.43
);
}
updateCamera();
return;
}
const pathId = pickRoute(event.clientX, event.clientY);
if (pathId) {
canvas.style.cursor = "pointer";
hoverTip.style.display = "block";
hoverTip.style.left = `${event.clientX + 12}px`;
hoverTip.style.top = `${event.clientY + 12}px`;
hoverTip.textContent =
`Inspect Path ${pathId}: ${pathDefinitions[pathId].name}`;
} else {
canvas.style.cursor = "grab";
hoverTip.style.display = "none";
}
});
function finishPointer(event) {
if (!pointer.down) return;
const wasClick = !pointer.moved;
pointer.down = false;
canvas.classList.remove("dragging");
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
if (wasClick) {
const pathId = pickRoute(event.clientX, event.clientY);
if (pathId) selectPath(pathId);
}
}
canvas.addEventListener("pointerup", finishPointer);
canvas.addEventListener("pointercancel", finishPointer);
canvas.addEventListener("pointerleave", () => {
if (!pointer.down) hoverTip.style.display = "none";
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
45,
220
);
updateCamera();
},
{ passive: false }
);
window.addEventListener("keydown", (event) => {
if (
event.target instanceof HTMLInputElement ||
event.target instanceof HTMLButtonElement
) return;
switch (event.key) {
case "ArrowLeft":
orbit.theta -= 0.08;
break;
case "ArrowRight":
orbit.theta += 0.08;
break;
case "ArrowUp":
orbit.phi = THREE.MathUtils.clamp(orbit.phi - 0.06, 0.24, 1.43);
break;
case "ArrowDown":
orbit.phi = THREE.MathUtils.clamp(orbit.phi + 0.06, 0.24, 1.43);
break;
case "+":
case "=":
orbit.radius = THREE.MathUtils.clamp(orbit.radius * 0.9, 45, 220);
break;
case "-":
orbit.radius = THREE.MathUtils.clamp(orbit.radius * 1.1, 45, 220);
break;
case "Home":
resetCamera();
break;
}
});
// ---------------------------------------------------------------------
// Resize and render loop
// ---------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
});
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const time = clock.getElapsedTime();
waterTiles.forEach(({ mesh, baseY, phase }) => {
mesh.position.y = baseY + Math.sin(time * 0.65 + phase) * 0.025;
});
boats.forEach(({ group, baseY, phase }) => {
group.position.y = baseY + Math.sin(time * 0.8 + phase) * 0.10;
group.rotation.z = Math.sin(time * 0.55 + phase) * 0.012;
});
updateCamera();
updateWorldLabels();
renderer.render(scene, camera);
}
updateCamera();
selectPath("A");
animate();
document.querySelector("#loading").style.display = "none";
</script>
</body>
</html>
```