Prompt specification
Build or customize the Three.js 3D scene "Mountain pass at three resolutions" 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: Mountain pass at three resolutions
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/mountain-pass-at-three-resolutions-x1303
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows a mountain pass represented at three resolutions. Start with one low-poly reference terrain containing two ridges separated by a narrow traversable saddle. Beside it, show coarse, medium, and fine cubic sampling grids derived from that same surface; do not reshape the valley separately for each panel. Mark the two endpoints of a route and highlight connected open cells in each representation. The coarse version may lose the pass, while the finer versions retain it. Keep a small reference silhouette visible behind each grid so the cause of the difference can be inspected.
Working Three.js Starter (mountain-pass-at-three-resolutions-x1303):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Mountain Pass — Three Resolutions</title>
<style>
:root {
color-scheme: dark;
--bg: #071019;
--panel: rgba(15, 27, 42, 0.88);
--panel-border: rgba(150, 194, 224, 0.17);
--text: #edf6ff;
--muted: #91a7ba;
--cyan: #55e0c1;
--blue: #4b91ae;
--gold: #ffd166;
--red: #ff7085;
--dark-cell: #30374b;
}
* {
box-sizing: border-box;
}
html,
body {
min-height: 100%;
margin: 0;
}
body {
overflow-x: hidden;
background:
radial-gradient(circle at 10% 0%, rgba(40, 111, 132, 0.25), transparent 34rem),
radial-gradient(circle at 90% 12%, rgba(101, 67, 124, 0.22), transparent 31rem),
linear-gradient(145deg, #071019 0%, #091320 55%, #080d17 100%);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
.page {
width: min(1840px, 100%);
margin: 0 auto;
padding: 30px 22px 42px;
}
header {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 24px;
margin-bottom: 22px;
}
.eyebrow {
margin: 0 0 8px;
color: var(--cyan);
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(1.9rem, 3.4vw, 3.55rem);
line-height: 0.98;
letter-spacing: -0.045em;
}
.subtitle {
max-width: 760px;
margin: 12px 0 0;
color: var(--muted);
font-size: 0.95rem;
line-height: 1.55;
}
.toolbar {
flex: 0 0 auto;
display: flex;
gap: 9px;
align-items: center;
}
button {
border: 1px solid rgba(160, 205, 235, 0.2);
border-radius: 10px;
padding: 10px 13px;
background: rgba(25, 43, 61, 0.8);
color: var(--text);
cursor: pointer;
font: inherit;
font-size: 0.8rem;
font-weight: 700;
transition: background 150ms ease, border-color 150ms ease;
}
button:hover {
background: rgba(43, 70, 91, 0.9);
border-color: rgba(85, 224, 193, 0.45);
}
.panels {
display: grid;
grid-template-columns: 1.12fr repeat(3, minmax(0, 1fr));
gap: 14px;
align-items: stretch;
}
.panel {
min-width: 0;
overflow: hidden;
border: 1px solid var(--panel-border);
border-radius: 18px;
background:
linear-gradient(180deg, rgba(25, 43, 61, 0.72), rgba(9, 18, 30, 0.93)),
var(--panel);
box-shadow:
0 22px 60px rgba(0, 0, 0, 0.27),
inset 0 1px rgba(255, 255, 255, 0.025);
}
.panel-head {
min-height: 72px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
padding: 15px 16px 13px;
border-bottom: 1px solid rgba(153, 193, 221, 0.1);
}
.panel-kicker {
margin: 0 0 5px;
color: var(--muted);
font-size: 0.62rem;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.panel h2 {
margin: 0;
font-size: 1rem;
letter-spacing: -0.015em;
}
.panel-meta {
margin: 5px 0 0;
color: #8299ad;
font-size: 0.69rem;
line-height: 1.35;
}
.status {
flex: 0 0 auto;
border: 1px solid rgba(255, 209, 102, 0.28);
border-radius: 999px;
padding: 5px 8px;
background: rgba(255, 209, 102, 0.08);
color: var(--gold);
font-size: 0.58rem;
font-weight: 900;
letter-spacing: 0.08em;
white-space: nowrap;
text-transform: uppercase;
}
.status.good {
border-color: rgba(85, 224, 193, 0.3);
background: rgba(85, 224, 193, 0.08);
color: var(--cyan);
}
.status.bad {
border-color: rgba(255, 112, 133, 0.3);
background: rgba(255, 112, 133, 0.08);
color: var(--red);
}
.viewport {
position: relative;
height: clamp(390px, 52vh, 580px);
overflow: hidden;
isolation: isolate;
touch-action: none;
cursor: grab;
}
.viewport.dragging {
cursor: grabbing;
}
.viewport canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
outline: none;
}
.overlay {
position: absolute;
z-index: 2;
pointer-events: none;
color: #a7bac9;
font-size: 0.62rem;
font-weight: 700;
letter-spacing: 0.04em;
text-shadow: 0 1px 5px #000;
}
.overlay.top-left {
top: 12px;
left: 13px;
}
.overlay.top-right {
top: 12px;
right: 13px;
color: #87a9bb;
text-align: right;
}
.overlay.bottom-left {
bottom: 12px;
left: 13px;
}
.overlay.bottom-right {
right: 13px;
bottom: 12px;
color: #6f8799;
text-align: right;
}
.source-tag {
top: 12px;
right: 12px;
border: 1px solid rgba(129, 183, 211, 0.18);
border-radius: 7px;
padding: 5px 7px;
background: rgba(8, 17, 28, 0.55);
color: #91aec1;
font-size: 0.55rem;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.legend {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 13px 21px;
margin-top: 18px;
padding: 14px 16px;
border: 1px solid rgba(150, 194, 224, 0.13);
border-radius: 13px;
background: rgba(13, 25, 39, 0.66);
color: var(--muted);
font-size: 0.72rem;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 7px;
}
.swatch {
width: 11px;
height: 11px;
border-radius: 3px;
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.15);
}
.swatch.blocked {
background: var(--dark-cell);
}
.swatch.open {
background: var(--blue);
}
.swatch.route {
background: var(--cyan);
}
.swatch.endpoint {
border-radius: 50%;
background: var(--gold);
}
.legend-note {
margin-left: auto;
color: #70889c;
}
.note {
margin: 12px 2px 0;
color: #6f879a;
font-size: 0.68rem;
line-height: 1.5;
}
@media (max-width: 1180px) {
.panels {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.viewport {
height: 480px;
}
}
@media (max-width: 720px) {
.page {
padding: 22px 12px 32px;
}
header {
align-items: flex-start;
flex-direction: column;
}
.toolbar {
width: 100%;
}
.toolbar button {
width: 100%;
}
.panels {
grid-template-columns: 1fr;
}
.viewport {
height: 430px;
}
.legend-note {
width: 100%;
margin-left: 0;
}
}
</style>
</head>
<body>
<main class="page">
<header>
<div>
<p class="eyebrow">One surface · three samplings</p>
<h1>Mountain Pass</h1>
<p class="subtitle">
Every panel samples the same height field. The coarse lattice can skip the
narrow saddle and disconnect the route; finer lattices resolve the low
corridor between the two ridges.
</p>
</div>
<div class="toolbar">
<button id="resetAll" type="button">Reset cameras</button>
</div>
</header>
<section class="panels">
<article class="panel">
<div class="panel-head">
<div>
<p class="panel-kicker">Source</p>
<h2>Low-poly reference terrain</h2>
<p class="panel-meta">Shared analytic field h(x, z)</p>
</div>
<span class="status">SOURCE</span>
</div>
<div class="viewport" id="referenceViewport">
<div class="overlay top-left">TWO RIDGES / ONE SADDLE</div>
<div class="overlay bottom-right">Route axis A → B</div>
</div>
</article>
<article class="panel">
<div class="panel-head">
<div>
<p class="panel-kicker">Sampling 01</p>
<h2>Coarse grid</h2>
<p class="panel-meta">10 × 8 sample positions</p>
</div>
<span class="status bad" id="coarseStatus">ANALYZING</span>
</div>
<div class="viewport" id="coarseViewport">
<div class="overlay source-tag">Source section behind</div>
<div class="overlay bottom-left">Pass limit: 0.48</div>
<div class="overlay bottom-right">Drag · wheel · double-click</div>
</div>
</article>
<article class="panel">
<div class="panel-head">
<div>
<p class="panel-kicker">Sampling 02</p>
<h2>Medium grid</h2>
<p class="panel-meta">21 × 15 sample positions</p>
</div>
<span class="status" id="mediumStatus">ANALYZING</span>
</div>
<div class="viewport" id="mediumViewport">
<div class="overlay source-tag">Source section behind</div>
<div class="overlay bottom-left">Pass limit: 0.48</div>
<div class="overlay bottom-right">Drag · wheel · double-click</div>
</div>
</article>
<article class="panel">
<div class="panel-head">
<div>
<p class="panel-kicker">Sampling 03</p>
<h2>Fine grid</h2>
<p class="panel-meta">35 × 27 sample positions</p>
</div>
<span class="status" id="fineStatus">ANALYZING</span>
</div>
<div class="viewport" id="fineViewport">
<div class="overlay source-tag">Source section behind</div>
<div class="overlay bottom-left">Pass limit: 0.48</div>
<div class="overlay bottom-right">Drag · wheel · double-click</div>
</div>
</article>
</section>
<div class="legend" aria-label="Visualization legend">
<span class="legend-item">
<span class="swatch blocked"></span>
Blocked / above pass limit
</span>
<span class="legend-item">
<span class="swatch open"></span>
Connected open component
</span>
<span class="legend-item">
<span class="swatch route"></span>
Cells connecting A to B
</span>
<span class="legend-item">
<span class="swatch endpoint"></span>
Route endpoints
</span>
<span class="legend-note">
The faint section in each grid is the shared surface sampled along z = 0.
</span>
</div>
<p class="note">
Controls are implemented directly with pointer and wheel events. The camera
changes only the view; it does not alter the terrain or the sampling grids.
</p>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------
// Shared source field. All terrain and all grids are derived from this.
// ---------------------------------------------------------------------
const HALF_X = 2.75;
const HALF_Z = 2.25;
const BASE_Y = -0.78;
const PASS_ELEVATION = 0.48;
const MAX_STEP = 0.32;
function terrainHeight(x, z) {
const ridgeProfile =
0.52 + 0.48 * Math.exp(-0.5 * Math.pow(z / 1.05, 2));
let h = 0.16 + 0.018 * (x * x + z * z);
// Two parallel ridge masses.
h += 2.4 *
Math.exp(-0.5 * Math.pow((x + 0.86) / 0.34, 2)) *
ridgeProfile;
h += 2.4 *
Math.exp(-0.5 * Math.pow((x - 0.86) / 0.34, 2)) *
ridgeProfile;
// A deliberately narrow, low saddle cut between the ridges.
const notchLength =
0.9 + 0.1 * Math.exp(-0.125 * z * z);
h -= 1.03 *
Math.exp(-0.5 * Math.pow(x / 0.18, 2)) *
notchLength;
return Math.max(-0.38, h);
}
function clamp01(v) {
return Math.max(0, Math.min(1, v));
}
function terrainColor(h) {
const valley = new THREE.Color("#184957");
const grass = new THREE.Color("#4d6b62");
const stone = new THREE.Color("#777268");
const snow = new THREE.Color("#d9d0b7");
if (h < 0.35) {
return valley.clone().lerp(grass, clamp01((h + 0.38) / 0.73));
}
if (h < 1.35) {
return grass.clone().lerp(stone, (h - 0.35) / 1.0);
}
return stone.clone().lerp(snow, clamp01((h - 1.35) / 1.25));
}
function addLights(scene) {
scene.add(new THREE.HemisphereLight(0xc9e9ff, 0x251a32, 1.65));
const key = new THREE.DirectionalLight(0xffe2b5, 2.5);
key.position.set(4, 7, 5);
scene.add(key);
const rim = new THREE.DirectionalLight(0x6acbff, 1.25);
rim.position.set(-5, 3, -4);
scene.add(rim);
}
// ---------------------------------------------------------------------
// Renderer and direct camera controls.
// ---------------------------------------------------------------------
const cameraStates = [];
function createScene(viewportId, defaultState) {
const viewport = document.getElementById(viewportId);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.domElement.setAttribute(
"aria-label",
"Interactive three-dimensional terrain panel"
);
viewport.prepend(renderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(40, 1, 0.1, 100);
const state = {
viewport,
renderer,
scene,
camera,
yaw: defaultState.yaw,
pitch: defaultState.pitch,
distance: defaultState.distance,
target: new THREE.Vector3(...defaultState.target),
default: { ...defaultState },
dragging: false,
pointerX: 0,
pointerY: 0
};
cameraStates.push(state);
addLights(scene);
function updateCamera() {
const horizontal = Math.cos(state.pitch) * state.distance;
camera.position.set(
state.target.x + Math.sin(state.yaw) * horizontal,
state.target.y + Math.sin(state.pitch) * state.distance,
state.target.z + Math.cos(state.yaw) * horizontal
);
camera.lookAt(state.target);
}
function resetCamera() {
state.yaw = state.default.yaw;
state.pitch = state.default.pitch;
state.distance = state.default.distance;
state.target.set(...state.default.target);
updateCamera();
}
state.updateCamera = updateCamera;
state.resetCamera = resetCamera;
updateCamera();
viewport.addEventListener("pointerdown", (event) => {
state.dragging = true;
state.pointerX = event.clientX;
state.pointerY = event.clientY;
viewport.setPointerCapture(event.pointerId);
viewport.classList.add("dragging");
});
viewport.addEventListener("pointermove", (event) => {
if (!state.dragging) return;
const dx = event.clientX - state.pointerX;
const dy = event.clientY - state.pointerY;
state.pointerX = event.clientX;
state.pointerY = event.clientY;
state.yaw -= dx * 0.006;
state.pitch = THREE.MathUtils.clamp(
state.pitch + dy * 0.005,
0.28,
1.25
);
updateCamera();
});
function endDrag(event) {
state.dragging = false;
viewport.classList.remove("dragging");
if (viewport.hasPointerCapture(event.pointerId)) {
viewport.releasePointerCapture(event.pointerId);
}
}
viewport.addEventListener("pointerup", endDrag);
viewport.addEventListener("pointercancel", endDrag);
viewport.addEventListener("wheel", (event) => {
event.preventDefault();
state.distance = THREE.MathUtils.clamp(
state.distance + event.deltaY * 0.008,
6.5,
17
);
updateCamera();
}, { passive: false });
viewport.addEventListener("dblclick", resetCamera);
function resize() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(viewport);
resize();
return state;
}
// ---------------------------------------------------------------------
// Shared geometry helpers.
// ---------------------------------------------------------------------
function createLabelSprite(letter, color) {
const canvas = document.createElement("canvas");
canvas.width = 96;
canvas.height = 96;
const context = canvas.getContext("2d");
context.clearRect(0, 0, 96, 96);
context.fillStyle = color;
context.beginPath();
context.arc(48, 48, 35, 0, Math.PI * 2);
context.fill();
context.strokeStyle = "rgba(255,255,255,0.85)";
context.lineWidth = 4;
context.stroke();
context.fillStyle = "#071019";
context.font = "900 42px system-ui";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(letter, 48, 49);
const texture = new THREE.CanvasTexture(canvas);
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(0.36, 0.36, 0.36);
sprite.renderOrder = 20;
return sprite;
}
const endpointAnimations = [];
function addEndpoint(scene, z, letter, color) {
const x = 0;
const h = terrainHeight(x, z);
const poleMaterial = new THREE.MeshBasicMaterial({ color });
const pole = new THREE.Mesh(
new THREE.CylinderGeometry(0.022, 0.022, 0.7, 8),
poleMaterial
);
pole.position.set(x, h + 0.35, z);
scene.add(pole);
const sphereMaterial = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 1.5,
roughness: 0.3,
depthTest: false
});
const sphere = new THREE.Mesh(
new THREE.SphereGeometry(0.095, 16, 12),
sphereMaterial
);
sphere.position.set(x, h + 0.75, z);
sphere.renderOrder = 18;
scene.add(sphere);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.16, 0.018, 6, 28),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.9,
depthTest: false
})
);
ring.rotation.x = Math.PI / 2;
ring.position.set(x, h + 0.035, z);
ring.renderOrder = 18;
scene.add(ring);
const label = createLabelSprite(letter, color);
label.position.set(x, h + 1.05, z);
scene.add(label);
endpointAnimations.push({ sphere, ring, phase: z < 0 ? 0 : Math.PI });
}
function createReferenceTerrain() {
const nx = 38;
const nz = 30;
const positions = [];
const colors = [];
const indices = [];
for (let iz = 0; iz <= nz; iz++) {
const z = -HALF_Z + (2 * HALF_Z * iz) / nz;
for (let ix = 0; ix <= nx; ix++) {
const x = -HALF_X + (2 * HALF_X * ix) / nx;
const h = terrainHeight(x, z);
positions.push(x, h, z);
const color = terrainColor(h);
colors.push(color.r, color.g, color.b);
}
}
const row = nx + 1;
for (let iz = 0; iz < nz; iz++) {
for (let ix = 0; ix < nx; ix++) {
const a = iz * row + ix;
const b = a + 1;
const c = a + row;
const d = c + 1;
indices.push(a, c, b, b, c, d);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(colors, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
const material = new THREE.MeshStandardMaterial({
vertexColors: true,
flatShading: true,
roughness: 0.94,
metalness: 0.02,
side: THREE.DoubleSide
});
const mesh = new THREE.Mesh(geometry, material);
return mesh;
}
function createTerrainSkirt() {
const positions = [];
const colors = [];
const perimeter = [];
for (let i = 0; i <= 38; i++) {
perimeter.push([
-HALF_X + (2 * HALF_X * i) / 38,
-HALF_Z
]);
}
for (let i = 1; i <= 30; i++) {
perimeter.push([
HALF_X,
-HALF_Z + (2 * HALF_Z * i) / 30
]);
}
for (let i = 37; i >= 0; i--) {
perimeter.push([
-HALF_X + (2 * HALF_X * i) / 38,
HALF_Z
]);
}
for (let i = 29; i >= 0; i--) {
perimeter.push([
-HALF_X,
-HALF_Z + (2 * HALF_Z * i) / 30
]);
}
const rock = new THREE.Color("#283343");
function pushTriangle(a, b, c) {
positions.push(...a, ...b, ...c);
for (let i = 0; i < 3; i++) {
colors.push(rock.r, rock.g, rock.b);
}
}
for (let i = 0; i < perimeter.length; i++) {
const p1 = perimeter[i];
const p2 = perimeter[(i + 1) % perimeter.length];
const a = [p1[0], terrainHeight(p1[0], p1[1]), p1[1]];
const b = [p2[0], terrainHeight(p2[0], p2[1]), p2[1]];
const c = [p1[0], BASE_Y, p1[1]];
const d = [p2[0], BASE_Y, p2[1]];
pushTriangle(a, c, b);
pushTriangle(b, c, d);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(colors, 3)
);
geometry.computeVertexNormals();
return new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
flatShading: true,
roughness: 1,
side: THREE.DoubleSide
})
);
}
function createReferencePanel() {
const state = createScene("referenceViewport", {
yaw: 0.28,
pitch: 0.66,
distance: 12.3,
target: [0, 0.55, 0]
});
const terrain = createReferenceTerrain();
state.scene.add(terrain);
state.scene.add(createTerrainSkirt());
const base = new THREE.Mesh(
new THREE.BoxGeometry(5.72, 0.16, 4.72),
new THREE.MeshStandardMaterial({
color: 0x1c2736,
roughness: 0.85
})
);
base.position.y = BASE_Y - 0.08;
state.scene.add(base);
const wire = new THREE.Mesh(
terrain.geometry,
new THREE.MeshBasicMaterial({
color: 0xd5e8f1,
wireframe: true,
transparent: true,
opacity: 0.065,
depthWrite: false
})
);
wire.position.y = 0.008;
state.scene.add(wire);
// The intended route follows the saddle's centerline.
const routePoints = [];
for (let i = 0; i <= 120; i++) {
const z = -HALF_Z + (2 * HALF_Z * i) / 120;
routePoints.push(
new THREE.Vector3(0, terrainHeight(0, z) + 0.075, z)
);
}
const routeCurve = new THREE.CatmullRomCurve3(routePoints);
const route = new THREE.Mesh(
new THREE.TubeGeometry(routeCurve, 180, 0.032, 7, false),
new THREE.MeshStandardMaterial({
color: 0xffd166,
emissive: 0xffb52e,
emissiveIntensity: 0.8,
roughness: 0.4
})
);
state.scene.add(route);
addEndpoint(state.scene, -HALF_Z, "A", "#ffd166");
addEndpoint(state.scene, HALF_Z, "B", "#ff7085");
return state;
}
// ---------------------------------------------------------------------
// Grid construction and connectivity.
// ---------------------------------------------------------------------
function createGridData(nx, nz) {
const nodes = [];
const indexAt = (ix, iz) => iz * nx + ix;
for (let iz = 0; iz < nz; iz++) {
const z = -HALF_Z + (2 * HALF_Z * iz) / (nz - 1);
for (let ix = 0; ix < nx; ix++) {
const x = -HALF_X + (2 * HALF_X * ix) / (nx - 1);
nodes.push({
x,
z,
h: terrainHeight(x, z),
open: terrainHeight(x, z) <= PASS_ELEVATION,
ix,
iz
});
}
}
function neighborIndices(index) {
const node = nodes[index];
const neighbors = [];
if (node.ix > 0) neighbors.push(indexAt(node.ix - 1, node.iz));
if (node.ix < nx - 1) neighbors.push(indexAt(node.ix + 1, node.iz));
if (node.iz > 0) neighbors.push(indexAt(node.ix, node.iz - 1));
if (node.iz < nz - 1) neighbors.push(indexAt(node.ix, node.iz + 1));
return neighbors;
}
function edgeAllowed(a, b) {
return (
nodes[a].open &&
nodes[b].open &&
Math.abs(nodes[a].h - nodes[b].h) <= MAX_STEP
);
}
const component = new Int32Array(nodes.length).fill(-1);
let componentId = 0;
for (let i = 0; i < nodes.length; i++) {
if (!nodes[i].open || component[i] !== -1) continue;
const stack = [i];
component[i] = componentId;
while (stack.length) {
const current = stack.pop();
for (const neighbor of neighborIndices(current)) {
if (component[neighbor] === -1 && edgeAllowed(current, neighbor)) {
component[neighbor] = componentId;
stack.push(neighbor);
}
}
}
componentId++;
}
function nearestNode(point) {
let best = 0;
let bestDistance = Infinity;
for (let i = 0; i < nodes.length; i++) {
const dx = nodes[i].x - point.x;
const dz = nodes[i].z - point.z;
const distance = dx * dx + dz * dz;
if (distance < bestDistance) {
bestDistance = distance;
best = i;
}
}
return best;
}
const start = nearestNode({ x: 0, z: -HALF_Z });
const goal = nearestNode({ x: 0, z: HALF_Z });
const parent = new Int32Array(nodes.length).fill(-2);
const queue = [];
if (nodes[start].open) {
parent[start] = -1;
queue.push(start);
}
let found = false;
for (let qi = 0; qi < queue.length; qi++) {
const current = queue[qi];
if (current === goal) {
found = true;
break;
}
for (const neighbor of neighborIndices(current)) {
if (parent[neighbor] === -2 && edgeAllowed(current, neighbor)) {
parent[neighbor] = current;
queue.push(neighbor);
}
}
}
const path = [];
if (found) {
let current = goal;
while (current !== -1) {
path.push(current);
current = parent[current];
}
path.reverse();
}
const routeComponent = found ? component[goal] : -1;
return {
nx,
nz,
nodes,
neighborIndices,
edgeAllowed,
component,
start,
goal,
path,
found
};
}
function createFloor(scene) {
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(5.9, 4.9),
new THREE.MeshStandardMaterial({
color: 0x101c2a,
roughness: 0.95,
transparent: true,
opacity: 0.88
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.72;
scene.add(floor);
const framePoints = [
new THREE.Vector3(-HALF_X, -0.705, -HALF_Z),
new THREE.Vector3(HALF_X, -0.705, -HALF_Z),
new THREE.Vector3(HALF_X, -0.705, HALF_Z),
new THREE.Vector3(-HALF_X, -0.705, HALF_Z),
new THREE.Vector3(-HALF_X, -0.705, -HALF_Z)
];
const frame = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(framePoints),
new THREE.LineBasicMaterial({
color: 0x6e93aa,
transparent: true,
opacity: 0.38
})
);
scene.add(frame);
}
// A small exact section of the same field, placed behind every grid.
function createSourceSection(scene) {
const group = new THREE.Group();
const shape = new THREE.Shape();
const topPoints = [];
shape.moveTo(-HALF_X, BASE_Y);
for (let i = 0; i <= 120; i++) {
const x = -HALF_X + (2 * HALF_X * i) / 120;
const h = terrainHeight(x, 0);
shape.lineTo(x, h);
topPoints.push(new THREE.Vector3(x, h, 0.012));
}
shape.lineTo(HALF_X, BASE_Y);
shape.closePath();
const fill = new THREE.Mesh(
new THREE.ShapeGeometry(shape),
new THREE.MeshBasicMaterial({
color: 0x849ab8,
transparent: true,
opacity: 0.24,
side: THREE.DoubleSide,
depthWrite: false
})
);
group.add(fill);
const outline = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(topPoints),
new THREE.LineBasicMaterial({
color: 0x9ed9f2,
transparent: true,
opacity: 0.72
})
);
group.add(outline);
const baseline = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-HALF_X, BASE_Y, 0.012),
new THREE.Vector3(HALF_X, BASE_Y, 0.012)
]),
new THREE.LineBasicMaterial({
color: 0x6f8ca3,
transparent: true,
opacity: 0.45
})
);
group.add(baseline);
// Mark the low saddle in the source section.
const saddleHeight = terrainHeight(0, 0);
const saddle = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, BASE_Y, 0.02),
new THREE.Vector3(0, saddleHeight, 0.02)
]),
new THREE.LineBasicMaterial({
color: 0xffd166,
transparent: true,
opacity: 0.9
})
);
group.add(saddle);
group.scale.setScalar(0.73);
group.position.set(0, 0.02, -3.42);
scene.add(group);
}
function createGridPanel({
viewportId,
nx,
nz,
statusId,
cameraOptions
}) {
const state = createScene(viewportId, cameraOptions);
const data = createGridData(nx, nz);
createFloor(state.scene);
createSourceSection(state.scene);
const spacingX = (2 * HALF_X) / (nx - 1);
const spacingZ = (2 * HALF_Z) / (nz - 1);
const cubeSize = Math.min(spacingX, spacingZ) * 0.72;
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.74,
metalness: 0.07
});
const mesh = new THREE.InstancedMesh(
geometry,
material,
data.nodes.length
);
mesh.instanceMatrix.setUsage(THREE.StaticDrawUsage);
const dummy = new THREE.Object3D();
const blockedLow = new THREE.Color("#293347");
const blockedHigh = new THREE.Color("#75576f");
const openLow = new THREE.Color("#347a91");
const openHigh = new THREE.Color("#5bc7c3");
const routeColor = new THREE.Color("#55e0b4");
for (let i = 0; i < data.nodes.length; i++) {
const node = data.nodes[i];
dummy.position.set(node.x, node.h, node.z);
dummy.scale.set(cubeSize, cubeSize, cubeSize);
dummy.updateMatrix();
mesh.setMatrixAt(i, dummy.matrix);
let color;
if (!node.open) {
const t = clamp01((node.h - PASS_ELEVATION) / 2.4);
color = blockedLow.clone().lerp(blockedHigh, t);
} else if (data.found && data.component[i] === data.routeComponent) {
color = routeColor.clone();
} else {
const t = clamp01(node.h / PASS_ELEVATION);
color = openLow.clone().lerp(openHigh, t);
}
mesh.setColorAt(i, color);
}
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
state.scene.add(mesh);
// Draw the connected open-cell graph.
const edgePoints = [];
for (let i = 0; i < data.nodes.length; i++) {
const node = data.nodes[i];
for (const neighborIndex of data.neighborIndices(i)) {
if (neighborIndex <= i) continue;
const neighbor = data.nodes[neighborIndex];
if (
data.edgeAllowed(i, neighborIndex) &&
data.component[i] === data.component[neighborIndex]
) {
edgePoints.push(
new THREE.Vector3(
node.x,
node.h + cubeSize * 0.58,
node.z
),
new THREE.Vector3(
neighbor.x,
neighbor.h + cubeSize * 0.58,
neighbor.z
)
);
}
}
}
const edgeGeometry = new THREE.BufferGeometry().setFromPoints(edgePoints);
const edgeLines = new THREE.LineSegments(
edgeGeometry,
new THREE.LineBasicMaterial({
color: 0x73d6dc,
transparent: true,
opacity: 0.26
})
);
state.scene.add(edgeLines);
if (data.found && data.path.length > 1) {
const pathPoints = data.path.map((index) => {
const node = data.nodes[index];
return new THREE.Vector3(
node.x,
node.h + cubeSize * 0.62,
node.z
);
});
const curve = new THREE.CatmullRomCurve3(pathPoints);
const route = new THREE.Mesh(
new THREE.TubeGeometry(
curve,
Math.max(32, data.path.length * 3),
Math.max(0.018, cubeSize * 0.11),
7,
false
),
new THREE.MeshStandardMaterial({
color: 0xffd166,
emissive: 0xffb72e,
emissiveIntensity: 0.85,
roughness: 0.36
})
);
state.scene.add(route);
}
addEndpoint(state.scene, -HALF_Z, "A", "#ffd166");
addEndpoint(state.scene, HALF_Z, "B", "#ff7085");
const status = document.getElementById(statusId);
status.textContent = data.found ? "PASS CONNECTED" : "PASS CLOSED";
status.classList.toggle("good", data.found);
status.classList.toggle("bad", !data.found);
return state;
}
// ---------------------------------------------------------------------
// Build all panels.
// ---------------------------------------------------------------------
createReferencePanel();
createGridPanel({
viewportId: "coarseViewport",
nx: 10,
nz: 8,
statusId: "coarseStatus",
cameraOptions: {
yaw: 0.38,
pitch: 0.72,
distance: 12.4,
target: [0, 0.48, -0.25]
}
});
createGridPanel({
viewportId: "mediumViewport",
nx: 21,
nz: 15,
statusId: "mediumStatus",
cameraOptions: {
yaw: 0.38,
pitch: 0.72,
distance: 12.4,
target: [0, 0.48, -0.25]
}
});
createGridPanel({
viewportId: "fineViewport",
nx: 35,
nz: 27,
statusId: "fineStatus",
cameraOptions: {
yaw: 0.38,
pitch: 0.72,
distance: 12.4,
target: [0, 0.48, -0.25]
}
});
document.getElementById("resetAll").addEventListener("click", () => {
for (const state of cameraStates) {
state.resetCamera();
}
});
// ---------------------------------------------------------------------
// Animation.
// ---------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
const elapsed = clock.getElapsedTime();
for (const animation of endpointAnimations) {
const pulse = 1 + 0.09 * Math.sin(elapsed * 3 + animation.phase);
animation.sphere.scale.setScalar(pulse);
animation.ring.scale.setScalar(1 + 0.06 * Math.sin(elapsed * 3 + animation.phase));
}
for (const state of cameraStates) {
state.renderer.render(state.scene, state.camera);
}
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
```