Prompt specification
Build or customize the Three.js 3D scene "Visibility Planning With Movable Screens" 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: Visibility Planning With Movable Screens
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/visibility-planning-with-movable-screens-x3464
Scene Description Prompt:
I'd like to see this as a low-poly Three.js scene: visibility planning with movable screens. Create a compact puzzle that lets players reposition screens before a traversal. Recompute sight lines from geometry and display why each attempted route succeeds or fails. Use cdnjs and return one self-contained HTML file.
Working Three.js Starter (visibility-planning-with-movable-screens-x3464):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Blind Spot — Visibility Puzzle</title>
<style>
:root {
--ink: #17332f;
--muted: #627772;
--paper: #f4f1e8;
--panel: #fffdf7;
--line: #d9ded5;
--teal: #238f88;
--orange: #d96643;
--amber: #e3a338;
--shadow: 0 12px 32px rgba(24, 51, 47, .13);
}
* { box-sizing: border-box; }
html, body {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
color: var(--ink);
background: var(--paper);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button, input { font: inherit; }
#app {
display: grid;
grid-template-columns: minmax(0, 1fr) 350px;
width: 100%;
height: 100dvh;
}
#viewport {
position: relative;
min-width: 0;
overflow: hidden;
background: #dce7e1;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.hud {
position: absolute;
inset: 0;
pointer-events: none;
}
.title-card {
position: absolute;
top: 22px;
left: 22px;
max-width: 430px;
padding: 16px 18px;
border: 1px solid rgba(255,255,255,.7);
border-radius: 16px;
background: rgba(255,253,247,.88);
box-shadow: var(--shadow);
backdrop-filter: blur(10px);
}
.eyebrow {
margin-bottom: 5px;
color: var(--teal);
font-size: 11px;
font-weight: 800;
letter-spacing: .17em;
text-transform: uppercase;
}
h1 {
margin: 0 0 6px;
font-size: clamp(25px, 3vw, 38px);
line-height: 1;
letter-spacing: -.04em;
}
.title-card p {
margin: 0;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.legend {
position: absolute;
left: 22px;
bottom: 20px;
display: flex;
flex-wrap: wrap;
gap: 8px;
max-width: calc(100% - 44px);
padding: 10px 12px;
border-radius: 12px;
background: rgba(255,253,247,.88);
box-shadow: var(--shadow);
font-size: 11px;
font-weight: 700;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 3px 5px;
}
.dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--teal);
}
.dot.orange { background: var(--orange); }
.dot.amber { background: var(--amber); }
.dot.gray { background: #82918d; }
#panel {
position: relative;
z-index: 2;
display: flex;
flex-direction: column;
gap: 14px;
min-height: 0;
padding: 20px;
overflow-y: auto;
background: var(--panel);
border-left: 1px solid var(--line);
box-shadow: -8px 0 28px rgba(30, 55, 50, .08);
}
.brand-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.brand {
font-size: 11px;
font-weight: 900;
letter-spacing: .16em;
text-transform: uppercase;
}
.level-chip {
padding: 5px 8px;
border: 1px solid var(--line);
border-radius: 999px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: .08em;
}
.status {
padding: 14px;
border: 1px solid var(--line);
border-left: 4px solid var(--teal);
border-radius: 12px;
background: #f7faf6;
}
.status[data-kind="warn"] {
border-left-color: var(--amber);
background: #fff9e9;
}
.status[data-kind="bad"] {
border-left-color: var(--orange);
background: #fff3ee;
}
.status[data-kind="good"] {
border-left-color: var(--teal);
background: #eef9f5;
}
.status-title {
margin-bottom: 5px;
font-size: 12px;
font-weight: 900;
letter-spacing: .08em;
text-transform: uppercase;
}
.status-body {
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.section-title {
margin: 0 0 9px;
color: var(--muted);
font-size: 10px;
font-weight: 900;
letter-spacing: .15em;
text-transform: uppercase;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
padding: 11px;
border: 1px solid var(--line);
border-radius: 10px;
background: #fafaf5;
}
.metric-label {
color: var(--muted);
font-size: 10px;
font-weight: 700;
}
.metric-value {
margin-top: 3px;
font-size: 17px;
font-weight: 850;
letter-spacing: -.02em;
}
.screen-card {
padding: 11px;
border: 1px solid var(--line);
border-radius: 10px;
background: #fafaf5;
color: var(--muted);
font-size: 12px;
line-height: 1.4;
}
.screen-card strong { color: var(--ink); }
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
button {
min-height: 40px;
padding: 9px 10px;
border: 1px solid var(--line);
border-radius: 10px;
color: var(--ink);
background: #fff;
font-size: 12px;
font-weight: 800;
cursor: pointer;
transition: transform .12s ease, background .12s ease, opacity .12s ease;
}
button:hover:not(:disabled) {
transform: translateY(-1px);
background: #f2f6f1;
}
button:active:not(:disabled) { transform: translateY(0); }
button:disabled {
opacity: .42;
cursor: default;
}
button.primary {
min-height: 48px;
color: #fff;
background: var(--ink);
border-color: var(--ink);
letter-spacing: .05em;
}
button.primary:hover:not(:disabled) { background: #24504a; }
.view-row {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 6px;
}
.view-row button {
min-height: 34px;
padding: 5px;
font-size: 16px;
}
.toggle-row {
display: flex;
align-items: center;
justify-content: space-between;
color: var(--muted);
font-size: 12px;
font-weight: 700;
}
.toggle-row input {
width: 17px;
height: 17px;
accent-color: var(--teal);
}
.history {
display: flex;
flex: 1;
flex-direction: column;
min-height: 100px;
}
#attempt-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.attempt {
padding: 10px;
border: 1px solid var(--line);
border-radius: 10px;
background: #fafaf5;
}
.attempt-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 4px;
font-size: 10px;
font-weight: 900;
letter-spacing: .08em;
text-transform: uppercase;
}
.attempt.pass .attempt-head { color: var(--teal); }
.attempt.fail .attempt-head { color: var(--orange); }
.attempt-body {
color: var(--muted);
font-size: 11px;
line-height: 1.42;
}
.empty {
padding: 16px 12px;
border: 1px dashed #cdd5ce;
border-radius: 10px;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
text-align: center;
}
.help {
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.help b { color: var(--ink); }
@media (max-width: 850px) {
html, body { overflow: auto; }
#app {
grid-template-columns: 1fr;
grid-template-rows: 62dvh auto;
height: auto;
min-height: 100dvh;
}
#panel {
overflow: visible;
border-top: 1px solid var(--line);
border-left: 0;
}
.title-card {
top: 14px;
left: 14px;
max-width: calc(100% - 28px);
padding: 13px 15px;
}
.title-card p { font-size: 12px; }
.legend { left: 14px; bottom: 12px; }
}
</style>
</head>
<body>
<div id="app">
<main id="viewport">
<canvas id="scene" aria-label="Interactive low-poly visibility planning puzzle"></canvas>
<div class="hud">
<section class="title-card">
<div class="eyebrow">Visibility planning / field test 03</div>
<h1>Blind Spot</h1>
<p>
Drag the two movable screens into the matching camera fans.
Keep the pale corridor clear, then send the runner.
</p>
</section>
<div class="legend">
<span><i class="dot"></i> Planned route</span>
<span><i class="dot orange"></i> Camera sight</span>
<span><i class="dot amber"></i> Movable screen A</span>
<span><i class="dot gray"></i> Solid geometry</span>
</div>
</div>
</main>
<aside id="panel">
<div class="brand-row">
<div class="brand">Signal / Works</div>
<div class="level-chip">LEVEL 03</div>
</div>
<section id="status" class="status" data-kind="info" aria-live="polite">
<div id="status-title" class="status-title">Preparing scene</div>
<div id="status-body" class="status-body">Computing geometry and sight lines…</div>
</section>
<section>
<h2 class="section-title">Current plan</h2>
<div class="metrics">
<div class="metric">
<div class="metric-label">Route length</div>
<div id="route-length" class="metric-value">—</div>
</div>
<div class="metric">
<div class="metric-label">Selected</div>
<div id="selected-screen" class="metric-value">None</div>
</div>
</div>
</section>
<div id="screen-info" class="screen-card">
Click a screen to select it, then drag it across the floor.
</div>
<div class="button-row">
<button id="undo" class="primary" disabled>Undo move</button>
<button id="reset">Reset level</button>
</div>
<button id="run" class="primary">RUN ROUTE</button>
<div>
<h2 class="section-title">Camera view</h2>
<div class="view-row">
<button id="rotate-left" title="Rotate left">↶</button>
<button id="rotate-right" title="Rotate right">↷</button>
<button id="zoom-out" title="Zoom out">−</button>
<button id="zoom-in" title="Zoom in">+</button>
</div>
</div>
<label class="toggle-row">
Show recomputed sight lines
<input id="show-sight" type="checkbox" checked>
</label>
<section class="history">
<h2 class="section-title">Attempt log</h2>
<div id="attempt-list">
<div class="empty">No attempts yet. Position the screens and run the route.</div>
</div>
</section>
<p class="help">
<b>Goal:</b> reach the green exit without entering an unobstructed camera cone.
Screens block sight <b>and</b> movement. Right-drag to orbit; use the arrow buttons
or mouse wheel to zoom. Keyboard: <b>R</b> run, <b>Z</b> undo, arrows rotate.
</p>
</aside>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
/* --------------------------------------------------------------------------
DOM and renderer
-------------------------------------------------------------------------- */
const canvas = document.querySelector("#scene");
const viewport = document.querySelector("#viewport");
const statusEl = document.querySelector("#status");
const statusTitleEl = document.querySelector("#status-title");
const statusBodyEl = document.querySelector("#status-body");
const routeLengthEl = document.querySelector("#route-length");
const selectedScreenEl = document.querySelector("#selected-screen");
const screenInfoEl = document.querySelector("#screen-info");
const attemptListEl = document.querySelector("#attempt-list");
const runButton = document.querySelector("#run");
const undoButton = document.querySelector("#undo");
const resetButton = document.querySelector("#reset");
const showSightCheckbox = document.querySelector("#show-sight");
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce7e1);
scene.fog = new THREE.Fog(0xdce7e1, 24, 42);
const camera = new THREE.OrthographicCamera(-10, 10, 7, -7, 0.1, 80);
let cameraAzimuth = 0.52;
let cameraElevation = 0.80;
let cameraRadius = 19;
const cameraTarget = new THREE.Vector3(0, 0, 0);
function updateCamera() {
const horizontal = Math.cos(cameraElevation) * cameraRadius;
camera.position.set(
cameraTarget.x + Math.sin(cameraAzimuth) * horizontal,
cameraTarget.y + Math.sin(cameraElevation) * cameraRadius,
cameraTarget.z + Math.cos(cameraAzimuth) * horizontal
);
camera.lookAt(cameraTarget);
camera.zoom = 17.5 / cameraRadius;
camera.updateProjectionMatrix();
}
function resize() {
const w = viewport.clientWidth;
const h = viewport.clientHeight;
const aspect = w / Math.max(1, h);
camera.left = -6.9 * aspect;
camera.right = 6.9 * aspect;
camera.top = 6.9;
camera.bottom = -6.9;
camera.updateProjectionMatrix();
renderer.setSize(w, h, false);
}
window.addEventListener("resize", resize);
resize();
updateCamera();
/* --------------------------------------------------------------------------
Materials, lighting, and reusable helpers
-------------------------------------------------------------------------- */
const hemi = new THREE.HemisphereLight(0xf7fff8, 0x6d8179, 2.2);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff4d9, 3.2);
sun.position.set(-8, 15, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -15;
sun.shadow.camera.right = 15;
sun.shadow.camera.top = 13;
sun.shadow.camera.bottom = -13;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
sun.shadow.bias = -0.00035;
scene.add(sun);
function standard(color, extra = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.83,
metalness: 0.02,
flatShading: true,
...extra
});
}
function makeLabel(text, background = "#17332f", foreground = "#ffffff", width = 1.25) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 256;
labelCanvas.height = 80;
const ctx = labelCanvas.getContext("2d");
ctx.fillStyle = background;
ctx.beginPath();
const r = 16;
ctx.moveTo(r, 0);
ctx.lineTo(256 - r, 0);
ctx.quadraticCurveTo(256, 0, 256, r);
ctx.lineTo(256, 80 - r);
ctx.quadraticCurveTo(256, 80, 256 - r, 80);
ctx.lineTo(r, 80);
ctx.quadraticCurveTo(0, 80, 0, 80 - r);
ctx.lineTo(0, r);
ctx.quadraticCurveTo(0, 0, r, 0);
ctx.closePath();
ctx.fill();
ctx.fillStyle = foreground;
ctx.font = "800 34px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 128, 42);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
}));
sprite.scale.set(width, width * 80 / 256, 1);
sprite.renderOrder = 20;
return sprite;
}
function box(w, h, d, material, x, y, z, parent = scene) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), material);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function disposeObject(object) {
object.traverse(child => {
if (child.geometry) child.geometry.dispose();
if (child.material) {
const materials = Array.isArray(child.material) ? child.material : [child.material];
materials.forEach(material => material.dispose());
}
});
}
/* --------------------------------------------------------------------------
Floor and fixed collision/sight geometry
-------------------------------------------------------------------------- */
const fixedObstacles = [];
const sightBlockMeshes = [];
const floor = box(
18.4, 0.30, 12.4,
standard(0xcdd8c9),
0, -0.17, 0
);
floor.castShadow = false;
const corridor = box(
16.7, 0.035, 0.72,
standard(0xe7e2c8),
0, 0.012, 3.8
);
corridor.castShadow = false;
const gridPositions = [];
for (let x = -9; x <= 9; x += 1) {
gridPositions.push(x, 0.008, -6, x, 0.008, 6);
}
for (let z = -6; z <= 6; z += 1) {
gridPositions.push(-9, 0.008, z, 9, 0.008, z);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute("position", new THREE.Float32BufferAttribute(gridPositions, 3));
scene.add(new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({ color: 0x9eafa3, transparent: true, opacity: 0.32 })
));
function addFixedBlock(id, name, x, z, w, d, h, color, options = {}) {
const mesh = box(w, h, d, standard(color), x, h / 2, z);
const obstacle = {
id,
name,
minX: x - w / 2,
maxX: x + w / 2,
minZ: z - d / 2,
maxZ: z + d / 2,
nav: options.nav !== false,
sight: options.sight !== false,
mesh
};
fixedObstacles.push(obstacle);
if (obstacle.sight) sightBlockMeshes.push(mesh);
return obstacle;
}
addFixedBlock("outer-left", "outer wall", -9.05, 0, 0.30, 12.35, 0.95, 0x8b9b91, { nav: false });
addFixedBlock("outer-right", "outer wall", 9.05, 0, 0.30, 12.35, 0.95, 0x8b9b91, { nav: false });
addFixedBlock("outer-top", "outer wall", 0, -6.05, 18.35, 0.30, 0.95, 0x8b9b91, { nav: false });
addFixedBlock("outer-bottom", "outer wall", 0, 6.05, 18.35, 0.30, 0.95, 0x8b9b91, { nav: false });
addFixedBlock(
"central-wall",
"central concrete wall",
0, -1.40, 0.56, 7.30, 1.70,
0x84958b
);
addFixedBlock("pillar-left", "left pillar", -7.0, -1.45, 1.15, 1.15, 1.25, 0x9aa99f);
addFixedBlock("pillar-right", "right pillar", 7.0, -1.45, 1.15, 1.15, 1.25, 0x9aa99f);
addFixedBlock("crate-left", "storage block", -2.55, -3.75, 1.10, 0.90, 0.80, 0xb49b75);
addFixedBlock("crate-right", "storage block", 2.55, -3.75, 1.10, 0.90, 0.80, 0xb49b75);
const wallLabel = makeLabel("SOLID", "#65776e", "#ffffff", 1.15);
wallLabel.position.set(0, 1.95, -1.15);
scene.add(wallLabel);
/* Start and destination */
const startDisc = new THREE.Mesh(
new THREE.CylinderGeometry(0.42, 0.48, 0.10, 12),
standard(0x3b9d78)
);
startDisc.position.set(-6, 0.04, 3.8);
startDisc.receiveShadow = true;
scene.add(startDisc);
const startLabel = makeLabel("START", "#28785e", "#ffffff", 1.35);
startLabel.position.set(-6, 1.25, 3.8);
scene.add(startLabel);
const goal = new THREE.Mesh(
new THREE.TorusGeometry(0.52, 0.12, 6, 18),
standard(0x31a58d, { emissive: 0x123d32, emissiveIntensity: 0.25 })
);
goal.rotation.x = Math.PI / 2;
goal.position.set(6, 0.17, 3.8);
goal.castShadow = true;
scene.add(goal);
const goalLabel = makeLabel("EXIT", "#28785e", "#ffffff", 1.2);
goalLabel.position.set(6, 1.3, 3.8);
scene.add(goalLabel);
/* --------------------------------------------------------------------------
Sensors
-------------------------------------------------------------------------- */
const sensorDefinitions = [
{ id: "L", name: "Camera L", x: -4.6, z: 0.2, yaw: 0.08, color: 0xe26b4b },
{ id: "R", name: "Camera R", x: 4.6, z: 0.2, yaw: -0.08, color: 0xe26b4b }
];
const sensors = sensorDefinitions.map(def => {
const group = new THREE.Group();
group.position.set(def.x, 0, def.z);
group.rotation.y = def.yaw;
scene.add(group);
const darkMaterial = standard(0x31423f);
const cameraMaterial = standard(def.color);
const base = new THREE.Mesh(
new THREE.CylinderGeometry(0.30, 0.40, 0.18, 8),
darkMaterial
);
base.position.y = 0.09;
base.castShadow = true;
group.add(base);
const post = new THREE.Mesh(
new THREE.CylinderGeometry(0.075, 0.10, 0.74, 6),
darkMaterial
);
post.position.y = 0.50;
post.castShadow = true;
group.add(post);
const body = box(0.54, 0.34, 0.58, cameraMaterial, 0, 1.00, 0, group);
const lens = new THREE.Mesh(
new THREE.CylinderGeometry(0.12, 0.16, 0.22, 8),
standard(0x182623)
);
lens.rotation.x = Math.PI / 2;
lens.position.set(0, 1.00, 0.36);
lens.castShadow = true;
group.add(lens);
const eye = new THREE.Mesh(
new THREE.CircleGeometry(0.065, 8),
new THREE.MeshBasicMaterial({ color: 0xffd27b })
);
eye.position.set(0, 1.00, 0.478);
group.add(eye);
const label = makeLabel(def.id, "#b84e35", "#ffffff", 0.72);
label.position.set(0, 1.70, 0);
group.add(label);
return {
...def,
group,
range: 8.5,
halfFov: THREE.MathUtils.degToRad(28),
eyeX: def.x + Math.sin(def.yaw) * 0.43,
eyeZ: def.z + Math.cos(def.yaw) * 0.43,
blockedScreens: new Set()
};
});
/* --------------------------------------------------------------------------
Movable screens
-------------------------------------------------------------------------- */
const SCREEN_WIDTH = 2.8;
const SCREEN_DEPTH = 0.18;
const SCREEN_HEIGHT = 1.20;
const initialScreenPositions = [
{ id: "A", name: "Screen A", x: -4.4, z: -4.35, color: 0xe3a338, css: "#e3a338" },
{ id: "B", name: "Screen B", x: 4.4, z: -4.35, color: 0x309d98, css: "#309d98" }
];
const screens = initialScreenPositions.map(def => {
const group = new THREE.Group();
group.position.set(def.x, 0, def.z);
scene.add(group);
const panelMaterial = standard(def.color, { roughness: 0.65 });
const panel = box(
SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_DEPTH,
panelMaterial,
0, 0.68, 0,
group
);
panel.userData.screenId = def.id;
const frameMaterial = standard(0x52645e);
box(SCREEN_WIDTH + 0.08, 0.08, 0.24, frameMaterial, 0, 0.12, 0, group);
box(SCREEN_WIDTH + 0.08, 0.08, 0.24, frameMaterial, 0, 1.25, 0, group);
box(0.10, 1.25, 0.24, frameMaterial, -SCREEN_WIDTH / 2 + 0.05, 0.68, 0, group);
box(0.10, 1.25, 0.24, frameMaterial, SCREEN_WIDTH / 2 - 0.05, 0.68, 0, group);
const outlineGeometry = new THREE.EdgesGeometry(
new THREE.BoxGeometry(SCREEN_WIDTH + 0.12, SCREEN_HEIGHT + 0.16, SCREEN_DEPTH + 0.12)
);
const outline = new THREE.LineSegments(
outlineGeometry,
new THREE.LineBasicMaterial({ color: def.color, transparent: true, opacity: 0.45 })
);
outline.position.y = 0.68;
group.add(outline);
const label = makeLabel(def.id, def.css, "#ffffff", 0.78);
label.position.set(0, 1.78, 0);
group.add(label);
sightBlockMeshes.push(panel);
return {
...def,
group,
panel,
outline,
collider: {
minX: def.x - SCREEN_WIDTH / 2,
maxX: def.x + SCREEN_WIDTH / 2,
minZ: def.z - SCREEN_DEPTH / 2,
maxZ: def.z + SCREEN_DEPTH / 2
}
};
});
const screenPickMeshes = screens.map(screen => screen.panel);
function updateScreenCollider(screen) {
screen.collider.minX = screen.group.position.x - SCREEN_WIDTH / 2;
screen.collider.maxX = screen.group.position.x + SCREEN_WIDTH / 2;
screen.collider.minZ = screen.group.position.z - SCREEN_DEPTH / 2;
screen.collider.maxZ = screen.group.position.z + SCREEN_DEPTH / 2;
}
function overlaps(a, b, pad = 0) {
return (
a.minX - pad < b.maxX &&
a.maxX + pad > b.minX &&
a.minZ - pad < b.maxZ &&
a.maxZ + pad > b.minZ
);
}
function isValidScreenPosition(screen, x, z) {
const candidate = {
minX: x - SCREEN_WIDTH / 2,
maxX: x + SCREEN_WIDTH / 2,
minZ: z - SCREEN_DEPTH / 2,
maxZ: z + SCREEN_DEPTH / 2
};
if (candidate.minX < -8.45 || candidate.maxX > 8.45) return false;
if (candidate.minZ < -5.35 || candidate.maxZ > 5.35) return false;
for (const obstacle of fixedObstacles) {
if (obstacle.nav && overlaps(candidate, obstacle, 0.07)) return false;
}
for (const other of screens) {
if (other === screen) continue;
if (overlaps(candidate, other.collider, 0.10)) return false;
}
for (const sensor of sensors) {
if (Math.hypot(x - sensor.x, z - sensor.z) < 0.85) return false;
}
return true;
}
/* --------------------------------------------------------------------------
Runner
-------------------------------------------------------------------------- */
const runner = new THREE.Group();
scene.add(runner);
const runnerBody = new THREE.Group();
runner.add(runnerBody);
const runnerMaterial = standard(0x246d68);
const skinMaterial = standard(0xe8b78d);
const darkMaterial = standard(0x273b37);
const torso = new THREE.Mesh(
new THREE.CylinderGeometry(0.18, 0.24, 0.56, 6),
runnerMaterial
);
torso.position.y = 0.58;
torso.castShadow = true;
runnerBody.add(torso);
const head = new THREE.Mesh(
new THREE.SphereGeometry(0.18, 7, 5),
skinMaterial
);
head.position.y = 1.00;
head.castShadow = true;
runnerBody.add(head);
box(0.13, 0.34, 0.14, darkMaterial, -0.11, 0.20, 0, runnerBody);
box(0.13, 0.34, 0.14, darkMaterial, 0.11, 0.20, 0, runnerBody);
box(0.30, 0.36, 0.16, standard(0xe3a338), 0, 0.64, -0.22, runnerBody);
runner.position.set(-6, 0, 3.8);
/* --------------------------------------------------------------------------
Raycasting, sight cones, and route visibility
-------------------------------------------------------------------------- */
const interactionRay = new THREE.Raycaster();
const lineOfSightRay = new THREE.Raycaster();
const sightGroup = new THREE.Group();
scene.add(sightGroup);
function clearGroup(group) {
while (group.children.length) {
const child = group.children.pop();
disposeObject(child);
}
}
function updateSightlines() {
clearGroup(sightGroup);
scene.updateMatrixWorld(true);
for (const sensor of sensors) {
sensor.blockedScreens.clear();
const origin = new THREE.Vector3(sensor.eyeX, 1.05, sensor.eyeZ);
const rayCount = 49;
const endpoints = [];
const linePoints = [];
for (let i = 0; i < rayCount; i++) {
const angle = sensor.yaw - sensor.halfFov +
(i / (rayCount - 1)) * sensor.halfFov * 2;
const direction = new THREE.Vector3(
Math.sin(angle),
0,
Math.cos(angle)
).normalize();
interactionRay.set(origin, direction);
interactionRay.near = 0.01;
interactionRay.far = sensor.range;
const hits = interactionRay.intersectObjects(sightBlockMeshes, false);
const endpoint = hits.length
? hits[0].point.clone()
: origin.clone().addScaledVector(direction, sensor.range);
if (hits.length && hits[0].object.userData.screenId) {
sensor.blockedScreens.add(hits[0].object.userData.screenId);
}
endpoints.push(new THREE.Vector2(endpoint.x, endpoint.z));
linePoints.push(origin, endpoint);
}
const lineGeometry = new THREE.BufferGeometry().setFromPoints(linePoints);
const lineMaterial = new THREE.LineBasicMaterial({
color: sensor.color,
transparent: true,
opacity: 0.52,
depthWrite: false
});
const rayLines = new THREE.LineSegments(lineGeometry, lineMaterial);
rayLines.renderOrder = 3;
sightGroup.add(rayLines);
const fanPositions = [];
for (let i = 0; i < endpoints.length - 1; i++) {
fanPositions.push(
origin.x, 0.025, origin.z,
endpoints[i].x, 0.025, endpoints[i].y,
endpoints[i + 1].x, 0.025, endpoints[i + 1].y
);
}
const fanGeometry = new THREE.BufferGeometry();
fanGeometry.setAttribute("position", new THREE.Float32BufferAttribute(fanPositions, 3));
const fanMaterial = new THREE.MeshBasicMaterial({
color: sensor.color,
transparent: true,
opacity: 0.085,
side: THREE.DoubleSide,
depthWrite: false
});
const fan = new THREE.Mesh(fanGeometry, fanMaterial);
fan.renderOrder = 1;
sightGroup.add(fan);
}
sightGroup.visible = showSightCheckbox.checked;
}
function angleDifference(a, b) {
return Math.atan2(Math.sin(a - b), Math.cos(a - b));
}
function cameraSeesPoint(sensor, point) {
const dx = point.x - sensor.eyeX;
const dz = point.z - sensor.eyeZ;
const distance = Math.hypot(dx, dz);
if (distance > sensor.range) return null;
const angle = Math.atan2(dx, dz);
const angularError = Math.abs(angleDifference(angle, sensor.yaw));
if (angularError > sensor.halfFov) return null;
const origin = new THREE.Vector3(sensor.eyeX, 1.05, sensor.eyeZ);
const target = new THREE.Vector3(point.x, 0.48, point.z);
const direction = target.clone().sub(origin);
const trueDistance = direction.length();
direction.normalize();
lineOfSightRay.set(origin, direction);
lineOfSightRay.near = 0.01;
lineOfSightRay.far = trueDistance - 0.035;
const hits = lineOfSightRay.intersectObjects(sightBlockMeshes, false);
if (hits.length && hits[0].distance < trueDistance - 0.025) return null;
return {
sensor,
distance,
angularError,
targetAngle: angle
};
}
/* --------------------------------------------------------------------------
Collision-aware route planner
-------------------------------------------------------------------------- */
const START = { x: -6, z: 3.8 };
const GOAL = { x: 6, z: 3.8 };
const RUNNER_RADIUS = 0.22;
function navigationObstacles() {
const obstacles = fixedObstacles
.filter(obstacle => obstacle.nav)
.map(obstacle => ({
name: obstacle.name,
minX: obstacle.minX,
maxX: obstacle.maxX,
minZ: obstacle.minZ,
maxZ: obstacle.maxZ
}));
for (const screen of screens) {
obstacles.push({
name: screen.name,
...screen.collider
});
}
return obstacles;
}
function pointInsideObstacle(x, z, obstacles) {
return obstacles.some(obstacle =>
x > obstacle.minX - RUNNER_RADIUS &&
x < obstacle.maxX + RUNNER_RADIUS &&
z > obstacle.minZ - RUNNER_RADIUS &&
z < obstacle.maxZ + RUNNER_RADIUS
);
}
function segmentIntersectsAABB(x1, z1, x2, z2, obstacle) {
let tMin = 0;
let tMax = 1;
const dx = x2 - x1;
const dz = z2 - z1;
const axes = [
[x1, dx, obstacle.minX - RUNNER_RADIUS, obstacle.maxX + RUNNER_RADIUS],
[z1, dz, obstacle.minZ - RUNNER_RADIUS, obstacle.maxZ + RUNNER_RADIUS]
];
for (const [origin, delta, min, max] of axes) {
if (Math.abs(delta) < 1e-8) {
if (origin < min || origin > max) return false;
} else {
let t1 = (min - origin) / delta;
let t2 = (max - origin) / delta;
if (t1 > t2) [t1, t2] = [t2, t1];
tMin = Math.max(tMin, t1);
tMax = Math.min(tMax, t2);
if (tMin > tMax) return false;
}
}
return true;
}
function segmentIsClear(a, b, obstacles) {
return !obstacles.some(obstacle =>
segmentIntersectsAABB(a.x, a.z, b.x, b.z, obstacle)
);
}
function simplifyPath(points, obstacles) {
if (points.length <= 2) return points;
const result = [points[0]];
let currentIndex = 0;
while (currentIndex < points.length - 1) {
let nextIndex = points.length - 1;
while (
nextIndex > currentIndex + 1 &&
!segmentIsClear(points[currentIndex], points[nextIndex], obstacles)
) {
nextIndex--;
}
result.push(points[nextIndex]);
currentIndex = nextIndex;
}
return result;
}
function computeRoute() {
const obstacles = navigationObstacles();
const step = 0.22;
const minX = -8.35;
const maxX = 8.35;
const minZ = -5.35;
const maxZ = 5.35;
const columns = Math.floor((maxX - minX) / step) + 1;
const rows = Math.floor((maxZ - minZ) / step) + 1;
const count = columns * rows;
const gridPoint = index => ({
x: minX + (index % columns) * step,
z: minZ + Math.floor(index / columns) * step
});
const nearestIndex = point => {
const x = Math.round((point.x - minX) / step);
const z = Math.round((point.z - minZ) / step);
return Math.max(0, Math.min(count - 1, z * columns + x));
};
const startIndex = nearestIndex(START);
const goalIndex = nearestIndex(GOAL);
const cameFrom = new Int32Array(count);
cameFrom.fill(-1);
const visited = new Uint8Array(count);
const queue = new Int32Array(count);
let head = 0;
let tail = 0;
queue[tail++] = startIndex;
visited[startIndex] = 1;
cameFrom[startIndex] = -2;
let found = false;
while (head < tail) {
const index = queue[head++];
if (index === goalIndex) {
found = true;
break;
}
const x = index % columns;
const z = Math.floor(index / columns);
const neighbors = [];
if (x > 0) neighbors.push(index - 1);
if (x < columns - 1) neighbors.push(index + 1);
if (z > 0) neighbors.push(index - columns);
if (z < rows - 1) neighbors.push(index + columns);
for (const neighbor of neighbors) {
if (visited[neighbor]) continue;
const p = gridPoint(neighbor);
if (pointInsideObstacle(p.x, p.z, obstacles)) continue;
visited[neighbor] = 1;
cameFrom[neighbor] = index;
queue[tail++] = neighbor;
}
}
if (!found) return null;
const raw = [];
let index = goalIndex;
while (index !== -2) {
raw.push(gridPoint(index));
index = cameFrom[index];
}
raw.reverse();
raw.unshift({ ...START });
raw.push({ ...GOAL });
return simplifyPath(raw, obstacles);
}
function pathLength(path) {
let total = 0;
for (let i = 1; i < path.length; i++) {
total += Math.hypot(
path[i].x - path[i - 1].x,
path[i].z - path[i - 1].z
);
}
return total;
}
function findVisibilityBreach(path) {
let distanceAlong = 0;
for (let i = 1; i < path.length; i++) {
const a = path[i - 1];
const b = path[i];
const length = Math.hypot(b.x - a.x, b.z - a.z);
const steps = Math.max(1, Math.ceil(length / 0.12));
for (let step = 0; step <= steps; step++) {
const t = step / steps;
const point = {
x: THREE.MathUtils.lerp(a.x, b.x, t),
z: THREE.MathUtils.lerp(a.z, b.z, t)
};
for (const sensor of sensors) {
const sighting = cameraSeesPoint(sensor, point);
if (sighting) {
return {
...sighting,
point,
distanceAlong: distanceAlong + length * t,
segmentIndex: i
};
}
}
}
distanceAlong += length;
}
return null;
}
/* --------------------------------------------------------------------------
Route rendering
-------------------------------------------------------------------------- */
const previewLine = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineDashedMaterial({
color: 0x287f79,
dashSize: 0.20,
gapSize: 0.12,
transparent: true,
opacity: 0.72
})
);
previewLine.renderOrder = 4;
scene.add(previewLine);
let runLine = null;
let failureMarker = null;
let currentRoute = null;
let currentBreach = null;
let running = false;
let attemptNumber = 0;
let selectedScreen = null;
const undoStack = [];
function clearRunLine() {
if (runLine) {
scene.remove(runLine);
disposeObject(runLine);
runLine = null;
}
if (failureMarker) {
scene.remove(failureMarker);
disposeObject(failureMarker);
failureMarker = null;
}
}
function updatePreview(path) {
previewLine.geometry.dispose();
if (!path || path.length < 2) {
previewLine.geometry = new THREE.BufferGeometry();
previewLine.visible = false;
return;
}
const points = path.map(point => new THREE.Vector3(point.x, 0.075, point.z));
previewLine.geometry = new THREE.BufferGeometry().setFromPoints(points);
previewLine.computeLineDistances();
previewLine.visible = true;
}
function drawRunLine(path, color) {
clearRunLine();
const points = path.map(point => new THREE.Vector3(point.x, 0.095, point.z));
runLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(points),
new THREE.LineBasicMaterial({ color })
);
runLine.renderOrder = 5;
scene.add(runLine);
}
function setStatus(kind, title, body) {
statusEl.dataset.kind = kind;
statusTitleEl.textContent = title;
statusBodyEl.textContent = body;
}
function selectScreen(screen) {
selectedScreen = screen;
for (const item of screens) {
item.outline.material.color.setHex(item === screen ? 0xffffff : item.color);
item.outline.material.opacity = item === screen ? 0.95 : 0.35;
}
selectedScreenEl.textContent = screen ? screen.id : "None";
if (screen) {
screenInfoEl.innerHTML = `
<strong>${screen.name} selected.</strong>
Position ${screen.x.toFixed(1)}, ${screen.z.toFixed(1)}.
Drag it into the matching camera fan, but keep the pale route clear.
`;
} else {
screenInfoEl.textContent = "Click a screen to select it, then drag it across the floor.";
}
}
function refreshPlan(announce = true) {
for (const screen of screens) updateScreenCollider(screen);
updateSightlines();
currentRoute = computeRoute();
currentBreach = currentRoute ? findVisibilityBreach(currentRoute) : null;
updatePreview(currentRoute);
if (!currentRoute) {
routeLengthEl.textContent = "Blocked";
if (announce) {
const corridorBlockers = screens.filter(screen =>
Math.abs(screen.group.position.z - 3.8) < 0.9 &&
screen.group.position.x > -7 &&
screen.group.position.x < 7
);
const names = corridorBlockers.length
? corridorBlockers.map(screen => screen.name).join(" and ")
: "the movable screens";
setStatus(
"bad",
"No traversable route",
`${names} close the remaining corridor. Slide the panel into a camera fan instead of onto the pale route.`
);
}
return;
}
const length = pathLength(currentRoute);
routeLengthEl.textContent = `${length.toFixed(1)} m`;
if (announce) {
if (currentBreach) {
const sensor = currentBreach.sensor;
const screenHint = sensor.blockedScreens.size
? "One screen clips the fan, but this ray still passes beside it."
: "No movable screen intersects this camera-to-route ray.";
setStatus(
"warn",
`Live check: ${sensor.name} can see the route`,
`${screenHint} Move the matching panel across the orange rays.`
);
} else {
setStatus(
"good",
"Live check: route concealed",
"The planned path is outside both unobstructed camera views. Run the route to record an attempt."
);
}
}
}
/* --------------------------------------------------------------------------
Attempt history and runner animation
-------------------------------------------------------------------------- */
function addAttempt(passed, headline, detail) {
const empty = attemptListEl.querySelector(".empty");
if (empty) empty.remove();
const article = document.createElement("article");
article.className = `attempt ${passed ? "pass" : "fail"}`;
article.innerHTML = `
<div class="attempt-head">
<span>Attempt ${String(attemptNumber).padStart(2, "0")}</span>
<span>${passed ? "Passed" : "Failed"}</span>
</div>
<div class="attempt-body"><strong>${headline}</strong><br>${detail}</div>
`;
attemptListEl.prepend(article);
while (attemptListEl.children.length > 5) {
attemptListEl.lastElementChild.remove();
}
}
function pointAtDistance(path, distance) {
let remaining = Math.max(0, distance);
for (let i = 1; i < path.length; i++) {
const a = path[i - 1];
const b = path[i];
const length = Math.hypot(b.x - a.x, b.z - a.z);
if (remaining <= length || i === path.length - 1) {
const t = length > 0 ? Math.min(1, remaining / length) : 1;
return {
x: THREE.MathUtils.lerp(a.x, b.x, t),
z: THREE.MathUtils.lerp(a.z, b.z, t),
dx: b.x - a.x,
dz: b.z - a.z
};
}
remaining -= length;
}
return { ...START, dx: 1, dz: 0 };
}
function animateRunner(path, stopDistance) {
return new Promise(resolve => {
const total = pathLength(path);
const distance = Math.min(total, stopDistance);
const duration = Math.max(0.55, distance / 4.3);
const startTime = performance.now();
function frame(now) {
const elapsed = Math.min(1, (now - startTime) / (duration * 1000));
const currentDistance = distance * elapsed;
const position = pointAtDistance(path, currentDistance);
runner.position.set(position.x, 0, position.z);
runner.rotation.y = Math.atan2(position.dx, position.dz);
runnerBody.position.y = Math.abs(Math.sin(elapsed * 28)) * 0.035;
if (elapsed < 1) {
requestAnimationFrame(frame);
} else {
runnerBody.position.y = 0;
resolve();
}
}
requestAnimationFrame(frame);
});
}
function showFailureMarker(point) {
const marker = new THREE.Mesh(
new THREE.TorusGeometry(0.32, 0.055, 5, 14),
new THREE.MeshBasicMaterial({ color: 0xd96643 })
);
marker.rotation.x = Math.PI / 2;
marker.position.set(point.x, 0.13, point.z);
marker.renderOrder = 8;
scene.add(marker);
failureMarker = marker;
}
async function runRoute() {
if (running) return;
running = true;
runButton.disabled = true;
undoButton.disabled = true;
resetButton.disabled = true;
runButton.textContent = "RUNNING…";
clearRunLine();
previewLine.visible = false;
const route = computeRoute();
if (!route) {
const blockers = screens.filter(screen =>
Math.abs(screen.group.position.z - 3.8) < 0.9
);
const detail = blockers.length
? `${blockers.map(screen => screen.name).join(" and ")} block the only remaining corridor.`
: "The movable geometry closes the only traversable corridor.";
attemptNumber++;
addAttempt(false, "Route could not be generated", detail);
setStatus("bad", "Attempt failed: no route", detail);
previewLine.visible = true;
finishRun();
return;
}
currentRoute = route;
updateSightlines();
const breach = findVisibilityBreach(route);
if (breach) {
drawRunLine(route, 0xd96643);
await animateRunner(route, breach.distanceAlong);
showFailureMarker(breach.point);
const sensor = breach.sensor;
const distanceText = breach.distanceAlong.toFixed(1);
const angleText = THREE.MathUtils.radToDeg(breach.angularError).toFixed(1);
let explanation;
if (sensor.blockedScreens.size) {
const names = [...sensor.blockedScreens].join(", ");
explanation = `${sensor.name} clips Screen ${names}, but the runner's ray passes beside the panel edge.`;
} else {
explanation = `No movable panel intersects the ray from ${sensor.name} to the runner.`;
}
attemptNumber++;
addAttempt(
false,
`${sensor.name} detected the runner ${distanceText} m into the route`,
`${explanation} The sight ray was ${breach.distance.toFixed(1)} m long and ${angleText}° from the camera axis.`
);
setStatus(
"bad",
`Attempt failed: ${sensor.name}`,
`${explanation} Move the matching screen across the orange fan and keep the corridor clear.`
);
} else {
drawRunLine(route, 0x2b9b82);
await animateRunner(route, pathLength(route));
const length = pathLength(route);
attemptNumber++;
addAttempt(
true,
"The runner reached the exit unseen",
`The ${length.toFixed(1)} m route was checked against actual wall and screen geometry. Every camera ray was blocked or outside the route.`
);
setStatus(
"good",
"Attempt passed: route is clear",
"The runner reached the green exit without entering an unobstructed camera cone."
);
}
finishRun();
}
function finishRun() {
running = false;
runButton.disabled = false;
runButton.textContent = "RUN ROUTE";
undoButton.disabled = undoStack.length === 0;
resetButton.disabled = false;
}
/* --------------------------------------------------------------------------
Screen dragging and direct camera controls
-------------------------------------------------------------------------- */
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.68);
const dragPoint = new THREE.Vector3();
let dragState = null;
let orbitState = null;
function setPointerFromEvent(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function pickScreen(event) {
interactionRay.near = 0; interactionRay.far = Infinity;
setPointerFromEvent(event);
interactionRay.setFromCamera(pointer, camera);
const hits = interactionRay.intersectObjects(screenPickMeshes, false);
if (!hits.length) return null;
return screens.find(screen => screen.id === hits[0].object.userData.screenId) || null;
}
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("pointerdown", event => {
if (running) return;
if (event.button === 2 || event.button === 1) {
orbitState = {
x: event.clientX,
y: event.clientY,
azimuth: cameraAzimuth,
elevation: cameraElevation
};
canvas.setPointerCapture(event.pointerId);
event.preventDefault();
return;
}
const screen = pickScreen(event);
selectScreen(screen);
if (!screen) return;
interactionRay.setFromCamera(pointer, camera);
if (!interactionRay.ray.intersectPlane(dragPlane, dragPoint)) return;
dragState = {
screen,
pointerId: event.pointerId,
offsetX: screen.group.position.x - dragPoint.x,
offsetZ: screen.group.position.z - dragPoint.z,
moved: false,
undoRecorded: false
};
canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = "grabbing";
event.preventDefault();
});
canvas.addEventListener("pointermove", event => {
if (orbitState) {
const dx = event.clientX - orbitState.x;
const dy = event.clientY - orbitState.y;
cameraAzimuth = orbitState.azimuth - dx * 0.006;
cameraElevation = THREE.MathUtils.clamp(
orbitState.elevation + dy * 0.004,
0.45,
1.15
);
updateCamera();
return;
}
if (!dragState) {
const screen = pickScreen(event);
canvas.style.cursor = screen ? "grab" : "default";
return;
}
if (event.pointerId !== dragState.pointerId) return;
setPointerFromEvent(event);
interactionRay.setFromCamera(pointer, camera);
if (!interactionRay.ray.intersectPlane(dragPlane, dragPoint)) return;
const screen = dragState.screen;
const x = dragPoint.x + dragState.offsetX;
const z = dragPoint.z + dragState.offsetZ;
if (!isValidScreenPosition(screen, x, z)) return;
if (!dragState.undoRecorded) {
undoStack.push(screens.map(item => ({
id: item.id,
x: item.group.position.x,
z: item.group.position.z
})));
dragState.undoRecorded = true;
undoButton.disabled = false;
}
screen.group.position.x = x;
screen.group.position.z = z;
dragState.moved = true;
clearRunLine();
previewLine.visible = true;
refreshPlan(true);
});
function endPointer(event) {
if (dragState && event.pointerId === dragState.pointerId) {
dragState = null;
canvas.style.cursor = "grab";
}
if (orbitState) orbitState = null;
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius + event.deltaY * 0.012,
11,
28
);
updateCamera();
}, { passive: false });
/* --------------------------------------------------------------------------
Buttons, reset, undo, and keyboard shortcuts
-------------------------------------------------------------------------- */
runButton.addEventListener("click", runRoute);
undoButton.addEventListener("click", () => {
if (running || undoStack.length === 0) return;
const snapshot = undoStack.pop();
for (const saved of snapshot) {
const screen = screens.find(item => item.id === saved.id);
if (!screen) continue;
screen.group.position.x = saved.x;
screen.group.position.z = saved.z;
}
clearRunLine();
previewLine.visible = true;
refreshPlan(true);
undoButton.disabled = undoStack.length === 0;
});
resetButton.addEventListener("click", () => {
if (running) return;
for (const screen of screens) {
const initial = initialScreenPositions.find(item => item.id === screen.id);
screen.group.position.x = initial.x;
screen.group.position.z = initial.z;
}
undoStack.length = 0;
attemptNumber = 0;
attemptListEl.innerHTML = '<div class="empty">No attempts yet. Position the screens and run the route.</div>';
clearRunLine();
selectScreen(null);
refreshPlan(true);
undoButton.disabled = true;
});
document.querySelector("#rotate-left").addEventListener("click", () => {
cameraAzimuth -= 0.18;
updateCamera();
});
document.querySelector("#rotate-right").addEventListener("click", () => {
cameraAzimuth += 0.18;
updateCamera();
});
document.querySelector("#zoom-in").addEventListener("click", () => {
cameraRadius = THREE.MathUtils.clamp(cameraRadius - 1.5, 11, 28);
updateCamera();
});
document.querySelector("#zoom-out").addEventListener("click", () => {
cameraRadius = THREE.MathUtils.clamp(cameraRadius + 1.5, 11, 28);
updateCamera();
});
showSightCheckbox.addEventListener("change", () => {
sightGroup.visible = showSightCheckbox.checked;
});
window.addEventListener("keydown", event => {
if (event.target instanceof HTMLInputElement) return;
if (event.key.toLowerCase() === "r") {
event.preventDefault();
runRoute();
} else if (event.key.toLowerCase() === "z") {
event.preventDefault();
undoButton.click();
} else if (event.key === "ArrowLeft") {
cameraAzimuth -= 0.12;
updateCamera();
} else if (event.key === "ArrowRight") {
cameraAzimuth += 0.12;
updateCamera();
} else if (event.key === "+" || event.key === "=") {
cameraRadius = Math.max(11, cameraRadius - 1);
updateCamera();
} else if (event.key === "-") {
cameraRadius = Math.min(28, cameraRadius + 1);
updateCamera();
} else if (event.key === "Escape") {
selectScreen(null);
}
});
/* --------------------------------------------------------------------------
Initial state and render loop
-------------------------------------------------------------------------- */
for (const screen of screens) updateScreenCollider(screen);
refreshPlan(true);
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```