Prompt specification
Build or customize the Three.js 3D scene "Trace household access by water and footbridge" 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: Trace household access by water and footbridge
Category: Architecture & Cities · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/trace-household-access-by-water-and-footbridge-x2968
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring Khlong Bang Luang's canal neighborhood in Bangkok. Let users compare boat and walking routes to selected doors in the schematic neighborhood. Require water connectivity for boats and explicit bridge links for pedestrians. Low-poly.
Verify the behavior against the actual geometry and data in each relevant state. Use schematic labels for deliberately synthetic elements.
Technical checks: Ensure every graph edge references defined nodes. Link banks, bridges, doors, and landings consistently, and let users choose continuous routes for each travel mode.
Return one complete HTML document. The file must run in a sandbox allowing inline scripts and the cdnjs Three.js r160 module. Construct procedural assets, use local event handlers and avoid remote assets, runtime network requests besides Three.js, pointer lock and native form submission. Keep the main requested geometry visible in the initial view.
Working Three.js Starter (trace-household-access-by-water-and-footbridge-x2968):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Khlong Bang Luang — Schematic Route Comparison</title>
<style>
:root {
--ink: #253b3a;
--muted: #61716d;
--paper: #f7f2e6;
--paper-deep: #eee5d2;
--line: rgba(37, 59, 58, 0.15);
--teal: #00aeb8;
--teal-dark: #087f88;
--orange: #f0643b;
--gold: #f1c75b;
--green: #287b61;
--shadow: 0 12px 32px rgba(38, 54, 49, 0.16);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
color: var(--ink);
background: #dce5d8;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button, select { font: inherit; }
button { color: inherit; }
[hidden] { display: none !important; }
#app {
display: grid;
grid-template-columns: minmax(0, 1fr) 370px;
width: 100%;
height: 100%;
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
isolation: isolate;
background:
radial-gradient(circle at 50% 35%, rgba(255,255,255,.55), transparent 46%),
#dce5d8;
}
#sceneHost, #worldLabels {
position: absolute;
inset: 0;
}
#sceneHost canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
#worldLabels {
z-index: 3;
pointer-events: none;
overflow: hidden;
}
#worldLabels.hidden { display: none; }
.scene-heading {
position: absolute;
z-index: 5;
top: 18px;
left: 20px;
max-width: 330px;
padding: 13px 15px 12px;
border: 1px solid rgba(255,255,255,.58);
border-radius: 15px;
background: rgba(250, 247, 237, 0.87);
box-shadow: 0 7px 22px rgba(45, 66, 59, .12);
backdrop-filter: blur(10px);
pointer-events: none;
}
.eyebrow {
margin: 0 0 4px;
color: var(--teal-dark);
font-size: 10px;
font-weight: 800;
letter-spacing: .16em;
text-transform: uppercase;
}
.scene-heading h1 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(22px, 2.2vw, 31px);
line-height: 1.02;
letter-spacing: -.025em;
}
.scene-heading p {
margin: 7px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.scene-chip {
position: absolute;
z-index: 5;
top: 21px;
right: 18px;
padding: 7px 10px;
border: 1px solid rgba(255,255,255,.58);
border-radius: 999px;
background: rgba(250, 247, 237, .87);
color: var(--green);
font-size: 10px;
font-weight: 800;
letter-spacing: .04em;
box-shadow: 0 5px 18px rgba(45,66,59,.1);
pointer-events: none;
}
.map-key {
position: absolute;
z-index: 5;
left: 18px;
bottom: 18px;
display: grid;
gap: 6px;
min-width: 190px;
padding: 10px 12px;
border: 1px solid rgba(255,255,255,.55);
border-radius: 13px;
background: rgba(250,247,237,.87);
box-shadow: 0 7px 22px rgba(45,66,59,.12);
backdrop-filter: blur(9px);
pointer-events: none;
}
.key-row {
display: flex;
align-items: center;
gap: 8px;
color: #4e605c;
font-size: 10px;
font-weight: 650;
}
.swatch {
width: 19px;
height: 5px;
flex: 0 0 auto;
border-radius: 99px;
background: var(--teal);
box-shadow: 0 0 0 1px rgba(0,0,0,.08);
}
.swatch.walk { background: var(--orange); }
.swatch.dock { background: var(--gold); }
.swatch.node {
width: 8px;
height: 8px;
border-radius: 50%;
background: #fff8df;
box-shadow: 0 0 0 1px rgba(41,65,61,.25);
}
.controls-hint {
position: absolute;
z-index: 5;
right: 18px;
bottom: 18px;
max-width: 300px;
padding: 8px 11px;
border-radius: 11px;
background: rgba(37,59,58,.78);
color: #fffdf5;
font-size: 10px;
line-height: 1.4;
text-align: right;
pointer-events: none;
}
.world-label {
position: absolute;
z-index: 4;
transform: translate(-50%, -50%);
min-width: max-content;
max-width: 190px;
padding: 5px 8px;
border: 1px solid rgba(255,255,255,.72);
border-radius: 8px;
background: rgba(250,247,237,.88);
color: #2e4541;
box-shadow: 0 4px 13px rgba(34,50,46,.14);
font-size: 9px;
font-weight: 800;
line-height: 1.2;
text-align: center;
white-space: nowrap;
pointer-events: none;
backdrop-filter: blur(5px);
}
.world-label small {
display: block;
margin-top: 2px;
color: #7a7162;
font-size: 7px;
font-weight: 750;
letter-spacing: .06em;
text-transform: uppercase;
}
.world-label.door-label {
border-color: rgba(240,100,59,.42);
cursor: pointer;
pointer-events: auto;
}
.world-label.door-label:hover,
.world-label.door-label.selected {
border-color: var(--orange);
background: #fff9e8;
box-shadow: 0 5px 17px rgba(240,100,59,.24);
}
#panel {
position: relative;
z-index: 10;
min-width: 0;
overflow-y: auto;
padding: 20px 18px 24px;
border-left: 1px solid rgba(54,72,66,.12);
background:
linear-gradient(180deg, rgba(255,255,255,.32), transparent 180px),
var(--paper);
box-shadow: -10px 0 35px rgba(45,61,56,.09);
scrollbar-width: thin;
scrollbar-color: #b7b5a5 transparent;
}
.panel-kicker {
color: var(--teal-dark);
font-size: 9px;
font-weight: 850;
letter-spacing: .15em;
text-transform: uppercase;
}
#panel h2 {
margin: 5px 0 5px;
font-family: Georgia, "Times New Roman", serif;
font-size: 27px;
line-height: 1;
letter-spacing: -.025em;
}
.panel-intro {
margin: 0 0 17px;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.field-label {
display: block;
margin: 0 0 6px;
color: #52635e;
font-size: 9px;
font-weight: 850;
letter-spacing: .11em;
text-transform: uppercase;
}
#doorSelect {
width: 100%;
height: 40px;
padding: 0 34px 0 11px;
border: 1px solid rgba(37,59,58,.18);
border-radius: 10px;
background: #fffdf7;
color: var(--ink);
font-size: 11px;
font-weight: 700;
outline: none;
}
#doorSelect:focus {
border-color: var(--teal);
box-shadow: 0 0 0 3px rgba(0,174,184,.13);
}
.origin-note {
display: flex;
align-items: flex-start;
gap: 8px;
margin: 9px 0 16px;
padding: 8px 10px;
border-radius: 9px;
background: rgba(0,174,184,.07);
color: #536762;
font-size: 9px;
line-height: 1.45;
}
.origin-dot {
width: 8px;
height: 8px;
margin-top: 2px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--teal);
box-shadow: 0 0 0 3px rgba(0,174,184,.13);
}
.mode-switch {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 4px;
margin: 0 0 12px;
padding: 4px;
border: 1px solid rgba(37,59,58,.12);
border-radius: 12px;
background: #e9e4d7;
}
.mode-switch button {
min-height: 31px;
padding: 0 6px;
border: 0;
border-radius: 8px;
background: transparent;
color: #65736e;
font-size: 9px;
font-weight: 850;
letter-spacing: .04em;
cursor: pointer;
}
.mode-switch button.active {
background: #fffdf7;
color: var(--ink);
box-shadow: 0 2px 7px rgba(45,61,56,.11);
}
.compare-summary {
margin: 0 0 10px;
padding: 10px 11px;
border: 1px solid rgba(40,123,97,.18);
border-radius: 10px;
background: rgba(40,123,97,.08);
color: #376757;
font-size: 10px;
font-weight: 700;
line-height: 1.45;
}
.route-card {
display: block;
width: 100%;
margin: 0 0 9px;
padding: 12px;
border: 1px solid rgba(37,59,58,.14);
border-radius: 13px;
background: rgba(255,253,247,.83);
box-shadow: 0 4px 12px rgba(45,61,56,.045);
text-align: left;
cursor: pointer;
transition: border-color .16s ease, opacity .16s ease, transform .16s ease, box-shadow .16s ease;
}
.route-card:hover { transform: translateY(-1px); }
.route-card.is-active { border-color: rgba(0,174,184,.48); }
#walkCard.is-active { border-color: rgba(240,100,59,.48); }
.route-card.is-dim { opacity: .47; }
.route-card-head {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 9px;
}
.route-icon {
width: 25px;
height: 25px;
display: grid;
place-items: center;
border-radius: 8px;
color: white;
background: var(--teal);
font-size: 13px;
}
#walkCard .route-icon { background: var(--orange); }
.route-title {
font-size: 12px;
font-weight: 850;
}
.route-subtitle {
margin-left: auto;
color: #8a8d83;
font-size: 8px;
font-weight: 800;
letter-spacing: .08em;
text-transform: uppercase;
}
.route-metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-bottom: 8px;
}
.metric {
padding: 7px 8px;
border-radius: 8px;
background: rgba(37,59,58,.055);
}
.metric strong {
display: block;
font-size: 15px;
line-height: 1;
letter-spacing: -.025em;
}
.metric small {
display: block;
margin-top: 3px;
color: #7c8178;
font-size: 7px;
font-weight: 800;
letter-spacing: .08em;
text-transform: uppercase;
}
.route-detail {
margin: 0 0 7px;
color: #5d6b67;
font-size: 9px;
line-height: 1.45;
}
.route-check {
display: flex;
gap: 6px;
color: var(--green);
font-size: 8px;
font-weight: 800;
line-height: 1.4;
}
.route-check::before {
content: "✓";
flex: 0 0 auto;
}
.panel-section {
margin-top: 17px;
padding-top: 15px;
border-top: 1px solid var(--line);
}
.section-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 10px;
}
.section-head h3 {
margin: 0;
font-size: 10px;
font-weight: 850;
letter-spacing: .08em;
text-transform: uppercase;
}
.status-pill {
padding: 4px 7px;
border-radius: 999px;
background: rgba(40,123,97,.1);
color: var(--green);
font-size: 7px;
font-weight: 850;
letter-spacing: .06em;
text-transform: uppercase;
}
.audit-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
}
.audit-item {
min-height: 49px;
padding: 8px;
border: 1px solid rgba(37,59,58,.1);
border-radius: 9px;
background: rgba(255,255,255,.42);
}
.audit-item span {
display: block;
color: #78817c;
font-size: 7px;
font-weight: 800;
letter-spacing: .07em;
text-transform: uppercase;
}
.audit-item strong {
display: block;
margin-top: 4px;
color: #31564b;
font-size: 11px;
line-height: 1.2;
}
#selectedAudit {
margin: 9px 0 0;
color: #65746f;
font-size: 8px;
line-height: 1.5;
}
details {
margin-top: 10px;
border: 1px solid rgba(37,59,58,.11);
border-radius: 10px;
background: rgba(255,255,255,.35);
}
summary {
padding: 9px 10px;
color: #566863;
font-size: 9px;
font-weight: 800;
cursor: pointer;
user-select: none;
}
.trace-wrap {
padding: 0 10px 10px;
}
.trace-wrap p {
margin: 7px 0 3px;
color: #7c8178;
font-size: 7px;
font-weight: 850;
letter-spacing: .08em;
text-transform: uppercase;
}
.trace-wrap code {
display: block;
overflow-wrap: anywhere;
color: #50635e;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 8px;
line-height: 1.5;
}
.utility-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-top: 12px;
}
.utility-button {
min-height: 34px;
border: 1px solid rgba(37,59,58,.16);
border-radius: 9px;
background: #fffdf7;
color: #53645f;
font-size: 9px;
font-weight: 800;
cursor: pointer;
}
.utility-button:hover {
border-color: rgba(0,174,184,.45);
color: var(--teal-dark);
}
.disclaimer {
margin: 14px 0 0;
color: #8a887d;
font-size: 8px;
line-height: 1.5;
}
#loading, #fatal {
position: absolute;
z-index: 20;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
max-width: 440px;
padding: 18px 20px;
border-radius: 14px;
background: rgba(255,252,243,.96);
box-shadow: var(--shadow);
color: #3e5550;
font-size: 12px;
line-height: 1.5;
text-align: center;
}
#fatal {
border: 1px solid rgba(192,74,54,.3);
color: #8f3f31;
}
@media (max-width: 900px) {
#app {
grid-template-columns: 1fr;
grid-template-rows: 58vh 42vh;
}
#panel {
padding: 14px;
border-left: 0;
border-top: 1px solid rgba(54,72,66,.12);
box-shadow: 0 -8px 26px rgba(45,61,56,.08);
}
.scene-heading {
top: 10px;
left: 10px;
max-width: 260px;
padding: 9px 11px;
}
.scene-heading p { display: none; }
.scene-chip { top: 12px; right: 10px; }
.map-key { left: 10px; bottom: 10px; transform: scale(.9); transform-origin: bottom left; }
.controls-hint { right: 10px; bottom: 10px; max-width: 210px; }
}
</style>
</head>
<body>
<div id="app">
<main id="stage" aria-label="Interactive low-poly schematic of Khlong Bang Luang">
<div id="sceneHost"></div>
<div id="worldLabels"></div>
<header class="scene-heading">
<p class="eyebrow">Bangkok · canal neighbourhood</p>
<h1>Khlong Bang Luang</h1>
<p>Low-poly schematic with boat and pedestrian route comparison. Door positions and the southern street layout are synthetic.</p>
</header>
<div class="scene-chip" id="modeReadout" aria-live="polite">Compare mode · both routes visible</div>
<div class="map-key" aria-label="Scene legend">
<div class="key-row"><span class="swatch"></span>Boat · water route</div>
<div class="key-row"><span class="swatch walk"></span>Walking · pedestrian route</div>
<div class="key-row"><span class="swatch dock"></span>Dock and door access</div>
<div class="key-row"><span class="swatch node"></span>Validated graph node</div>
</div>
<div class="controls-hint">Drag: orbit · right-drag: pan · wheel: zoom<br>Click a gold door beacon or its label</div>
<div id="loading">Loading the procedural Three.js scene…</div>
<div id="fatal" role="alert" hidden></div>
</main>
<aside id="panel" aria-label="Route comparison controls and network audit">
<div class="panel-kicker">Schematic navigation study</div>
<h2>Route comparator</h2>
<p class="panel-intro">Choose a destination door. The boat search is restricted to water edges; the pedestrian search can cross the canal only through an explicitly rendered bridge edge.</p>
<label class="field-label" for="doorSelect">Destination door</label>
<select id="doorSelect" aria-label="Destination door"></select>
<div class="origin-note">
<span class="origin-dot"></span>
<span>Fixed synthetic origins: south canal landing for boats and the south-west lane entrance for pedestrians.</span>
</div>
<div class="mode-switch" role="group" aria-label="Visible route mode">
<button type="button" data-mode="compare" class="active" aria-pressed="true">Compare</button>
<button type="button" data-mode="boat" aria-pressed="false">Boat</button>
<button type="button" data-mode="walk" aria-pressed="false">Walk</button>
</div>
<div class="compare-summary" id="compareSummary" aria-live="polite">Computing validated routes…</div>
<button type="button" class="route-card is-active" id="boatCard" aria-label="Focus the boat route">
<div class="route-card-head">
<span class="route-icon">≈</span>
<span class="route-title">Boat route</span>
<span class="route-subtitle">Water only</span>
</div>
<div class="route-metrics">
<div class="metric"><strong id="boatDistance">—</strong><small>route distance</small></div>
<div class="metric"><strong id="boatTime">—</strong><small>estimated time</small></div>
</div>
<p class="route-detail" id="boatDetail">Waiting for graph validation.</p>
<div class="route-check" id="boatCheck">Water connectivity check pending.</div>
</button>
<button type="button" class="route-card is-active" id="walkCard" aria-label="Focus the walking route">
<div class="route-card-head">
<span class="route-icon">⌁</span>
<span class="route-title">Walking route</span>
<span class="route-subtitle">Street + bridges</span>
</div>
<div class="route-metrics">
<div class="metric"><strong id="walkDistance">—</strong><small>route distance</small></div>
<div class="metric"><strong id="walkTime">—</strong><small>estimated time</small></div>
</div>
<p class="route-detail" id="walkDetail">Waiting for graph validation.</p>
<div class="route-check" id="walkCheck">Bridge connectivity check pending.</div>
</button>
<section class="panel-section">
<div class="section-head">
<h3>Network audit</h3>
<span class="status-pill" id="networkStatus">Validating</span>
</div>
<div class="audit-grid">
<div class="audit-item"><span>Water component</span><strong id="auditWater">—</strong></div>
<div class="audit-item"><span>Walk component</span><strong id="auditWalk">—</strong></div>
<div class="audit-item"><span>Bridge geometry</span><strong id="auditBridge">—</strong></div>
<div class="audit-item"><span>Door anchors</span><strong id="auditDoor">—</strong></div>
</div>
<p id="selectedAudit" aria-live="polite">No route selected.</p>
<details>
<summary>Show actual route trace</summary>
<div class="trace-wrap">
<p>Boat · water edges then dock</p>
<code id="boatTrace">—</code>
<p>Walking · street and explicit bridge edges</p>
<code id="walkTrace">—</code>
</div>
</details>
</section>
<div class="utility-row">
<button type="button" class="utility-button" id="resetView">Reset camera</button>
<button type="button" class="utility-button" id="toggleLabels">Labels on</button>
</div>
<p class="disclaimer">This is a deliberately synthetic, navigation-grade illustration rather than a survey. Building arrangements, door anchors, bridges, and the southern entrance do not represent exact real-world coordinates.</p>
</aside>
</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 METERS_PER_UNIT = 6;
const WALK_METERS_PER_MINUTE = 75;
const BOAT_METERS_PER_MINUTE = 200;
const nodes = new Map();
const edges = [];
const edgeById = new Map();
const doors = [];
function centerX(z) {
if (z < -18) return -3;
if (z < 10) return -3 + ((z + 18) / 28) * 5;
return 2 + ((z - 10) / 34) * 5;
}
function addNode(id, position, metadata = {}) {
if (nodes.has(id)) throw new Error(`Duplicate node id: ${id}`);
nodes.set(id, {
id,
position: [...position],
layer: metadata.layer ?? "walk",
side: metadata.side ?? "center",
...metadata
});
}
function addEdge(id, from, to, kind, metadata = {}) {
if (edgeById.has(id)) throw new Error(`Duplicate edge id: ${id}`);
const edge = { id, from, to, kind, ...metadata };
edges.push(edge);
edgeById.set(id, edge);
}
const doorSpecs = [
{
key: "artist",
name: "Artist House area door",
scheme: "schematic",
z: -30,
side: -1,
bankNodeId: "walk_l1",
waterNodeId: "landing_a",
style: "artist"
},
{
key: "temple",
name: "Temple lane door",
scheme: "synthetic",
z: -16,
side: 1,
bankNodeId: "walk_r2",
waterNodeId: "landing_b",
style: "temple"
},
{
key: "workshop",
name: "Community workshop door",
scheme: "synthetic",
z: 0,
side: -1,
bankNodeId: "walk_l3",
waterNodeId: "landing_c",
style: "workshop"
},
{
key: "cafe",
name: "Canal café door",
scheme: "synthetic",
z: 16,
side: 1,
bankNodeId: "walk_r4",
waterNodeId: "landing_d",
style: "cafe"
},
{
key: "woodshop",
name: "North woodshop door",
scheme: "synthetic",
z: 31,
side: -1,
bankNodeId: "walk_l5",
waterNodeId: "landing_e",
style: "woodshop"
}
];
function buildNetwork() {
const waterCenters = [
["water_south", -43],
["water_c1", -30],
["water_c2", -16],
["water_c3", 0],
["water_c4", 16],
["water_c5", 31],
["water_north", 43]
];
for (const [id, z] of waterCenters) {
addNode(id, [centerX(z), 0.12, z], { layer: "water", side: "center" });
}
for (let i = 1; i < waterCenters.length; i++) {
addEdge(
`water_center_${i - 1}`,
waterCenters[i - 1][0],
waterCenters[i][0],
"water",
{ name: `Canal reach ${i}` }
);
}
const landings = [
["landing_a", -30, -1],
["landing_b", -16, 1],
["landing_c", 0, -1],
["landing_d", 16, 1],
["landing_e", 31, -1]
];
landings.forEach(([id, z, side], index) => {
addNode(
id,
[centerX(z) + side * 3.45, 0.12, z],
{ layer: "water", side: side < 0 ? "left" : "right", landing: true }
);
addEdge(
`water_branch_${index + 1}`,
`water_c${index + 1}`,
id,
"water",
{ name: `Water landing ${index + 1}` }
);
});
const walkZ = [-43, -30, -16, 0, 16, 31, 43];
for (let i = 0; i < walkZ.length; i++) {
const z = walkZ[i];
addNode(
`walk_l${i}`,
[centerX(z) - 7.1, 0.34, z],
{ layer: "walk", side: "left" }
);
addNode(
`walk_r${i}`,
[centerX(z) + 7.1, 0.34, z],
{ layer: "walk", side: "right" }
);
}
for (let i = 0; i < walkZ.length - 1; i++) {
addEdge(`walk_left_${i}`, `walk_l${i}`, `walk_l${i + 1}`, "walk", { bank: "left" });
addEdge(`walk_right_${i}`, `walk_r${i}`, `walk_r${i + 1}`, "walk", { bank: "right" });
}
for (let i = 1; i <= 5; i++) {
addEdge(
`bridge_${i}`,
`walk_l${i}`,
`walk_r${i}`,
"bridge",
{ name: `Schematic footbridge ${i}` }
);
}
for (const spec of doorSpecs) {
const nodeId = `door_${spec.key}`;
const position = [centerX(spec.z) + spec.side * 8.55, 0.34, spec.z];
addNode(nodeId, position, {
layer: "walk",
side: spec.side < 0 ? "left" : "right",
door: true
});
const approachEdgeId = `walk_to_${spec.key}`;
const dockEdgeId = `dock_${spec.key}`;
addEdge(approachEdgeId, spec.bankNodeId, nodeId, "walk", {
doorApproach: true,
name: `Door approach ${spec.key}`
});
addEdge(dockEdgeId, spec.waterNodeId, nodeId, "dock", {
name: `Door dock ${spec.key}`
});
doors.push({
...spec,
nodeId,
position,
approachEdgeId,
dockEdgeId
});
}
}
function shortestPath(startId, endId, acceptEdge) {
if (!nodes.has(startId) || !nodes.has(endId)) return null;
const distances = new Map([[startId, 0]]);
const previous = new Map();
const unvisited = new Set(nodes.keys());
while (unvisited.size) {
let current = null;
let bestDistance = Infinity;
for (const id of unvisited) {
const distance = distances.get(id) ?? Infinity;
if (distance < bestDistance) {
current = id;
bestDistance = distance;
}
}
if (current === null) break;
unvisited.delete(current);
if (current === endId) break;
for (const edge of edges) {
if (!acceptEdge(edge)) continue;
let neighbor = null;
if (edge.from === current) neighbor = edge.to;
else if (edge.to === current) neighbor = edge.from;
if (neighbor === null || !unvisited.has(neighbor)) continue;
const candidate = bestDistance + edge.length;
if (candidate < (distances.get(neighbor) ?? Infinity)) {
distances.set(neighbor, candidate);
previous.set(neighbor, { node: current, edgeId: edge.id });
}
}
}
if (!distances.has(endId)) return null;
const pathNodes = [endId];
const pathEdges = [];
let cursor = endId;
while (cursor !== startId) {
const step = previous.get(cursor);
if (!step) return null;
pathEdges.push(step.edgeId);
pathNodes.push(step.node);
cursor = step.node;
}
pathNodes.reverse();
pathEdges.reverse();
return {
nodes: pathNodes,
edges: pathEdges,
distance: distances.get(endId)
};
}
function reachableNodes(startId, acceptEdge) {
const reached = new Set([startId]);
const queue = [startId];
while (queue.length) {
const current = queue.shift();
for (const edge of edges) {
if (!acceptEdge(edge)) continue;
let neighbor = null;
if (edge.from === current) neighbor = edge.to;
else if (edge.to === current) neighbor = edge.from;
if (neighbor && nodes.has(neighbor) && !reached.has(neighbor)) {
reached.add(neighbor);
queue.push(neighbor);
}
}
}
return reached;
}
function validateNetwork() {
const errors = [];
const allowedKinds = new Set(["water", "walk", "bridge", "dock"]);
for (const node of nodes.values()) {
if (!node.id || typeof node.id !== "string") {
errors.push(`Invalid node id: ${node.id}`);
continue;
}
if (
!Array.isArray(node.position) ||
node.position.length !== 3 ||
!node.position.every((value) => typeof value === "number" && Number.isFinite(value))
) {
errors.push(`Undefined or non-finite coordinates on node ${node.id}`);
}
}
for (const edge of edges) {
if (!allowedKinds.has(edge.kind)) errors.push(`Unknown edge kind on ${edge.id}`);
const from = nodes.get(edge.from);
const to = nodes.get(edge.to);
if (!from || !to) {
errors.push(`Edge ${edge.id} references an undefined node`);
continue;
}
if (from.id === to.id) errors.push(`Self-edge ${edge.id}`);
edge.length = Math.hypot(
to.position[0] - from.position[0],
to.position[1] - from.position[1],
to.position[2] - from.position[2]
);
if (!Number.isFinite(edge.length) || edge.length <= 0) {
errors.push(`Invalid length for edge ${edge.id}`);
}
if (edge.kind === "bridge") {
if (!(from.side === "left" && to.side === "right") && !(from.side === "right" && to.side === "left")) {
errors.push(`Bridge ${edge.id} does not connect opposite banks`);
}
if (Math.abs(from.position[2] - to.position[2]) > 0.001) {
errors.push(`Bridge ${edge.id} endpoints are not aligned`);
}
}
if (edge.kind === "walk" && from.side !== to.side) {
errors.push(`Walking edge ${edge.id} crosses banks without a bridge`);
}
}
for (const door of doors) {
if (!nodes.has(door.nodeId)) errors.push(`Missing door node ${door.nodeId}`);
if (!nodes.has(door.waterNodeId)) errors.push(`Missing water landing ${door.waterNodeId}`);
if (!nodes.has(door.bankNodeId)) errors.push(`Missing bank node ${door.bankNodeId}`);
const dock = edgeById.get(door.dockEdgeId);
const approach = edgeById.get(door.approachEdgeId);
if (!dock || dock.from !== door.waterNodeId || dock.to !== door.nodeId) {
errors.push(`Dock for ${door.nodeId} is not linked to its water landing`);
}
if (!approach || approach.from !== door.bankNodeId || approach.to !== door.nodeId) {
errors.push(`Pedestrian approach for ${door.nodeId} is not linked to its bank`);
}
const waterNode = nodes.get(door.waterNodeId);
const doorNode = nodes.get(door.nodeId);
if (waterNode && doorNode && waterNode.side !== doorNode.side) {
errors.push(`Door ${door.nodeId} uses the opposite-bank water landing`);
}
}
if (errors.length) {
return {
errors,
waterReachable: new Set(),
walkReachable: new Set()
};
}
const waterReachable = reachableNodes("water_south", (edge) => edge.kind === "water");
const walkReachable = reachableNodes(
"walk_l0",
(edge) => edge.kind === "walk" || edge.kind === "bridge"
);
for (const door of doors) {
const boatPath = shortestPath(
"water_south",
door.waterNodeId,
(edge) => edge.kind === "water"
);
const walkPath = shortestPath(
"walk_l0",
door.nodeId,
(edge) => edge.kind === "walk" || edge.kind === "bridge"
);
if (!boatPath) errors.push(`No water-only route to ${door.nodeId}`);
if (!walkPath) errors.push(`No bridge-valid pedestrian route to ${door.nodeId}`);
}
return { errors, waterReachable, walkReachable };
}
function computeDoorRoutes(door) {
const waterPath = shortestPath(
"water_south",
door.waterNodeId,
(edge) => edge.kind === "water"
);
const walkPath = shortestPath(
"walk_l0",
door.nodeId,
(edge) => edge.kind === "walk" || edge.kind === "bridge"
);
if (!waterPath || !walkPath) {
throw new Error(`A required route disappeared while computing ${door.nodeId}`);
}
const dockEdge = edgeById.get(door.dockEdgeId);
const waterMeters = waterPath.distance * METERS_PER_UNIT;
const dockMeters = dockEdge.length * METERS_PER_UNIT;
const boatMeters = waterMeters + dockMeters;
const walkMeters = walkPath.distance * METERS_PER_UNIT;
const bridgeEdges = walkPath.edges.map((id) => edgeById.get(id)).filter((edge) => edge.kind === "bridge");
return {
boat: {
waterPath,
dockEdge,
waterMeters,
dockMeters,
totalMeters: boatMeters,
minutes: boatMeters / BOAT_METERS_PER_MINUTE
},
walk: {
path: walkPath,
totalMeters: walkMeters,
minutes: walkMeters / WALK_METERS_PER_MINUTE,
bridgeEdges
}
};
}
buildNetwork();
const networkAudit = validateNetwork();
function startScene() {
if (networkAudit.errors.length) {
throw new Error(`Network validation failed:\n${networkAudit.errors.join("\n")}`);
}
const stage = $("stage");
const sceneHost = $("sceneHost");
const labelsLayer = $("worldLabels");
const doorSelect = $("doorSelect");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce5d8);
scene.fog = new THREE.Fog(0xdce5d8, 165, 290);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.06;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute("aria-label", "3D schematic canal neighbourhood");
renderer.domElement.setAttribute("tabindex", "0");
sceneHost.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 500);
const orbit = {
theta: 0.52,
phi: 0.72,
radius: 155,
target: new THREE.Vector3(0, 0, 0)
};
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);
camera.updateMatrixWorld();
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xf7f1d8, 0x667c68, 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff0cc, 3.15);
sun.position.set(-38, 76, 42);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -68;
sun.shadow.camera.right = 68;
sun.shadow.camera.top = 68;
sun.shadow.camera.bottom = -68;
sun.shadow.camera.near = 5;
sun.shadow.camera.far = 190;
sun.shadow.bias = -0.0007;
scene.add(sun);
const world = new THREE.Group();
scene.add(world);
const boatRouteGroup = new THREE.Group();
const walkRouteGroup = new THREE.Group();
world.add(boatRouteGroup, walkRouteGroup);
const material = (color, options = {}) => new THREE.MeshStandardMaterial({
color,
roughness: 0.86,
metalness: 0,
flatShading: true,
...options
});
const mats = {
ground: material(0xaeb88a),
trench: material(0x285e5f),
water: material(0x329395, { roughness: 0.38, metalness: 0.08, side: THREE.DoubleSide }),
stone: material(0xcbbd9b),
path: material(0xd9bf8f),
pathEdge: material(0xc5ad7d),
wood: material(0x80573c),
woodLight: material(0xb78350),
woodDark: material(0x5d4435),
roofRed: material(0x984d42, { side: THREE.DoubleSide }),
roofGreen: material(0x426f63, { side: THREE.DoubleSide }),
roofBlue: material(0x476f7d, { side: THREE.DoubleSide }),
cream: material(0xe8ddbd),
gold: material(0xd5a83d),
foliageA: material(0x4e7d50),
foliageB: material(0x71935a),
trunk: material(0x6e523b),
dark: material(0x304744),
window: material(0x284d59, { roughness: 0.42 }),
orange: material(0xd66b43),
teal: material(0x438c83),
pale: material(0xeee3c8),
coral: material(0xc8664c)
};
function addBox(parent, size, position, mat, castShadow = true) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(size[0], size[1], size[2]), mat);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addCylinder(parent, radiusTop, radiusBottom, height, position, mat, radialSegments = 6) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radiusTop, radiusBottom, height, radialSegments),
mat
);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addRibbon(offset, width, y, mat, steps = 72) {
const z0 = -48;
const z1 = 48;
const positions = [];
const indices = [];
for (let i = 0; i <= steps; i++) {
const z = z0 + ((z1 - z0) * i / steps);
const x = centerX(z) + offset;
positions.push(x - width / 2, y, z, x + width / 2, y, z);
if (i < steps) {
const a = i * 2;
const b = a + 1;
const c = a + 2;
const d = a + 3;
indices.push(a, c, b, b, c, d);
}
}
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.receiveShadow = true;
world.add(mesh);
return mesh;
}
function addFlatStrip(a, b, width, y, mat, parent = world) {
const dx = b.x - a.x;
const dz = b.z - a.z;
const length = Math.hypot(dx, dz);
if (length < 0.01) return null;
const mesh = addBox(parent, [length + 0.03, 0.08, width], [(a.x + b.x) / 2, y, (a.z + b.z) / 2], mat, false);
mesh.rotation.y = -Math.atan2(dz, dx);
return mesh;
}
function buildLandscape() {
addBox(world, [62, 1.4, 104], [0, -0.72, 0], mats.ground, false);
addRibbon(0, 10.2, 0.012, mats.trench);
addRibbon(0, 8.8, 0.042, mats.water);
addRibbon(-4.8, 0.82, 0.14, mats.stone);
addRibbon(4.8, 0.82, 0.14, mats.stone);
addRibbon(-7.1, 2.5, 0.205, mats.path);
addRibbon(7.1, 2.5, 0.205, mats.path);
for (let i = 0; i < 11; i++) {
const z = -41 + i * 8.1;
const x = centerX(z) + (i % 2 === 0 ? -1.6 : 1.45);
const ripple = addBox(world, [1.15 + (i % 3) * 0.2, 0.025, 0.075], [x, 0.085, z], mats.pale, false);
ripple.rotation.y = (i % 2 ? 1 : -1) * 0.15;
}
const patches = [
[-20, -41, 10, 8], [20, -39, 9, 7],
[-21, -8, 10, 9], [20, -6, 9, 9],
[-21, 18, 9, 8], [20, 22, 10, 9]
];
patches.forEach(([x, z, w, d], index) => {
const patchMat = index % 2 ? mats.foliageB : material(0x98aa78);
addBox(world, [w, 0.035, d], [x, 0.005, z], patchMat, false);
});
}
function roofGeometry(width, depth, height) {
const w = width / 2;
const d = depth / 2;
const positions = [
-w, 0, -d, 0, height, -d, w, 0, -d,
-w, 0, d, w, 0, d, 0, height, d,
-w, 0, -d, -w, 0, d, 0, height, d,
-w, 0, -d, 0, height, d, 0, height, -d,
w, 0, -d, 0, height, -d, 0, height, d,
w, 0, -d, 0, height, d, w, 0, d
];
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.computeVertexNormals();
return geometry;
}
function gableGeometry(width, depth, height) {
const w = width / 2;
const d = depth / 2;
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute([
-w, 0, -d, w, 0, -d, 0, height, -d,
-w, 0, d, w, 0, d, 0, height, d
], 3));
geometry.computeVertexNormals();
return geometry;
}
const houseStyles = {
artist: { wall: 0x78a39c, roof: mats.roofRed, accent: material(0xe6bd55) },
temple: { wall: 0xe3d5b1, roof: material(0xb96e43, { side: THREE.DoubleSide }), accent: mats.gold },
workshop: { wall: 0xc86d52, roof: mats.roofBlue, accent: material(0xe4d9bd) },
cafe: { wall: 0xe1b85f, roof: material(0x8f5748, { side: THREE.DoubleSide }), accent: material(0x3f817b) },
woodshop: { wall: 0x9b704d, roof: mats.roofGreen, accent: material(0xc99c62) }
};
function createHouse(door) {
const style = houseStyles[door.style];
const group = new THREE.Group();
group.position.set(centerX(door.z) + door.side * 12, 0, door.z);
world.add(group);
const wallMat = material(style.wall);
const roofMat = style.roof;
const accentMat = style.accent;
[-2.35, 2.35].forEach((x) => {
[-2.7, 2.7].forEach((z) => {
addBox(group, [0.34, 1.18, 0.34], [x, 0.59, z], mats.woodDark);
});
});
addBox(group, [5.2, 0.22, 0.28], [0, 1.1, -2.6], mats.wood);
addBox(group, [5.2, 0.22, 0.28], [0, 1.1, 2.6], mats.wood);
addBox(group, [5.8, 3.8, 7.2], [0, 3.0, 0], wallMat);
const roof = new THREE.Mesh(roofGeometry(7.0, 8.1, 1.65), roofMat);
roof.position.y = 4.9;
roof.castShadow = true;
roof.receiveShadow = true;
group.add(roof);
const gable = new THREE.Mesh(gableGeometry(5.8, 7.2, 1.42), wallMat);
gable.position.y = 4.9;
group.add(gable);
const frontX = -door.side * 3.02;
const outwardX = -door.side;
addBox(group, [0.16, 1.9, 1.12], [frontX + outwardX * 0.04, 2.05, 0], mats.dark);
addBox(group, [0.20, 0.18, 1.38], [frontX + outwardX * 0.06, 3.03, 0], accentMat);
[-2.15, 2.15].forEach((z) => {
addBox(group, [0.16, 0.88, 1.02], [frontX + outwardX * 0.08, 3.08, z], mats.window);
addBox(group, [0.18, 0.12, 1.13], [frontX + outwardX * 0.11, 3.58, z], accentMat);
});
addBox(group, [0.18, 0.52, 2.45], [frontX + outwardX * 0.13, 4.26, 0], accentMat);
if (door.style === "artist") {
addBox(group, [0.13, 1.05, 1.05], [frontX + outwardX * 0.14, 3.0, -1.08], mats.coral);
addBox(group, [0.14, 0.78, 0.76], [frontX + outwardX * 0.15, 2.9, 1.0], mats.teal);
}
if (door.style === "temple") {
const spire = new THREE.Mesh(new THREE.ConeGeometry(2.05, 3.7, 6), mats.gold);
spire.position.set(0, 2.6, -5.2);
spire.castShadow = true;
group.add(spire);
const finial = new THREE.Mesh(new THREE.OctahedronGeometry(0.42, 0), accentMat);
finial.position.set(0, 4.7, -5.2);
group.add(finial);
}
if (door.style === "workshop") {
addBox(group, [0.8, 0.8, 0.8], [frontX + outwardX * 0.55, 0.4, -4.2], mats.woodLight);
addBox(group, [0.65, 0.65, 0.65], [frontX + outwardX * 0.48, 1.12, -4.2], accentMat);
}
if (door.style === "cafe") {
for (let i = -3; i <= 3; i++) {
addBox(
group,
[1.25, 0.15, 0.72],
[frontX + outwardX * 0.65, 3.42, i * 0.72],
i % 2 ? accentMat : mats.cream
);
}
}
if (door.style === "woodshop") {
for (let i = 0; i < 5; i++) {
const log = addCylinder(group, 0.17, 0.17, 2.1, [frontX + outwardX * 0.65, 0.2 + i * 0.32, 4.35], mats.woodLight, 6);
log.rotation.z = Math.PI / 2;
}
}
}
function createTree(x, z, scale = 1, variant = 0) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.scale.setScalar(scale);
world.add(group);
addCylinder(group, 0.19, 0.29, 2.5, [0, 1.25, 0], mats.trunk, 5);
const foliage = new THREE.Mesh(
new THREE.IcosahedronGeometry(1.55 + (variant % 2) * 0.16, 0),
variant % 2 ? mats.foliageA : mats.foliageB
);
foliage.position.set(0.05, 3.15, 0);
foliage.rotation.y = variant * 0.71;
foliage.castShadow = true;
group.add(foliage);
const crown = new THREE.Mesh(new THREE.IcosahedronGeometry(1.05, 0), mats.foliageA);
crown.position.set(0.58, 3.65, -0.18);
crown.castShadow = true;
group.add(crown);
}
function createStall(x, z, canopyMat) {
const group = new THREE.Group();
group.position.set(x, 0, z);
world.add(group);
[-1.2, 1.2].forEach((px) => {
[-0.9, 0.9].forEach((pz) => addBox(group, [0.12, 2.4, 0.12], [px, 1.2, pz], mats.woodDark));
});
const canopy = new THREE.Mesh(new THREE.ConeGeometry(2.25, 1.05, 4), canopyMat);
canopy.position.y = 2.55;
canopy.rotation.y = Math.PI / 4;
canopy.scale.z = 0.78;
canopy.castShadow = true;
group.add(canopy);
addBox(group, [1.7, 0.8, 1.0], [0, 0.4, 0.2], mats.woodLight);
addBox(group, [0.65, 0.65, 0.65], [-0.8, 0.34, -0.55], mats.teal);
addBox(group, [0.55, 0.55, 0.55], [0.7, 0.29, -0.5], mats.orange);
}
function buildBoatModel(color) {
const group = new THREE.Group();
const hullMat = material(color);
const trimMat = material(0x6c4935);
const hull = addBox(group, [1.35, 0.48, 3.25], [0, 0.18, 0], hullMat);
hull.castShadow = true;
const bow = new THREE.Mesh(new THREE.ConeGeometry(0.68, 1.9, 4), hullMat);
bow.rotation.x = Math.PI / 2;
bow.position.set(0, 0.18, 2.2);
bow.castShadow = true;
group.add(bow);
addBox(group, [1.08, 0.11, 2.75], [0, 0.47, -0.1], trimMat);
addBox(group, [1.08, 0.14, 1.25], [0, 1.08, -0.55], mats.cream);
addBox(group, [1.28, 0.12, 1.48], [0, 1.44, -0.55], mats.orange);
[-0.42, 0.42].forEach((x) => addBox(group, [0.08, 0.72, 0.08], [x, 0.8, -0.55], mats.woodDark));
const engine = addBox(group, [0.62, 0.55, 0.52], [0, 0.64, -1.85], mats.dark);
engine.castShadow = true;
const shaft = addCylinder(group, 0.045, 0.045, 2.8, [0, 0.18, -2.4], mats.woodDark, 5);
shaft.rotation.x = Math.PI / 2;
const person = new THREE.Mesh(new THREE.SphereGeometry(0.24, 7, 5), material(0x8f5a43));
person.position.set(0, 1.08, 0.72);
group.add(person);
addCylinder(group, 0.24, 0.29, 0.58, [0, 0.83, 0.72], mats.teal, 6);
return group;
}
function buildWalkerModel() {
const group = new THREE.Group();
const body = new THREE.Mesh(new THREE.ConeGeometry(0.32, 0.8, 7), mats.orange);
body.position.y = 0.55;
group.add(body);
const head = new THREE.Mesh(new THREE.SphereGeometry(0.23, 8, 6), mats.cream);
head.position.y = 1.12;
group.add(head);
const hat = addCylinder(group, 0.35, 0.35, 0.07, [0, 1.31, 0], mats.gold, 8);
hat.castShadow = true;
return group;
}
buildLandscape();
const renderedBridgeIds = new Set();
function createBridge(edge) {
const from = nodes.get(edge.from);
const to = nodes.get(edge.to);
if (!from || !to) throw new Error(`Cannot render undefined bridge ${edge.id}`);
const a = new THREE.Vector3(...from.position);
const b = new THREE.Vector3(...to.position);
const dx = b.x - a.x;
const dz = b.z - a.z;
const length = Math.hypot(dx, dz);
const group = new THREE.Group();
group.position.set((a.x + b.x) / 2, 0, (a.z + b.z) / 2);
group.rotation.y = -Math.atan2(dz, dx);
world.add(group);
addBox(group, [length, 0.20, 2.25], [0, 0.39, 0], mats.wood);
const plankCount = Math.max(8, Math.round(length / 0.95));
for (let i = 0; i <= plankCount; i++) {
const x = -length / 2 + (length * i / plankCount);
addBox(group, [0.045, 0.025, 2.20], [x, 0.505, 0], mats.woodDark, false);
}
[-1.06, 1.06].forEach((z) => {
addBox(group, [length, 0.12, 0.12], [0, 1.20, z], mats.woodLight);
for (let i = 0; i <= 4; i++) {
const x = -length / 2 + (length * i / 4);
addBox(group, [0.13, 1.0, 0.13], [x, 0.79, z], mats.woodDark);
}
});
renderedBridgeIds.add(edge.id);
}
edges.filter((edge) => edge.kind === "bridge").forEach(createBridge);
doors.forEach(createHouse);
const treeData = [
[-21, -40, 1.0, 0], [-23, -22, 0.9, 1], [-22, -8, 1.05, 2],
[-21, 10, 0.95, 3], [-23, 25, 1.08, 4], [-22, 40, 0.96, 5],
[22, -40, 0.95, 1], [23, -23, 1.1, 2], [21, -6, 0.92, 3],
[22, 8, 1.05, 4], [21, 26, 0.96, 5], [23, 40, 1.0, 0],
[-10, -43, 0.75, 2], [12, -43, 0.8, 3]
];
treeData.forEach(([x, z, scale, variant]) => createTree(x, z, scale, variant));
createStall(-17.5, -40, mats.coral);
createStall(18.5, -39, mats.teal);
createStall(20, 8, mats.gold);
const staticBoat1 = buildBoatModel(0xcf7047);
staticBoat1.position.set(centerX(-8) - 1.1, 0.12, -8);
staticBoat1.rotation.y = 0.12;
staticBoat1.scale.setScalar(0.92);
world.add(staticBoat1);
const staticBoat2 = buildBoatModel(0x3d8179);
staticBoat2.position.set(centerX(23) + 1.15, 0.12, 23);
staticBoat2.rotation.y = -0.17;
staticBoat2.scale.setScalar(0.86);
world.add(staticBoat2);
const staticBoat3 = buildBoatModel(0xd0a547);
staticBoat3.position.set(centerX(38) - 0.75, 0.12, 38);
staticBoat3.rotation.y = 0.23;
staticBoat3.scale.setScalar(0.78);
world.add(staticBoat3);
doors.forEach((door) => {
const approach = edgeById.get(door.approachEdgeId);
const bank = nodes.get(approach.from);
const doorNode = nodes.get(door.nodeId);
addFlatStrip(
new THREE.Vector3(...bank.position),
new THREE.Vector3(...doorNode.position),
1.28,
0.245,
mats.pathEdge
);
const landing = nodes.get(door.waterNodeId);
const dockA = new THREE.Vector3(...landing.position);
const dockB = new THREE.Vector3(...doorNode.position);
const dockLength = Math.hypot(dockB.x - dockA.x, dockB.z - dockA.z);
const plankCount = Math.max(5, Math.ceil(dockLength / 0.72));
for (let i = 0; i < plankCount; i++) {
const t0 = i / plankCount;
const t1 = (i + 1) / plankCount;
const p0 = dockA.clone().lerp(dockB, t0);
const p1 = dockA.clone().lerp(dockB, t1);
const segmentLength = Math.hypot(p1.x - p0.x, p1.z - p0.z);
const plank = addBox(
world,
[segmentLength + 0.08, 0.11, 1.12],
[(p0.x + p1.x) / 2, 0.17 + ((p0.y + p1.y) / 2 - 0.12) * 0.45, (p0.z + p1.z) / 2],
i % 2 ? mats.woodLight : mats.wood,
false
);
plank.rotation.y = -Math.atan2(p1.z - p0.z, p1.x - p0.x);
}
});
const nodeDotMaterial = new THREE.MeshBasicMaterial({
color: 0xfff6d2,
transparent: true,
opacity: 0.78,
depthWrite: false
});
for (const node of nodes.values()) {
const dot = new THREE.Mesh(
new THREE.CylinderGeometry(node.layer === "water" ? 0.13 : 0.10, node.layer === "water" ? 0.13 : 0.10, 0.035, 8),
nodeDotMaterial
);
dot.position.set(node.position[0], node.position[1] + 0.11, node.position[2]);
dot.renderOrder = 6;
world.add(dot);
}
const pickables = [];
const doorMarkers = new Map();
function createDoorMarker(door) {
const group = new THREE.Group();
group.position.set(door.position[0], door.position[1], door.position[2]);
world.add(group);
const headMaterial = new THREE.MeshStandardMaterial({
color: 0xffd166,
emissive: 0x7d4c00,
emissiveIntensity: 0.65,
roughness: 0.45,
flatShading: true
});
const head = new THREE.Mesh(new THREE.SphereGeometry(0.43, 8, 6), headMaterial);
head.position.y = 1.42;
head.castShadow = true;
head.userData.doorId = door.nodeId;
group.add(head);
pickables.push(head);
const beam = addCylinder(
group,
0.065,
0.065,
1.35,
[0, 0.68, 0],
new THREE.MeshStandardMaterial({
color: 0xf1c75b,
emissive: 0x6d4900,
emissiveIntensity: 0.35,
roughness: 0.6
}),
6
);
beam.castShadow = true;
const ringMaterial = new THREE.MeshBasicMaterial({
color: 0xffd166,
depthTest: false,
depthWrite: false
});
const ring = new THREE.Mesh(new THREE.TorusGeometry(0.72, 0.085, 6, 22), ringMaterial);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.04;
ring.renderOrder = 22;
group.add(ring);
doorMarkers.set(door.nodeId, { group, head, ring, headMaterial });
}
doors.forEach(createDoorMarker);
const selectionHalo = new THREE.Mesh(
new THREE.TorusGeometry(1.16, 0.075, 6, 28),
new THREE.MeshBasicMaterial({
color: 0xf0643b,
transparent: true,
opacity: 0.9,
depthTest: false,
depthWrite: false
})
);
selectionHalo.rotation.x = Math.PI / 2;
selectionHalo.renderOrder = 24;
world.add(selectionHalo);
const routeMaterials = {
boat: new THREE.MeshBasicMaterial({
color: 0x00c6cf,
transparent: true,
opacity: 0.98,
depthTest: false,
depthWrite: false
}),
dock: new THREE.MeshBasicMaterial({
color: 0xf1c75b,
transparent: true,
opacity: 0.98,
depthTest: false,
depthWrite: false
}),
walk: new THREE.MeshBasicMaterial({
color: 0xf0643b,
transparent: true,
opacity: 0.98,
depthTest: false,
depthWrite: false
})
};
function clearGroup(group) {
const children = [...group.children];
for (const child of children) {
child.traverse((object) => {
if (object.geometry) object.geometry.dispose();
});
group.remove(child);
}
}
function routeSegment(parent, a, b, radius, mat, withArrow = true) {
const delta = b.clone().sub(a);
const length = delta.length();
if (length < 0.001) return;
const geometry = new THREE.CylinderGeometry(radius, radius, length, 7, 1, false);
const mesh = new THREE.Mesh(geometry, mat);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), delta.clone().normalize());
mesh.renderOrder = 30;
parent.add(mesh);
if (withArrow && length > 0.75) {
const arrow = new THREE.Mesh(new THREE.ConeGeometry(radius * 2.1, radius * 5.4, 6), mat);
arrow.position.copy(a).lerp(b, 0.64);
arrow.quaternion.copy(mesh.quaternion);
arrow.renderOrder = 31;
parent.add(arrow);
}
}
function dashedSegment(parent, a, b, mat) {
const delta = b.clone().sub(a);
const length = delta.length();
const pieces = Math.max(2, Math.ceil(length / 1.15));
for (let i = 0; i < pieces; i++) {
const t0 = i / pieces;
const t1 = Math.min(1, t0 + 0.56 / pieces);
routeSegment(parent, a.clone().lerp(b, t0), a.clone().lerp(b, t1), 0.12, mat, false);
}
}
function routePoint(nodeId, y) {
const p = nodes.get(nodeId).position;
return new THREE.Vector3(p[0], y, p[2]);
}
function routeEndpoint(parent, point, mat, radius = 0.26) {
const mesh = new THREE.Mesh(new THREE.SphereGeometry(radius, 8, 6), mat);
mesh.position.copy(point);
mesh.renderOrder = 32;
parent.add(mesh);
}
const animatedBoat = buildBoatModel(0xf0643b);
animatedBoat.scale.setScalar(0.70);
world.add(animatedBoat);
const animatedWalker = buildWalkerModel();
world.add(animatedWalker);
const labelItems = [];
const doorLabels = new Map();
function addWorldLabel(text, subtext, position, doorId = null) {
const element = document.createElement("div");
element.className = `world-label${doorId ? " door-label" : ""}`;
const title = document.createElement("span");
title.textContent = text;
element.appendChild(title);
if (subtext) {
const sub = document.createElement("small");
sub.textContent = subtext;
element.appendChild(sub);
}
labelsLayer.appendChild(element);
const item = {
element,
position: position.isVector3 ? position.clone() : new THREE.Vector3(...position),
doorId
};
labelItems.push(item);
if (doorId) {
doorLabels.set(doorId, element);
element.addEventListener("click", (event) => {
event.stopPropagation();
selectDoor(doorId);
});
}
return item;
}
doors.forEach((door) => {
addWorldLabel(
door.name.replace(" door", ""),
`${door.scheme} door`,
new THREE.Vector3(door.position[0], door.position[1] + 2.35, door.position[2]),
door.nodeId
);
});
addWorldLabel(
"Khlong Bang Luang canal",
"schematic reach",
new THREE.Vector3(centerX(9), 0.8, 9)
);
addWorldLabel(
"Schematic footbridge 3",
"explicit pedestrian link",
new THREE.Vector3(centerX(0), 2.25, 0)
);
addWorldLabel(
"South boat landing",
"schematic origin",
new THREE.Vector3(nodes.get("water_south").position[0], 1.1, nodes.get("water_south").position[2])
);
addWorldLabel(
"South lane entrance",
"schematic origin",
new THREE.Vector3(nodes.get("walk_l0").position[0] - 0.5, 1.1, nodes.get("walk_l0").position[2])
);
for (const door of doors) {
const option = document.createElement("option");
option.value = door.nodeId;
option.textContent = `${door.name} — ${door.scheme}`;
doorSelect.appendChild(option);
}
let selectedDoorId = null;
let activeRoutes = null;
let mode = "compare";
let labelsVisible = true;
const visualPaths = { boat: [], walk: [] };
function formatDuration(minutes) {
if (minutes < 1) return "<1 min";
if (minutes < 10) return `${Math.round(minutes)} min`;
return `${Math.round(minutes)} min`;
}
function updateMarkerSelection() {
for (const door of doors) {
const marker = doorMarkers.get(door.nodeId);
const selected = door.nodeId === selectedDoorId;
marker.ring.material.color.set(selected ? 0xf0643b : 0xffd166);
marker.ring.scale.setScalar(selected ? 1.28 : 1);
marker.headMaterial.color.set(selected ? 0xff8b58 : 0xffd166);
marker.headMaterial.emissive.set(selected ? 0x8a2600 : 0x7d4c00);
marker.head.scale.setScalar(selected ? 1.18 : 1);
doorLabels.get(door.nodeId)?.classList.toggle("selected", selected);
}
}
function rebuildRouteGeometry(routes) {
clearGroup(boatRouteGroup);
clearGroup(walkRouteGroup);
const boatPoints = routes.boat.waterPath.nodes.map((id) => routePoint(id, 0.29));
visualPaths.boat = boatPoints;
for (let i = 0; i < boatPoints.length - 1; i++) {
routeSegment(boatRouteGroup, boatPoints[i], boatPoints[i + 1], 0.19, routeMaterials.boat, true);
}
const dockStart = routePoint(routes.boat.dockEdge.from, 0.29);
const dockEnd = routePoint(routes.boat.dockEdge.to, 0.68);
dashedSegment(boatRouteGroup, dockStart, dockEnd, routeMaterials.dock);
routeEndpoint(boatRouteGroup, boatPoints[0], routeMaterials.boat, 0.31);
routeEndpoint(boatRouteGroup, boatPoints[boatPoints.length - 1], routeMaterials.boat, 0.29);
const walkPoints = routes.walk.path.nodes.map((id) => routePoint(id, 0.69));
visualPaths.walk = walkPoints;
for (let i = 0; i < walkPoints.length - 1; i++) {
routeSegment(walkRouteGroup, walkPoints[i], walkPoints[i + 1], 0.17, routeMaterials.walk, true);
}
routeEndpoint(walkRouteGroup, walkPoints[0], routeMaterials.walk, 0.28);
routeEndpoint(walkRouteGroup, walkPoints[walkPoints.length - 1], routeMaterials.walk, 0.31);
}
function updateRouteInterface(door, routes) {
const boat = routes.boat;
const walk = routes.walk;
const bridgeNames = walk.bridgeEdges.map((edge) => edge.name);
$("boatDistance").textContent = `${Math.round(boat.totalMeters)} m`;
$("boatTime").textContent = formatDuration(boat.minutes);
$("boatDetail").textContent =
`${boat.waterPath.edges.length} water links · ${Math.round(boat.waterMeters)} m on canal · ${Math.round(boat.dockMeters)} m dock`;
$("boatCheck").textContent =
`Water-connected at ${nodes.get(door.waterNodeId).id}; dock is appended after the water path.`;
$("walkDistance").textContent = `${Math.round(walk.totalMeters)} m`;
$("walkTime").textContent = formatDuration(walk.minutes);
$("walkDetail").textContent = bridgeNames.length
? `${walk.path.edges.length} pedestrian links · ${bridgeNames.length} explicit bridge: ${bridgeNames.join(", ")}`
: `${walk.path.edges.length} pedestrian links · same-bank route, no canal crossing required`;
$("walkCheck").textContent = bridgeNames.length
? `Bridge-valid path; canal crossing uses ${bridgeNames.join(", ")}.`
: "Bridge-valid path; this destination is reached from the starting bank.";
const difference = boat.minutes - walk.minutes;
if (Math.abs(difference) < 0.5) {
$("compareSummary").textContent = "The validated boat and walking routes have nearly identical estimated travel times for this door.";
} else if (difference < 0) {
$("compareSummary").textContent =
`Boat is about ${Math.abs(difference).toFixed(1)} minutes faster for this synthetic door, including the final dock segment.`;
} else {
$("compareSummary").textContent =
`Walking is about ${Math.abs(difference).toFixed(1)} minutes faster for this synthetic door.`;
}
const boatTrace = [...boat.waterPath.nodes, door.nodeId].join(" → ");
$("boatTrace").textContent = `${boatTrace} [dock: ${door.dockEdgeId}]`;
$("walkTrace").textContent =
`${walk.path.nodes.join(" → ")} [bridges: ${bridgeNames.length ? bridgeNames.join(", ") : "none required"}]`;
$("selectedAudit").textContent =
`Selected ${door.nodeId}: ${boat.waterPath.edges.length} water edges + 1 dock edge; ` +
`${walk.path.edges.length} walk/bridge edges. Both ribbons are drawn from these exact validated nodes.`;
}
function selectDoor(doorId) {
const door = doors.find((candidate) => candidate.nodeId === doorId);
if (!door) return;
selectedDoorId = doorId;
doorSelect.value = doorId;
updateMarkerSelection();
const routes = computeDoorRoutes(door);
activeRoutes = routes;
rebuildRouteGeometry(routes);
updateRouteInterface(door, routes);
selectionHalo.position.set(door.position[0], door.position[1] + 0.05, door.position[2]);
}
function setMode(nextMode) {
mode = nextMode;
document.querySelectorAll(".mode-switch button").forEach((button) => {
const active = button.dataset.mode === mode;
button.classList.toggle("active", active);
button.setAttribute("aria-pressed", String(active));
});
boatRouteGroup.visible = mode !== "walk";
walkRouteGroup.visible = mode !== "boat";
animatedBoat.visible = mode !== "walk";
animatedWalker.visible = mode !== "boat";
$("boatCard").classList.toggle("is-active", mode !== "walk");
$("boatCard").classList.toggle("is-dim", mode === "walk");
$("walkCard").classList.toggle("is-active", mode !== "boat");
$("walkCard").classList.toggle("is-dim", mode === "boat");
$("modeReadout").textContent = mode === "compare"
? "Compare mode · both routes visible"
: mode === "boat"
? "Boat mode · water route visible"
: "Walk mode · bridge-valid route visible";
}
document.querySelectorAll(".mode-switch button").forEach((button) => {
button.addEventListener("click", () => setMode(button.dataset.mode));
});
$("boatCard").addEventListener("click", () => setMode("boat"));
$("walkCard").addEventListener("click", () => setMode("walk"));
doorSelect.addEventListener("change", (event) => selectDoor(event.target.value));
$("resetView").addEventListener("click", () => {
orbit.theta = 0.52;
orbit.phi = 0.72;
orbit.radius = 155;
orbit.target.set(0, 0, 0);
updateCamera();
});
$("toggleLabels").addEventListener("click", () => {
labelsVisible = !labelsVisible;
labelsLayer.classList.toggle("hidden", !labelsVisible);
$("toggleLabels").textContent = labelsVisible ? "Labels on" : "Labels off";
});
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function doorUnderPointer(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(pickables, false);
return intersections.length ? intersections[0].object.userData.doorId : null;
}
const pointerState = {
active: false,
id: null,
button: 0,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0,
moved: false
};
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0 && event.button !== 1 && event.button !== 2) return;
pointerState.active = true;
pointerState.id = event.pointerId;
pointerState.button = event.button;
pointerState.startX = event.clientX;
pointerState.startY = event.clientY;
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
pointerState.moved = false;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointerState.active || event.pointerId !== pointerState.id) {
if (!pointerState.active) {
renderer.domElement.style.cursor = doorUnderPointer(event) ? "pointer" : "grab";
}
return;
}
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
const totalDX = event.clientX - pointerState.startX;
const totalDY = event.clientY - pointerState.startY;
if (Math.hypot(totalDX, totalDY) > 4) pointerState.moved = true;
if (pointerState.button === 0) {
orbit.theta -= dx * 0.005;
orbit.phi = THREE.MathUtils.clamp(orbit.phi - dy * 0.005, 0.34, 1.34);
} else {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrixWorld, 0);
right.y = 0;
right.normalize();
const scale = orbit.radius * 2 * Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)) / stage.clientHeight;
orbit.target.addScaledVector(right, -dx * scale);
orbit.target.addScaledVector(forward, dy * scale);
orbit.target.x = THREE.MathUtils.clamp(orbit.target.x, -32, 32);
orbit.target.z = THREE.MathUtils.clamp(orbit.target.z, -38, 38);
}
updateCamera();
renderer.domElement.style.cursor = "grabbing";
});
function endPointer(event) {
if (!pointerState.active || event.pointerId !== pointerState.id) return;
if (!pointerState.moved && pointerState.button === 0) {
const doorId = doorUnderPointer(event);
if (doorId) selectDoor(doorId);
}
pointerState.active = false;
pointerState.id = null;
renderer.domElement.style.cursor = "grab";
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener("contextmenu", (event) => event.preventDefault());
renderer.domElement.addEventListener("wheel", (event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
70,
215
);
updateCamera();
}, { passive: false });
renderer.domElement.addEventListener("dblclick", () => {
orbit.theta = 0.52;
orbit.phi = 0.72;
orbit.radius = 155;
orbit.target.set(0, 0, 0);
updateCamera();
});
function resize() {
const width = Math.max(1, stage.clientWidth);
const height = Math.max(1, stage.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
resize();
new ResizeObserver(resize).observe(stage);
const waterNodeCount = [...nodes.values()].filter((node) => node.layer === "water").length;
const walkNodeCount = [...nodes.values()].filter((node) => node.layer === "walk").length;
const bridgeCount = edges.filter((edge) => edge.kind === "bridge").length;
if (renderedBridgeIds.size !== bridgeCount) {
throw new Error(`Only ${renderedBridgeIds.size} of ${bridgeCount} bridge edges were rendered`);
}
if (pickables.length !== doors.length) {
throw new Error(`Only ${pickables.length} of ${doors.length} door anchors were created`);
}
$("auditWater").textContent = `${networkAudit.waterReachable.size}/${waterNodeCount} reachable`;
$("auditWalk").textContent = `${networkAudit.walkReachable.size}/${walkNodeCount} reachable`;
$("auditBridge").textContent = `${renderedBridgeIds.size}/${bridgeCount} meshes match`;
$("auditDoor").textContent = `${pickables.length}/${doors.length} finite anchors`;
$("networkStatus").textContent = "Validated · no undefined nodes";
selectDoor("door_temple");
setMode("compare");
function samplePolyline(points, t) {
if (!points.length) return null;
if (points.length === 1) return { position: points[0].clone(), direction: new THREE.Vector3(0, 0, 1) };
const lengths = [];
let total = 0;
for (let i = 0; i < points.length - 1; i++) {
const length = points[i].distanceTo(points[i + 1]);
lengths.push(length);
total += length;
}
let target = ((t % 1) + 1) % 1 * total;
for (let i = 0; i < lengths.length; i++) {
if (target <= lengths[i] || i === lengths.length - 1) {
const localT = lengths[i] > 0 ? target / lengths[i] : 0;
const position = points[i].clone().lerp(points[i + 1], localT);
const direction = points[i + 1].clone().sub(points[i]).normalize();
return { position, direction };
}
target -= lengths[i];
}
return {
position: points[points.length - 1].clone(),
direction: points[points.length - 1].clone().sub(points[points.length - 2]).normalize()
};
}
function updateLabels() {
if (!labelsVisible) return;
const width = stage.clientWidth;
const height = stage.clientHeight;
for (const item of labelItems) {
const projected = item.position.clone().project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
projected.x > -1.08 &&
projected.x < 1.08 &&
projected.y > -1.08 &&
projected.y < 1.08;
item.element.style.display = visible ? "block" : "none";
if (!visible) continue;
item.element.style.left = `${(projected.x * 0.5 + 0.5) * width}px`;
item.element.style.top = `${(-projected.y * 0.5 + 0.5) * height}px`;
}
}
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
if (activeRoutes && visualPaths.boat.length) {
const boatSample = samplePolyline(visualPaths.boat, reducedMotion ? 0.38 : elapsed * 0.035);
animatedBoat.position.copy(boatSample.position);
animatedBoat.position.y += 0.02;
animatedBoat.rotation.y = Math.atan2(boatSample.direction.x, boatSample.direction.z);
}
if (activeRoutes && visualPaths.walk.length) {
const walkSample = samplePolyline(visualPaths.walk, reducedMotion ? 0.48 : elapsed * 0.042);
animatedWalker.position.copy(walkSample.position);
}
const pulse = reducedMotion ? 1 : 1 + Math.sin(elapsed * 2.4) * 0.055;
selectionHalo.scale.setScalar(pulse);
updateLabels();
renderer.render(scene, camera);
}
$("loading").hidden = true;
animate();
}
try {
startScene();
} catch (error) {
console.error(error);
$("loading").hidden = true;
const fatal = $("fatal");
fatal.hidden = false;
fatal.textContent = `The procedural scene could not start: ${error.message}`;
}
</script>
</body>
</html>
```