Prompt specification
Build or customize the Three.js 3D scene "Find a viewpoint for two beacons" 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: Find a viewpoint for two beacons
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/find-a-viewpoint-for-two-beacons-x1328
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing landmark visibility across terrain. Let users move an observer across a hillside to see two beacons simultaneously. Highlight visibility changes and keep the obstacle geometry identical during the search. Low-poly.
Working Three.js Starter (find-a-viewpoint-for-two-beacons-x1328):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ridgeline — Dual Beacon Visibility</title>
<style>
:root {
--ink: #142326;
--muted: #92a5a4;
--panel: rgba(14, 27, 29, 0.86);
--panel-soft: rgba(19, 36, 38, 0.72);
--line: rgba(216, 239, 231, 0.14);
--clear: #8df2a7;
--blocked: #ff7184;
--amber: #ffc857;
--cyan: #59d9ff;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #bdcfca;
color: #eef7f3;
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
cursor: crosshair;
touch-action: none;
}
.wash {
position: fixed;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 52% 40%, transparent 35%, rgba(12, 30, 31, 0.08) 100%),
linear-gradient(180deg, rgba(225, 239, 230, 0.12), transparent 28%);
}
.glass {
background: var(--panel);
border: 1px solid var(--line);
box-shadow: 0 18px 50px rgba(5, 18, 19, 0.2);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
.topbar {
position: fixed;
top: 18px;
left: 18px;
right: 18px;
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 14px;
pointer-events: none;
z-index: 10;
}
.brand {
width: min(390px, calc(100vw - 36px));
padding: 17px 19px 16px;
border-radius: 17px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
color: #abc0bb;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow-mark {
width: 8px;
height: 8px;
border-radius: 2px;
background: var(--amber);
box-shadow: 0 0 15px rgba(255, 200, 87, 0.65);
transform: rotate(45deg);
}
h1 {
margin: 8px 0 4px;
font-size: clamp(23px, 3vw, 32px);
line-height: 1;
letter-spacing: -0.045em;
font-weight: 720;
}
.subtitle {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.lock-pill {
display: flex;
align-items: center;
gap: 10px;
min-height: 43px;
padding: 0 14px;
border-radius: 13px;
color: #dceae5;
font-size: 10px;
font-weight: 760;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.lock-icon {
position: relative;
width: 15px;
height: 12px;
border: 2px solid #8df2a7;
border-radius: 3px;
}
.lock-icon::before {
content: "";
position: absolute;
left: 2px;
top: -8px;
width: 7px;
height: 8px;
border: 2px solid #8df2a7;
border-bottom: 0;
border-radius: 7px 7px 0 0;
}
.lock-pill b {
color: #8df2a7;
font-size: 10px;
}
.beacon-panel {
position: fixed;
top: 104px;
right: 18px;
width: 294px;
display: grid;
gap: 10px;
pointer-events: none;
z-index: 10;
}
.beacon-card {
position: relative;
overflow: hidden;
padding: 14px;
border-radius: 15px;
background: var(--panel-soft);
border: 1px solid var(--line);
backdrop-filter: blur(12px);
transition:
border-color 180ms ease,
background 180ms ease,
transform 180ms ease;
}
.beacon-card::after {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 3px;
background: #728786;
transition: background 180ms ease;
}
.beacon-card[data-state="visible"] {
border-color: rgba(141, 242, 167, 0.42);
background: rgba(18, 42, 37, 0.83);
}
.beacon-card[data-state="visible"]::after {
background: var(--clear);
box-shadow: 0 0 18px rgba(141, 242, 167, 0.8);
}
.beacon-card[data-state="blocked"] {
border-color: rgba(255, 113, 132, 0.35);
background: rgba(49, 26, 32, 0.82);
}
.beacon-card[data-state="blocked"]::after {
background: var(--blocked);
}
.beacon-card.flash {
animation: cardFlash 780ms ease-out;
}
@keyframes cardFlash {
0% {
transform: translateX(0) scale(1);
box-shadow: 0 0 0 rgba(255, 255, 255, 0);
}
30% {
transform: translateX(-3px) scale(1.018);
box-shadow: 0 0 28px rgba(255, 255, 255, 0.17);
}
100% {
transform: translateX(0) scale(1);
}
}
.beacon-head,
.beacon-foot {
display: flex;
align-items: center;
}
.beacon-head {
gap: 10px;
}
.beacon-icon {
display: grid;
place-items: center;
width: 35px;
height: 35px;
flex: 0 0 35px;
border-radius: 10px;
font-size: 16px;
color: #182727;
background: var(--amber);
box-shadow: 0 0 20px rgba(255, 200, 87, 0.2);
}
#cardB .beacon-icon {
background: var(--cyan);
box-shadow: 0 0 20px rgba(89, 217, 255, 0.2);
}
.beacon-name {
min-width: 0;
flex: 1;
}
.beacon-name small {
display: block;
margin-bottom: 3px;
color: #829a97;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.beacon-name strong {
display: block;
overflow: hidden;
color: #f0f7f4;
font-size: 13px;
white-space: nowrap;
text-overflow: ellipsis;
}
.state-pill {
padding: 5px 7px;
border-radius: 999px;
color: #9caead;
background: rgba(255, 255, 255, 0.06);
font-size: 8px;
font-weight: 850;
letter-spacing: 0.1em;
text-transform: uppercase;
}
[data-state="visible"] .state-pill {
color: #b8ffd0;
background: rgba(141, 242, 167, 0.12);
}
[data-state="blocked"] .state-pill {
color: #ffc0c9;
background: rgba(255, 113, 132, 0.12);
}
.beacon-foot {
gap: 7px;
margin-top: 12px;
padding-top: 10px;
border-top: 1px solid rgba(255, 255, 255, 0.08);
color: #a8b9b6;
font-size: 9px;
letter-spacing: 0.03em;
}
.state-dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: #738785;
}
[data-state="visible"] .state-dot {
background: var(--clear);
box-shadow: 0 0 10px var(--clear);
}
[data-state="blocked"] .state-dot {
background: var(--blocked);
box-shadow: 0 0 10px var(--blocked);
}
.distance {
margin-left: auto;
color: #d4e0dc;
font-variant-numeric: tabular-nums;
}
.world-label {
position: fixed;
z-index: 8;
display: none;
pointer-events: none;
padding: 6px 9px;
border: 1px solid rgba(255, 255, 255, 0.16);
border-radius: 999px;
color: #f5fbf8;
background: rgba(13, 28, 29, 0.78);
box-shadow: 0 8px 22px rgba(0, 0, 0, 0.17);
backdrop-filter: blur(7px);
font-size: 9px;
font-weight: 780;
letter-spacing: 0.09em;
text-transform: uppercase;
transform: translate(-50%, -100%);
white-space: nowrap;
}
.world-label::before {
content: "";
display: inline-block;
width: 6px;
height: 6px;
margin-right: 6px;
border-radius: 50%;
background: #718583;
vertical-align: 1px;
}
.world-label[data-state="visible"]::before {
background: var(--clear);
box-shadow: 0 0 8px var(--clear);
}
.world-label[data-state="blocked"]::before {
background: var(--blocked);
}
.minimap-panel {
position: fixed;
bottom: 18px;
left: 18px;
width: 242px;
padding: 12px;
border-radius: 16px;
z-index: 12;
}
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 0 2px 9px;
color: #dce9e5;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.panel-title span:last-child {
color: #78908c;
font-size: 8px;
letter-spacing: 0.08em;
}
#minimap {
display: block;
width: 216px;
height: 216px;
border-radius: 10px;
background: #70877d;
cursor: crosshair;
touch-action: none;
}
.map-caption {
margin: 9px 2px 0;
color: #839995;
font-size: 9px;
line-height: 1.4;
}
.controls {
position: fixed;
left: 50%;
bottom: 18px;
width: min(600px, calc(100vw - 310px));
min-width: 410px;
padding: 12px 14px;
border-radius: 17px;
transform: translateX(-50%);
z-index: 12;
}
.control-row {
display: flex;
align-items: center;
gap: 9px;
}
.mode-group {
display: flex;
padding: 3px;
border-radius: 10px;
background: rgba(255, 255, 255, 0.055);
}
.mode-button,
.reset-button {
min-height: 31px;
border: 0;
border-radius: 8px;
color: #9db0ad;
background: transparent;
cursor: pointer;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
transition: 160ms ease;
}
.mode-button {
padding: 0 11px;
}
.mode-button.active {
color: #142729;
background: #e3eee8;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.16);
}
.reset-button {
padding: 0 11px;
border: 1px solid var(--line);
}
.reset-button:hover,
.mode-button:hover:not(.active) {
color: #f0f8f4;
background: rgba(255, 255, 255, 0.07);
}
.summary {
margin-left: auto;
color: #f3faf6;
font-size: 9px;
font-weight: 820;
letter-spacing: 0.08em;
text-transform: uppercase;
white-space: nowrap;
}
.summary::before {
content: "";
display: inline-block;
width: 7px;
height: 7px;
margin-right: 7px;
border-radius: 50%;
background: var(--blocked);
box-shadow: 0 0 10px rgba(255, 113, 132, 0.45);
}
.summary[data-count="1"]::before {
background: var(--amber);
box-shadow: 0 0 10px rgba(255, 200, 87, 0.5);
}
.summary[data-count="2"]::before {
background: var(--clear);
box-shadow: 0 0 10px rgba(141, 242, 167, 0.65);
}
.control-foot {
display: flex;
align-items: center;
gap: 15px;
margin-top: 9px;
padding-top: 9px;
border-top: 1px solid rgba(255, 255, 255, 0.08);
color: #829895;
font-size: 9px;
}
.coordinates {
color: #c6d6d1;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.line-toggle {
display: flex;
align-items: center;
gap: 6px;
cursor: pointer;
user-select: none;
}
.line-toggle input {
width: 13px;
height: 13px;
margin: 0;
accent-color: #8df2a7;
}
.help {
margin-left: auto;
text-align: right;
line-height: 1.4;
}
.toast {
position: fixed;
top: 92px;
left: 50%;
z-index: 30;
max-width: min(460px, calc(100vw - 30px));
padding: 11px 15px;
border: 1px solid rgba(141, 242, 167, 0.35);
border-radius: 999px;
color: #eaffef;
background: rgba(18, 42, 34, 0.92);
box-shadow: 0 12px 36px rgba(4, 20, 18, 0.24);
opacity: 0;
pointer-events: none;
transform: translate(-50%, -12px);
transition: 220ms ease;
font-size: 11px;
font-weight: 680;
text-align: center;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
.toast[data-tone="lost"] {
color: #ffe4e8;
border-color: rgba(255, 113, 132, 0.38);
background: rgba(54, 27, 33, 0.93);
}
#loading {
position: fixed;
inset: 0;
z-index: 100;
display: grid;
place-items: center;
color: #dfece7;
background: #172b2d;
transition: opacity 400ms ease;
font-size: 11px;
font-weight: 750;
letter-spacing: 0.16em;
text-transform: uppercase;
}
#loading.hidden {
opacity: 0;
pointer-events: none;
}
@media (max-width: 850px) {
.lock-pill {
display: none;
}
.beacon-panel {
top: 92px;
right: 12px;
width: 270px;
}
.minimap-panel {
bottom: 12px;
left: 12px;
transform: scale(0.82);
transform-origin: bottom left;
}
.controls {
bottom: 12px;
width: calc(100vw - 255px);
min-width: 350px;
}
}
@media (max-width: 640px) {
.brand {
padding: 13px 15px;
}
.subtitle {
display: none;
}
.beacon-panel {
top: 88px;
left: 12px;
right: 12px;
width: auto;
grid-template-columns: 1fr 1fr;
}
.beacon-card {
padding: 10px;
}
.beacon-icon {
width: 29px;
height: 29px;
flex-basis: 29px;
}
.state-pill {
display: none;
}
.beacon-foot {
margin-top: 8px;
padding-top: 7px;
}
.minimap-panel {
display: none;
}
.controls {
left: 12px;
right: 12px;
width: auto;
min-width: 0;
transform: none;
}
.help {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive low-poly terrain visibility scene"></canvas>
<div class="wash"></div>
<header class="topbar">
<div class="brand glass">
<div class="eyebrow">
<span class="eyebrow-mark"></span>
Ridgeline / Visibility Lab
</div>
<h1>Dual Beacon Search</h1>
<p class="subtitle">
Move the observer across the hillside. Terrain and obstacle geometry remain fixed.
</p>
</div>
<div class="lock-pill glass">
<span class="lock-icon"></span>
<span>Static world</span>
<b id="obstacleCount">0 fixed occluders</b>
</div>
</header>
<section class="beacon-panel">
<article class="beacon-card" id="cardA" data-state="unknown">
<div class="beacon-head">
<div class="beacon-icon">▲</div>
<div class="beacon-name">
<small>Landmark 01</small>
<strong>Pine Beacon</strong>
</div>
<span class="state-pill" id="pillA">Checking</span>
</div>
<div class="beacon-foot">
<span class="state-dot"></span>
<span id="statusA">Locating sightline</span>
<span class="distance" id="distanceA">— m</span>
</div>
</article>
<article class="beacon-card" id="cardB" data-state="unknown">
<div class="beacon-head">
<div class="beacon-icon">▲</div>
<div class="beacon-name">
<small>Landmark 02</small>
<strong>Ridge Relay</strong>
</div>
<span class="state-pill" id="pillB">Checking</span>
</div>
<div class="beacon-foot">
<span class="state-dot"></span>
<span id="statusB">Locating sightline</span>
<span class="distance" id="distanceB">— m</span>
</div>
</article>
</section>
<div class="world-label" id="labelA">Pine Beacon</div>
<div class="world-label" id="labelB">Ridge Relay</div>
<section class="minimap-panel glass">
<div class="panel-title">
<span>Terrain Map</span>
<span>Click to move</span>
</div>
<canvas id="minimap" width="240" height="240"></canvas>
<p class="map-caption">
The minimap and 3D observer use the same terrain and occlusion data.
</p>
</section>
<section class="controls glass">
<div class="control-row">
<div class="mode-group" aria-label="Pointer mode">
<button class="mode-button active" id="moveMode">Move</button>
<button class="mode-button" id="orbitMode">Orbit</button>
</div>
<button class="reset-button" id="resetButton">Reset</button>
<div class="summary" id="summary" data-count="0">0 / 2 visible</div>
</div>
<div class="control-foot">
<span class="coordinates" id="coordinates">X 0.0 · Z 0.0 · 0.0 m</span>
<label class="line-toggle">
<input type="checkbox" id="showLines" checked />
Sightlines
</label>
<span class="help">
Drag hillside to move · Right-drag to orbit · Scroll to zoom
</span>
</div>
</section>
<div class="toast" id="toast"></div>
<div id="loading">Building fixed terrain…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Core setup
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const minimap = document.querySelector("#minimap");
const minimapContext = minimap.getContext("2d");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color("#c5d7d1");
scene.fog = new THREE.Fog("#c5d7d1", 80, 190);
const camera = new THREE.PerspectiveCamera(
48,
window.innerWidth / window.innerHeight,
0.1,
260
);
const hemisphereLight = new THREE.HemisphereLight(
"#e7f1e8",
"#556a5f",
2.15
);
scene.add(hemisphereLight);
const sun = new THREE.DirectionalLight("#fff1cf", 3.1);
sun.position.set(-30, 48, 24);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -48;
sun.shadow.camera.right = 48;
sun.shadow.camera.top = 48;
sun.shadow.camera.bottom = -48;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 115;
sun.shadow.normalBias = 0.035;
scene.add(sun);
const WORLD_SIZE = 72;
const TERRAIN_SEGMENTS = 48;
const observerEyeHeight = 2.05;
const clamp = THREE.MathUtils.clamp;
const lerp = THREE.MathUtils.lerp;
// -------------------------------------------------------------------------
// Deterministic terrain. This height function never changes during a search.
// -------------------------------------------------------------------------
function hash2(x, z) {
const value = Math.sin(x * 127.1 + z * 311.7 + 19.19) * 43758.5453123;
return value - Math.floor(value);
}
function smoothstep(value) {
return value * value * (3 - 2 * value);
}
function valueNoise(x, z) {
const ix = Math.floor(x);
const iz = Math.floor(z);
const fx = smoothstep(x - ix);
const fz = smoothstep(z - iz);
const a = hash2(ix, iz);
const b = hash2(ix + 1, iz);
const c = hash2(ix, iz + 1);
const d = hash2(ix + 1, iz + 1);
return lerp(lerp(a, b, fx), lerp(c, d, fx), fz);
}
function terrainHeight(x, z) {
const ridge =
0.026 * (x + 36) +
1.25 * Math.sin((z + 6) * 0.095) +
0.68 * Math.cos((x - 4) * 0.13);
const noise =
valueNoise(x * 0.075 + 40, z * 0.075 - 22) * 1.4 +
valueNoise(x * 0.16 - 3, z * 0.16 + 8) * 0.42;
const pineKnoll =
4.5 * Math.exp(
-((x + 17) * (x + 17) / 175 + (z - 14) * (z - 14) / 170)
);
const ridgeKnoll =
4.8 * Math.exp(
-((x - 18) * (x - 18) / 185 + (z + 16) * (z + 16) / 175)
);
return ridge + noise + pineKnoll + ridgeKnoll - 2.25;
}
const terrainPositions = [];
const terrainColors = [];
const terrainIndices = [];
const lowColor = new THREE.Color("#728d72");
const highColor = new THREE.Color("#c6be98");
const color = new THREE.Color();
for (let iz = 0; iz <= TERRAIN_SEGMENTS; iz++) {
const z = -WORLD_SIZE / 2 + (iz / TERRAIN_SEGMENTS) * WORLD_SIZE;
for (let ix = 0; ix <= TERRAIN_SEGMENTS; ix++) {
const x = -WORLD_SIZE / 2 + (ix / TERRAIN_SEGMENTS) * WORLD_SIZE;
const height = terrainHeight(x, z);
terrainPositions.push(x, height, z);
const heightMix = clamp((height + 3.5) / 12.5, 0, 1);
color.copy(lowColor).lerp(highColor, heightMix);
color.multiplyScalar(0.94 + ((ix + iz) % 2) * 0.055);
terrainColors.push(color.r, color.g, color.b);
}
}
for (let iz = 0; iz < TERRAIN_SEGMENTS; iz++) {
for (let ix = 0; ix < TERRAIN_SEGMENTS; ix++) {
const a = iz * (TERRAIN_SEGMENTS + 1) + ix;
const b = a + 1;
const c = a + TERRAIN_SEGMENTS + 1;
const d = c + 1;
terrainIndices.push(a, c, b, b, c, d);
}
}
const terrainGeometry = new THREE.BufferGeometry();
terrainGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(terrainPositions, 3)
);
terrainGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(terrainColors, 3)
);
terrainGeometry.setIndex(terrainIndices);
terrainGeometry.computeVertexNormals();
terrainGeometry.computeBoundingSphere();
const terrainMaterial = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.98,
metalness: 0,
flatShading: true
});
const terrainMesh = new THREE.Mesh(terrainGeometry, terrainMaterial);
terrainMesh.receiveShadow = true;
scene.add(terrainMesh);
// A subtle wire overlay reinforces the low-poly terrain.
const terrainWire = new THREE.Mesh(
terrainGeometry,
new THREE.MeshBasicMaterial({
color: "#314b42",
wireframe: true,
transparent: true,
opacity: 0.075,
depthWrite: false
})
);
terrainWire.renderOrder = 1;
scene.add(terrainWire);
// Diorama edge / skirt.
const perimeter = [];
const edgeSteps = 24;
for (let i = 0; i < edgeSteps; i++) {
const t = i / edgeSteps;
perimeter.push(
new THREE.Vector3(
lerp(-WORLD_SIZE / 2, WORLD_SIZE / 2, t),
terrainHeight(
lerp(-WORLD_SIZE / 2, WORLD_SIZE / 2, t),
-WORLD_SIZE / 2
),
-WORLD_SIZE / 2
)
);
}
for (let i = 0; i < edgeSteps; i++) {
const t = i / edgeSteps;
perimeter.push(
new THREE.Vector3(
WORLD_SIZE / 2,
terrainHeight(
WORLD_SIZE / 2,
lerp(-WORLD_SIZE / 2, WORLD_SIZE / 2, t)
),
lerp(-WORLD_SIZE / 2, WORLD_SIZE / 2, t)
)
);
}
for (let i = 0; i < edgeSteps; i++) {
const t = i / edgeSteps;
perimeter.push(
new THREE.Vector3(
lerp(WORLD_SIZE / 2, -WORLD_SIZE / 2, t),
terrainHeight(
lerp(WORLD_SIZE / 2, -WORLD_SIZE / 2, t),
WORLD_SIZE / 2
),
WORLD_SIZE / 2
)
);
}
for (let i = 0; i < edgeSteps; i++) {
const t = i / edgeSteps;
perimeter.push(
new THREE.Vector3(
-WORLD_SIZE / 2,
terrainHeight(
-WORLD_SIZE / 2,
lerp(WORLD_SIZE / 2, -WORLD_SIZE / 2, t)
),
lerp(WORLD_SIZE / 2, -WORLD_SIZE / 2, t)
)
);
}
const skirtPositions = [];
const bottomY = -5.2;
for (let i = 0; i < perimeter.length; i++) {
const a = perimeter[i];
const b = perimeter[(i + 1) % perimeter.length];
skirtPositions.push(
a.x, a.y, a.z,
b.x, b.y, b.z,
a.x, bottomY, a.z,
b.x, b.y, b.z,
b.x, bottomY, b.z,
a.x, bottomY, a.z
);
}
const skirtGeometry = new THREE.BufferGeometry();
skirtGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(skirtPositions, 3)
);
skirtGeometry.computeVertexNormals();
const skirtMesh = new THREE.Mesh(
skirtGeometry,
new THREE.MeshStandardMaterial({
color: "#596b5f",
roughness: 1,
flatShading: true,
side: THREE.DoubleSide
})
);
skirtMesh.receiveShadow = true;
scene.add(skirtMesh);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(230, 230),
new THREE.MeshStandardMaterial({
color: "#aebeb3",
roughness: 1
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = bottomY - 0.03;
ground.receiveShadow = true;
scene.add(ground);
// -------------------------------------------------------------------------
// Beacons
// -------------------------------------------------------------------------
function makeGlowTexture() {
const glowCanvas = document.createElement("canvas");
glowCanvas.width = 128;
glowCanvas.height = 128;
const context = glowCanvas.getContext("2d");
const gradient = context.createRadialGradient(64, 64, 0, 64, 64, 64);
gradient.addColorStop(0, "rgba(255,255,255,1)");
gradient.addColorStop(0.12, "rgba(255,255,255,.95)");
gradient.addColorStop(0.36, "rgba(255,255,255,.35)");
gradient.addColorStop(1, "rgba(255,255,255,0)");
context.fillStyle = gradient;
context.fillRect(0, 0, 128, 128);
const texture = new THREE.CanvasTexture(glowCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
function makeCrossTexture() {
const crossCanvas = document.createElement("canvas");
crossCanvas.width = 128;
crossCanvas.height = 128;
const context = crossCanvas.getContext("2d");
context.strokeStyle = "#ffffff";
context.lineWidth = 13;
context.lineCap = "round";
context.beginPath();
context.moveTo(32, 32);
context.lineTo(96, 96);
context.moveTo(96, 32);
context.lineTo(32, 96);
context.stroke();
const texture = new THREE.CanvasTexture(crossCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
const glowTexture = makeGlowTexture();
const crossTexture = makeCrossTexture();
const beacons = [];
function createBeacon(id, name, x, z, cssColor) {
const color = new THREE.Color(cssColor);
const group = new THREE.Group();
group.position.set(x, terrainHeight(x, z), z);
const platform = new THREE.Mesh(
new THREE.CylinderGeometry(2.15, 2.55, 0.42, 8),
new THREE.MeshStandardMaterial({
color: "#64746c",
roughness: 0.92,
flatShading: true
})
);
platform.position.y = 0.2;
platform.castShadow = true;
platform.receiveShadow = true;
group.add(platform);
const mast = new THREE.Mesh(
new THREE.CylinderGeometry(0.16, 0.25, 4.15, 6),
new THREE.MeshStandardMaterial({
color: "#263a3c",
roughness: 0.72,
metalness: 0.2,
flatShading: true
})
);
mast.position.y = 2.28;
mast.castShadow = true;
group.add(mast);
const housing = new THREE.Mesh(
new THREE.BoxGeometry(1.18, 0.9, 1.18),
new THREE.MeshStandardMaterial({
color: "#dce5dc",
roughness: 0.72,
flatShading: true
})
);
housing.position.y = 4.18;
housing.castShadow = true;
group.add(housing);
const roof = new THREE.Mesh(
new THREE.ConeGeometry(1.03, 0.85, 4),
new THREE.MeshStandardMaterial({
color: cssColor,
roughness: 0.68,
flatShading: true
})
);
roof.position.y = 5.02;
roof.rotation.y = Math.PI / 4;
roof.castShadow = true;
group.add(roof);
const lampMaterial = new THREE.MeshStandardMaterial({
color: cssColor,
emissive: cssColor,
emissiveIntensity: 1.7,
roughness: 0.25
});
const lamp = new THREE.Mesh(
new THREE.SphereGeometry(0.34, 8, 6),
lampMaterial
);
lamp.position.y = 4.48;
group.add(lamp);
const glow = new THREE.Sprite(
new THREE.SpriteMaterial({
map: glowTexture,
color: cssColor,
transparent: true,
opacity: 0.78,
depthWrite: false,
blending: THREE.AdditiveBlending
})
);
glow.position.y = 4.48;
glow.scale.set(2.8, 2.8, 2.8);
group.add(glow);
const halo = new THREE.Mesh(
new THREE.TorusGeometry(2.65, 0.075, 4, 36),
new THREE.MeshBasicMaterial({
color: cssColor,
transparent: true,
opacity: 0.65,
depthWrite: false
})
);
halo.rotation.x = Math.PI / 2;
halo.position.y = 0.12;
group.add(halo);
const beaconLight = new THREE.PointLight(cssColor, 2.2, 12, 2);
beaconLight.position.y = 4.48;
group.add(beaconLight);
const target = new THREE.Object3D();
target.position.y = 4.48;
group.add(target);
scene.add(group);
const beacon = {
id,
name,
group,
target,
lamp,
glow,
halo,
beaconLight,
color,
cssColor,
phase: id === "A" ? 0 : Math.PI,
visible: undefined,
hitPoint: null
};
beacons.push(beacon);
return beacon;
}
createBeacon("A", "Pine Beacon", -17, 14, "#ffc857");
createBeacon("B", "Ridge Relay", 18, -16, "#59d9ff");
// -------------------------------------------------------------------------
// Locked obstacle world
//
// All obstacle geometry and transforms are created once below. Nothing in
// this group is moved, scaled, or regenerated while the observer searches.
// -------------------------------------------------------------------------
function mulberry32(seed) {
return function random() {
let value = seed += 0x6D2B79F5;
value = Math.imul(value ^ (value >>> 15), value | 1);
value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
};
}
const random = mulberry32(94721);
const obstacleRoot = new THREE.Group();
obstacleRoot.name = "LOCKED_OBSTACLE_GEOMETRY";
scene.add(obstacleRoot);
const obstacleRecords = [];
const trunkGeometry = new THREE.CylinderGeometry(0.18, 0.28, 1.8, 5);
const lowerPineGeometry = new THREE.ConeGeometry(1.35, 3.2, 6);
const upperPineGeometry = new THREE.ConeGeometry(0.98, 2.8, 6);
const rockGeometry = new THREE.DodecahedronGeometry(1, 0);
const trunkMaterial = new THREE.MeshStandardMaterial({
color: "#574638",
roughness: 1,
flatShading: true
});
const pineMaterials = [
new THREE.MeshStandardMaterial({
color: "#294f45",
roughness: 1,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: "#356354",
roughness: 1,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: "#466b58",
roughness: 1,
flatShading: true
})
];
const rockMaterials = [
new THREE.MeshStandardMaterial({
color: "#778078",
roughness: 1,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: "#8a8b7f",
roughness: 1,
flatShading: true
})
];
function nearBeacon(x, z, distance) {
return beacons.some(
(beacon) =>
Math.hypot(
x - beacon.group.position.x,
z - beacon.group.position.z
) < distance
);
}
let treeCount = 0;
for (let attempt = 0; attempt < 700 && treeCount < 42; attempt++) {
const x = lerp(-33, 33, random());
const z = lerp(-33, 33, random());
if (nearBeacon(x, z, 6.2)) continue;
const tooClose = obstacleRecords.some(
(record) => Math.hypot(record.x - x, record.z - z) < 2.35
);
if (tooClose) continue;
const scale = 0.68 + random() * 0.53;
const tree = new THREE.Group();
tree.position.set(x, terrainHeight(x, z), z);
tree.scale.setScalar(scale);
tree.rotation.y = random() * Math.PI * 2;
const trunk = new THREE.Mesh(trunkGeometry, trunkMaterial);
trunk.position.y = 0.9;
trunk.castShadow = true;
trunk.receiveShadow = true;
tree.add(trunk);
const lower = new THREE.Mesh(
lowerPineGeometry,
pineMaterials[treeCount % pineMaterials.length]
);
lower.position.y = 2.25;
lower.rotation.y = random() * Math.PI;
lower.castShadow = true;
lower.receiveShadow = true;
tree.add(lower);
const upper = new THREE.Mesh(
upperPineGeometry,
pineMaterials[(treeCount + 1) % pineMaterials.length]
);
upper.position.y = 3.7;
upper.rotation.y = random() * Math.PI;
upper.castShadow = true;
upper.receiveShadow = true;
tree.add(upper);
obstacleRoot.add(tree);
obstacleRecords.push({
kind: "tree",
x,
z,
radius: 1.35 * scale
});
treeCount++;
}
let rockCount = 0;
for (let attempt = 0; attempt < 500 && rockCount < 16; attempt++) {
const x = lerp(-32, 32, random());
const z = lerp(-32, 32, random());
if (nearBeacon(x, z, 5.8)) continue;
const tooClose = obstacleRecords.some(
(record) => Math.hypot(record.x - x, record.z - z) < 2.1
);
if (tooClose) continue;
const scale = 0.55 + random() * 0.9;
const rock = new THREE.Mesh(
rockGeometry,
rockMaterials[rockCount % rockMaterials.length]
);
rock.position.set(x, terrainHeight(x, z) + scale * 0.46, z);
rock.scale.set(
scale * (0.85 + random() * 0.5),
scale * (0.55 + random() * 0.35),
scale * (0.8 + random() * 0.6)
);
rock.rotation.set(random() * 0.35, random() * Math.PI, random() * 0.25);
rock.castShadow = true;
rock.receiveShadow = true;
obstacleRoot.add(rock);
obstacleRecords.push({
kind: "rock",
x,
z,
radius: scale
});
rockCount++;
}
document.querySelector("#obstacleCount").textContent =
`${treeCount + rockCount} fixed occluders`;
// These exact meshes are used for rendering and raycasting.
const collisionRoots = [terrainMesh, skirtMesh, obstacleRoot];
// -------------------------------------------------------------------------
// Observer
// -------------------------------------------------------------------------
const observer = new THREE.Group();
observer.name = "MOVABLE_OBSERVER";
const observerRingMaterial = new THREE.MeshBasicMaterial({
color: "#ff7184",
transparent: true,
opacity: 0.9,
depthWrite: false
});
const observerRing = new THREE.Mesh(
new THREE.TorusGeometry(0.88, 0.075, 4, 32),
observerRingMaterial
);
observerRing.rotation.x = Math.PI / 2;
observerRing.position.y = 0.11;
observer.add(observerRing);
const observerBody = new THREE.Mesh(
new THREE.CylinderGeometry(0.35, 0.5, 1.02, 6),
new THREE.MeshStandardMaterial({
color: "#f2c84b",
roughness: 0.75,
flatShading: true
})
);
observerBody.position.y = 0.83;
observerBody.castShadow = true;
observer.add(observerBody);
const observerHead = new THREE.Mesh(
new THREE.SphereGeometry(0.3, 8, 6),
new THREE.MeshStandardMaterial({
color: "#f3dfc5",
roughness: 0.9,
flatShading: true
})
);
observerHead.position.y = 1.58;
observerHead.castShadow = true;
observer.add(observerHead);
const observerHat = new THREE.Mesh(
new THREE.ConeGeometry(0.43, 0.32, 7),
new THREE.MeshStandardMaterial({
color: "#e29c2e",
roughness: 0.9,
flatShading: true
})
);
observerHat.position.y = 1.91;
observerHat.castShadow = true;
observer.add(observerHat);
const observerBeacon = new THREE.Mesh(
new THREE.SphereGeometry(0.12, 6, 5),
new THREE.MeshBasicMaterial({ color: "#ffffff" })
);
observerBeacon.position.set(0, 1.9, 0.32);
observer.add(observerBeacon);
scene.add(observer);
// -------------------------------------------------------------------------
// Sightline overlays
// -------------------------------------------------------------------------
for (const beacon of beacons) {
const clearGeometry = new THREE.BufferGeometry();
clearGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(new Float32Array(6), 3)
);
beacon.clearLine = new THREE.Line(
clearGeometry,
new THREE.LineBasicMaterial({
color: beacon.cssColor,
transparent: true,
opacity: 0.92,
depthTest: false,
depthWrite: false,
blending: THREE.AdditiveBlending,
toneMapped: false
})
);
beacon.clearLine.frustumCulled = false;
beacon.clearLine.renderOrder = 20;
scene.add(beacon.clearLine);
const blockedGeometry = new THREE.BufferGeometry();
blockedGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(new Float32Array(6), 3)
);
beacon.blockedLine = new THREE.Line(
blockedGeometry,
new THREE.LineDashedMaterial({
color: "#ff7184",
dashSize: 0.75,
gapSize: 0.48,
transparent: true,
opacity: 0.7,
depthTest: false,
depthWrite: false,
toneMapped: false
})
);
beacon.blockedLine.frustumCulled = false;
beacon.blockedLine.renderOrder = 20;
scene.add(beacon.blockedLine);
beacon.hitMarker = new THREE.Sprite(
new THREE.SpriteMaterial({
map: crossTexture,
color: "#ff7184",
transparent: true,
opacity: 0.95,
depthTest: false,
depthWrite: false
})
);
beacon.hitMarker.scale.set(1.1, 1.1, 1.1);
beacon.hitMarker.visible = false;
beacon.hitMarker.renderOrder = 22;
scene.add(beacon.hitMarker);
}
// -------------------------------------------------------------------------
// UI references and shared state
// -------------------------------------------------------------------------
const ui = {
A: {
card: document.querySelector("#cardA"),
pill: document.querySelector("#pillA"),
status: document.querySelector("#statusA"),
distance: document.querySelector("#distanceA"),
label: document.querySelector("#labelA")
},
B: {
card: document.querySelector("#cardB"),
pill: document.querySelector("#pillB"),
status: document.querySelector("#statusB"),
distance: document.querySelector("#distanceB"),
label: document.querySelector("#labelB")
}
};
const summary = document.querySelector("#summary");
const coordinates = document.querySelector("#coordinates");
const toast = document.querySelector("#toast");
const showLinesInput = document.querySelector("#showLines");
let showLines = true;
let visibilityDirty = true;
let pointerMode = "move";
let toastTimer = 0;
let initialObserver = { x: 0, z: 10 };
const losRaycaster = new THREE.Raycaster();
const pickRaycaster = new THREE.Raycaster();
const pointerNDC = new THREE.Vector2();
const effects = [];
// -------------------------------------------------------------------------
// Visibility calculation
// -------------------------------------------------------------------------
function calculateVisibilityAt(x, z) {
const start = new THREE.Vector3(
x,
terrainHeight(x, z) + observerEyeHeight,
z
);
const results = beacons.map((beacon) => {
const target = beacon.target.getWorldPosition(new THREE.Vector3());
const direction = target.clone().sub(start);
const distance = direction.length();
direction.normalize();
losRaycaster.set(start, direction);
losRaycaster.near = 0.035;
losRaycaster.far = Math.max(0.05, distance - 0.16);
const hits = losRaycaster.intersectObjects(collisionRoots, true);
const hit = hits.length ? hits[0] : null;
return {
visible: !hit,
hitPoint: hit ? hit.point.clone() : null,
distance
};
});
return results;
}
function writeLinePosition(line, start, end) {
const positions = line.geometry.attributes.position.array;
positions[0] = start.x;
positions[1] = start.y;
positions[2] = start.z;
positions[3] = end.x;
positions[4] = end.y;
positions[5] = end.z;
line.geometry.attributes.position.needsUpdate = true;
}
function flashCard(card) {
card.classList.remove("flash");
void card.offsetWidth;
card.classList.add("flash");
}
function showToast(message, tone = "gained") {
window.clearTimeout(toastTimer);
toast.textContent = message;
toast.dataset.tone = tone;
toast.classList.add("show");
toastTimer = window.setTimeout(() => {
toast.classList.remove("show");
}, 2200);
}
function spawnPulse(color) {
const pulse = new THREE.Mesh(
new THREE.RingGeometry(0.5, 0.62, 32),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.9,
side: THREE.DoubleSide,
depthWrite: false
})
);
pulse.rotation.x = -Math.PI / 2;
pulse.position.set(
observer.position.x,
observer.position.y + 0.14,
observer.position.z
);
scene.add(pulse);
effects.push({
mesh: pulse,
born: performance.now()
});
}
function updateVisibility() {
visibilityDirty = false;
const start = observer.position.clone();
start.y += observerEyeHeight;
const gained = [];
const lost = [];
let visibleCount = 0;
for (const beacon of beacons) {
const target = beacon.target.getWorldPosition(new THREE.Vector3());
const direction = target.clone().sub(start);
const distance = direction.length();
direction.normalize();
losRaycaster.set(start, direction);
losRaycaster.near = 0.035;
losRaycaster.far = Math.max(0.05, distance - 0.16);
const hits = losRaycaster.intersectObjects(collisionRoots, true);
const hit = hits.length ? hits[0] : null;
const visible = !hit;
beacon.hitPoint = hit ? hit.point.clone() : null;
if (visible) visibleCount++;
if (beacon.visible !== undefined && beacon.visible !== visible) {
if (visible) {
gained.push(beacon);
spawnPulse("#8df2a7");
} else {
lost.push(beacon);
spawnPulse("#ff7184");
}
flashCard(ui[beacon.id].card);
}
beacon.visible = visible;
const card = ui[beacon.id].card;
card.dataset.state = visible ? "visible" : "blocked";
ui[beacon.id].pill.textContent = visible ? "Clear" : "Blocked";
ui[beacon.id].status.textContent = visible
? "Clear line of sight"
: "Obstacle blocks sightline";
ui[beacon.id].distance.textContent = `${distance.toFixed(1)} m`;
ui[beacon.id].label.dataset.state = visible ? "visible" : "blocked";
writeLinePosition(beacon.clearLine, start, target);
writeLinePosition(beacon.blockedLine, start, target);
beacon.blockedLine.computeLineDistances();
beacon.clearLine.visible = showLines && visible;
beacon.blockedLine.visible = showLines && !visible;
beacon.hitMarker.visible = showLines && !visible;
if (beacon.hitPoint) {
beacon.hitMarker.position.copy(beacon.hitPoint);
}
}
observerRingMaterial.color.set(
visibleCount === 2
? "#8df2a7"
: visibleCount === 1
? "#ffc857"
: "#ff7184"
);
summary.dataset.count = String(visibleCount);
summary.textContent = `${visibleCount} / 2 visible`;
if (gained.length === 2) {
showToast("Both beacons now have a clear line of sight.");
} else if (lost.length === 2) {
showToast("Both sightlines are now obstructed.", "lost");
} else if (gained.length) {
showToast(`${gained[0].name} gained — line of sight is clear.`);
} else if (lost.length) {
showToast(`${lost[0].name} was lost behind terrain or an obstacle.`, "lost");
}
}
// -------------------------------------------------------------------------
// Observer placement
// -------------------------------------------------------------------------
function placeObserver(x, z) {
const half = WORLD_SIZE / 2 - 1.4;
observer.position.set(
clamp(x, -half, half),
terrainHeight(clamp(x, -half, half), clamp(z, -half, half)),
clamp(z, -half, half)
);
coordinates.textContent =
`X ${observer.position.x.toFixed(1)} · ` +
`Z ${observer.position.z.toFixed(1)} · ` +
`${observer.position.y.toFixed(1)} m`;
visibilityDirty = true;
}
// Pick a useful initial observation point without modifying any geometry.
scene.updateMatrixWorld(true);
{
let best = null;
for (let z = -26; z <= 26; z += 4) {
for (let x = -27; x <= 27; x += 4) {
const results = calculateVisibilityAt(x, z);
const count = results.filter((result) => result.visible).length;
const distanceFromPreferred = Math.hypot(x - 0, z - 10);
const score =
(count === 2 ? 1000 : count * 100) -
distanceFromPreferred * 0.45 +
terrainHeight(x, z) * 0.2;
if (!best || score > best.score) {
best = { x, z, score };
}
}
}
initialObserver = { x: best.x, z: best.z };
placeObserver(initialObserver.x, initialObserver.z);
updateVisibility();
}
// -------------------------------------------------------------------------
// Direct camera controls
// -------------------------------------------------------------------------
const orbit = {
theta: 0.58,
phi: 0.82,
radius: 70,
target: new THREE.Vector3(0, 2, 0)
};
function applyCamera() {
const aspectCompensation =
camera.aspect < 0.9 ? 0.9 / camera.aspect : 1;
const radius = orbit.radius * aspectCompensation;
const horizontal = Math.sin(orbit.phi) * radius;
camera.position.set(
orbit.target.x + horizontal * Math.sin(orbit.theta),
orbit.target.y + Math.cos(orbit.phi) * radius,
orbit.target.z + horizontal * Math.cos(orbit.theta)
);
camera.lookAt(orbit.target);
}
function pickTerrain(event) {
const rect = canvas.getBoundingClientRect();
pointerNDC.x =
((event.clientX - rect.left) / rect.width) * 2 - 1;
pointerNDC.y =
-((event.clientY - rect.top) / rect.height) * 2 + 1;
pickRaycaster.setFromCamera(pointerNDC, camera);
const hits = pickRaycaster.intersectObject(terrainMesh, false);
return hits.length ? hits[0] : null;
}
let interaction = null;
canvas.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
canvas.addEventListener("pointerdown", (event) => {
if (event.button === 2 || pointerMode === "orbit") {
interaction = {
type: "orbit",
x: event.clientX,
y: event.clientY
};
canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = "grabbing";
event.preventDefault();
return;
}
if (event.button !== 0) return;
const hit = pickTerrain(event);
if (!hit) return;
interaction = { type: "observer" };
canvas.setPointerCapture(event.pointerId);
placeObserver(hit.point.x, hit.point.z);
event.preventDefault();
});
canvas.addEventListener("pointermove", (event) => {
if (!interaction) return;
if (interaction.type === "orbit") {
const deltaX = event.clientX - interaction.x;
const deltaY = event.clientY - interaction.y;
orbit.theta -= deltaX * 0.006;
orbit.phi = clamp(orbit.phi - deltaY * 0.005, 0.35, 1.35);
interaction.x = event.clientX;
interaction.y = event.clientY;
} else {
const hit = pickTerrain(event);
if (hit) placeObserver(hit.point.x, hit.point.z);
}
event.preventDefault();
});
function endPointerInteraction(event) {
if (!interaction) return;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
interaction = null;
canvas.style.cursor = pointerMode === "move" ? "crosshair" : "grab";
}
canvas.addEventListener("pointerup", endPointerInteraction);
canvas.addEventListener("pointercancel", endPointerInteraction);
canvas.addEventListener(
"wheel",
(event) => {
orbit.radius = clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
29,
105
);
event.preventDefault();
},
{ passive: false }
);
// -------------------------------------------------------------------------
// UI controls and keyboard movement
// -------------------------------------------------------------------------
const moveModeButton = document.querySelector("#moveMode");
const orbitModeButton = document.querySelector("#orbitMode");
const resetButton = document.querySelector("#resetButton");
function setPointerMode(mode) {
pointerMode = mode;
moveModeButton.classList.toggle("active", mode === "move");
orbitModeButton.classList.toggle("active", mode === "orbit");
canvas.style.cursor = mode === "move" ? "crosshair" : "grab";
}
moveModeButton.addEventListener("click", () => setPointerMode("move"));
orbitModeButton.addEventListener("click", () => setPointerMode("orbit"));
resetButton.addEventListener("click", () => {
orbit.theta = 0.58;
orbit.phi = 0.82;
orbit.radius = 70;
orbit.target.set(0, 2, 0);
placeObserver(initialObserver.x, initialObserver.z);
});
showLinesInput.addEventListener("change", () => {
showLines = showLinesInput.checked;
visibilityDirty = true;
});
const heldKeys = new Set();
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLInputElement) return;
const relevant = [
"ArrowUp",
"ArrowDown",
"ArrowLeft",
"ArrowRight",
"w",
"a",
"s",
"d",
"W",
"A",
"S",
"D"
];
if (relevant.includes(event.key)) {
heldKeys.add(event.key);
event.preventDefault();
}
});
window.addEventListener("keyup", (event) => {
heldKeys.delete(event.key);
});
window.addEventListener("blur", () => {
heldKeys.clear();
});
function updateKeyboardMovement(deltaTime) {
let directionX = 0;
let directionZ = 0;
if (
heldKeys.has("ArrowLeft") ||
heldKeys.has("a") ||
heldKeys.has("A")
) {
directionX -= 1;
}
if (
heldKeys.has("ArrowRight") ||
heldKeys.has("d") ||
heldKeys.has("D")
) {
directionX += 1;
}
if (
heldKeys.has("ArrowUp") ||
heldKeys.has("w") ||
heldKeys.has("W")
) {
directionZ -= 1;
}
if (
heldKeys.has("ArrowDown") ||
heldKeys.has("s") ||
heldKeys.has("S")
) {
directionZ += 1;
}
if (!directionX && !directionZ) return;
const length = Math.hypot(directionX, directionZ);
directionX /= length;
directionZ /= length;
const fast = heldKeys.has("Shift");
const speed = (fast ? 15 : 7.5) * deltaTime;
placeObserver(
observer.position.x + directionX * speed,
observer.position.z + directionZ * speed
);
}
// -------------------------------------------------------------------------
// Static minimap base and dynamic observer layer
// -------------------------------------------------------------------------
const mapSize = 240;
const mapMargin = 10;
const mapScale = (mapSize - mapMargin * 2) / WORLD_SIZE;
const mapBase = document.createElement("canvas");
mapBase.width = mapSize;
mapBase.height = mapSize;
const mapBaseContext = mapBase.getContext("2d");
function worldToMap(x, z) {
return {
x: mapMargin + (x + WORLD_SIZE / 2) * mapScale,
y: mapMargin + (z + WORLD_SIZE / 2) * mapScale
};
}
function buildMinimapBase() {
const image = mapBaseContext.createImageData(mapSize, mapSize);
for (let py = 0; py < mapSize; py++) {
for (let px = 0; px < mapSize; px++) {
const x =
((px - mapMargin) / mapScale) - WORLD_SIZE / 2;
const z =
((py - mapMargin) / mapScale) - WORLD_SIZE / 2;
const height = terrainHeight(x, z);
const mix = clamp((height + 4) / 12.5, 0, 1);
const slopeX =
terrainHeight(x + 1, z) - terrainHeight(x - 1, z);
const slopeZ =
terrainHeight(x, z + 1) - terrainHeight(x, z - 1);
const shade = clamp(
0.96 - slopeX * 0.025 - slopeZ * 0.025,
0.72,
1.13
);
const index = (py * mapSize + px) * 4;
image.data[index] = clamp(lerp(74, 181, mix) * shade, 0, 255);
image.data[index + 1] = clamp(lerp(112, 174, mix) * shade, 0, 255);
image.data[index + 2] = clamp(lerp(94, 128, mix) * shade, 0, 255);
image.data[index + 3] = 255;
}
}
mapBaseContext.putImageData(image, 0, 0);
mapBaseContext.strokeStyle = "rgba(235,245,230,.12)";
mapBaseContext.lineWidth = 1;
for (let i = 1; i < 7; i++) {
const p = mapMargin + (i / 7) * (mapSize - mapMargin * 2);
mapBaseContext.beginPath();
mapBaseContext.moveTo(p, mapMargin);
mapBaseContext.lineTo(p, mapSize - mapMargin);
mapBaseContext.stroke();
mapBaseContext.beginPath();
mapBaseContext.moveTo(mapMargin, p);
mapBaseContext.lineTo(mapSize - mapMargin, p);
mapBaseContext.stroke();
}
for (const record of obstacleRecords) {
const point = worldToMap(record.x, record.z);
if (record.kind === "tree") {
mapBaseContext.fillStyle = "rgba(24,63,49,.9)";
mapBaseContext.beginPath();
mapBaseContext.moveTo(point.x, point.y - record.radius * mapScale);
mapBaseContext.lineTo(
point.x + record.radius * mapScale * 0.85,
point.y + record.radius * mapScale
);
mapBaseContext.lineTo(
point.x - record.radius * mapScale * 0.85,
point.y + record.radius * mapScale
);
mapBaseContext.closePath();
mapBaseContext.fill();
} else {
mapBaseContext.fillStyle = "rgba(72,78,69,.8)";
mapBaseContext.beginPath();
mapBaseContext.ellipse(
point.x,
point.y,
record.radius * mapScale,
record.radius * mapScale * 0.7,
0,
0,
Math.PI * 2
);
mapBaseContext.fill();
}
}
for (const beacon of beacons) {
const point = worldToMap(
beacon.group.position.x,
beacon.group.position.z
);
mapBaseContext.save();
mapBaseContext.translate(point.x, point.y);
mapBaseContext.rotate(Math.PI / 4);
mapBaseContext.fillStyle = beacon.cssColor;
mapBaseContext.shadowColor = beacon.cssColor;
mapBaseContext.shadowBlur = 10;
mapBaseContext.fillRect(-4, -4, 8, 8);
mapBaseContext.restore();
}
mapBaseContext.fillStyle = "rgba(235,245,230,.6)";
mapBaseContext.font = "bold 9px system-ui";
mapBaseContext.fillText("N", mapSize - 17, 17);
}
buildMinimapBase();
function drawMinimap(time) {
const context = minimapContext;
context.clearRect(0, 0, mapSize, mapSize);
context.drawImage(mapBase, 0, 0);
const observerPoint = worldToMap(
observer.position.x,
observer.position.z
);
for (const beacon of beacons) {
const beaconPoint = worldToMap(
beacon.group.position.x,
beacon.group.position.z
);
context.save();
context.beginPath();
context.moveTo(observerPoint.x, observerPoint.y);
context.lineTo(beaconPoint.x, beaconPoint.y);
context.strokeStyle = beacon.visible ? beacon.cssColor : "#ff7184";
context.globalAlpha = beacon.visible ? 0.9 : 0.7;
context.lineWidth = beacon.visible ? 2 : 1.4;
context.setLineDash(beacon.visible ? [] : [4, 3]);
context.stroke();
context.restore();
if (!beacon.visible && beacon.hitPoint) {
const hitPoint = worldToMap(
beacon.hitPoint.x,
beacon.hitPoint.z
);
context.fillStyle = "#ff7184";
context.beginPath();
context.arc(hitPoint.x, hitPoint.y, 2.6, 0, Math.PI * 2);
context.fill();
}
}
const pulse = 5.5 + Math.sin(time * 0.004) * 1.2;
context.strokeStyle = observerRingMaterial.color.getStyle();
context.lineWidth = 2;
context.beginPath();
context.arc(
observerPoint.x,
observerPoint.y,
pulse,
0,
Math.PI * 2
);
context.stroke();
context.fillStyle = "#ffffff";
context.beginPath();
context.arc(observerPoint.x, observerPoint.y, 3, 0, Math.PI * 2);
context.fill();
context.fillStyle = "#172a2b";
context.beginPath();
context.arc(observerPoint.x, observerPoint.y, 1.4, 0, Math.PI * 2);
context.fill();
}
let draggingMinimap = false;
function moveFromMinimap(event) {
const rect = minimap.getBoundingClientRect();
const px =
((event.clientX - rect.left) / rect.width) * mapSize;
const py =
((event.clientY - rect.top) / rect.height) * mapSize;
const x =
((px - mapMargin) / mapScale) - WORLD_SIZE / 2;
const z =
((py - mapMargin) / mapScale) - WORLD_SIZE / 2;
placeObserver(x, z);
}
minimap.addEventListener("pointerdown", (event) => {
draggingMinimap = true;
minimap.setPointerCapture(event.pointerId);
moveFromMinimap(event);
event.preventDefault();
});
minimap.addEventListener("pointermove", (event) => {
if (!draggingMinimap) return;
moveFromMinimap(event);
event.preventDefault();
});
function endMinimapDrag(event) {
draggingMinimap = false;
if (minimap.hasPointerCapture(event.pointerId)) {
minimap.releasePointerCapture(event.pointerId);
}
}
minimap.addEventListener("pointerup", endMinimapDrag);
minimap.addEventListener("pointercancel", endMinimapDrag);
// -------------------------------------------------------------------------
// Labels, animation, and resize
// -------------------------------------------------------------------------
const projected = new THREE.Vector3();
function updateWorldLabels() {
for (const beacon of beacons) {
beacon.target.getWorldPosition(projected);
projected.project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.15 &&
Math.abs(projected.y) < 1.15;
const label = ui[beacon.id].label;
label.style.display = visible ? "block" : "none";
if (visible) {
label.style.left =
`${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
label.style.top =
`${(-projected.y * 0.5 + 0.5) * window.innerHeight - 12}px`;
}
}
}
function resize() {
renderer.setSize(window.innerWidth, window.innerHeight, false);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
applyCamera();
}
window.addEventListener("resize", resize);
resize();
let previousTime = performance.now();
let firstFrame = true;
function animate(time) {
requestAnimationFrame(animate);
const deltaTime = Math.min((time - previousTime) / 1000, 0.05);
previousTime = time;
updateKeyboardMovement(deltaTime);
applyCamera();
if (visibilityDirty) updateVisibility();
for (const beacon of beacons) {
const pulse = 0.5 + 0.5 * Math.sin(time * 0.003 + beacon.phase);
beacon.halo.scale.setScalar(1 + pulse * 0.08);
beacon.halo.material.opacity =
(beacon.visible ? 0.42 : 0.17) + pulse * 0.24;
beacon.glow.material.opacity =
(beacon.visible ? 0.58 : 0.28) + pulse * 0.26;
beacon.glow.scale.setScalar(2.55 + pulse * 0.35);
beacon.beaconLight.intensity =
(beacon.visible ? 2.1 : 0.95) + pulse * 0.4;
}
observerRing.scale.setScalar(1 + Math.sin(time * 0.004) * 0.055);
for (let index = effects.length - 1; index >= 0; index--) {
const effect = effects[index];
const age = (time - effect.born) / 1000;
if (age >= 1.1) {
scene.remove(effect.mesh);
effect.mesh.geometry.dispose();
effect.mesh.material.dispose();
effects.splice(index, 1);
continue;
}
effect.mesh.scale.setScalar(1 + age * 5.5);
effect.mesh.material.opacity = Math.max(0, 0.9 * (1 - age / 1.1));
}
updateWorldLabels();
drawMinimap(time);
renderer.render(scene, camera);
if (firstFrame) {
firstFrame = false;
document.querySelector("#loading").classList.add("hidden");
}
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```