Prompt specification
Build or customize the Three.js 3D scene "Resource-route fragmentation model" 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: Resource-route fragmentation model
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/resource-route-fragmentation-model-x0680
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows a simplified landscape with elephant-like agents and water points; users add a barrier and compare reachable routes under explicit pathfinding rules, avoiding population or conservation forecasts. Low-poly.
Working Three.js Starter (resource-route-fragmentation-model-x0680):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Landscape Route Lab</title>
<style>
:root {
--ink: #19312d;
--muted: #62756f;
--paper: #f7f5ee;
--panel: #fffdf8;
--line: #d9dfd7;
--accent: #df7047;
--baseline: #56798a;
--green: #23856e;
--soft-green: #e4f1eb;
--soft-orange: #fae8df;
--shadow: 0 16px 50px rgba(24, 47, 42, 0.13);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
color: var(--ink);
background: #dce5df;
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, select, input { font: inherit; }
#app {
display: grid;
grid-template-columns: minmax(0, 1fr) 380px;
width: 100%;
height: 100%;
}
#scene {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 20%, #edf3ec 0, #dce5df 72%);
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.scene-header {
position: absolute;
top: 18px;
left: 20px;
z-index: 4;
pointer-events: none;
}
.eyebrow {
margin: 0 0 5px;
color: #48665d;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.scene-title {
margin: 0;
font-size: clamp(22px, 3vw, 36px);
line-height: 1.05;
letter-spacing: -0.035em;
}
.scene-subtitle {
max-width: 430px;
margin: 8px 0 0;
color: #557068;
font-size: 13px;
line-height: 1.45;
}
#modeHint {
position: absolute;
z-index: 5;
left: 50%;
bottom: 56px;
transform: translateX(-50%);
max-width: calc(100% - 40px);
padding: 9px 14px;
border: 1px solid rgba(255,255,255,0.65);
border-radius: 999px;
background: rgba(25, 49, 45, 0.88);
color: white;
box-shadow: var(--shadow);
font-size: 12px;
text-align: center;
pointer-events: none;
backdrop-filter: blur(10px);
}
.camera-help {
position: absolute;
left: 20px;
bottom: 18px;
z-index: 4;
color: #466158;
font-size: 11px;
line-height: 1.55;
pointer-events: none;
}
kbd {
padding: 1px 5px;
border: 1px solid #b8c7bf;
border-bottom-width: 2px;
border-radius: 4px;
background: rgba(255,255,255,0.58);
color: #345149;
font-size: 10px;
font-weight: 700;
}
#toast {
position: absolute;
z-index: 8;
top: 20px;
right: 20px;
max-width: 310px;
padding: 11px 14px;
border: 1px solid #d7ddd4;
border-radius: 12px;
background: rgba(255,253,248,0.94);
box-shadow: var(--shadow);
color: #38564d;
font-size: 12px;
line-height: 1.4;
opacity: 0;
transform: translateY(-8px);
transition: opacity 160ms ease, transform 160ms ease;
pointer-events: none;
}
#toast.visible {
opacity: 1;
transform: translateY(0);
}
#loading {
position: absolute;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
background: #e3ebe5;
color: #49655c;
font-size: 14px;
font-weight: 700;
}
#panel {
position: relative;
z-index: 10;
overflow-y: auto;
border-left: 1px solid rgba(46, 75, 67, 0.12);
background: var(--panel);
box-shadow: -12px 0 38px rgba(31, 55, 49, 0.08);
scrollbar-width: thin;
scrollbar-color: #bdc9c1 transparent;
}
.panel-inner {
padding: 25px 24px 30px;
}
.panel-heading {
margin-bottom: 20px;
}
.panel-heading h1 {
margin: 3px 0 8px;
font-size: 25px;
line-height: 1.08;
letter-spacing: -0.035em;
}
.panel-heading p {
margin: 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.section {
padding: 19px 0;
border-top: 1px solid var(--line);
}
.section:first-of-type {
border-top: 0;
padding-top: 0;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin: 0 0 11px;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.section-note {
color: var(--muted);
font-size: 11px;
font-weight: 500;
letter-spacing: 0;
text-transform: none;
}
.mode-buttons {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
padding: 5px;
border-radius: 12px;
background: #edf0ea;
}
.mode-buttons button {
min-height: 38px;
padding: 7px 8px;
border: 0;
border-radius: 8px;
background: transparent;
color: #536961;
cursor: pointer;
font-size: 12px;
font-weight: 750;
transition: background 120ms ease, color 120ms ease, box-shadow 120ms ease;
}
.mode-buttons button:hover {
color: var(--ink);
background: rgba(255,255,255,0.55);
}
.mode-buttons button.active {
background: white;
color: var(--ink);
box-shadow: 0 2px 8px rgba(37, 66, 58, 0.11);
}
.tool-copy {
min-height: 37px;
margin: 10px 0 12px;
color: var(--muted);
font-size: 12px;
line-height: 1.48;
}
.button-row {
display: flex;
flex-wrap: wrap;
gap: 7px;
}
.small-button {
padding: 8px 11px;
border: 1px solid #ccd6ce;
border-radius: 8px;
background: #fff;
color: #37564d;
cursor: pointer;
font-size: 11px;
font-weight: 750;
}
.small-button:hover:not(:disabled) {
border-color: #9caf9f;
background: #f4f7f3;
}
.small-button:disabled {
opacity: 0.42;
cursor: not-allowed;
}
.small-button.danger {
color: #a44e36;
}
.toggle-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
margin-top: 14px;
padding: 11px 12px;
border: 1px solid #d8e0d8;
border-radius: 10px;
background: #f5f8f4;
}
.toggle-copy strong {
display: block;
margin-bottom: 2px;
font-size: 12px;
}
.toggle-copy span {
color: var(--muted);
font-size: 10px;
line-height: 1.4;
}
.toggle-row input {
width: 17px;
height: 17px;
accent-color: var(--baseline);
cursor: pointer;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-top: 11px;
color: #61746d;
font-size: 10px;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 6px;
}
.legend-line {
width: 24px;
height: 4px;
border-radius: 999px;
background: var(--accent);
}
.legend-line.dashed {
height: 0;
border-top: 3px dashed var(--baseline);
background: transparent;
}
.legend-dot {
width: 10px;
height: 10px;
border-radius: 50%;
background: #3d9fd0;
}
.field-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.field label {
display: block;
margin: 0 0 5px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
}
select {
width: 100%;
height: 39px;
padding: 0 30px 0 10px;
border: 1px solid #ccd6ce;
border-radius: 8px;
outline: none;
background: #fff;
color: var(--ink);
font-size: 12px;
font-weight: 650;
cursor: pointer;
}
select:focus {
border-color: #5b897b;
box-shadow: 0 0 0 3px rgba(76, 133, 115, 0.12);
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-top: 13px;
}
.stat {
min-width: 0;
padding: 10px 9px;
border: 1px solid #dce2db;
border-radius: 10px;
background: #f8f9f5;
}
.stat-label {
display: block;
margin-bottom: 4px;
overflow: hidden;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.04em;
text-overflow: ellipsis;
text-transform: uppercase;
white-space: nowrap;
}
.stat-value {
display: block;
color: var(--ink);
font-size: 18px;
font-weight: 800;
letter-spacing: -0.03em;
}
.stat-value.current { color: var(--accent); }
.stat-value.baseline { color: var(--baseline); }
.route-summary {
margin-top: 10px;
padding: 10px 11px;
border-left: 3px solid var(--accent);
border-radius: 0 8px 8px 0;
background: var(--soft-orange);
color: #704b3c;
font-size: 11px;
line-height: 1.45;
}
.table-wrap {
overflow: hidden;
border: 1px solid #dce2db;
border-radius: 10px;
background: white;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 11px;
}
th {
padding: 9px 8px;
border-bottom: 1px solid #dce2db;
background: #f3f6f2;
color: #6a7b75;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.035em;
text-align: left;
text-transform: uppercase;
}
td {
padding: 10px 8px;
border-bottom: 1px solid #edf0ec;
color: #425c54;
vertical-align: middle;
}
tr:last-child td { border-bottom: 0; }
tbody tr {
cursor: pointer;
transition: background 120ms ease;
}
tbody tr:hover { background: #f8faf7; }
tbody tr.selected { background: #edf4ef; }
.water-name {
display: block;
color: var(--ink);
font-weight: 750;
}
.water-id {
color: #8a9993;
font-size: 9px;
}
.step-count {
display: block;
font-weight: 750;
}
.status-word {
color: var(--accent);
font-weight: 800;
}
.delta.same { color: #6c8078; }
.delta.added { color: #b95b39; }
.rules {
margin: 0;
padding-left: 19px;
color: #596e66;
font-size: 11px;
line-height: 1.65;
}
.rules li + li { margin-top: 3px; }
.rules strong { color: #315149; }
.rule-note {
margin: 11px 0 0;
padding: 9px 10px;
border-radius: 8px;
background: #edf3ef;
color: #4e675e;
font-size: 10px;
line-height: 1.5;
}
.disclaimer {
margin: 15px 0 0;
color: #788881;
font-size: 10px;
line-height: 1.55;
}
@media (max-width: 850px) {
html, body { overflow: auto; }
#app {
grid-template-columns: 1fr;
grid-template-rows: 58vh 42vh;
}
#panel {
border-top: 1px solid rgba(46, 75, 67, 0.12);
border-left: 0;
}
.scene-header {
top: 13px;
left: 14px;
}
.scene-subtitle { display: none; }
.camera-help { left: 14px; bottom: 12px; }
#modeHint { bottom: 43px; }
}
@media (max-width: 480px) {
.panel-inner { padding: 21px 17px 28px; }
.field-grid { grid-template-columns: 1fr; }
.stats { grid-template-columns: 1fr 1fr; }
.stats .stat:last-child { grid-column: 1 / -1; }
}
</style>
</head>
<body>
<main id="app">
<section id="scene" aria-label="Interactive low-poly landscape">
<div class="scene-header">
<p class="eyebrow">Landscape Route Lab</p>
<h1 class="scene-title">Compare routes.<br>Test barriers.</h1>
<p class="scene-subtitle">
Add barriers to the grid, then compare deterministic routes to each water point.
</p>
</div>
<div id="modeHint">Inspect mode · drag to orbit, Shift-drag to pan, scroll to zoom</div>
<div class="camera-help">
<kbd>Drag</kbd> orbit · <kbd>Shift + drag</kbd> pan · <kbd>Scroll</kbd> zoom<br>
Click an elephant-like agent or a water label to select it.
</div>
<div id="toast" role="status" aria-live="polite"></div>
<div id="loading">Building the route landscape…</div>
</section>
<aside id="panel" aria-label="Route comparison controls">
<div class="panel-inner">
<header class="panel-heading">
<p class="eyebrow">Deterministic grid experiment</p>
<h1>Barrier & Reachability</h1>
<p>
Compare a baseline that ignores barriers with the current route that
treats every barrier cell as impassable.
</p>
</header>
<section class="section">
<h2 class="section-title">
Barrier tools
<span class="section-note" id="barrierCount">0 barriers</span>
</h2>
<div class="mode-buttons" role="group" aria-label="Interaction mode">
<button type="button" class="active" data-mode="inspect">Inspect</button>
<button type="button" data-mode="barrier">Add barrier</button>
<button type="button" data-mode="erase">Erase</button>
</div>
<p class="tool-copy" id="toolCopy">
Select an agent or water point. Drag on the landscape to orbit the camera.
</p>
<div class="button-row">
<button type="button" class="small-button" id="undoButton" disabled>Undo barrier</button>
<button type="button" class="small-button danger" id="clearButton" disabled>Clear barriers</button>
</div>
<label class="toggle-row" for="baselineToggle">
<span class="toggle-copy">
<strong>Overlay baseline route</strong>
<span>Dashed route ignores all barriers.</span>
</span>
<input type="checkbox" id="baselineToggle" checked>
</label>
<div class="legend" aria-label="Route legend">
<span class="legend-item"><i class="legend-line"></i> Current route</span>
<span class="legend-item"><i class="legend-line dashed"></i> Baseline</span>
<span class="legend-item"><i class="legend-dot"></i> Water point</span>
</div>
</section>
<section class="section">
<h2 class="section-title">Selected comparison</h2>
<div class="field-grid">
<div class="field">
<label for="agentSelect">Starting agent</label>
<select id="agentSelect"></select>
</div>
<div class="field">
<label for="waterSelect">Destination</label>
<select id="waterSelect"></select>
</div>
</div>
<div class="stats">
<div class="stat">
<span class="stat-label">Current</span>
<span class="stat-value current" id="currentSteps">—</span>
</div>
<div class="stat">
<span class="stat-label">Baseline</span>
<span class="stat-value baseline" id="baselineSteps">—</span>
</div>
<div class="stat">
<span class="stat-label">Reachable now</span>
<span class="stat-value" id="reachableCount">—</span>
</div>
</div>
<div class="route-summary" id="routeSummary">
Select a route to inspect its comparison.
</div>
</section>
<section class="section">
<h2 class="section-title">
Reachability table
<span class="section-note">Steps from selected agent</span>
</h2>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Water point</th>
<th>Baseline</th>
<th>Current</th>
<th>Δ</th>
</tr>
</thead>
<tbody id="routeTable"></tbody>
</table>
</div>
</section>
<section class="section">
<h2 class="section-title">Explicit pathfinding rules</h2>
<ul class="rules">
<li><strong>Movement:</strong> four orthogonal neighbors only; diagonals are forbidden.</li>
<li><strong>Cost:</strong> every cell-to-cell step costs exactly 1.</li>
<li><strong>Shortest path:</strong> breadth-first search returns a minimum-step route.</li>
<li><strong>Barriers:</strong> current routes cannot enter or cross a barrier cell.</li>
<li><strong>Water:</strong> a water cell is traversable and may be the route endpoint.</li>
<li><strong>Deterministic tie-break:</strong> neighbors are tested north, east, south, west.</li>
</ul>
<p class="rule-note">
Baseline and current routes use the same starting agent, destination,
movement rules, and step cost. Only barrier occupancy differs.
</p>
</section>
<p class="disclaimer">
Static reachability and route comparison only. The agents are visual
markers; this tool does not predict population, behavior, conservation
outcomes, or future conditions.
</p>
</div>
</aside>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------
// DOM and state
// ---------------------------------------------------------------------
const sceneElement = document.getElementById("scene");
const panel = document.getElementById("panel");
const loading = document.getElementById("loading");
const toast = document.getElementById("toast");
const modeHint = document.getElementById("modeHint");
const toolCopy = document.getElementById("toolCopy");
const agentSelect = document.getElementById("agentSelect");
const waterSelect = document.getElementById("waterSelect");
const routeTable = document.getElementById("routeTable");
const currentStepsElement = document.getElementById("currentSteps");
const baselineStepsElement = document.getElementById("baselineSteps");
const reachableCountElement = document.getElementById("reachableCount");
const routeSummary = document.getElementById("routeSummary");
const baselineToggle = document.getElementById("baselineToggle");
const undoButton = document.getElementById("undoButton");
const clearButton = document.getElementById("clearButton");
const barrierCount = document.getElementById("barrierCount");
const COLS = 24;
const ROWS = 18;
const CELL = 1.15;
const WIDTH = COLS * CELL;
const DEPTH = ROWS * CELL;
const agents = [
{ id: "A1", name: "A1 · Western herd", x: 3, z: 14, yaw: -0.55 },
{ id: "A2", name: "A2 · Eastern herd", x: 20, z: 14, yaw: 2.45 },
{ id: "A3", name: "A3 · Central herd", x: 11, z: 9, yaw: 0.35 }
];
const waters = [
{ id: "W1", name: "North spring", x: 7, z: 3 },
{ id: "W2", name: "East watering hole", x: 19, z: 3 },
{ id: "W3", name: "South pool", x: 18, z: 14 },
{ id: "W4", name: "West wetland", x: 4, z: 9 }
];
let selectedAgentId = "A1";
let selectedWaterId = "W1";
let mode = "inspect";
let barriers = [];
let toastTimer = 0;
// ---------------------------------------------------------------------
// Renderer, scene, and custom camera controls
// ---------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce5df);
scene.fog = new THREE.Fog(0xdce5df, 55, 100);
const camera = new THREE.PerspectiveCamera(
42,
sceneElement.clientWidth / sceneElement.clientHeight,
0.1,
150
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(sceneElement.clientWidth, sceneElement.clientHeight, false);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.domElement.setAttribute("tabindex", "0");
renderer.domElement.setAttribute(
"aria-label",
"Interactive 3D route landscape. Drag to orbit and click agents or water points."
);
sceneElement.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xf6fff8, 0x718276, 2.0);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff2d8, 2.8);
sun.position.set(-18, 30, 20);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -28;
sun.shadow.camera.right = 28;
sun.shadow.camera.top = 24;
sun.shadow.camera.bottom = -24;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 80;
sun.shadow.bias = -0.0005;
scene.add(sun);
const cameraTarget = new THREE.Vector3(0, 0, 0);
const spherical = new THREE.Spherical(40, 0.87, 0.73);
function updateCamera() {
const offset = new THREE.Vector3().setFromSpherical(spherical);
camera.position.copy(cameraTarget).add(offset);
camera.lookAt(cameraTarget);
}
updateCamera();
function resize() {
const width = sceneElement.clientWidth;
const height = sceneElement.clientHeight;
if (!width || !height) return;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
new ResizeObserver(resize).observe(sceneElement);
// ---------------------------------------------------------------------
// Materials and low-poly helpers
// ---------------------------------------------------------------------
const tileMaterials = [
new THREE.MeshStandardMaterial({ color: 0x91a77c, roughness: 1 }),
new THREE.MeshStandardMaterial({ color: 0x9aae83, roughness: 1 }),
new THREE.MeshStandardMaterial({ color: 0x87a078, roughness: 1 }),
new THREE.MeshStandardMaterial({ color: 0xa2b38a, roughness: 1 }),
new THREE.MeshStandardMaterial({ color: 0x91aa86, roughness: 1 })
];
const elephantMaterial = new THREE.MeshStandardMaterial({
color: 0x8e9691,
roughness: 0.95,
flatShading: true
});
const elephantLightMaterial = new THREE.MeshStandardMaterial({
color: 0xa7aca7,
roughness: 0.95,
flatShading: true
});
const earMaterial = new THREE.MeshStandardMaterial({
color: 0x777f7b,
roughness: 1,
side: THREE.DoubleSide,
flatShading: true
});
const tuskMaterial = new THREE.MeshStandardMaterial({
color: 0xe8dfc5,
roughness: 0.9,
flatShading: true
});
const eyeMaterial = new THREE.MeshBasicMaterial({ color: 0x17201d });
const waterMaterial = new THREE.MeshStandardMaterial({
color: 0x3a9fc8,
roughness: 0.3,
metalness: 0.05,
flatShading: true
});
const waterInnerMaterial = new THREE.MeshStandardMaterial({
color: 0x78cbe0,
roughness: 0.25,
transparent: true,
opacity: 0.88,
flatShading: true
});
const barrierMaterial = new THREE.MeshStandardMaterial({
color: 0xc65d39,
roughness: 0.9,
flatShading: true
});
const barrierPostMaterial = new THREE.MeshStandardMaterial({
color: 0x77452f,
roughness: 1,
flatShading: true
});
const currentRouteMaterial = new THREE.MeshBasicMaterial({ color: 0xef7549 });
const baselineRouteMaterial = new THREE.MeshBasicMaterial({ color: 0x56798a });
const previewRouteMaterial = new THREE.MeshBasicMaterial({
color: 0xef7549,
transparent: true,
opacity: 0.52,
depthTest: false
});
function cylinderBetween(a, b, radius, material, radialSegments = 6) {
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
const geometry = new THREE.CylinderGeometry(
radius,
radius,
length,
radialSegments
);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
return mesh;
}
function makeLabel(text, background = "#29483f", foreground = "#ffffff") {
const canvas = document.createElement("canvas");
canvas.width = 320;
canvas.height = 96;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = background;
context.beginPath();
context.roundRect(5, 8, 310, 80, 22);
context.fill();
context.fillStyle = foreground;
context.font = "700 29px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 160, 49);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(1.65, 0.50, 1);
sprite.renderOrder = 20;
return sprite;
}
// ---------------------------------------------------------------------
// Terrain
// ---------------------------------------------------------------------
const terrainGroup = new THREE.Group();
scene.add(terrainGroup);
const tileHeights = new Float32Array(COLS * ROWS);
const tileGeometry = new THREE.BoxGeometry(CELL * 0.94, 1, CELL * 0.94);
let randomSeed = 417;
function seededRandom() {
randomSeed = (randomSeed * 1664525 + 1013904223) >>> 0;
return randomSeed / 4294967296;
}
function cellIndex(x, z) {
return z * COLS + x;
}
function cellTop(x, z) {
return -0.06 + tileHeights[cellIndex(x, z)];
}
function cellWorld(x, z, extra = 0) {
return new THREE.Vector3(
(x - (COLS - 1) / 2) * CELL,
cellTop(x, z) + extra,
(z - (ROWS - 1) / 2) * CELL
);
}
for (let z = 0; z < ROWS; z++) {
for (let x = 0; x < COLS; x++) {
const index = cellIndex(x, z);
const wave = Math.sin(x * 0.62) * 0.035 + Math.cos(z * 0.54) * 0.028;
const height = 0.17 + seededRandom() * 0.22 + wave;
tileHeights[index] = height;
const material = tileMaterials[Math.floor(seededRandom() * tileMaterials.length)];
const tile = new THREE.Mesh(tileGeometry, material);
tile.scale.y = height;
tile.position.set(
(x - (COLS - 1) / 2) * CELL,
-0.06 + height / 2,
(z - (ROWS - 1) / 2) * CELL
);
tile.receiveShadow = true;
terrainGroup.add(tile);
}
}
const boardBase = new THREE.Mesh(
new THREE.BoxGeometry(WIDTH + 0.55, 0.55, DEPTH + 0.55),
new THREE.MeshStandardMaterial({ color: 0x786b50, roughness: 1 })
);
boardBase.position.y = -0.35;
boardBase.receiveShadow = true;
terrainGroup.add(boardBase);
const outsideGround = new THREE.Mesh(
new THREE.PlaneGeometry(120, 120),
new THREE.MeshStandardMaterial({ color: 0xcbd6c5, roughness: 1 })
);
outsideGround.rotation.x = -Math.PI / 2;
outsideGround.position.y = -0.64;
outsideGround.receiveShadow = true;
scene.add(outsideGround);
function addTree(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, -0.62, z);
group.scale.setScalar(scale);
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.13, 0.19, 1.4, 5),
new THREE.MeshStandardMaterial({ color: 0x765337, roughness: 1 })
);
trunk.position.y = 0.7;
trunk.castShadow = true;
const crown = new THREE.Mesh(
new THREE.ConeGeometry(0.82, 2.15, 7),
new THREE.MeshStandardMaterial({
color: 0x557b5d,
roughness: 1,
flatShading: true
})
);
crown.position.y = 2.05;
crown.castShadow = true;
const crownTop = new THREE.Mesh(
new THREE.ConeGeometry(0.57, 1.55, 7),
new THREE.MeshStandardMaterial({
color: 0x6d916b,
roughness: 1,
flatShading: true
})
);
crownTop.position.y = 2.78;
crownTop.castShadow = true;
group.add(trunk, crown, crownTop);
scene.add(group);
}
[
[-18, -13, 1.05], [-14, 13, 0.88], [17, 13, 1.1],
[19, -13, 0.9], [-19, 2, 0.72], [10, -15, 0.8]
].forEach(([x, z, scale]) => addTree(x, z, scale));
function addRock(x, z, scale = 1) {
const rock = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.65, 0),
new THREE.MeshStandardMaterial({
color: 0x879187,
roughness: 1,
flatShading: true
})
);
rock.position.set(x, -0.18, z);
rock.scale.set(scale * 1.2, scale * 0.7, scale);
rock.rotation.set(seededRandom(), seededRandom(), seededRandom());
rock.castShadow = true;
rock.receiveShadow = true;
scene.add(rock);
}
[
[-16, -7, 0.7], [-16.5, 8, 0.9], [16, 9.5, 0.75],
[15, -11.5, 0.85], [-10, 14, 0.5], [7, -13.4, 0.6]
].forEach(([x, z, scale]) => addRock(x, z, scale));
// Invisible plane used only for reliable grid picking.
const pickPlane = new THREE.Mesh(
new THREE.PlaneGeometry(WIDTH, DEPTH),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false
})
);
pickPlane.rotation.x = -Math.PI / 2;
pickPlane.position.y = 0;
scene.add(pickPlane);
// ---------------------------------------------------------------------
// Elephant-like low-poly agents
// ---------------------------------------------------------------------
const pickRoots = [];
const agentGroups = new Map();
const waterGroups = new Map();
function buildElephant(agent) {
const group = new THREE.Group();
group.userData.pickType = "agent";
group.userData.id = agent.id;
group.rotation.y = agent.yaw;
const body = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.50, 0),
elephantMaterial
);
body.scale.set(1.18, 0.78, 0.78);
body.position.set(0, 0.65, -0.08);
body.castShadow = true;
group.add(body);
const shoulder = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.42, 1),
elephantLightMaterial
);
shoulder.scale.set(0.92, 0.95, 0.90);
shoulder.position.set(0, 0.74, 0.23);
shoulder.castShadow = true;
group.add(shoulder);
const head = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.31, 1),
elephantMaterial
);
head.scale.set(0.85, 0.90, 0.80);
head.position.set(0, 0.78, 0.51);
head.castShadow = true;
group.add(head);
for (const side of [-1, 1]) {
const ear = new THREE.Mesh(
new THREE.CircleGeometry(0.29, 5),
earMaterial
);
ear.scale.set(0.85, 1.18, 1);
ear.position.set(side * 0.31, 0.83, 0.40);
ear.rotation.set(0.08, side * Math.PI / 2, side * 0.12);
ear.castShadow = true;
group.add(ear);
const eye = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.043, 0),
eyeMaterial
);
eye.position.set(side * 0.16, 0.89, 0.73);
group.add(eye);
const tusk = new THREE.Mesh(
new THREE.ConeGeometry(0.045, 0.32, 5),
tuskMaterial
);
tusk.position.set(side * 0.13, 0.59, 0.74);
tusk.rotation.x = Math.PI / 2.45;
tusk.rotation.z = side * -0.13;
tusk.castShadow = true;
group.add(tusk);
}
const legPositions = [
[-0.28, -0.25], [0.28, -0.25],
[-0.28, 0.27], [0.28, 0.27]
];
for (const [x, z] of legPositions) {
const leg = new THREE.Mesh(
new THREE.CylinderGeometry(0.095, 0.12, 0.51, 5),
elephantMaterial
);
leg.position.set(x, 0.25, z);
leg.castShadow = true;
group.add(leg);
}
const trunkPoints = [
new THREE.Vector3(0, 0.70, 0.70),
new THREE.Vector3(0, 0.48, 0.91),
new THREE.Vector3(0, 0.28, 1.00),
new THREE.Vector3(0, 0.14, 0.96)
];
for (let i = 0; i < trunkPoints.length - 1; i++) {
const trunkPart = cylinderBetween(
trunkPoints[i],
trunkPoints[i + 1],
0.075 - i * 0.008,
elephantMaterial,
5
);
trunkPart.castShadow = true;
group.add(trunkPart);
}
const tail = cylinderBetween(
new THREE.Vector3(0, 0.72, -0.47),
new THREE.Vector3(0.03, 0.35, -0.59),
0.025,
elephantMaterial,
5
);
group.add(tail);
const label = makeLabel(agent.id, "#35574c");
label.position.set(0, 1.70, 0);
group.add(label);
group.position.copy(cellWorld(agent.x, agent.z));
group.userData.baseY = group.position.y;
scene.add(group);
pickRoots.push(group);
agentGroups.set(agent.id, group);
}
agents.forEach(buildElephant);
// ---------------------------------------------------------------------
// Water points
// ---------------------------------------------------------------------
for (const water of waters) {
const group = new THREE.Group();
group.userData.pickType = "water";
group.userData.id = water.id;
group.position.copy(cellWorld(water.x, water.z, 0.04));
const outer = new THREE.Mesh(
new THREE.CylinderGeometry(0.46, 0.50, 0.13, 8),
waterMaterial
);
outer.castShadow = true;
outer.receiveShadow = true;
group.add(outer);
const inner = new THREE.Mesh(
new THREE.CylinderGeometry(0.32, 0.36, 0.145, 8),
waterInnerMaterial
);
inner.position.y = 0.025;
group.add(inner);
const reedMaterial = new THREE.MeshStandardMaterial({
color: 0x6d8b50,
roughness: 1,
flatShading: true
});
for (let i = 0; i < 3; i++) {
const angle = i * 2.1 + water.x;
const reed = new THREE.Mesh(
new THREE.CylinderGeometry(0.018, 0.025, 0.34, 4),
reedMaterial
);
reed.position.set(
Math.cos(angle) * 0.40,
0.19,
Math.sin(angle) * 0.40
);
group.add(reed);
}
const label = makeLabel(water.id, "#287b9c");
label.position.set(0, 1.15, 0);
group.add(label);
scene.add(group);
pickRoots.push(group);
waterGroups.set(water.id, group);
}
const selectionRing = new THREE.Mesh(
new THREE.TorusGeometry(0.64, 0.045, 6, 28),
new THREE.MeshBasicMaterial({ color: 0xf5a14c })
);
selectionRing.rotation.x = Math.PI / 2;
scene.add(selectionRing);
const targetRing = new THREE.Mesh(
new THREE.TorusGeometry(0.60, 0.045, 6, 28),
new THREE.MeshBasicMaterial({ color: 0x3a9fc8 })
);
targetRing.rotation.x = Math.PI / 2;
scene.add(targetRing);
// ---------------------------------------------------------------------
// Barriers
// ---------------------------------------------------------------------
const barrierRoot = new THREE.Group();
scene.add(barrierRoot);
const previewRoot = new THREE.Group();
scene.add(previewRoot);
function rasterizeLine(start, end) {
// Bresenham line. The resulting occupied cells form a continuous chain.
const cells = [];
let x = start.x;
let z = start.z;
const dx = Math.abs(end.x - start.x);
const dz = Math.abs(end.z - start.z);
const sx = start.x < end.x ? 1 : -1;
const sz = start.z < end.z ? 1 : -1;
let error = dx - dz;
while (true) {
cells.push({ x, z });
if (x === end.x && z === end.z) break;
const doubledError = error * 2;
if (doubledError > -dz) {
error -= dz;
x += sx;
}
if (doubledError < dx) {
error += dx;
z += sz;
}
}
return cells;
}
function makeBarrierVisual(cells) {
const group = new THREE.Group();
for (let i = 0; i < cells.length - 1; i++) {
const a = cells[i];
const b = cells[i + 1];
const rope = cylinderBetween(
cellWorld(a.x, a.z, 0.45),
cellWorld(b.x, b.z, 0.45),
0.055,
barrierMaterial,
6
);
rope.castShadow = true;
group.add(rope);
}
const postEvery = Math.max(1, Math.floor(cells.length / 5));
for (let i = 0; i < cells.length; i += postEvery) {
const cell = cells[i];
const top = cellTop(cell.x, cell.z);
const post = new THREE.Mesh(
new THREE.CylinderGeometry(0.075, 0.095, 0.72, 6),
barrierPostMaterial
);
post.position.set(
(cell.x - (COLS - 1) / 2) * CELL,
top + 0.30,
(cell.z - (ROWS - 1) / 2) * CELL
);
post.castShadow = true;
group.add(post);
const cap = new THREE.Mesh(
new THREE.ConeGeometry(0.095, 0.16, 6),
barrierMaterial
);
cap.position.set(post.position.x, top + 0.72, post.position.z);
cap.castShadow = true;
group.add(cap);
}
return group;
}
function clearGroupGeometry(group) {
for (const child of [...group.children]) {
group.remove(child);
child.traverse((object) => {
if (object.geometry) object.geometry.dispose();
});
}
}
function showBarrierPreview(cells) {
clearGroupGeometry(previewRoot);
for (let i = 0; i < cells.length - 1; i++) {
const a = cells[i];
const b = cells[i + 1];
const segment = cylinderBetween(
cellWorld(a.x, a.z, 0.48),
cellWorld(b.x, b.z, 0.48),
0.065,
previewRouteMaterial,
6
);
segment.renderOrder = 15;
previewRoot.add(segment);
}
}
function addBarrier(start, end) {
const cells = rasterizeLine(start, end);
const visual = makeBarrierVisual(cells);
barrierRoot.add(visual);
barriers.push({ cells, visual });
updateBarrierControls();
recomputeRoutes();
showToast(
`Added a ${cells.length}-cell barrier. Current routes now treat it as impassable.`
);
}
function removeBarrierAt(cell) {
const index = barriers.findIndex((barrier) =>
barrier.cells.some((occupied) =>
occupied.x === cell.x && occupied.z === cell.z
)
);
if (index < 0) {
showToast("No barrier occupies that tile.");
return;
}
const [removed] = barriers.splice(index, 1);
barrierRoot.remove(removed.visual);
removed.visual.traverse((object) => {
if (object.geometry) object.geometry.dispose();
});
updateBarrierControls();
recomputeRoutes();
showToast("Barrier removed. Routes were recalculated.");
}
function undoBarrier() {
const removed = barriers.pop();
if (!removed) return;
barrierRoot.remove(removed.visual);
removed.visual.traverse((object) => {
if (object.geometry) object.geometry.dispose();
});
updateBarrierControls();
recomputeRoutes();
showToast("Last barrier removed.");
}
function clearBarriers() {
if (!barriers.length) return;
for (const barrier of barriers) {
barrierRoot.remove(barrier.visual);
barrier.visual.traverse((object) => {
if (object.geometry) object.geometry.dispose();
});
}
barriers = [];
updateBarrierControls();
recomputeRoutes();
showToast("All barriers cleared.");
}
function updateBarrierControls() {
const count = barriers.length;
barrierCount.textContent = `${count} barrier${count === 1 ? "" : "s"}`;
undoButton.disabled = count === 0;
clearButton.disabled = count === 0;
}
// ---------------------------------------------------------------------
// Explicit pathfinding: BFS on a four-neighbor grid
// ---------------------------------------------------------------------
function buildBlockedSet() {
const blocked = new Set();
for (const barrier of barriers) {
for (const cell of barrier.cells) {
blocked.add(cellIndex(cell.x, cell.z));
}
}
return blocked;
}
function findPath(start, target, blockedSet) {
if (
start.x < 0 || start.x >= COLS ||
start.z < 0 || start.z >= ROWS ||
target.x < 0 || target.x >= COLS ||
target.z < 0 || target.z >= ROWS
) {
return null;
}
const startIndex = cellIndex(start.x, start.z);
const targetIndex = cellIndex(target.x, target.z);
if (blockedSet.has(startIndex) || blockedSet.has(targetIndex)) {
return null;
}
const total = COLS * ROWS;
const previous = new Int32Array(total);
previous.fill(-1);
const distance = new Int32Array(total);
distance.fill(-1);
const queue = new Int32Array(total);
let head = 0;
let tail = 0;
queue[tail++] = startIndex;
distance[startIndex] = 0;
previous[startIndex] = startIndex;
// Deterministic neighbor order: north, east, south, west.
const neighborOffsets = [
[0, -1],
[1, 0],
[0, 1],
[-1, 0]
];
while (head < tail) {
const current = queue[head++];
if (current === targetIndex) break;
const currentX = current % COLS;
const currentZ = Math.floor(current / COLS);
for (const [offsetX, offsetZ] of neighborOffsets) {
const nextX = currentX + offsetX;
const nextZ = currentZ + offsetZ;
if (
nextX < 0 || nextX >= COLS ||
nextZ < 0 || nextZ >= ROWS
) {
continue;
}
const next = cellIndex(nextX, nextZ);
if (distance[next] !== -1 || blockedSet.has(next)) continue;
distance[next] = distance[current] + 1;
previous[next] = current;
queue[tail++] = next;
}
}
if (distance[targetIndex] < 0) return null;
const cells = [];
let cursor = targetIndex;
while (true) {
cells.push({
x: cursor % COLS,
z: Math.floor(cursor / COLS)
});
if (cursor === startIndex) break;
cursor = previous[cursor];
}
cells.reverse();
return { distance: distance[targetIndex], cells };
}
// ---------------------------------------------------------------------
// Route rendering
// ---------------------------------------------------------------------
const currentRouteRoot = new THREE.Group();
const baselineRouteRoot = new THREE.Group();
scene.add(currentRouteRoot, baselineRouteRoot);
function clearRouteGroup(group) {
for (const child of [...group.children]) {
group.remove(child);
child.traverse((object) => {
if (object.geometry) object.geometry.dispose();
});
}
}
function drawRoute(path, group, material, dashed = false, verticalOffset = 0.25) {
if (!path) return;
const points = path.cells.map((cell) =>
cellWorld(cell.x, cell.z, verticalOffset)
);
for (let i = 0; i < points.length - 1; i++) {
const a = points[i];
const b = points[i + 1];
const segmentVector = new THREE.Vector3().subVectors(b, a);
const length = segmentVector.length();
const direction = segmentVector.clone().normalize();
if (!dashed) {
const segment = cylinderBetween(a, b, 0.055, material, 6);
segment.renderOrder = 4;
group.add(segment);
} else {
const dashLength = 0.34;
const gapLength = 0.22;
const stride = dashLength + gapLength;
for (let distanceAlong = 0; distanceAlong < length; distanceAlong += stride) {
const start = a.clone().addScaledVector(direction, distanceAlong);
const end = a.clone().addScaledVector(
direction,
Math.min(distanceAlong + dashLength, length)
);
const dash = cylinderBetween(start, end, 0.045, material, 5);
dash.renderOrder = 5;
group.add(dash);
}
}
}
}
function updateSelectionMarkers() {
const agent = agents.find((item) => item.id === selectedAgentId);
const water = waters.find((item) => item.id === selectedWaterId);
selectionRing.position.copy(cellWorld(agent.x, agent.z, 0.13));
targetRing.position.copy(cellWorld(water.x, water.z, 0.18));
}
function recomputeRoutes() {
const agent = agents.find((item) => item.id === selectedAgentId);
const water = waters.find((item) => item.id === selectedWaterId);
const blockedSet = buildBlockedSet();
const baseline = findPath(agent, water, new Set());
const current = findPath(agent, water, blockedSet);
clearRouteGroup(currentRouteRoot);
clearRouteGroup(baselineRouteRoot);
drawRoute(current, currentRouteRoot, currentRouteMaterial, false, 0.25);
drawRoute(baseline, baselineRouteRoot, baselineRouteMaterial, true, 0.36);
baselineRouteRoot.visible = baselineToggle.checked;
if (current) {
const marker = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.12, 0),
currentRouteMaterial
);
marker.position.copy(cellWorld(water.x, water.z, 0.34));
currentRouteRoot.add(marker);
}
updateSelectionMarkers();
updatePanel(agent, water, baseline, current, blockedSet);
}
// ---------------------------------------------------------------------
// Panel and controls
// ---------------------------------------------------------------------
function updatePanel(agent, water, baseline, current, blockedSet) {
currentStepsElement.textContent = current ? `${current.distance} steps` : "Blocked";
baselineStepsElement.textContent = baseline
? `${baseline.distance} steps`
: "—";
let reachable = 0;
const rows = [];
for (const destination of waters) {
const baselineResult = findPath(agent, destination, new Set());
const currentResult = findPath(agent, destination, blockedSet);
if (currentResult) reachable++;
const baselineText = baselineResult
? `${baselineResult.distance} steps`
: "No route";
const currentText = currentResult
? `${currentResult.distance} steps`
: "Blocked";
let deltaText = "—";
let deltaClass = "same";
if (baselineResult && currentResult) {
const difference = currentResult.distance - baselineResult.distance;
deltaText = difference === 0 ? "0" : `+${difference}`;
deltaClass = difference === 0 ? "same" : "added";
} else if (!currentResult && baselineResult) {
deltaText = "—";
deltaClass = "added";
}
const selectedClass = destination.id === selectedWaterId ? " selected" : "";
rows.push(`
<tr class="${selectedClass}" data-water-id="${destination.id}">
<td>
<span class="water-name">${destination.name}</span>
<span class="water-id">${destination.id}</span>
</td>
<td><span class="step-count">${baselineText}</span></td>
<td>
<span class="step-count ${currentResult ? "" : "status-word"}">
${currentText}
</span>
</td>
<td><span class="delta ${deltaClass}">${deltaText}</span></td>
</tr>
`);
}
routeTable.innerHTML = rows.join("");
reachableCountElement.textContent = `${reachable} / ${waters.length}`;
if (!current) {
routeSummary.textContent =
`${agent.id} cannot reach ${water.id} with the current barriers. ` +
`The dashed baseline remains visible for comparison.`;
} else if (!baseline) {
routeSummary.textContent =
`${agent.id} reaches ${water.id} in ${current.distance} steps. ` +
`No baseline route is available.`;
} else {
const difference = current.distance - baseline.distance;
const comparison = difference === 0
? "The current route has the same length as the baseline."
: `The current route is ${difference} step${Math.abs(difference) === 1 ? "" : "s"} longer than the baseline.`;
routeSummary.textContent =
`${agent.id} → ${water.id}: ${current.distance} current steps, ` +
`${baseline.distance} baseline steps. ${comparison}`;
}
for (const row of routeTable.querySelectorAll("tr")) {
row.addEventListener("click", () => {
selectWater(row.dataset.waterId);
});
}
}
function selectAgent(id) {
selectedAgentId = id;
agentSelect.value = id;
recomputeRoutes();
}
function selectWater(id) {
selectedWaterId = id;
waterSelect.value = id;
recomputeRoutes();
}
for (const agent of agents) {
const option = document.createElement("option");
option.value = agent.id;
option.textContent = agent.name;
agentSelect.appendChild(option);
}
for (const water of waters) {
const option = document.createElement("option");
option.value = water.id;
option.textContent = `${water.id} · ${water.name}`;
waterSelect.appendChild(option);
}
agentSelect.value = selectedAgentId;
waterSelect.value = selectedWaterId;
agentSelect.addEventListener("change", () => {
selectAgent(agentSelect.value);
});
waterSelect.addEventListener("change", () => {
selectWater(waterSelect.value);
});
baselineToggle.addEventListener("change", () => {
baselineRouteRoot.visible = baselineToggle.checked;
});
undoButton.addEventListener("click", undoBarrier);
clearButton.addEventListener("click", clearBarriers);
function setMode(nextMode) {
mode = nextMode;
for (const button of document.querySelectorAll("[data-mode]")) {
button.classList.toggle("active", button.dataset.mode === mode);
}
if (mode === "inspect") {
modeHint.textContent =
"Inspect mode · drag to orbit, Shift-drag to pan, scroll to zoom";
toolCopy.textContent =
"Select an agent or water point. Drag on the landscape to orbit the camera.";
renderer.domElement.style.cursor = "grab";
} else if (mode === "barrier") {
modeHint.textContent =
"Barrier mode · drag from one tile to another to place an impassable line";
toolCopy.textContent =
"Drag across the grid. Each rasterized tile on the line becomes an impassable barrier cell.";
renderer.domElement.style.cursor = "crosshair";
} else {
modeHint.textContent =
"Erase mode · click any barrier tile to remove that entire barrier";
toolCopy.textContent =
"Click a tile occupied by a barrier. The complete barrier is removed and routes are recalculated.";
renderer.domElement.style.cursor = "not-allowed";
}
clearGroupGeometry(previewRoot);
}
for (const button of document.querySelectorAll("[data-mode]")) {
button.addEventListener("click", () => setMode(button.dataset.mode));
}
function showToast(message) {
toast.textContent = message;
toast.classList.add("visible");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("visible"), 2800);
}
// ---------------------------------------------------------------------
// Picking and custom pointer controls
// ---------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let pointerState = null;
function setPointerFromEvent(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
function groundCellFromEvent(event) {
setPointerFromEvent(event);
const hit = raycaster.intersectObject(pickPlane, false)[0];
if (!hit) return null;
const x = Math.floor((hit.point.x + WIDTH / 2) / CELL);
const z = Math.floor((hit.point.z + DEPTH / 2) / CELL);
if (x < 0 || x >= COLS || z < 0 || z >= ROWS) return null;
return { x, z };
}
function pickSceneObject(event) {
setPointerFromEvent(event);
const hits = raycaster.intersectObjects(pickRoots, true);
if (!hits.length) return;
let object = hits[0].object;
while (object && !object.userData.pickType) {
object = object.parent;
}
if (!object) return;
if (object.userData.pickType === "agent") {
selectAgent(object.userData.id);
} else if (object.userData.pickType === "water") {
selectWater(object.userData.id);
}
}
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.focus();
renderer.domElement.setPointerCapture(event.pointerId);
if (event.button === 0 && mode === "barrier") {
const cell = groundCellFromEvent(event);
pointerState = {
kind: "barrier",
start: cell,
last: cell,
moved: false
};
if (cell) showBarrierPreview([cell]);
return;
}
if (event.button === 0 && mode === "erase") {
pointerState = {
kind: "erase",
start: groundCellFromEvent(event),
moved: false
};
return;
}
pointerState = {
kind: "camera",
startX: event.clientX,
startY: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
button: event.button,
moved: false
};
renderer.domElement.style.cursor = "grabbing";
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointerState) return;
if (pointerState.kind === "barrier") {
const cell = groundCellFromEvent(event);
if (!cell) return;
pointerState.last = cell;
pointerState.moved =
pointerState.start.x !== cell.x || pointerState.start.z !== cell.z;
showBarrierPreview(rasterizeLine(pointerState.start, cell));
return;
}
if (pointerState.kind !== "camera") return;
const deltaX = event.clientX - pointerState.lastX;
const deltaY = event.clientY - pointerState.lastY;
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
const totalDistance = Math.hypot(
event.clientX - pointerState.startX,
event.clientY - pointerState.startY
);
if (totalDistance > 4) pointerState.moved = true;
const panning = pointerState.button === 2 || event.shiftKey;
if (panning) {
const scale = spherical.radius * 0.00145;
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3()
.crossVectors(forward, new THREE.Vector3(0, 1, 0))
.normalize();
cameraTarget.addScaledVector(right, -deltaX * scale);
cameraTarget.addScaledVector(forward, deltaY * scale);
cameraTarget.x = THREE.MathUtils.clamp(
cameraTarget.x,
-WIDTH / 2,
WIDTH / 2
);
cameraTarget.z = THREE.MathUtils.clamp(
cameraTarget.z,
-DEPTH / 2,
DEPTH / 2
);
} else {
spherical.theta -= deltaX * 0.005;
spherical.phi = THREE.MathUtils.clamp(
spherical.phi - deltaY * 0.005,
0.24,
1.43
);
}
updateCamera();
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (!pointerState) return;
if (pointerState.kind === "barrier") {
const end = groundCellFromEvent(event) || pointerState.last;
const start = pointerState.start;
if (start && end) {
addBarrier(start, end);
}
clearGroupGeometry(previewRoot);
} else if (pointerState.kind === "erase") {
if (!pointerState.moved) {
const cell = groundCellFromEvent(event) || pointerState.start;
if (cell) removeBarrierAt(cell);
}
} else if (pointerState.kind === "camera" && !pointerState.moved) {
pickSceneObject(event);
}
pointerState = null;
renderer.domElement.style.cursor =
mode === "inspect" ? "grab" :
mode === "barrier" ? "crosshair" :
"not-allowed";
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerState = null;
clearGroupGeometry(previewRoot);
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
spherical.radius = THREE.MathUtils.clamp(
spherical.radius * Math.exp(event.deltaY * 0.001),
16,
78
);
updateCamera();
},
{ passive: false }
);
// ---------------------------------------------------------------------
// Animation
// ---------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
agents.forEach((agent, index) => {
const group = agentGroups.get(agent.id);
const bob = Math.sin(elapsed * 1.7 + index * 1.9) * 0.015;
group.position.y = group.userData.baseY + bob;
});
renderer.render(scene, camera);
}
updateBarrierControls();
recomputeRoutes();
setMode("inspect");
loading.remove();
animate();
</script>
</body>
</html>
```