Prompt specification
Build or customize the Three.js 3D scene "Choose a route using different priorities" 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: Choose a route using different priorities
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/choose-a-route-using-different-priorities-x1300
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing route distance and travel-time tradeoffs. Let users prioritize distance, ascent, or accessibility in a fictional road network. Highlight the resulting route and show why changing the criterion can change the preferred path. Low-poly.
Working Three.js Starter (choose-a-route-using-different-priorities-x1300):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#081820">
<title>Northvale Route Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #081820;
--panel: rgba(10, 28, 36, 0.92);
--panel-solid: #0b2029;
--line: rgba(181, 222, 218, 0.15);
--text: #edf7f2;
--muted: #91aaa8;
--mint: #55efbd;
--blue: #69b7ff;
--amber: #ffbd69;
--violet: #c59bff;
--coral: #ff8b78;
--shadow: 0 24px 70px rgba(0, 0, 0, 0.35);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#app,
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.topbar {
position: fixed;
z-index: 20;
top: 0;
left: 0;
right: 0;
height: 72px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 24px;
pointer-events: none;
background: linear-gradient(180deg, rgba(4, 15, 21, 0.8), transparent);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
}
.brand-mark {
width: 34px;
height: 34px;
display: grid;
place-items: center;
border: 1px solid rgba(85, 239, 189, 0.35);
border-radius: 10px;
color: var(--mint);
background: rgba(85, 239, 189, 0.08);
box-shadow: inset 0 0 20px rgba(85, 239, 189, 0.06);
}
.brand-title {
font-size: 14px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.brand-subtitle {
margin-top: 2px;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.05em;
}
.live-route {
display: flex;
align-items: center;
gap: 10px;
padding: 9px 13px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(9, 26, 34, 0.7);
backdrop-filter: blur(12px);
color: var(--muted);
font-size: 12px;
}
.live-route strong {
color: var(--text);
font-weight: 700;
}
.live-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--mint);
box-shadow: 0 0 12px var(--mint);
}
.panel {
position: fixed;
z-index: 30;
top: 84px;
left: 20px;
bottom: 20px;
width: 372px;
overflow: auto;
padding: 20px;
border: 1px solid var(--line);
border-radius: 22px;
background: var(--panel);
backdrop-filter: blur(20px) saturate(1.15);
box-shadow: var(--shadow);
scrollbar-width: thin;
scrollbar-color: rgba(145, 170, 168, 0.3) transparent;
}
.panel::-webkit-scrollbar {
width: 5px;
}
.panel::-webkit-scrollbar-thumb {
background: rgba(145, 170, 168, 0.3);
border-radius: 10px;
}
.eyebrow {
color: var(--mint);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
h1 {
margin: 7px 0 7px;
font-size: 27px;
line-height: 1.08;
letter-spacing: -0.04em;
}
.intro {
margin: 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.endpoints {
display: flex;
align-items: center;
gap: 10px;
margin: 17px 0;
padding: 12px 13px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255, 255, 255, 0.025);
font-size: 12px;
font-weight: 650;
}
.endpoint-dot {
width: 8px;
height: 8px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--mint);
box-shadow: 0 0 10px rgba(85, 239, 189, 0.6);
}
.endpoint-dot.end {
background: var(--coral);
box-shadow: 0 0 10px rgba(255, 139, 120, 0.55);
}
.endpoint-arrow {
flex: 1;
height: 1px;
background: linear-gradient(90deg, var(--mint), var(--coral));
opacity: 0.65;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 19px 0 10px;
color: #c9d9d6;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.section-title small {
color: var(--muted);
font-size: 9px;
font-weight: 600;
letter-spacing: 0;
text-transform: none;
}
.presets {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-bottom: 16px;
}
.preset {
min-height: 56px;
padding: 8px 4px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.025);
cursor: pointer;
transition: 160ms ease;
}
.preset:hover,
.preset.active {
border-color: rgba(85, 239, 189, 0.55);
background: rgba(85, 239, 189, 0.09);
transform: translateY(-1px);
}
.preset-icon {
display: block;
margin-bottom: 5px;
color: var(--mint);
font-size: 15px;
line-height: 1;
}
.preset-name {
display: block;
font-size: 10px;
font-weight: 700;
white-space: nowrap;
}
.slider-row {
margin: 13px 0;
}
.slider-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 7px;
font-size: 12px;
}
.slider-label {
display: flex;
align-items: center;
gap: 8px;
font-weight: 650;
}
.slider-swatch {
width: 7px;
height: 7px;
border-radius: 50%;
}
.slider-output {
min-width: 38px;
padding: 3px 7px;
border-radius: 7px;
background: rgba(255, 255, 255, 0.05);
color: #c9d9d6;
font-size: 10px;
text-align: right;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 0;
appearance: none;
border-radius: 99px;
outline: none;
background: rgba(255, 255, 255, 0.09);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 16px;
height: 16px;
appearance: none;
border: 3px solid #effff9;
border-radius: 50%;
background: var(--range-color, var(--mint));
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.35);
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border: 3px solid #effff9;
border-radius: 50%;
background: var(--range-color, var(--mint));
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.35);
}
#distanceSlider {
--range-color: var(--blue);
}
#ascentSlider {
--range-color: var(--amber);
}
#accessSlider {
--range-color: var(--violet);
}
.mix-note {
min-height: 28px;
color: var(--muted);
font-size: 10px;
line-height: 1.4;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 9px;
}
.metric {
min-height: 78px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255, 255, 255, 0.025);
}
.metric-label {
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.metric-value {
margin-top: 7px;
font-size: 21px;
font-weight: 780;
letter-spacing: -0.035em;
}
.metric-value small {
color: var(--muted);
font-size: 10px;
font-weight: 600;
letter-spacing: 0;
}
.metric.accent .metric-value {
color: var(--mint);
}
.insight {
position: relative;
margin-top: 11px;
padding: 15px;
overflow: hidden;
border: 1px solid rgba(85, 239, 189, 0.23);
border-radius: 15px;
background:
linear-gradient(135deg, rgba(85, 239, 189, 0.09), rgba(85, 239, 189, 0.015)),
rgba(0, 0, 0, 0.08);
}
.insight::after {
content: "";
position: absolute;
top: -35px;
right: -35px;
width: 95px;
height: 95px;
border-radius: 50%;
background: rgba(85, 239, 189, 0.08);
filter: blur(2px);
}
.insight-kicker {
color: var(--mint);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.insight-title {
margin: 6px 0 6px;
font-size: 16px;
font-weight: 780;
}
.insight-text {
margin: 0;
color: #b8cbc7;
font-size: 11px;
line-height: 1.55;
}
.route-flow {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 5px;
margin-top: 11px;
}
.route-stop {
padding: 4px 7px;
border: 1px solid rgba(85, 239, 189, 0.15);
border-radius: 7px;
background: rgba(85, 239, 189, 0.06);
color: #dff9ef;
font-size: 9px;
font-weight: 650;
}
.route-arrow {
color: #60807a;
font-size: 9px;
}
.ref-list {
display: grid;
gap: 8px;
}
.ref-card {
width: 100%;
padding: 12px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255, 255, 255, 0.022);
text-align: left;
cursor: pointer;
transition: 160ms ease;
}
.ref-card:hover {
background: rgba(255, 255, 255, 0.045);
transform: translateX(2px);
}
.ref-card.active {
border-color: rgba(85, 239, 189, 0.45);
background: rgba(85, 239, 189, 0.055);
}
.ref-head {
display: flex;
align-items: center;
gap: 8px;
}
.ref-swatch {
width: 8px;
height: 8px;
border-radius: 50%;
box-shadow: 0 0 9px currentColor;
}
.ref-name {
font-size: 11px;
font-weight: 750;
}
.ref-distance {
margin-left: auto;
color: #d9e8e4;
font-size: 11px;
font-weight: 760;
}
.ref-stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin-top: 9px;
color: var(--muted);
font-size: 9px;
}
.ref-stats b {
display: block;
margin-bottom: 2px;
color: #d5e4e1;
font-size: 10px;
}
.layer-controls {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 12px;
}
.toggle {
display: flex;
align-items: center;
gap: 8px;
padding: 9px;
border: 1px solid var(--line);
border-radius: 10px;
color: var(--muted);
font-size: 10px;
cursor: pointer;
user-select: none;
}
.toggle input {
accent-color: var(--mint);
}
details {
margin-top: 13px;
padding: 11px 12px;
border: 1px solid var(--line);
border-radius: 11px;
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
summary {
color: #bdd0cc;
font-weight: 700;
cursor: pointer;
}
details p {
margin: 9px 0 0;
}
.map-tools {
position: fixed;
z-index: 25;
top: 88px;
right: 20px;
display: flex;
gap: 8px;
}
.tool-button {
height: 38px;
padding: 0 12px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(10, 28, 36, 0.78);
backdrop-filter: blur(12px);
color: #d8e8e4;
font-size: 10px;
font-weight: 700;
cursor: pointer;
transition: 150ms ease;
}
.tool-button:hover {
border-color: rgba(85, 239, 189, 0.42);
color: var(--mint);
}
.compass {
position: fixed;
z-index: 15;
top: 140px;
right: 22px;
width: 47px;
height: 47px;
display: grid;
place-items: center;
border: 1px solid var(--line);
border-radius: 50%;
background: rgba(10, 28, 36, 0.6);
color: var(--muted);
pointer-events: none;
backdrop-filter: blur(10px);
}
.compass span {
position: absolute;
top: 4px;
font-size: 8px;
font-weight: 800;
}
.compass-needle {
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 17px solid var(--coral);
transform-origin: 50% 70%;
}
.legend {
position: fixed;
z-index: 20;
right: 22px;
bottom: 22px;
display: flex;
align-items: center;
gap: 14px;
padding: 10px 13px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(10, 28, 36, 0.74);
backdrop-filter: blur(12px);
color: var(--muted);
font-size: 9px;
pointer-events: none;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
white-space: nowrap;
}
.legend-line {
width: 16px;
height: 3px;
border-radius: 3px;
background: var(--mint);
}
.legend-line.dashed {
height: 0;
border-top: 2px dashed var(--blue);
background: transparent;
}
.camera-hint {
position: fixed;
z-index: 15;
left: 414px;
bottom: 23px;
padding: 8px 11px;
border: 1px solid rgba(181, 222, 218, 0.1);
border-radius: 9px;
background: rgba(6, 20, 27, 0.55);
color: rgba(181, 205, 201, 0.7);
font-size: 9px;
pointer-events: none;
backdrop-filter: blur(8px);
}
#labelLayer {
position: fixed;
z-index: 10;
inset: 0;
overflow: hidden;
pointer-events: none;
}
.map-label {
position: absolute;
padding: 3px 6px;
border: 1px solid rgba(210, 235, 230, 0.14);
border-radius: 6px;
background: rgba(7, 22, 29, 0.76);
color: #d5e5e1;
font-size: 9px;
font-weight: 700;
white-space: nowrap;
transform: translate(-50%, -100%);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}
.map-label.endpoint {
border-color: rgba(85, 239, 189, 0.4);
color: #cffff0;
}
.map-label.callout {
padding: 6px 8px;
font-size: 8px;
letter-spacing: 0.02em;
}
.map-label.callout.warning {
border-color: rgba(255, 139, 120, 0.42);
color: #ffd2c9;
background: rgba(51, 22, 22, 0.82);
}
.map-label.callout.smooth {
border-color: rgba(197, 155, 255, 0.38);
color: #eadcff;
background: rgba(30, 22, 48, 0.82);
}
#loading {
position: fixed;
z-index: 100;
inset: 0;
display: grid;
place-items: center;
background: #081820;
transition: opacity 400ms ease;
}
#loading.hidden {
opacity: 0;
pointer-events: none;
}
.loader {
text-align: center;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.loader-ring {
width: 38px;
height: 38px;
margin: 0 auto 13px;
border: 2px solid rgba(85, 239, 189, 0.15);
border-top-color: var(--mint);
border-radius: 50%;
animation: spin 900ms linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
@media (max-width: 800px) {
.topbar {
height: 64px;
padding: 0 14px;
}
.brand-subtitle {
display: none;
}
.live-route {
font-size: 10px;
}
.panel {
top: auto;
left: 10px;
right: 10px;
bottom: 10px;
width: auto;
max-height: 51vh;
padding: 16px;
border-radius: 18px;
}
.map-tools {
top: 74px;
right: 12px;
}
.compass {
top: 123px;
right: 13px;
}
.legend,
.camera-hint {
display: none;
}
h1 {
font-size: 23px;
}
}
</style>
</head>
<body>
<div id="app">
<div id="scene" aria-label="Interactive low-poly fictional route map"></div>
<div id="labelLayer"></div>
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<svg width="21" height="21" viewBox="0 0 24 24" fill="none">
<path d="M4 18L9 6L14 14L20 4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<circle cx="4" cy="18" r="2" fill="currentColor"/>
<circle cx="20" cy="4" r="2" fill="currentColor"/>
</svg>
</div>
<div>
<div class="brand-title">Northvale Route Lab</div>
<div class="brand-subtitle">Fictional network · route trade-off study</div>
</div>
</div>
<div class="live-route">
<span class="live-dot"></span>
<span>Current route</span>
<strong id="liveRoute">45.0 km · calculating</strong>
</div>
</header>
<aside class="panel" aria-label="Route preferences">
<div class="eyebrow">Interactive planning study</div>
<h1>What should the road optimize?</h1>
<p class="intro">
Move the priorities and watch the preferred path change across the Northvale network.
</p>
<div class="endpoints">
<span class="endpoint-dot"></span>
<span>West Quay</span>
<span class="endpoint-arrow"></span>
<span>East Dock</span>
<span class="endpoint-dot end"></span>
</div>
<div class="section-title">
Quick priorities
<small>try a clean trade-off</small>
</div>
<div class="presets">
<button class="preset active" data-mode="distance">
<span class="preset-icon">↔</span>
<span class="preset-name">Shortest</span>
</button>
<button class="preset" data-mode="ascent">
<span class="preset-icon">⌁</span>
<span class="preset-name">Lowest climb</span>
</button>
<button class="preset" data-mode="access">
<span class="preset-icon">♿</span>
<span class="preset-name">Step-free</span>
</button>
</div>
<div class="section-title">
Priority mix
<small id="mixTotal">normalized</small>
</div>
<div class="slider-row">
<div class="slider-head">
<label class="slider-label" for="distanceSlider">
<span class="slider-swatch" style="background:var(--blue)"></span>
Distance
</label>
<output class="slider-output" id="distanceOutput">100%</output>
</div>
<input id="distanceSlider" type="range" min="0" max="100" value="100">
</div>
<div class="slider-row">
<div class="slider-head">
<label class="slider-label" for="ascentSlider">
<span class="slider-swatch" style="background:var(--amber)"></span>
Low ascent
</label>
<output class="slider-output" id="ascentOutput">0%</output>
</div>
<input id="ascentSlider" type="range" min="0" max="100" value="0">
</div>
<div class="slider-row">
<div class="slider-head">
<label class="slider-label" for="accessSlider">
<span class="slider-swatch" style="background:var(--violet)"></span>
Accessibility
</label>
<output class="slider-output" id="accessOutput">0%</output>
</div>
<input id="accessSlider" type="range" min="0" max="100" value="0">
</div>
<div class="mix-note" id="mixNote">
A single priority takes full control of the route.
</div>
<div class="section-title">
Selected route
<small id="routeTitle">Distance-first</small>
</div>
<div class="metric-grid">
<div class="metric">
<div class="metric-label">Distance</div>
<div class="metric-value" id="metricDistance">45.0 <small>km</small></div>
</div>
<div class="metric">
<div class="metric-label">Total ascent</div>
<div class="metric-value" id="metricAscent">6.0 <small>m</small></div>
</div>
<div class="metric accent">
<div class="metric-label">Travel time</div>
<div class="metric-value" id="metricTime">1h 18m</div>
</div>
<div class="metric">
<div class="metric-label">Step-free score</div>
<div class="metric-value" id="metricAccess">75<small>%</small></div>
</div>
</div>
<div class="insight">
<div class="insight-kicker">Why this route wins</div>
<div class="insight-title" id="insightTitle">The direct line is only slightly faster</div>
<p class="insight-text" id="insightText"></p>
<div class="route-flow" id="routeFlow"></div>
</div>
<div class="section-title">
Reference trade-offs
<small>click to prioritize</small>
</div>
<div class="ref-list" id="referenceList"></div>
<div class="section-title">
Map layers
</div>
<div class="layer-controls">
<label class="toggle">
<input id="toggleAlternatives" type="checkbox" checked>
Compare routes
</label>
<label class="toggle">
<input id="toggleLabels" type="checkbox" checked>
Place labels
</label>
</div>
<details>
<summary>How the fictional model works</summary>
<p>
Distance is measured along the road graph. Ascent counts only elevation gained.
Accessibility combines pavement quality, maximum gradient, and restricted segments.
Travel time uses road speed, slope penalties, and small delays on restricted roads.
</p>
<p>
All place names, distances, elevations, and road conditions are fictional.
</p>
</details>
</aside>
<div class="map-tools">
<button class="tool-button" id="resetView" title="Reset camera">↺ Reset</button>
<button class="tool-button" id="topView" title="Top-down camera">Top view</button>
</div>
<div class="compass" aria-hidden="true">
<span>N</span>
<div class="compass-needle" id="compassNeedle"></div>
</div>
<div class="legend">
<div class="legend-item"><span class="legend-line"></span> Selected route</div>
<div class="legend-item"><span class="legend-line dashed"></span> Alternatives</div>
<div class="legend-item"><span class="legend-line" style="background:#718582;height:2px"></span> Local road</div>
</div>
<div class="camera-hint">Drag to orbit · Shift-drag to pan · Scroll to zoom · Double-click to reset</div>
<div id="loading">
<div class="loader">
<div class="loader-ring"></div>
Building Northvale
</div>
</div>
</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 clamp = THREE.MathUtils.clamp;
// -------------------------------------------------------------------------
// Fictional graph
// -------------------------------------------------------------------------
const nodes = [
{ id: 0, name: "West Quay", x: -16, z: 5, elev: 0.8 },
{ id: 1, name: "Pine Gate", x: -11, z: -6, elev: 2.0 },
{ id: 2, name: "High Ridge", x: -3, z: -9, elev: 7.0 },
{ id: 3, name: "Beacon", x: 6, z: -11, elev: 8.5 },
{ id: 4, name: "East Dock", x: 17, z: 4, elev: 1.0 },
{ id: 5, name: "Market", x: -1, z: 2, elev: 4.8 },
{ id: 6, name: "Southbank", x: -7, z: 13, elev: 1.1 },
{ id: 7, name: "Old Mill", x: 6, z: 13, elev: 2.0 },
{ id: 8, name: "Lake Bend", x: 9, z: 6, elev: 1.5 },
{ id: 9, name: "North Path", x: -10, z: 1, elev: 1.4 },
{ id: 10, name: "Orchard", x: 2, z: -4, elev: 6.8 },
{ id: 11, name: "Garden Way", x: 5, z: 1, elev: 3.0 }
];
const edges = [];
const graph = nodes.map(() => []);
let edgeId = 0;
function addEdge(a, b, distance, access, name, bend = 0.7) {
const edge = {
id: edgeId++,
a,
b,
distance,
access,
name,
bend,
points: null
};
edges.push(edge);
graph[a].push({ to: b, edge });
graph[b].push({ to: a, edge });
return edge;
}
addEdge(0, 9, 7.5, 0.96, "Harbor Road", 0.35);
addEdge(0, 6, 13.5, 0.98, "Quayway", 0.6);
addEdge(9, 1, 8.5, 0.90, "Pine Link", -0.8);
addEdge(9, 5, 9.5, 0.35, "Ridge Cut", 0.8);
addEdge(1, 2, 8.5, 0.42, "Ridge Steps", -0.5);
addEdge(2, 3, 10.0, 0.72, "Beacon Climb", 0.7);
addEdge(3, 4, 15.5, 0.88, "Beacon Road", -0.4);
addEdge(6, 5, 13.0, 0.97, "Market Approach", 0.5);
addEdge(6, 7, 17.5, 0.84, "Mill Switchback", -1.0);
addEdge(7, 8, 8.0, 0.72, "Old Mill Track", 0.4);
addEdge(8, 4, 8.5, 0.96, "Dock Road", 0.35);
addEdge(5, 10, 7.0, 0.55, "Orchard Steps", -0.6);
addEdge(10, 11, 6.0, 0.84, "Upper Orchard", 0.4);
addEdge(11, 8, 6.5, 0.97, "Garden Way", 0.25);
addEdge(5, 11, 13.5, 0.98, "Step-free Boulevard", -0.55);
addEdge(5, 7, 14.5, 0.88, "Mill Lane", 0.7);
addEdge(10, 2, 9.5, 0.48, "Ridge Shelf", -0.4);
addEdge(2, 11, 10.5, 0.50, "High Cut", 0.8);
addEdge(1, 10, 8.5, 0.40, "Pine Stair", 0.4);
const startId = 0;
const endId = 4;
const referenceModes = {
distance: {
title: "Distance-first",
color: "#69b7ff",
path: [0, 9, 5, 10, 11, 8, 4]
},
ascent: {
title: "Lowest climb",
color: "#ffbd69",
path: [0, 6, 7, 8, 4]
},
access: {
title: "Step-free",
color: "#c59bff",
path: [0, 6, 5, 11, 8, 4]
}
};
function edgeBetween(a, b) {
return edges.find((e) => (e.a === a && e.b === b) || (e.a === b && e.b === a));
}
function pathKey(path) {
return path.join("-");
}
function samePath(a, b) {
return a.length === b.length && a.every((v, i) => v === b[i]);
}
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x081820);
scene.fog = new THREE.Fog(0x081820, 62, 118);
const camera = new THREE.PerspectiveCamera(42, innerWidth / innerHeight, 0.1, 180);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
$("scene").appendChild(renderer.domElement);
const hemi = new THREE.HemisphereLight(0xb9e9ee, 0x18372e, 2.0);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xffe1b0, 3.0);
sun.position.set(-18, 30, 18);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.camera.left = -30;
sun.shadow.camera.right = 30;
sun.shadow.camera.top = 26;
sun.shadow.camera.bottom = -26;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 75;
sun.shadow.bias = -0.0006;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x70b8ff, 1.1);
rim.position.set(22, 10, -20);
scene.add(rim);
// Terrain elevation is interpolated from the fictional junction elevations.
function terrainHeight(x, z) {
let weightSum = 0;
let valueSum = 0;
let nearestDistance = Infinity;
let nearest = nodes[0];
for (const node of nodes) {
const d2 = (x - node.x) ** 2 + (z - node.z) ** 2;
const weight = 1 / (d2 + 1.2);
weightSum += weight;
valueSum += weight * node.elev;
const distance = Math.sqrt(d2);
if (distance < nearestDistance) {
nearestDistance = distance;
nearest = node;
}
}
let height = valueSum / weightSum;
const detailFade = clamp(nearestDistance / 2.8, 0, 1);
height +=
0.19 *
Math.sin(x * 0.44 + z * 0.22) *
Math.sin(z * 0.37 - x * 0.13) *
detailFade;
if (nearestDistance < 0.72) {
const blend = 1 - nearestDistance / 0.72;
height = THREE.MathUtils.lerp(height, nearest.elev, blend);
}
return height;
}
function terrainColor(height, x, z) {
const low = new THREE.Color(0x315b4d);
const mid = new THREE.Color(0x58735a);
const high = new THREE.Color(0x8b8767);
const peak = new THREE.Color(0xa9a080);
let color;
if (height < 2.4) {
color = low.clone().lerp(mid, clamp((height - 0.5) / 2, 0, 1));
} else if (height < 5.3) {
color = mid.clone().lerp(high, clamp((height - 2.4) / 3, 0, 1));
} else {
color = high.clone().lerp(peak, clamp((height - 5.3) / 3, 0, 1));
}
const variation = 0.92 + 0.12 * Math.sin(x * 1.73 + z * 2.19);
color.multiplyScalar(variation);
return color;
}
const water = new THREE.Mesh(
new THREE.PlaneGeometry(180, 180),
new THREE.MeshStandardMaterial({
color: 0x0d3340,
roughness: 0.88,
metalness: 0.04
})
);
water.rotation.x = -Math.PI / 2;
water.position.y = -1.56;
water.receiveShadow = true;
scene.add(water);
const mapBase = new THREE.Mesh(
new THREE.BoxGeometry(48.8, 1.4, 38.8),
new THREE.MeshStandardMaterial({
color: 0x183a35,
roughness: 0.92
})
);
mapBase.position.y = -0.85;
mapBase.castShadow = true;
mapBase.receiveShadow = true;
scene.add(mapBase);
const mapWidth = 48;
const mapDepth = 38;
const gridX = 32;
const gridZ = 25;
const terrainPositions = [];
const terrainColors = [];
function pushTerrainTriangle(a, b, c) {
const avg = (a[1] + b[1] + c[1]) / 3;
const color = terrainColor(avg, (a[0] + b[0] + c[0]) / 3, (a[2] + b[2] + c[2]) / 3);
for (const p of [a, b, c]) {
terrainPositions.push(p[0], p[1], p[2]);
terrainColors.push(color.r, color.g, color.b);
}
}
for (let iz = 0; iz < gridZ; iz++) {
for (let ix = 0; ix < gridX; ix++) {
const x0 = -mapWidth / 2 + (ix / gridX) * mapWidth;
const x1 = -mapWidth / 2 + ((ix + 1) / gridX) * mapWidth;
const z0 = -mapDepth / 2 + (iz / gridZ) * mapDepth;
const z1 = -mapDepth / 2 + ((iz + 1) / gridZ) * mapDepth;
const a = [x0, terrainHeight(x0, z0), z0];
const b = [x1, terrainHeight(x1, z0), z0];
const c = [x1, terrainHeight(x1, z1), z1];
const d = [x0, terrainHeight(x0, z1), z1];
if ((ix + iz) % 2 === 0) {
pushTerrainTriangle(a, b, c);
pushTerrainTriangle(a, c, d);
} else {
pushTerrainTriangle(a, b, d);
pushTerrainTriangle(b, c, d);
}
}
}
const terrainGeometry = new THREE.BufferGeometry();
terrainGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(terrainPositions, 3)
);
terrainGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(terrainColors, 3)
);
terrainGeometry.computeVertexNormals();
const terrain = new THREE.Mesh(
terrainGeometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
flatShading: true,
roughness: 0.96,
metalness: 0.0
})
);
terrain.receiveShadow = true;
scene.add(terrain);
// A dark vertical rim gives the terrain the look of a physical map slab.
const wallPositions = [];
const boundary = [];
for (let ix = 0; ix <= gridX; ix++) {
const x = -mapWidth / 2 + (ix / gridX) * mapWidth;
const z = -mapDepth / 2;
boundary.push([x, terrainHeight(x, z), z]);
}
for (let iz = 1; iz <= gridZ; iz++) {
const z = -mapDepth / 2 + (iz / gridZ) * mapDepth;
const x = mapWidth / 2;
boundary.push([x, terrainHeight(x, z), z]);
}
for (let ix = gridX - 1; ix >= 0; ix--) {
const x = -mapWidth / 2 + (ix / gridX) * mapWidth;
const z = mapDepth / 2;
boundary.push([x, terrainHeight(x, z), z]);
}
for (let iz = gridZ - 1; iz >= 0; iz--) {
const z = -mapDepth / 2 + (iz / gridZ) * mapDepth;
const x = -mapWidth / 2;
boundary.push([x, terrainHeight(x, z), z]);
}
for (let i = 0; i < boundary.length; i++) {
const a = boundary[i];
const b = boundary[(i + 1) % boundary.length];
wallPositions.push(
a[0], a[1], a[2], b[0], b[1], b[2], b[0], -0.15, b[2],
a[0], a[1], a[2], b[0], -0.15, b[2], a[0], -0.15, a[2]
);
}
const wallGeometry = new THREE.BufferGeometry();
wallGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(wallPositions, 3)
);
wallGeometry.computeVertexNormals();
const walls = new THREE.Mesh(
wallGeometry,
new THREE.MeshStandardMaterial({
color: 0x234b42,
roughness: 1,
flatShading: true
})
);
walls.castShadow = true;
walls.receiveShadow = true;
scene.add(walls);
// -------------------------------------------------------------------------
// Roads
// -------------------------------------------------------------------------
function edgePoints(edge, from = edge.a, lift = 0.13) {
const start = nodes[edge.a];
const end = nodes[edge.b];
const dx = end.x - start.x;
const dz = end.z - start.z;
const length = Math.hypot(dx, dz) || 1;
const perpendicularX = -dz / length;
const perpendicularZ = dx / length;
const controlX = (start.x + end.x) / 2 + perpendicularX * edge.bend;
const controlZ = (start.z + end.z) / 2 + perpendicularZ * edge.bend;
const curve = new THREE.QuadraticBezierCurve3(
new THREE.Vector3(start.x, 0, start.z),
new THREE.Vector3(controlX, 0, controlZ),
new THREE.Vector3(end.x, 0, end.z)
);
const points = [];
for (let i = 0; i <= 18; i++) {
const p = curve.getPoint(i / 18);
points.push(
new THREE.Vector3(p.x, terrainHeight(p.x, p.z) + lift, p.z)
);
}
if (from === edge.b) points.reverse();
return points;
}
const roadMaterial = new THREE.MeshStandardMaterial({
color: 0x718582,
roughness: 0.78,
metalness: 0.04
});
for (const edge of edges) {
edge.points = edgePoints(edge);
const curve = new THREE.CatmullRomCurve3(edge.points, false, "centripetal");
const geometry = new THREE.TubeGeometry(
curve,
30,
0.105,
4,
false
);
const road = new THREE.Mesh(geometry, roadMaterial);
road.receiveShadow = true;
scene.add(road);
}
// Junction markers.
const nodeMaterial = new THREE.MeshStandardMaterial({
color: 0xd7e1d7,
roughness: 0.65,
flatShading: true
});
const startMaterial = new THREE.MeshStandardMaterial({
color: 0x55efbd,
emissive: 0x123d31,
roughness: 0.55
});
const endMaterial = new THREE.MeshStandardMaterial({
color: 0xff8b78,
emissive: 0x4a1c18,
roughness: 0.55
});
const markerGeometry = new THREE.CylinderGeometry(0.42, 0.48, 0.28, 8);
const ringGeometry = new THREE.TorusGeometry(0.72, 0.075, 6, 18);
const endpointRings = [];
for (const node of nodes) {
const y = terrainHeight(node.x, node.z);
const marker = new THREE.Mesh(
markerGeometry,
node.id === startId
? startMaterial
: node.id === endId
? endMaterial
: nodeMaterial
);
marker.position.set(node.x, y + 0.19, node.z);
marker.castShadow = true;
scene.add(marker);
if (node.id === startId || node.id === endId) {
const ring = new THREE.Mesh(
ringGeometry,
new THREE.MeshBasicMaterial({
color: node.id === startId ? 0x55efbd : 0xff8b78,
transparent: true,
opacity: 0.72
})
);
ring.rotation.x = Math.PI / 2;
ring.position.set(node.x, y + 0.13, node.z);
scene.add(ring);
endpointRings.push(ring);
}
}
// -------------------------------------------------------------------------
// Low-poly vegetation and rocks
// -------------------------------------------------------------------------
let randomSeed = 71839;
function random() {
randomSeed = (randomSeed * 1664525 + 1013904223) >>> 0;
return randomSeed / 4294967296;
}
function pointSegmentDistance(px, pz, ax, az, bx, bz) {
const vx = bx - ax;
const vz = bz - az;
const wx = px - ax;
const wz = pz - az;
const denom = vx * vx + vz * vz || 1;
const t = clamp((wx * vx + wz * vz) / denom, 0, 1);
const cx = ax + t * vx;
const cz = az + t * vz;
return Math.hypot(px - cx, pz - cz);
}
function clearForDecoration(x, z, roadClearance = 1.35) {
if (nodes.some((n) => Math.hypot(x - n.x, z - n.z) < 2.0)) return false;
for (const edge of edges) {
const a = nodes[edge.a];
const b = nodes[edge.b];
if (pointSegmentDistance(x, z, a.x, a.z, b.x, b.z) < roadClearance) return false;
}
return true;
}
const trunkGeometry = new THREE.CylinderGeometry(0.11, 0.14, 0.7, 5);
const crownGeometry = new THREE.ConeGeometry(0.58, 1.45, 5);
const trunkMaterial = new THREE.MeshStandardMaterial({ color: 0x5b4934, roughness: 1 });
const crownMaterials = [
new THREE.MeshStandardMaterial({ color: 0x214d3b, roughness: 1, flatShading: true }),
new THREE.MeshStandardMaterial({ color: 0x2d6247, roughness: 1, flatShading: true }),
new THREE.MeshStandardMaterial({ color: 0x3b6c4d, roughness: 1, flatShading: true })
];
let treeCount = 0;
for (let attempt = 0; attempt < 500 && treeCount < 46; attempt++) {
const x = (random() - 0.5) * 45;
const z = (random() - 0.5) * 35;
if (!clearForDecoration(x, z)) continue;
const y = terrainHeight(x, z);
const scale = 0.7 + random() * 0.65;
const trunk = new THREE.Mesh(trunkGeometry, trunkMaterial);
trunk.position.set(x, y + 0.35 * scale, z);
trunk.scale.setScalar(scale);
trunk.castShadow = true;
const crown = new THREE.Mesh(
crownGeometry,
crownMaterials[treeCount % crownMaterials.length]
);
crown.position.set(x, y + 1.25 * scale, z);
crown.rotation.y = random() * Math.PI;
crown.scale.setScalar(scale);
crown.castShadow = true;
scene.add(trunk, crown);
treeCount++;
}
const rockGeometry = new THREE.DodecahedronGeometry(0.42, 0);
const rockMaterial = new THREE.MeshStandardMaterial({
color: 0x7c8274,
roughness: 1,
flatShading: true
});
let rockCount = 0;
for (let attempt = 0; attempt < 260 && rockCount < 20; attempt++) {
const x = (random() - 0.5) * 45;
const z = (random() - 0.5) * 35;
if (!clearForDecoration(x, z, 1.1)) continue;
const y = terrainHeight(x, z);
const rock = new THREE.Mesh(rockGeometry, rockMaterial);
const scale = 0.45 + random() * 0.9;
rock.position.set(x, y + 0.18 * scale, z);
rock.scale.set(scale * 1.2, scale * 0.65, scale);
rock.rotation.set(random(), random(), random());
rock.castShadow = true;
scene.add(rock);
rockCount++;
}
// -------------------------------------------------------------------------
// Route calculation
// -------------------------------------------------------------------------
function normalizedWeights() {
const d = Number($("distanceSlider").value);
const a = Number($("ascentSlider").value);
const x = Number($("accessSlider").value);
const total = d + a + x;
if (total === 0) {
return { d: 1, a: 0, x: 0, raw: { d, a, x }, total: 0 };
}
return {
d: d / total,
a: a / total,
x: x / total,
raw: { d, a, x },
total
};
}
function edgeCost(edge, from, weights) {
const to = edge.a === from ? edge.b : edge.a;
const climb = Math.max(0, nodes[to].elev - nodes[from].elev);
const accessPenalty = Math.pow(1 - edge.access, 1.15) * 3;
return (
weights.d * (edge.distance / 50) +
weights.a * (climb / 12) +
weights.x * accessPenalty
);
}
function findRoute(weights) {
const n = nodes.length;
const costs = Array(n).fill(Infinity);
const previousNode = Array(n).fill(-1);
const previousEdge = Array(n).fill(-1);
const visited = Array(n).fill(false);
costs[startId] = 0;
for (let iteration = 0; iteration < n; iteration++) {
let current = -1;
let currentCost = Infinity;
for (let i = 0; i < n; i++) {
if (!visited[i] && costs[i] < currentCost) {
current = i;
currentCost = costs[i];
}
}
if (current === -1 || current === endId) break;
visited[current] = true;
for (const connection of graph[current]) {
const nextCost =
costs[current] + edgeCost(connection.edge, current, weights);
if (nextCost < costs[connection.to]) {
costs[connection.to] = nextCost;
previousNode[connection.to] = current;
previousEdge[connection.to] = connection.edge.id;
}
}
}
const path = [];
let cursor = endId;
while (cursor !== -1) {
path.push(cursor);
if (cursor === startId) break;
cursor = previousNode[cursor];
}
path.reverse();
return path;
}
function calculatePath(path) {
let distance = 0;
let climb = 0;
let accessWeighted = 0;
let minutes = 0;
let restrictedSegments = 0;
for (let i = 0; i < path.length - 1; i++) {
const from = path[i];
const to = path[i + 1];
const edge = edgeBetween(from, to);
const elevationGain = Math.max(0, nodes[to].elev - nodes[from].elev);
const grade = (elevationGain / edge.distance) * 100;
const speed = Math.max(9, 30 + 12 * edge.access - 7 * grade);
distance += edge.distance;
climb += elevationGain;
accessWeighted += edge.access * edge.distance;
minutes += (edge.distance / speed) * 60 + elevationGain * 1.1;
if (edge.access < 0.6) {
minutes += 1.8;
restrictedSegments++;
}
}
return {
distance,
climb,
access: (accessWeighted / distance) * 100,
minutes,
restrictedSegments
};
}
const referenceMetrics = {};
for (const [mode, reference] of Object.entries(referenceModes)) {
referenceMetrics[mode] = calculatePath(reference.path);
}
// -------------------------------------------------------------------------
// Selected route and alternative route visuals
// -------------------------------------------------------------------------
const routeVisualGroup = new THREE.Group();
const alternativeGroup = new THREE.Group();
scene.add(routeVisualGroup, alternativeGroup);
let currentRouteCurve = null;
let currentRouteKey = "";
let routePulse = 0;
function disposeObject(object) {
object.traverse((child) => {
if (child.geometry) child.geometry.dispose();
if (child.material) {
if (Array.isArray(child.material)) {
child.material.forEach((m) => m.dispose());
} else {
child.material.dispose();
}
}
});
}
function routePoints(path, lift = 0.27) {
const points = [];
for (let i = 0; i < path.length - 1; i++) {
const edge = edgeBetween(path[i], path[i + 1]);
const segment = edgePoints(edge, path[i], lift);
points.push(...segment);
}
return points;
}
function rebuildRoute(path) {
routeVisualGroup.traverse((child) => {
if (child.geometry) child.geometry.dispose();
if (child.material) child.material.dispose();
});
routeVisualGroup.clear();
const points = routePoints(path);
currentRouteCurve = new THREE.CatmullRomCurve3(points, false, "centripetal");
const glow = new THREE.Mesh(
new THREE.TubeGeometry(currentRouteCurve, 260, 0.47, 6, false),
new THREE.MeshBasicMaterial({
color: 0x55efbd,
transparent: true,
opacity: 0.13,
depthWrite: false
})
);
glow.renderOrder = 4;
routeVisualGroup.add(glow);
const routeMesh = new THREE.Mesh(
new THREE.TubeGeometry(currentRouteCurve, 260, 0.245, 6, false),
new THREE.MeshStandardMaterial({
color: 0x55efbd,
emissive: 0x0b4a38,
emissiveIntensity: 0.85,
roughness: 0.42,
metalness: 0.08
})
);
routeMesh.castShadow = true;
routeMesh.renderOrder = 5;
routeVisualGroup.add(routeMesh);
for (const nodeId of path) {
const node = nodes[nodeId];
const stop = new THREE.Mesh(
new THREE.CylinderGeometry(0.28, 0.32, 0.16, 8),
new THREE.MeshBasicMaterial({ color: 0xdffff4 })
);
stop.position.set(
node.x,
terrainHeight(node.x, node.z) + 0.34,
node.z
);
routeVisualGroup.add(stop);
}
routePulse = 1;
}
for (const reference of Object.values(referenceModes)) {
const geometry = new THREE.BufferGeometry().setFromPoints(
routePoints(reference.path, 0.22)
);
const line = new THREE.Line(
geometry,
new THREE.LineDashedMaterial({
color: new THREE.Color(reference.color),
dashSize: 0.7,
gapSize: 0.45,
transparent: true,
opacity: 0.48,
depthWrite: false
})
);
line.computeLineDistances();
line.renderOrder = 3;
alternativeGroup.add(line);
}
// A tiny low-poly vehicle makes the active direction easy to read.
const vehicle = new THREE.Group();
const vehicleBody = new THREE.Mesh(
new THREE.BoxGeometry(0.52, 0.22, 0.8),
new THREE.MeshStandardMaterial({
color: 0xf4fff8,
emissive: 0x365c50,
roughness: 0.5
})
);
vehicleBody.position.y = 0.17;
const vehicleCab = new THREE.Mesh(
new THREE.BoxGeometry(0.42, 0.25, 0.38),
new THREE.MeshStandardMaterial({
color: 0xffc36b,
roughness: 0.55,
flatShading: true
})
);
vehicleCab.position.set(0, 0.37, -0.08);
vehicle.add(vehicleBody, vehicleCab);
scene.add(vehicle);
// -------------------------------------------------------------------------
// Map labels
// -------------------------------------------------------------------------
const labelEntries = [];
function addLabel(text, position, className = "") {
const element = document.createElement("div");
element.className = `map-label ${className}`;
element.textContent = text;
$("labelLayer").appendChild(element);
labelEntries.push({ element, position });
}
for (const node of nodes) {
addLabel(
node.name,
new THREE.Vector3(node.x, node.elev + 0.85, node.z),
node.id === startId || node.id === endId ? "endpoint" : ""
);
}
const ridgeEdge = edges.find((edge) => edge.name === "Ridge Cut");
const boulevardEdge = edges.find((edge) => edge.name === "Step-free Boulevard");
const millEdge = edges.find((edge) => edge.name === "Mill Switchback");
function edgeLabelPosition(edge) {
const points = edgePoints(edge, edge.a, 1.0);
return points[Math.floor(points.length / 2)].clone();
}
const ridgeGrade =
(Math.abs(nodes[ridgeEdge.b].elev - nodes[ridgeEdge.a].elev) /
ridgeEdge.distance) *
100;
addLabel(
`Ridge Cut · ${Math.round(ridgeGrade)}% grade · unpaved`,
edgeLabelPosition(ridgeEdge),
"callout warning"
);
addLabel(
"Step-free boulevard",
edgeLabelPosition(boulevardEdge),
"callout smooth"
);
addLabel(
"Long, low-grade switchback",
edgeLabelPosition(millEdge),
"callout"
);
function updateLabels() {
const width = innerWidth;
const height = innerHeight;
for (const entry of labelEntries) {
const projected = entry.position.clone().project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
projected.x > -1.15 &&
projected.x < 1.15 &&
projected.y > -1.15 &&
projected.y < 1.15;
entry.element.style.display = visible ? "block" : "none";
if (!visible) continue;
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
entry.element.style.left = `${x}px`;
entry.element.style.top = `${y}px`;
}
}
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
function formatTime(minutes) {
const rounded = Math.max(1, Math.round(minutes));
const hours = Math.floor(rounded / 60);
const mins = rounded % 60;
return hours ? `${hours}h ${String(mins).padStart(2, "0")}m` : `${mins}m`;
}
function signed(value, digits = 1) {
const rounded = Number(value).toFixed(digits);
return Number(rounded) > 0 ? `+${rounded}` : rounded;
}
function buildReferenceCards() {
const list = $("referenceList");
list.innerHTML = "";
for (const [mode, reference] of Object.entries(referenceModes)) {
const metrics = referenceMetrics[mode];
const button = document.createElement("button");
button.className = "ref-card";
button.dataset.mode = mode;
button.innerHTML = `
<div class="ref-head">
<span class="ref-swatch" style="color:${reference.color};background:${reference.color}"></span>
<span class="ref-name">${reference.title}</span>
<span class="ref-distance">${metrics.distance.toFixed(1)} km</span>
</div>
<div class="ref-stats">
<span><b>${metrics.climb.toFixed(1)} m</b>ascent</span>
<span><b>${formatTime(metrics.minutes)}</b>travel</span>
<span><b>${Math.round(metrics.access)}%</b>step-free</span>
</div>
`;
button.addEventListener("click", () => applyPreset(mode));
list.appendChild(button);
}
}
function applyPreset(mode) {
if (mode === "distance") {
$("distanceSlider").value = 100;
$("ascentSlider").value = 0;
$("accessSlider").value = 0;
} else if (mode === "ascent") {
$("distanceSlider").value = 0;
$("ascentSlider").value = 100;
$("accessSlider").value = 0;
} else {
$("distanceSlider").value = 0;
$("ascentSlider").value = 0;
$("accessSlider").value = 100;
}
updateRoute();
}
function updatePresetState(weights) {
const values = [weights.raw.d, weights.raw.a, weights.raw.x];
const total = values.reduce((a, b) => a + b, 0);
const pure = total > 0 && values.some((v) => v === 100);
document.querySelectorAll(".preset").forEach((button) => {
const mode = button.dataset.mode;
const index = mode === "distance" ? 0 : mode === "ascent" ? 1 : 2;
button.classList.toggle("active", pure && values[index] === 100);
});
}
function routeTitle(path, weights) {
for (const [mode, reference] of Object.entries(referenceModes)) {
if (samePath(path, reference.path)) return reference.title;
}
if (weights.total === 0) return "Distance-first";
if (weights.raw.d >= 75) return "Mostly distance";
if (weights.raw.a >= 75) return "Mostly low climb";
if (weights.raw.x >= 75) return "Mostly step-free";
return "Mixed-criteria route";
}
function updateNarrative(path, metrics, weights) {
const distance = referenceMetrics.distance;
const ascent = referenceMetrics.ascent;
const access = referenceMetrics.access;
if (samePath(path, referenceModes.distance.path)) {
const extraKm = ascent.distance - distance.distance;
const extraClimb = distance.climb - ascent.climb;
const timeDifference = Math.abs(distance.minutes - ascent.minutes);
$("insightTitle").textContent = "Short distance hides the steepest section";
$("insightText").textContent =
`The direct route is ${extraKm.toFixed(1)} km shorter than the low-climb road, ` +
`but adds ${extraClimb.toFixed(1)} m of ascent. The Ridge Cut is steep and unpaved; ` +
`the two routes differ by only about ${Math.round(timeDifference)} minutes of travel.`;
} else if (samePath(path, referenceModes.ascent.path)) {
const extraKm = ascent.distance - distance.distance;
const savedClimb = distance.climb - ascent.climb;
$("insightTitle").textContent = "A little longer, much easier to drive";
$("insightText").textContent =
`The switchback saves ${savedClimb.toFixed(1)} m of climbing for ` +
`${extraKm.toFixed(1)} km more distance. It avoids the Ridge Cut and keeps ` +
`${Math.round(ascent.access)}% of the route step-free, though the full ` +
`step-free alternative remains the smoothest choice.`;
} else if (samePath(path, referenceModes.access.path)) {
const extraKm = access.distance - distance.distance;
const extraTime = access.minutes - distance.minutes;
$("insightTitle").textContent = "Accessibility buys a quieter, gentler road";
$("insightText").textContent =
`This route adds ${extraKm.toFixed(1)} km and about ${Math.round(extraTime)} ` +
`minutes versus the shortest line. In return it avoids restricted, unpaved ` +
`segments and reaches ${Math.round(access.access)}% step-free quality.`;
} else {
const kmDelta = metrics.distance - distance.distance;
const climbDelta = metrics.climb - distance.climb;
const accessDelta = metrics.access - distance.access;
$("insightTitle").textContent = "Your mix selects a different compromise";
$("insightText").textContent =
`Compared with the distance-first route, this line changes distance by ` +
`${signed(kmDelta)} km, ascent by ${signed(climbDelta)} m, and step-free score by ` +
`${signed(accessDelta, 0)} points. The colored reference lines reveal each possible trade-off.`;
}
}
function updateRoute() {
const weights = normalizedWeights();
const path = findRoute(weights);
const metrics = calculatePath(path);
if (pathKey(path) !== currentRouteKey) {
currentRouteKey = pathKey(path);
rebuildRoute(path);
}
$("distanceOutput").textContent = `${Math.round(weights.d * 100)}%`;
$("ascentOutput").textContent = `${Math.round(weights.a * 100)}%`;
$("accessOutput").textContent = `${Math.round(weights.x * 100)}%`;
$("mixTotal").textContent =
weights.total === 0 ? "choose one or more" : "normalized to 100%";
$("mixNote").textContent =
weights.total === 0
? "All priorities are off, so distance is used as the fallback."
: weights.raw.d === 100 || weights.raw.a === 100 || weights.raw.x === 100
? "One priority has full control of the route."
: "Weights are blended, so the path can change gradually.";
$("metricDistance").innerHTML = `${metrics.distance.toFixed(1)} <small>km</small>`;
$("metricAscent").innerHTML = `${metrics.climb.toFixed(1)} <small>m</small>`;
$("metricTime").textContent = formatTime(metrics.minutes);
$("metricAccess").innerHTML = `${Math.round(metrics.access)}<small>%</small>`;
$("routeTitle").textContent = routeTitle(path, weights);
$("liveRoute").textContent =
`${metrics.distance.toFixed(1)} km · ${formatTime(metrics.minutes)}`;
$("routeFlow").innerHTML = path
.map((nodeId, index) => {
const stop = `<span class="route-stop">${nodes[nodeId].name}</span>`;
return index === path.length - 1 ? stop : `${stop}<span class="route-arrow">›</span>`;
})
.join("");
updateNarrative(path, metrics, weights);
updatePresetState(weights);
document.querySelectorAll(".ref-card").forEach((card) => {
const mode = card.dataset.mode;
card.classList.toggle(
"active",
samePath(path, referenceModes[mode].path)
);
});
}
document.querySelectorAll(".preset").forEach((button) => {
button.addEventListener("click", () => applyPreset(button.dataset.mode));
});
["distanceSlider", "ascentSlider", "accessSlider"].forEach((id) => {
$(id).addEventListener("input", updateRoute);
});
$("toggleAlternatives").addEventListener("change", (event) => {
alternativeGroup.visible = event.target.checked;
});
$("toggleLabels").addEventListener("change", (event) => {
$("labelLayer").style.display = event.target.checked ? "block" : "none";
});
buildReferenceCards();
updateRoute();
// -------------------------------------------------------------------------
// Camera controls implemented directly, without Three.js add-ons
// -------------------------------------------------------------------------
const cameraGoal = {
target: new THREE.Vector3(1.5, 2.2, 0),
radius: 58,
theta: 0.56,
phi: 0.88
};
const cameraCurrent = {
target: cameraGoal.target.clone(),
radius: cameraGoal.radius,
theta: cameraGoal.theta,
phi: cameraGoal.phi
};
function updateCamera() {
const sinPhi = Math.sin(cameraCurrent.phi);
camera.position.set(
cameraCurrent.target.x +
cameraCurrent.radius * sinPhi * Math.sin(cameraCurrent.theta),
cameraCurrent.target.y + cameraCurrent.radius * Math.cos(cameraCurrent.phi),
cameraCurrent.target.z +
cameraCurrent.radius * sinPhi * Math.cos(cameraCurrent.theta)
);
camera.lookAt(cameraCurrent.target);
}
function resetCamera() {
cameraGoal.target.set(1.5, 2.2, 0);
cameraGoal.radius = 58;
cameraGoal.theta = 0.56;
cameraGoal.phi = 0.88;
}
$("resetView").addEventListener("click", resetCamera);
$("topView").addEventListener("click", () => {
cameraGoal.target.set(1.5, 1.5, 0);
cameraGoal.radius = 54;
cameraGoal.theta = 0.0;
cameraGoal.phi = 0.04;
});
const canvas = renderer.domElement;
const pointers = new Map();
let dragMode = "orbit";
let pinchDistance = 0;
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
dragMode = event.shiftKey || event.button === 2 ? "pan" : "orbit";
if (pointers.size === 2) {
const values = [...pointers.values()];
pinchDistance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
});
canvas.addEventListener("pointermove", (event) => {
if (!pointers.has(event.pointerId)) return;
const previous = pointers.get(event.pointerId);
const dx = event.clientX - previous.x;
const dy = event.clientY - previous.y;
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 2) {
const values = [...pointers.values()];
const distance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
if (pinchDistance > 0 && distance > 0) {
cameraGoal.radius = clamp(
cameraGoal.radius * (pinchDistance / distance),
22,
88
);
}
pinchDistance = distance;
return;
}
if (dragMode === "orbit") {
cameraGoal.theta -= dx * 0.006;
cameraGoal.phi = clamp(cameraGoal.phi - dy * 0.005, 0.035, 1.42);
} else {
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0);
right.y = 0;
right.normalize();
const forward = camera.getWorldDirection(new THREE.Vector3());
forward.y = 0;
forward.normalize();
const panScale = cameraGoal.radius * 0.00145;
cameraGoal.target.addScaledVector(right, -dx * panScale);
cameraGoal.target.addScaledVector(forward, dy * panScale);
cameraGoal.target.x = clamp(cameraGoal.target.x, -22, 22);
cameraGoal.target.z = clamp(cameraGoal.target.z, -18, 18);
}
});
function endPointer(event) {
pointers.delete(event.pointerId);
if (pointers.size < 2) pinchDistance = 0;
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener("lostpointercapture", endPointer);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraGoal.radius = clamp(
cameraGoal.radius * Math.exp(event.deltaY * 0.001),
22,
88
);
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetCamera);
// -------------------------------------------------------------------------
// Animation and resize
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
const delta = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
const smoothing = 1 - Math.pow(0.0008, delta);
cameraCurrent.target.lerp(cameraGoal.target, smoothing);
cameraCurrent.radius = THREE.MathUtils.lerp(
cameraCurrent.radius,
cameraGoal.radius,
smoothing
);
cameraCurrent.theta = THREE.MathUtils.lerp(
cameraCurrent.theta,
cameraGoal.theta,
smoothing
);
cameraCurrent.phi = THREE.MathUtils.lerp(
cameraCurrent.phi,
cameraGoal.phi,
smoothing
);
updateCamera();
updateLabels();
$("compassNeedle").style.transform =
`rotate(${-cameraCurrent.theta * 180 / Math.PI}deg)`;
if (currentRouteCurve) {
const t = (elapsed * 0.035) % 1;
const point = currentRouteCurve.getPointAt(t);
const tangent = currentRouteCurve.getTangentAt(t);
vehicle.position.copy(point);
vehicle.position.y += 0.28;
vehicle.lookAt(point.clone().add(tangent));
}
routePulse *= 0.94;
const glow = routeVisualGroup.children[0];
if (glow) {
glow.material.opacity = 0.12 + routePulse * 0.22;
}
for (let i = 0; i < endpointRings.length; i++) {
const pulse = 1 + Math.sin(elapsed * 2.2 + i * Math.PI) * 0.08;
endpointRings[i].scale.setScalar(pulse);
}
renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
requestAnimationFrame(() => {
$("loading").classList.add("hidden");
setTimeout(() => $("loading").remove(), 450);
});
</script>
</body>
</html>
```