Prompt specification
Build or customize the Three.js 3D scene "Connect Destinations With Limited Lane Modules" 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: Connect Destinations With Limited Lane Modules
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/connect-destinations-with-limited-lane-modules-x2092
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing connected cycling routes through junctions. Create a planning puzzle placing a limited set of cycle-link modules. Validate destination connectivity and geometric clearance under a clearly simplified transport model. Low-poly.
Working Three.js Starter (connect-destinations-with-limited-lane-modules-x2092):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Cycle Junction — Routeworks Puzzle</title>
<style>
:root {
color-scheme: dark;
--bg: #07131b;
--panel: rgba(10, 25, 34, 0.88);
--panel-soft: rgba(16, 38, 48, 0.78);
--line: rgba(157, 214, 218, 0.18);
--text: #eef8f5;
--muted: #9eb6b6;
--cyan: #69e4d0;
--yellow: #ffd166;
--red: #ff7185;
--green: #68e3a2;
}
* {
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 {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
#labels {
position: fixed;
inset: 0;
pointer-events: none;
overflow: hidden;
}
.world-label {
position: absolute;
left: 0;
top: 0;
padding: 5px 9px;
border: 1px solid rgba(255, 255, 255, 0.16);
border-radius: 999px;
background: rgba(5, 16, 22, 0.82);
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.25);
color: white;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.11em;
text-transform: uppercase;
white-space: nowrap;
will-change: transform;
}
.world-label.source {
border-color: rgba(255, 209, 102, 0.55);
color: #ffe3a3;
}
.world-label.destination {
border-color: rgba(104, 227, 162, 0.55);
color: #a5f3ca;
}
.glass {
background: var(--panel);
border: 1px solid var(--line);
box-shadow:
0 18px 55px rgba(0, 0, 0, 0.30),
inset 0 1px 0 rgba(255, 255, 255, 0.035);
backdrop-filter: blur(14px) saturate(120%);
-webkit-backdrop-filter: blur(14px) saturate(120%);
}
#objective {
position: fixed;
top: 16px;
left: 16px;
width: min(360px, calc(100vw - 32px));
padding: 18px;
border-radius: 18px;
pointer-events: none;
}
.eyebrow {
margin: 0 0 6px;
color: var(--cyan);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(22px, 3vw, 34px);
line-height: 1.02;
letter-spacing: -0.035em;
}
.subtitle {
margin: 9px 0 14px;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.targets {
display: flex;
flex-wrap: wrap;
gap: 7px;
}
.target {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 7px 9px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255, 255, 255, 0.025);
color: #d8e8e6;
font-size: 11px;
font-weight: 750;
}
.target::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--yellow);
box-shadow: 0 0 12px rgba(255, 209, 102, 0.55);
}
.target.destination::before {
background: var(--green);
box-shadow: 0 0 12px rgba(104, 227, 162, 0.55);
}
#kitPanel {
position: fixed;
top: 16px;
right: 16px;
width: 326px;
max-height: calc(100vh - 32px);
padding: 16px;
border-radius: 18px;
overflow: auto;
scrollbar-width: thin;
scrollbar-color: rgba(105, 228, 208, 0.35) transparent;
}
.panel-heading {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 11px;
}
.panel-heading h2 {
margin: 0;
font-size: 14px;
letter-spacing: 0.02em;
}
.panel-heading span {
color: var(--muted);
font-size: 11px;
}
#inventory {
display: grid;
gap: 7px;
}
.kit-card {
width: 100%;
min-height: 57px;
display: grid;
grid-template-columns: 38px 1fr auto;
align-items: center;
gap: 10px;
padding: 8px 9px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.025);
color: var(--text);
text-align: left;
cursor: pointer;
transition:
transform 140ms ease,
border-color 140ms ease,
background 140ms ease;
}
.kit-card:hover {
transform: translateX(-2px);
border-color: rgba(105, 228, 208, 0.38);
background: rgba(105, 228, 208, 0.055);
}
.kit-card.selected {
border-color: var(--cyan);
background: rgba(105, 228, 208, 0.09);
box-shadow: inset 3px 0 0 var(--cyan);
}
.kit-card.exhausted {
opacity: 0.45;
}
.kit-icon {
width: 36px;
height: 36px;
display: grid;
place-items: center;
border-radius: 9px;
background: rgba(0, 0, 0, 0.20);
}
.kit-icon svg {
width: 29px;
height: 29px;
fill: none;
stroke: currentColor;
stroke-width: 3.6;
stroke-linecap: square;
stroke-linejoin: miter;
}
.kit-copy {
min-width: 0;
}
.kit-copy b {
display: block;
font-size: 12px;
line-height: 1.15;
}
.kit-copy small {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 10px;
line-height: 1.2;
}
.kit-count {
min-width: 25px;
height: 25px;
display: grid;
place-items: center;
border-radius: 8px;
background: rgba(255, 255, 255, 0.075);
color: white;
font-size: 12px;
font-weight: 850;
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-top: 10px;
}
.action,
.primary-action {
min-height: 35px;
padding: 8px 9px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255, 255, 255, 0.035);
color: var(--text);
font-size: 11px;
font-weight: 750;
cursor: pointer;
transition: background 130ms ease, border-color 130ms ease;
}
.action:hover:not(:disabled),
.primary-action:hover {
background: rgba(105, 228, 208, 0.09);
border-color: rgba(105, 228, 208, 0.35);
}
.action:disabled {
opacity: 0.38;
cursor: default;
}
.primary-action {
width: 100%;
margin-top: 8px;
border-color: rgba(105, 228, 208, 0.44);
background: rgba(105, 228, 208, 0.12);
color: #baffef;
}
.divider {
height: 1px;
margin: 15px 0 12px;
background: var(--line);
}
#statusBanner {
padding: 11px;
border: 1px solid rgba(255, 209, 102, 0.30);
border-radius: 11px;
background: rgba(255, 209, 102, 0.07);
}
#statusBanner.success {
border-color: rgba(104, 227, 162, 0.40);
background: rgba(104, 227, 162, 0.08);
}
#statusBanner b {
display: block;
font-size: 12px;
}
#statusBanner span {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
#checkList {
display: grid;
gap: 8px;
margin-top: 11px;
}
.check-row {
display: grid;
grid-template-columns: 17px 1fr;
gap: 8px;
align-items: start;
}
.check-icon {
width: 17px;
height: 17px;
display: grid;
place-items: center;
border-radius: 50%;
background: rgba(255, 113, 133, 0.13);
color: var(--red);
font-size: 10px;
font-weight: 900;
}
.check-row.good .check-icon {
background: rgba(104, 227, 162, 0.13);
color: var(--green);
}
.check-row b {
display: block;
font-size: 11px;
line-height: 1.2;
}
.check-row small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9.5px;
line-height: 1.35;
}
#selectedInfo {
min-height: 16px;
margin-top: 9px;
color: var(--yellow);
font-size: 10px;
}
details {
margin-top: 12px;
padding-top: 11px;
border-top: 1px solid var(--line);
}
summary {
color: #c9dcda;
font-size: 10px;
font-weight: 800;
cursor: pointer;
}
details p {
margin: 9px 0 0;
color: var(--muted);
font-size: 9.5px;
line-height: 1.55;
}
#legend {
position: fixed;
left: 16px;
bottom: 16px;
display: flex;
flex-wrap: wrap;
gap: 10px;
max-width: min(560px, calc(100vw - 380px));
padding: 10px 12px;
border-radius: 13px;
pointer-events: none;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
color: #c2d3d1;
font-size: 9.5px;
font-weight: 700;
}
.legend-dot {
width: 8px;
height: 8px;
border-radius: 3px;
background: var(--cyan);
}
.legend-dot.hazard {
border-radius: 50%;
background: var(--red);
}
.legend-dot.island {
background: #65777c;
}
#controls {
position: fixed;
left: 50%;
bottom: 16px;
transform: translateX(-50%);
padding: 9px 12px;
border-radius: 12px;
color: #b9cecc;
font-size: 10px;
pointer-events: none;
white-space: nowrap;
}
kbd {
display: inline-block;
min-width: 20px;
margin: 0 2px;
padding: 2px 5px;
border: 1px solid rgba(255, 255, 255, 0.17);
border-bottom-width: 2px;
border-radius: 5px;
background: rgba(255, 255, 255, 0.055);
color: white;
font: 700 9px/1.2 inherit;
text-align: center;
}
#toast {
position: fixed;
left: 50%;
bottom: 78px;
transform: translate(-50%, 12px);
max-width: min(440px, calc(100vw - 30px));
padding: 10px 14px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(5, 17, 23, 0.95);
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.35);
color: #dff7f2;
font-size: 11px;
opacity: 0;
pointer-events: none;
transition: opacity 160ms ease, transform 160ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#statusBanner.pulse {
animation: pulse 500ms ease;
}
@keyframes pulse {
50% {
transform: scale(1.025);
border-color: var(--cyan);
}
}
@media (max-width: 820px) {
#objective {
width: min(330px, calc(100vw - 32px));
padding: 14px;
}
.subtitle {
display: none;
}
.targets {
margin-top: 11px;
}
#kitPanel {
top: auto;
right: 8px;
bottom: 60px;
width: min(300px, calc(100vw - 16px));
max-height: 53vh;
padding: 12px;
}
#legend {
display: none;
}
#controls {
left: 8px;
right: 8px;
bottom: 8px;
transform: none;
overflow: hidden;
text-overflow: ellipsis;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive three-dimensional cycling route puzzle"></canvas>
<div id="labels" aria-hidden="true"></div>
<section id="objective" class="glass">
<p class="eyebrow">Routeworks / Planning Puzzle</p>
<h1>Cycle Junction</h1>
<p class="subtitle">
Build a finite network of cycle links from the depot to both eastern
destinations. Every placed arm must connect, and all modules must belong
to the depot network.
</p>
<div class="targets">
<span class="target">Depot</span>
<span class="target destination">North Quay</span>
<span class="target destination">Old Yard</span>
</div>
</section>
<aside id="kitPanel" class="glass">
<div class="panel-heading">
<h2>Build kit</h2>
<span id="kitRemaining"></span>
</div>
<div id="inventory"></div>
<div class="actions">
<button id="rotateBtn" class="action">Rotate · R</button>
<button id="undoBtn" class="action">Undo · Z</button>
<button id="removeBtn" class="action">Remove selected</button>
<button id="clearBtn" class="action">Clear kit</button>
</div>
<div class="divider"></div>
<div id="statusBanner">
<b id="statusTitle">Network incomplete</b>
<span id="statusCopy">Place a module to begin.</span>
</div>
<div id="checkList"></div>
<div id="selectedInfo"></div>
<button id="checkBtn" class="primary-action">Check network</button>
<button id="hintBtn" class="action" style="width:100%; margin-top:7px;">
Give a planning hint
</button>
<details>
<summary>Simplified transport and clearance model</summary>
<p>
The board is a directed-position graph. Two adjacent modules connect
only when both have reciprocal arms on their shared cell edge.
Connectivity is tested by graph traversal from the depot.
</p>
<p>
Each module owns a swept corridor: its centerline arms are inflated
by a module-specific radius. These capsules must avoid the orange
keep-clear disks and planted islands. Clearance envelopes may overlap
at a properly paired arm, which represents a shared junction zone.
</p>
<p>
This intentionally simplified model does not simulate gradients,
traffic priority, cyclist speed, vehicle swept paths over time, curb
geometry, or real-world construction tolerances.
</p>
</details>
</aside>
<div id="legend" class="glass">
<span class="legend-item">
<i class="legend-dot"></i> Cycle corridor
</span>
<span class="legend-item">
<i class="legend-dot hazard"></i> Keep-clear disk
</span>
<span class="legend-item">
<i class="legend-dot island"></i> Planted island
</span>
<span class="legend-item">Grid coordinates: columns A–I, rows 1–7</span>
</div>
<div id="controls" class="glass">
<kbd>Click</kbd> place / select
<kbd>R</kbd> rotate
<kbd>Del</kbd> remove
<kbd>Z</kbd> undo
Drag to orbit
Right-drag to pan
Wheel to zoom
</div>
<div id="toast" role="status" aria-live="polite"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------
// Puzzle definition
// ---------------------------------------------------------------------
const COLS = 9;
const ROWS = 7;
const CELL = 1.18;
const DIRECTIONS = {
N: { key: "N", dx: 0, dz: -1 },
E: { key: "E", dx: 1, dz: 0 },
S: { key: "S", dx: 0, dz: 1 },
W: { key: "W", dx: -1, dz: 0 }
};
const MODULE_DEFS = {
straight: {
name: "Straight link",
short: "Two opposed arms",
ports: ["N", "S"],
clearance: 0.145,
color: 0x67ddca,
rotations: 2
},
corner: {
name: "Corner link",
short: "Two right-angle arms",
ports: ["N", "E"],
clearance: 0.175,
color: 0xf3c66d,
rotations: 4
},
tee: {
name: "T-junction",
short: "Three-arm junction",
ports: ["N", "E", "S"],
clearance: 0.195,
color: 0xb89cff,
rotations: 4
},
cross: {
name: "Cross-junction",
short: "Four-arm junction",
ports: ["N", "E", "S", "W"],
clearance: 0.215,
color: 0xff8f77,
rotations: 1
},
source: {
name: "Cycle depot",
short: "Fixed one-arm source",
ports: ["E"],
clearance: 0.18,
color: 0xffd166,
rotations: 1
},
sink: {
name: "Destination",
short: "Fixed one-arm destination",
ports: ["W"],
clearance: 0.18,
color: 0x68e3a2,
rotations: 1
}
};
const INITIAL_INVENTORY = {
straight: 9,
corner: 4,
tee: 1,
cross: 1
};
const fixedModules = [
{
key: "0,3",
gx: 0,
gz: 3,
type: "source",
rot: 0,
label: "Cycle Depot"
},
{
key: "8,1",
gx: 8,
gz: 1,
type: "sink",
rot: 0,
label: "North Quay"
},
{
key: "8,5",
gx: 8,
gz: 5,
type: "sink",
rot: 0,
label: "Old Yard"
}
];
const fixedByKey = new Map(fixedModules.map(m => [m.key, m]));
// Occupied cells that cannot contain a module.
const ISLAND_CELLS = [
"0,0",
"3,0",
"5,0",
"8,0",
"0,6",
"3,6",
"5,6"
];
const ISLANDS = ISLAND_CELLS.map(key => {
const [gx, gz] = key.split(",").map(Number);
return {
key,
gx,
gz,
radius: 0.32,
color: 0x667b7c
};
});
// Small offset keep-out disks make different module envelopes behave
// differently in the same cell.
const HAZARDS = [
{ gx: 2, gz: 4, ox: -0.22, oz: 0.18, radius: 0.16 },
{ gx: 6, gz: 5, ox: 0.20, oz: -0.19, radius: 0.16 },
{ gx: 1, gz: 1, ox: 0.19, oz: -0.20, radius: 0.15 }
];
const placedByKey = new Map();
const history = [];
let selectedType = "straight";
let selectedRot = 0;
let selectedKey = null;
let hoverCell = null;
function cellKey(gx, gz) {
return `${gx},${gz}`;
}
function coordinateName(gx, gz) {
return `${String.fromCharCode(65 + gx)}${gz + 1}`;
}
function worldPosition(gx, gz, y = 0) {
return new THREE.Vector3(
(gx - (COLS - 1) / 2) * CELL,
y,
(gz - (ROWS - 1) / 2) * CELL
);
}
function rotateDirection(direction, rotations) {
let { dx, dz } = direction;
for (let i = 0; i < rotations; i++) {
const nextX = -dz;
const nextZ = dx;
dx = nextX;
dz = nextZ;
}
const key =
dx === 0 && dz === -1 ? "N" :
dx === 1 && dz === 0 ? "E" :
dx === 0 && dz === 1 ? "S" :
"W";
return { key, dx, dz };
}
function portsFor(module) {
const def = MODULE_DEFS[module.type];
return def.ports.map(name =>
rotateDirection(DIRECTIONS[name], module.rot || 0)
);
}
function allModules() {
return [...fixedModules, ...placedByKey.values()];
}
function moduleIndex() {
return new Map(allModules().map(m => [m.key, m]));
}
function inventoryUsed(type) {
let count = 0;
for (const module of placedByKey.values()) {
if (module.type === type) count++;
}
return count;
}
function inventoryRemaining(type) {
return INITIAL_INVENTORY[type] - inventoryUsed(type);
}
// ---------------------------------------------------------------------
// Three.js scene
// ---------------------------------------------------------------------
const canvas = document.getElementById("scene");
const labelLayer = document.getElementById("labels");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.1;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07131b);
scene.fog = new THREE.Fog(0x07131b, 19, 39);
const camera = new THREE.OrthographicCamera(-8, 8, 5, -5, 0.1, 100);
const cameraTarget = new THREE.Vector3(0, 0, 0);
const cameraSpherical = {
radius: 15,
theta: 0.72,
phi: 0.86
};
function updateCamera() {
const { radius, theta, phi } = cameraSpherical;
camera.position.set(
cameraTarget.x + radius * Math.sin(phi) * Math.sin(theta),
cameraTarget.y + radius * Math.cos(phi),
cameraTarget.z + radius * Math.sin(phi) * Math.cos(theta)
);
camera.lookAt(cameraTarget);
camera.updateMatrixWorld();
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
const viewHeight = Math.max(8.4, 11.8 / aspect);
camera.left = -viewHeight * aspect / 2;
camera.right = viewHeight * aspect / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(width, height, false);
}
window.addEventListener("resize", resize);
resize();
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xbdeaf1, 0x17222a, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff2d6, 3.4);
sun.position.set(-7, 12, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.camera.left = -10;
sun.shadow.camera.right = 10;
sun.shadow.camera.top = 10;
sun.shadow.camera.bottom = -10;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 30;
sun.shadow.bias = -0.0005;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x5fd9d1, 1.25);
rimLight.position.set(8, 6, -9);
scene.add(rimLight);
function makeStandardMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.72,
metalness: 0.04,
flatShading: true,
...options
});
}
const boardRoot = new THREE.Group();
const moduleRoot = new THREE.Group();
const routeParticleRoot = new THREE.Group();
scene.add(boardRoot, moduleRoot, routeParticleRoot);
function createBoard() {
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(50, 50),
makeStandardMaterial(0x081820, { roughness: 1 })
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.31;
ground.receiveShadow = true;
boardRoot.add(ground);
const boardWidth = COLS * CELL + 0.5;
const boardDepth = ROWS * CELL + 0.5;
const boardBase = new THREE.Mesh(
new THREE.BoxGeometry(boardWidth, 0.26, boardDepth),
makeStandardMaterial(0x102832)
);
boardBase.position.y = -0.17;
boardBase.receiveShadow = true;
boardBase.castShadow = true;
boardRoot.add(boardBase);
const tileGeometry = new THREE.BoxGeometry(CELL * 0.925, 0.055, CELL * 0.925);
const tileMaterials = [
makeStandardMaterial(0x142c35),
makeStandardMaterial(0x17313a)
];
for (let gz = 0; gz < ROWS; gz++) {
for (let gx = 0; gx < COLS; gx++) {
const tile = new THREE.Mesh(
tileGeometry,
tileMaterials[(gx + gz) % 2]
);
tile.position.copy(worldPosition(gx, gz, -0.015));
tile.receiveShadow = true;
boardRoot.add(tile);
}
}
const outline = new THREE.LineSegments(
new THREE.EdgesGeometry(
new THREE.BoxGeometry(boardWidth, 0.27, boardDepth)
),
new THREE.LineBasicMaterial({
color: 0x35525a,
transparent: true,
opacity: 0.7
})
);
outline.position.y = -0.16;
boardRoot.add(outline);
for (const island of ISLANDS) {
const group = new THREE.Group();
group.position.copy(worldPosition(island.gx, island.gz, 0));
const base = new THREE.Mesh(
new THREE.CylinderGeometry(0.36, 0.39, 0.20, 7),
makeStandardMaterial(island.color)
);
base.position.y = 0.08;
base.castShadow = true;
base.receiveShadow = true;
group.add(base);
const rock = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.23, 0),
makeStandardMaterial(0x7c8e86)
);
rock.position.y = 0.28;
rock.scale.y = 0.8;
rock.castShadow = true;
group.add(rock);
boardRoot.add(group);
}
for (const hazard of HAZARDS) {
const group = new THREE.Group();
const position = worldPosition(hazard.gx, hazard.gz, 0);
position.x += hazard.ox * CELL;
position.z += hazard.oz * CELL;
group.position.copy(position);
const pedestal = new THREE.Mesh(
new THREE.CylinderGeometry(0.115, 0.15, 0.18, 6),
makeStandardMaterial(0x7b3540)
);
pedestal.position.y = 0.09;
pedestal.castShadow = true;
group.add(pedestal);
const marker = new THREE.Mesh(
new THREE.ConeGeometry(0.095, 0.25, 6),
makeStandardMaterial(0xff6677)
);
marker.position.y = 0.31;
marker.castShadow = true;
group.add(marker);
const keepClear = new THREE.Mesh(
new THREE.RingGeometry(hazard.radius * 0.72, hazard.radius, 24),
new THREE.MeshBasicMaterial({
color: 0xff7185,
transparent: true,
opacity: 0.56,
side: THREE.DoubleSide,
depthWrite: false
})
);
keepClear.rotation.x = -Math.PI / 2;
keepClear.position.y = 0.026;
group.add(keepClear);
boardRoot.add(group);
}
const postGeometry = new THREE.CylinderGeometry(0.07, 0.09, 0.45, 6);
const postMaterial = makeStandardMaterial(0x46636a);
const corners = [
[-COLS * CELL / 2 - 0.38, -ROWS * CELL / 2 - 0.38],
[ COLS * CELL / 2 + 0.38, -ROWS * CELL / 2 - 0.38],
[-COLS * CELL / 2 - 0.38, ROWS * CELL / 2 + 0.38],
[ COLS * CELL / 2 + 0.38, ROWS * CELL / 2 + 0.38]
];
for (const [x, z] of corners) {
const post = new THREE.Mesh(postGeometry, postMaterial);
post.position.set(x, 0.09, z);
post.castShadow = true;
boardRoot.add(post);
const cap = new THREE.Mesh(
new THREE.OctahedronGeometry(0.10, 0),
makeStandardMaterial(0xffcf76, {
emissive: 0x6a4211,
emissiveIntensity: 0.45
})
);
cap.position.set(x, 0.39, z);
cap.castShadow = true;
boardRoot.add(cap);
}
}
createBoard();
function cylinderBetween(a, b, radius, material, radialSegments = 8) {
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
const geometry = new THREE.CylinderGeometry(
radius,
radius,
length,
radialSegments,
1,
false
);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.castShadow = true;
mesh.receiveShadow = true;
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];
for (const material of materials) {
material.dispose();
}
}
});
}
function createModuleVisual(module, isGhost = false) {
const def = MODULE_DEFS[module.type];
const group = new THREE.Group();
const baseColor = isGhost ? 0x69e4d0 : 0x1b313a;
const laneColor = isGhost ? 0x69e4d0 : def.color;
const baseMaterial = makeStandardMaterial(baseColor, {
transparent: isGhost,
opacity: isGhost ? 0.34 : 1,
depthWrite: !isGhost
});
const plate = new THREE.Mesh(
new THREE.BoxGeometry(CELL * 0.77, 0.105, CELL * 0.77),
baseMaterial
);
plate.position.y = 0.04;
plate.castShadow = !isGhost;
plate.receiveShadow = !isGhost;
group.add(plate);
const laneMaterial = makeStandardMaterial(laneColor, {
emissive: laneColor,
emissiveIntensity: isGhost ? 0.3 : 0.12,
transparent: isGhost,
opacity: isGhost ? 0.88 : 1,
depthWrite: !isGhost
});
const sleeveMaterial = new THREE.MeshBasicMaterial({
color: laneColor,
transparent: true,
opacity: isGhost ? 0.18 : 0.075,
depthWrite: false,
side: THREE.DoubleSide
});
const portMarkers = [];
const center = new THREE.Vector3(0, 0.16, 0);
for (const port of portsFor(module)) {
const end = new THREE.Vector3(
port.dx * CELL / 2,
0.16,
port.dz * CELL / 2
);
const sleeve = cylinderBetween(
center,
end,
def.clearance,
sleeveMaterial,
8
);
sleeve.castShadow = false;
sleeve.renderOrder = 1;
group.add(sleeve);
const lane = cylinderBetween(
center,
end,
0.058,
laneMaterial,
8
);
group.add(lane);
const markerMaterial = makeStandardMaterial(0xe8fff9, {
emissive: 0x1b4f4b,
emissiveIntensity: 0.25,
transparent: isGhost,
opacity: isGhost ? 0.65 : 1,
depthWrite: !isGhost
});
const marker = new THREE.Mesh(
new THREE.CylinderGeometry(0.083, 0.083, 0.105, 8),
markerMaterial
);
marker.position.copy(end);
marker.castShadow = !isGhost;
group.add(marker);
portMarkers.push({ mesh: marker, port });
}
const hub = new THREE.Mesh(
new THREE.CylinderGeometry(0.105, 0.12, 0.12, 8),
laneMaterial
);
hub.position.y = 0.16;
hub.castShadow = !isGhost;
group.add(hub);
let indicator = null;
if (module.type === "source") {
indicator = new THREE.Mesh(
new THREE.OctahedronGeometry(0.14, 0),
makeStandardMaterial(0xffd166, {
emissive: 0xffa928,
emissiveIntensity: 0.7
})
);
indicator.position.y = 0.55;
indicator.castShadow = true;
group.add(indicator);
}
if (module.type === "sink") {
indicator = new THREE.Mesh(
new THREE.TorusGeometry(0.17, 0.045, 4, 12),
makeStandardMaterial(0x68e3a2, {
emissive: 0x2ca873,
emissiveIntensity: 0.6
})
);
indicator.rotation.x = Math.PI / 2;
indicator.position.y = 0.46;
indicator.castShadow = true;
group.add(indicator);
}
group.userData = {
module,
laneMaterial,
sleeveMaterial,
portMarkers,
indicator,
isGhost
};
return group;
}
const moduleVisuals = new Map();
function rebuildModuleVisuals() {
for (const child of [...moduleRoot.children]) {
moduleRoot.remove(child);
disposeObject(child);
}
moduleVisuals.clear();
for (const module of allModules()) {
const visual = createModuleVisual(module, false);
visual.position.copy(worldPosition(module.gx, module.gz, 0));
visual.userData.moduleKey = module.key;
moduleRoot.add(visual);
moduleVisuals.set(module.key, visual);
}
}
const hoverMaterial = new THREE.MeshBasicMaterial({
color: 0x69e4d0,
transparent: true,
opacity: 0.12,
depthWrite: false
});
const hoverTile = new THREE.Mesh(
new THREE.BoxGeometry(CELL * 0.90, 0.025, CELL * 0.90),
hoverMaterial
);
hoverTile.position.y = 0.025;
hoverTile.visible = false;
scene.add(hoverTile);
const selectionPoints = [
new THREE.Vector3(-CELL * 0.42, 0, -CELL * 0.42),
new THREE.Vector3( CELL * 0.42, 0, -CELL * 0.42),
new THREE.Vector3( CELL * 0.42, 0, CELL * 0.42),
new THREE.Vector3(-CELL * 0.42, 0, CELL * 0.42)
];
const selectionRing = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints(selectionPoints),
new THREE.LineBasicMaterial({
color: 0xffd166,
transparent: true,
opacity: 0.95
})
);
selectionRing.visible = false;
scene.add(selectionRing);
let ghost = null;
function removeGhost() {
if (!ghost) return;
scene.remove(ghost);
disposeObject(ghost);
ghost = null;
}
// ---------------------------------------------------------------------
// Geometric clearance model
// ---------------------------------------------------------------------
function moduleSegments(module) {
const center = worldPosition(module.gx, module.gz, 0);
return portsFor(module).map(port => ({
a: { x: center.x, z: center.z },
b: {
x: center.x + port.dx * CELL / 2,
z: center.z + port.dz * CELL / 2
},
port
}));
}
function pointSegmentDistance(point, a, b) {
const abx = b.x - a.x;
const abz = b.z - a.z;
const lengthSquared = abx * abx + abz * abz;
if (lengthSquared < 1e-12) {
return Math.hypot(point.x - a.x, point.z - a.z);
}
const t = THREE.MathUtils.clamp(
((point.x - a.x) * abx + (point.z - a.z) * abz) /
lengthSquared,
0,
1
);
const closest = {
x: a.x + abx * t,
z: a.z + abz * t
};
return Math.hypot(point.x - closest.x, point.z - closest.z);
}
function orientation(a, b, c) {
const value =
(b.z - a.z) * (c.x - b.x) -
(b.x - a.x) * (c.z - b.z);
if (Math.abs(value) < 1e-9) return 0;
return value > 0 ? 1 : 2;
}
function segmentsIntersect(a, b, c, d) {
const o1 = orientation(a, b, c);
const o2 = orientation(a, b, d);
const o3 = orientation(c, d, a);
const o4 = orientation(c, d, b);
return o1 !== o2 && o3 !== o4;
}
function segmentDistance(a, b, c, d) {
if (segmentsIntersect(a, b, c, d)) return 0;
return Math.min(
pointSegmentDistance(a, c, d),
pointSegmentDistance(b, c, d),
pointSegmentDistance(c, a, b),
pointSegmentDistance(d, a, b)
);
}
function moduleOverlap(a, b) {
const aSegments = moduleSegments(a);
const bSegments = moduleSegments(b);
const required =
MODULE_DEFS[a.type].clearance +
MODULE_DEFS[b.type].clearance;
for (const first of aSegments) {
for (const second of bSegments) {
if (
segmentDistance(first.a, first.b, second.a, second.b) <
required - 0.0001
) {
return true;
}
}
}
return false;
}
function modulesDirectlyConnected(a, b) {
const dx = b.gx - a.gx;
const dz = b.gz - a.gz;
if (Math.abs(dx) + Math.abs(dz) !== 1) return false;
for (const port of portsFor(a)) {
if (port.dx !== dx || port.dz !== dz) continue;
const reciprocal = portsFor(b).some(other =>
other.dx === -dx && other.dz === -dz
);
if (reciprocal) return true;
}
return false;
}
function hazardWorldPosition(hazard) {
const position = worldPosition(hazard.gx, hazard.gz, 0);
position.x += hazard.ox * CELL;
position.z += hazard.oz * CELL;
return position;
}
function clearanceProblemsForModule(module) {
const problems = [];
const radius = MODULE_DEFS[module.type].clearance;
for (const segment of moduleSegments(module)) {
for (const hazard of HAZARDS) {
const position = hazardWorldPosition(hazard);
const distance = pointSegmentDistance(
{ x: position.x, z: position.z },
segment.a,
segment.b
);
if (distance <= radius + hazard.radius) {
problems.push(
`${coordinateName(hazard.gx, hazard.gz)} keep-clear disk`
);
}
}
for (const island of ISLANDS) {
const position = worldPosition(island.gx, island.gz, 0);
const distance = pointSegmentDistance(
{ x: position.x, z: position.z },
segment.a,
segment.b
);
if (distance <= radius + island.radius) {
problems.push(
`${coordinateName(island.gx, island.gz)} planted island`
);
}
}
}
return [...new Set(problems)];
}
function candidateInfo(type, rot, gx, gz) {
const key = cellKey(gx, gz);
if (gx < 0 || gx >= COLS || gz < 0 || gz >= ROWS) {
return { ok: false, reason: "That cell is outside the board." };
}
if (fixedByKey.has(key)) {
return { ok: false, reason: "Fixed depot or destination cell." };
}
if (placedByKey.has(key)) {
return { ok: false, reason: "This cell already contains a module." };
}
if (ISLAND_CELLS.includes(key)) {
return {
ok: false,
reason: "A planted island occupies this cell."
};
}
if (inventoryRemaining(type) <= 0) {
return { ok: false, reason: "No modules of this type remain in the kit." };
}
const candidate = {
key,
gx,
gz,
type,
rot,
fixed: false
};
const worldProblems = clearanceProblemsForModule(candidate);
if (worldProblems.length) {
return {
ok: false,
reason: `Clearance conflict with ${worldProblems[0]}.`
};
}
for (const existing of allModules()) {
if (
moduleOverlap(candidate, existing) &&
!modulesDirectlyConnected(candidate, existing)
) {
return {
ok: false,
reason: `Swept envelope overlaps the ${MODULE_DEFS[existing.type].name.toLowerCase()}.`
};
}
}
return { ok: true, reason: "Placement is physically clear." };
}
// ---------------------------------------------------------------------
// Connectivity and global validation
// ---------------------------------------------------------------------
function validateNetwork() {
const modules = allModules();
const index = moduleIndex();
const adjacency = new Map(modules.map(module => [module.key, new Set()]));
const openPorts = [];
for (const module of modules) {
for (const port of portsFor(module)) {
const neighborKey = cellKey(
module.gx + port.dx,
module.gz + port.dz
);
const neighbor = index.get(neighborKey);
const reciprocal = neighbor && portsFor(neighbor).some(other =>
other.dx === -port.dx && other.dz === -port.dz
);
if (!neighbor || !reciprocal) {
openPorts.push({
module: module.key,
port: port.key
});
} else {
adjacency.get(module.key).add(neighbor.key);
adjacency.get(neighbor.key).add(module.key);
}
}
}
const sourceKey = "0,3";
const destinationKeys = ["8,1", "8,5"];
const visited = new Set();
const parent = new Map();
const queue = [sourceKey];
visited.add(sourceKey);
parent.set(sourceKey, null);
while (queue.length) {
const key = queue.shift();
for (const neighbor of adjacency.get(key) || []) {
if (visited.has(neighbor)) continue;
visited.add(neighbor);
parent.set(neighbor, key);
queue.push(neighbor);
}
}
const destinationResults = destinationKeys.map(key => ({
key,
connected: visited.has(key)
}));
const orphanModules = [...placedByKey.keys()].filter(
key => !visited.has(key)
);
const clearanceIssues = [];
for (const module of modules) {
for (const problem of clearanceProblemsForModule(module)) {
clearanceIssues.push(`${module.key}: ${problem}`);
}
}
for (let i = 0; i < modules.length; i++) {
for (let j = i + 1; j < modules.length; j++) {
const a = modules[i];
const b = modules[j];
if (
!modulesDirectlyConnected(a, b) &&
moduleOverlap(a, b)
) {
clearanceIssues.push(
`${a.key} and ${b.key} have overlapping clearance envelopes`
);
}
}
}
const destinationsConnected = destinationResults.every(
result => result.connected
);
const interfacesPaired = openPorts.length === 0;
const allModulesConnected = orphanModules.length === 0;
const clearanceClear = clearanceIssues.length === 0;
return {
visited,
parent,
adjacency,
openPorts,
destinationResults,
orphanModules,
clearanceIssues,
destinationsConnected,
interfacesPaired,
allModulesConnected,
clearanceClear,
complete:
destinationsConnected &&
interfacesPaired &&
allModulesConnected &&
clearanceClear
};
}
function updateModuleStates(validation) {
const index = moduleIndex();
for (const module of allModules()) {
const visual = moduleVisuals.get(module.key);
if (!visual) continue;
const connected = validation.visited.has(module.key);
const def = MODULE_DEFS[module.type];
visual.userData.laneMaterial.emissive.setHex(
connected ? def.color : 0x000000
);
visual.userData.laneMaterial.emissiveIntensity =
connected ? 0.31 : 0.08;
for (const marker of visual.userData.portMarkers) {
const neighborKey = cellKey(
module.gx + marker.port.dx,
module.gz + marker.port.dz
);
const neighbor = index.get(neighborKey);
const paired = neighbor && portsFor(neighbor).some(other =>
other.dx === -marker.port.dx &&
other.dz === -marker.port.dz
);
marker.mesh.material.color.setHex(
!paired ? 0xff6278 :
connected ? 0xeafff9 :
0xffd166
);
}
const indicator = visual.userData.indicator;
if (indicator) {
if (module.type === "sink") {
indicator.material.color.setHex(
connected ? 0x68e3a2 : 0xffbd59
);
indicator.material.emissive.setHex(
connected ? 0x2ca873 : 0x704615
);
}
}
}
}
// ---------------------------------------------------------------------
// Interface
// ---------------------------------------------------------------------
const inventoryElement = document.getElementById("inventory");
const kitRemainingElement = document.getElementById("kitRemaining");
const rotateButton = document.getElementById("rotateBtn");
const undoButton = document.getElementById("undoBtn");
const removeButton = document.getElementById("removeBtn");
const clearButton = document.getElementById("clearBtn");
const checkButton = document.getElementById("checkBtn");
const hintButton = document.getElementById("hintBtn");
const statusBanner = document.getElementById("statusBanner");
const statusTitle = document.getElementById("statusTitle");
const statusCopy = document.getElementById("statusCopy");
const checkList = document.getElementById("checkList");
const selectedInfo = document.getElementById("selectedInfo");
const toastElement = document.getElementById("toast");
function glyphFor(type) {
const paths = {
straight: '<path d="M16 5v22"/>',
corner: '<path d="M16 27V16h11"/>',
tee: '<path d="M16 5v22M16 16h11"/>',
cross: '<path d="M16 5v22M5 16h22"/>'
};
return `
<svg viewBox="0 0 32 32" aria-hidden="true">
${paths[type]}
</svg>
`;
}
function buildInventory() {
inventoryElement.innerHTML = "";
for (const [type, def] of Object.entries(MODULE_DEFS)) {
if (!INITIAL_INVENTORY[type]) continue;
const button = document.createElement("button");
button.className = "kit-card";
button.dataset.type = type;
button.innerHTML = `
<span class="kit-icon" style="color:#${def.color.toString(16).padStart(6, "0")}">
${glyphFor(type)}
</span>
<span class="kit-copy">
<b>${def.name}</b>
<small>${def.short} · clearance r=${def.clearance.toFixed(3)}</small>
</span>
<span class="kit-count"></span>
`;
button.addEventListener("click", () => {
selectedType = type;
selectedRot = 0;
updateKitUI();
rebuildGhost();
});
inventoryElement.appendChild(button);
}
}
function updateKitUI() {
const cards = [...inventoryElement.querySelectorAll(".kit-card")];
for (const card of cards) {
const type = card.dataset.type;
const remaining = inventoryRemaining(type);
card.querySelector(".kit-count").textContent = remaining;
card.classList.toggle("selected", type === selectedType);
card.classList.toggle("exhausted", remaining <= 0);
card.setAttribute(
"aria-pressed",
String(type === selectedType)
);
}
const totalRemaining = Object.keys(INITIAL_INVENTORY).reduce(
(sum, type) => sum + inventoryRemaining(type),
0
);
kitRemainingElement.textContent = `${totalRemaining} modules left`;
const rotations = MODULE_DEFS[selectedType].rotations;
const fake = { type: selectedType, rot: selectedRot };
const portNames = portsFor(fake).map(port => port.key).join("–");
rotateButton.disabled = rotations <= 1;
rotateButton.textContent = `Rotate · R (${portNames})`;
}
function checkRow(good, title, detail) {
return `
<div class="check-row ${good ? "good" : ""}">
<span class="check-icon">${good ? "✓" : "!"}</span>
<div>
<b>${title}</b>
<small>${detail}</small>
</div>
</div>
`;
}
function updateStatus(validation) {
const north = validation.destinationResults[0].connected;
const yard = validation.destinationResults[1].connected;
statusBanner.classList.toggle("success", validation.complete);
if (validation.complete) {
statusTitle.textContent = "Route complete — both destinations connected";
statusCopy.textContent =
"All placed modules are paired, attached to the depot, and clear of keep-out geometry.";
} else {
statusTitle.textContent = "Network incomplete";
const remainingChecks =
(!north ? 1 : 0) +
(!yard ? 1 : 0) +
(!validation.interfacesPaired ? 1 : 0) +
(!validation.allModulesConnected ? 1 : 0) +
(!validation.clearanceClear ? 1 : 0);
statusCopy.textContent =
`${remainingChecks} planning ${remainingChecks === 1 ? "check remains" : "checks remain"}.`;
}
checkList.innerHTML = [
checkRow(
north,
"Depot → North Quay",
north ? "Connected by reciprocal module arms." : "No continuous graph path."
),
checkRow(
yard,
"Depot → Old Yard",
yard ? "Connected by reciprocal module arms." : "No continuous graph path."
),
checkRow(
validation.interfacesPaired,
"Module interfaces",
validation.interfacesPaired
? "Every exposed arm is paired."
: `${validation.openPorts.length} open or mismatched arm${validation.openPorts.length === 1 ? "" : "s"}.`
),
checkRow(
validation.allModulesConnected,
"Depot attachment",
validation.allModulesConnected
? "Every placed module belongs to the depot network."
: `${validation.orphanModules.length} orphan module${validation.orphanModules.length === 1 ? "" : "s"}.`
),
checkRow(
validation.clearanceClear,
"Geometric clearance",
validation.clearanceClear
? "Swept envelopes clear all hard constraints."
: `${validation.clearanceIssues.length} clearance conflict${validation.clearanceIssues.length === 1 ? "" : "s"}.`
)
].join("");
if (selectedKey) {
const module = placedByKey.get(selectedKey);
const fixed = fixedByKey.get(selectedKey);
if (module) {
selectedInfo.textContent =
`Selected ${MODULE_DEFS[module.type].name} at ${coordinateName(module.gx, module.gz)}.`;
} else if (fixed) {
selectedInfo.textContent = `Selected fixed ${fixed.label}.`;
} else {
selectedInfo.textContent = "";
}
} else {
selectedInfo.textContent = "";
}
updateKitUI();
}
let toastTimer = 0;
function showToast(message) {
toastElement.textContent = message;
toastElement.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toastElement.classList.remove("show");
}, 2400);
}
function snapshot() {
return [...placedByKey.values()].map(module => ({
key: module.key,
gx: module.gx,
gz: module.gz,
type: module.type,
rot: module.rot
}));
}
function restoreSnapshot(snapshotData) {
placedByKey.clear();
for (const module of snapshotData) {
placedByKey.set(module.key, {
...module,
fixed: false
});
}
if (selectedKey && !placedByKey.has(selectedKey)) {
selectedKey = null;
}
rebuildEverything();
}
function selectType(type) {
selectedType = type;
selectedRot = 0;
updateKitUI();
rebuildGhost();
}
function rotateBuild() {
const rotations = MODULE_DEFS[selectedType].rotations;
if (rotations <= 1) return;
selectedRot = (selectedRot + 1) % rotations;
updateKitUI();
rebuildGhost();
}
function attemptPlacement(gx, gz) {
const info = candidateInfo(selectedType, selectedRot, gx, gz);
if (!info.ok) {
showToast(info.reason);
return;
}
history.push(snapshot());
const module = {
key: cellKey(gx, gz),
gx,
gz,
type: selectedType,
rot: selectedRot,
fixed: false
};
placedByKey.set(module.key, module);
selectedKey = null;
rebuildEverything();
showToast(
`${MODULE_DEFS[selectedType].name} placed at ${coordinateName(gx, gz)}.`
);
}
function removeSelected() {
if (!selectedKey) {
showToast("Select a placed module first.");
return;
}
if (!placedByKey.has(selectedKey)) {
showToast("Fixed depot and destination modules cannot be removed.");
return;
}
history.push(snapshot());
placedByKey.delete(selectedKey);
selectedKey = null;
rebuildEverything();
showToast("Module returned to the kit.");
}
function clearKit() {
if (placedByKey.size === 0) {
showToast("The board is already clear.");
return;
}
history.push(snapshot());
placedByKey.clear();
selectedKey = null;
rebuildEverything();
showToast("All placed modules returned to the kit.");
}
function undo() {
if (!history.length) {
showToast("Nothing to undo.");
return;
}
restoreSnapshot(history.pop());
showToast("Last placement change undone.");
}
function checkNetwork() {
const validation = validateNetwork();
updateStatus(validation);
statusBanner.classList.remove("pulse");
void statusBanner.offsetWidth;
statusBanner.classList.add("pulse");
showToast(
validation.complete
? "Both destinations are connected and the clearance model passes."
: "Network checked. See the remaining planning checks."
);
}
function showHint() {
const count = placedByKey.size;
if (count === 0) {
showToast("Hint: begin with the depot's east arm at A4.");
} else if (!placedByKey.has("4,3")) {
showToast(
"Hint: the central four-way module at E4 can carry the western stem and both branches."
);
} else {
showToast(
"Hint: try E3/E5 corners, rows 3 and 5 for straights, and H2/H6 as final turns."
);
}
}
buildInventory();
rotateButton.addEventListener("click", rotateBuild);
undoButton.addEventListener("click", undo);
removeButton.addEventListener("click", removeSelected);
clearButton.addEventListener("click", clearKit);
checkButton.addEventListener("click", checkNetwork);
hintButton.addEventListener("click", showHint);
// ---------------------------------------------------------------------
// Ghost preview and pointer controls
// ---------------------------------------------------------------------
function rebuildGhost() {
removeGhost();
if (!hoverCell) return;
const { gx, gz } = hoverCell;
const key = cellKey(gx, gz);
if (fixedByKey.has(key) || placedByKey.has(key)) return;
const info = candidateInfo(selectedType, selectedRot, gx, gz);
const ghostModule = {
key,
gx,
gz,
type: selectedType,
rot: selectedRot
};
ghost = createModuleVisual(ghostModule, true);
ghost.position.copy(worldPosition(gx, gz, 0));
const color = info.ok ? 0x69e4d0 : 0xff6278;
ghost.traverse(child => {
if (!child.material) return;
const materials = Array.isArray(child.material)
? child.material
: [child.material];
for (const material of materials) {
if (material.color) material.color.setHex(color);
if (material.emissive) material.emissive.setHex(color);
}
});
scene.add(ghost);
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const groundPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.02);
function pointerToCell(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;
raycaster.setFromCamera(pointer, camera);
const hit = new THREE.Vector3();
if (!raycaster.ray.intersectPlane(groundPlane, hit)) {
return null;
}
const gx = Math.floor(
(hit.x + (COLS - 1) * CELL / 2) / CELL
);
const gz = Math.floor(
(hit.z + (ROWS - 1) * CELL / 2) / CELL
);
if (gx < 0 || gx >= COLS || gz < 0 || gz >= ROWS) {
return null;
}
return { gx, gz };
}
function updateHover(event) {
const cell = pointerToCell(event);
const changed =
!hoverCell ||
!cell ||
hoverCell.gx !== cell.gx ||
hoverCell.gz !== cell.gz;
hoverCell = cell;
if (!cell) {
hoverTile.visible = false;
if (changed) removeGhost();
return;
}
hoverTile.visible = true;
hoverTile.position.copy(worldPosition(cell.gx, cell.gz, 0.025));
const key = cellKey(cell.gx, cell.gz);
const occupied = fixedByKey.has(key) || placedByKey.has(key);
hoverMaterial.color.setHex(occupied ? 0xffd166 : 0x69e4d0);
if (changed) rebuildGhost();
}
let dragState = null;
canvas.addEventListener("pointerdown", event => {
canvas.setPointerCapture(event.pointerId);
dragState = {
mode: event.button === 2 ? "pan" : "orbit",
x: event.clientX,
y: event.clientY,
startX: event.clientX,
startY: event.clientY,
moved: false
};
});
canvas.addEventListener("pointermove", event => {
if (!dragState) {
updateHover(event);
return;
}
const dx = event.clientX - dragState.x;
const dy = event.clientY - dragState.y;
dragState.x = event.clientX;
dragState.y = event.clientY;
const totalDistance = Math.hypot(
event.clientX - dragState.startX,
event.clientY - dragState.startY
);
if (totalDistance > 4) dragState.moved = true;
if (dragState.mode === "orbit") {
cameraSpherical.theta -= dx * 0.006;
cameraSpherical.phi = THREE.MathUtils.clamp(
cameraSpherical.phi - dy * 0.005,
0.42,
1.30
);
} else {
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 = 0.012 / camera.zoom;
cameraTarget.addScaledVector(right, -dx * scale);
cameraTarget.addScaledVector(forward, -dy * scale);
}
updateCamera();
removeGhost();
});
canvas.addEventListener("pointerup", event => {
if (!dragState) return;
const wasClick = !dragState.moved && dragState.mode === "orbit";
dragState = null;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
updateHover(event);
if (!wasClick || !hoverCell) return;
const { gx, gz } = hoverCell;
const key = cellKey(gx, gz);
if (placedByKey.has(key)) {
selectedKey = key;
updateSelectionRing();
const module = placedByKey.get(key);
showToast(
`${MODULE_DEFS[module.type].name} selected at ${coordinateName(gx, gz)}.`
);
return;
}
if (fixedByKey.has(key)) {
selectedKey = key;
updateSelectionRing();
showToast(`${fixedByKey.get(key).label} is fixed.`);
return;
}
selectedKey = null;
updateSelectionRing();
attemptPlacement(gx, gz);
});
canvas.addEventListener("pointercancel", () => {
dragState = null;
});
canvas.addEventListener("pointerleave", () => {
if (!dragState) {
hoverTile.visible = false;
hoverCell = null;
removeGhost();
}
});
canvas.addEventListener("contextmenu", event => {
event.preventDefault();
});
canvas.addEventListener("wheel", event => {
event.preventDefault();
camera.zoom = THREE.MathUtils.clamp(
camera.zoom * (event.deltaY > 0 ? 0.91 : 1.10),
0.65,
2.45
);
camera.updateProjectionMatrix();
}, { passive: false });
function updateSelectionRing() {
const module = placedByKey.get(selectedKey) || fixedByKey.get(selectedKey);
selectionRing.visible = Boolean(module);
if (module) {
selectionRing.position.copy(
worldPosition(module.gx, module.gz, 0.245)
);
}
}
window.addEventListener("keydown", event => {
if (event.target instanceof HTMLInputElement) return;
const key = event.key.toLowerCase();
if (key === "r") {
rotateBuild();
} else if (key === "z") {
undo();
} else if (event.key === "Delete" || event.key === "Backspace") {
event.preventDefault();
removeSelected();
} else if (event.key === "Escape") {
selectedKey = null;
updateSelectionRing();
} else if (event.code === "Space") {
event.preventDefault();
checkNetwork();
}
});
// ---------------------------------------------------------------------
// Animated route particles
// ---------------------------------------------------------------------
function disposeRouteParticles() {
for (const child of [...routeParticleRoot.children]) {
routeParticleRoot.remove(child);
disposeObject(child);
}
}
function rebuildRouteParticles(validation) {
disposeRouteParticles();
const routes = [];
for (const destination of validation.destinationResults) {
if (!destination.connected) continue;
const path = [];
let current = destination.key;
while (current) {
const [gx, gz] = current.split(",").map(Number);
path.unshift(worldPosition(gx, gz, 0.28));
current = validation.parent.get(current);
}
if (path.length > 1) routes.push(path);
}
for (const path of routes) {
const totalLength = pathLength(path);
for (let i = 0; i < 5; i++) {
const particle = new THREE.Mesh(
new THREE.OctahedronGeometry(0.065, 0),
makeStandardMaterial(0xb6fff2, {
emissive: 0x49d9c4,
emissiveIntensity: 1.1
})
);
particle.userData.path = path;
particle.userData.totalLength = totalLength;
particle.userData.offset = i / 5;
routeParticleRoot.add(particle);
}
}
}
function pathLength(path) {
let length = 0;
for (let i = 1; i < path.length; i++) {
length += path[i].distanceTo(path[i - 1]);
}
return length;
}
function samplePath(path, distance) {
if (path.length === 1) return path[0].clone();
for (let i = 1; i < path.length; i++) {
const segmentLength = path[i].distanceTo(path[i - 1]);
if (distance <= segmentLength) {
const t = segmentLength === 0
? 0
: distance / segmentLength;
return path[i - 1].clone().lerp(path[i], t);
}
distance -= segmentLength;
}
return path[path.length - 1].clone();
}
// ---------------------------------------------------------------------
// World labels
// ---------------------------------------------------------------------
const worldLabels = [];
for (const module of fixedModules) {
const element = document.createElement("div");
element.className = `world-label ${module.type}`;
element.textContent = module.label;
labelLayer.appendChild(element);
worldLabels.push({
element,
gx: module.gx,
gz: module.gz,
height: module.type === "source" ? 0.92 : 0.78
});
}
function updateWorldLabels() {
const width = window.innerWidth;
const height = window.innerHeight;
for (const label of worldLabels) {
const position = worldPosition(label.gx, label.gz, label.height);
position.project(camera);
const visible = position.z > -1 && position.z < 1;
label.element.style.display = visible ? "block" : "none";
if (!visible) continue;
const x = (position.x * 0.5 + 0.5) * width;
const y = (-position.y * 0.5 + 0.5) * height;
label.element.style.transform =
`translate(-50%, -50%) translate(${x}px, ${y}px)`;
}
}
// ---------------------------------------------------------------------
// Final assembly and animation
// ---------------------------------------------------------------------
function rebuildEverything() {
rebuildModuleVisuals();
const validation = validateNetwork();
updateModuleStates(validation);
updateStatus(validation);
rebuildRouteParticles(validation);
updateSelectionRing();
rebuildGhost();
}
rebuildEverything();
const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
const time = clock.getElapsedTime();
for (const particle of routeParticleRoot.children) {
const path = particle.userData.path;
const totalLength = particle.userData.totalLength;
const distance = (
time * 0.95 +
particle.userData.offset * totalLength
) % totalLength;
particle.position.copy(samplePath(path, distance));
particle.rotation.y = time * 2.5;
particle.rotation.x = time * 1.7;
}
for (const module of fixedModules) {
const visual = moduleVisuals.get(module.key);
if (!visual?.userData.indicator) continue;
visual.userData.indicator.rotation.y = time * 1.4;
visual.userData.indicator.position.y =
module.type === "source"
? 0.55 + Math.sin(time * 2.2) * 0.035
: 0.46 + Math.sin(time * 2.2 + 1.3) * 0.025;
}
updateWorldLabels();
renderer.render(scene, camera);
});
</script>
</body>
</html>
```