Prompt specification
Build or customize the Three.js 3D scene "Map Resolution Changes Rover Planning" 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: Map Resolution Changes Rover Planning
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/map-resolution-changes-rover-planning-x3820
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows rover movement over uneven terrain. Create a route-planning experiment comparing coarse and fine terrain representations. Show obstacles lost in the coarse map and verify the final path against the actual scene geometry. Low-poly.
Working Three.js Starter (map-resolution-changes-rover-planning-x3820):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rover Route Lab — Coarse vs. Fine Terrain Planning</title>
<style>
:root {
--bg: #071218;
--panel: rgba(8, 22, 29, 0.91);
--panel-border: rgba(137, 220, 218, 0.18);
--text: #e8f4f1;
--muted: #91aaa9;
--cyan: #55e6d5;
--pink: #ff628c;
--orange: #ffb347;
--green: #76e29b;
--red: #ff657a;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input { font: inherit; }
button {
color: var(--text);
background: rgba(255, 255, 255, 0.055);
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 8px;
padding: 8px 10px;
cursor: pointer;
transition: 140ms ease;
}
button:hover {
background: rgba(85, 230, 213, 0.12);
border-color: rgba(85, 230, 213, 0.38);
}
button.primary {
background: rgba(85, 230, 213, 0.15);
border-color: rgba(85, 230, 213, 0.4);
}
button.coarse {
background: rgba(255, 98, 140, 0.12);
border-color: rgba(255, 98, 140, 0.34);
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.panel {
position: fixed;
z-index: 10;
background: var(--panel);
border: 1px solid var(--panel-border);
border-radius: 14px;
box-shadow: 0 14px 45px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(13px);
}
#controls {
top: 16px;
left: 16px;
width: 292px;
padding: 15px;
}
#results {
top: 16px;
right: 16px;
width: 305px;
padding: 15px;
}
#maps {
left: 16px;
bottom: 16px;
padding: 12px;
}
h1 {
margin: 0 0 4px;
font-size: 19px;
letter-spacing: -0.02em;
}
h2 {
margin: 0 0 8px;
font-size: 13px;
text-transform: uppercase;
letter-spacing: 0.11em;
color: var(--muted);
}
p {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.eyebrow {
margin-bottom: 7px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
text-transform: uppercase;
letter-spacing: 0.16em;
}
.divider {
height: 1px;
margin: 13px 0;
background: rgba(255, 255, 255, 0.08);
}
.row {
display: flex;
gap: 7px;
align-items: center;
}
.row > * { min-width: 0; }
.spread { justify-content: space-between; }
.field {
display: grid;
grid-template-columns: 1fr 92px;
gap: 8px;
align-items: center;
margin-top: 10px;
}
.field label {
color: var(--muted);
font-size: 12px;
}
input[type="number"] {
width: 100%;
padding: 7px 8px;
color: var(--text);
background: rgba(0, 0, 0, 0.24);
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 7px;
}
input[type="range"] {
width: 100%;
accent-color: var(--cyan);
}
.checks {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px 9px;
margin-top: 9px;
}
.checks label {
display: flex;
gap: 6px;
align-items: center;
color: var(--muted);
font-size: 11px;
cursor: pointer;
}
.checks input { accent-color: var(--cyan); }
.play-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 11px;
}
.play-row button {
min-height: 39px;
font-size: 12px;
font-weight: 700;
}
.small-button {
margin-top: 8px;
width: 100%;
font-size: 11px;
}
.status-card {
margin-top: 9px;
padding: 11px;
background: rgba(255, 255, 255, 0.035);
border: 1px solid rgba(255, 255, 255, 0.075);
border-radius: 10px;
}
.status-card .name {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 5px;
font-size: 13px;
font-weight: 800;
}
.status-card .detail {
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.badge {
padding: 3px 7px;
border-radius: 999px;
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.badge.pass {
color: var(--green);
background: rgba(118, 226, 155, 0.12);
}
.badge.fail {
color: var(--red);
background: rgba(255, 101, 122, 0.13);
}
#collisionList {
margin-top: 8px;
font-size: 11px;
line-height: 1.55;
}
.collision-item {
padding: 6px 8px;
margin-top: 5px;
color: #ffd5dc;
background: rgba(255, 101, 122, 0.08);
border-left: 2px solid var(--red);
border-radius: 4px;
}
.map-grid {
display: flex;
gap: 11px;
}
.map-card {
width: 250px;
}
.map-title {
display: flex;
justify-content: space-between;
margin-bottom: 5px;
font-size: 11px;
font-weight: 800;
}
.map-title span:last-child {
color: var(--muted);
font-size: 9px;
font-weight: 600;
}
.map-card canvas {
display: block;
width: 250px;
height: 166px;
border-radius: 9px;
border: 1px solid rgba(255, 255, 255, 0.1);
background: #0a171c;
}
.map-note {
width: 512px;
margin-top: 8px;
font-size: 10px;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-top: 7px;
font-size: 9px;
color: var(--muted);
}
.legend i {
display: inline-block;
width: 8px;
height: 8px;
margin-right: 4px;
border-radius: 2px;
}
#toast {
position: fixed;
z-index: 30;
left: 50%;
bottom: 22px;
transform: translate(-50%, 20px);
max-width: min(600px, 80vw);
padding: 10px 15px;
color: var(--text);
background: rgba(5, 15, 20, 0.94);
border: 1px solid rgba(85, 230, 213, 0.28);
border-radius: 999px;
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.35);
opacity: 0;
pointer-events: none;
transition: 180ms ease;
font-size: 12px;
text-align: center;
}
#toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
#cameraHint {
position: fixed;
right: 17px;
bottom: 16px;
z-index: 8;
padding: 8px 11px;
color: var(--muted);
background: rgba(7, 18, 24, 0.72);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 9px;
font-size: 10px;
pointer-events: none;
}
@media (max-width: 1050px) {
#controls { width: 250px; }
#results { width: 270px; }
.map-card, .map-card canvas { width: 210px; }
.map-card canvas { height: 140px; }
.map-note { width: 431px; }
}
@media (max-width: 780px) {
#controls {
top: 8px;
left: 8px;
width: 220px;
padding: 10px;
}
#results {
top: 8px;
right: 8px;
width: 220px;
padding: 10px;
}
#maps { display: none; }
#cameraHint { display: none; }
h1 { font-size: 15px; }
.checks { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<div id="viewport"></div>
<section id="controls" class="panel">
<div class="eyebrow">Three.js planning experiment</div>
<h1>Rover Route Lab</h1>
<p>
Compare a center-sampled coarse map with a denser swept-edge map,
then test both routes against the actual low-poly scene.
</p>
<div class="divider"></div>
<div class="field">
<label for="seed">Terrain seed</label>
<div class="row">
<input id="seed" type="number" value="17" min="1" max="999999">
<button id="shuffle" title="Choose a new seed">↻</button>
</div>
</div>
<button id="rebuild" class="small-button primary">Rebuild experiment</button>
<div class="field">
<label for="speed">Rover speed</label>
<input id="speed" type="range" min="1" max="10" value="5" step="0.5">
</div>
<div class="play-row">
<button id="playCoarse" class="coarse">▶ Play coarse</button>
<button id="playFine" class="primary">▶ Play fine</button>
</div>
<button id="resetRover" class="small-button">Reset rover / goal</button>
<div class="divider"></div>
<div class="checks">
<label><input id="showCoarse" type="checkbox" checked> Coarse path</label>
<label><input id="showFine" type="checkbox" checked> Fine path</label>
<label><input id="showObstacles" type="checkbox" checked> Rocks</label>
<label><input id="showCoarseMesh" type="checkbox" checked> Coarse mesh</label>
</div>
</section>
<section id="results" class="panel">
<div class="eyebrow">Actual-geometry verification</div>
<h2>Route report</h2>
<div class="status-card">
<div class="name">
<span style="color:var(--pink)">Coarse plan</span>
<span id="coarseBadge" class="badge">Checking</span>
</div>
<div id="coarseStat" class="detail"></div>
<div id="coarseResult" class="detail" style="margin-top:5px"></div>
</div>
<div class="status-card">
<div class="name">
<span style="color:var(--cyan)">Fine plan</span>
<span id="fineBadge" class="badge">Checking</span>
</div>
<div id="fineStat" class="detail"></div>
<div id="fineResult" class="detail" style="margin-top:5px"></div>
</div>
<div class="divider"></div>
<h2>Detected conflicts</h2>
<div id="collisionList"></div>
<div class="divider"></div>
<h2>Terrain check</h2>
<div id="terrainStat" class="detail"></div>
</section>
<section id="maps" class="panel">
<div class="map-grid">
<div class="map-card">
<div class="map-title">
<span style="color:var(--pink)">COARSE · CENTER SAMPLES</span>
<span>2 m grid</span>
</div>
<canvas id="coarseMap"></canvas>
</div>
<div class="map-card">
<div class="map-title">
<span style="color:var(--cyan)">FINE · SWEPT EDGES</span>
<span>1 m grid</span>
</div>
<canvas id="fineMap"></canvas>
</div>
</div>
<p class="map-note">
Orange dashed rings show actual narrow rocks that the coarse center samples missed.
The fine map samples every 1 m and checks the swept rover footprint between cells.
</p>
<div class="legend">
<span><i style="background:var(--pink)"></i>Coarse route</span>
<span><i style="background:var(--cyan)"></i>Fine route</span>
<span><i style="background:#8c9b9d"></i>Visible rock</span>
<span><i style="background:var(--orange)"></i>Lost narrow rock</span>
</div>
</section>
<div id="toast"></div>
<div id="cameraHint">Drag to orbit · wheel to zoom · double-click to reset camera</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
/* --------------------------------------------------------------------------
Configuration
-------------------------------------------------------------------------- */
const WORLD = {
minX: -24,
maxX: 24,
minZ: -16,
maxZ: 16,
nx: 64,
nz: 44
};
const ROVER_RADIUS = 0.62;
const HIDDEN_ROCK_RADIUS = 0.62;
const START = { x: -20, z: -10 };
const GOAL = { x: 20, z: 10 };
const COLORS = {
fine: 0x55e6d5,
coarse: 0xff628c,
hidden: 0xffb347,
visibleRock: 0x77878a
};
const $ = id => document.getElementById(id);
const viewport = $("viewport");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071218);
scene.fog = new THREE.Fog(0x071218, 58, 105);
const camera = new THREE.PerspectiveCamera(
44,
innerWidth / innerHeight,
0.1,
180
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
viewport.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xbde9ed, 0x263126, 1.65);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffe6c4, 2.35);
sun.position.set(-18, 34, 16);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -32;
sun.shadow.camera.right = 32;
sun.shadow.camera.top = 28;
sun.shadow.camera.bottom = -28;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 85;
sun.shadow.bias = -0.0007;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x52c8ff, 0.65);
rimLight.position.set(24, 12, -25);
scene.add(rimLight);
let dynamicRoot = new THREE.Group();
scene.add(dynamicRoot);
let terrainData = null;
let obstacles = [];
let visibleObstacles = [];
let hiddenObstacles = [];
let coarsePlan = null;
let finePlan = null;
let routes = {};
let playback = null;
let rover = null;
let roverBodyMaterial = null;
let obstacleGroup = null;
let routeGroup = null;
let coarseMeshGroup = null;
let roverFlashUntil = 0;
let toastTimer = null;
/* --------------------------------------------------------------------------
Camera controls: implemented directly, without examples or addons
-------------------------------------------------------------------------- */
const orbit = {
theta: 0.76,
phi: 0.91,
radius: 58,
target: new THREE.Vector3(0, 0, 0),
dragging: false,
lastX: 0,
lastY: 0
};
function updateCamera() {
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + orbit.radius * sinPhi * Math.sin(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + orbit.radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(orbit.target);
}
function resetCamera() {
orbit.theta = 0.76;
orbit.phi = 0.91;
orbit.radius = 58;
orbit.target.set(0, 0, 0);
updateCamera();
}
renderer.domElement.addEventListener("pointerdown", event => {
orbit.dragging = true;
orbit.lastX = event.clientX;
orbit.lastY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!orbit.dragging) return;
const dx = event.clientX - orbit.lastX;
const dy = event.clientY - orbit.lastY;
orbit.lastX = event.clientX;
orbit.lastY = event.clientY;
orbit.theta -= dx * 0.006;
orbit.phi = THREE.MathUtils.clamp(orbit.phi - dy * 0.006, 0.16, 1.43);
updateCamera();
});
function endDrag(event) {
orbit.dragging = false;
if (event.pointerId !== undefined &&
renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener("contextmenu", event => event.preventDefault());
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
24,
86
);
updateCamera();
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
resetCamera();
/* --------------------------------------------------------------------------
Terrain and triangle queries
-------------------------------------------------------------------------- */
function seededValue(seed) {
const x = Math.sin(seed * 91.733 + 4.21) * 43758.5453;
return x - Math.floor(x);
}
function terrainHeight(x, z, seed = Number($("seed").value) || 17) {
const phase = seededValue(seed) * Math.PI * 2;
return (
0.78 * Math.sin(x * 0.245 + phase) +
0.55 * Math.cos(z * 0.305 - phase * 0.63) +
0.32 * Math.sin((x + z) * 0.165 + phase * 0.4) +
0.22 * Math.cos((x - z * 0.55) * 0.42 - phase)
);
}
function triangleContainsAndHeight(triangle, x, z) {
const [a, b, c] = triangle;
const denominator =
(b.z - c.z) * (a.x - c.x) +
(c.x - b.x) * (a.z - c.z);
if (Math.abs(denominator) < 1e-10) return null;
const v =
((b.z - c.z) * (x - c.x) +
(c.x - b.x) * (z - c.z)) / denominator;
const w =
((c.z - a.z) * (x - c.x) +
(a.x - c.x) * (z - c.z)) / denominator;
const u = 1 - v - w;
const epsilon = 1e-6;
if (u < -epsilon || v < -epsilon || w < -epsilon) return null;
return {
y: v * a.y + w * b.y + u * c.y,
normal: new THREE.Vector3()
.crossVectors(
new THREE.Vector3().subVectors(b, a),
new THREE.Vector3().subVectors(c, a)
)
.normalize()
};
}
function groundAt(x, z) {
if (!terrainData) {
return {
y: terrainHeight(x, z),
normal: new THREE.Vector3(0, 1, 0)
};
}
const {
minX, minZ, dx, dz, nx, nz, triangles
} = terrainData;
const ix = THREE.MathUtils.clamp(
Math.floor((x - minX) / dx),
0,
nx - 2
);
const iz = THREE.MathUtils.clamp(
Math.floor((z - minZ) / dz),
0,
nz - 2
);
const index = (iz * nx + ix) * 2;
const first = triangleContainsAndHeight(triangles[index], x, z);
if (first) return first;
const second = triangleContainsAndHeight(triangles[index + 1], x, z);
if (second) return second;
return {
y: terrainHeight(x, z),
normal: new THREE.Vector3(0, 1, 0)
};
}
function disposeDynamicRoot() {
scene.remove(dynamicRoot);
dynamicRoot.traverse(object => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const materials = Array.isArray(object.material)
? object.material
: [object.material];
materials.forEach(material => material.dispose());
}
});
dynamicRoot = new THREE.Group();
scene.add(dynamicRoot);
}
function buildTerrain() {
const nx = WORLD.nx;
const nz = WORLD.nz;
const dx = (WORLD.maxX - WORLD.minX) / nx;
const dz = (WORLD.maxZ - WORLD.minZ) / nz;
const vertices = [];
const triangles = [];
function vertex(ix, iz) {
const x = WORLD.minX + ix * dx;
const z = WORLD.minZ + iz * dz;
return new THREE.Vector3(x, terrainHeight(x, z), z);
}
for (let iz = 0; iz < nz; iz++) {
for (let ix = 0; ix < nx; ix++) {
const a = vertex(ix, iz);
const b = vertex(ix + 1, iz);
const c = vertex(ix, iz + 1);
const d = vertex(ix + 1, iz + 1);
// Both triangles have upward-facing winding.
triangles.push([a, c, b]);
triangles.push([b, c, d]);
}
}
terrainData = {
minX: WORLD.minX,
maxX: WORLD.maxX,
minZ: WORLD.minZ,
maxZ: WORLD.maxZ,
nx,
nz,
dx,
dz,
triangles
};
const positions = [];
const colors = [];
const lowColor = new THREE.Color(0x244642);
const highColor = new THREE.Color(0x8a8055);
function pushTriangle(triangle) {
const averageHeight =
(triangle[0].y + triangle[1].y + triangle[2].y) / 3;
const t = THREE.MathUtils.clamp(
(averageHeight + 1.65) / 3.3,
0,
1
);
const color = lowColor.clone().lerp(highColor, t);
const variation = 0.94 + seededValue(
averageHeight * 193 + triangle[0].x * 3 + triangle[0].z
) * 0.12;
color.multiplyScalar(variation);
triangle.forEach(point => {
positions.push(point.x, point.y, point.z);
colors.push(color.r, color.g, color.b);
});
}
triangles.forEach(pushTriangle);
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(colors, 3)
);
geometry.computeVertexNormals();
const material = new THREE.MeshStandardMaterial({
vertexColors: true,
flatShading: true,
roughness: 0.97,
metalness: 0.02
});
const terrainMesh = new THREE.Mesh(geometry, material);
terrainMesh.receiveShadow = true;
terrainMesh.castShadow = true;
dynamicRoot.add(terrainMesh);
const wire = new THREE.LineSegments(
new THREE.WireframeGeometry(geometry),
new THREE.LineBasicMaterial({
color: 0xc7e5dc,
transparent: true,
opacity: 0.065,
depthWrite: false
})
);
dynamicRoot.add(wire);
}
/* --------------------------------------------------------------------------
Planning helpers
-------------------------------------------------------------------------- */
class MinHeap {
constructor() {
this.items = [];
}
push(item) {
const items = this.items;
items.push(item);
let index = items.length - 1;
while (index > 0) {
const parent = Math.floor((index - 1) / 2);
if (items[parent].f <= item.f) break;
items[index] = items[parent];
index = parent;
}
items[index] = item;
}
pop() {
const items = this.items;
if (!items.length) return null;
const root = items[0];
const last = items.pop();
if (items.length) {
let index = 0;
while (true) {
const left = index * 2 + 1;
const right = left + 1;
if (left >= items.length) break;
let smaller = left;
if (right < items.length && items[right].f < items[left].f) {
smaller = right;
}
if (items[smaller].f >= last.f) break;
items[index] = items[smaller];
index = smaller;
}
items[index] = last;
}
return root;
}
}
function pointSegmentDistance2D(px, pz, ax, az, bx, bz) {
const dx = bx - ax;
const dz = bz - az;
const lengthSquared = dx * dx + dz * dz;
let t = 0;
if (lengthSquared > 1e-12) {
t = THREE.MathUtils.clamp(
((px - ax) * dx + (pz - az) * dz) / lengthSquared,
0,
1
);
}
const qx = ax + t * dx;
const qz = az + t * dz;
return {
distance: Math.hypot(px - qx, pz - qz),
t
};
}
function edgeHitsObstacle(a, b, obstacle) {
const threshold = obstacle.r + ROVER_RADIUS;
return pointSegmentDistance2D(
obstacle.x,
obstacle.z,
a.x,
a.z,
b.x,
b.z
).distance <= threshold;
}
function makePlanningGrid(kind, obstacleList) {
const config = kind === "coarse"
? {
minX: -24,
maxX: 24,
minZ: -16,
maxZ: 16,
step: 2
}
: {
minX: -23,
maxX: 23,
minZ: -15,
maxZ: 15,
step: 1
};
const nx = (config.maxX - config.minX) / config.step + 1;
const nz = (config.maxZ - config.minZ) / config.step + 1;
const count = nx * nz;
const blocked = new Uint8Array(count);
const heights = new Float64Array(count);
for (let iz = 0; iz < nz; iz++) {
for (let ix = 0; ix < nx; ix++) {
const index = iz * nx + ix;
const x = config.minX + ix * config.step;
const z = config.minZ + iz * config.step;
heights[index] = kind === "coarse"
? terrainHeight(x, z)
: groundAt(x, z).y;
// Deliberate coarse-map limitation:
// only the center sample of a coarse cell is tested.
for (const obstacle of obstacleList) {
const distance = Math.hypot(x - obstacle.x, z - obstacle.z);
if (distance <= obstacle.r + ROVER_RADIUS) {
blocked[index] = 1;
break;
}
}
}
}
return {
...config,
nx,
nz,
count,
blocked,
heights,
kind
};
}
function planAStar(kind, obstacleList) {
const grid = makePlanningGrid(kind, obstacleList);
const { nx, nz, step, minX, minZ } = grid;
function indexOf(x, z) {
const ix = Math.round((x - minX) / step);
const iz = Math.round((z - minZ) / step);
return iz * nx + ix;
}
function coordinates(index) {
const ix = index % nx;
const iz = Math.floor(index / nx);
return {
x: minX + ix * step,
z: minZ + iz * step
};
}
const startIndex = indexOf(START.x, START.z);
const goalIndex = indexOf(GOAL.x, GOAL.z);
const gScore = new Float64Array(grid.count);
gScore.fill(Infinity);
const parent = new Int32Array(grid.count);
parent.fill(-1);
const closed = new Uint8Array(grid.count);
const heap = new MinHeap();
const goal = coordinates(goalIndex);
const heuristic = index => {
const p = coordinates(index);
return (Math.abs(p.x - goal.x) + Math.abs(p.z - goal.z)) / step;
};
gScore[startIndex] = 0;
heap.push({ index: startIndex, f: heuristic(startIndex) });
const directions = [
{ x: 1, z: 0 },
{ x: 0, z: 1 },
{ x: -1, z: 0 },
{ x: 0, z: -1 }
];
while (heap.items.length) {
const currentItem = heap.pop();
const current = currentItem.index;
if (closed[current]) continue;
closed[current] = 1;
if (current === goalIndex) {
const nodes = [];
let cursor = current;
while (cursor !== -1) {
nodes.push(coordinates(cursor));
cursor = parent[cursor];
}
nodes.reverse();
return { ...grid, nodes };
}
const currentPosition = coordinates(current);
for (const direction of directions) {
const ix = current % nx + direction.x;
const iz = Math.floor(current / nx) + direction.z;
if (ix < 0 || ix >= nx || iz < 0 || iz >= nz) continue;
const neighbor = iz * nx + ix;
if (closed[neighbor] || grid.blocked[neighbor]) continue;
const neighborPosition = coordinates(neighbor);
// The fine representation checks the swept rover footprint along
// every cell edge. The coarse representation does not.
if (kind === "fine") {
let blockedEdge = false;
for (const obstacle of obstacleList) {
if (edgeHitsObstacle(
currentPosition,
neighborPosition,
obstacle
)) {
blockedEdge = true;
break;
}
}
if (blockedEdge) continue;
}
const heightDifference = Math.abs(
grid.heights[neighbor] - grid.heights[current]
);
const slope = heightDifference / step;
const terrainCost = 1 + Math.min(2.2, slope * 1.7);
const tentative = gScore[current] + step * terrainCost;
if (tentative < gScore[neighbor]) {
gScore[neighbor] = tentative;
parent[neighbor] = current;
heap.push({
index: neighbor,
f: tentative + heuristic(neighbor)
});
}
}
}
console.warn("No route found for", kind);
return { ...grid, nodes: [] };
}
/*
Generate narrow "surprise" rocks from the coarse route.
Their X/Z coordinates are odd/odd:
- the nearest coarse 2 m center is sqrt(2) away, so the coarse cell test misses it;
- the fine 1 m grid samples their exact center;
- the coarse route passes one metre from their centers, creating a real collision.
*/
function deriveHiddenObstacles(routeNodes, visibleList) {
if (!routeNodes || routeNodes.length < 2) return [];
const candidates = [];
for (let i = 0; i < routeNodes.length - 1; i++) {
const a = routeNodes[i];
const b = routeNodes[i + 1];
const midX = (a.x + b.x) / 2;
const midZ = (a.z + b.z) / 2;
let x;
let z;
if (Math.abs(a.x - b.x) > Math.abs(a.z - b.z)) {
x = midX;
z = midZ + (midZ < 15 ? 1 : -1);
} else {
x = midX + (midX < 23 ? 1 : -1);
z = midZ;
}
if (
x < -23 || x > 23 ||
z < -15 || z > 15 ||
!Number.isInteger(x) || !Number.isInteger(z)
) continue;
const nearVisible = visibleList.some(obstacle =>
Math.hypot(x - obstacle.x, z - obstacle.z) <
obstacle.r + ROVER_RADIUS + 1.3
);
if (nearVisible) continue;
candidates.push({
x,
z,
r: HIDDEN_ROCK_RADIUS,
hidden: true,
fraction: i / Math.max(1, routeNodes.length - 1)
});
}
if (!candidates.length) return [];
const selected = [];
const targetFractions = [0.30, 0.60, 0.84];
for (const target of targetFractions) {
const candidate = candidates
.filter(item => !selected.includes(item))
.sort((a, b) =>
Math.abs(a.fraction - target) - Math.abs(b.fraction - target)
)[0];
if (!candidate) continue;
const separated = selected.every(other =>
Math.hypot(candidate.x - other.x, candidate.z - other.z) > 5
);
if (separated) selected.push(candidate);
if (selected.length === 3) break;
}
if (!selected.length) selected.push(candidates[0]);
return selected;
}
/* --------------------------------------------------------------------------
Path densification and actual scene verification
-------------------------------------------------------------------------- */
function densifyPath(nodes) {
const path = [];
for (let i = 0; i < nodes.length - 1; i++) {
const a = nodes[i];
const b = nodes[i + 1];
const length = Math.hypot(b.x - a.x, b.z - a.z);
const subdivisions = Math.max(1, Math.ceil(length / 0.42));
for (let j = 0; j < subdivisions; j++) {
if (i > 0 && j === 0) continue;
const t = j / subdivisions;
const x = THREE.MathUtils.lerp(a.x, b.x, t);
const z = THREE.MathUtils.lerp(a.z, b.z, t);
path.push(new THREE.Vector3(
x,
groundAt(x, z).y + 0.055,
z
));
}
}
if (nodes.length) {
const last = nodes[nodes.length - 1];
path.push(new THREE.Vector3(
last.x,
groundAt(last.x, last.z).y + 0.055,
last.z
));
}
return path;
}
function cumulativeDistances(path) {
const cumulative = [0];
for (let i = 1; i < path.length; i++) {
cumulative.push(
cumulative[i - 1] + path[i].distanceTo(path[i - 1])
);
}
return cumulative;
}
function verifyAgainstActualScene(path, obstacleList) {
const cumulative = cumulativeDistances(path);
const collisions = [];
for (const obstacle of obstacleList) {
const threshold = obstacle.r + ROVER_RADIUS;
let earliest = null;
for (let i = 0; i < path.length - 1; i++) {
const a = path[i];
const b = path[i + 1];
const result = pointSegmentDistance2D(
obstacle.x,
obstacle.z,
a.x,
a.z,
b.x,
b.z
);
if (result.distance <= threshold) {
const distance =
cumulative[i] +
result.t * (cumulative[i + 1] - cumulative[i]);
if (!earliest || distance < earliest.distance) {
earliest = {
obstacle,
distance,
point: new THREE.Vector3(
THREE.MathUtils.lerp(a.x, b.x, result.t),
THREE.MathUtils.lerp(a.y, b.y, result.t),
THREE.MathUtils.lerp(a.z, b.z, result.t)
)
};
}
}
}
if (earliest) collisions.push(earliest);
}
collisions.sort((a, b) => a.distance - b.distance);
let minimumGroundClearance = Infinity;
let maximumGrade = 0;
for (let i = 0; i < path.length - 1; i++) {
const a = path[i];
const b = path[i + 1];
for (let sample = 0; sample <= 4; sample++) {
const t = sample / 4;
const x = THREE.MathUtils.lerp(a.x, b.x, t);
const y = THREE.MathUtils.lerp(a.y, b.y, t);
const z = THREE.MathUtils.lerp(a.z, b.z, t);
const actualGround = groundAt(x, z);
minimumGroundClearance = Math.min(
minimumGroundClearance,
y - actualGround.y
);
const grade = THREE.MathUtils.radToDeg(
Math.acos(THREE.MathUtils.clamp(actualGround.normal.y, -1, 1))
);
maximumGrade = Math.max(maximumGrade, grade);
}
}
for (const point of path) {
const actualGround = groundAt(point.x, point.z);
const grade = THREE.MathUtils.radToDeg(
Math.acos(THREE.MathUtils.clamp(actualGround.normal.y, -1, 1))
);
maximumGrade = Math.max(maximumGrade, grade);
}
return {
collisions,
minimumGroundClearance,
maximumGrade,
length: cumulative[cumulative.length - 1] || 0,
cumulative
};
}
/* --------------------------------------------------------------------------
Scene objects
-------------------------------------------------------------------------- */
function buildCoarseMeshOverlay() {
coarseMeshGroup = new THREE.Group();
const positions = [];
const step = coarsePlan.step;
const minX = coarsePlan.minX;
const minZ = coarsePlan.minZ;
const nx = coarsePlan.nx;
const nz = coarsePlan.nz;
function point(ix, iz) {
const x = minX + ix * step;
const z = minZ + iz * step;
return new THREE.Vector3(x, terrainHeight(x, z) + 0.075, z);
}
for (let iz = 0; iz < nz; iz++) {
for (let ix = 0; ix < nx; ix++) {
if (ix + 1 < nx) {
const a = point(ix, iz);
const b = point(ix + 1, iz);
positions.push(a.x, a.y, a.z, b.x, b.y, b.z);
}
if (iz + 1 < nz) {
const a = point(ix, iz);
const b = point(ix, iz + 1);
positions.push(a.x, a.y, a.z, b.x, b.y, b.z);
}
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
const lines = new THREE.LineSegments(
geometry,
new THREE.LineBasicMaterial({
color: COLORS.coarse,
transparent: true,
opacity: 0.18,
depthWrite: false
})
);
coarseMeshGroup.add(lines);
coarseMeshGroup.visible = $("showCoarseMesh").checked;
dynamicRoot.add(coarseMeshGroup);
}
function buildObstacles() {
obstacleGroup = new THREE.Group();
obstacleGroup.visible = $("showObstacles").checked;
obstacles.forEach((obstacle, index) => {
const geometry = new THREE.IcosahedronGeometry(obstacle.r, 0);
geometry.computeBoundingSphere();
const color = obstacle.hidden ? COLORS.hidden : COLORS.visibleRock;
const material = new THREE.MeshStandardMaterial({
color,
flatShading: true,
roughness: 0.88,
metalness: 0.08,
emissive: obstacle.hidden ? 0x301300 : 0x000000,
emissiveIntensity: obstacle.hidden ? 0.28 : 0
});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(
obstacle.x,
groundAt(obstacle.x, obstacle.z).y + obstacle.r * 0.43,
obstacle.z
);
mesh.rotation.set(
seededValue(index + 2) * 1.7,
seededValue(index + 9) * Math.PI,
seededValue(index + 14) * 0.7
);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.userData.obstacle = obstacle;
obstacleGroup.add(mesh);
if (obstacle.hidden) {
const ringGeometry = new THREE.TorusGeometry(
obstacle.r + 0.38,
0.035,
4,
24
);
const ring = new THREE.Mesh(
ringGeometry,
new THREE.MeshBasicMaterial({
color: COLORS.hidden,
transparent: true,
opacity: 0.78
})
);
ring.rotation.x = Math.PI / 2;
ring.position.set(
obstacle.x,
groundAt(obstacle.x, obstacle.z).y + 0.11,
obstacle.z
);
obstacleGroup.add(ring);
}
});
dynamicRoot.add(obstacleGroup);
}
function makeTextSprite(text, color = "#e8f4f1") {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 64;
const context = canvas.getContext("2d");
context.fillStyle = "rgba(5,15,20,0.78)";
context.beginPath();
context.roundRect(3, 3, 250, 58, 16);
context.fill();
context.strokeStyle = color;
context.lineWidth = 3;
context.stroke();
context.fillStyle = color;
context.font = "bold 27px sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 128, 32);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false
})
);
sprite.scale.set(4.0, 1.0, 1);
return sprite;
}
function buildMarkers() {
const startY = groundAt(START.x, START.z).y;
const goalY = groundAt(GOAL.x, GOAL.z).y;
const startRing = new THREE.Mesh(
new THREE.RingGeometry(0.72, 1.05, 20),
new THREE.MeshBasicMaterial({
color: COLORS.fine,
side: THREE.DoubleSide
})
);
startRing.rotation.x = -Math.PI / 2;
startRing.position.set(START.x, startY + 0.11, START.z);
dynamicRoot.add(startRing);
const startLabel = makeTextSprite("START", "#55e6d5");
startLabel.position.set(START.x, startY + 2.4, START.z);
dynamicRoot.add(startLabel);
const goalRing = new THREE.Mesh(
new THREE.RingGeometry(0.72, 1.05, 20),
new THREE.MeshBasicMaterial({
color: 0xffe08a,
side: THREE.DoubleSide
})
);
goalRing.rotation.x = -Math.PI / 2;
goalRing.position.set(GOAL.x, goalY + 0.11, GOAL.z);
dynamicRoot.add(goalRing);
const pole = new THREE.Mesh(
new THREE.CylinderGeometry(0.055, 0.07, 2.5, 6),
new THREE.MeshStandardMaterial({
color: 0xd9ded8,
flatShading: true
})
);
pole.position.set(GOAL.x, goalY + 1.25, GOAL.z);
pole.castShadow = true;
dynamicRoot.add(pole);
const flag = new THREE.Mesh(
new THREE.ConeGeometry(0.55, 1.2, 3),
new THREE.MeshStandardMaterial({
color: 0xffd36d,
flatShading: true
})
);
flag.position.set(GOAL.x + 0.25, goalY + 2.3, goalZSafe());
flag.rotation.z = -Math.PI / 2;
dynamicRoot.add(flag);
const goalLabel = makeTextSprite("GOAL", "#ffe08a");
goalLabel.position.set(GOAL.x, goalY + 3.0, GOAL.z);
dynamicRoot.add(goalLabel);
}
function goalZSafe() {
return GOAL.z;
}
function buildRouteLines() {
routeGroup = new THREE.Group();
const coarseGeometry = new THREE.BufferGeometry().setFromPoints(
routes.coarse.path.map(point =>
new THREE.Vector3(point.x, point.y + 0.11, point.z)
)
);
const coarseLine = new THREE.Line(
coarseGeometry,
new THREE.LineDashedMaterial({
color: COLORS.coarse,
dashSize: 0.62,
gapSize: 0.34,
transparent: true,
opacity: 0.95
})
);
coarseLine.computeLineDistances();
routeGroup.add(coarseLine);
const fineGeometry = new THREE.BufferGeometry().setFromPoints(
routes.fine.path.map(point =>
new THREE.Vector3(point.x, point.y + 0.14, point.z)
)
);
const fineLine = new THREE.Line(
fineGeometry,
new THREE.LineBasicMaterial({
color: COLORS.fine,
transparent: true,
opacity: 0.98
})
);
routeGroup.add(fineLine);
routeGroup.userData.coarseLine = coarseLine;
routeGroup.userData.fineLine = fineLine;
routeGroup.userData.coarseLine.visible = $("showCoarse").checked;
routeGroup.userData.fineLine.visible = $("showFine").checked;
dynamicRoot.add(routeGroup);
}
function buildRover() {
rover = new THREE.Group();
roverBodyMaterial = new THREE.MeshStandardMaterial({
color: 0xff9b45,
flatShading: true,
roughness: 0.72,
metalness: 0.08,
emissive: 0x000000
});
const body = new THREE.Mesh(
new THREE.BoxGeometry(1.42, 0.48, 1.78),
roverBodyMaterial
);
body.position.y = 0.64;
rover.add(body);
const cabinMaterial = new THREE.MeshStandardMaterial({
color: 0xe7e5d5,
flatShading: true,
roughness: 0.8
});
const cabin = new THREE.Mesh(
new THREE.BoxGeometry(1.0, 0.52, 0.86),
cabinMaterial
);
cabin.position.set(0, 1.08, -0.18);
rover.add(cabin);
const glassMaterial = new THREE.MeshStandardMaterial({
color: 0x163d4b,
flatShading: true,
roughness: 0.26,
metalness: 0.35
});
const glass = new THREE.Mesh(
new THREE.BoxGeometry(1.025, 0.28, 0.88),
glassMaterial
);
glass.position.set(0, 1.16, -0.18);
rover.add(glass);
const wheelMaterial = new THREE.MeshStandardMaterial({
color: 0x151b1d,
flatShading: true,
roughness: 0.95
});
const wheelHolders = [];
for (const side of [-1, 1]) {
for (const z of [-0.62, 0, 0.62]) {
const holder = new THREE.Group();
holder.position.set(side * 0.81, 0.34, z);
const wheel = new THREE.Mesh(
new THREE.CylinderGeometry(0.32, 0.32, 0.24, 10),
wheelMaterial
);
wheel.rotation.z = Math.PI / 2;
holder.add(wheel);
rover.add(holder);
wheelHolders.push(holder);
}
}
const antenna = new THREE.Mesh(
new THREE.CylinderGeometry(0.025, 0.035, 1.25, 6),
new THREE.MeshStandardMaterial({
color: 0x20292b,
flatShading: true
})
);
antenna.position.set(0.42, 1.55, 0.35);
antenna.rotation.z = -0.18;
rover.add(antenna);
const beaconMaterial = new THREE.MeshStandardMaterial({
color: 0x66efff,
emissive: 0x1d9cb3,
emissiveIntensity: 1.2,
flatShading: true
});
const beacon = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.105, 0),
beaconMaterial
);
beacon.position.set(0.42, 2.2, 0.35);
rover.add(beacon);
rover.userData.wheelHolders = wheelHolders;
rover.traverse(object => {
if (object.isMesh) {
object.castShadow = true;
object.receiveShadow = true;
}
});
dynamicRoot.add(rover);
}
/* --------------------------------------------------------------------------
Map insets
-------------------------------------------------------------------------- */
function drawMap(canvas, plan, path, isCoarse) {
const bounds = canvas.getBoundingClientRect();
const width = Math.max(1, bounds.width);
const height = Math.max(1, bounds.height);
const ratio = Math.min(devicePixelRatio, 2);
canvas.width = Math.round(width * ratio);
canvas.height = Math.round(height * ratio);
const context = canvas.getContext("2d");
context.setTransform(ratio, 0, 0, ratio, 0, 0);
context.clearRect(0, 0, width, height);
const margin = 8;
const mapWidth = width - margin * 2;
const mapHeight = height - margin * 2;
const sx = mapWidth / (WORLD.maxX - WORLD.minX);
const sy = mapHeight / (WORLD.maxZ - WORLD.minZ);
function mapX(x) {
return margin + (x - WORLD.minX) * sx;
}
function mapZ(z) {
return margin + (z - WORLD.minZ) * sy;
}
context.fillStyle = "#0a171c";
context.fillRect(0, 0, width, height);
const cellWidth = plan.step * sx;
const cellHeight = plan.step * sy;
for (let iz = 0; iz < plan.nz; iz++) {
for (let ix = 0; ix < plan.nx; ix++) {
const index = iz * plan.nx + ix;
const x = plan.minX + ix * plan.step;
const z = plan.minZ + iz * plan.step;
const h = plan.heights[index];
const light = 25 + THREE.MathUtils.clamp((h + 1.6) / 3.2, 0, 1) * 24;
context.fillStyle = `hsl(165 19% ${light}%)`;
context.fillRect(
mapX(x),
mapZ(z),
cellWidth + 0.6,
cellHeight + 0.6
);
if (plan.blocked[index]) {
context.fillStyle = isCoarse
? "rgba(255,98,140,0.48)"
: "rgba(255,101,122,0.40)";
context.fillRect(
mapX(x),
mapZ(z),
cellWidth + 0.6,
cellHeight + 0.6
);
}
}
}
function drawPath(routePath, color, dashed) {
context.beginPath();
routePath.forEach((point, index) => {
const x = mapX(point.x);
const y = mapZ(point.z);
if (index === 0) context.moveTo(x, y);
else context.lineTo(x, y);
});
context.strokeStyle = color;
context.lineWidth = isCoarse ? 1.8 : 2.0;
context.setLineDash(dashed ? [5, 3] : []);
context.stroke();
context.setLineDash([]);
}
drawPath(path, isCoarse ? "#ff628c" : "#55e6d5", isCoarse);
for (const obstacle of obstacles) {
const x = mapX(obstacle.x);
const y = mapZ(obstacle.z);
const radius = Math.max(3, obstacle.r * ((sx + sy) * 0.5));
if (obstacle.hidden && isCoarse) {
context.beginPath();
context.arc(x, y, radius + 1.5, 0, Math.PI * 2);
context.strokeStyle = "#ffb347";
context.lineWidth = 1.4;
context.setLineDash([3, 2]);
context.stroke();
context.setLineDash([]);
context.fillStyle = "#ffb347";
context.font = "bold 9px sans-serif";
context.fillText("!", x - 2, y + 3);
} else {
context.beginPath();
context.arc(x, y, radius, 0, Math.PI * 2);
context.fillStyle = obstacle.hidden ? "#ffb347" : "#8c9b9d";
context.fill();
if (obstacle.hidden) {
context.strokeStyle = "#ffe0a3";
context.lineWidth = 1;
context.stroke();
}
}
}
context.beginPath();
context.arc(mapX(START.x), mapZ(START.z), 4.2, 0, Math.PI * 2);
context.fillStyle = "#55e6d5";
context.fill();
context.beginPath();
context.arc(mapX(GOAL.x), mapZ(GOAL.z), 4.2, 0, Math.PI * 2);
context.fillStyle = "#ffe08a";
context.fill();
}
/* --------------------------------------------------------------------------
Results and playback
-------------------------------------------------------------------------- */
function formatDistance(value) {
return `${value.toFixed(1)} m`;
}
function updateResultUI() {
const coarseBlocked = coarsePlan.blocked.reduce(
(sum, value) => sum + value,
0
);
const fineBlocked = finePlan.blocked.reduce(
(sum, value) => sum + value,
0
);
$("coarseStat").textContent =
`${coarsePlan.nx * coarsePlan.nz} center samples · ` +
`${coarseBlocked} blocked samples · ` +
`${formatDistance(routes.coarse.verification.length)}`;
$("fineStat").textContent =
`${finePlan.nx * finePlan.nz} node samples + swept edges · ` +
`${fineBlocked} blocked nodes · ` +
`${formatDistance(routes.fine.verification.length)}`;
const coarseVerification = routes.coarse.verification;
const fineVerification = routes.fine.verification;
const coarseHidden = coarseVerification.collisions.filter(
collision => collision.obstacle.hidden
).length;
const fineHidden = fineVerification.collisions.filter(
collision => collision.obstacle.hidden
).length;
if (coarseVerification.collisions.length) {
$("coarseBadge").className = "badge fail";
$("coarseBadge").textContent = "Collision";
$("coarseResult").textContent =
`FAILED · ${coarseVerification.collisions.length} actual rock conflict(s); ` +
`${coarseHidden} narrow rock(s) were absent from coarse occupancy.`;
} else {
$("coarseBadge").className = "badge pass";
$("coarseBadge").textContent = "Clear";
$("coarseResult").textContent =
"PASS · No rock conflicts were found in the actual scene.";
}
if (fineVerification.collisions.length) {
$("fineBadge").className = "badge fail";
$("fineBadge").textContent = "Collision";
$("fineResult").textContent =
`FAILED · ${fineVerification.collisions.length} conflict(s), including ` +
`${fineHidden} narrow rock(s).`;
} else {
$("fineBadge").className = "badge pass";
$("fineBadge").textContent = "Verified";
$("fineResult").textContent =
`PASS · 0 rock conflicts; ${fineHidden} previously lost rocks detected ` +
`and avoided.`;
}
const allCollisions = [
...coarseVerification.collisions.map(item => ({
...item,
route: "Coarse"
})),
...fineVerification.collisions.map(item => ({
...item,
route: "Fine"
}))
];
$("collisionList").innerHTML = allCollisions.length
? allCollisions.map(item => `
<div class="collision-item">
<b>${item.route}:</b> ${item.obstacle.hidden ? "narrow hidden rock" : "visible rock"}
at (${item.obstacle.x.toFixed(1)}, ${item.obstacle.z.toFixed(1)}) ·
contact at ${formatDistance(item.distance)}
</div>
`).join("")
: `<div style="color:var(--green)">No actual-geometry collisions.</div>`;
const maxGrade = Math.max(
coarseVerification.maximumGrade,
fineVerification.maximumGrade
);
const minimumClearance = Math.min(
coarseVerification.minimumGroundClearance,
fineVerification.minimumGroundClearance
);
$("terrainStat").textContent =
`Actual triangulated terrain: ${terrainData.triangles.length.toLocaleString()} triangles. ` +
`Maximum sampled grade ${maxGrade.toFixed(1)}°. ` +
`Minimum rover/ground clearance ${minimumClearance.toFixed(3)} m.`;
drawMap($("coarseMap"), coarsePlan, routes.coarse.path, true);
drawMap($("fineMap"), finePlan, routes.fine.path, false);
}
function showToast(message, duration = 2600) {
clearTimeout(toastTimer);
$("toast").textContent = message;
$("toast").classList.add("visible");
toastTimer = setTimeout(() => {
$("toast").classList.remove("visible");
}, duration);
}
function sampleRoute(route, distance) {
const path = route.path;
const cumulative = route.cumulative;
if (!path.length) return {
position: new THREE.Vector3(),
direction: new THREE.Vector3(0, 0, 1)
};
if (distance <= 0) {
return {
position: path[0].clone(),
direction: path[1].clone().sub(path[0]).normalize()
};
}
const total = cumulative[cumulative.length - 1];
const clamped = THREE.MathUtils.clamp(distance, 0, total);
let low = 0;
let high = cumulative.length - 1;
while (low < high - 1) {
const middle = Math.floor((low + high) / 2);
if (cumulative[middle] <= clamped) low = middle;
else high = middle;
}
const segmentLength = cumulative[high] - cumulative[low];
const t = segmentLength > 1e-8
? (clamped - cumulative[low]) / segmentLength
: 0;
const position = path[low].clone().lerp(path[high], t);
const direction = path[high].clone().sub(path[low]).normalize();
return { position, direction };
}
function orientRover(position, direction) {
const forward = direction.clone().normalize();
const worldUp = new THREE.Vector3(0, 1, 0);
const right = new THREE.Vector3()
.crossVectors(worldUp, forward)
.normalize();
const correctedUp = new THREE.Vector3()
.crossVectors(forward, right)
.normalize();
const basis = new THREE.Matrix4().makeBasis(
right,
correctedUp,
forward
);
rover.quaternion.setFromRotationMatrix(basis);
rover.position.copy(position);
}
function playRoute(type) {
const route = routes[type];
if (!route || !route.path.length) return;
playback = {
type,
distance: 0,
active: true,
stoppedByCollision: false
};
const sample = sampleRoute(route, 0);
orientRover(sample.position, sample.direction);
rover.visible = true;
if (type === "coarse") {
showToast(
"Coarse route: following the center-sampled map. " +
"Playback will stop at the first actual collision."
);
} else {
showToast(
"Fine route: sweeping the rover footprint between 1 m samples. " +
"All previously lost rocks are detected."
);
}
}
function resetRover() {
playback = null;
roverFlashUntil = 0;
if (roverBodyMaterial) {
roverBodyMaterial.emissive.setHex(0x000000);
}
const sample = sampleRoute(routes.fine, 0);
orientRover(sample.position, sample.direction);
}
function updatePlayback(delta) {
if (!playback || !playback.active) return;
const route = routes[playback.type];
const speed = Number($("speed").value);
const verification = route.verification;
const firstCollision = verification.collisions[0];
const limit = firstCollision
? Math.min(route.verification.length, firstCollision.distance)
: route.verification.length;
const previous = playback.distance;
playback.distance = Math.min(
limit,
playback.distance + delta * speed
);
const traveled = playback.distance - previous;
const sample = sampleRoute(route, playback.distance);
orientRover(sample.position, sample.direction);
for (const holder of rover.userData.wheelHolders || []) {
holder.rotation.x -= traveled / 0.32;
}
if (firstCollision && playback.distance >= firstCollision.distance - 0.001) {
playback.active = false;
playback.stoppedByCollision = true;
roverFlashUntil = performance.now() + 1500;
showToast(
`Coarse route stopped: actual collision with ${
firstCollision.obstacle.hidden ? "a narrow hidden rock" : "a visible rock"
} at ${formatDistance(firstCollision.distance)}.`
);
} else if (playback.distance >= route.verification.length - 0.001) {
playback.active = false;
showToast(
"Fine route reached the goal and passed actual-scene verification."
);
}
}
/* --------------------------------------------------------------------------
Experiment construction
-------------------------------------------------------------------------- */
function rebuildExperiment() {
disposeDynamicRoot();
playback = null;
roverFlashUntil = 0;
buildTerrain();
visibleObstacles = [
{ x: -8, z: -4, r: 1.25, hidden: false },
{ x: 4, z: 2, r: 1.15, hidden: false },
{ x: 12, z: 6, r: 1.10, hidden: false },
{ x: -15, z: 7, r: 0.95, hidden: false },
{ x: 15, z: -7, r: 0.90, hidden: false },
{ x: -1, z: -10, r: 0.80, hidden: false }
];
// First derive a provisional coarse route.
const provisionalCoarse = planAStar("coarse", visibleObstacles);
hiddenObstacles = deriveHiddenObstacles(
provisionalCoarse.nodes,
visibleObstacles
);
obstacles = [
...visibleObstacles,
...hiddenObstacles
];
// Replan with the complete scene. The center-sampled coarse map still
// misses the odd/odd narrow rocks.
coarsePlan = planAStar("coarse", obstacles);
finePlan = planAStar("fine", obstacles);
routes.coarse = {
path: densifyPath(coarsePlan.nodes)
};
routes.fine = {
path: densifyPath(finePlan.nodes)
};
routes.coarse.cumulative = cumulativeDistances(routes.coarse.path);
routes.fine.cumulative = cumulativeDistances(routes.fine.path);
routes.coarse.verification = verifyAgainstActualScene(
routes.coarse.path,
obstacles
);
routes.fine.verification = verifyAgainstActualScene(
routes.fine.path,
obstacles
);
buildCoarseMeshOverlay();
buildObstacles();
buildMarkers();
buildRouteLines();
buildRover();
updateResultUI();
resetRover();
showToast(
`Experiment rebuilt: ${hiddenObstacles.length} narrow rock(s) are missing ` +
`from the coarse occupancy map.`
);
}
/* --------------------------------------------------------------------------
UI events
-------------------------------------------------------------------------- */
$("rebuild").addEventListener("click", rebuildExperiment);
$("shuffle").addEventListener("click", () => {
$("seed").value = Math.floor(Math.random() * 999999) + 1;
rebuildExperiment();
});
$("seed").addEventListener("change", rebuildExperiment);
$("playCoarse").addEventListener("click", () => playRoute("coarse"));
$("playFine").addEventListener("click", () => playRoute("fine"));
$("resetRover").addEventListener("click", resetRover);
$("showCoarse").addEventListener("change", event => {
if (routeGroup?.userData.coarseLine) {
routeGroup.userData.coarseLine.visible = event.target.checked;
}
});
$("showFine").addEventListener("change", event => {
if (routeGroup?.userData.fineLine) {
routeGroup.userData.fineLine.visible = event.target.checked;
}
});
$("showObstacles").addEventListener("change", event => {
if (obstacleGroup) obstacleGroup.visible = event.target.checked;
});
$("showCoarseMesh").addEventListener("change", event => {
if (coarseMeshGroup) coarseMeshGroup.visible = event.target.checked;
});
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
if (coarsePlan && finePlan) {
drawMap($("coarseMap"), coarsePlan, routes.coarse.path, true);
drawMap($("fineMap"), finePlan, routes.fine.path, false);
}
});
/* --------------------------------------------------------------------------
Render loop
-------------------------------------------------------------------------- */
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
updatePlayback(delta);
if (roverBodyMaterial) {
if (performance.now() < roverFlashUntil) {
const pulse = 0.35 + Math.abs(Math.sin(performance.now() * 0.018));
roverBodyMaterial.emissive.setHex(0xff203f);
roverBodyMaterial.emissiveIntensity = pulse;
rover.scale.setScalar(1 + pulse * 0.035);
} else {
roverBodyMaterial.emissive.setHex(0x000000);
roverBodyMaterial.emissiveIntensity = 0;
rover.scale.lerp(new THREE.Vector3(1, 1, 1), 0.15);
}
}
if (obstacleGroup) {
for (const child of obstacleGroup.children) {
if (child.isMesh && child.geometry?.type === "TorusGeometry") {
const pulse = 1 + Math.sin(clock.elapsedTime * 3.5) * 0.035;
child.scale.set(pulse, pulse, pulse);
}
}
}
renderer.render(scene, camera);
}
rebuildExperiment();
animate();
setTimeout(() => {
if (routes.fine?.path.length) playRoute("fine");
}, 850);
</script>
</body>
</html>
```