Prompt specification
Build or customize the Three.js 3D scene "One Support Removed Route Repair" 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: One Support Removed Route Repair
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/one-support-removed-route-repair-x3444
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing a low-poly bridge-repair construction puzzle. A small character needs to cross a river using a fixed collection of planks, short piers, and walkway tiles. Begin with a valid route, then mark one pier location unavailable and return its supported pieces to the player's inventory. Let the player reuse the remaining modules without receiving extra parts. Each placed plank must meet the game's explicit support and overlap rules, and the resulting walking surface must form a connected route. Test the character's crossing only after placement, highlighting the first unsupported span or disconnected edge when the proposed repair fails.
Keep discarded and currently placed modules in separate visible trays, with the count updating after every move so players can account for the entire available kit.
Working Three.js Starter (one-support-removed-route-repair-x3444):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Timberline Crossing — Bridge Repair Puzzle</title>
<style>
:root {
--ink: #17343d;
--muted: #55727a;
--panel: rgba(247, 251, 249, 0.94);
--line: rgba(36, 77, 84, 0.17);
--cyan: #0a9daa;
--cyan-dark: #087681;
--amber: #d18a26;
--red: #d94d47;
--green: #27875d;
--shadow: 0 12px 35px rgba(17, 54, 62, 0.18);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #a9d9e7;
color: var(--ink);
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;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
.panel {
background: var(--panel);
border: 1px solid rgba(255, 255, 255, 0.74);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
}
#brief {
position: fixed;
top: 18px;
left: 18px;
width: min(370px, calc(100vw - 36px));
max-height: calc(100vh - 245px);
padding: 17px 18px 15px;
border-radius: 18px;
overflow: auto;
z-index: 4;
}
.eyebrow {
margin: 0 0 5px;
color: var(--cyan-dark);
font-size: 11px;
font-weight: 850;
letter-spacing: 0.14em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 25px;
line-height: 1.05;
letter-spacing: -0.04em;
}
.subtitle {
margin: 7px 0 13px;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.phase {
display: inline-flex;
align-items: center;
gap: 7px;
margin-bottom: 12px;
padding: 6px 10px;
border-radius: 999px;
background: #e1f4f1;
color: #08736f;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.04em;
}
.phase::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 0 4px rgba(10, 157, 170, 0.12);
}
.rules {
margin: 0;
padding: 11px 12px 11px 28px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.58);
color: #385961;
font-size: 12px;
line-height: 1.48;
}
.rules li + li {
margin-top: 5px;
}
.rules strong {
color: var(--ink);
}
#statusBox {
margin-top: 11px;
padding: 11px 12px;
border-left: 4px solid var(--cyan);
border-radius: 8px 11px 11px 8px;
background: rgba(230, 246, 244, 0.72);
transition: border-color 160ms ease, background 160ms ease;
}
#statusBox.error {
border-left-color: var(--red);
background: rgba(255, 232, 229, 0.82);
}
#statusBox.success {
border-left-color: var(--green);
background: rgba(229, 247, 235, 0.86);
}
#statusTitle {
margin: 0 0 3px;
font-size: 13px;
font-weight: 850;
}
#statusText {
margin: 0;
color: #4d6870;
font-size: 12px;
line-height: 1.42;
}
#selectionText {
min-height: 34px;
margin: 10px 1px 8px;
color: var(--muted);
font-size: 12px;
line-height: 1.4;
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.button {
min-height: 38px;
padding: 9px 12px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.85);
color: var(--ink);
font-size: 12px;
font-weight: 800;
cursor: pointer;
transition: transform 120ms ease, background 120ms ease, opacity 120ms ease;
}
.button:hover:not(:disabled) {
transform: translateY(-1px);
background: white;
}
.button:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.button.primary {
border-color: var(--cyan);
background: var(--cyan);
color: white;
}
.button.primary:hover:not(:disabled) {
background: var(--cyan-dark);
}
.button.danger {
color: #ad3935;
}
#testButton {
grid-column: 1 / -1;
min-height: 44px;
font-size: 13px;
}
#kitDock {
position: fixed;
left: 18px;
right: 18px;
bottom: 18px;
display: grid;
grid-template-columns: 1fr 1fr 1.25fr;
gap: 11px;
z-index: 4;
pointer-events: none;
}
.tray {
min-width: 0;
max-height: 205px;
padding: 12px 13px;
border-radius: 16px;
overflow: auto;
pointer-events: auto;
}
.tray-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 9px;
}
.tray-heading h2 {
margin: 0;
font-size: 12px;
font-weight: 900;
letter-spacing: 0.055em;
text-transform: uppercase;
}
.count {
min-width: 23px;
padding: 3px 7px;
border-radius: 999px;
background: #dceceb;
color: #17666d;
font-size: 11px;
font-weight: 900;
text-align: center;
}
.balance {
margin: 1px 0 9px;
color: var(--muted);
font-size: 10.5px;
line-height: 1.35;
}
.parts {
display: flex;
flex-wrap: wrap;
gap: 7px;
}
.part {
display: flex;
align-items: center;
gap: 7px;
min-width: 105px;
padding: 8px 9px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.72);
color: var(--ink);
cursor: pointer;
text-align: left;
}
.part:disabled {
opacity: 0.38;
cursor: not-allowed;
}
.part.selected {
border-color: var(--cyan);
background: #e4f7f4;
box-shadow: 0 0 0 2px rgba(10, 157, 170, 0.12);
}
.part.locked {
cursor: default;
}
.swatch {
width: 16px;
height: 16px;
flex: 0 0 auto;
border-radius: 4px;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.12);
}
.swatch.pier {
background: linear-gradient(90deg, #496b72 0 42%, #b88a55 42% 100%);
}
.swatch.plank {
background: #b5773f;
}
.swatch.tile {
background: #d8b56b;
}
.part-name {
display: block;
font-size: 11px;
font-weight: 850;
}
.part-meta {
display: block;
margin-top: 1px;
color: var(--muted);
font-size: 9.5px;
}
.placed-list {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 5px;
}
.placed-item,
.discarded-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 6px;
min-width: 0;
padding: 6px 8px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255, 255, 255, 0.65);
color: var(--ink);
font-size: 10.5px;
}
.placed-item {
cursor: pointer;
text-align: left;
}
.placed-item.selected {
border-color: var(--cyan);
background: #e4f7f4;
}
.placed-item span,
.discarded-item span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.mini-button {
flex: 0 0 auto;
padding: 3px 6px;
border: 1px solid var(--line);
border-radius: 6px;
background: white;
color: var(--cyan-dark);
font-size: 9px;
font-weight: 850;
cursor: pointer;
}
.mini-button:disabled {
color: var(--muted);
cursor: not-allowed;
opacity: 0.65;
}
#cameraHelp {
position: fixed;
top: 18px;
right: 18px;
max-width: 260px;
padding: 10px 12px;
border-radius: 12px;
color: #315860;
font-size: 10.5px;
line-height: 1.45;
z-index: 3;
}
#cameraHelp strong {
color: var(--ink);
}
#resetCamera {
display: block;
margin-top: 7px;
padding: 5px 8px;
border: 1px solid var(--line);
border-radius: 7px;
background: rgba(255, 255, 255, 0.78);
color: var(--ink);
font-size: 10px;
font-weight: 800;
cursor: pointer;
}
#tooltip {
position: fixed;
z-index: 8;
display: none;
max-width: 220px;
padding: 7px 9px;
border-radius: 8px;
background: rgba(20, 48, 55, 0.92);
color: white;
font-size: 10.5px;
line-height: 1.35;
pointer-events: none;
transform: translate(12px, 12px);
}
#toast {
position: fixed;
left: 50%;
bottom: 240px;
z-index: 10;
max-width: min(520px, calc(100vw - 36px));
padding: 9px 13px;
border-radius: 999px;
background: rgba(22, 55, 62, 0.93);
color: white;
font-size: 11px;
font-weight: 700;
text-align: center;
opacity: 0;
transform: translate(-50%, 8px);
transition: opacity 160ms ease, transform 160ms ease;
pointer-events: none;
}
#toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
#startOverlay {
position: fixed;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
padding: 20px;
background: rgba(25, 67, 75, 0.28);
backdrop-filter: blur(4px);
}
#startOverlay.hidden {
display: none;
}
.start-card {
width: min(460px, 100%);
padding: 25px;
border: 1px solid rgba(255, 255, 255, 0.85);
border-radius: 22px;
background: rgba(249, 252, 249, 0.96);
box-shadow: 0 25px 80px rgba(13, 52, 61, 0.28);
}
.start-card h2 {
margin: 0 0 9px;
font-size: 28px;
letter-spacing: -0.04em;
}
.start-card p {
margin: 0 0 12px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.inspection {
margin: 15px 0;
padding: 12px 13px;
border: 1px solid #cde3dd;
border-radius: 12px;
background: #eaf6f0;
color: #286849;
font-size: 12px;
line-height: 1.45;
}
#startRepair {
width: 100%;
min-height: 47px;
}
@media (max-width: 900px) {
#brief {
width: 320px;
max-height: calc(100vh - 255px);
}
#kitDock {
grid-template-columns: 1fr 1fr;
}
#placedTray {
grid-column: 1 / -1;
max-height: 132px;
}
.placed-list {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
#toast {
bottom: 285px;
}
}
@media (max-width: 620px) {
#brief {
top: 9px;
left: 9px;
width: calc(100vw - 18px);
max-height: 43vh;
padding: 13px;
}
h1 {
font-size: 21px;
}
.rules {
display: none;
}
#kitDock {
left: 8px;
right: 8px;
bottom: 8px;
gap: 6px;
}
.tray {
padding: 9px;
max-height: 145px;
}
#placedTray {
max-height: 120px;
}
.placed-list {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.part {
min-width: 88px;
padding: 6px;
}
#cameraHelp {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive low-poly bridge repair puzzle"></canvas>
<section id="brief" class="panel">
<p class="eyebrow">Field Repair Challenge</p>
<h1>Timberline Crossing</h1>
<p class="subtitle">
Reuse the exact kit on the river. No extra parts will be issued.
</p>
<div id="phaseBadge" class="phase">Inspection</div>
<ol class="rules">
<li><strong>Short piers</strong> snap to empty support sockets P1–P5.</li>
<li><strong>Planks and tiles</strong> occupy exactly one marked bay.</li>
<li>
A deck piece needs support at <strong>at least one end</strong>.
Its bearing must lap the support centerline by <strong>0.05 m</strong> or more.
</li>
<li>
Neighboring deck pieces must share <strong>0.08–0.16 m</strong>
of joint overlap. Double placement is never allowed.
</li>
<li>
Outer bays may bear on the <strong>riverbank abutments</strong>.
P3 will be locked when the inspection event occurs.
</li>
</ol>
<div id="statusBox">
<p id="statusTitle">Route inspection</p>
<p id="statusText">
The original crossing is structurally valid. Inspect it before the closure event.
</p>
</div>
<div id="selectionText">Select a part from the Available tray.</div>
<div class="actions">
<button id="returnButton" class="button" disabled>Return selected</button>
<button id="discardButton" class="button danger" disabled>Discard 1 part</button>
<button id="testButton" class="button primary" disabled>Test character crossing</button>
<button id="restartButton" class="button">Restart puzzle</button>
</div>
</section>
<aside id="cameraHelp" class="panel">
<strong>Camera controls</strong><br />
Drag to orbit · Scroll to zoom<br />
Click glowing sockets to place parts.
<button id="resetCamera">Reset camera</button>
</aside>
<div id="kitDock">
<section class="tray panel">
<div class="tray-heading">
<h2>Available / Inventory</h2>
<span id="availableCount" class="count">0</span>
</div>
<div id="balanceText" class="balance">Kit balance: 0 available + 0 discarded + 0 placed</div>
<div id="availableTray" class="parts"></div>
</section>
<section class="tray panel">
<div class="tray-heading">
<h2>Discarded</h2>
<span id="discardedCount" class="count">0</span>
</div>
<div id="discardedTray" class="parts"></div>
</section>
<section id="placedTray" class="tray panel">
<div class="tray-heading">
<h2>Currently Placed</h2>
<span id="placedCount" class="count">0</span>
</div>
<div id="placedList" class="placed-list"></div>
</section>
</div>
<div id="tooltip"></div>
<div id="toast"></div>
<div id="startOverlay">
<div class="start-card">
<p class="eyebrow">Pre-closure inspection</p>
<h2>The crossing is valid—for now.</h2>
<p>
All six bays are connected, and short piers P1, P3, and P5 support the route.
The worksite has warned that support point <strong>P3 may be lost to flooding</strong>.
</p>
<div class="inspection">
<strong>Inspection result:</strong> The character can safely cross the original bridge.
After P3 is closed, the two deck pieces bearing on P3 will return to inventory.
The damaged pier will be discarded, but every other module remains reusable.
</div>
<button id="startRepair" class="button primary">
Mark P3 unavailable and begin repair
</button>
</div>
</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 constants
// -------------------------------------------------------------------------
const $ = (id) => document.getElementById(id);
const canvas = $("scene");
const TYPE_NAMES = {
pier: "Short pier",
plank: "Plank",
tile: "Walkway tile"
};
const TYPE_ORDER = ["pier", "plank", "tile"];
const STATION_SPACING = 2.0;
const ANCHOR_X = [-7, -5, -3, -1, 1, 3, 5];
const BAY_COUNT = 6;
const CLOSED_ANCHOR = 3;
const MODULE_LENGTH = {
plank: 2.12,
tile: 2.14
};
const MIN_BEARING_LAP = 0.05;
const MIN_JOINT_OVERLAP = 0.08;
const MAX_JOINT_OVERLAP = 0.16;
const state = {
phase: "inspection",
closed: false,
selectedType: null,
selectedModule: null,
routeChanged: false,
lastTestSuccess: false,
crossing: false,
fault: null
};
let toastTimer = 0;
function toast(message) {
$("toast").textContent = message;
$("toast").classList.add("visible");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => $("toast").classList.remove("visible"), 2400);
}
function setStatus(title, text, kind = "") {
$("statusTitle").textContent = title;
$("statusText").textContent = text;
$("statusBox").className = kind;
}
// -------------------------------------------------------------------------
// Renderer, camera, lights
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xa9d9e7);
scene.fog = new THREE.Fog(0xa9d9e7, 25, 49);
const camera = new THREE.PerspectiveCamera(
40,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraState = {
azimuth: 0.67,
polar: 0.94,
radius: 20.5,
target: new THREE.Vector3(0, 0.7, 0)
};
function updateCamera() {
const s = Math.sin(cameraState.polar);
const y = Math.cos(cameraState.polar) * cameraState.radius;
const horizontal = s * cameraState.radius;
camera.position.set(
cameraState.target.x + Math.sin(cameraState.azimuth) * horizontal,
cameraState.target.y + y,
cameraState.target.z + Math.cos(cameraState.azimuth) * horizontal
);
camera.lookAt(cameraState.target);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xdaf7ff, 0x536b42, 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff2cf, 3.2);
sun.position.set(-8, 15, 10);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -15;
sun.shadow.camera.right = 15;
sun.shadow.camera.top = 12;
sun.shadow.camera.bottom = -12;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 40;
sun.shadow.bias = -0.0005;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x9ed9ef, 0.8);
fill.position.set(9, 7, -10);
scene.add(fill);
// -------------------------------------------------------------------------
// Materials
// -------------------------------------------------------------------------
const materials = {
bank: new THREE.MeshStandardMaterial({
color: 0x759657,
roughness: 0.95,
flatShading: true
}),
bankSide: new THREE.MeshStandardMaterial({
color: 0x8c7352,
roughness: 1,
flatShading: true
}),
wood: new THREE.MeshStandardMaterial({
color: 0xa96d37,
roughness: 0.88,
flatShading: true
}),
woodLight: new THREE.MeshStandardMaterial({
color: 0xc28a50,
roughness: 0.9,
flatShading: true
}),
woodDark: new THREE.MeshStandardMaterial({
color: 0x774526,
roughness: 1,
flatShading: true
}),
pierStone: new THREE.MeshStandardMaterial({
color: 0x58737a,
roughness: 0.92,
flatShading: true
}),
tile: new THREE.MeshStandardMaterial({
color: 0xd6b36a,
roughness: 0.94,
flatShading: true
}),
tileEdge: new THREE.MeshStandardMaterial({
color: 0xa67b37,
roughness: 1,
flatShading: true
}),
metal: new THREE.MeshStandardMaterial({
color: 0x44575a,
roughness: 0.7,
metalness: 0.25,
flatShading: true
}),
character: new THREE.MeshStandardMaterial({
color: 0xf3a52c,
roughness: 0.82,
flatShading: true
}),
shirt: new THREE.MeshStandardMaterial({
color: 0x267d91,
roughness: 0.85,
flatShading: true
}),
skin: new THREE.MeshStandardMaterial({
color: 0xe7b58a,
roughness: 0.85,
flatShading: true
}),
trousers: new THREE.MeshStandardMaterial({
color: 0x334a58,
roughness: 0.9,
flatShading: true
})
};
// -------------------------------------------------------------------------
// Environment
// -------------------------------------------------------------------------
let seed = 80317;
function random() {
seed = (seed * 1664525 + 1013904223) >>> 0;
return seed / 4294967296;
}
function addBox(parent, size, position, material, shadow = true) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size[0], size[1], size[2]),
material
);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = shadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
const environment = new THREE.Group();
scene.add(environment);
// Faceted river surface.
const waterGeometry = new THREE.PlaneGeometry(13.6, 14, 14, 14);
const waterPositions = waterGeometry.attributes.position;
for (let i = 0; i < waterPositions.count; i++) {
waterPositions.setZ(i, (random() - 0.5) * 0.10);
}
waterGeometry.rotateX(-Math.PI / 2);
waterGeometry.computeVertexNormals();
const waterMaterial = new THREE.MeshStandardMaterial({
color: 0x3f9fb1,
roughness: 0.42,
metalness: 0.08,
transparent: true,
opacity: 0.93,
flatShading: true,
side: THREE.DoubleSide
});
const water = new THREE.Mesh(waterGeometry, waterMaterial);
water.receiveShadow = true;
environment.add(water);
// Riverbanks.
const leftBank = addBox(
environment,
[6.2, 1.45, 14],
[-10.1, 0.32, 0],
materials.bank
);
leftBank.material = materials.bank;
const rightBank = addBox(
environment,
[5.0, 1.45, 14],
[8.1, 0.32, 0],
materials.bank
);
// Visible earth under the grassy bank edges.
addBox(environment, [6.25, 0.42, 14.05], [-10.1, -0.32, 0], materials.bankSide);
addBox(environment, [5.05, 0.42, 14.05], [8.1, -0.32, 0], materials.bankSide);
// Abutments at the two fixed bank supports.
addBox(environment, [0.72, 0.38, 1.72], [ANCHOR_X[0], 0.88, 0], materials.pierStone);
addBox(environment, [0.72, 0.38, 1.72], [ANCHOR_X[6], 0.88, 0], materials.pierStone);
// Low-poly stones and trees.
function addTree(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 1.05, z);
group.scale.setScalar(scale);
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.13, 0.18, 1.2, 5),
materials.woodDark
);
trunk.position.y = 0.6;
trunk.castShadow = true;
group.add(trunk);
const crown = new THREE.Mesh(
new THREE.ConeGeometry(0.72, 1.8, 7),
new THREE.MeshStandardMaterial({
color: random() > 0.5 ? 0x3f7950 : 0x4e8b58,
roughness: 1,
flatShading: true
})
);
crown.position.y = 1.75;
crown.castShadow = true;
group.add(crown);
environment.add(group);
}
addTree(-10.4, -4.8, 1.12);
addTree(-9.1, 4.7, 0.88);
addTree(-11.3, 2.4, 0.72);
addTree(9.2, -4.3, 1.02);
addTree(8.0, 4.8, 0.82);
addTree(10.1, 2.1, 0.7);
for (let i = 0; i < 26; i++) {
const side = i % 2 === 0 ? -1 : 1;
const x = side < 0
? -7.35 - random() * 5.5
: 5.85 + random() * 5.1;
const z = -6.6 + random() * 13.2;
const rock = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.16 + random() * 0.22, 0),
new THREE.MeshStandardMaterial({
color: random() > 0.5 ? 0x8d9584 : 0xa5aa96,
roughness: 1,
flatShading: true
})
);
rock.position.set(x, 1.08, z);
rock.rotation.set(random(), random(), random());
rock.scale.y = 0.55 + random() * 0.45;
rock.castShadow = true;
environment.add(rock);
}
// Visible support foundations.
for (let i = 1; i <= 5; i++) {
const foundation = new THREE.Mesh(
new THREE.CylinderGeometry(0.53, 0.62, 0.13, 8),
new THREE.MeshStandardMaterial({
color: 0x809798,
roughness: 1,
flatShading: true
})
);
foundation.position.set(ANCHOR_X[i], 0.05, 0);
foundation.receiveShadow = true;
environment.add(foundation);
}
// -------------------------------------------------------------------------
// Fixed module inventory
// -------------------------------------------------------------------------
const modules = new Map();
function addModule(id, type, stateName, slot = null, anchor = null, broken = false) {
modules.set(id, {
id,
type,
state: stateName,
slot,
anchor,
broken
});
}
function initialModuleState() {
modules.clear();
addModule("pier-1", "pier", "placed", null, 1);
addModule("pier-2", "pier", "placed", null, 3);
addModule("pier-3", "pier", "placed", null, 5);
addModule("span-1", "tile", "placed", 0);
addModule("span-2", "plank", "placed", 1);
addModule("span-3", "plank", "placed", 2);
addModule("span-4", "tile", "placed", 3);
addModule("span-5", "plank", "placed", 4);
addModule("span-6", "plank", "placed", 5);
}
initialModuleState();
function moduleById(id) {
return modules.get(id);
}
function modulesWithState(stateName) {
return [...modules.values()].filter((m) => m.state === stateName);
}
function countByType(stateName, type) {
return modulesWithState(stateName).filter((m) => m.type === type).length;
}
function spanAt(slot) {
return modulesWithState("placed").find((m) => m.slot === slot) || null;
}
function pierAt(anchor) {
return modulesWithState("placed").find((m) => m.anchor === anchor) || null;
}
function availableModuleOfType(type) {
return modulesWithState("available").find((m) => m.type === type) || null;
}
// -------------------------------------------------------------------------
// Module visuals and placement targets
// -------------------------------------------------------------------------
const moduleRoot = new THREE.Group();
const markerRoot = new THREE.Group();
const faultRoot = new THREE.Group();
const characterRoot = new THREE.Group();
scene.add(moduleRoot, markerRoot, faultRoot, characterRoot);
const moduleGroups = new Map();
const spanMarkers = [];
const pierMarkers = [];
const pickProxies = [];
const invisibleProxyMaterial = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false
});
function createSpanMarker(slot) {
const markerMaterial = new THREE.MeshBasicMaterial({
color: 0x42d5d0,
transparent: true,
opacity: 0.24,
depthWrite: false
});
const marker = new THREE.Mesh(
new THREE.BoxGeometry(2.05, 0.035, 1.38),
markerMaterial
);
marker.position.set(
(ANCHOR_X[slot] + ANCHOR_X[slot + 1]) / 2,
1.33,
0
);
marker.visible = false;
markerRoot.add(marker);
spanMarkers.push(marker);
const proxy = new THREE.Mesh(
new THREE.BoxGeometry(2.05, 0.18, 1.38),
invisibleProxyMaterial
);
proxy.position.copy(marker.position);
proxy.userData.target = { kind: "span", slot };
markerRoot.add(proxy);
pickProxies.push(proxy);
}
function createPierMarker(anchor) {
const markerMaterial = new THREE.MeshBasicMaterial({
color: 0x42d5d0,
transparent: true,
opacity: 0.35,
depthWrite: false
});
const marker = new THREE.Mesh(
new THREE.TorusGeometry(0.57, 0.055, 4, 12),
markerMaterial
);
marker.rotation.x = Math.PI / 2;
marker.position.set(ANCHOR_X[anchor], 1.32, 0);
marker.visible = false;
markerRoot.add(marker);
pierMarkers.push(marker);
const proxy = new THREE.Mesh(
new THREE.CylinderGeometry(0.57, 0.57, 0.22, 10),
invisibleProxyMaterial
);
proxy.position.set(ANCHOR_X[anchor], 1.23, 0);
proxy.userData.target = { kind: "pier", anchor };
markerRoot.add(proxy);
pickProxies.push(proxy);
}
for (let i = 0; i < BAY_COUNT; i++) createSpanMarker(i);
for (let i = 1; i <= 5; i++) createPierMarker(i);
// Permanent warning X above closed support P3.
const closedMarker = new THREE.Group();
const closedMaterial = new THREE.MeshBasicMaterial({
color: 0xe34e45,
transparent: true,
opacity: 0.88,
depthTest: false
});
for (const angle of [-Math.PI / 4, Math.PI / 4]) {
const bar = new THREE.Mesh(
new THREE.BoxGeometry(1.05, 0.045, 0.10),
closedMaterial
);
bar.rotation.y = angle;
bar.position.set(ANCHOR_X[CLOSED_ANCHOR], 1.42, 0);
bar.renderOrder = 12;
closedMarker.add(bar);
}
closedMarker.visible = false;
markerRoot.add(closedMarker);
function clearGroup(group) {
for (const child of [...group.children]) {
child.traverse((object) => {
if (object.geometry) object.geometry.dispose();
});
group.remove(child);
}
}
function createModuleVisual(module) {
const group = new THREE.Group();
group.userData.moduleId = module.id;
if (module.type === "pier") {
group.position.x = ANCHOR_X[module.anchor];
const post = new THREE.Mesh(
new THREE.CylinderGeometry(0.37, 0.50, 1.00, 6),
materials.pierStone
);
post.position.y = 0.54;
post.castShadow = true;
post.receiveShadow = true;
group.add(post);
const cap = addBox(
group,
[0.92, 0.18, 1.48],
[0, 1.01, 0],
materials.woodDark
);
cap.castShadow = true;
const brace = addBox(
group,
[0.82, 0.13, 0.17],
[0, 0.46, 0],
materials.wood
);
brace.rotation.z = 0.38;
const boltLeft = new THREE.Mesh(
new THREE.CylinderGeometry(0.055, 0.055, 0.035, 8),
materials.metal
);
boltLeft.position.set(-0.31, 1.115, 0.48);
group.add(boltLeft);
const boltRight = boltLeft.clone();
boltRight.position.x = 0.31;
group.add(boltRight);
} else if (module.type === "plank") {
const length = MODULE_LENGTH.plank;
group.position.x = (ANCHOR_X[module.slot] + ANCHOR_X[module.slot + 1]) / 2;
for (let i = -1; i <= 1; i++) {
const board = addBox(
group,
[length, 0.16, 0.38],
[0, 1.18, i * 0.42],
i === 0 ? materials.woodLight : materials.wood
);
board.castShadow = true;
}
for (const x of [-0.76, 0.76]) {
for (const z of [-0.43, 0.43]) {
const nail = new THREE.Mesh(
new THREE.CylinderGeometry(0.035, 0.035, 0.025, 8),
materials.metal
);
nail.position.set(x, 1.272, z);
group.add(nail);
}
}
} else {
const length = MODULE_LENGTH.tile;
group.position.x = (ANCHOR_X[module.slot] + ANCHOR_X[module.slot + 1]) / 2;
addBox(
group,
[length, 0.22, 1.42],
[0, 1.16, 0],
materials.tile
);
for (const x of [-0.72, 0.72]) {
addBox(
group,
[0.08, 0.028, 1.30],
[x, 1.283, 0],
materials.tileEdge
);
}
addBox(
group,
[length - 0.18, 0.028, 0.08],
[0, 1.283, 0],
materials.tileEdge
);
}
return group;
}
function rebuildModuleVisuals() {
clearGroup(moduleRoot);
moduleGroups.clear();
for (const module of modulesWithState("placed")) {
const group = createModuleVisual(module);
moduleRoot.add(group);
moduleGroups.set(module.id, group);
}
updateSelectionOutline();
}
let selectionOutline = null;
function updateSelectionOutline() {
if (selectionOutline) {
scene.remove(selectionOutline);
selectionOutline.geometry.dispose();
selectionOutline.material.dispose();
selectionOutline = null;
}
if (!state.selectedModule) return;
const group = moduleGroups.get(state.selectedModule);
if (!group) return;
selectionOutline = new THREE.BoxHelper(group, 0x36e4e0);
selectionOutline.material.depthTest = false;
selectionOutline.material.transparent = true;
selectionOutline.material.opacity = 0.95;
selectionOutline.renderOrder = 9;
scene.add(selectionOutline);
}
function updateMarkers() {
const showSpans =
state.phase === "repair" &&
(state.selectedType === "plank" || state.selectedType === "tile");
const showPiers =
state.phase === "repair" &&
state.selectedType === "pier";
spanMarkers.forEach((marker, slot) => {
marker.visible = showSpans && !spanAt(slot);
marker.material.opacity = 0.32;
});
pierMarkers.forEach((marker, anchor) => {
const unavailable = state.closed && anchor === CLOSED_ANCHOR;
marker.visible = showPiers && !pierAt(anchor) && !unavailable;
});
closedMarker.visible = state.closed;
}
// -------------------------------------------------------------------------
// Character
// -------------------------------------------------------------------------
function buildCharacter() {
const body = new THREE.Group();
const leftLeg = new THREE.Mesh(
new THREE.CylinderGeometry(0.09, 0.10, 0.45, 6),
materials.trousers
);
leftLeg.position.set(0, 0.23, -0.13);
leftLeg.castShadow = true;
body.add(leftLeg);
const rightLeg = leftLeg.clone();
rightLeg.position.z = 0.13;
body.add(rightLeg);
const torso = new THREE.Mesh(
new THREE.CylinderGeometry(0.23, 0.27, 0.48, 6),
materials.shirt
);
torso.position.y = 0.69;
torso.castShadow = true;
body.add(torso);
const belt = new THREE.Mesh(
new THREE.CylinderGeometry(0.27, 0.27, 0.09, 6),
materials.metal
);
belt.position.y = 0.49;
body.add(belt);
const head = new THREE.Mesh(
new THREE.SphereGeometry(0.225, 8, 6),
materials.skin
);
head.position.y = 1.10;
head.castShadow = true;
body.add(head);
const hat = new THREE.Mesh(
new THREE.CylinderGeometry(0.25, 0.28, 0.12, 8),
materials.character
);
hat.position.y = 1.29;
hat.castShadow = true;
body.add(hat);
const brim = new THREE.Mesh(
new THREE.BoxGeometry(0.48, 0.045, 0.52),
materials.character
);
brim.position.y = 1.25;
brim.castShadow = true;
body.add(brim);
const leftArm = new THREE.Mesh(
new THREE.CylinderGeometry(0.065, 0.075, 0.42, 6),
materials.shirt
);
leftArm.position.set(0, 0.70, -0.29);
leftArm.rotation.x = -0.17;
leftArm.castShadow = true;
body.add(leftArm);
const rightArm = leftArm.clone();
rightArm.position.z = 0.29;
body.add(rightArm);
return body;
}
const character = buildCharacter();
characterRoot.add(character);
const START_X = -8.25;
const END_X = 6.25;
let crossingAnimation = null;
function resetCharacter() {
character.position.set(START_X, 1.08, 0);
character.rotation.set(0, 0, 0);
crossingAnimation = null;
}
resetCharacter();
const crossingPath = [
START_X,
...Array.from({ length: BAY_COUNT }, (_, i) =>
(ANCHOR_X[i] + ANCHOR_X[i + 1]) / 2
),
END_X
];
function startCrossing() {
state.crossing = true;
resetCharacter();
crossingAnimation = {
startTime: performance.now(),
duration: 6800
};
refreshUI();
}
function updateCrossing(now) {
if (!crossingAnimation) return;
const t = Math.min(
1,
(now - crossingAnimation.startTime) / crossingAnimation.duration
);
const eased = t * t * (3 - 2 * t);
const scaled = eased * (crossingPath.length - 1);
const index = Math.min(
crossingPath.length - 2,
Math.floor(scaled)
);
const local = scaled - index;
const x = THREE.MathUtils.lerp(
crossingPath[index],
crossingPath[index + 1],
local
);
const isBank = x < -7.05 || x > 5.65;
const baseY = isBank ? 1.08 : 1.27;
const bob = isBank ? 0 : Math.sin(t * Math.PI * 18) * 0.018;
character.position.set(x, baseY + bob, 0);
character.rotation.z = Math.sin(t * Math.PI * 18) * 0.015;
if (t >= 1) {
crossingAnimation = null;
state.crossing = false;
state.routeChanged = false;
state.lastTestSuccess = true;
setStatus(
"Crossing certified",
"Every bay is connected and supported. The repair uses only modules from the original kit.",
"success"
);
refreshUI();
}
}
// -------------------------------------------------------------------------
// Structural rules and validation
// -------------------------------------------------------------------------
function bearingLap(module) {
return (MODULE_LENGTH[module.type] - STATION_SPACING) / 2;
}
function jointOverlap(first, second) {
return (
MODULE_LENGTH[first.type] +
MODULE_LENGTH[second.type] -
2 * STATION_SPACING
) / 2;
}
function supportsForBay(slot) {
const supports = [];
const leftAnchor = slot;
const rightAnchor = slot + 1;
if (leftAnchor === 0) {
supports.push({ anchor: leftAnchor, kind: "bank" });
} else if (pierAt(leftAnchor)) {
supports.push({ anchor: leftAnchor, kind: "pier" });
}
if (rightAnchor === 6) {
supports.push({ anchor: rightAnchor, kind: "bank" });
} else if (pierAt(rightAnchor)) {
supports.push({ anchor: rightAnchor, kind: "pier" });
}
return supports;
}
function validateRoute() {
for (let slot = 0; slot < BAY_COUNT; slot++) {
const module = spanAt(slot);
if (!module) {
return {
ok: false,
kind: "missing",
slot,
title: `Disconnected edge at Bay ${slot + 1}`,
text:
"A required deck piece is missing. The route is not connected from the near bank to the far bank."
};
}
const supports = supportsForBay(slot);
const lap = bearingLap(module);
if (supports.length === 0) {
return {
ok: false,
kind: "unsupported",
slot,
title: `Unsupported span at Bay ${slot + 1}`,
text:
"Neither end bears on a pier or bank abutment. Move a short pier under this span or redesign the adjacent bays."
};
}
if (lap < MIN_BEARING_LAP) {
return {
ok: false,
kind: "unsupported",
slot,
title: `Insufficient bearing at Bay ${slot + 1}`,
text:
`The deck piece laps the support centerline by only ${lap.toFixed(2)} m; ${MIN_BEARING_LAP.toFixed(2)} m is required.`
};
}
if (slot > 0) {
const previous = spanAt(slot - 1);
const overlap = jointOverlap(previous, module);
if (
overlap < MIN_JOINT_OVERLAP ||
overlap > MAX_JOINT_OVERLAP
) {
return {
ok: false,
kind: "joint",
slot,
anchor: slot,
title: `Disconnected edge before Bay ${slot + 1}`,
text:
`The neighboring deck pieces overlap by ${overlap.toFixed(2)} m. The required joint overlap is ${MIN_JOINT_OVERLAP.toFixed(2)}–${MAX_JOINT_OVERLAP.toFixed(2)} m.`
};
}
}
}
return {
ok: true,
title: "Route is structurally valid",
text:
"All six bays are occupied, adjacent, and supported. The character may attempt the crossing."
};
}
function clearFault() {
clearGroup(faultRoot);
state.fault = null;
}
function highlightFault(fault) {
clearFault();
state.fault = fault;
const redMaterial = new THREE.MeshBasicMaterial({
color: 0xe84640,
transparent: true,
opacity: 0.38,
depthTest: false,
depthWrite: false
});
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0xff4d45,
transparent: true,
opacity: 0.96,
depthTest: false
});
let x;
let width;
if (fault.kind === "joint") {
x = ANCHOR_X[fault.anchor];
width = 0.26;
} else {
x = (ANCHOR_X[fault.slot] + ANCHOR_X[fault.slot + 1]) / 2;
width = 2.14;
}
const overlay = new THREE.Mesh(
new THREE.BoxGeometry(width, 0.10, 1.52),
redMaterial
);
overlay.position.set(x, 1.38, 0);
overlay.renderOrder = 11;
faultRoot.add(overlay);
const outline = new THREE.LineSegments(
new THREE.EdgesGeometry(overlay.geometry),
edgeMaterial
);
outline.position.copy(overlay.position);
outline.renderOrder = 12;
faultRoot.add(outline);
if (fault.kind === "missing") {
for (const z of [-0.67, 0.67]) {
const post = new THREE.Mesh(
new THREE.BoxGeometry(0.08, 0.75, 0.08),
edgeMaterial
);
post.position.set(x, 1.05, z);
post.renderOrder = 12;
faultRoot.add(post);
}
}
}
function testCrossing() {
if (state.phase !== "repair" || !state.routeChanged || state.crossing) {
return;
}
const result = validateRoute();
if (!result.ok) {
highlightFault(result);
setStatus(result.title, result.text, "error");
toast("Repair rejected — the first fault is highlighted in red.");
refreshUI();
return;
}
clearFault();
setStatus(
"Test passed",
result.text,
"success"
);
toast("Support check passed. The character is crossing.");
startCrossing();
}
// -------------------------------------------------------------------------
// Player actions
// -------------------------------------------------------------------------
function selectType(type) {
if (countByType("available", type) === 0) return;
state.selectedType = type;
state.selectedModule = null;
updateSelectionOutline();
updateMarkers();
refreshUI();
}
function selectModule(id) {
const module = moduleById(id);
if (!module || module.state !== "placed") return;
state.selectedModule = id;
state.selectedType = null;
updateSelectionOutline();
updateMarkers();
refreshUI();
}
function placeModule(type, target) {
if (state.crossing) return;
if (type === "pier") {
if (target.kind !== "pier") {
toast("Short piers can only be placed in a circular support socket.");
return;
}
if (state.closed && target.anchor === CLOSED_ANCHOR) {
toast("P3 is unavailable. It cannot be used as a support point.");
return;
}
if (pierAt(target.anchor)) {
toast("That support socket already contains a pier.");
return;
}
} else {
if (target.kind !== "span") {
toast("Planks and tiles must be placed in a marked deck bay.");
return;
}
if (spanAt(target.slot)) {
toast("That bay is occupied. Select the placed piece to return it.");
return;
}
}
const module = availableModuleOfType(type);
if (!module) {
toast("No modules of that type remain in inventory.");
return;
}
module.state = "placed";
if (type === "pier") {
module.anchor = target.anchor;
module.slot = null;
} else {
module.slot = target.slot;
module.anchor = null;
}
state.selectedModule = module.id;
state.routeChanged = true;
state.lastTestSuccess = false;
clearFault();
resetCharacter();
setStatus(
type === "pier" ? "Pier staged" : "Deck piece staged",
type === "pier"
? `The short pier is snapped into P${target.anchor}. Test the route after arranging the deck.`
: `The ${TYPE_NAMES[type].toLowerCase()} now occupies Bay ${target.slot + 1}.`
);
rebuildModuleVisuals();
updateMarkers();
refreshUI();
}
function returnSelectedModule() {
if (state.crossing) return;
const module = moduleById(state.selectedModule);
if (!module || module.state !== "placed") return;
module.state = "available";
module.slot = null;
module.anchor = null;
state.selectedModule = null;
state.selectedType = module.type;
state.routeChanged = true;
state.lastTestSuccess = false;
clearFault();
resetCharacter();
setStatus(
"Part returned",
`One ${TYPE_NAMES[module.type].toLowerCase()} is back in inventory. It can be reused in another compatible socket.`
);
rebuildModuleVisuals();
updateMarkers();
refreshUI();
}
function discardSelectedType() {
if (state.crossing) return;
const type = state.selectedType;
const module = availableModuleOfType(type);
if (!module) return;
module.state = "discarded";
module.broken = false;
module.slot = null;
module.anchor = null;
state.selectedModule = null;
state.routeChanged = true;
state.lastTestSuccess = false;
clearFault();
resetCharacter();
setStatus(
"Part discarded",
`One ${TYPE_NAMES[type].toLowerCase()} was moved to the Discarded tray. It can be restored while the puzzle is active.`
);
refreshUI();
}
function restoreDiscarded(id) {
if (state.crossing) return;
const module = moduleById(id);
if (!module || module.state !== "discarded" || module.broken) return;
module.state = "available";
module.slot = null;
module.anchor = null;
state.selectedType = module.type;
state.selectedModule = null;
state.routeChanged = true;
state.lastTestSuccess = false;
clearFault();
resetCharacter();
setStatus(
"Part restored",
`The discarded ${TYPE_NAMES[module.type].toLowerCase()} is available again.`
);
refreshUI();
}
function closePier() {
state.phase = "repair";
state.closed = true;
const closedPier = moduleById("pier-2");
closedPier.state = "discarded";
closedPier.broken = true;
const returnedSpanA = moduleById("span-3");
const returnedSpanB = moduleById("span-4");
returnedSpanA.state = "available";
returnedSpanB.state = "available";
returnedSpanA.slot = null;
returnedSpanB.slot = null;
state.selectedType = "plank";
state.selectedModule = null;
state.routeChanged = false;
state.lastTestSuccess = false;
$("startOverlay").classList.add("hidden");
setStatus(
"P3 unavailable — repair required",
"The damaged pier is discarded. The plank and walkway tile that bore on P3 have returned to inventory. Reuse the remaining kit to restore a supported, connected route."
);
clearFault();
rebuildModuleVisuals();
updateMarkers();
refreshUI();
toast("Closure event: two supported deck pieces returned to inventory.");
}
function restartPuzzle() {
initialModuleState();
state.phase = "inspection";
state.closed = false;
state.selectedType = null;
state.selectedModule = null;
state.routeChanged = false;
state.lastTestSuccess = false;
state.crossing = false;
$("startOverlay").classList.remove("hidden");
setStatus(
"Route inspection",
"The original crossing is structurally valid. Inspect it before the closure event."
);
clearFault();
resetCharacter();
rebuildModuleVisuals();
updateMarkers();
refreshUI();
}
// -------------------------------------------------------------------------
// UI rendering
// -------------------------------------------------------------------------
function moduleDisplayName(module) {
if (module.type === "pier") {
return `Short pier • P${module.anchor}`;
}
return `${TYPE_NAMES[module.type]} • Bay ${module.slot + 1}`;
}
function refreshUI() {
const available = modulesWithState("available");
const discarded = modulesWithState("discarded");
const placed = modulesWithState("placed");
$("availableCount").textContent = available.length;
$("discardedCount").textContent = discarded.length;
$("placedCount").textContent = placed.length;
$("balanceText").textContent =
`Kit balance: ${available.length} available + ${discarded.length} discarded + ${placed.length} placed = ${modules.size}`;
$("phaseBadge").textContent =
state.phase === "inspection"
? "Pre-closure inspection"
: state.crossing
? "Crossing test"
: "Repair in progress";
$("availableTray").innerHTML = TYPE_ORDER.map((type) => {
const count = countByType("available", type);
const selected = state.selectedType === type;
return `
<button
class="part ${selected ? "selected" : ""}"
data-select-type="${type}"
${count === 0 ? "disabled" : ""}
>
<span class="swatch ${type}"></span>
<span>
<span class="part-name">${TYPE_NAMES[type]}</span>
<span class="part-meta">${count} in inventory</span>
</span>
</button>
`;
}).join("");
$("discardedTray").innerHTML = discarded.length
? discarded.map((module) => `
<div class="discarded-item">
<span>
<span class="swatch ${module.type}" style="display:inline-block; margin-right:5px; vertical-align:-3px;"></span>
${TYPE_NAMES[module.type]}${module.broken ? " • damaged" : ""}
</span>
<button
class="mini-button"
data-restore="${module.id}"
${module.broken ? "disabled title='This damaged pier caused the closure.'" : ""}
>
${module.broken ? "Locked" : "Restore"}
</button>
</div>
`).join("")
: `<span style="color:#55727a; font-size:11px;">No discarded modules.</span>`;
$("placedList").innerHTML = placed.length
? placed.map((module) => `
<button
class="placed-item ${state.selectedModule === module.id ? "selected" : ""}"
data-select-module="${module.id}"
>
<span>${moduleDisplayName(module)}</span>
</button>
`).join("")
: `<span style="color:#55727a; font-size:11px;">No modules placed.</span>`;
const selected = state.selectedModule
? moduleById(state.selectedModule)
: null;
if (selected && selected.state === "placed") {
$("selectionText").textContent =
`Selected: ${moduleDisplayName(selected)}. Return it to inventory or choose a different part.`;
} else if (state.selectedType) {
const target =
state.selectedType === "pier"
? "a glowing circular pier socket"
: "a glowing deck bay";
$("selectionText").textContent =
`Selected: ${TYPE_NAMES[state.selectedType]}. Click ${target}.`;
} else {
$("selectionText").textContent =
"Select an available part, a placed module, or click a glowing socket.";
}
$("returnButton").disabled =
!selected || selected.state !== "placed" || state.crossing;
$("discardButton").disabled =
!state.selectedType ||
countByType("available", state.selectedType) === 0 ||
state.crossing;
$("testButton").disabled =
state.phase !== "repair" ||
!state.routeChanged ||
state.crossing;
$("testButton").textContent = state.crossing
? "Character is crossing…"
: "Test character crossing";
}
$("availableTray").addEventListener("click", (event) => {
const button = event.target.closest("[data-select-type]");
if (!button) return;
selectType(button.dataset.selectType);
});
$("discardedTray").addEventListener("click", (event) => {
const button = event.target.closest("[data-restore]");
if (!button || button.disabled) return;
restoreDiscarded(button.dataset.restore);
});
$("placedList").addEventListener("click", (event) => {
const button = event.target.closest("[data-select-module]");
if (!button) return;
selectModule(button.dataset.selectModule);
});
$("returnButton").addEventListener("click", returnSelectedModule);
$("discardButton").addEventListener("click", discardSelectedType);
$("testButton").addEventListener("click", testCrossing);
$("restartButton").addEventListener("click", restartPuzzle);
$("startRepair").addEventListener("click", closePier);
$("resetCamera").addEventListener("click", () => {
cameraState.azimuth = 0.67;
cameraState.polar = 0.94;
cameraState.radius = 20.5;
updateCamera();
});
// -------------------------------------------------------------------------
// Raycasting and direct camera controls
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function setRayFromClient(clientX, clientY) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
function moduleIdFromObject(object) {
let current = object;
while (current) {
if (current.userData.moduleId) return current.userData.moduleId;
current = current.parent;
}
return null;
}
function pickAt(clientX, clientY) {
setRayFromClient(clientX, clientY);
const moduleHits = raycaster.intersectObjects(moduleRoot.children, true);
if (moduleHits.length) {
const id = moduleIdFromObject(moduleHits[0].object);
if (id) return { kind: "module", id };
}
const proxyHits = raycaster.intersectObjects(pickProxies, false);
if (proxyHits.length) {
return proxyHits[0].object.userData.target;
}
return null;
}
function targetDescription(target) {
if (!target) return "";
if (target.kind === "module") {
const module = moduleById(target.id);
return moduleDisplayName(module);
}
if (target.kind === "span") {
const module = spanAt(target.slot);
return module
? `${moduleDisplayName(module)} — occupied`
: `Bay ${target.slot + 1} — empty deck socket`;
}
if (target.kind === "pier") {
const module = pierAt(target.anchor);
return module
? `${moduleDisplayName(module)} — occupied`
: `P${target.anchor} — empty support socket`;
}
return "";
}
let pointerDown = false;
let pointerStartX = 0;
let pointerStartY = 0;
let pointerMoved = false;
canvas.addEventListener("pointerdown", (event) => {
pointerDown = true;
pointerMoved = false;
pointerStartX = event.clientX;
pointerStartY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (pointerDown) {
const dx = event.clientX - pointerStartX;
const dy = event.clientY - pointerStartY;
if (Math.abs(dx) + Math.abs(dy) > 5) {
pointerMoved = true;
}
cameraState.azimuth -= dx * 0.006;
cameraState.polar = THREE.MathUtils.clamp(
cameraState.polar - dy * 0.0045,
0.48,
1.28
);
updateCamera();
$("tooltip").style.display = "none";
return;
}
const target = pickAt(event.clientX, event.clientY);
if (!target) {
$("tooltip").style.display = "none";
canvas.style.cursor = "grab";
return;
}
canvas.style.cursor = "pointer";
$("tooltip").style.display = "block";
$("tooltip").style.left = `${event.clientX}px`;
$("tooltip").style.top = `${event.clientY}px`;
$("tooltip").textContent = targetDescription(target);
});
canvas.addEventListener("pointerup", (event) => {
if (pointerDown && !pointerMoved) {
const target = pickAt(event.clientX, event.clientY);
if (target) {
if (target.kind === "module") {
selectModule(target.id);
} else if (state.selectedType) {
placeModule(state.selectedType, target);
} else {
const occupied = target.kind === "span"
? spanAt(target.slot)
: pierAt(target.anchor);
if (occupied) {
selectModule(occupied.id);
} else {
toast("Choose a part from the Available tray first.");
}
}
}
}
pointerDown = false;
canvas.style.cursor = "grab";
});
canvas.addEventListener("pointercancel", () => {
pointerDown = false;
});
canvas.addEventListener("pointerleave", () => {
$("tooltip").style.display = "none";
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.012,
12,
31
);
updateCamera();
},
{ passive: false }
);
// -------------------------------------------------------------------------
// Resize and animation loop
// -------------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
function animate(now) {
requestAnimationFrame(animate);
updateCrossing(now);
if (state.fault) {
const pulse = 0.28 + Math.sin(now * 0.006) * 0.12;
for (const child of faultRoot.children) {
if (child.material && "opacity" in child.material) {
child.material.opacity = pulse;
}
}
}
water.position.y = Math.sin(now * 0.00055) * 0.018;
renderer.render(scene, camera);
}
rebuildModuleVisuals();
updateMarkers();
refreshUI();
requestAnimationFrame(animate);
</script>
</body>
</html>
```