Prompt specification
Build or customize the Three.js 3D scene "Compass route with a blocked pass" 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: Compass route with a blocked pass
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/compass-route-with-a-blocked-pass-x1292
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts compass bearings. Let the user close one mountain pass and choose new waypoint bearings. Animate the traveler only along traversable paths, displaying distance and route changes. Voxel style.
Working Three.js Starter (compass-route-with-a-blocked-pass-x1292):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Compass — Mountain Route Planner</title>
<style>
:root {
--ink: #10272c;
--panel: rgba(10, 28, 32, 0.88);
--panel-border: rgba(255, 255, 255, 0.14);
--text: #eef8f5;
--muted: #9cb7b5;
--mint: #73e0c3;
--yellow: #ffd66b;
--red: #ff7c70;
--blue: #8ed9ef;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #9bcdd2;
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
border: 1px solid var(--panel-border);
color: var(--text);
background: rgba(255, 255, 255, 0.08);
cursor: pointer;
}
button:hover {
background: rgba(255, 255, 255, 0.15);
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
}
.panel {
pointer-events: auto;
background: var(--panel);
border: 1px solid var(--panel-border);
box-shadow:
0 12px 34px rgba(0, 0, 0, 0.2),
inset 0 1px 0 rgba(255, 255, 255, 0.06);
backdrop-filter: blur(13px);
}
.eyebrow {
color: var(--mint);
font-size: 0.7rem;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.controls {
position: absolute;
top: 18px;
left: 18px;
width: 320px;
max-height: calc(100vh - 36px);
overflow: auto;
padding: 18px;
border-radius: 14px;
}
.controls::-webkit-scrollbar,
.route-panel::-webkit-scrollbar {
width: 6px;
}
.controls::-webkit-scrollbar-thumb,
.route-panel::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.18);
border-radius: 8px;
}
h1 {
margin: 5px 0 7px;
font-size: 1.55rem;
line-height: 1.05;
letter-spacing: -0.04em;
}
.intro {
margin: 0 0 15px;
color: var(--muted);
font-size: 0.82rem;
line-height: 1.45;
}
.section-title {
margin: 16px 0 9px;
color: #d8e9e6;
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.waypoint-buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.waypoint-buttons button {
padding: 8px 9px;
border-radius: 7px;
text-align: left;
font-size: 0.76rem;
font-weight: 700;
}
.waypoint-buttons button.active {
color: #092823;
border-color: var(--mint);
background: var(--mint);
}
.bearing-layout {
display: grid;
grid-template-columns: 112px 1fr;
gap: 15px;
align-items: center;
}
.compass {
position: relative;
width: 108px;
height: 108px;
border: 2px solid rgba(255, 255, 255, 0.26);
border-radius: 50%;
background:
linear-gradient(90deg, transparent 49%, rgba(255, 255, 255, 0.08) 50%, transparent 51%),
linear-gradient(transparent 49%, rgba(255, 255, 255, 0.08) 50%, transparent 51%),
rgba(0, 0, 0, 0.15);
cursor: crosshair;
touch-action: none;
}
.compass::after {
content: "";
position: absolute;
inset: 17px;
border: 1px dashed rgba(255, 255, 255, 0.2);
border-radius: 50%;
pointer-events: none;
}
.cardinal {
position: absolute;
z-index: 2;
color: #d7e6e3;
font-size: 0.63rem;
font-weight: 900;
pointer-events: none;
}
.cardinal.north { top: 3px; left: 50%; transform: translateX(-50%); }
.cardinal.east { right: 5px; top: 50%; transform: translateY(-50%); }
.cardinal.south { bottom: 3px; left: 50%; transform: translateX(-50%); }
.cardinal.west { left: 4px; top: 50%; transform: translateY(-50%); }
.needle {
position: absolute;
z-index: 3;
left: calc(50% - 3px);
bottom: 50%;
width: 6px;
height: 43px;
border-radius: 3px 3px 0 0;
background: linear-gradient(to top, #f5faf8 0 45%, var(--red) 46% 100%);
transform-origin: 50% 100%;
transform: rotate(0deg);
pointer-events: none;
}
.needle::before {
content: "";
position: absolute;
top: -3px;
left: -4px;
border-left: 7px solid transparent;
border-right: 7px solid transparent;
border-bottom: 10px solid var(--red);
}
.compass-center {
position: absolute;
z-index: 4;
left: 50%;
top: 50%;
width: 9px;
height: 9px;
transform: translate(-50%, -50%);
border-radius: 50%;
background: var(--text);
pointer-events: none;
}
.bearing-readout {
display: flex;
align-items: baseline;
gap: 7px;
margin-bottom: 8px;
}
#bearingValue {
color: var(--yellow);
font-size: 2rem;
font-weight: 900;
line-height: 1;
font-variant-numeric: tabular-nums;
}
#bearingName {
color: var(--muted);
font-size: 0.75rem;
font-weight: 700;
}
#bearingRange {
width: 100%;
accent-color: var(--yellow);
cursor: ew-resize;
}
.range-labels {
display: flex;
justify-content: space-between;
margin-top: 3px;
color: #789492;
font-size: 0.62rem;
font-weight: 700;
}
.toggle-button,
.primary-button,
.secondary-button {
width: 100%;
padding: 11px 12px;
border-radius: 8px;
font-weight: 800;
font-size: 0.8rem;
}
.toggle-button {
margin-bottom: 8px;
border-color: rgba(255, 124, 112, 0.45);
background: rgba(255, 124, 112, 0.12);
}
.toggle-button.closed {
color: #2a0c09;
background: var(--red);
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.primary-button {
color: #092823;
border-color: var(--mint);
background: var(--mint);
}
.secondary-button {
background: rgba(255, 255, 255, 0.08);
}
.hint {
margin: 13px 0 0;
padding-top: 12px;
border-top: 1px solid rgba(255, 255, 255, 0.1);
color: #8faaa7;
font-size: 0.7rem;
line-height: 1.5;
}
.telemetry {
position: absolute;
top: 18px;
right: 18px;
width: 250px;
padding: 16px;
border-radius: 14px;
}
.status-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 13px;
}
#status {
padding: 5px 8px;
border-radius: 999px;
color: #092823;
background: var(--mint);
font-size: 0.65rem;
font-weight: 900;
letter-spacing: 0.08em;
}
#currentBearing {
color: var(--yellow);
font-size: 1.55rem;
font-weight: 900;
font-variant-numeric: tabular-nums;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
min-height: 68px;
padding: 10px;
border: 1px solid rgba(255, 255, 255, 0.09);
border-radius: 8px;
background: rgba(255, 255, 255, 0.04);
}
.metric-label {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 0.61rem;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric-value {
font-size: 1.12rem;
font-weight: 900;
font-variant-numeric: tabular-nums;
}
.metric-value small {
color: var(--muted);
font-size: 0.65rem;
}
.route-panel {
position: absolute;
right: 18px;
bottom: 18px;
width: min(560px, calc(100vw - 36px));
max-height: 280px;
overflow: auto;
padding: 16px;
border-radius: 14px;
}
.route-header {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
margin-bottom: 11px;
}
.route-title {
font-weight: 900;
font-size: 0.95rem;
}
#routeDistance {
color: var(--yellow);
font-size: 0.75rem;
font-weight: 800;
white-space: nowrap;
}
#routeSteps {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 13px;
}
.route-step {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 8px;
border: 1px solid rgba(255, 214, 107, 0.25);
border-radius: 6px;
color: #f7e7b8;
background: rgba(255, 214, 107, 0.08);
font-size: 0.68rem;
font-weight: 750;
}
.route-step::before {
content: "";
width: 6px;
height: 6px;
background: var(--yellow);
box-shadow: 0 0 8px rgba(255, 214, 107, 0.7);
}
.route-step.closed::before {
background: var(--red);
box-shadow: 0 0 8px rgba(255, 124, 112, 0.7);
}
.event-log {
display: grid;
gap: 6px;
margin: 0;
padding: 0;
list-style: none;
}
.event-log li {
display: grid;
grid-template-columns: 58px 1fr;
gap: 8px;
color: #b8cdca;
font-size: 0.7rem;
line-height: 1.35;
}
.event-log time {
color: #688986;
font-variant-numeric: tabular-nums;
}
.event-log li.change {
color: #ffe397;
}
.event-log li.warning {
color: #ffaaa2;
}
@media (max-width: 820px) {
.controls {
width: 285px;
max-height: calc(100vh - 36px);
}
.telemetry {
width: 205px;
}
.route-panel {
max-height: 220px;
}
}
@media (max-width: 620px) {
.controls {
top: 10px;
left: 10px;
width: 255px;
max-height: 52vh;
padding: 13px;
}
.telemetry {
top: 10px;
right: 10px;
width: 155px;
padding: 12px;
}
.metric-grid {
grid-template-columns: 1fr;
}
.metric {
min-height: 52px;
}
.metric:nth-child(n + 3) {
display: none;
}
.route-panel {
right: 10px;
bottom: 10px;
width: calc(100vw - 20px);
max-height: 35vh;
}
}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<div class="hud">
<section class="panel controls">
<div class="eyebrow">Voxel Navigation System</div>
<h1>Compass Route Planner</h1>
<p class="intro">
Choose a waypoint, set its preferred bearing, and watch the traveler
select a traversable trail toward the summit.
</p>
<div class="section-title">1 · Select Waypoint</div>
<div id="waypointButtons" class="waypoint-buttons"></div>
<div class="section-title">2 · Set New Bearing</div>
<div class="bearing-layout">
<div id="compass" class="compass" title="Click or drag to set bearing">
<span class="cardinal north">N</span>
<span class="cardinal east">E</span>
<span class="cardinal south">S</span>
<span class="cardinal west">W</span>
<div id="needle" class="needle"></div>
<div class="compass-center"></div>
</div>
<div>
<div class="bearing-readout">
<span id="bearingValue">050°</span>
<span id="bearingName">NE</span>
</div>
<input
id="bearingRange"
type="range"
min="0"
max="359"
value="50"
aria-label="Waypoint bearing"
/>
<div class="range-labels">
<span>N 0°</span>
<span>E 90°</span>
<span>S 180°</span>
<span>W 270°</span>
</div>
</div>
</div>
<div class="section-title">3 · Change Route Conditions</div>
<button id="passToggle" class="toggle-button">
Close Kestrel Pass
</button>
<div class="button-row">
<button id="pauseButton" class="primary-button">Pause Traveler</button>
<button id="restartButton" class="secondary-button">Restart Route</button>
</div>
<p class="hint">
Bearings are clockwise from North. The planner uses the closest
traversable path to each chosen bearing. Drag to orbit, wheel to zoom,
Shift-drag to pan, and click a world beacon to select a waypoint.
</p>
</section>
<section class="panel telemetry">
<div class="status-row">
<span id="status">TRAVELING</span>
<span id="currentBearing">050°</span>
</div>
<div class="metric-grid">
<div class="metric">
<span class="metric-label">Traveled</span>
<span class="metric-value"><span id="distanceTraveled">0.0</span> <small>u</small></span>
</div>
<div class="metric">
<span class="metric-label">Remaining</span>
<span class="metric-value"><span id="distanceRemaining">0.0</span> <small>u</small></span>
</div>
<div class="metric">
<span class="metric-label">Current Heading</span>
<span class="metric-value"><span id="headingText">050°</span></span>
</div>
<div class="metric">
<span class="metric-label">Next Trail</span>
<span id="nextTrail" class="metric-value">Pine Approach</span>
</div>
</div>
</section>
<section class="panel route-panel">
<div class="route-header">
<span class="route-title">Planned Route</span>
<span id="routeDistance">0.0 units</span>
</div>
<div id="routeSteps"></div>
<ul id="eventLog" class="event-log"></ul>
</section>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene setup
// -------------------------------------------------------------------------
const canvas = document.getElementById("scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
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(0x9bcdd2);
scene.fog = new THREE.Fog(0x9bcdd2, 42, 100);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
220
);
const hemiLight = new THREE.HemisphereLight(0xd9f4ff, 0x486044, 2.0);
scene.add(hemiLight);
const sun = new THREE.DirectionalLight(0xfff1c7, 2.7);
sun.position.set(-24, 36, 18);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -42;
sun.shadow.camera.right = 42;
sun.shadow.camera.top = 42;
sun.shadow.camera.bottom = -42;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 100;
sun.shadow.bias = -0.0004;
scene.add(sun);
const ambient = new THREE.AmbientLight(0xffffff, 0.18);
scene.add(ambient);
// -------------------------------------------------------------------------
// Custom camera controls — no addons
// -------------------------------------------------------------------------
const cameraControl = {
target: new THREE.Vector3(0, 2, 0),
yaw: 0.38,
pitch: 0.76,
radius: 53,
minRadius: 20,
maxRadius: 78,
dragging: false,
panning: false,
pointerId: null,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0,
moved: 0
};
function updateCamera() {
const { target, yaw, pitch, radius } = cameraControl;
const horizontal = Math.sin(pitch) * radius;
camera.position.set(
target.x + Math.sin(yaw) * horizontal,
target.y + Math.cos(pitch) * radius,
target.z + Math.cos(yaw) * horizontal
);
camera.lookAt(target);
}
canvas.addEventListener("pointerdown", (event) => {
cameraControl.dragging = true;
cameraControl.panning = event.shiftKey;
cameraControl.pointerId = event.pointerId;
cameraControl.startX = event.clientX;
cameraControl.startY = event.clientY;
cameraControl.lastX = event.clientX;
cameraControl.lastY = event.clientY;
cameraControl.moved = 0;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!cameraControl.dragging) return;
const dx = event.clientX - cameraControl.lastX;
const dy = event.clientY - cameraControl.lastY;
cameraControl.moved += Math.abs(dx) + Math.abs(dy);
cameraControl.lastX = event.clientX;
cameraControl.lastY = event.clientY;
if (cameraControl.panning) {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3().crossVectors(forward, camera.up);
const panScale = cameraControl.radius * 0.0015;
cameraControl.target.addScaledVector(right, -dx * panScale);
cameraControl.target.addScaledVector(forward, dy * panScale);
} else {
cameraControl.yaw -= dx * 0.005;
cameraControl.pitch = THREE.MathUtils.clamp(
cameraControl.pitch + dy * 0.004,
0.22,
1.25
);
}
});
const raycaster = new THREE.Raycaster();
const pointerNdc = new THREE.Vector2();
canvas.addEventListener("pointerup", (event) => {
if (cameraControl.pointerId !== event.pointerId) return;
const wasClick =
cameraControl.moved < 6 &&
Math.abs(event.clientX - cameraControl.startX) < 6 &&
Math.abs(event.clientY - cameraControl.startY) < 6;
cameraControl.dragging = false;
cameraControl.panning = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
if (wasClick) {
pointerNdc.x = (event.clientX / window.innerWidth) * 2 - 1;
pointerNdc.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(pointerNdc, camera);
const hit = raycaster.intersectObjects(pickables, false)[0];
if (hit?.object.userData.nodeId) {
selectNode(hit.object.userData.nodeId);
}
}
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraControl.radius = THREE.MathUtils.clamp(
cameraControl.radius * Math.exp(event.deltaY * 0.001),
cameraControl.minRadius,
cameraControl.maxRadius
);
},
{ passive: false }
);
// -------------------------------------------------------------------------
// Voxel terrain
// -------------------------------------------------------------------------
const CELL = 2;
const ORIGIN_X = -29;
const ORIGIN_Z = -25;
const COLS = 31;
const ROWS = 27;
const terrainHeights = new Map();
function continuousTerrainHeight(x, z) {
const peaks = [
{ x: 20, z: -14, height: 10.5, spread: 8.5 },
{ x: 4, z: -10, height: 6.2, spread: 6.2 },
{ x: 27, z: 15, height: 5.0, spread: 7.0 },
{ x: -27, z: -13, height: 5.6, spread: 7.4 },
{ x: -25, z: 19, height: 2.8, spread: 6.0 }
];
let height = 0.45;
for (const peak of peaks) {
const dx = x - peak.x;
const dz = z - peak.z;
height +=
peak.height *
Math.exp(-(dx * dx + dz * dz) / (2 * peak.spread * peak.spread));
}
height +=
0.22 *
Math.sin(x * 0.31 + z * 0.11) *
Math.cos(z * 0.27 - x * 0.08);
return Math.max(0, Math.round(height * 2) / 2);
}
for (let iz = 0; iz < ROWS; iz++) {
for (let ix = 0; ix < COLS; ix++) {
const x = ORIGIN_X + ix * CELL;
const z = ORIGIN_Z + iz * CELL;
terrainHeights.set(`${ix},${iz}`, continuousTerrainHeight(x, z));
}
}
function heightAt(x, z) {
const ix = THREE.MathUtils.clamp(
Math.round((x - ORIGIN_X) / CELL),
0,
COLS - 1
);
const iz = THREE.MathUtils.clamp(
Math.round((z - ORIGIN_Z) / CELL),
0,
ROWS - 1
);
return terrainHeights.get(`${ix},${iz}`) ?? 0;
}
const terrainGeometry = new THREE.BoxGeometry(1.97, 1, 1.97);
const terrainMaterial = new THREE.MeshStandardMaterial({
roughness: 0.95,
metalness: 0
});
const terrain = new THREE.InstancedMesh(
terrainGeometry,
terrainMaterial,
COLS * ROWS
);
const dummy = new THREE.Object3D();
const color = new THREE.Color();
let terrainIndex = 0;
for (let iz = 0; iz < ROWS; iz++) {
for (let ix = 0; ix < COLS; ix++) {
const x = ORIGIN_X + ix * CELL;
const z = ORIGIN_Z + iz * CELL;
const h = terrainHeights.get(`${ix},${iz}`);
dummy.position.set(x, (h - 2) / 2, z);
dummy.scale.set(1, h + 2, 1);
dummy.updateMatrix();
terrain.setMatrixAt(terrainIndex, dummy.matrix);
if (h > 8.2) {
color.setHSL(0.56, 0.18, 0.82 - (h - 8.2) * 0.025);
} else if (h > 6.2) {
color.setHSL(0.58, 0.12, 0.67);
} else {
const variation = ((ix * 17 + iz * 13) % 9) * 0.008;
color.setHSL(0.285, 0.25, 0.38 + variation);
}
terrain.setColorAt(terrainIndex, color);
terrainIndex++;
}
}
terrain.instanceMatrix.needsUpdate = true;
terrain.instanceColor.needsUpdate = true;
terrain.receiveShadow = true;
scene.add(terrain);
const base = new THREE.Mesh(
new THREE.BoxGeometry(74, 2.2, 68),
new THREE.MeshStandardMaterial({ color: 0x355b4f, roughness: 1 })
);
base.position.y = -2.1;
base.receiveShadow = true;
scene.add(base);
// -------------------------------------------------------------------------
// Nodes, edges, and path helpers
// -------------------------------------------------------------------------
const nodeDefinitions = {
camp: {
name: "Pine Camp",
x: -18,
z: 14,
color: 0x8edfbc
},
fork: {
name: "Whisper Fork",
x: -6,
z: 4,
color: 0xf0d477
},
kestrel: {
name: "Kestrel Ridge",
x: 3,
z: -9,
color: 0xf39c87
},
lake: {
name: "Mirror Lake",
x: 12,
z: 9,
color: 0x8ed9ef
},
summit: {
name: "Cloud Summit",
x: 19,
z: -14,
color: 0xd8efff
}
};
const nodes = {};
for (const [id, definition] of Object.entries(nodeDefinitions)) {
nodes[id] = {
...definition,
id,
y: heightAt(definition.x, definition.z)
};
}
function resamplePath(rawPoints, spacing = 0.5) {
const output = [];
for (let i = 0; i < rawPoints.length - 1; i++) {
const a = rawPoints[i];
const b = rawPoints[i + 1];
const dx = b.x - a.x;
const dz = b.z - a.z;
const length = Math.hypot(dx, dz);
const steps = Math.max(1, Math.ceil(length / spacing));
for (let step = 0; step < steps; step++) {
const t = step / steps;
const x = THREE.MathUtils.lerp(a.x, b.x, t);
const z = THREE.MathUtils.lerp(a.z, b.z, t);
output.push(
new THREE.Vector3(x, heightAt(x, z) + 0.25, z)
);
}
}
const last = rawPoints[rawPoints.length - 1];
output.push(
new THREE.Vector3(
last.x,
heightAt(last.x, last.z) + 0.25,
last.z
)
);
return output;
}
function measurePolyline(points) {
const cumulative = [0];
for (let i = 1; i < points.length; i++) {
cumulative.push(
cumulative[i - 1] + points[i].distanceTo(points[i - 1])
);
}
return {
points,
cumulative,
length: cumulative[cumulative.length - 1]
};
}
function samplePolyline(points, cumulative, distance) {
const d = THREE.MathUtils.clamp(distance, 0, cumulative[cumulative.length - 1]);
for (let i = 1; i < points.length; i++) {
if (d <= cumulative[i]) {
const segmentLength = cumulative[i] - cumulative[i - 1];
const t = segmentLength === 0 ? 0 : (d - cumulative[i - 1]) / segmentLength;
const point = points[i - 1].clone().lerp(points[i], t);
const tangent = points[i].clone().sub(points[i - 1]).normalize();
return { point, tangent };
}
}
return {
point: points[points.length - 1].clone(),
tangent: points[points.length - 1]
.clone()
.sub(points[points.length - 2])
.normalize()
};
}
const edgeDefinitions = [
{
id: "pine",
name: "Pine Approach",
a: "camp",
b: "fork",
raw: [
new THREE.Vector3(-18, 0, 14),
new THREE.Vector3(-14, 0, 10),
new THREE.Vector3(-10, 0, 7),
new THREE.Vector3(-6, 0, 4)
]
},
{
id: "pass",
name: "Kestrel Pass",
a: "fork",
b: "kestrel",
raw: [
new THREE.Vector3(-6, 0, 4),
new THREE.Vector3(-3, 0, 1),
new THREE.Vector3(-1, 0, -3),
new THREE.Vector3(3, 0, -9)
]
},
{
id: "north-spur",
name: "North Spur",
a: "kestrel",
b: "summit",
raw: [
new THREE.Vector3(3, 0, -9),
new THREE.Vector3(8, 0, -11),
new THREE.Vector3(13, 0, -12),
new THREE.Vector3(19, 0, -14)
]
},
{
id: "mirror",
name: "Mirror Switchback",
a: "fork",
b: "lake",
raw: [
new THREE.Vector3(-6, 0, 4),
new THREE.Vector3(-2, 0, 8),
new THREE.Vector3(4, 0, 10),
new THREE.Vector3(12, 0, 9)
]
},
{
id: "glacier",
name: "Glacier Ledge",
a: "lake",
b: "summit",
raw: [
new THREE.Vector3(12, 0, 9),
new THREE.Vector3(16, 0, 3),
new THREE.Vector3(18, 0, -5),
new THREE.Vector3(19, 0, -14)
]
},
{
id: "lowland",
name: "Lowland Trail",
a: "camp",
b: "lake",
raw: [
new THREE.Vector3(-18, 0, 14),
new THREE.Vector3(-10, 0, 16),
new THREE.Vector3(-2, 0, 13),
new THREE.Vector3(5, 0, 12),
new THREE.Vector3(12, 0, 9)
]
}
];
const edges = edgeDefinitions.map((definition) => {
const measured = measurePolyline(resamplePath(definition.raw));
return {
...definition,
...measured,
closed: false,
mesh: null
};
});
const edgeById = new Map(edges.map((edge) => [edge.id, edge]));
function edgeBetween(a, b) {
return edges.find(
(edge) =>
(edge.a === a && edge.b === b) ||
(edge.a === b && edge.b === a)
);
}
function orientedPoints(edge, fromNode) {
return edge.a === fromNode ? edge.points : [...edge.points].reverse();
}
function orientedCumulative(edge, fromNode) {
if (edge.a === fromNode) return edge.cumulative;
return [...edge.cumulative]
.map((value, index) => edge.length - value)
.reverse();
}
const adjacency = {};
for (const id of Object.keys(nodes)) adjacency[id] = [];
for (const edge of edges) {
adjacency[edge.a].push({ edge, next: edge.b });
adjacency[edge.b].push({ edge, next: edge.a });
}
// -------------------------------------------------------------------------
// Path meshes
// -------------------------------------------------------------------------
const pathGeometry = new THREE.BoxGeometry(0.68, 0.18, 0.68);
const pathMaterial = new THREE.MeshStandardMaterial({
color: 0xd9b777,
roughness: 0.9
});
for (const edge of edges) {
const mesh = new THREE.InstancedMesh(
pathGeometry,
pathMaterial.clone(),
edge.points.length
);
edge.points.forEach((point, index) => {
dummy.position.copy(point);
dummy.position.y -= 0.02;
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
});
mesh.instanceMatrix.needsUpdate = true;
mesh.receiveShadow = true;
scene.add(mesh);
edge.mesh = mesh;
}
// -------------------------------------------------------------------------
// Labels, waypoint beacons, and bearing arrows
// -------------------------------------------------------------------------
const pickables = [];
const markerMaterials = new Map();
function makeLabel(text, accent = "#73e0c3", width = 7.2) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 128;
const ctx = labelCanvas.getContext("2d");
ctx.clearRect(0, 0, 512, 128);
ctx.fillStyle = "rgba(8, 25, 29, 0.84)";
ctx.fillRect(8, 22, 496, 84);
ctx.strokeStyle = accent;
ctx.lineWidth = 5;
ctx.strokeRect(8, 22, 496, 84);
ctx.fillStyle = "#f3fbf8";
ctx.font = "800 37px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 256, 65);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(width, width * 0.25, 1);
sprite.renderOrder = 20;
return sprite;
}
const arrowGroups = new Map();
for (const node of Object.values(nodes)) {
const group = new THREE.Group();
group.position.set(node.x, node.y + 0.26, node.z);
const platform = new THREE.Mesh(
new THREE.BoxGeometry(3.1, 0.35, 3.1),
new THREE.MeshStandardMaterial({
color: 0x304a43,
roughness: 0.9
})
);
platform.position.y = 0.12;
platform.receiveShadow = true;
group.add(platform);
const beaconMaterial = new THREE.MeshStandardMaterial({
color: node.color,
emissive: node.color,
emissiveIntensity: 0.25,
roughness: 0.55
});
markerMaterials.set(node.id, beaconMaterial);
const beacon = new THREE.Mesh(
new THREE.BoxGeometry(0.52, 2.1, 0.52),
beaconMaterial
);
beacon.position.y = 1.45;
beacon.castShadow = true;
beacon.userData.nodeId = node.id;
group.add(beacon);
pickables.push(beacon);
const cap = new THREE.Mesh(
new THREE.BoxGeometry(0.85, 0.35, 0.85),
beaconMaterial
);
cap.position.y = 2.62;
cap.castShadow = true;
cap.userData.nodeId = node.id;
group.add(cap);
pickables.push(cap);
const label = makeLabel(node.name.toUpperCase(), `#${node.color.toString(16).padStart(6, "0")}`, 7.5);
label.position.y = 4.3;
group.add(label);
scene.add(group);
const arrow = new THREE.Group();
const arrowMaterial = new THREE.MeshStandardMaterial({
color: 0x73e0c3,
emissive: 0x24695a,
emissiveIntensity: 0.45,
roughness: 0.65
});
const shaft = new THREE.Mesh(
new THREE.BoxGeometry(0.22, 0.15, 2.15),
arrowMaterial
);
shaft.position.z = -0.92;
arrow.add(shaft);
const head = new THREE.Mesh(
new THREE.BoxGeometry(0.7, 0.15, 0.65),
arrowMaterial
);
head.position.z = -2.05;
arrow.add(head);
const arrowX = node.x;
const arrowZ = node.z + 3.1;
arrow.position.set(arrowX, heightAt(arrowX, arrowZ) + 0.28, arrowZ);
scene.add(arrow);
arrowGroups.set(node.id, arrow);
}
// Camp details.
const camp = nodes.camp;
const tent = new THREE.Group();
tent.position.set(camp.x - 2.8, heightAt(camp.x - 2.8, camp.z - 1.2), camp.z - 1.2);
const tentBody = new THREE.Mesh(
new THREE.BoxGeometry(2.4, 1.25, 2.0),
new THREE.MeshStandardMaterial({ color: 0xde765d, roughness: 0.9 })
);
tentBody.position.y = 0.63;
tentBody.castShadow = true;
tent.add(tentBody);
const tentDoor = new THREE.Mesh(
new THREE.BoxGeometry(0.75, 0.95, 0.12),
new THREE.MeshStandardMaterial({ color: 0xf0d7b1 })
);
tentDoor.position.set(0, 0.49, 1.04);
tent.add(tentDoor);
scene.add(tent);
// Lake tiles.
const lakeGroup = new THREE.Group();
lakeGroup.position.set(nodes.lake.x, nodes.lake.y + 0.12, nodes.lake.z);
const lakeMaterial = new THREE.MeshStandardMaterial({
color: 0x4da7bd,
emissive: 0x143f48,
emissiveIntensity: 0.3,
roughness: 0.25,
metalness: 0.08
});
for (let ix = -2; ix <= 2; ix++) {
for (let iz = -1; iz <= 1; iz++) {
if (Math.abs(ix) + Math.abs(iz) > 3) continue;
const tile = new THREE.Mesh(
new THREE.BoxGeometry(0.9, 0.12, 0.9),
lakeMaterial
);
tile.position.set(ix * 0.78, 0, iz * 0.78);
lakeGroup.add(tile);
}
}
scene.add(lakeGroup);
// Summit monument.
const summit = nodes.summit;
const monument = new THREE.Group();
monument.position.set(summit.x, summit.y, summit.z);
const monumentBase = new THREE.Mesh(
new THREE.BoxGeometry(2.6, 0.45, 2.6),
new THREE.MeshStandardMaterial({ color: 0xd8efff })
);
monumentBase.position.y = 0.23;
monument.add(monumentBase);
const monumentBody = new THREE.Mesh(
new THREE.BoxGeometry(0.75, 3.2, 0.75),
new THREE.MeshStandardMaterial({ color: 0xb6d8e8, roughness: 0.55 })
);
monumentBody.position.y = 2;
monument.add(monumentBody);
const monumentTop = new THREE.Mesh(
new THREE.BoxGeometry(1.5, 0.55, 1.5),
new THREE.MeshStandardMaterial({
color: 0xffd66b,
emissive: 0x7f5712,
emissiveIntensity: 0.3
})
);
monumentTop.position.y = 3.85;
monument.add(monumentTop);
scene.add(monument);
// -------------------------------------------------------------------------
// Kestrel Pass gate
// -------------------------------------------------------------------------
const passEdge = edgeById.get("pass");
const passMiddle = samplePolyline(
passEdge.points,
passEdge.cumulative,
passEdge.length * 0.5
);
const passGate = new THREE.Group();
passGate.position.copy(passMiddle.point);
passGate.position.y = heightAt(passGate.position.x, passGate.position.z) + 0.2;
const tangent = passMiddle.tangent;
passGate.rotation.y = Math.atan2(tangent.x, tangent.z);
const postMaterial = new THREE.MeshStandardMaterial({
color: 0x65463c,
roughness: 0.85
});
for (const side of [-1, 1]) {
const post = new THREE.Mesh(
new THREE.BoxGeometry(0.35, 3.0, 0.35),
postMaterial
);
post.position.set(side * 1.45, 1.5, 0);
post.castShadow = true;
passGate.add(post);
}
const barrier = new THREE.Mesh(
new THREE.BoxGeometry(3.15, 0.42, 0.42),
new THREE.MeshStandardMaterial({
color: 0xff7569,
emissive: 0x7e1f18,
emissiveIntensity: 0.25
})
);
barrier.position.y = 1.35;
barrier.castShadow = true;
passGate.add(barrier);
const passLabel = makeLabel("KESTREL PASS", "#ff7c70", 6.3);
passLabel.position.set(0, 4.3, 0);
passGate.add(passLabel);
scene.add(passGate);
// -------------------------------------------------------------------------
// Voxel trees and rocks
// -------------------------------------------------------------------------
function distanceToSegmentXZ(px, pz, ax, az, bx, bz) {
const abx = bx - ax;
const abz = bz - az;
const apx = px - ax;
const apz = pz - az;
const lengthSquared = abx * abx + abz * abz;
const t =
lengthSquared === 0
? 0
: THREE.MathUtils.clamp(
(apx * abx + apz * abz) / lengthSquared,
0,
1
);
const x = ax + abx * t;
const z = az + abz * t;
return Math.hypot(px - x, pz - z);
}
function nearAnyPath(x, z) {
for (const edge of edges) {
for (let i = 1; i < edge.points.length; i++) {
const a = edge.points[i - 1];
const b = edge.points[i];
const distance = distanceToSegmentXZ(x, z, a.x, a.z, b.x, b.z);
if (distance < 2.25) return true;
}
}
return false;
}
let randomSeed = 7319;
function random() {
randomSeed = (randomSeed * 16807) % 2147483647;
return (randomSeed - 1) / 2147483646;
}
const treeTrunks = [];
const treeLeaves = [];
for (let attempt = 0; attempt < 500 && treeTrunks.length < 85; attempt++) {
const x = ORIGIN_X + random() * (COLS - 1) * CELL;
const z = ORIGIN_Z + random() * (ROWS - 1) * CELL;
const h = heightAt(x, z);
if (h > 5.8 || nearAnyPath(x, z)) continue;
treeTrunks.push({ x, y: h, z, scale: 0.75 + random() * 0.5 });
treeLeaves.push({ x, y: h + 1.2, z, scale: 1 });
treeLeaves.push({ x, y: h + 1.9, z, scale: 0.72 });
}
const trunkMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.45, 1.5, 0.45),
new THREE.MeshStandardMaterial({ color: 0x694a35, roughness: 1 }),
treeTrunks.length
);
treeTrunks.forEach((tree, index) => {
dummy.position.set(tree.x, tree.y + 0.75, tree.z);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(tree.scale, tree.scale, tree.scale);
dummy.updateMatrix();
trunkMesh.setMatrixAt(index, dummy.matrix);
});
trunkMesh.instanceMatrix.needsUpdate = true;
trunkMesh.castShadow = true;
scene.add(trunkMesh);
const leafMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1.25, 1.05, 1.25),
new THREE.MeshStandardMaterial({ color: 0x285d4b, roughness: 1 }),
treeLeaves.length
);
treeLeaves.forEach((leaf, index) => {
dummy.position.set(leaf.x, leaf.y, leaf.z);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(leaf.scale, leaf.scale, leaf.scale);
dummy.updateMatrix();
leafMesh.setMatrixAt(index, dummy.matrix);
color.setHSL(0.39 + (index % 4) * 0.008, 0.32, 0.27 + (index % 3) * 0.025);
leafMesh.setColorAt(index, color);
});
leafMesh.instanceMatrix.needsUpdate = true;
leafMesh.instanceColor.needsUpdate = true;
leafMesh.castShadow = true;
scene.add(leafMesh);
const rockData = [];
for (let attempt = 0; attempt < 260 && rockData.length < 55; attempt++) {
const x = ORIGIN_X + random() * (COLS - 1) * CELL;
const z = ORIGIN_Z + random() * (ROWS - 1) * CELL;
if (nearAnyPath(x, z)) continue;
rockData.push({ x, y: heightAt(x, z), z, scale: 0.35 + random() * 0.65 });
}
const rockMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({ color: 0x7a8177, roughness: 1 }),
rockData.length
);
rockData.forEach((rock, index) => {
dummy.position.set(rock.x, rock.y + rock.scale * 0.35, rock.z);
dummy.rotation.set(0, random() * Math.PI, 0);
dummy.scale.set(rock.scale, rock.scale * 0.65, rock.scale);
dummy.updateMatrix();
rockMesh.setMatrixAt(index, dummy.matrix);
});
rockMesh.instanceMatrix.needsUpdate = true;
rockMesh.castShadow = true;
scene.add(rockMesh);
// Blocky clouds.
const cloudData = [];
for (let i = 0; i < 15; i++) {
cloudData.push({
x: -45 + random() * 90,
y: 19 + random() * 8,
z: -40 + random() * 75,
sx: 2.5 + random() * 4,
sy: 0.65 + random() * 0.8,
sz: 1.5 + random() * 2.5
});
}
const cloudMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
color: 0xf4fbf7,
roughness: 1,
transparent: true,
opacity: 0.86
}),
cloudData.length
);
cloudData.forEach((cloud, index) => {
dummy.position.set(cloud.x, cloud.y, cloud.z);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(cloud.sx, cloud.sy, cloud.sz);
dummy.updateMatrix();
cloudMesh.setMatrixAt(index, dummy.matrix);
});
cloudMesh.instanceMatrix.needsUpdate = true;
scene.add(cloudMesh);
// -------------------------------------------------------------------------
// Traveler
// -------------------------------------------------------------------------
const traveler = new THREE.Group();
const travelerMaterials = {
body: new THREE.MeshStandardMaterial({ color: 0xef785e, roughness: 0.8 }),
head: new THREE.MeshStandardMaterial({ color: 0xf0c39e, roughness: 0.85 }),
hat: new THREE.MeshStandardMaterial({ color: 0x274d61, roughness: 0.85 }),
pack: new THREE.MeshStandardMaterial({ color: 0x5f8f70, roughness: 0.9 }),
leg: new THREE.MeshStandardMaterial({ color: 0x273f49, roughness: 0.9 })
};
const body = new THREE.Mesh(
new THREE.BoxGeometry(0.85, 1.0, 0.62),
travelerMaterials.body
);
body.position.y = 1.25;
body.castShadow = true;
traveler.add(body);
const head = new THREE.Mesh(
new THREE.BoxGeometry(0.63, 0.63, 0.63),
travelerMaterials.head
);
head.position.y = 2.05;
head.castShadow = true;
traveler.add(head);
const hat = new THREE.Mesh(
new THREE.BoxGeometry(0.78, 0.25, 0.78),
travelerMaterials.hat
);
hat.position.y = 2.45;
hat.castShadow = true;
traveler.add(hat);
const pack = new THREE.Mesh(
new THREE.BoxGeometry(0.65, 0.78, 0.3),
travelerMaterials.pack
);
pack.position.set(0, 1.35, 0.43);
pack.castShadow = true;
traveler.add(pack);
const leftLeg = new THREE.Mesh(
new THREE.BoxGeometry(0.29, 0.65, 0.32),
travelerMaterials.leg
);
leftLeg.position.set(-0.22, 0.35, 0);
leftLeg.castShadow = true;
traveler.add(leftLeg);
const rightLeg = new THREE.Mesh(
new THREE.BoxGeometry(0.29, 0.65, 0.32),
travelerMaterials.leg
);
rightLeg.position.set(0.22, 0.35, 0);
rightLeg.castShadow = true;
traveler.add(rightLeg);
const shadow = new THREE.Mesh(
new THREE.BoxGeometry(1.15, 0.04, 0.95),
new THREE.MeshBasicMaterial({
color: 0x18332d,
transparent: true,
opacity: 0.25
})
);
shadow.position.y = 0.025;
traveler.add(shadow);
scene.add(traveler);
// -------------------------------------------------------------------------
// Bearing logic and route planner
// -------------------------------------------------------------------------
const preferences = {
camp: 50,
fork: 35,
kestrel: 73,
lake: 17
};
const goal = "summit";
function normalizeAngle(angle) {
return ((angle % 360) + 360) % 360;
}
function angleDifference(a, b) {
const difference = Math.abs(normalizeAngle(a) - normalizeAngle(b));
return Math.min(difference, 360 - difference);
}
function bearingBetween(fromId, toId) {
const from = nodes[fromId];
const to = nodes[toId];
const dx = to.x - from.x;
const dz = to.z - from.z;
return normalizeAngle(Math.atan2(dx, -dz) * THREE.MathUtils.RAD2DEG);
}
function cardinalName(bearing) {
const names = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];
return names[Math.round(normalizeAngle(bearing) / 45) % 8];
}
function findBestRoute(start, banned = new Set()) {
let best = null;
let bestScore = Infinity;
function visit(nodeId, path, visited, score, length) {
if (nodeId === goal) {
if (score < bestScore) {
bestScore = score;
best = [...path];
}
return;
}
const options = adjacency[nodeId]
.map(({ edge, next }) => ({ edge, next }))
.filter(
({ edge, next }) =>
!edge.closed &&
!visited.has(next) &&
!banned.has(next)
)
.sort((a, b) => {
const errorA =
angleDifference(preferences[nodeId], bearingBetween(nodeId, a.next)) +
a.edge.length * 0.0001;
const errorB =
angleDifference(preferences[nodeId], bearingBetween(nodeId, b.next)) +
b.edge.length * 0.0001;
return errorA - errorB;
});
for (const { edge, next } of options) {
const bearingError = angleDifference(
preferences[nodeId],
bearingBetween(nodeId, next)
);
visit(
next,
[...path, next],
new Set([...visited, next]),
score + bearingError + edge.length * 0.0001,
length + edge.length
);
}
}
visit(start, [start], new Set([start]), 0, 0);
return best ?? [start];
}
const state = {
running: true,
node: "camp",
edge: null,
edgeFrom: null,
edgeTo: null,
edgeProgress: 0,
edgeLength: 0,
edgePoints: [],
edgeCumulative: [],
traveled: 0,
speed: 3.8,
visited: new Set(["camp"]),
currentHeading: preferences.camp,
activeNode: "camp"
};
let plannedNodes = ["camp"];
let plannedSignature = "";
let lastLoggedSignature = "";
let routeMesh = null;
function currentPlan() {
if (state.edge) {
const banned = new Set(state.visited);
banned.add(state.edgeFrom);
const future = findBestRoute(state.edgeTo, banned);
if (future.length <= 1) {
return [state.edgeFrom, state.edgeTo];
}
return [state.edgeFrom, state.edgeTo, ...future.slice(1)];
}
return findBestRoute(state.node, new Set(state.visited));
}
function plannedEdgeIds(nodeList = plannedNodes) {
const result = [];
for (let i = 1; i < nodeList.length; i++) {
const edge = edgeBetween(nodeList[i - 1], nodeList[i]);
if (edge) result.push(edge.id);
}
return result;
}
function signatureFor(nodeList) {
return plannedEdgeIds(nodeList).join(">");
}
function routeNames(nodeList = plannedNodes) {
const names = [];
for (let i = 1; i < nodeList.length; i++) {
const edge = edgeBetween(nodeList[i - 1], nodeList[i]);
if (edge) names.push(edge.name);
}
return names;
}
function rebuildRouteMesh() {
if (routeMesh) {
scene.remove(routeMesh);
routeMesh.geometry.dispose();
routeMesh.material.dispose();
routeMesh = null;
}
const positions = [];
for (let i = 1; i < plannedNodes.length; i++) {
const edge = edgeBetween(plannedNodes[i - 1], plannedNodes[i]);
if (!edge) continue;
const points = orientedPoints(edge, plannedNodes[i - 1]);
for (let p = 0; p < points.length; p += 2) {
positions.push(points[p]);
}
const last = points[points.length - 1];
if (positions[positions.length - 1] !== last) positions.push(last);
}
if (!positions.length) return;
const geometry = new THREE.BoxGeometry(0.38, 0.18, 0.38);
const material = new THREE.MeshStandardMaterial({
color: 0xffd66b,
emissive: 0x7d5711,
emissiveIntensity: 0.75,
roughness: 0.45
});
routeMesh = new THREE.InstancedMesh(geometry, material, positions.length);
positions.forEach((point, index) => {
dummy.position.set(point.x, point.y + 0.18, point.z);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
routeMesh.setMatrixAt(index, dummy.matrix);
});
routeMesh.instanceMatrix.needsUpdate = true;
scene.add(routeMesh);
}
function updatePlan() {
plannedNodes = currentPlan();
plannedSignature = signatureFor(plannedNodes);
rebuildRouteMesh();
updateRoutePanel();
}
function updateRoutePanel() {
const steps = document.getElementById("routeSteps");
steps.innerHTML = "";
for (let i = 1; i < plannedNodes.length; i++) {
const edge = edgeBetween(plannedNodes[i - 1], plannedNodes[i]);
if (!edge) continue;
const item = document.createElement("div");
item.className = `route-step${edge.closed ? " closed" : ""}`;
item.textContent = edge.name;
steps.appendChild(item);
}
document.getElementById("routeDistance").textContent =
`${plannedDistance().toFixed(1)} units`;
}
// -------------------------------------------------------------------------
// UI and event log
// -------------------------------------------------------------------------
const waypointButtons = document.getElementById("waypointButtons");
const waypointButtonMap = new Map();
for (const id of ["camp", "fork", "kestrel", "lake"]) {
const button = document.createElement("button");
button.textContent = nodes[id].name;
button.addEventListener("click", () => selectNode(id));
waypointButtons.appendChild(button);
waypointButtonMap.set(id, button);
}
function selectNode(id) {
state.activeNode = id;
for (const [nodeId, button] of waypointButtonMap) {
button.classList.toggle("active", nodeId === id);
}
for (const [nodeId, material] of markerMaterials) {
material.emissiveIntensity = nodeId === id ? 1.25 : 0.25;
}
const bearing = preferences[id];
document.getElementById("bearingRange").value = bearing;
updateBearingDisplay();
}
function updateBearingDisplay() {
const bearing = preferences[state.activeNode];
document.getElementById("bearingValue").textContent =
`${String(Math.round(bearing)).padStart(3, "0")}°`;
document.getElementById("bearingName").textContent = cardinalName(bearing);
document.getElementById("needle").style.transform =
`rotate(${bearing}deg)`;
const arrow = arrowGroups.get(state.activeNode);
if (arrow) arrow.rotation.y = -THREE.MathUtils.degToRad(bearing);
}
function updateAllArrows() {
for (const [id, arrow] of arrowGroups) {
arrow.rotation.y = -THREE.MathUtils.degToRad(preferences[id]);
}
}
function addLog(message, type = "") {
const list = document.getElementById("eventLog");
const item = document.createElement("li");
item.className = type;
const time = document.createElement("time");
const now = new Date();
time.textContent = now.toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
second: "2-digit"
});
const text = document.createElement("span");
text.textContent = message;
item.append(time, text);
list.prepend(item);
while (list.children.length > 7) {
list.lastChild.remove();
}
}
function logPlanIfChanged(reason, warning = false) {
if (plannedSignature !== lastLoggedSignature) {
const routeText = routeNames().join(" → ") || "No route";
addLog(
`${reason} Route: ${routeText}.`,
warning ? "warning" : "change"
);
} else if (reason) {
addLog(`${reason} Route unchanged.`);
}
lastLoggedSignature = plannedSignature;
}
const bearingRange = document.getElementById("bearingRange");
bearingRange.addEventListener("input", () => {
preferences[state.activeNode] = Number(bearingRange.value);
updateBearingDisplay();
updateAllArrows();
updatePlan();
});
bearingRange.addEventListener("change", () => {
updatePlan();
logPlanIfChanged(
`${nodes[state.activeNode].name} bearing set to ${bearingRange.value}°.`
);
});
const compass = document.getElementById("compass");
let compassDragging = false;
function setCompassBearing(event) {
const rect = compass.getBoundingClientRect();
const x = event.clientX - (rect.left + rect.width / 2);
const y = event.clientY - (rect.top + rect.height / 2);
const bearing = normalizeAngle(
Math.atan2(x, -y) * THREE.MathUtils.RAD2DEG
);
preferences[state.activeNode] = Math.round(bearing) % 360;
bearingRange.value = preferences[state.activeNode];
updateBearingDisplay();
updateAllArrows();
updatePlan();
}
compass.addEventListener("pointerdown", (event) => {
compassDragging = true;
compass.setPointerCapture(event.pointerId);
setCompassBearing(event);
});
compass.addEventListener("pointermove", (event) => {
if (compassDragging) setCompassBearing(event);
});
compass.addEventListener("pointerup", (event) => {
compassDragging = false;
if (compass.hasPointerCapture(event.pointerId)) {
compass.releasePointerCapture(event.pointerId);
}
logPlanIfChanged(
`${nodes[state.activeNode].name} bearing set to ${preferences[state.activeNode]}°.`
);
});
const passToggle = document.getElementById("passToggle");
passToggle.addEventListener("click", () => {
passEdge.closed = !passEdge.closed;
if (passEdge.closed) {
passEdge.mesh.material.color.setHex(0x8d4943);
barrier.position.y = 1.35;
passLabel.material.color.setHex(0xffaaaa);
passToggle.textContent = "Reopen Kestrel Pass";
passToggle.classList.add("closed");
addLog(
state.edge?.id === "pass"
? "Kestrel Pass closed. The traveler will finish the committed segment, then reroute."
: "Kestrel Pass closed. Recalculating the summit route.",
"warning"
);
} else {
passEdge.mesh.material.color.setHex(0xd9b777);
barrier.position.y = 4.3;
passLabel.material.color.setHex(0xffffff);
passToggle.textContent = "Close Kestrel Pass";
passToggle.classList.remove("closed");
addLog("Kestrel Pass reopened. Recalculating the summit route.");
}
updatePlan();
logPlanIfChanged(
passEdge.closed ? "Kestrel Pass is closed." : "Kestrel Pass is open.",
passEdge.closed
);
});
const pauseButton = document.getElementById("pauseButton");
pauseButton.addEventListener("click", () => {
state.running = !state.running;
pauseButton.textContent = state.running
? "Pause Traveler"
: "Resume Traveler";
});
document.getElementById("restartButton").addEventListener("click", () => {
restartJourney();
});
function restartJourney() {
state.running = true;
state.node = "camp";
state.edge = null;
state.edgeFrom = null;
state.edgeTo = null;
state.edgeProgress = 0;
state.edgeLength = 0;
state.edgePoints = [];
state.edgeCumulative = [];
state.traveled = 0;
state.currentHeading = preferences.camp;
state.visited = new Set(["camp"]);
pauseButton.textContent = "Pause Traveler";
const campNode = nodes.camp;
traveler.position.set(campNode.x, campNode.y + 0.18, campNode.z);
updatePlan();
lastLoggedSignature = plannedSignature;
addLog("Journey restarted at Pine Camp.");
startNextEdge();
}
// -------------------------------------------------------------------------
// Travel along traversable path segments
// -------------------------------------------------------------------------
function startNextEdge() {
if (state.node === goal) {
state.running = false;
pauseButton.textContent = "Traveler Finished";
addLog("Cloud Summit reached. Route complete.");
return;
}
if (plannedNodes.length < 2) return;
const from = plannedNodes[0];
const to = plannedNodes[1];
const edge = edgeBetween(from, to);
if (!edge || edge.closed) return;
state.edge = edge;
state.edgeFrom = from;
state.edgeTo = to;
state.edgeProgress = 0;
state.edgeLength = edge.length;
state.edgePoints = orientedPoints(edge, from);
state.edgeCumulative = orientedCumulative(edge, from);
const sample = samplePolyline(
state.edgePoints,
state.edgeCumulative,
0
);
traveler.position.copy(sample.point);
}
function arriveAtNode() {
const reachedNode = state.edgeTo;
const previousNode = state.edgeFrom;
state.node = reachedNode;
state.edge = null;
state.edgeFrom = null;
state.edgeTo = null;
state.edgeProgress = 0;
state.visited.add(reachedNode);
const node = nodes[reachedNode];
traveler.position.set(node.x, node.y + 0.18, node.z);
if (reachedNode === goal) {
state.running = false;
pauseButton.textContent = "Traveler Finished";
updatePlan();
lastLoggedSignature = plannedSignature;
addLog("Cloud Summit reached. Journey complete.");
return;
}
addLog(`Reached ${node.name}.`);
updatePlan();
lastLoggedSignature = plannedSignature;
startNextEdge();
}
function plannedDistance() {
let distance = 0;
for (let i = 1; i < plannedNodes.length; i++) {
const edge = edgeBetween(plannedNodes[i - 1], plannedNodes[i]);
if (edge) distance += edge.length;
}
return distance;
}
function remainingDistance() {
if (!state.edge) return plannedDistance();
let distance = state.edgeLength - state.edgeProgress;
for (let i = 2; i < plannedNodes.length; i++) {
const edge = edgeBetween(plannedNodes[i - 1], plannedNodes[i]);
if (edge) distance += edge.length;
}
return distance;
}
// -------------------------------------------------------------------------
// Telemetry
// -------------------------------------------------------------------------
let telemetryTimer = 0;
function updateTelemetry(delta) {
telemetryTimer += delta;
if (telemetryTimer < 0.08) return;
telemetryTimer = 0;
const status = document.getElementById("status");
if (state.node === goal) {
status.textContent = "ARRIVED";
status.style.background = "var(--yellow)";
} else if (!state.running) {
status.textContent = "PAUSED";
status.style.background = "var(--muted)";
} else {
status.textContent = "TRAVELING";
status.style.background = "var(--mint)";
}
document.getElementById("distanceTraveled").textContent =
state.traveled.toFixed(1);
document.getElementById("distanceRemaining").textContent =
remainingDistance().toFixed(1);
const heading = Math.round(state.currentHeading);
document.getElementById("currentBearing").textContent =
`${String(heading).padStart(3, "0")}°`;
document.getElementById("headingText").textContent =
`${String(heading).padStart(3, "0")}°`;
const nextEdge = state.edge || (
plannedNodes.length > 1
? edgeBetween(plannedNodes[0], plannedNodes[1])
: null
);
document.getElementById("nextTrail").textContent =
nextEdge?.name ?? "Summit";
}
// -------------------------------------------------------------------------
// Main animation loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
let walkTime = 0;
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (state.running && state.edge) {
const remainingOnEdge = state.edgeLength - state.edgeProgress;
const step = Math.min(remainingOnEdge, state.speed * delta);
state.edgeProgress += step;
state.traveled += step;
walkTime += delta * state.speed * 4.5;
const sample = samplePolyline(
state.edgePoints,
state.edgeCumulative,
state.edgeProgress
);
traveler.position.copy(sample.point);
const heading = normalizeAngle(
Math.atan2(sample.tangent.x, -sample.tangent.z) *
THREE.MathUtils.RAD2DEG
);
state.currentHeading = heading;
traveler.rotation.y = -THREE.MathUtils.degToRad(heading);
const stride = Math.sin(walkTime) * 0.42;
leftLeg.rotation.x = stride;
rightLeg.rotation.x = -stride;
body.position.y = 1.25 + Math.abs(Math.sin(walkTime)) * 0.08;
head.position.y = 2.05 + Math.abs(Math.sin(walkTime)) * 0.08;
if (state.edgeProgress >= state.edgeLength - 0.001) {
arriveAtNode();
}
}
updateCamera();
updateTelemetry(delta);
renderer.render(scene, camera);
}
// -------------------------------------------------------------------------
// Initialize and resize
// -------------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
selectNode("camp");
updateAllArrows();
updatePlan();
lastLoggedSignature = plannedSignature;
const campNode = nodes.camp;
traveler.position.set(campNode.x, campNode.y + 0.18, campNode.z);
addLog(
`Initial route: ${routeNames().join(" → ")}. Click a beacon or use the bearing controls to reroute.`
);
startNextEdge();
animate();
</script>
</body>
</html>
```