Prompt specification
Build or customize the Three.js 3D scene "Connect Three Resource Patches" 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 Three Resource Patches
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/connect-three-resource-patches-x3586
Scene Description Prompt:
Create a standalone low-poly scene in one HTML file using Three.js from cdnjs. Create a small board where players place a limited number of path tiles. Validate connectivity between patches and allow several geometrically different valid solutions.
Working Three.js Starter (connect-three-resource-patches-x3586):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Trailweave — Low-poly Path Puzzle</title>
<style>
:root {
--ink: #17383b;
--muted: #5f7775;
--cream: #fffaf0;
--panel: rgba(255, 250, 240, 0.92);
--line: rgba(23, 56, 59, 0.13);
--teal: #268f87;
--teal-dark: #176963;
--amber: #eea84a;
--amber-dark: #b86f28;
--red: #c95f55;
--shadow: 0 16px 44px rgba(30, 64, 63, 0.18);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
font-family: Inter, ui-rounded, "SF Pro Rounded", system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
color: var(--ink);
background: #b9d8d5;
}
button { font: inherit; }
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: crosshair;
}
.hud {
position: fixed;
inset: 0;
z-index: 5;
pointer-events: none;
}
.panel {
pointer-events: auto;
background: var(--panel);
border: 1px solid rgba(255, 255, 255, 0.7);
box-shadow: var(--shadow);
backdrop-filter: blur(15px);
-webkit-backdrop-filter: blur(15px);
}
.brand {
position: absolute;
top: 24px;
left: 24px;
width: min(390px, calc(100vw - 48px));
pointer-events: none;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 7px;
color: var(--teal-dark);
font-size: 11px;
font-weight: 850;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 22px;
height: 3px;
border-radius: 99px;
background: var(--amber);
}
h1 {
margin: 0;
font-size: clamp(28px, 4vw, 48px);
line-height: 0.95;
letter-spacing: -0.055em;
font-weight: 900;
text-shadow: 0 2px 0 rgba(255, 255, 255, 0.3);
}
.brand p {
margin: 10px 0 0;
max-width: 350px;
color: #446967;
font-size: 13px;
line-height: 1.45;
}
.status-panel {
position: absolute;
top: 24px;
right: 24px;
width: 290px;
padding: 18px;
border-radius: 22px;
}
.status-head {
display: flex;
align-items: center;
gap: 10px;
}
.status-dot {
width: 11px;
height: 11px;
flex: 0 0 auto;
border-radius: 50%;
background: #91a6a3;
box-shadow: 0 0 0 5px rgba(145, 166, 163, 0.14);
transition: 180ms ease;
}
.status-panel.good .status-dot {
background: #45a96b;
box-shadow: 0 0 0 5px rgba(69, 169, 107, 0.15);
}
.status-panel.linked .status-dot {
background: var(--teal);
box-shadow: 0 0 0 5px rgba(38, 143, 135, 0.15);
}
.status-panel.bad .status-dot {
background: var(--red);
box-shadow: 0 0 0 5px rgba(201, 95, 85, 0.14);
}
#statusTitle {
font-size: 16px;
font-weight: 850;
letter-spacing: -0.02em;
}
#statusText {
min-height: 38px;
margin: 10px 0 13px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.metrics {
display: flex;
gap: 7px;
margin-bottom: 12px;
}
.metric {
flex: 1;
padding: 8px 9px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.45);
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.metric strong {
display: block;
margin-top: 2px;
color: var(--ink);
font-size: 14px;
letter-spacing: -0.02em;
}
.primary {
width: 100%;
min-height: 43px;
border: 0;
border-radius: 13px;
color: white;
background: var(--teal-dark);
box-shadow: 0 7px 16px rgba(23, 105, 99, 0.2);
font-size: 13px;
font-weight: 850;
cursor: pointer;
transition: transform 150ms ease, background 150ms ease;
}
.primary:hover {
background: #0f5954;
transform: translateY(-1px);
}
.primary:active { transform: translateY(1px); }
.primary.complete {
background: #3b925b;
box-shadow: 0 7px 16px rgba(59, 146, 91, 0.2);
}
.inventory {
position: absolute;
left: 24px;
bottom: 24px;
width: 346px;
padding: 15px;
border-radius: 22px;
}
.inventory-header {
display: flex;
align-items: center;
justify-content: space-between;
margin: 0 2px 11px;
}
.inventory-header strong {
font-size: 12px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.inventory-header span {
color: var(--muted);
font-size: 11px;
}
.tools {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.tool {
position: relative;
display: grid;
grid-template-columns: 42px 1fr;
align-items: center;
gap: 9px;
min-height: 68px;
padding: 10px;
border: 1px solid var(--line);
border-radius: 16px;
color: var(--ink);
background: rgba(255, 255, 255, 0.52);
text-align: left;
cursor: pointer;
transition: 160ms ease;
}
.tool:hover:not(:disabled) {
transform: translateY(-2px);
border-color: rgba(38, 143, 135, 0.4);
background: rgba(255, 255, 255, 0.8);
}
.tool.active {
border-color: var(--teal);
background: #effaf5;
box-shadow: inset 0 0 0 1px var(--teal);
}
.tool:disabled {
cursor: not-allowed;
opacity: 0.45;
filter: grayscale(0.6);
}
.tool-icon {
display: grid;
place-items: center;
width: 42px;
height: 42px;
border-radius: 13px;
color: white;
background: var(--amber-dark);
}
.tool[data-type="bend"] .tool-icon { background: var(--teal-dark); }
.tool-icon svg {
width: 27px;
height: 27px;
fill: none;
stroke: currentColor;
stroke-width: 4;
stroke-linecap: round;
stroke-linejoin: round;
}
.tool b {
display: block;
font-size: 13px;
font-weight: 850;
}
.tool small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.count {
position: absolute;
top: 8px;
right: 9px;
min-width: 21px;
height: 21px;
padding: 0 5px;
border-radius: 99px;
color: var(--ink);
background: #fff;
font-size: 11px;
font-weight: 900;
line-height: 21px;
text-align: center;
box-shadow: 0 2px 6px rgba(23, 56, 59, 0.12);
}
.tool[data-type="bend"] .count {
color: white;
background: var(--teal);
}
.tool[data-type="straight"] .count {
color: white;
background: var(--amber-dark);
}
.inventory-actions {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 7px;
margin-top: 9px;
}
.small-button {
min-height: 35px;
padding: 6px 9px;
border: 1px solid var(--line);
border-radius: 11px;
color: var(--ink);
background: rgba(255, 255, 255, 0.55);
font-size: 10px;
font-weight: 800;
cursor: pointer;
transition: 150ms ease;
}
.small-button:hover:not(:disabled) {
background: white;
transform: translateY(-1px);
}
.small-button:disabled {
opacity: 0.35;
cursor: not-allowed;
}
.hint {
position: absolute;
left: 50%;
bottom: 24px;
transform: translateX(-50%);
width: max-content;
max-width: calc(100vw - 410px);
padding: 10px 15px;
border: 1px solid rgba(255, 255, 255, 0.62);
border-radius: 999px;
color: #446967;
background: rgba(255, 250, 240, 0.76);
box-shadow: 0 8px 25px rgba(30, 64, 63, 0.11);
backdrop-filter: blur(10px);
font-size: 11px;
font-weight: 700;
text-align: center;
}
.world-label {
position: absolute;
z-index: 4;
padding: 5px 9px;
border: 1px solid rgba(255, 255, 255, 0.8);
border-radius: 999px;
color: white;
background: rgba(23, 56, 59, 0.78);
box-shadow: 0 5px 14px rgba(23, 56, 59, 0.16);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.1em;
text-transform: uppercase;
transform: translate(-50%, -50%);
pointer-events: none;
white-space: nowrap;
}
#startLabel { background: rgba(25, 116, 108, 0.9); }
#goalLabel { background: rgba(183, 104, 36, 0.92); }
#toast {
position: fixed;
left: 50%;
top: 24px;
z-index: 20;
max-width: min(420px, calc(100vw - 32px));
padding: 11px 16px;
border: 1px solid rgba(255, 255, 255, 0.6);
border-radius: 999px;
color: white;
background: rgba(23, 56, 59, 0.92);
box-shadow: var(--shadow);
font-size: 12px;
font-weight: 750;
opacity: 0;
transform: translate(-50%, -12px);
pointer-events: none;
transition: 180ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#loading {
position: fixed;
inset: 0;
z-index: 50;
display: grid;
place-items: center;
color: var(--ink);
background: #c4dfdb;
font-size: 13px;
font-weight: 850;
letter-spacing: 0.15em;
text-transform: uppercase;
transition: opacity 350ms ease;
}
#loading.hide { opacity: 0; pointer-events: none; }
@media (max-width: 760px) {
.brand {
top: 14px;
left: 14px;
}
.brand p { display: none; }
h1 { font-size: 29px; }
.status-panel {
top: 12px;
right: 12px;
width: 220px;
padding: 13px;
border-radius: 17px;
}
#statusText { min-height: 0; font-size: 10px; }
.metrics { margin-bottom: 8px; }
.primary { min-height: 37px; font-size: 11px; }
.inventory {
left: 10px;
right: 10px;
bottom: 10px;
width: auto;
padding: 10px;
border-radius: 17px;
}
.inventory-header { margin-bottom: 7px; }
.tool { min-height: 55px; grid-template-columns: 34px 1fr; padding: 7px; }
.tool-icon { width: 34px; height: 34px; border-radius: 10px; }
.tool-icon svg { width: 22px; height: 22px; }
.tool b { font-size: 11px; }
.tool small { display: none; }
.count { top: 4px; right: 4px; }
.inventory-actions { margin-top: 6px; }
.hint { display: none; }
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="hud">
<header class="brand">
<div class="eyebrow">Low-poly path puzzle</div>
<h1>Trailweave</h1>
<p>
Connect the teal grove to the amber lookout. Your tile set is limited,
but the island offers more than one possible route.
</p>
</header>
<section id="statusPanel" class="status-panel panel" aria-live="polite">
<div class="status-head">
<span class="status-dot"></span>
<strong id="statusTitle">Build a trail</strong>
</div>
<p id="statusText">Place path pieces between the two glowing patches.</p>
<div class="metrics">
<div class="metric">Placed<strong id="placedMetric">0</strong></div>
<div class="metric">Spare<strong id="spareMetric">13</strong></div>
<div class="metric">Route<strong id="routeMetric">—</strong></div>
</div>
<button id="validateButton" class="primary">Test connection</button>
</section>
<section class="inventory panel">
<div class="inventory-header">
<strong>Path pieces</strong>
<span>Choose, place, rotate</span>
</div>
<div class="tools">
<button class="tool active" data-type="straight" aria-label="Select straight tile">
<span class="tool-icon">
<svg viewBox="0 0 32 32" aria-hidden="true">
<path d="M5 16h22"></path>
</svg>
</span>
<span>
<b>Straight</b>
<small>Horizontal / vertical</small>
</span>
<span id="straightCount" class="count">9</span>
</button>
<button class="tool" data-type="bend" aria-label="Select bend tile">
<span class="tool-icon">
<svg viewBox="0 0 32 32" aria-hidden="true">
<path d="M7 25V16a5 5 0 0 1 5-5h13"></path>
</svg>
</span>
<span>
<b>Bend</b>
<small>Four rotations</small>
</span>
<span id="bendCount" class="count">4</span>
</button>
</div>
<div class="inventory-actions">
<button id="rotateButton" class="small-button">Rotate · R</button>
<button id="undoButton" class="small-button" disabled>Undo</button>
<button id="clearButton" class="small-button">Clear</button>
</div>
</section>
<div class="hint">
Click to place · Click a piece to rotate · Right-click to remove · Drag to orbit · Scroll to zoom
</div>
<div id="startLabel" class="world-label">Teal grove</div>
<div id="goalLabel" class="world-label">Amber lookout</div>
</div>
<div id="toast" role="status"></div>
<div id="loading">Preparing the island…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------
// Constants and state
// ---------------------------------------------------------------------
const COLS = 11;
const ROWS = 7;
const CELL = 1;
const START = Object.freeze({ c: 0, r: 3 });
const GOAL = Object.freeze({ c: 10, r: 3 });
const BLOCKED = new Set([
"0,0", "10,0", "0,6", "10,6",
"4,3", "6,3",
"3,1", "7,1",
"2,5", "8,5",
"5,0", "5,6"
]);
const DIRECTIONS = [
{ name: "N", dc: 0, dr: -1 },
{ name: "E", dc: 1, dr: 0 },
{ name: "S", dc: 0, dr: 1 },
{ name: "W", dc: -1, dr: 0 }
];
const BEND_PATTERNS = [
[1, 2], // East + South
[0, 1], // North + East
[0, 3], // North + West
[2, 3] // South + West
];
const inventory = { straight: 9, bend: 4 };
const tiles = new Map();
const undoStack = [];
let selectedType = "straight";
let selectedRotation = 0;
let hoverCell = null;
let currentRoute = null;
let validationChecked = false;
let routeValidated = false;
let toastTimer = 0;
const sceneHost = document.getElementById("scene");
const statusPanel = document.getElementById("statusPanel");
const statusTitle = document.getElementById("statusTitle");
const statusText = document.getElementById("statusText");
const placedMetric = document.getElementById("placedMetric");
const spareMetric = document.getElementById("spareMetric");
const routeMetric = document.getElementById("routeMetric");
const validateButton = document.getElementById("validateButton");
const undoButton = document.getElementById("undoButton");
const clearButton = document.getElementById("clearButton");
const rotateButton = document.getElementById("rotateButton");
const toast = document.getElementById("toast");
// ---------------------------------------------------------------------
// Three.js setup
// ---------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
sceneHost.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xb9d8d5);
scene.fog = new THREE.Fog(0xb9d8d5, 20, 42);
const camera = new THREE.OrthographicCamera(-8, 8, 5, -5, 0.1, 100);
const cameraTarget = new THREE.Vector3(0, 0.15, 0);
const cameraView = {
theta: 0.48,
phi: 0.88,
zoom: 1
};
const hemi = new THREE.HemisphereLight(0xe9fff7, 0x587d78, 2.15);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff2cf, 3.4);
sun.position.set(-7, 13, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -11;
sun.shadow.camera.right = 11;
sun.shadow.camera.top = 11;
sun.shadow.camera.bottom = -11;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
sun.shadow.normalBias = 0.035;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x9edbd1, 1.1);
rim.position.set(8, 5, -9);
scene.add(rim);
const boardGroup = new THREE.Group();
const pieceGroup = new THREE.Group();
const previewGroup = new THREE.Group();
const routeGlowGroup = new THREE.Group();
const particleGroup = new THREE.Group();
const cloudGroup = new THREE.Group();
scene.add(
boardGroup,
pieceGroup,
previewGroup,
routeGlowGroup,
particleGroup,
cloudGroup
);
const hoverMarker = new THREE.Mesh(
new THREE.BoxGeometry(0.9, 0.025, 0.9),
new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.35,
depthWrite: false
})
);
hoverMarker.visible = false;
hoverMarker.renderOrder = 4;
scene.add(hoverMarker);
// ---------------------------------------------------------------------
// Utilities
// ---------------------------------------------------------------------
function keyFor(c, r) {
return `${c},${r}`;
}
function worldX(c) {
return (c - (COLS - 1) / 2) * CELL;
}
function worldZ(r) {
return (r - (ROWS - 1) / 2) * CELL;
}
function worldPosition(c, r, y = 0) {
return new THREE.Vector3(worldX(c), y, worldZ(r));
}
function hash(x, z) {
const value = Math.sin(x * 12.9898 + z * 78.233) * 43758.5453;
return value - Math.floor(value);
}
function standardMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.86,
metalness: 0,
flatShading: true,
...options
});
}
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 clearGroup(group) {
for (const child of [...group.children]) {
group.remove(child);
disposeObject(child);
}
}
function showToast(message) {
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 2300);
}
function isInside(c, r) {
return c >= 0 && c < COLS && r >= 0 && r < ROWS;
}
function isPatch(c, r) {
return (
(c === START.c && r === START.r) ||
(c === GOAL.c && r === GOAL.r)
);
}
function isBuildable(c, r) {
return (
isInside(c, r) &&
!isPatch(c, r) &&
!BLOCKED.has(keyFor(c, r))
);
}
function connectionsFor(type, rotation) {
if (type === "straight") {
return rotation === 0 ? [1, 3] : [0, 2];
}
return BEND_PATTERNS[rotation % 4];
}
// ---------------------------------------------------------------------
// Island and terrain
// ---------------------------------------------------------------------
function createTree(scale = 1, hue = 0) {
const group = new THREE.Group();
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.055, 0.075, 0.34, 5),
standardMaterial(0x74523b)
);
trunk.position.y = 0.16;
trunk.castShadow = true;
group.add(trunk);
const greens = [0x2f8069, 0x3b9273, 0x286e60];
const lower = new THREE.Mesh(
new THREE.ConeGeometry(0.23, 0.65, 6),
standardMaterial(greens[hue % greens.length])
);
lower.position.y = 0.57;
lower.castShadow = true;
group.add(lower);
const upper = new THREE.Mesh(
new THREE.ConeGeometry(0.17, 0.52, 6),
standardMaterial(greens[(hue + 1) % greens.length])
);
upper.position.y = 0.88;
upper.castShadow = true;
group.add(upper);
group.scale.setScalar(scale);
return group;
}
function createRockCluster(c, r, index) {
const group = new THREE.Group();
group.position.copy(worldPosition(c, r, 0.08));
const rockCount = 3 + (index % 2);
for (let i = 0; i < rockCount; i++) {
const radius = 0.12 + hash(c * 7 + i, r * 11) * 0.11;
const rock = new THREE.Mesh(
new THREE.DodecahedronGeometry(radius, 0),
standardMaterial(
i % 2 === 0 ? 0x87928b : 0x9b9a88,
{ roughness: 1 }
)
);
rock.position.set(
(hash(i, c) - 0.5) * 0.38,
radius * 0.58,
(hash(r, i) - 0.5) * 0.38
);
rock.scale.set(1, 0.75 + hash(i, r) * 0.45, 1);
rock.rotation.set(
hash(i, c) * Math.PI,
hash(r, i) * Math.PI,
hash(c + r, i) * Math.PI
);
rock.castShadow = true;
rock.receiveShadow = true;
group.add(rock);
}
const tuft = new THREE.Mesh(
new THREE.ConeGeometry(0.13, 0.32, 5),
standardMaterial(0x4f8067)
);
tuft.position.set(0.2, 0.13, -0.2);
tuft.castShadow = true;
group.add(tuft);
return group;
}
function buildTerrain() {
const palette = [
0x83ad78, 0x91b77f, 0x78a472, 0x9cba83, 0x86ad79
];
const base = new THREE.Mesh(
new THREE.BoxGeometry(COLS * CELL + 0.38, 0.58, ROWS * CELL + 0.38),
standardMaterial(0x536b60, { roughness: 1 })
);
base.position.y = -0.36;
base.receiveShadow = true;
base.castShadow = true;
boardGroup.add(base);
const lowerBase = new THREE.Mesh(
new THREE.BoxGeometry(COLS * CELL + 0.62, 0.18, ROWS * CELL + 0.62),
standardMaterial(0x425951, { roughness: 1 })
);
lowerBase.position.y = -0.68;
lowerBase.receiveShadow = true;
boardGroup.add(lowerBase);
for (let r = 0; r < ROWS; r++) {
for (let c = 0; c < COLS; c++) {
const key = keyFor(c, r);
const blocked = BLOCKED.has(key);
const side = new THREE.Mesh(
new THREE.BoxGeometry(0.965, 0.35, 0.965),
standardMaterial(blocked ? 0x777f72 : 0x687e64, {
roughness: 1
})
);
side.position.set(worldX(c), -0.145, worldZ(r));
side.receiveShadow = true;
side.castShadow = true;
boardGroup.add(side);
let geometry = new THREE.PlaneGeometry(0.965, 0.965, 2, 2);
geometry.rotateX(-Math.PI / 2);
const positions = geometry.attributes.position;
for (let i = 0; i < positions.count; i++) {
const x = positions.getX(i);
const z = positions.getZ(i);
const elevation =
(hash(c * 4 + x, r * 4 + z) - 0.5) * 0.085;
positions.setY(i, elevation);
}
geometry.computeVertexNormals();
geometry = geometry.toNonIndexed();
geometry.computeVertexNormals();
const baseColor = new THREE.Color(
blocked ? 0x8c9686 : palette[Math.floor(hash(c, r) * palette.length)]
);
const colors = new Float32Array(geometry.attributes.position.count * 3);
const facetColor = new THREE.Color();
for (let i = 0; i < geometry.attributes.position.count; i += 3) {
facetColor.copy(baseColor).multiplyScalar(
0.88 + hash(c * 5 + i, r * 7 - i) * 0.22
);
for (let j = 0; j < 3; j++) {
const offset = (i + j) * 3;
colors[offset] = facetColor.r;
colors[offset + 1] = facetColor.g;
colors[offset + 2] = facetColor.b;
}
}
geometry.setAttribute(
"color",
new THREE.BufferAttribute(colors, 3)
);
const topMaterial = standardMaterial(0xffffff, {
vertexColors: true,
roughness: 1
});
const top = new THREE.Mesh(geometry, topMaterial);
top.position.set(worldX(c), 0.045, worldZ(r));
top.receiveShadow = true;
boardGroup.add(top);
if (blocked) {
const obstacleIndex = c + r * COLS;
if (r === 0 || r === ROWS - 1) {
const tree = createTree(0.82 + hash(c, r) * 0.2, obstacleIndex);
tree.position.copy(worldPosition(c, r, 0.08));
boardGroup.add(tree);
} else {
boardGroup.add(createRockCluster(c, r, obstacleIndex));
}
}
}
}
const water = new THREE.Mesh(
new THREE.PlaneGeometry(100, 100),
standardMaterial(0x8fc2bd, {
roughness: 0.72,
metalness: 0.03
})
);
water.rotation.x = -Math.PI / 2;
water.position.y = -0.79;
water.receiveShadow = true;
scene.add(water);
const waveMaterial = new THREE.MeshBasicMaterial({
color: 0xc8e6df,
transparent: true,
opacity: 0.38,
depthWrite: false
});
for (let i = 0; i < 22; i++) {
const wave = new THREE.Mesh(
new THREE.CircleGeometry(0.22 + hash(i, 2) * 0.35, 3),
waveMaterial
);
wave.rotation.x = -Math.PI / 2;
wave.rotation.z = hash(i, 3) * Math.PI;
wave.position.set(
(hash(i, 5) - 0.5) * 24,
-0.775,
(hash(i, 7) - 0.5) * 20
);
scene.add(wave);
}
}
function buildClouds() {
const cloudMaterial = standardMaterial(0xe9f5ec, {
roughness: 1,
transparent: true,
opacity: 0.78
});
const cloudData = [
[-7, 3.2, -7, 1.0],
[7, 2.7, 4, 0.8],
[2, 3.8, -10, 0.65],
[-10, 2.1, 6, 0.7]
];
for (const [x, y, z, scale] of cloudData) {
const cloud = new THREE.Group();
cloud.position.set(x, y, z);
cloud.scale.setScalar(scale);
cloud.userData.baseX = x;
cloud.userData.phase = hash(x, z) * Math.PI * 2;
for (let i = 0; i < 4; i++) {
const puff = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.58 + i * 0.04, 0),
cloudMaterial
);
puff.position.set((i - 1.5) * 0.45, Math.sin(i) * 0.1, i % 2 * 0.2);
puff.scale.set(1.2, 0.65, 0.8);
cloud.add(puff);
}
cloudGroup.add(cloud);
}
}
// ---------------------------------------------------------------------
// Patch endpoints
// ---------------------------------------------------------------------
let goalCrystal;
function createPatch(c, r, isStart) {
const group = new THREE.Group();
group.position.copy(worldPosition(c, r, 0));
const soil = new THREE.Mesh(
new THREE.CylinderGeometry(0.43, 0.49, 0.13, 9),
standardMaterial(isStart ? 0x2b897a : 0xd78b43)
);
soil.position.y = 0.12;
soil.receiveShadow = true;
soil.castShadow = true;
group.add(soil);
const inner = new THREE.Mesh(
new THREE.CylinderGeometry(0.28, 0.3, 0.035, 9),
standardMaterial(isStart ? 0x55b6a4 : 0xf4c66e)
);
inner.position.y = 0.205;
inner.receiveShadow = true;
group.add(inner);
if (isStart) {
const pool = new THREE.Mesh(
new THREE.CylinderGeometry(0.16, 0.18, 0.035, 8),
standardMaterial(0x78d9cf, {
emissive: 0x236f69,
emissiveIntensity: 0.38,
roughness: 0.4
})
);
pool.position.y = 0.23;
group.add(pool);
for (let i = 0; i < 3; i++) {
const sprout = new THREE.Mesh(
new THREE.ConeGeometry(0.1, 0.34, 5),
standardMaterial(i === 1 ? 0x54a67e : 0x377d67)
);
const angle = i * Math.PI * 2 / 3;
sprout.position.set(
Math.cos(angle) * 0.3,
0.36,
Math.sin(angle) * 0.3
);
sprout.castShadow = true;
group.add(sprout);
}
} else {
const crystal = new THREE.Mesh(
new THREE.OctahedronGeometry(0.31, 0),
standardMaterial(0xffbf52, {
emissive: 0xe58a28,
emissiveIntensity: 0.45,
roughness: 0.35
})
);
crystal.position.y = 0.55;
crystal.scale.set(0.8, 1.45, 0.8);
crystal.castShadow = true;
group.add(crystal);
goalCrystal = crystal;
}
boardGroup.add(group);
return group;
}
// ---------------------------------------------------------------------
// Path pieces
// ---------------------------------------------------------------------
function createPiece(type, rotation, ghost = false) {
const group = new THREE.Group();
const baseColor = type === "straight" ? 0x506c73 : 0x466773;
const pathColor = type === "straight" ? 0xf0ae4b : 0x4fc4af;
const gemColor = type === "straight" ? 0xffd17d : 0x8de4d0;
const baseMaterial = standardMaterial(baseColor, {
transparent: ghost,
opacity: ghost ? 0.24 : 1,
depthWrite: !ghost
});
const pathMaterial = standardMaterial(pathColor, {
transparent: ghost,
opacity: ghost ? 0.56 : 1,
depthWrite: !ghost,
roughness: 0.62
});
const gemMaterial = standardMaterial(gemColor, {
transparent: ghost,
opacity: ghost ? 0.65 : 1,
depthWrite: !ghost,
emissive: pathColor,
emissiveIntensity: ghost ? 0.15 : 0.22
});
const base = new THREE.Mesh(
new THREE.BoxGeometry(0.73, 0.12, 0.73),
baseMaterial
);
base.castShadow = !ghost;
base.receiveShadow = !ghost;
group.add(base);
const connectors = type === "straight" ? [1, 3] : [1, 2];
for (const direction of connectors) {
let geometry;
let x = 0;
let z = 0;
if (direction === 1) {
geometry = new THREE.BoxGeometry(0.5, 0.065, 0.17);
x = 0.235;
} else if (direction === 3) {
geometry = new THREE.BoxGeometry(0.5, 0.065, 0.17);
x = -0.235;
} else if (direction === 2) {
geometry = new THREE.BoxGeometry(0.17, 0.065, 0.5);
z = 0.235;
} else {
geometry = new THREE.BoxGeometry(0.17, 0.065, 0.5);
z = -0.235;
}
const connector = new THREE.Mesh(geometry, pathMaterial);
connector.position.set(x, 0.09, z);
connector.castShadow = !ghost;
group.add(connector);
}
const center = new THREE.Mesh(
new THREE.CylinderGeometry(0.13, 0.15, 0.075, 6),
gemMaterial
);
center.position.y = 0.11;
center.castShadow = !ghost;
group.add(center);
group.rotation.y = rotation * Math.PI / 2;
group.userData.type = type;
group.userData.rotation = rotation;
return group;
}
function addTile(c, r, type, rotation, animate = false) {
const mesh = createPiece(type, rotation);
mesh.position.copy(worldPosition(c, r, animate ? 0.8 : 0.18));
if (animate) {
mesh.userData.dropStart = performance.now();
mesh.userData.dropDuration = 340;
}
pieceGroup.add(mesh);
const tile = { c, r, type, rotation, mesh };
tiles.set(keyFor(c, r), tile);
return tile;
}
function removeTile(key) {
const tile = tiles.get(key);
if (!tile) return;
tiles.delete(key);
inventory[tile.type]++;
pieceGroup.remove(tile.mesh);
disposeObject(tile.mesh);
}
function rotateTile(tile) {
tile.rotation = tile.type === "straight"
? (tile.rotation + 1) % 2
: (tile.rotation + 1) % 4;
tile.mesh.rotation.y = tile.rotation * Math.PI / 2;
}
// ---------------------------------------------------------------------
// Connectivity validation
// ---------------------------------------------------------------------
function sourceNeighbors() {
const neighbors = [];
for (let direction = 0; direction < 4; direction++) {
const step = DIRECTIONS[direction];
const c = START.c + step.dc;
const r = START.r + step.dr;
const tile = tiles.get(keyFor(c, r));
if (
tile &&
connectionsFor(tile.type, tile.rotation).includes((direction + 2) % 4)
) {
neighbors.push({ id: keyFor(c, r), kind: "tile" });
}
}
return neighbors;
}
function tileNeighbors(tile) {
const neighbors = [];
const connections = connectionsFor(tile.type, tile.rotation);
for (const direction of connections) {
const step = DIRECTIONS[direction];
const c = tile.c + step.dc;
const r = tile.r + step.dr;
if (!isInside(c, r)) continue;
if (c === GOAL.c && r === GOAL.r) {
neighbors.push({ id: "goal", kind: "goal" });
continue;
}
const neighbor = tiles.get(keyFor(c, r));
if (!neighbor) continue;
const opposite = (direction + 2) % 4;
const neighborConnections = connectionsFor(
neighbor.type,
neighbor.rotation
);
if (neighborConnections.includes(opposite)) {
neighbors.push({ id: keyFor(c, r), kind: "tile" });
}
}
return neighbors;
}
function findRoute() {
const previous = new Map([["source", null]]);
const queue = ["source"];
let foundGoal = false;
while (queue.length && !foundGoal) {
const currentId = queue.shift();
const neighbors = currentId === "source"
? sourceNeighbors()
: tileNeighbors(tiles.get(currentId));
for (const neighbor of neighbors) {
if (previous.has(neighbor.id)) continue;
previous.set(neighbor.id, currentId);
queue.push(neighbor.id);
if (neighbor.id === "goal") {
foundGoal = true;
break;
}
}
}
if (!foundGoal) return null;
const ids = [];
let current = "goal";
while (current !== null) {
ids.unshift(current);
current = previous.get(current);
}
const nodes = ids.map((id) => {
if (id === "source") {
return { kind: "patch", c: START.c, r: START.r };
}
if (id === "goal") {
return { kind: "patch", c: GOAL.c, r: GOAL.r };
}
return { kind: "tile", ...tiles.get(id) };
});
return {
nodes,
tiles: nodes.filter((node) => node.kind === "tile")
};
}
function showRouteGlow(route) {
clearGroup(routeGlowGroup);
routeGlowMaterials.length = 0;
const material = new THREE.MeshBasicMaterial({
color: 0xffdf70,
transparent: true,
opacity: 0.86,
depthWrite: false
});
routeGlowMaterials.push(material);
const points = route.nodes.map((node) =>
worldPosition(node.c, node.r, 0.31)
);
const up = new THREE.Vector3(0, 1, 0);
for (let i = 0; i < points.length - 1; i++) {
const a = points[i];
const b = points[i + 1];
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
if (length < 0.001) continue;
const segment = new THREE.Mesh(
new THREE.CylinderGeometry(0.043, 0.043, length, 6),
material
);
segment.position.copy(a).add(b).multiplyScalar(0.5);
segment.quaternion.setFromUnitVectors(
up,
direction.normalize()
);
segment.renderOrder = 5;
routeGlowGroup.add(segment);
}
for (const point of points) {
const node = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.073, 0),
material
);
node.position.copy(point);
node.renderOrder = 6;
routeGlowGroup.add(node);
}
}
const routeGlowMaterials = [];
// ---------------------------------------------------------------------
// State, undo and HUD
// ---------------------------------------------------------------------
function snapshot() {
return {
inventory: { ...inventory },
tiles: [...tiles.values()].map((tile) => ({
c: tile.c,
r: tile.r,
type: tile.type,
rotation: tile.rotation
}))
};
}
function restoreSnapshot(state) {
for (const tile of [...tiles.values()]) {
pieceGroup.remove(tile.mesh);
disposeObject(tile.mesh);
}
tiles.clear();
inventory.straight = state.inventory.straight;
inventory.bend = state.inventory.bend;
for (const data of state.tiles) {
addTile(data.c, data.r, data.type, data.rotation, false);
}
}
function mutate(action) {
undoStack.push(snapshot());
if (undoStack.length > 60) undoStack.shift();
action();
invalidateValidation();
refreshHUD();
}
function invalidateValidation() {
validationChecked = false;
routeValidated = false;
currentRoute = null;
clearGroup(routeGlowGroup);
routeGlowMaterials.length = 0;
}
function refreshHUD() {
currentRoute = findRoute();
const placed = tiles.size;
const spare = inventory.straight + inventory.bend;
placedMetric.textContent = placed;
spareMetric.textContent = spare;
routeMetric.textContent = currentRoute ? currentRoute.tiles.length : "—";
document.getElementById("straightCount").textContent = inventory.straight;
document.getElementById("bendCount").textContent = inventory.bend;
const straightButton = document.querySelector('[data-type="straight"]');
const bendButton = document.querySelector('[data-type="bend"]');
straightButton.disabled = inventory.straight === 0;
bendButton.disabled = inventory.bend === 0;
straightButton.classList.toggle("active", selectedType === "straight");
bendButton.classList.toggle("active", selectedType === "bend");
undoButton.disabled = undoStack.length === 0;
clearButton.disabled = placed === 0;
statusPanel.classList.remove("good", "linked", "bad");
if (currentRoute && routeValidated) {
statusPanel.classList.add("good");
statusTitle.textContent = "Route connected!";
statusText.textContent =
`${currentRoute.tiles.length} pieces form a continuous trail between the patches.`;
validateButton.textContent = "Connection confirmed";
validateButton.classList.add("complete");
} else if (currentRoute) {
statusPanel.classList.add("linked");
statusTitle.textContent = "Link detected";
statusText.textContent =
"The ports appear connected. Test the route to lock in your trail.";
validateButton.textContent = "Test connection";
validateButton.classList.remove("complete");
} else if (validationChecked) {
statusPanel.classList.add("bad");
statusTitle.textContent = "No continuous route";
statusText.textContent =
"Check that neighboring tile ports meet and that at least one piece reaches each patch.";
validateButton.textContent = "Test again";
validateButton.classList.remove("complete");
} else {
statusTitle.textContent = placed ? "Keep weaving" : "Build a trail";
statusText.textContent = placed
? "North and south detours can both work. Shape a continuous, port-to-port trail."
: "Place path pieces between the two glowing patches.";
validateButton.textContent = "Test connection";
validateButton.classList.remove("complete");
}
updatePreview();
}
function selectType(type) {
if (inventory[type] <= 0) {
showToast(`No ${type} pieces remain.`);
return;
}
selectedType = type;
selectedRotation = 0;
refreshHUD();
}
function rotateSelection() {
selectedRotation = selectedType === "straight"
? (selectedRotation + 1) % 2
: (selectedRotation + 1) % 4;
updatePreview();
}
// ---------------------------------------------------------------------
// Preview and board interaction
// ---------------------------------------------------------------------
let previewSignature = "";
function updatePreview() {
const signature = hoverCell
? [
hoverCell.c,
hoverCell.r,
selectedType,
selectedRotation,
inventory[selectedType],
tiles.has(keyFor(hoverCell.c, hoverCell.r))
].join(":")
: "";
if (signature === previewSignature) return;
previewSignature = signature;
clearGroup(previewGroup);
hoverMarker.visible = Boolean(hoverCell);
if (!hoverCell) return;
const { c, r } = hoverCell;
hoverMarker.position.copy(worldPosition(c, r, 0.14));
const occupied = tiles.has(keyFor(c, r));
const blocked = BLOCKED.has(keyFor(c, r));
const patch = isPatch(c, r);
if (occupied) {
hoverMarker.material.color.set(0x53c5ae);
hoverMarker.material.opacity = 0.42;
return;
}
if (blocked) {
hoverMarker.material.color.set(0xd66d60);
hoverMarker.material.opacity = 0.48;
return;
}
if (patch) {
hoverMarker.material.color.set(0xffffff);
hoverMarker.material.opacity = 0.22;
return;
}
hoverMarker.material.color.set(
inventory[selectedType] > 0 ? 0xffffff : 0xd66d60
);
hoverMarker.material.opacity = inventory[selectedType] > 0 ? 0.32 : 0.45;
if (inventory[selectedType] <= 0) return;
const ghost = createPiece(selectedType, selectedRotation, true);
ghost.position.copy(worldPosition(c, r, 0.19));
previewGroup.add(ghost);
}
function interactWithCell(c, r) {
const key = keyFor(c, r);
const existing = tiles.get(key);
if (existing) {
mutate(() => rotateTile(existing));
showToast("Piece rotated.");
return;
}
if (!isInside(c, r)) return;
if (isPatch(c, r)) {
showToast("The endpoint patches cannot be covered.");
return;
}
if (BLOCKED.has(key)) {
showToast("A rocky outcrop blocks this cell.");
return;
}
if (inventory[selectedType] <= 0) {
showToast(`No ${selectedType} pieces remain.`);
return;
}
mutate(() => {
inventory[selectedType]--;
addTile(c, r, selectedType, selectedRotation, true);
});
}
function removeAt(c, r) {
const key = keyFor(c, r);
if (!tiles.has(key)) return;
mutate(() => removeTile(key));
showToast("Piece removed.");
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const boardPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.09);
function cellFromEvent(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const point = new THREE.Vector3();
if (!raycaster.ray.intersectPlane(boardPlane, point)) return null;
const c = Math.round(point.x + (COLS - 1) / 2);
const r = Math.round(point.z + (ROWS - 1) / 2);
if (!isInside(c, r)) return null;
return { c, r };
}
let pointerDown = false;
let pointerMoved = false;
let pointerButton = 0;
let startX = 0;
let startY = 0;
let lastX = 0;
let lastY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button === 2) {
event.preventDefault();
const cell = cellFromEvent(event);
if (cell) removeAt(cell.c, cell.r);
return;
}
if (event.button !== 0) return;
pointerDown = true;
pointerMoved = false;
pointerButton = event.button;
startX = lastX = event.clientX;
startY = lastY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (pointerDown) {
const totalDistance = Math.hypot(
event.clientX - startX,
event.clientY - startY
);
if (totalDistance > 5) pointerMoved = true;
if (pointerMoved) {
const dx = event.clientX - lastX;
const dy = event.clientY - lastY;
cameraView.theta -= dx * 0.006;
cameraView.phi = THREE.MathUtils.clamp(
cameraView.phi + dy * 0.004,
0.52,
1.28
);
updateCamera();
}
lastX = event.clientX;
lastY = event.clientY;
}
hoverCell = cellFromEvent(event);
updatePreview();
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (!pointerDown) return;
pointerDown = false;
if (pointerButton === 0 && !pointerMoved) {
const cell = cellFromEvent(event);
if (cell) interactWithCell(cell.c, cell.r);
}
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = false;
pointerMoved = false;
});
renderer.domElement.addEventListener("pointerleave", () => {
if (!pointerDown) {
hoverCell = null;
updatePreview();
}
});
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("wheel", (event) => {
event.preventDefault();
cameraView.zoom = THREE.MathUtils.clamp(
cameraView.zoom * (event.deltaY > 0 ? 0.91 : 1.1),
0.72,
1.65
);
updateCamera();
}, { passive: false });
// ---------------------------------------------------------------------
// Buttons and keyboard
// ---------------------------------------------------------------------
document.querySelectorAll(".tool").forEach((button) => {
button.addEventListener("click", () => {
selectType(button.dataset.type);
});
});
rotateButton.addEventListener("click", rotateSelection);
undoButton.addEventListener("click", () => {
if (!undoStack.length) return;
restoreSnapshot(undoStack.pop());
invalidateValidation();
refreshHUD();
showToast("Last action undone.");
});
clearButton.addEventListener("click", () => {
if (!tiles.size) return;
mutate(() => {
for (const key of [...tiles.keys()]) {
const tile = tiles.get(key);
pieceGroup.remove(tile.mesh);
disposeObject(tile.mesh);
tiles.delete(key);
inventory[tile.type]++;
}
});
showToast("Board cleared.");
});
validateButton.addEventListener("click", () => {
currentRoute = findRoute();
validationChecked = true;
routeValidated = Boolean(currentRoute);
if (currentRoute) {
showRouteGlow(currentRoute);
celebrate();
showToast("The trail connects both patches!");
} else {
clearGroup(routeGlowGroup);
showToast("No complete route yet. Check the tile ports.");
}
refreshHUD();
});
window.addEventListener("keydown", (event) => {
if (event.ctrlKey || event.metaKey) {
if (event.key.toLowerCase() === "z" && undoStack.length) {
event.preventDefault();
restoreSnapshot(undoStack.pop());
invalidateValidation();
refreshHUD();
showToast("Last action undone.");
}
return;
}
if (event.key.toLowerCase() === "r") {
rotateSelection();
} else if (event.key === "1") {
selectType("straight");
} else if (event.key === "2") {
selectType("bend");
} else if (
(event.key === "Delete" || event.key === "Backspace") &&
hoverCell
) {
event.preventDefault();
removeAt(hoverCell.c, hoverCell.r);
}
});
// ---------------------------------------------------------------------
// Celebration particles
// ---------------------------------------------------------------------
const particles = [];
const celebrationColors = [
0xffc45b, 0xff8c62, 0x65cdb8, 0xfff0ad, 0x5aa6c4
];
function celebrate() {
const origin = worldPosition(GOAL.c, GOAL.r, 0.9);
for (let i = 0; i < 28; i++) {
const material = standardMaterial(
celebrationColors[i % celebrationColors.length]
);
const particle = new THREE.Mesh(
new THREE.BoxGeometry(0.055, 0.025, 0.12),
material
);
particle.position.copy(origin);
particle.rotation.set(
hash(i, 1) * Math.PI,
hash(i, 2) * Math.PI,
hash(i, 3) * Math.PI
);
const angle = hash(i, 4) * Math.PI * 2;
const speed = 1.2 + hash(i, 5) * 2.1;
particles.push({
mesh: particle,
velocity: new THREE.Vector3(
Math.cos(angle) * speed,
2 + hash(i, 6) * 2.5,
Math.sin(angle) * speed
),
spin: new THREE.Vector3(
(hash(i, 7) - 0.5) * 8,
(hash(i, 8) - 0.5) * 8,
(hash(i, 9) - 0.5) * 8
),
born: performance.now()
});
particleGroup.add(particle);
}
}
function updateParticles(now) {
for (let i = particles.length - 1; i >= 0; i--) {
const particle = particles[i];
const age = (now - particle.born) / 1000;
if (age > 2.5) {
particleGroup.remove(particle.mesh);
disposeObject(particle.mesh);
particles.splice(i, 1);
continue;
}
particle.velocity.y -= 5.5 * (1 / 60);
particle.mesh.position.addScaledVector(particle.velocity, 1 / 60);
particle.mesh.rotation.x += particle.spin.x / 60;
particle.mesh.rotation.y += particle.spin.y / 60;
particle.mesh.rotation.z += particle.spin.z / 60;
particle.mesh.scale.setScalar(Math.max(0, 1 - age * 0.22));
}
}
// ---------------------------------------------------------------------
// Camera, labels and animation
// ---------------------------------------------------------------------
function updateCamera() {
const radius = 18;
camera.position.set(
cameraTarget.x +
radius * Math.sin(cameraView.phi) * Math.sin(cameraView.theta),
cameraTarget.y + radius * Math.cos(cameraView.phi),
cameraTarget.z +
radius * Math.sin(cameraView.phi) * Math.cos(cameraView.theta)
);
camera.lookAt(cameraTarget);
camera.zoom = cameraView.zoom;
camera.updateProjectionMatrix();
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
const halfHeight = Math.max(4.5, 6.7 / aspect);
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
}
window.addEventListener("resize", resize);
const startLabel = document.getElementById("startLabel");
const goalLabel = document.getElementById("goalLabel");
const labelPoint = new THREE.Vector3();
function updateLabel(element, c, r, height) {
labelPoint.copy(worldPosition(c, r, height)).project(camera);
const visible =
labelPoint.z > -1 &&
labelPoint.z < 1 &&
Math.abs(labelPoint.x) < 1.15 &&
Math.abs(labelPoint.y) < 1.15;
element.style.display = visible ? "block" : "none";
if (!visible) return;
const x = (labelPoint.x * 0.5 + 0.5) * window.innerWidth;
const y = (-labelPoint.y * 0.5 + 0.5) * window.innerHeight;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}
function animate(now) {
requestAnimationFrame(animate);
for (const tile of tiles.values()) {
const drop = tile.mesh.userData.dropStart;
if (drop) {
const progress = Math.min(
1,
(now - drop) / tile.mesh.userData.dropDuration
);
const eased = 1 - Math.pow(1 - progress, 3);
tile.mesh.position.y = THREE.MathUtils.lerp(0.8, 0.18, eased);
const pop = 0.88 + eased * 0.12 + Math.sin(progress * Math.PI) * 0.08;
tile.mesh.scale.setScalar(pop);
if (progress >= 1) {
tile.mesh.position.y = 0.18;
tile.mesh.scale.setScalar(1);
delete tile.mesh.userData.dropStart;
}
}
}
for (const material of routeGlowMaterials) {
material.opacity = 0.72 + Math.sin(now * 0.004) * 0.17;
}
if (goalCrystal) {
goalCrystal.rotation.y = now * 0.00055;
goalCrystal.position.y = 0.55 + Math.sin(now * 0.0024) * 0.035;
}
for (const cloud of cloudGroup.children) {
cloud.position.x =
cloud.userData.baseX + Math.sin(now * 0.00018 + cloud.userData.phase) * 0.7;
}
updateParticles(now);
updateLabel(startLabel, START.c, START.r, 1.18);
updateLabel(goalLabel, GOAL.c, GOAL.r, 1.22);
renderer.render(scene, camera);
}
// ---------------------------------------------------------------------
// Initialize
// ---------------------------------------------------------------------
buildTerrain();
buildClouds();
createPatch(START.c, START.r, true);
createPatch(GOAL.c, GOAL.r, false);
resize();
updateCamera();
refreshHUD();
renderer.render(scene, camera);
requestAnimationFrame(animate);
requestAnimationFrame(() => {
document.getElementById("loading").classList.add("hide");
});
</script>
</body>
</html>
```