Prompt specification
Build or customize the Three.js 3D scene "Saddle pass between two summits" 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: Saddle pass between two summits
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/saddle-pass-between-two-summits-x1295
Scene Description Prompt:
I'd like to see this as a low-poly Three.js scene: saddle pass between two summits. Create two hills joined by a saddle and overlay elevation contours. Highlight the lowest crossing route between valleys without routing the path over either summit. Use cdnjs and return one self-contained HTML file.
Verify the behavior against the actual geometry and data in each relevant state. Use schematic labels for deliberately synthetic elements.
Technical checks: Compute the route using the actual displayed height field. Compare routes with the same endpoints and saddle by their highest sampled elevation, and keep the chosen low pass clear of both summits.
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 (saddle-pass-between-two-summits-x1295):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Saddle Pass — Low-Poly Terrain</title>
<style>
:root {
--ink: #173a36;
--muted: #52706b;
--paper: #f4f0e4;
--line: rgba(23, 58, 54, 0.18);
--orange: #f45b38;
--gold: #ffd166;
--pass: #16735f;
--fail: #b6382b;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #d8d5c8;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
canvas {
position: fixed;
inset: 0;
display: block;
touch-action: none;
}
#labels {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 3;
}
.map-label {
position: absolute;
min-width: max-content;
transform: translate(-50%, -100%);
padding: 7px 10px 8px;
border: 1px solid rgba(23, 58, 54, 0.22);
border-radius: 5px;
background: rgba(247, 243, 231, 0.92);
box-shadow: 0 4px 18px rgba(23, 58, 54, 0.12);
color: var(--ink);
font-size: 11px;
line-height: 1.25;
letter-spacing: 0.02em;
white-space: nowrap;
transition: opacity 120ms ease;
}
.map-label::after {
content: "";
position: absolute;
left: 50%;
top: 100%;
width: 1px;
height: 12px;
background: rgba(23, 58, 54, 0.48);
}
.map-label strong {
display: block;
font-size: 12px;
font-weight: 760;
}
.map-label small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 10px;
}
.map-label.route-label {
border-color: rgba(244, 91, 56, 0.52);
background: rgba(255, 244, 225, 0.95);
}
.map-label.route-label strong { color: #a92e1e; }
.map-label.saddle-label {
border-color: rgba(217, 117, 40, 0.56);
background: rgba(255, 238, 201, 0.96);
}
.panel {
position: fixed;
z-index: 5;
border: 1px solid rgba(23, 58, 54, 0.17);
border-radius: 8px;
background: rgba(247, 243, 231, 0.94);
box-shadow: 0 12px 40px rgba(23, 58, 54, 0.16);
backdrop-filter: blur(9px);
}
#info {
top: 18px;
left: 18px;
width: 310px;
padding: 15px;
}
.eyebrow {
margin: 0 0 4px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 20px;
line-height: 1.05;
letter-spacing: -0.035em;
}
.subtitle {
margin: 6px 0 12px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.status {
display: flex;
align-items: flex-start;
gap: 8px;
margin: 0 0 12px;
padding: 9px 10px;
border-radius: 5px;
background: rgba(22, 115, 95, 0.09);
color: var(--pass);
font-size: 11px;
font-weight: 760;
line-height: 1.4;
}
.status::before {
content: "";
flex: 0 0 auto;
width: 8px;
height: 8px;
margin-top: 3px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 0 3px rgba(22, 115, 95, 0.12);
}
.metrics {
display: grid;
grid-template-columns: 1fr auto;
gap: 7px 12px;
padding: 10px 0 11px;
border-top: 1px solid var(--line);
border-bottom: 1px solid var(--line);
font-size: 11px;
}
.metrics span:nth-child(odd) { color: var(--muted); }
.metrics span:nth-child(even) {
font-variant-numeric: tabular-nums;
font-weight: 760;
text-align: right;
}
.metric-good { color: var(--pass); }
.metric-warn { color: #b05a20; }
.toolbar {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-top: 12px;
}
button {
appearance: none;
border: 1px solid rgba(23, 58, 54, 0.24);
border-radius: 4px;
padding: 7px 9px;
background: rgba(255, 255, 255, 0.46);
color: var(--ink);
cursor: pointer;
font: inherit;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.015em;
transition: background 120ms ease, border-color 120ms ease, transform 120ms ease;
}
button:hover {
border-color: rgba(23, 58, 54, 0.5);
background: rgba(255, 255, 255, 0.84);
transform: translateY(-1px);
}
button:focus-visible {
outline: 2px solid var(--orange);
outline-offset: 2px;
}
button[aria-pressed="true"] {
border-color: rgba(244, 91, 56, 0.55);
background: rgba(244, 91, 56, 0.1);
color: #a92e1e;
}
#verifyButton {
border-color: rgba(22, 115, 95, 0.45);
background: rgba(22, 115, 95, 0.1);
color: var(--pass);
}
.layer-note {
margin: 9px 1px 0;
color: var(--muted);
font-size: 9px;
line-height: 1.4;
}
#profilePanel {
display: none;
right: 18px;
top: 18px;
width: 350px;
padding: 13px;
}
#profilePanel.open { display: block; }
.profile-heading {
display: flex;
justify-content: space-between;
gap: 10px;
margin-bottom: 7px;
}
.profile-heading strong {
font-size: 12px;
}
.profile-heading span {
color: var(--muted);
font-size: 9px;
}
#profile {
display: block;
width: 100%;
height: auto;
overflow: visible;
border: 1px solid var(--line);
border-radius: 5px;
background: rgba(255, 255, 255, 0.45);
}
.profile-caption {
margin: 8px 0 0;
color: var(--muted);
font-size: 9px;
line-height: 1.45;
}
#legend {
right: 18px;
bottom: 18px;
width: 245px;
padding: 12px 13px;
}
.legend-row {
display: flex;
align-items: center;
gap: 8px;
margin-top: 8px;
color: var(--muted);
font-size: 10px;
}
.swatch {
width: 25px;
height: 0;
border-top: 3px solid var(--orange);
border-radius: 3px;
}
.swatch.contour {
border-top-width: 2px;
border-color: #315e56;
}
.swatch.major {
border-top-width: 3px;
border-color: #173a36;
}
.swatch.rejected {
border-top: 2px dashed #a54a38;
}
.terrain-chip {
width: 25px;
height: 9px;
border-radius: 2px;
background: linear-gradient(90deg, #3c675d, #92966e, #c5b087);
}
#help {
position: fixed;
z-index: 4;
left: 18px;
bottom: 18px;
padding: 7px 9px;
border-radius: 4px;
background: rgba(247, 243, 231, 0.75);
color: var(--muted);
font-size: 9px;
pointer-events: none;
}
@media (max-width: 760px) {
#info {
top: 10px;
left: 10px;
width: min(292px, calc(100vw - 20px));
padding: 12px;
}
h1 { font-size: 17px; }
.subtitle { margin-bottom: 9px; }
#profilePanel {
top: auto;
right: 10px;
bottom: 43px;
width: min(330px, calc(100vw - 20px));
}
#legend { display: none; }
#help { left: 10px; bottom: 10px; }
.map-label { padding: 5px 7px; }
.map-label strong { font-size: 10px; }
.map-label small { font-size: 8px; }
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive low-poly terrain showing two summits, a saddle, elevation contours, and a verified lowest crossing route"></canvas>
<div id="labels" aria-hidden="true">
<div class="map-label" id="labelSummitA"><strong>Summit A</strong><small>Schematic high point</small></div>
<div class="map-label" id="labelSummitB"><strong>Summit B</strong><small>Schematic high point</small></div>
<div class="map-label saddle-label" id="labelSaddle"><strong>Saddle</strong><small>15.4 m pass</small></div>
<div class="map-label" id="labelWest"><strong>West valley</strong><small>Route origin</small></div>
<div class="map-label" id="labelEast"><strong>East valley</strong><small>Route destination</small></div>
<div class="map-label route-label" id="labelRoute"><strong>Lowest crossing route</strong><small>Rendered-mesh maximum</small></div>
</div>
<aside class="panel" id="info">
<p class="eyebrow">Procedural terrain · schematic labels</p>
<h1>Saddle Pass</h1>
<p class="subtitle">Two faceted summits joined by a 15.4 m col. The orange route uses the rendered mesh and avoids both summit cores.</p>
<div class="status" id="statusText">Checking geometry…</div>
<div class="metrics">
<span>Saddle node</span><span id="metricSaddle">—</span>
<span>Route maximum</span><span id="metricRouteMax" class="metric-good">—</span>
<span>Nearest summit</span><span id="metricClearance" class="metric-good">—</span>
<span>Route length</span><span id="metricLength">—</span>
<span>Direct valley line</span><span id="metricDirect" class="metric-warn">—</span>
<span>Terrain mesh</span><span id="metricMesh">—</span>
</div>
<div class="toolbar">
<button id="overviewButton" type="button">Overview</button>
<button id="planButton" type="button">Plan</button>
<button id="contourButton" type="button" aria-pressed="true">Contours</button>
<button id="routeButton" type="button" aria-pressed="true">Route</button>
<button id="verifyButton" type="button">Verify geometry</button>
</div>
<p class="layer-note" id="layerNote">Visible: terrain, 5 m contours, selected route. Metrics are sampled from the rendered triangles, not duplicated label data.</p>
</aside>
<aside class="panel" id="profilePanel">
<div class="profile-heading">
<strong>Rendered-mesh route profile</strong>
<span id="profileLength">—</span>
</div>
<svg id="profile" viewBox="0 0 320 132" role="img" aria-label="Elevation profile of the selected route"></svg>
<p class="profile-caption" id="profileCaption"></p>
</aside>
<aside class="panel" id="legend">
<div class="eyebrow">Map layers</div>
<div class="legend-row"><span class="swatch"></span>Selected lowest crossing</div>
<div class="legend-row"><span class="swatch contour"></span>5 m contour</div>
<div class="legend-row"><span class="swatch major"></span>10 m major contour</div>
<div class="legend-row"><span class="swatch rejected"></span>Rejected direct summit line</div>
<div class="legend-row"><span class="terrain-chip"></span>Faceted synthetic elevation</div>
</aside>
<div id="help">Drag: orbit · Shift/right-drag: pan · Wheel: zoom · Double-click: reset</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xd8d5c8);
scene.fog = new THREE.Fog(0xd8d5c8, 120, 260);
const camera = new THREE.OrthographicCamera(-50, 50, 29, -29, 0.1, 400);
const cameraState = {
yaw: 0.72,
pitch: 0.62,
zoom: 0.94,
target: new THREE.Vector3(0, 8, 0)
};
const hemi = new THREE.HemisphereLight(0xf7f0d8, 0x38594f, 2.15);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xffe6b8, 3.1);
sun.position.set(-38, 68, 42);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -65;
sun.shadow.camera.right = 65;
sun.shadow.camera.top = 55;
sun.shadow.camera.bottom = -55;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 170;
sun.shadow.bias = -0.00035;
scene.add(sun);
const rim = new THREE.DirectionalLight(0xa9d8cf, 1.15);
rim.position.set(45, 25, -45);
scene.add(rim);
const NX = 85;
const NZ = 57;
const XMIN = -42;
const ZMIN = -28;
const DX = 1;
const DZ = 1;
const SADDLE_HEIGHT = 15.4;
const ROUTE_LIMIT = 15.5;
const SUMMIT_EXCLUSION_RADIUS = 4.0;
const vertexCount = NX * NZ;
const gridHeights = new Float32Array(vertexCount);
const indexOf = (i, j) => j * NX + i;
const gridX = i => XMIN + i * DX;
const gridZ = j => ZMIN + j * DZ;
function rawElevation(x, z) {
const valleyBase = 2.4 + 0.7 * (1 - Math.abs(x) / 42);
const sx2 = 2 * 6.48 * 6.48;
const sz2 = 2 * 8.0 * 8.0;
const westHill = 32.0 * Math.exp(-(
((x + 12) * (x + 12)) / sx2 +
(z * z) / sz2
));
const eastHill = 36.5 * Math.exp(-(
((x - 12) * (x - 12)) / sx2 +
(z * z) / sz2
));
return valleyBase + westHill + eastHill;
}
const verticalOffset = SADDLE_HEIGHT - rawElevation(0, 0);
for (let j = 0; j < NZ; j++) {
for (let i = 0; i < NX; i++) {
gridHeights[indexOf(i, j)] = rawElevation(gridX(i), gridZ(j)) + verticalOffset;
}
}
const saddleI = Math.round((0 - XMIN) / DX);
const saddleJ = Math.round((0 - ZMIN) / DZ);
const saddleIndex = indexOf(saddleI, saddleJ);
const saddleHeight = gridHeights[saddleIndex];
const summitAIndex = indexOf(Math.round((-12 - XMIN) / DX), saddleJ);
const summitBIndex = indexOf(Math.round((12 - XMIN) / DX), saddleJ);
const summitA = {
x: gridX(Math.round((-12 - XMIN) / DX)),
z: gridZ(saddleJ),
y: gridHeights[summitAIndex]
};
const summitB = {
x: gridX(Math.round((12 - XMIN) / DX)),
z: gridZ(saddleJ),
y: gridHeights[summitBIndex]
};
function terrainColor(elevation, faceIndex) {
const stops = [
[2, new THREE.Color(0x315e57)],
[10, new THREE.Color(0x66816d)],
[20, new THREE.Color(0x94956e)],
[30, new THREE.Color(0xb29a6d)],
[41, new THREE.Color(0xcbb994)]
];
const color = new THREE.Color();
for (let k = 0; k < stops.length - 1; k++) {
const a = stops[k];
const b = stops[k + 1];
if (elevation <= b[0]) {
const t = THREE.MathUtils.clamp((elevation - a[0]) / (b[0] - a[0]), 0, 1);
color.copy(a[1]).lerp(b[1], t);
break;
}
}
const variation = (((faceIndex * 16807) % 101) / 101 - 0.5) * 0.065;
color.offsetHSL(variation * 0.35, variation * 0.3, variation);
return color;
}
const terrainPositions = [];
const terrainColors = [];
const triangles = [];
function pushTriangle(a, b, c, faceIndex) {
const elevation = (gridHeights[a] + gridHeights[b] + gridHeights[c]) / 3;
const color = terrainColor(elevation, faceIndex);
for (const vertex of [a, b, c]) {
const i = vertex % NX;
const j = Math.floor(vertex / NX);
terrainPositions.push(gridX(i), gridHeights[vertex], gridZ(j));
terrainColors.push(color.r, color.g, color.b);
}
triangles.push([a, b, c]);
}
let faceIndex = 0;
for (let j = 0; j < NZ - 1; j++) {
for (let i = 0; i < NX - 1; i++) {
const a = indexOf(i, j);
const b = indexOf(i + 1, j);
const c = indexOf(i + 1, j + 1);
const d = indexOf(i, j + 1);
pushTriangle(a, b, c, faceIndex++);
pushTriangle(a, c, d, faceIndex++);
}
}
const terrainGeometry = new THREE.BufferGeometry();
terrainGeometry.setAttribute("position", new THREE.Float32BufferAttribute(terrainPositions, 3));
terrainGeometry.setAttribute("color", new THREE.Float32BufferAttribute(terrainColors, 3));
terrainGeometry.computeVertexNormals();
const terrainMaterial = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.96,
metalness: 0,
flatShading: true,
side: THREE.DoubleSide
});
const terrain = new THREE.Mesh(terrainGeometry, terrainMaterial);
terrain.castShadow = true;
terrain.receiveShadow = true;
scene.add(terrain);
const boundary = [];
for (let i = 0; i < NX; i++) boundary.push(indexOf(i, 0));
for (let j = 1; j < NZ; j++) boundary.push(indexOf(NX - 1, j));
for (let i = NX - 2; i >= 0; i--) boundary.push(indexOf(i, NZ - 1));
for (let j = NZ - 2; j > 0; j--) boundary.push(indexOf(0, j));
const skirtPositions = [];
const skirtColors = [];
const skirtColor = new THREE.Color(0x294d47);
for (let k = 0; k < boundary.length; k++) {
const p = boundary[k];
const q = boundary[(k + 1) % boundary.length];
const pi = p % NX;
const pj = Math.floor(p / NX);
const qi = q % NX;
const qj = Math.floor(q / NX);
const px = gridX(pi), pz = gridZ(pj);
const qx = gridX(qi), qz = gridZ(qj);
const py = gridHeights[p], qy = gridHeights[q];
const bottom = -1.4;
skirtPositions.push(
px, py, pz, qx, qy, qz, px, bottom, pz,
qx, qy, qz, qx, bottom, qz, px, bottom, pz
);
for (let n = 0; n < 6; n++) skirtColors.push(skirtColor.r, skirtColor.g, skirtColor.b);
}
const skirtGeometry = new THREE.BufferGeometry();
skirtGeometry.setAttribute("position", new THREE.Float32BufferAttribute(skirtPositions, 3));
skirtGeometry.setAttribute("color", new THREE.Float32BufferAttribute(skirtColors, 3));
skirtGeometry.computeVertexNormals();
const skirt = new THREE.Mesh(
skirtGeometry,
new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 1, flatShading: true })
);
skirt.castShadow = true;
skirt.receiveShadow = true;
scene.add(skirt);
const plinth = new THREE.Mesh(
new THREE.BoxGeometry(84.6, 1.1, 56.6),
new THREE.MeshStandardMaterial({ color: 0x24443f, roughness: 0.92 })
);
plinth.position.y = -1.95;
plinth.castShadow = true;
plinth.receiveShadow = true;
scene.add(plinth);
function contourIntersections(triangle, level) {
const points = [];
const vertices = triangle.map(index => {
const i = index % NX;
const j = Math.floor(index / NX);
return { x: gridX(i), y: gridHeights[index], z: gridZ(j) };
});
for (let e = 0; e < 3; e++) {
const p = vertices[e];
const q = vertices[(e + 1) % 3];
const crosses =
(p.y <= level && q.y > level) ||
(q.y <= level && p.y > level);
if (!crosses) continue;
const denominator = q.y - p.y;
const t = Math.abs(denominator) < 1e-9 ? 0.5 : (level - p.y) / denominator;
points.push({
x: p.x + (q.x - p.x) * t,
z: p.z + (q.z - p.z) * t
});
}
return points;
}
const contourGroups = { minor: [], major: [] };
for (let level = 5; level <= 40; level += 5) {
const group = level % 10 === 0 ? contourGroups.major : contourGroups.minor;
for (const triangle of triangles) {
const hits = contourIntersections(triangle, level);
for (let k = 0; k + 1 < hits.length; k += 2) {
group.push(
hits[k].x, level + 0.14, hits[k].z,
hits[k + 1].x, level + 0.14, hits[k + 1].z
);
}
}
}
const minorContours = new THREE.LineSegments(
new THREE.BufferGeometry().setAttribute(
"position", new THREE.Float32BufferAttribute(contourGroups.minor, 3)
),
new THREE.LineBasicMaterial({
color: 0x315e56,
transparent: true,
opacity: 0.46,
depthWrite: false
})
);
minorContours.renderOrder = 2;
scene.add(minorContours);
const majorContours = new THREE.LineSegments(
new THREE.BufferGeometry().setAttribute(
"position", new THREE.Float32BufferAttribute(contourGroups.major, 3)
),
new THREE.LineBasicMaterial({
color: 0x173a36,
transparent: true,
opacity: 0.78,
depthWrite: false
})
);
majorContours.renderOrder = 3;
scene.add(majorContours);
function surfaceHeightAt(x, z) {
const fi = THREE.MathUtils.clamp((x - XMIN) / DX, 0, NX - 1.000001);
const fj = THREE.MathUtils.clamp((z - ZMIN) / DZ, 0, NZ - 1.000001);
const i = Math.floor(fi);
const j = Math.floor(fj);
const tx = fi - i;
const tz = fj - j;
const a = indexOf(i, j);
const b = indexOf(i + 1, j);
const c = indexOf(i + 1, j + 1);
const d = indexOf(i, j + 1);
if (tz <= tx) {
const wa = 1 - tx;
const wb = tx - tz;
const wc = tz;
return wa * gridHeights[a] + wb * gridHeights[b] + wc * gridHeights[c];
}
const wa = 1 - tz;
const wc = tx;
const wd = tz - tx;
return wa * gridHeights[a] + wc * gridHeights[c] + wd * gridHeights[d];
}
class MinHeap {
constructor() { this.items = []; }
push(item) {
this.items.push(item);
let i = this.items.length - 1;
while (i > 0) {
const parent = (i - 1) >> 1;
if (this.items[parent].cost <= item.cost) break;
this.items[i] = this.items[parent];
i = parent;
}
this.items[i] = item;
}
pop() {
if (!this.items.length) return null;
const root = this.items[0];
const last = this.items.pop();
if (this.items.length) {
let i = 0;
while (true) {
let child = i * 2 + 1;
if (child >= this.items.length) break;
if (child + 1 < this.items.length &&
this.items[child + 1].cost < this.items[child].cost) child++;
if (this.items[child].cost >= last.cost) break;
this.items[i] = this.items[child];
i = child;
}
this.items[i] = last;
}
return root;
}
get length() { return this.items.length; }
}
function segmentMaximum(a, b) {
let maximum = Math.max(gridHeights[a], gridHeights[b]);
const ai = a % NX, aj = Math.floor(a / NX);
const bi = b % NX, bj = Math.floor(b / NX);
for (let step = 1; step < 8; step++) {
const t = step / 8;
const x = THREE.MathUtils.lerp(gridX(ai), gridX(bi), t);
const z = THREE.MathUtils.lerp(gridZ(aj), gridZ(bj), t);
maximum = Math.max(maximum, surfaceHeightAt(x, z));
}
return maximum;
}
function shortestFeasiblePath(start, end) {
const distance = new Float64Array(vertexCount);
distance.fill(Infinity);
const previous = new Int32Array(vertexCount);
previous.fill(-1);
const visited = new Uint8Array(vertexCount);
const heap = new MinHeap();
distance[start] = 0;
heap.push({ id: start, cost: 0 });
const neighborOffsets = [
[-1, 0], [1, 0], [0, -1], [0, 1],
[-1, -1], [1, -1], [-1, 1], [1, 1]
];
while (heap.length) {
const current = heap.pop();
if (visited[current.id]) continue;
visited[current.id] = 1;
if (current.id === end) break;
const i = current.id % NX;
const j = Math.floor(current.id / NX);
for (const [di, dj] of neighborOffsets) {
const ni = i + di;
const nj = j + dj;
if (ni < 0 || ni >= NX || nj < 0 || nj >= NZ) continue;
const next = indexOf(ni, nj);
if (visited[next]) continue;
const edgeMaximum = segmentMaximum(current.id, next);
if (edgeMaximum > ROUTE_LIMIT + 1e-7) continue;
const stepLength = Math.hypot(di * DX, dj * DZ);
const nextCost = distance[current.id] + stepLength;
if (nextCost + 1e-10 < distance[next]) {
distance[next] = nextCost;
previous[next] = current.id;
heap.push({ id: next, cost: nextCost });
}
}
}
if (!Number.isFinite(distance[end])) {
throw new Error("No feasible saddle route was found in the rendered terrain.");
}
const path = [];
let cursor = end;
while (cursor !== -1) {
path.push(cursor);
if (cursor === start) break;
cursor = previous[cursor];
}
path.reverse();
return path;
}
const westIndex = indexOf(Math.round((-39 - XMIN) / DX), saddleJ);
const eastIndex = indexOf(Math.round((39 - XMIN) / DX), saddleJ);
const northGate = indexOf(saddleI, saddleJ + 3);
const southGate = indexOf(saddleI, saddleJ - 3);
const westPath = shortestFeasiblePath(westIndex, northGate);
const eastPath = shortestFeasiblePath(southGate, eastIndex);
const routePath = [
...westPath,
saddleIndex,
...eastPath
];
const routeSamples = [];
for (let k = 0; k < routePath.length - 1; k++) {
const a = routePath[k];
const b = routePath[k + 1];
const ai = a % NX, aj = Math.floor(a / NX);
const bi = b % NX, bj = Math.floor(b / NX);
const ax = gridX(ai), az = gridZ(aj);
const bx = gridX(bi), bz = gridZ(bj);
const length = Math.hypot(bx - ax, bz - az);
const steps = Math.max(1, Math.ceil(length * 5));
for (let s = 0; s < steps; s++) {
const t = s / steps;
const x = THREE.MathUtils.lerp(ax, bx, t);
const z = THREE.MathUtils.lerp(az, bz, t);
routeSamples.push({ x, z, y: surfaceHeightAt(x, z) });
}
}
const finalVertex = routePath[routePath.length - 1];
const finalI = finalVertex % NX;
const finalJ = Math.floor(finalVertex / NX);
routeSamples.push({
x: gridX(finalI),
z: gridZ(finalJ),
y: surfaceHeightAt(gridX(finalI), gridZ(finalJ))
});
let cumulativeDistance = 0;
for (let k = 0; k < routeSamples.length; k++) {
const p = routeSamples[k];
p.distance = cumulativeDistance;
if (k > 0) {
cumulativeDistance += Math.hypot(
p.x - routeSamples[k - 1].x,
p.z - routeSamples[k - 1].z
);
}
}
const routeLength = cumulativeDistance;
let routeMaximum = -Infinity;
let nearestSummit = Infinity;
for (const p of routeSamples) {
routeMaximum = Math.max(routeMaximum, p.y);
nearestSummit = Math.min(
nearestSummit,
Math.hypot(p.x - summitA.x, p.z - summitA.z),
Math.hypot(p.x - summitB.x, p.z - summitB.z)
);
}
const saddleUsed = routePath.includes(saddleIndex);
const passes = (
routeMaximum <= ROUTE_LIMIT + 1e-7 &&
saddleUsed &&
nearestSummit > SUMMIT_EXCLUSION_RADIUS
);
function makeRibbon(width, lift, color, renderOrder) {
const positions = [];
const indices = [];
for (let k = 0; k < routeSamples.length; k++) {
const current = routeSamples[k];
const before = routeSamples[Math.max(0, k - 1)];
const after = routeSamples[Math.min(routeSamples.length - 1, k + 1)];
let tx = after.x - before.x;
let tz = after.z - before.z;
const tangentLength = Math.hypot(tx, tz) || 1;
tx /= tangentLength;
tz /= tangentLength;
const sideX = -tz * width * 0.5;
const sideZ = tx * width * 0.5;
const leftX = current.x + sideX;
const leftZ = current.z + sideZ;
const rightX = current.x - sideX;
const rightZ = current.z - sideZ;
positions.push(
leftX, surfaceHeightAt(leftX, leftZ) + lift, leftZ,
rightX, surfaceHeightAt(rightX, rightZ) + lift, rightZ
);
if (k < routeSamples.length - 1) {
const a = k * 2;
indices.push(a, a + 1, a + 2, a + 1, a + 3, a + 2);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.setIndex(indices);
geometry.computeVertexNormals();
const mesh = new THREE.Mesh(
geometry,
new THREE.MeshBasicMaterial({
color,
side: THREE.DoubleSide,
depthWrite: false,
polygonOffset: true,
polygonOffsetFactor: -2,
polygonOffsetUnits: -2
})
);
mesh.renderOrder = renderOrder;
scene.add(mesh);
return mesh;
}
const routeUnderlay = makeRibbon(1.12, 0.16, 0x7b2f22, 5);
const routeRibbon = makeRibbon(0.58, 0.23, 0xf45b38, 6);
const markerMaterial = new THREE.MeshBasicMaterial({ color: 0xf45b38 });
const saddleRing = new THREE.Mesh(
new THREE.TorusGeometry(1.18, 0.14, 6, 28),
markerMaterial
);
saddleRing.rotation.x = Math.PI / 2;
saddleRing.position.set(0, saddleHeight + 0.35, 0);
saddleRing.renderOrder = 7;
scene.add(saddleRing);
for (const summit of [summitA, summitB]) {
const marker = new THREE.Mesh(
new THREE.OctahedronGeometry(1.05, 0),
new THREE.MeshStandardMaterial({
color: 0xf0dfb5,
roughness: 0.82,
flatShading: true
})
);
marker.position.set(summit.x, summit.y + 1.15, summit.z);
marker.castShadow = true;
scene.add(marker);
const pin = new THREE.Mesh(
new THREE.CylinderGeometry(0.08, 0.08, 1.2, 6),
new THREE.MeshBasicMaterial({ color: 0x173a36 })
);
pin.position.set(summit.x, summit.y + 0.35, summit.z);
scene.add(pin);
}
for (const endpoint of [westIndex, eastIndex]) {
const i = endpoint % NX;
const j = Math.floor(endpoint / NX);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.9, 0.12, 6, 24),
markerMaterial
);
ring.rotation.x = Math.PI / 2;
ring.position.set(gridX(i), gridHeights[endpoint] + 0.27, gridZ(j));
ring.renderOrder = 7;
scene.add(ring);
}
const directLineSamples = [];
const directWest = westIndex;
const directEast = eastIndex;
const directSteps = 120;
for (let k = 0; k <= directSteps; k++) {
const t = k / directSteps;
const x = THREE.MathUtils.lerp(gridX(directWest % NX), gridX(directEast % NX), t);
const z = gridZ(saddleJ);
directLineSamples.push({ x, z, y: surfaceHeightAt(x, z) });
}
const directMaximum = Math.max(...directLineSamples.map(p => p.y));
let directSummitCrossings = 0;
for (const summit of [summitA, summitB]) {
if (directLineSamples.some(p => Math.hypot(p.x - summit.x, p.z - summit.z) < 1.6)) {
directSummitCrossings++;
}
}
const rejectedPositions = [];
for (const p of directLineSamples) {
rejectedPositions.push(p.x, p.y + 0.27, p.z);
}
const rejectedLine = new THREE.Line(
new THREE.BufferGeometry().setAttribute(
"position", new THREE.Float32BufferAttribute(rejectedPositions, 3)
),
new THREE.LineDashedMaterial({
color: 0xa54a38,
dashSize: 0.9,
gapSize: 0.65,
transparent: true,
opacity: 0.58,
depthWrite: false
})
);
rejectedLine.computeLineDistances();
rejectedLine.renderOrder = 4;
rejectedLine.visible = false;
scene.add(rejectedLine);
const formatMeters = value => `${value.toFixed(2)} m`;
document.querySelector("#metricSaddle").textContent = formatMeters(saddleHeight);
document.querySelector("#metricRouteMax").textContent = formatMeters(routeMaximum);
document.querySelector("#metricClearance").textContent = formatMeters(nearestSummit);
document.querySelector("#metricLength").textContent = formatMeters(routeLength);
document.querySelector("#metricDirect").textContent =
`${directMaximum.toFixed(2)} m · ${directSummitCrossings} summits`;
document.querySelector("#metricMesh").textContent =
`${vertexCount.toLocaleString()} nodes · ${triangles.length.toLocaleString()} facets`;
document.querySelector("#statusText").textContent = passes
? `PASS — the route uses the saddle, stays at or below ${ROUTE_LIMIT.toFixed(1)} m, and clears both summit cores.`
: "FAIL — the route did not satisfy the saddle-height and summit-clearance checks.";
document.querySelector("#labelSummitA").innerHTML =
`<strong>Summit A</strong><small>${summitA.y.toFixed(2)} m · schematic summit</small>`;
document.querySelector("#labelSummitB").innerHTML =
`<strong>Summit B</strong><small>${summitB.y.toFixed(2)} m · schematic summit</small>`;
document.querySelector("#labelSaddle").innerHTML =
`<strong>Saddle</strong><small>${saddleHeight.toFixed(2)} m · verified col</small>`;
document.querySelector("#labelRoute").innerHTML =
`<strong>Lowest crossing route</strong><small>max ${routeMaximum.toFixed(2)} m · saddle-constrained</small>`;
function buildProfile() {
const svg = document.querySelector("#profile");
while (svg.firstChild) svg.removeChild(svg.firstChild);
const NS = "http://www.w3.org/2000/svg";
const W = 320, H = 132;
const left = 34, right = 310, top = 12, bottom = 108;
const yMax = 20;
const xAt = d => left + (d / routeLength) * (right - left);
const yAt = e => bottom - (e / yMax) * (bottom - top);
function add(tag, attrs, text) {
const element = document.createElementNS(NS, tag);
for (const [key, value] of Object.entries(attrs)) element.setAttribute(key, value);
if (text !== undefined) element.textContent = text;
svg.appendChild(element);
return element;
}
add("rect", { x: left, y: top, width: right - left, height: bottom - top,
fill: "rgba(255,255,255,0.28)", stroke: "rgba(23,58,54,0.18)" });
for (const elevation of [0, 5, 10, 15]) {
add("line", { x1: left, x2: right, y1: yAt(elevation), y2: yAt(elevation),
stroke: "rgba(23,58,54,0.10)", "stroke-width": 1 });
add("text", { x: left - 6, y: yAt(elevation) + 3, "text-anchor": "end",
fill: "#52706b", "font-size": 8 }, `${elevation}`);
}
add("line", {
x1: left, x2: right, y1: yAt(ROUTE_LIMIT), y2: yAt(ROUTE_LIMIT),
stroke: "#b05a20", "stroke-width": 1.2, "stroke-dasharray": "4 3"
});
add("text", { x: right - 2, y: yAt(ROUTE_LIMIT) - 4, "text-anchor": "end",
fill: "#b05a20", "font-size": 8, "font-weight": 700 }, "15.5 m limit");
const pathData = routeSamples.map((p, k) =>
`${k ? "L" : "M"}${xAt(p.distance).toFixed(2)},${yAt(p.y).toFixed(2)}`
).join(" ");
add("path", { d: pathData, fill: "none", stroke: "#f45b38", "stroke-width": 2.2,
"stroke-linejoin": "round", "stroke-linecap": "round" });
const saddleSample = routeSamples.reduce((best, p) =>
Math.hypot(p.x, p.z) < Math.hypot(best.x, best.z) ? p : best
);
add("circle", { cx: xAt(saddleSample.distance), cy: yAt(saddleSample.y), r: 3.2,
fill: "#ffd166", stroke: "#7b2f22", "stroke-width": 1.1 });
add("text", { x: left, y: 124, fill: "#52706b", "font-size": 8 }, "0 m");
add("text", { x: right, y: 124, "text-anchor": "end", fill: "#52706b",
"font-size": 8 }, `${routeLength.toFixed(1)} m route distance`);
add("text", { x: left, y: top - 1, fill: "#52706b", "font-size": 8 }, "elevation (m)");
document.querySelector("#profileLength").textContent =
`${routeLength.toFixed(1)} m route`;
document.querySelector("#profileCaption").textContent =
`Selected route maximum ${routeMaximum.toFixed(2)} m. The dashed direct valley line reaches ${directMaximum.toFixed(2)} m and crosses ${directSummitCrossings} summit cores, so it is not selected.`;
}
const labelDefinitions = [
{ id: "labelSummitA", position: new THREE.Vector3(summitA.x, summitA.y + 2.25, summitA.z) },
{ id: "labelSummitB", position: new THREE.Vector3(summitB.x, summitB.y + 2.25, summitB.z) },
{ id: "labelSaddle", position: new THREE.Vector3(0, saddleHeight + 1.35, 0) },
{ id: "labelWest", position: new THREE.Vector3(gridX(westIndex % NX), gridHeights[westIndex] + 0.8, gridZ(saddleJ)) },
{ id: "labelEast", position: new THREE.Vector3(gridX(eastIndex % NX), gridHeights[eastIndex] + 0.8, gridZ(saddleJ)) }
];
const routeLabelSample = routeSamples.reduce((best, p) =>
Math.abs(p.x + 20) < Math.abs(best.x + 20) ? p : best
);
labelDefinitions.push({
id: "labelRoute",
position: new THREE.Vector3(routeLabelSample.x, routeLabelSample.y + 1.2, routeLabelSample.z)
});
function updateLabels() {
camera.updateMatrixWorld();
for (const definition of labelDefinitions) {
const element = document.getElementById(definition.id);
const projected = definition.position.clone().project(camera);
const visible = projected.z > -1 && projected.z < 1 &&
projected.x > -1.25 && projected.x < 1.25 &&
projected.y > -1.25 && projected.y < 1.25;
element.style.display = visible ? "block" : "none";
if (!visible) continue;
element.style.left = `${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
element.style.top = `${(-projected.y * 0.5 + 0.5) * window.innerHeight}px`;
}
}
let cameraTween = null;
function setCameraPreset(preset) {
cameraTween = {
start: performance.now(),
duration: 720,
from: {
yaw: cameraState.yaw,
pitch: cameraState.pitch,
zoom: cameraState.zoom,
target: cameraState.target.clone()
},
to: preset
};
}
function updateCamera() {
if (cameraTween) {
const raw = THREE.MathUtils.clamp(
(performance.now() - cameraTween.start) / cameraTween.duration,
0, 1
);
const t = raw * raw * (3 - 2 * raw);
cameraState.yaw = THREE.MathUtils.lerp(cameraTween.from.yaw, cameraTween.to.yaw, t);
cameraState.pitch = THREE.MathUtils.lerp(cameraTween.from.pitch, cameraTween.to.pitch, t);
cameraState.zoom = THREE.MathUtils.lerp(cameraTween.from.zoom, cameraTween.to.zoom, t);
cameraState.target.lerpVectors(cameraTween.from.target, cameraTween.to.target, t);
if (raw >= 1) cameraTween = null;
}
const distance = 120;
const cp = Math.cos(cameraState.pitch);
camera.position.set(
cameraState.target.x + distance * cp * Math.sin(cameraState.yaw),
cameraState.target.y + distance * Math.sin(cameraState.pitch),
cameraState.target.z + distance * cp * Math.cos(cameraState.yaw)
);
camera.lookAt(cameraState.target);
camera.zoom = cameraState.zoom;
camera.updateProjectionMatrix();
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
const aspect = width / height;
const viewHeight = Math.max(58, 94 / aspect);
camera.left = -viewHeight * aspect / 2;
camera.right = viewHeight * aspect / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
}
window.addEventListener("resize", resize);
resize();
let dragging = false;
let panning = false;
let pointerX = 0;
let pointerY = 0;
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("pointerdown", event => {
dragging = true;
panning = event.button === 2 || event.shiftKey;
pointerX = event.clientX;
pointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
cameraTween = null;
});
canvas.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
if (panning) {
const scale = 0.07 / cameraState.zoom;
const rightX = Math.cos(cameraState.yaw);
const rightZ = -Math.sin(cameraState.yaw);
cameraState.target.x -= (dx * rightX - dy * rightZ) * scale;
cameraState.target.z -= (dx * rightZ + dy * rightX) * scale;
} else {
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(cameraState.pitch + dy * 0.005, 0.22, 1.49);
}
});
function stopDragging() { dragging = false; }
canvas.addEventListener("pointerup", stopDragging);
canvas.addEventListener("pointercancel", stopDragging);
canvas.addEventListener("lostpointercapture", stopDragging);
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraTween = null;
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * Math.exp(-event.deltaY * 0.001),
0.55,
2.4
);
}, { passive: false });
canvas.addEventListener("dblclick", () => {
setCameraPreset({
yaw: 0.72,
pitch: 0.62,
zoom: 0.94,
target: new THREE.Vector3(0, 8, 0)
});
});
const overviewPreset = {
yaw: 0.72,
pitch: 0.62,
zoom: 0.94,
target: new THREE.Vector3(0, 8, 0)
};
const planPreset = {
yaw: 0,
pitch: 1.48,
zoom: 1.03,
target: new THREE.Vector3(0, 4, 0)
};
document.querySelector("#overviewButton").addEventListener("click", () => {
setCameraPreset(overviewPreset);
});
document.querySelector("#planButton").addEventListener("click", () => {
setCameraPreset(planPreset);
});
const contourButton = document.querySelector("#contourButton");
contourButton.addEventListener("click", () => {
const visible = !minorContours.visible;
minorContours.visible = visible;
majorContours.visible = visible;
contourButton.setAttribute("aria-pressed", String(visible));
updateLayerNote();
});
const routeButton = document.querySelector("#routeButton");
routeButton.addEventListener("click", () => {
const visible = !routeRibbon.visible;
routeUnderlay.visible = visible;
routeRibbon.visible = visible;
saddleRing.visible = visible;
document.querySelector("#labelRoute").style.display = visible ? "block" : "none";
routeButton.setAttribute("aria-pressed", String(visible));
updateLayerNote();
});
const profilePanel = document.querySelector("#profilePanel");
const verifyButton = document.querySelector("#verifyButton");
verifyButton.addEventListener("click", () => {
const opening = !profilePanel.classList.contains("open");
profilePanel.classList.toggle("open", opening);
verifyButton.textContent = opening ? "Hide verification" : "Verify geometry";
rejectedLine.visible = opening;
if (opening) {
buildProfile();
setCameraPreset(planPreset);
}
updateLayerNote();
});
function updateLayerNote() {
const layers = ["terrain"];
if (minorContours.visible) layers.push("5 m contours");
if (routeRibbon.visible) layers.push("selected route");
if (rejectedLine.visible) layers.push("rejected direct line");
document.querySelector("#layerNote").textContent =
`Visible: ${layers.join(", ")}. Metrics are sampled from the rendered triangles, not duplicated label data.`;
}
updateLayerNote();
function animate() {
requestAnimationFrame(animate);
updateCamera();
updateLabels();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```