Prompt specification
Build or customize the Three.js 3D scene "Sensor-inspired navigation toy" 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: Sensor-inspired navigation toy
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/sensor-inspired-navigation-toy-x0668
Scene Description Prompt:
Build a low-poly cat-like robot that avoids user-arranged obstacles through flexible whisker contact sensors and explicit rules. Three.js from cdnjs, one HTML file.
Working Three.js Starter (sensor-inspired-navigation-toy-x0668):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WHISKER — Reactive Robot Lab</title>
<style>
:root {
--bg: #071018;
--panel: rgba(9, 21, 31, 0.86);
--panel-border: rgba(129, 222, 255, 0.15);
--text: #e7f7ff;
--muted: #7895a6;
--cyan: #64f3df;
--cyan-soft: rgba(100, 243, 223, 0.14);
--orange: #ffad66;
--orange-soft: rgba(255, 173, 102, 0.13);
--red: #ff657a;
--line: rgba(141, 216, 243, 0.12);
}
* {
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);
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 5;
}
.topbar {
position: absolute;
top: 18px;
left: 20px;
right: 20px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
}
.brand-mark {
width: 38px;
height: 38px;
border: 1px solid rgba(100, 243, 223, 0.5);
border-radius: 11px;
display: grid;
place-items: center;
background: var(--cyan-soft);
box-shadow: 0 0 26px rgba(100, 243, 223, 0.12);
}
.brand-mark::before {
content: "";
width: 15px;
height: 15px;
border: 2px solid var(--cyan);
border-radius: 50% 50% 45% 45%;
transform: rotate(-10deg);
box-shadow:
-7px -7px 0 -4px var(--orange),
7px -7px 0 -4px var(--orange);
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
h1 {
margin: 3px 0 0;
font-size: 20px;
line-height: 1;
letter-spacing: 0.06em;
font-weight: 750;
}
.top-status {
display: flex;
align-items: center;
gap: 10px;
padding: 9px 12px;
border: 1px solid var(--panel-border);
border-radius: 999px;
background: rgba(7, 17, 25, 0.72);
backdrop-filter: blur(12px);
color: #a9c1ce;
font-size: 11px;
font-weight: 700;
letter-spacing: 0.08em;
}
.live-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px var(--cyan);
animation: pulse 1.8s infinite;
}
@keyframes pulse {
50% {
opacity: 0.45;
transform: scale(0.8);
}
}
.panel {
position: absolute;
top: 82px;
width: 278px;
max-height: calc(100vh - 112px);
overflow: auto;
pointer-events: auto;
border: 1px solid var(--panel-border);
border-radius: 17px;
background: var(--panel);
backdrop-filter: blur(18px) saturate(1.25);
box-shadow:
0 22px 60px rgba(0, 0, 0, 0.28),
inset 0 1px 0 rgba(255, 255, 255, 0.025);
scrollbar-width: thin;
scrollbar-color: rgba(100, 243, 223, 0.25) transparent;
}
.rules-panel {
left: 20px;
}
.editor-panel {
right: 20px;
width: 286px;
}
.panel-header {
padding: 17px 17px 14px;
border-bottom: 1px solid var(--line);
display: flex;
align-items: center;
justify-content: space-between;
}
.panel-title {
font-size: 11px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.panel-subtitle {
margin-top: 5px;
color: var(--muted);
font-size: 10px;
letter-spacing: 0.03em;
}
.state-pill {
padding: 6px 8px;
border: 1px solid rgba(100, 243, 223, 0.25);
border-radius: 7px;
background: var(--cyan-soft);
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
}
.rules {
padding: 8px;
}
.rule {
position: relative;
display: grid;
grid-template-columns: 30px 1fr;
gap: 10px;
padding: 11px 9px;
border-radius: 10px;
transition:
background 160ms ease,
transform 160ms ease;
}
.rule + .rule {
border-top: 1px solid rgba(141, 216, 243, 0.07);
}
.rule.active {
background: linear-gradient(
90deg,
rgba(100, 243, 223, 0.12),
rgba(100, 243, 223, 0.025)
);
transform: translateX(2px);
}
.rule-number {
color: #54717f;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
padding-top: 2px;
}
.rule.active .rule-number {
color: var(--cyan);
}
.rule-name {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.05em;
}
.rule.active .rule-name {
color: var(--cyan);
}
.rule-description {
margin-top: 5px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.sensor-section {
padding: 14px 16px 16px;
border-top: 1px solid var(--line);
}
.sensor-heading {
display: flex;
justify-content: space-between;
margin-bottom: 10px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.sensor-grid {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 5px;
}
.sensor {
position: relative;
min-width: 0;
padding: 8px 2px 7px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255, 255, 255, 0.018);
text-align: center;
color: #587383;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 8px;
font-weight: 800;
}
.sensor::before {
content: "";
display: block;
width: 5px;
height: 5px;
margin: 0 auto 6px;
border-radius: 50%;
background: #375361;
}
.sensor.contact {
color: var(--orange);
border-color: rgba(255, 173, 102, 0.5);
background: var(--orange-soft);
}
.sensor.contact::before {
background: var(--orange);
box-shadow: 0 0 10px var(--orange);
}
.editor-body {
padding: 15px;
}
.button-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.button-grid .wide {
grid-column: 1 / -1;
}
.ui-button {
min-height: 35px;
padding: 8px 10px;
border: 1px solid rgba(139, 216, 242, 0.16);
border-radius: 9px;
background: rgba(139, 216, 242, 0.055);
color: #c8dce6;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.03em;
cursor: pointer;
transition:
background 140ms ease,
border-color 140ms ease,
transform 140ms ease;
}
.ui-button:hover {
background: rgba(100, 243, 223, 0.11);
border-color: rgba(100, 243, 223, 0.36);
color: white;
}
.ui-button:active {
transform: translateY(1px);
}
.ui-button.primary {
border-color: rgba(100, 243, 223, 0.36);
background: rgba(100, 243, 223, 0.13);
color: var(--cyan);
}
.ui-button.danger:hover {
border-color: rgba(255, 101, 122, 0.4);
background: rgba(255, 101, 122, 0.1);
color: #ff9cac;
}
.selected-card {
margin-top: 13px;
padding: 11px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.018);
}
.selected-title {
display: flex;
justify-content: space-between;
align-items: center;
color: #bdd3dd;
font-size: 10px;
font-weight: 800;
}
.selected-title span:last-child {
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9px;
}
.selected-meta {
margin-top: 7px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9px;
line-height: 1.55;
}
.control-row {
margin-top: 14px;
padding-top: 14px;
border-top: 1px solid var(--line);
}
.control-label {
display: flex;
justify-content: space-between;
margin-bottom: 9px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.control-label output {
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
input[type="range"] {
width: 100%;
height: 4px;
appearance: none;
border-radius: 99px;
outline: none;
background: rgba(121, 171, 190, 0.22);
}
input[type="range"]::-webkit-slider-thumb {
width: 14px;
height: 14px;
appearance: none;
border: 2px solid #12303a;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px rgba(100, 243, 223, 0.5);
cursor: pointer;
}
.check-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 13px;
color: var(--muted);
font-size: 10px;
}
.check-row input {
accent-color: var(--cyan);
}
.telemetry {
position: absolute;
left: 50%;
bottom: 20px;
transform: translateX(-50%);
min-width: 520px;
padding: 11px 15px;
border: 1px solid var(--panel-border);
border-radius: 13px;
background: rgba(7, 17, 25, 0.77);
backdrop-filter: blur(14px);
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 14px;
}
.metric {
position: relative;
padding-left: 12px;
}
.metric + .metric::before {
content: "";
position: absolute;
left: 0;
top: 3px;
bottom: 3px;
width: 1px;
background: var(--line);
}
.metric-label {
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.metric-value {
margin-top: 4px;
color: #d8edf4;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 12px;
font-weight: 800;
}
.hint {
position: absolute;
bottom: 91px;
left: 50%;
transform: translateX(-50%);
padding: 6px 11px;
border-radius: 999px;
background: rgba(5, 13, 19, 0.65);
color: #7894a2;
font-size: 9px;
letter-spacing: 0.035em;
white-space: nowrap;
}
.hint b {
color: #aec6d1;
font-weight: 700;
}
.toast {
position: absolute;
top: 78px;
left: 50%;
transform: translate(-50%, -12px);
padding: 8px 13px;
border: 1px solid rgba(100, 243, 223, 0.25);
border-radius: 9px;
background: rgba(8, 24, 31, 0.9);
color: var(--cyan);
font-size: 10px;
font-weight: 700;
opacity: 0;
transition:
opacity 180ms ease,
transform 180ms ease;
}
.toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 900px) {
.panel {
top: 76px;
width: 238px;
}
.editor-panel {
width: 238px;
}
.telemetry {
min-width: 420px;
}
.hint {
display: none;
}
}
@media (max-width: 680px) {
.rules-panel {
display: none;
}
.editor-panel {
top: auto;
right: 12px;
bottom: 12px;
width: 218px;
max-height: 58vh;
}
.topbar {
left: 12px;
right: 12px;
}
.top-status {
display: none;
}
.telemetry {
left: 12px;
right: 12px;
bottom: 12px;
min-width: 0;
transform: none;
grid-template-columns: repeat(2, 1fr);
}
.editor-panel {
bottom: 112px;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="hud">
<header class="topbar">
<div class="brand">
<div class="brand-mark"></div>
<div>
<div class="eyebrow">Reactive Systems Laboratory</div>
<h1>WHISKER / CAT-07</h1>
</div>
</div>
<div class="top-status">
<span class="live-dot"></span>
<span id="topStatus">SIMULATION RUNNING</span>
</div>
</header>
<aside class="panel rules-panel">
<div class="panel-header">
<div>
<div class="panel-title">Explicit Rule Stack</div>
<div class="panel-subtitle">Deterministic whisker-driven behavior</div>
</div>
<div class="state-pill" id="statePill">SEEK</div>
</div>
<div class="rules">
<div class="rule" data-rule="seek">
<div class="rule-number">01</div>
<div>
<div class="rule-name">VECTOR_SEEK</div>
<div class="rule-description">
Rotate toward the amber goal while the direct path is clear.
</div>
</div>
</div>
<div class="rule" data-rule="guard">
<div class="rule-number">02</div>
<div>
<div class="rule-name">WHISKER_LATCH</div>
<div class="rule-description">
Any flexible-tip contact cancels forward thrust immediately.
</div>
</div>
</div>
<div class="rule" data-rule="deflect">
<div class="rule-number">03</div>
<div>
<div class="rule-name">EDGE_DEFLECT</div>
<div class="rule-description">
Turn away from the contacted side and commit to a tangent.
</div>
</div>
</div>
<div class="rule" data-rule="recover">
<div class="rule-number">04</div>
<div>
<div class="rule-name">CHASSIS_RECOVER</div>
<div class="rule-description">
Reverse and rotate if the body reaches an obstacle.
</div>
</div>
</div>
<div class="rule" data-rule="resume">
<div class="rule-number">05</div>
<div>
<div class="rule-name">CLEAR_RESUME</div>
<div class="rule-description">
Resume goal seeking only after a 250 ms clear interval.
</div>
</div>
</div>
</div>
<div class="sensor-section">
<div class="sensor-heading">
<span>Whisker channels</span>
<span id="contactLabel">0 contacts</span>
</div>
<div class="sensor-grid">
<div class="sensor" id="sensor-LF">LF</div>
<div class="sensor" id="sensor-LS">LS</div>
<div class="sensor" id="sensor-CF">CF</div>
<div class="sensor" id="sensor-RF">RF</div>
<div class="sensor" id="sensor-RS">RS</div>
</div>
</div>
</aside>
<aside class="panel editor-panel">
<div class="panel-header">
<div>
<div class="panel-title">Scenario Editor</div>
<div class="panel-subtitle">Arrange obstacles and inspect responses</div>
</div>
</div>
<div class="editor-body">
<div class="button-grid">
<button class="ui-button primary" id="toggleSim">Pause</button>
<button class="ui-button" id="addObstacle">Add obstacle</button>
<button class="ui-button" id="rotateObstacle">Rotate +45°</button>
<button class="ui-button danger" id="deleteObstacle">Delete</button>
<button class="ui-button wide" id="resetScenario">Reset scenario</button>
</div>
<div class="selected-card">
<div class="selected-title">
<span id="selectedName">No obstacle selected</span>
<span id="selectedId">—</span>
</div>
<div class="selected-meta" id="selectedMeta">
Drag an obstacle to reposition it.
</div>
</div>
<div class="control-row">
<div class="control-label">
<span>Robot velocity</span>
<output id="speedOutput">1.35 m/s</output>
</div>
<input
id="speedSlider"
type="range"
min="0.55"
max="2.2"
step="0.05"
value="1.35"
/>
</div>
<div class="check-row">
<span>Show flexible whiskers</span>
<input id="whiskerToggle" type="checkbox" checked />
</div>
</div>
</aside>
<div class="hint">
<b>Drag</b> obstacles · <b>Double-click floor</b> to move goal ·
<b>Drag empty space</b> to orbit · <b>Scroll</b> to zoom
</div>
<div class="telemetry">
<div class="metric">
<div class="metric-label">Behavior state</div>
<div class="metric-value" id="metricState">SEEK</div>
</div>
<div class="metric">
<div class="metric-label">Whisker contacts</div>
<div class="metric-value" id="metricContacts">00</div>
</div>
<div class="metric">
<div class="metric-label">Goal distance</div>
<div class="metric-value" id="metricDistance">0.00 m</div>
</div>
<div class="metric">
<div class="metric-label">Obstacle count</div>
<div class="metric-value" id="metricObstacles">03</div>
</div>
</div>
<div class="toast" id="toast"></div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Core scene
// -------------------------------------------------------------------------
const ARENA = { halfX: 9, halfZ: 6 };
const COLORS = {
cyan: 0x64f3df,
orange: 0xffad66,
red: 0xff657a,
dark: 0x0b1821,
obstacle: 0x405665
};
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071018);
scene.fog = new THREE.Fog(0x071018, 15, 31);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.1;
document.getElementById("scene").appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraControl = {
target: new THREE.Vector3(0, 0.25, 0),
yaw: 0.57,
pitch: 0.72,
distance: 16.8
};
function updateCamera() {
const horizontal = Math.cos(cameraControl.pitch) * cameraControl.distance;
camera.position.set(
cameraControl.target.x +
Math.sin(cameraControl.yaw) * horizontal,
cameraControl.target.y +
Math.sin(cameraControl.pitch) * cameraControl.distance,
cameraControl.target.z +
Math.cos(cameraControl.yaw) * horizontal
);
camera.lookAt(cameraControl.target);
}
updateCamera();
scene.add(new THREE.HemisphereLight(0xa9eaff, 0x17212b, 1.65));
const keyLight = new THREE.DirectionalLight(0xe9f8ff, 2.5);
keyLight.position.set(5, 11, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -12;
keyLight.shadow.camera.right = 12;
keyLight.shadow.camera.top = 9;
keyLight.shadow.camera.bottom = -9;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 30;
keyLight.shadow.bias = -0.0005;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4ccfff, 1.25);
rimLight.position.set(-8, 5, -8);
scene.add(rimLight);
// -------------------------------------------------------------------------
// Arena
// -------------------------------------------------------------------------
const floorMaterial = new THREE.MeshStandardMaterial({
color: 0x0c1b25,
roughness: 0.92,
metalness: 0.08
});
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(ARENA.halfX * 2, ARENA.halfZ * 2),
floorMaterial
);
floor.rotation.x = -Math.PI / 2;
floor.receiveShadow = true;
scene.add(floor);
const gridPoints = [];
for (let x = -ARENA.halfX; x <= ARENA.halfX; x++) {
gridPoints.push(x, 0.012, -ARENA.halfZ, x, 0.012, ARENA.halfZ);
}
for (let z = -ARENA.halfZ; z <= ARENA.halfZ; z++) {
gridPoints.push(-ARENA.halfX, 0.012, z, ARENA.halfX, 0.012, z);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridPoints, 3)
);
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x4c8194,
transparent: true,
opacity: 0.16
})
);
scene.add(grid);
const borderPoints = [
new THREE.Vector3(-ARENA.halfX, 0.035, -ARENA.halfZ),
new THREE.Vector3(ARENA.halfX, 0.035, -ARENA.halfZ),
new THREE.Vector3(ARENA.halfX, 0.035, ARENA.halfZ),
new THREE.Vector3(-ARENA.halfX, 0.035, ARENA.halfZ),
new THREE.Vector3(-ARENA.halfX, 0.035, -ARENA.halfZ)
];
const border = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(borderPoints),
new THREE.LineBasicMaterial({
color: COLORS.cyan,
transparent: true,
opacity: 0.45
})
);
scene.add(border);
for (const x of [-ARENA.halfX, ARENA.halfX]) {
for (const z of [-ARENA.halfZ, ARENA.halfZ]) {
const beacon = new THREE.Mesh(
new THREE.CylinderGeometry(0.07, 0.1, 0.34, 6),
new THREE.MeshStandardMaterial({
color: 0x173d46,
emissive: COLORS.cyan,
emissiveIntensity: 0.7,
roughness: 0.5
})
);
beacon.position.set(x, 0.17, z);
scene.add(beacon);
}
}
// -------------------------------------------------------------------------
// Goal beacon
// -------------------------------------------------------------------------
const goal = {
position: new THREE.Vector3(5, 0, -3),
group: new THREE.Group()
};
const goalRing = new THREE.Mesh(
new THREE.TorusGeometry(0.48, 0.055, 8, 36),
new THREE.MeshStandardMaterial({
color: COLORS.orange,
emissive: COLORS.orange,
emissiveIntensity: 1.5,
roughness: 0.35
})
);
goalRing.rotation.x = Math.PI / 2;
goalRing.position.y = 0.075;
goal.group.add(goalRing);
const goalBeam = new THREE.Mesh(
new THREE.CylinderGeometry(0.28, 0.42, 2.2, 16, 1, true),
new THREE.MeshBasicMaterial({
color: COLORS.orange,
transparent: true,
opacity: 0.08,
side: THREE.DoubleSide,
depthWrite: false
})
);
goalBeam.position.y = 1.1;
goal.group.add(goalBeam);
const goalDiamond = new THREE.Mesh(
new THREE.OctahedronGeometry(0.23, 0),
new THREE.MeshStandardMaterial({
color: 0xffd19f,
emissive: COLORS.orange,
emissiveIntensity: 1.8,
roughness: 0.25
})
);
goalDiamond.position.y = 1.65;
goal.group.add(goalDiamond);
goal.group.traverse((child) => {
if (child.isMesh) child.userData.isGoal = true;
});
scene.add(goal.group);
// -------------------------------------------------------------------------
// Obstacles
// -------------------------------------------------------------------------
const obstacles = [];
let obstacleSerial = 0;
let selectedObstacle = null;
function createObstacle({
x,
z,
w = 1.5,
d = 1.2,
h = 1.4,
rot = 0,
color = 0x405665
}) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.rotation.y = rot;
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(w, h, d),
new THREE.MeshStandardMaterial({
color,
roughness: 0.7,
metalness: 0.16,
flatShading: true,
emissive: 0x081018,
emissiveIntensity: 0.25
})
);
mesh.position.y = h / 2;
mesh.castShadow = true;
mesh.receiveShadow = true;
group.add(mesh);
const cap = new THREE.Mesh(
new THREE.BoxGeometry(w * 0.72, 0.035, d * 0.16),
new THREE.MeshStandardMaterial({
color: 0xffb86e,
emissive: 0x8a3f0d,
emissiveIntensity: 0.6,
roughness: 0.45
})
);
cap.position.set(0, h / 2 + 0.023, 0);
group.add(cap);
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x78909c,
transparent: true,
opacity: 0.42
});
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(mesh.geometry),
edgeMaterial
);
edges.position.copy(mesh.position);
group.add(edges);
const obstacle = {
id: ++obstacleSerial,
group,
mesh,
cap,
edges,
edgeMaterial,
w,
d,
h,
rot
};
mesh.userData.obstacle = obstacle;
cap.userData.obstacle = obstacle;
scene.add(group);
obstacles.push(obstacle);
return obstacle;
}
function disposeObstacle(obstacle) {
scene.remove(obstacle.group);
obstacle.group.traverse((child) => {
if (child.geometry) child.geometry.dispose();
if (child.material) {
const materials = Array.isArray(child.material)
? child.material
: [child.material];
for (const material of materials) material.dispose();
}
});
}
function selectObstacle(obstacle) {
selectedObstacle = obstacle;
for (const item of obstacles) {
const selected = item === obstacle;
item.edgeMaterial.color.setHex(selected ? 0x64f3df : 0x78909c);
item.edgeMaterial.opacity = selected ? 1 : 0.42;
item.mesh.material.emissive.setHex(selected ? 0x0c4645 : 0x081018);
item.mesh.material.emissiveIntensity = selected ? 0.75 : 0.25;
}
const selectedName = document.getElementById("selectedName");
const selectedId = document.getElementById("selectedId");
const selectedMeta = document.getElementById("selectedMeta");
if (obstacle) {
selectedName.textContent = "Obstacle selected";
selectedId.textContent = `#${String(obstacle.id).padStart(2, "0")}`;
selectedMeta.textContent =
`X ${obstacle.group.position.x.toFixed(1)} · ` +
`Z ${obstacle.group.position.z.toFixed(1)} · ` +
`${obstacle.w.toFixed(1)} × ${obstacle.d.toFixed(1)} m`;
} else {
selectedName.textContent = "No obstacle selected";
selectedId.textContent = "—";
selectedMeta.textContent = "Drag an obstacle to reposition it.";
}
}
// -------------------------------------------------------------------------
// Low-poly cat robot
// -------------------------------------------------------------------------
const robot = {
position: new THREE.Vector3(-5, 0, 3),
heading: 2.1,
speed: 1.35,
state: "SEEK",
timer: 0,
clearFor: 0,
escapeDirection: 1,
cruiseHeading: 0,
paused: false,
moving: false
};
const robotGroup = new THREE.Group();
scene.add(robotGroup);
const robotDark = new THREE.MeshStandardMaterial({
color: 0x223744,
roughness: 0.58,
metalness: 0.34,
flatShading: true
});
const robotLight = new THREE.MeshStandardMaterial({
color: 0x8aa9b7,
roughness: 0.48,
metalness: 0.28,
flatShading: true
});
const robotAccent = new THREE.MeshStandardMaterial({
color: 0x49d7c5,
emissive: 0x164f49,
emissiveIntensity: 0.85,
roughness: 0.38,
metalness: 0.25,
flatShading: true
});
const robotOrange = new THREE.MeshStandardMaterial({
color: 0xe58e4d,
emissive: 0x4b1b08,
emissiveIntensity: 0.65,
roughness: 0.52,
flatShading: true
});
const body = new THREE.Mesh(
new THREE.DodecahedronGeometry(1, 0),
robotDark
);
body.scale.set(0.72, 0.52, 0.93);
body.position.set(0, 0.73, 0);
body.castShadow = true;
body.receiveShadow = true;
robotGroup.add(body);
const chest = new THREE.Mesh(
new THREE.DodecahedronGeometry(1, 0),
robotAccent
);
chest.scale.set(0.39, 0.47, 0.42);
chest.position.set(0, 0.78, 0.5);
chest.castShadow = true;
robotGroup.add(chest);
const head = new THREE.Mesh(
new THREE.DodecahedronGeometry(1, 0),
robotLight
);
head.scale.set(0.59, 0.57, 0.55);
head.position.set(0, 1.28, 0.48);
head.castShadow = true;
robotGroup.add(head);
const facePlate = new THREE.Mesh(
new THREE.BoxGeometry(0.64, 0.31, 0.08),
new THREE.MeshStandardMaterial({
color: 0x13262f,
roughness: 0.35,
metalness: 0.45
})
);
facePlate.position.set(0, 1.37, 0.96);
robotGroup.add(facePlate);
const eyeGeometry = new THREE.SphereGeometry(0.085, 12, 8);
const eyeMaterial = new THREE.MeshStandardMaterial({
color: 0xbafff6,
emissive: COLORS.cyan,
emissiveIntensity: 2.8,
roughness: 0.2
});
for (const x of [-0.2, 0.2]) {
const eye = new THREE.Mesh(eyeGeometry, eyeMaterial);
eye.position.set(x, 1.39, 1.025);
robotGroup.add(eye);
}
const nose = new THREE.Mesh(
new THREE.OctahedronGeometry(0.09, 0),
robotOrange
);
nose.position.set(0, 1.2, 1.075);
robotGroup.add(nose);
for (const side of [-1, 1]) {
const ear = new THREE.Mesh(
new THREE.ConeGeometry(0.25, 0.58, 4),
robotDark
);
ear.position.set(side * 0.37, 1.79, 0.39);
ear.rotation.z = side * -0.13;
ear.castShadow = true;
robotGroup.add(ear);
const innerEar = new THREE.Mesh(
new THREE.ConeGeometry(0.13, 0.33, 4),
robotOrange
);
innerEar.position.set(side * 0.37, 1.77, 0.52);
innerEar.rotation.z = side * -0.13;
robotGroup.add(innerEar);
}
const legs = [];
for (const z of [-0.52, 0.5]) {
for (const x of [-0.43, 0.43]) {
const legPivot = new THREE.Group();
legPivot.position.set(x, 0.49, z);
robotGroup.add(legPivot);
const leg = new THREE.Mesh(
new THREE.CylinderGeometry(0.105, 0.14, 0.44, 5),
robotDark
);
leg.position.y = -0.22;
leg.castShadow = true;
legPivot.add(leg);
const foot = new THREE.Mesh(
new THREE.BoxGeometry(0.24, 0.12, 0.32),
robotLight
);
foot.position.set(0, -0.46, 0.06);
foot.castShadow = true;
legPivot.add(foot);
legs.push({
pivot: legPivot,
phase: z > 0 ? (x > 0 ? 0 : Math.PI) : (x > 0 ? Math.PI : 0)
});
}
}
const tailSegments = [];
const tailGeometry = new THREE.CylinderGeometry(1, 1, 1, 5);
for (let i = 0; i < 5; i++) {
const segment = new THREE.Mesh(tailGeometry, robotAccent);
segment.castShadow = true;
robotGroup.add(segment);
tailSegments.push(segment);
}
const robotLightSource = new THREE.PointLight(COLORS.cyan, 1.4, 4.5, 2);
robotLightSource.position.set(0, 1.35, 0.8);
robotGroup.add(robotLightSource);
function setCylinderBetween(mesh, a, b, radius) {
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.scale.set(radius, length, radius);
}
function updateRobotVisual(time) {
robotGroup.position.copy(robot.position);
robotGroup.rotation.y = robot.heading;
for (const leg of legs) {
const swing = robot.moving
? Math.sin(time * 9 + leg.phase) * 0.28
: Math.sin(time * 1.5 + leg.phase) * 0.025;
leg.pivot.rotation.x = swing;
}
let previous = new THREE.Vector3(0, 0.72, -0.72);
for (let i = 0; i < tailSegments.length; i++) {
const t = (i + 1) / tailSegments.length;
const current = new THREE.Vector3(
0.2 + Math.sin(time * 2.4 - i * 0.72) * 0.14 * t,
0.75 + t * 0.7,
-0.72 - i * 0.23 + Math.sin(t * Math.PI) * 0.12
);
setCylinderBetween(
tailSegments[i],
previous,
current,
0.115 * (1 - i * 0.12)
);
previous = current;
}
}
// -------------------------------------------------------------------------
// Flexible whisker sensors
// -------------------------------------------------------------------------
const WHISKER_NODE_COUNT = 7;
const whiskerSpecs = [
{ id: "LF", angle: -0.48, length: 1.82, side: -1 },
{ id: "LS", angle: -1.03, length: 1.36, side: -1 },
{ id: "CF", angle: 0, length: 1.62, side: 0 },
{ id: "RF", angle: 0.48, length: 1.82, side: 1 },
{ id: "RS", angle: 1.03, length: 1.36, side: 1 }
];
const whiskers = whiskerSpecs.map((spec) => {
const positions = new Float32Array(WHISKER_NODE_COUNT * 3);
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
const lineMaterial = new THREE.LineBasicMaterial({
color: 0xa9fff5,
transparent: true,
opacity: 0.92
});
const line = new THREE.Line(geometry, lineMaterial);
line.frustumCulled = false;
scene.add(line);
const tipMaterial = new THREE.MeshStandardMaterial({
color: 0xbafff6,
emissive: COLORS.cyan,
emissiveIntensity: 1.6,
roughness: 0.25
});
const tip = new THREE.Mesh(
new THREE.SphereGeometry(0.045, 8, 6),
tipMaterial
);
scene.add(tip);
return { ...spec, line, lineMaterial, tip, tipMaterial, positions };
});
const contactMarkers = [];
for (let i = 0; i < 8; i++) {
const marker = new THREE.Mesh(
new THREE.SphereGeometry(0.075, 8, 6),
new THREE.MeshBasicMaterial({
color: COLORS.orange,
transparent: true,
opacity: 0.9
})
);
marker.visible = false;
scene.add(marker);
contactMarkers.push(marker);
}
function robotLocalToWorld(local, target = new THREE.Vector3()) {
const c = Math.cos(robot.heading);
const s = Math.sin(robot.heading);
return target.set(
robot.position.x + c * local.x + s * local.z,
local.y,
robot.position.z - s * local.x + c * local.z
);
}
function worldDirectionToRobotLocal(world, target = new THREE.Vector3()) {
const c = Math.cos(robot.heading);
const s = Math.sin(robot.heading);
return target.set(
c * world.x - s * world.z,
0,
s * world.x + c * world.z
);
}
// Segment versus oriented 2D box.
// Returns the first intersection parameter, or null.
function segmentBox2D(ax, az, bx, bz, obstacle) {
const c = Math.cos(obstacle.rot);
const s = Math.sin(obstacle.rot);
const dxWorld = bx - ax;
const dzWorld = bz - az;
const localAx =
c * dxWorld - s * dzWorld +
(c * ax + s * az - obstacle.group.position.x);
const localAz =
s * dxWorld + c * dzWorld +
(-s * ax + c * az - obstacle.group.position.z);
const halfW = obstacle.w / 2;
const halfD = obstacle.d / 2;
let tMin = 0;
let tMax = 1;
if (Math.abs(localAx) < 1e-8) {
if (localAx < -halfW || localAx > halfW) return null;
} else {
let t1 = (-halfW - localAx) / localAx;
let t2 = (halfW - localAx) / localAx;
if (t1 > t2) [t1, t2] = [t2, t1];
tMin = Math.max(tMin, t1);
tMax = Math.min(tMax, t2);
if (tMin > tMax) return null;
}
if (Math.abs(localAz) < 1e-8) {
if (localAz < -halfD || localAz > halfD) return null;
} else {
let t1 = (-halfD - localAz) / localAz;
let t2 = (halfD - localAz) / localAz;
if (t1 > t2) [t1, t2] = [t2, t1];
tMin = Math.max(tMin, t1);
tMax = Math.min(tMax, t2);
if (tMin > tMax) return null;
}
return tMin;
}
function obstacleContactNormal(ax, az, bx, bz, obstacle, t) {
const c = Math.cos(obstacle.rot);
const s = Math.sin(obstacle.rot);
const worldX = ax + (bx - ax) * t;
const worldZ = az + (bz - az) * t;
const localX =
c * (worldX - obstacle.group.position.x) -
s * (worldZ - obstacle.group.position.z);
const localZ =
s * (worldX - obstacle.group.position.x) +
c * (worldZ - obstacle.group.position.z);
const distanceX = obstacle.w / 2 - Math.abs(localX);
const distanceZ = obstacle.d / 2 - Math.abs(localZ);
let normalLocalX = 0;
let normalLocalZ = 0;
if (distanceX < distanceZ) {
normalLocalX = localX >= 0 ? 1 : -1;
} else {
normalLocalZ = localZ >= 0 ? 1 : -1;
}
return new THREE.Vector3(
c * normalLocalX + s * normalLocalZ,
0,
-s * normalLocalX + c * normalLocalZ
);
}
function updateWhiskers() {
const contacts = [];
const activeSensorIds = new Set();
for (const whisker of whiskers) {
const desiredLocal = [];
const desiredWorld = [];
const baseX = whisker.side === 0 ? 0 : whisker.side * 0.29;
const baseZ = whisker.side === 0 ? 1.01 : 0.88;
const dirX = Math.sin(whisker.angle);
const dirZ = Math.cos(whisker.angle);
for (let i = 0; i < WHISKER_NODE_COUNT; i++) {
const t = i / (WHISKER_NODE_COUNT - 1);
const local = new THREE.Vector3(
baseX + dirX * whisker.length * t,
1.15 - t * 0.23 + Math.sin(t * Math.PI) * 0.055,
baseZ + dirZ * whisker.length * t
);
desiredLocal.push(local);
desiredWorld.push(robotLocalToWorld(local));
}
let hit = null;
for (let segment = 0; segment < desiredWorld.length - 1; segment++) {
const a = desiredWorld[segment];
const b = desiredWorld[segment + 1];
for (const obstacle of obstacles) {
const t = segmentBox2D(
a.x,
a.z,
b.x,
b.z,
obstacle
);
if (t !== null) {
if (!hit || segment < hit.segment) {
const normal = obstacleContactNormal(
a.x,
a.z,
b.x,
b.z,
obstacle,
t
);
const point = new THREE.Vector3().lerpVectors(a, b, t);
hit = {
sensor: whisker,
obstacle,
normal,
point,
segment,
segmentT: t
};
}
}
}
}
if (hit) {
const normalLocal = worldDirectionToRobotLocal(hit.normal);
const contactFraction =
(hit.segment + hit.segmentT) / (WHISKER_NODE_COUNT - 1);
for (let i = 0; i < desiredLocal.length; i++) {
const fraction = i / (WHISKER_NODE_COUNT - 1);
if (fraction >= contactFraction - 0.04) {
const bend = Math.min(1, (fraction - contactFraction + 0.04) * 3.5);
desiredLocal[i].x += normalLocal.x * bend * 0.18;
desiredLocal[i].z += normalLocal.z * bend * 0.18;
}
}
activeSensorIds.add(whisker.id);
contacts.push({
sensor: whisker,
obstacle: hit.obstacle,
normal: hit.normal,
point: hit.point
});
}
for (let i = 0; i < desiredLocal.length; i++) {
const world = robotLocalToWorld(desiredLocal[i]);
const offset = i * 3;
whisker.positions[offset] = world.x;
whisker.positions[offset + 1] = world.y;
whisker.positions[offset + 2] = world.z;
}
whisker.line.geometry.attributes.position.needsUpdate = true;
const tipWorld = robotLocalToWorld(desiredLocal[desiredLocal.length - 1]);
whisker.tip.position.copy(tipWorld);
const isContact = activeSensorIds.has(whisker.id);
whisker.lineMaterial.color.setHex(isContact ? 0xffad66 : 0xa9fff5);
whisker.tipMaterial.color.setHex(isContact ? 0xffc38f : 0xbafff6);
whisker.tipMaterial.emissive.setHex(isContact ? 0xff6d2d : 0x64f3df);
}
for (const marker of contactMarkers) marker.visible = false;
contacts.forEach((contact, index) => {
if (!contactMarkers[index]) return;
const marker = contactMarkers[index];
marker.visible = true;
marker.position.set(contact.point.x, 1.05, contact.point.z);
marker.scale.setScalar(0.9 + Math.sin(performance.now() * 0.012) * 0.15);
});
return contacts;
}
// -------------------------------------------------------------------------
// Chassis collision
// -------------------------------------------------------------------------
function bodyCollision() {
const radius = 0.48;
for (const obstacle of obstacles) {
const c = Math.cos(obstacle.rot);
const s = Math.sin(obstacle.rot);
const dx = robot.position.x - obstacle.group.position.x;
const dz = robot.position.z - obstacle.group.position.z;
const localX = c * dx - s * dz;
const localZ = s * dx + c * dz;
const clampedX = THREE.MathUtils.clamp(
localX,
-obstacle.w / 2,
obstacle.w / 2
);
const clampedZ = THREE.MathUtils.clamp(
localZ,
-obstacle.d / 2,
obstacle.d / 2
);
const differenceX = localX - clampedX;
const differenceZ = localZ - clampedZ;
const distanceSquared =
differenceX * differenceX + differenceZ * differenceZ;
if (distanceSquared < radius * radius) {
let normalLocalX = 0;
let normalLocalZ = 0;
if (distanceSquared > 1e-8) {
const distance = Math.sqrt(distanceSquared);
normalLocalX = differenceX / distance;
normalLocalZ = differenceZ / distance;
} else {
const escapeX = obstacle.w / 2 - Math.abs(localX);
const escapeZ = obstacle.d / 2 - Math.abs(localZ);
if (escapeX < escapeZ) {
normalLocalX = localX >= 0 ? 1 : -1;
} else {
normalLocalZ = localZ >= 0 ? 1 : -1;
}
}
return {
obstacle,
normal: new THREE.Vector3(
c * normalLocalX + s * normalLocalZ,
0,
-s * normalLocalX + c * normalLocalZ
)
};
}
}
return null;
}
// -------------------------------------------------------------------------
// Explicit behavior rules
// -------------------------------------------------------------------------
function forwardVector() {
return new THREE.Vector3(
Math.sin(robot.heading),
0,
Math.cos(robot.heading)
);
}
function moveRobot(distance) {
const forward = forwardVector();
robot.position.addScaledVector(forward, distance);
robot.position.x = THREE.MathUtils.clamp(
robot.position.x,
-ARENA.halfX + 0.65,
ARENA.halfX - 0.65
);
robot.position.z = THREE.MathUtils.clamp(
robot.position.z,
-ARENA.halfZ + 0.65,
ARENA.halfZ - 0.65
);
}
function steeringClearance(angle) {
const start = robot.position;
const end = start.clone().add(
new THREE.Vector3(Math.sin(angle), 0, Math.cos(angle)).multiplyScalar(3)
);
let nearest = 3;
for (const obstacle of obstacles) {
const t = segmentBox2D(
start.x,
start.z,
end.x,
end.z,
obstacle
);
if (t !== null) nearest = Math.min(nearest, t * 3);
}
return nearest;
}
function chooseEscapeDirection(contacts) {
const left = contacts.some((contact) => contact.sensor.angle < -0.15);
const right = contacts.some((contact) => contact.sensor.angle > 0.15);
if (left && !right) return 1;
if (right && !left) return -1;
const rightClearance = steeringClearance(robot.heading + 1.15);
const leftClearance = steeringClearance(robot.heading - 1.15);
if (rightClearance !== leftClearance) {
return rightClearance > leftClearance ? 1 : -1;
}
return 1;
}
function steerTowardGoal(dt) {
const dx = goal.position.x - robot.position.x;
const dz = goal.position.z - robot.position.z;
const targetAngle = Math.atan2(dx, dz);
const difference = Math.atan2(
Math.sin(targetAngle - robot.heading),
Math.cos(targetAngle - robot.heading)
);
const turnRate = 1.85;
robot.heading += THREE.MathUtils.clamp(
difference,
-turnRate * dt,
turnRate * dt
);
}
function updateRobotBehavior(dt, contacts, chassisHit) {
const goalDistance = Math.hypot(
goal.position.x - robot.position.x,
goal.position.z - robot.position.z
);
if (goalDistance < 0.72) {
robot.state = "ARRIVED";
robot.moving = false;
return;
}
if (robot.state === "ARRIVED") {
robot.state = "SEEK";
robot.clearFor = 0;
}
if (chassisHit) {
if (robot.state !== "RECOVER") {
robot.timer = 0.68;
robot.escapeDirection = chooseEscapeDirection(contacts);
}
robot.state = "RECOVER";
}
robot.moving = false;
switch (robot.state) {
case "SEEK": {
robot.clearFor = contacts.length === 0 ? robot.clearFor + dt : 0;
if (contacts.length > 0) {
// WHISKER_LATCH
robot.state = "EVADE";
robot.timer = 1.18;
robot.escapeDirection = chooseEscapeDirection(contacts);
break;
}
if (robot.clearFor >= 0.25) {
// VECTOR_SEEK
steerTowardGoal(dt);
moveRobot(robot.speed * dt);
robot.moving = true;
}
break;
}
case "EVADE": {
robot.timer -= dt;
// EDGE_DEFLECT: pivot away from the touched side.
robot.heading += robot.escapeDirection * 1.62 * dt;
if (robot.timer <= 0) {
robot.state = "CRUISE";
robot.timer = 0.92;
robot.cruiseHeading = robot.heading;
}
break;
}
case "CRUISE": {
robot.timer -= dt;
robot.heading = robot.cruiseHeading;
moveRobot(robot.speed * 0.72 * dt);
robot.moving = true;
if (contacts.length > 0) {
robot.state = "EVADE";
robot.timer = 1.18;
robot.escapeDirection = chooseEscapeDirection(contacts);
} else if (robot.timer <= 0) {
robot.state = "SEEK";
robot.clearFor = 0;
}
break;
}
case "RECOVER": {
// CHASSIS_RECOVER
robot.timer -= dt;
moveRobot(-robot.speed * 1.05 * dt);
robot.heading += robot.escapeDirection * 0.95 * dt;
robot.moving = true;
if (robot.timer <= 0) {
robot.state = "EVADE";
robot.timer = 1.32;
}
break;
}
}
}
// -------------------------------------------------------------------------
// Scenario management
// -------------------------------------------------------------------------
function resetScenario() {
for (const obstacle of obstacles) disposeObstacle(obstacle);
obstacles.length = 0;
obstacleSerial = 0;
createObstacle({
x: -1.25,
z: 0.2,
w: 2.5,
d: 1.05,
h: 1.45,
rot: 0.32,
color: 0x405665
});
createObstacle({
x: 1.35,
z: -1.65,
w: 1.35,
d: 2.45,
h: 1.55,
rot: -0.38,
color: 0x4b5e69
});
createObstacle({
x: 3.5,
z: 2.05,
w: 2.15,
d: 0.95,
h: 1.35,
rot: 0.13,
color: 0x3c5260
});
robot.position.set(-5, 0, 3);
robot.heading = Math.atan2(
goal.position.x - robot.position.x,
goal.position.z - robot.position.z
);
robot.state = "SEEK";
robot.timer = 0;
robot.clearFor = 0;
robot.escapeDirection = 1;
selectObstacle(null);
updateRobotVisual(0);
updateTelemetry([]);
}
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
const ui = {
statePill: document.getElementById("statePill"),
metricState: document.getElementById("metricState"),
metricContacts: document.getElementById("metricContacts"),
metricDistance: document.getElementById("metricDistance"),
metricObstacles: document.getElementById("metricObstacles"),
contactLabel: document.getElementById("contactLabel"),
topStatus: document.getElementById("topStatus"),
toggleSim: document.getElementById("toggleSim"),
speedSlider: document.getElementById("speedSlider"),
speedOutput: document.getElementById("speedOutput"),
whiskerToggle: document.getElementById("whiskerToggle"),
toast: document.getElementById("toast")
};
const ruleElements = [...document.querySelectorAll(".rule")];
const sensorElements = new Map(
whiskerSpecs.map((spec) => [
spec.id,
document.getElementById(`sensor-${spec.id}`)
])
);
let toastTimer = 0;
function showToast(message) {
ui.toast.textContent = message;
ui.toast.classList.add("visible");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
ui.toast.classList.remove("visible");
}, 1800);
}
function setActiveRules(activeIds) {
for (const element of ruleElements) {
element.classList.toggle(
"active",
activeIds.includes(element.dataset.rule)
);
}
}
function updateTelemetry(contacts) {
const distance = Math.hypot(
goal.position.x - robot.position.x,
goal.position.z - robot.position.z
);
ui.statePill.textContent = robot.state;
ui.metricState.textContent = robot.state;
ui.metricContacts.textContent = String(contacts.length).padStart(2, "0");
ui.metricDistance.textContent = `${distance.toFixed(2)} m`;
ui.metricObstacles.textContent = String(obstacles.length).padStart(2, "0");
ui.contactLabel.textContent = `${contacts.length} contact${
contacts.length === 1 ? "" : "s"
}`;
const activeSensors = new Set(contacts.map((contact) => contact.sensor.id));
for (const [id, element] of sensorElements) {
element.classList.toggle("contact", activeSensors.has(id));
}
const activeRules = {
SEEK: ["seek", "resume"],
EVADE: ["guard", "deflect"],
CRUISE: ["deflect", "resume"],
RECOVER: ["guard", "recover"],
ARRIVED: ["seek", "resume"]
};
setActiveRules(activeRules[robot.state] || []);
}
ui.toggleSim.addEventListener("click", () => {
robot.paused = !robot.paused;
ui.toggleSim.textContent = robot.paused ? "Run" : "Pause";
ui.topStatus.textContent = robot.paused
? "SIMULATION PAUSED"
: "SIMULATION RUNNING";
});
ui.speedSlider.addEventListener("input", () => {
robot.speed = Number(ui.speedSlider.value);
ui.speedOutput.textContent = `${robot.speed.toFixed(2)} m/s`;
});
ui.whiskerToggle.addEventListener("change", () => {
const visible = ui.whiskerToggle.checked;
for (const whisker of whiskers) {
whisker.line.visible = visible;
whisker.tip.visible = visible;
}
});
document.getElementById("addObstacle").addEventListener("click", () => {
const presetIndex = obstacles.length % 4;
const presets = [
{ w: 1.7, d: 0.9, h: 1.4, color: 0x405665 },
{ w: 1.0, d: 1.8, h: 1.55, color: 0x4b5e69 },
{ w: 2.25, d: 0.85, h: 1.3, color: 0x3c5260 },
{ w: 1.35, d: 1.35, h: 1.65, color: 0x536875 }
];
const preset = presets[presetIndex];
const x = THREE.MathUtils.clamp(
(Math.random() - 0.5) * 8,
-6.5,
6.5
);
const z = THREE.MathUtils.clamp(
(Math.random() - 0.5) * 6,
-4,
4
);
const obstacle = createObstacle({
x,
z,
...preset,
rot: (Math.random() - 0.5) * 0.7
});
selectObstacle(obstacle);
showToast("Obstacle added — drag it into the robot's route");
});
document.getElementById("rotateObstacle").addEventListener("click", () => {
if (!selectedObstacle) {
showToast("Select an obstacle first");
return;
}
selectedObstacle.rot += Math.PI / 4;
selectedObstacle.group.rotation.y = selectedObstacle.rot;
const selectedMeta = document.getElementById("selectedMeta");
selectedMeta.textContent =
`X ${selectedObstacle.group.position.x.toFixed(1)} · ` +
`Z ${selectedObstacle.group.position.z.toFixed(1)} · ` +
`${selectedObstacle.w.toFixed(1)} × ${selectedObstacle.d.toFixed(1)} m`;
});
document.getElementById("deleteObstacle").addEventListener("click", () => {
if (!selectedObstacle) {
showToast("Select an obstacle first");
return;
}
const index = obstacles.indexOf(selectedObstacle);
disposeObstacle(selectedObstacle);
obstacles.splice(index, 1);
selectObstacle(null);
showToast("Obstacle removed");
});
document.getElementById("resetScenario").addEventListener("click", () => {
resetScenario();
showToast("Scenario restored");
});
// -------------------------------------------------------------------------
// Custom pointer camera and direct manipulation
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const groundPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
const groundPoint = new THREE.Vector3();
let pointerAction = 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 intersectGround(event) {
setPointerFromEvent(event);
return raycaster.ray.intersectPlane(groundPlane, groundPoint);
}
function findObstacleHit(event) {
setPointerFromEvent(event);
const hits = raycaster.intersectObjects(
obstacles.map((obstacle) => obstacle.mesh),
false
);
return hits.length ? hits[0].object.userData.obstacle : null;
}
function findGoalHit(event) {
setPointerFromEvent(event);
const hits = raycaster.intersectObject(goal.group, true);
return hits.some((hit) => hit.object.userData.isGoal);
}
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.setPointerCapture(event.pointerId);
if (event.button === 1) {
pointerAction = { mode: "pan", x: event.clientX, y: event.clientY };
return;
}
if (event.button === 2) {
pointerAction = { mode: "orbit", x: event.clientX, y: event.clientY };
return;
}
const obstacle = findObstacleHit(event);
if (obstacle) {
selectObstacle(obstacle);
const point = intersectGround(event);
pointerAction = {
mode: "obstacle",
obstacle,
offsetX: point
? obstacle.group.position.x - point.x
: 0,
offsetZ: point
? obstacle.group.position.z - point.z
: 0
};
return;
}
if (findGoalHit(event)) {
const point = intersectGround(event);
pointerAction = {
mode: "goal",
offsetX: point ? goal.position.x - point.x : 0,
offsetZ: point ? goal.position.z - point.z : 0
};
return;
}
pointerAction = {
mode: "orbit",
x: event.clientX,
y: event.clientY
};
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointerAction) return;
if (pointerAction.mode === "orbit") {
const dx = event.clientX - pointerAction.x;
const dy = event.clientY - pointerAction.y;
cameraControl.yaw -= dx * 0.006;
cameraControl.pitch = THREE.MathUtils.clamp(
cameraControl.pitch + dy * 0.0045,
0.3,
1.28
);
pointerAction.x = event.clientX;
pointerAction.y = event.clientY;
updateCamera();
} else if (pointerAction.mode === "pan") {
const dx = event.clientX - pointerAction.x;
const dy = event.clientY - pointerAction.y;
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();
const scale = cameraControl.distance * 0.0016;
cameraControl.target.addScaledVector(right, -dx * scale);
cameraControl.target.addScaledVector(forward, dy * scale);
cameraControl.target.x = THREE.MathUtils.clamp(
cameraControl.target.x,
-8,
8
);
cameraControl.target.z = THREE.MathUtils.clamp(
cameraControl.target.z,
-6,
6
);
pointerAction.x = event.clientX;
pointerAction.y = event.clientY;
updateCamera();
} else if (pointerAction.mode === "obstacle") {
const point = intersectGround(event);
if (!point) return;
pointerAction.obstacle.group.position.x = THREE.MathUtils.clamp(
point.x + pointerAction.offsetX,
-ARENA.halfX + pointerAction.obstacle.w / 2,
ARENA.halfX - pointerAction.obstacle.w / 2
);
pointerAction.obstacle.group.position.z = THREE.MathUtils.clamp(
point.z + pointerAction.offsetZ,
-ARENA.halfZ + pointerAction.obstacle.d / 2,
ARENA.halfZ - pointerAction.obstacle.d / 2
);
const selectedMeta = document.getElementById("selectedMeta");
selectedMeta.textContent =
`X ${pointerAction.obstacle.group.position.x.toFixed(1)} · ` +
`Z ${pointerAction.obstacle.group.position.z.toFixed(1)} · ` +
`${pointerAction.obstacle.w.toFixed(1)} × ${pointerAction.obstacle.d.toFixed(1)} m`;
} else if (pointerAction.mode === "goal") {
const point = intersectGround(event);
if (!point) return;
goal.position.x = THREE.MathUtils.clamp(
point.x + pointerAction.offsetX,
-8.4,
8.4
);
goal.position.z = THREE.MathUtils.clamp(
point.z + pointerAction.offsetZ,
-5.4,
5.4
);
if (robot.state === "ARRIVED") {
robot.state = "SEEK";
robot.clearFor = 0;
}
}
});
function endPointerAction(event) {
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
pointerAction = null;
}
renderer.domElement.addEventListener("pointerup", endPointerAction);
renderer.domElement.addEventListener("pointercancel", endPointerAction);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraControl.distance = THREE.MathUtils.clamp(
cameraControl.distance + event.deltaY * 0.012,
9,
25
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", (event) => {
const obstacle = findObstacleHit(event);
if (obstacle) return;
const point = intersectGround(event);
if (!point) return;
goal.position.x = THREE.MathUtils.clamp(point.x, -8.4, 8.4);
goal.position.z = THREE.MathUtils.clamp(point.z, -5.4, 5.4);
if (robot.state === "ARRIVED") {
robot.state = "SEEK";
robot.clearFor = 0;
}
showToast("Goal beacon relocated");
});
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
let telemetryAccumulator = 0;
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
const time = clock.elapsedTime;
updateRobotVisual(time);
const contacts = updateWhiskers();
const chassisHit = bodyCollision();
if (!robot.paused) {
updateRobotBehavior(delta, contacts, chassisHit);
}
updateRobotVisual(time);
goal.group.position.set(goal.position.x, 0, goal.position.z);
goalDiamond.rotation.y = time * 1.2;
goalDiamond.position.y = 1.65 + Math.sin(time * 2.2) * 0.1;
goalRing.rotation.z = time * 0.35;
telemetryAccumulator += delta;
if (telemetryAccumulator > 0.08) {
updateTelemetry(contacts);
telemetryAccumulator = 0;
}
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
resetScenario();
animate();
</script>
</body>
</html>
```