Prompt specification
Build or customize the Three.js 3D scene "Place Two Wells for Five Homes" 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: Place Two Wells for Five Homes
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/place-two-wells-for-five-homes-x3578
Scene Description Prompt:
Create a small fictional settlement puzzle with home locations and a service-distance limit. Verify coverage using actual traversable paths rather than circular decoration alone. Build this with Three.js from cdnjs as a low-poly scene in one self-contained HTML file.
Working Three.js Starter (place-two-wells-for-five-homes-x3578):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bramblewick Commons — A Pathfinding Puzzle</title>
<style>
:root {
--ink: #153033;
--panel: rgba(17, 39, 42, 0.94);
--panel-soft: rgba(255, 255, 255, 0.08);
--cream: #fff4d7;
--muted: #b9ccca;
--mint: #78e0bd;
--gold: #ffd166;
--coral: #ff8b91;
--danger: #ff8b91;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #a9c9d2;
color: var(--cream);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas:active {
cursor: grabbing;
}
#panel {
position: fixed;
z-index: 20;
top: 18px;
right: 18px;
width: min(355px, calc(100vw - 36px));
max-height: calc(100vh - 36px);
overflow: auto;
padding: 20px;
border: 1px solid rgba(255, 255, 255, 0.14);
border-radius: 20px;
background: var(--panel);
box-shadow: 0 22px 60px rgba(15, 35, 38, 0.28);
backdrop-filter: blur(14px);
scrollbar-width: thin;
scrollbar-color: #628587 transparent;
}
.eyebrow {
margin-bottom: 5px;
color: var(--mint);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: 31px;
font-weight: 600;
line-height: 1.05;
}
.intro {
margin: 11px 0 16px;
color: var(--muted);
font-size: 13px;
line-height: 1.48;
}
.stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-bottom: 15px;
}
.stat {
padding: 11px 12px;
border: 1px solid rgba(255, 255, 255, 0.09);
border-radius: 13px;
background: rgba(255, 255, 255, 0.055);
}
.stat span {
display: block;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.stat strong {
display: block;
margin-top: 3px;
font-size: 20px;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 14px 0 8px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
#service-slots {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
.slot {
min-height: 54px;
padding: 8px 5px;
border: 1px dashed rgba(255, 255, 255, 0.17);
border-radius: 11px;
color: #779493;
font-size: 10px;
font-weight: 700;
text-align: center;
}
.slot.filled {
border-style: solid;
color: var(--cream);
background: rgba(255, 255, 255, 0.06);
}
.slot-dot {
display: block;
width: 10px;
height: 10px;
margin: 0 auto 6px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 13px currentColor;
}
#home-list {
display: grid;
gap: 6px;
}
.home-row {
display: grid;
grid-template-columns: 12px 1fr auto;
align-items: center;
gap: 9px;
width: 100%;
padding: 9px 10px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
color: var(--cream);
font: inherit;
font-size: 12px;
text-align: left;
cursor: pointer;
transition: background 120ms ease, border-color 120ms ease;
}
.home-row:hover,
.home-row.selected {
border-color: rgba(255, 255, 255, 0.24);
background: rgba(255, 255, 255, 0.09);
}
.home-row .status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #789092;
}
.home-row.covered .status-dot {
background: var(--mint);
box-shadow: 0 0 8px rgba(120, 224, 189, 0.8);
}
.home-row.uncovered .status-dot {
background: var(--danger);
}
.home-row .distance {
color: var(--muted);
font-variant-numeric: tabular-nums;
}
.home-row.covered .distance {
color: var(--mint);
}
.home-row.uncovered .distance {
color: var(--danger);
}
#inspect {
min-height: 47px;
margin-top: 9px;
padding: 10px 11px;
border-radius: 11px;
background: rgba(0, 0, 0, 0.16);
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
#inspect strong {
display: block;
margin-bottom: 2px;
color: var(--cream);
font-size: 12px;
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 7px;
margin-top: 13px;
}
button {
border: 0;
border-radius: 10px;
font: inherit;
font-size: 11px;
font-weight: 800;
cursor: pointer;
}
.actions button {
padding: 10px 6px;
border: 1px solid rgba(255, 255, 255, 0.11);
background: rgba(255, 255, 255, 0.08);
color: var(--cream);
}
.actions button:hover {
background: rgba(255, 255, 255, 0.14);
}
.actions #check {
border-color: transparent;
background: var(--mint);
color: #173633;
}
.actions button:disabled {
opacity: 0.38;
cursor: default;
}
#feedback {
display: none;
margin-top: 12px;
padding: 11px 12px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 12px;
background: rgba(255, 255, 255, 0.06);
font-size: 11px;
line-height: 1.45;
}
#feedback.visible {
display: block;
}
#feedback strong {
display: block;
margin-bottom: 3px;
font-size: 12px;
}
#feedback.success {
border-color: rgba(120, 224, 189, 0.45);
background: rgba(120, 224, 189, 0.12);
color: #d9fff2;
}
#feedback.error {
border-color: rgba(255, 139, 145, 0.42);
background: rgba(255, 139, 145, 0.11);
color: #ffe1e3;
}
.rule-note {
margin: 13px 0 0;
padding-top: 12px;
border-top: 1px solid rgba(255, 255, 255, 0.09);
color: #91aaa9;
font-size: 10px;
line-height: 1.5;
}
.rule-note strong {
color: #c4d8d5;
}
#map-help {
position: fixed;
z-index: 10;
top: 18px;
left: 18px;
max-width: min(420px, calc(100vw - 36px));
padding: 10px 13px;
border: 1px solid rgba(255, 255, 255, 0.22);
border-radius: 12px;
background: rgba(20, 43, 45, 0.79);
box-shadow: 0 10px 30px rgba(15, 35, 38, 0.14);
color: #e6f1e9;
font-size: 11px;
line-height: 1.45;
backdrop-filter: blur(9px);
}
#map-help b {
color: var(--mint);
}
#labels {
position: fixed;
z-index: 5;
inset: 0;
overflow: hidden;
pointer-events: none;
}
.map-label {
position: absolute;
display: none;
min-width: max-content;
padding: 5px 8px;
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: 9px;
background: rgba(24, 45, 45, 0.84);
box-shadow: 0 5px 15px rgba(10, 25, 25, 0.2);
color: #fff7df;
font-size: 10px;
font-weight: 700;
line-height: 1.25;
text-align: center;
transform: translate(-50%, -100%);
white-space: nowrap;
}
.map-label .label-distance {
display: block;
margin-top: 1px;
color: #b7ceca;
font-size: 9px;
font-weight: 600;
}
.map-label.covered {
border-color: rgba(120, 224, 189, 0.72);
}
.map-label.covered .label-distance {
color: var(--mint);
}
.map-label.uncovered {
border-color: rgba(255, 139, 145, 0.72);
}
.map-label.uncovered .label-distance {
color: var(--danger);
}
.service-label {
border-color: rgba(255, 255, 255, 0.35);
font-size: 9px;
letter-spacing: 0.05em;
text-transform: uppercase;
}
#toast {
position: fixed;
z-index: 30;
left: 50%;
bottom: 22px;
max-width: min(460px, calc(100vw - 30px));
padding: 10px 14px;
border: 1px solid rgba(255, 255, 255, 0.18);
border-radius: 12px;
background: rgba(18, 38, 39, 0.91);
color: #fff4d7;
box-shadow: 0 12px 35px rgba(10, 25, 25, 0.25);
font-size: 12px;
opacity: 0;
pointer-events: none;
transform: translate(-50%, 10px);
transition: opacity 160ms ease, transform 160ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 700px) {
#panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 48vh;
padding: 15px;
border-radius: 17px;
}
h1 {
font-size: 25px;
}
#map-help {
top: 10px;
left: 10px;
font-size: 10px;
}
.map-label {
font-size: 9px;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div id="labels"></div>
<div id="map-help">
<b>Bramblewick Commons</b> — drag to orbit, scroll to zoom.
Click a floating diamond to place a service post.
</div>
<aside id="panel">
<div class="eyebrow">A small settlement puzzle</div>
<h1>Light the Common Houses</h1>
<p class="intro">
Place <strong>three public hearths</strong> so every home can reach one
within <strong>16 walking metres</strong>. Only the tan road segments
are traversable.
</p>
<div class="stats">
<div class="stat">
<span>Services placed</span>
<strong id="placed-count">0 / 3</strong>
</div>
<div class="stat">
<span>Homes covered</span>
<strong id="covered-count">0 / 6</strong>
</div>
</div>
<div class="section-title">
<span>Service posts</span>
<span id="placement-note">Choose 3 junctions</span>
</div>
<div id="service-slots">
<div class="slot" id="slot-0"><span class="slot-dot"></span>Empty</div>
<div class="slot" id="slot-1"><span class="slot-dot"></span>Empty</div>
<div class="slot" id="slot-2"><span class="slot-dot"></span>Empty</div>
</div>
<div class="section-title">
<span>Home route status</span>
<span>Nearest service</span>
</div>
<div id="home-list"></div>
<div id="inspect">
<strong>Route inspector</strong>
Click a home to reveal its shortest traversable route.
</div>
<div class="actions">
<button id="check" type="button">Check paths</button>
<button id="undo" type="button" disabled>Undo</button>
<button id="reset" type="button" disabled>Reset</button>
</div>
<div id="feedback" aria-live="polite"></div>
<p class="rule-note">
<strong>How coverage is measured:</strong> a Dijkstra shortest-path search
runs over the 25 walkable road and driveway segments. The dashed circles
are visual guides only and do not determine coverage.
</p>
</aside>
<div id="toast" role="status"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Configuration and graph data
// -------------------------------------------------------------------------
const SERVICE_LIMIT = 16;
const SERVICE_COLORS = [0xffd166, 0x70e0c0, 0xff8b91];
const SERVICE_CSS = ["#ffd166", "#70e0c0", "#ff8b91"];
const ROADS = [
{ id: "r0", name: "Market Cross", x: 0, z: 0 },
{ id: "r1", name: "West Gate", x: -8, z: 0 },
{ id: "r2", name: "Orchard Turn", x:-11, z: 5 },
{ id: "r3", name: "Bell Rise", x: -5, z: 8 },
{ id: "r4", name: "High Cross", x: 2, z: 9 },
{ id: "r5", name: "Ridge Lookout", x: 8, z: 7 },
{ id: "r6", name: "East Gate", x: 10, z: 0 },
{ id: "r7", name: "Reed Bend", x: -3, z: -7 },
{ id: "r8", name: "River Stone", x: 5, z: -6 },
{ id: "r9", name: "South Mill", x: -7, z: -7 },
{ id: "r10", name: "Fern Cross", x: 3, z: 5 },
{ id: "r11", name: "Chalk Lane", x: -2, z: 5 },
{ id: "r12", name: "East Ridge", x: 12, z: 5 }
];
const HOMES = [
{ id: "h0", name: "Cobble Cottage", x:-15, z: 1, color:0xd9826b, driveTo:"r1" },
{ id: "h1", name: "Apple House", x:-14, z: 8, color:0xe5b65f, driveTo:"r2" },
{ id: "h2", name: "Forge Home", x: -6, z: 13, color:0x8ba9a1, driveTo:"r3" },
{ id: "h3", name: "Cloud Cottage", x: 2, z: 15, color:0x7f9fc1, driveTo:"r4" },
{ id: "h4", name: "Sunward House", x: 14, z: 10, color:0xc58fb2, driveTo:"r12" },
{ id: "h5", name: "Reed House", x: 7, z:-11, color:0x8eb77b, driveTo:"r8" }
];
const ROAD_EDGES = [
["r0","r1"], ["r0","r6"], ["r0","r11"], ["r0","r7"],
["r11","r3"], ["r11","r10"], ["r3","r2"], ["r3","r4"],
["r2","r1"], ["r4","r10"], ["r10","r5"], ["r5","r12"],
["r12","r6"], ["r7","r9"], ["r7","r8"], ["r8","r6"],
["r8","r10"], ["r1","r9"]
];
const nodes = [];
const nodeById = new Map();
for (const road of ROADS) {
const node = {
...road,
index: nodes.length,
type: "road"
};
nodes.push(node);
nodeById.set(node.id, node);
}
for (const home of HOMES) {
const node = {
...home,
index: nodes.length,
type: "home"
};
nodes.push(node);
nodeById.set(node.id, node);
}
const edges = [];
const adjacency = nodes.map(() => []);
function addEdge(aId, bId, kind = "road") {
const a = nodeById.get(aId);
const b = nodeById.get(bId);
const weight = Math.hypot(a.x - b.x, a.z - b.z);
const edge = { a: a.index, b: b.index, weight, kind };
edges.push(edge);
adjacency[a.index].push({ to: b.index, weight });
adjacency[b.index].push({ to: a.index, weight });
}
for (const [a, b] of ROAD_EDGES) addEdge(a, b, "road");
for (const home of HOMES) addEdge(home.driveTo, home.id, "drive");
const ROAD_IDS = ROADS.map(n => n.id);
const HOME_IDS = HOMES.map(n => n.id);
// -------------------------------------------------------------------------
// Scene setup
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xa9c9d2);
scene.fog = new THREE.Fog(0xa9c9d2, 40, 72);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.getElementById("scene").appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
120
);
const cameraState = {
radius: 36,
theta: 0.58,
phi: 0.86,
target: new THREE.Vector3(0, 0.7, 0)
};
function updateCamera() {
const s = cameraState;
camera.position.set(
s.target.x + s.radius * Math.sin(s.phi) * Math.sin(s.theta),
s.target.y + s.radius * Math.cos(s.phi),
s.target.z + s.radius * Math.sin(s.phi) * Math.cos(s.theta)
);
camera.lookAt(s.target);
}
updateCamera();
const hemi = new THREE.HemisphereLight(0xe8f5f3, 0x657755, 2.25);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff0cf, 3.0);
sun.position.set(-16, 25, 12);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -25;
sun.shadow.camera.right = 25;
sun.shadow.camera.top = 23;
sun.shadow.camera.bottom = -23;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 60;
sun.shadow.bias = -0.0007;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x9fc7d7, 0.65);
fill.position.set(16, 10, -18);
scene.add(fill);
// Seeded randomness keeps the village stable between reloads.
let randomSeed = 81724;
function random() {
randomSeed = (randomSeed * 1664525 + 1013904223) >>> 0;
return randomSeed / 4294967296;
}
// -------------------------------------------------------------------------
// Low-poly terrain
// -------------------------------------------------------------------------
const terrainGeometry = new THREE.PlaneGeometry(43, 33, 30, 22);
terrainGeometry.rotateX(-Math.PI / 2);
const terrainPositions = terrainGeometry.attributes.position;
const terrainColors = new Float32Array(terrainPositions.count * 3);
const terrainColor = new THREE.Color();
for (let i = 0; i < terrainPositions.count; i++) {
const x = terrainPositions.getX(i);
const z = terrainPositions.getZ(i);
const height = -0.26 + random() * 0.16
+ Math.sin(x * 0.28) * 0.035 + Math.cos(z * 0.31) * 0.025;
terrainPositions.setY(i, height);
const variation = random() * 0.08;
terrainColor.setHSL(0.25 + variation * 0.12, 0.31, 0.48 + variation);
terrainColors[i * 3] = terrainColor.r;
terrainColors[i * 3 + 1] = terrainColor.g;
terrainColors[i * 3 + 2] = terrainColor.b;
}
terrainGeometry.setAttribute(
"color",
new THREE.BufferAttribute(terrainColors, 3)
);
terrainGeometry.computeVertexNormals();
const terrain = new THREE.Mesh(
terrainGeometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 1,
flatShading: true
})
);
terrain.receiveShadow = true;
scene.add(terrain);
const earthBase = new THREE.Mesh(
new THREE.BoxGeometry(43.3, 0.55, 33.3),
new THREE.MeshStandardMaterial({
color: 0x6f6650,
roughness: 1,
flatShading: true
})
);
earthBase.position.y = -0.53;
earthBase.receiveShadow = true;
scene.add(earthBase);
// A decorative pond in an area with no modeled road.
const pondShore = new THREE.Mesh(
new THREE.CircleGeometry(1.8, 18),
new THREE.MeshStandardMaterial({
color: 0x9c9b72,
roughness: 1,
flatShading: true
})
);
pondShore.rotation.x = -Math.PI / 2;
pondShore.position.set(1.5, -0.015, 2.4);
pondShore.receiveShadow = true;
scene.add(pondShore);
const pond = new THREE.Mesh(
new THREE.CircleGeometry(1.5, 18),
new THREE.MeshStandardMaterial({
color: 0x5da8b5,
roughness: 0.42,
metalness: 0.05,
flatShading: true
})
);
pond.rotation.x = -Math.PI / 2;
pond.position.set(1.5, 0.012, 2.4);
scene.add(pond);
// -------------------------------------------------------------------------
// Walkable roads and driveways
// -------------------------------------------------------------------------
const roadMaterial = new THREE.MeshStandardMaterial({
color: 0xc9ad7a,
roughness: 1,
flatShading: true
});
const drivewayMaterial = new THREE.MeshStandardMaterial({
color: 0xb99b6f,
roughness: 1,
flatShading: true
});
function addRoad(edge) {
const a = nodes[edge.a];
const b = nodes[edge.b];
const length = edge.weight;
const width = edge.kind === "drive" ? 0.72 : 1.05;
const road = new THREE.Mesh(
new THREE.BoxGeometry(length, 0.075, width),
edge.kind === "drive" ? drivewayMaterial : roadMaterial
);
road.position.set(
(a.x + b.x) / 2,
0,
(a.z + b.z) / 2
);
road.rotation.y = -Math.atan2(b.z - a.z, b.x - a.x);
road.receiveShadow = true;
scene.add(road);
}
for (const edge of edges) addRoad(edge);
const plazaMaterial = new THREE.MeshStandardMaterial({
color: 0xd4bb88,
roughness: 1,
flatShading: true
});
for (const id of ROAD_IDS) {
const node = nodeById.get(id);
const plaza = new THREE.Mesh(
new THREE.CylinderGeometry(0.56, 0.62, 0.085, 8),
plazaMaterial
);
plaza.position.set(node.x, 0.025, node.z);
plaza.receiveShadow = true;
scene.add(plaza);
}
// -------------------------------------------------------------------------
// Candidate service posts
// -------------------------------------------------------------------------
const pickables = [];
const markerById = new Map();
const candidateMaterial = new THREE.MeshStandardMaterial({
color: 0x79aaa7,
emissive: 0x173f3d,
emissiveIntensity: 0.55,
roughness: 0.4,
flatShading: true
});
const markerWoodMaterial = new THREE.MeshStandardMaterial({
color: 0x75543a,
roughness: 1,
flatShading: true
});
const invisiblePickMaterial = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
colorWrite: false
});
for (const id of ROAD_IDS) {
const node = nodeById.get(id);
const group = new THREE.Group();
group.position.set(node.x, 0, node.z);
const base = new THREE.Mesh(
new THREE.CylinderGeometry(0.36, 0.44, 0.18, 7),
markerWoodMaterial
);
base.position.y = 0.11;
base.castShadow = true;
group.add(base);
const pole = new THREE.Mesh(
new THREE.CylinderGeometry(0.07, 0.09, 0.9, 6),
markerWoodMaterial
);
pole.position.y = 0.58;
pole.castShadow = true;
group.add(pole);
const crystal = new THREE.Mesh(
new THREE.OctahedronGeometry(0.29, 0),
candidateMaterial.clone()
);
crystal.position.y = 1.2;
crystal.castShadow = true;
group.add(crystal);
const halo = new THREE.Mesh(
new THREE.RingGeometry(0.43, 0.53, 24),
new THREE.MeshBasicMaterial({
color: 0x70e0c0,
transparent: true,
opacity: 0.6,
side: THREE.DoubleSide,
depthWrite: false
})
);
halo.rotation.x = -Math.PI / 2;
halo.position.y = 0.075;
halo.visible = false;
group.add(halo);
const pickSphere = new THREE.Mesh(
new THREE.SphereGeometry(0.75, 10, 8),
invisiblePickMaterial
);
pickSphere.position.y = 0.9;
pickSphere.userData = { kind: "service", id };
group.add(pickSphere);
pickables.push(pickSphere);
scene.add(group);
markerById.set(id, {
group,
crystal,
halo,
baseY: crystal.position.y
});
}
// -------------------------------------------------------------------------
// Homes
// -------------------------------------------------------------------------
const homeVisuals = new Map();
for (const home of HOMES) {
const group = new THREE.Group();
group.position.set(home.x, 0, home.z);
const foundation = new THREE.Mesh(
new THREE.BoxGeometry(2.55, 0.28, 2.35),
new THREE.MeshStandardMaterial({
color: 0x777568,
roughness: 1,
flatShading: true
})
);
foundation.position.y = 0.04;
foundation.castShadow = true;
foundation.receiveShadow = true;
group.add(foundation);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: home.color,
roughness: 0.86,
flatShading: true,
emissive: 0x000000,
emissiveIntensity: 0
});
const body = new THREE.Mesh(
new THREE.BoxGeometry(2.35, 1.7, 2.05),
bodyMaterial
);
body.position.y = 0.98;
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const roof = new THREE.Mesh(
new THREE.ConeGeometry(1.83, 1.2, 4),
new THREE.MeshStandardMaterial({
color: 0x7e4f43,
roughness: 1,
flatShading: true
})
);
roof.position.y = 2.35;
roof.rotation.y = Math.PI / 4;
roof.scale.z = 0.94;
roof.castShadow = true;
group.add(roof);
const door = new THREE.Mesh(
new THREE.BoxGeometry(0.46, 0.85, 0.08),
new THREE.MeshStandardMaterial({
color: 0x5c493a,
roughness: 1
})
);
door.position.set(0, 0.55, 1.065);
group.add(door);
const windowMaterial = new THREE.MeshStandardMaterial({
color: 0xffe6a3,
emissive: 0x8e5a15,
emissiveIntensity: 0.22,
roughness: 0.5
});
for (const x of [-0.72, 0.72]) {
const windowMesh = new THREE.Mesh(
new THREE.BoxGeometry(0.38, 0.38, 0.06),
windowMaterial
);
windowMesh.position.set(x, 1.14, 1.065);
group.add(windowMesh);
}
const chimney = new THREE.Mesh(
new THREE.BoxGeometry(0.3, 0.9, 0.3),
new THREE.MeshStandardMaterial({
color: 0x806457,
roughness: 1,
flatShading: true
})
);
chimney.position.set(0.63, 2.75, -0.2);
chimney.castShadow = true;
group.add(chimney);
const pickBox = new THREE.Mesh(
new THREE.BoxGeometry(2.8, 3.6, 2.6),
invisiblePickMaterial
);
pickBox.position.y = 1.6;
pickBox.userData = { kind: "home", id: home.id };
group.add(pickBox);
pickables.push(pickBox);
scene.add(group);
homeVisuals.set(home.id, { group, bodyMaterial, roof });
}
// -------------------------------------------------------------------------
// Trees, rocks, and hills
// -------------------------------------------------------------------------
const trunkMaterial = new THREE.MeshStandardMaterial({
color: 0x79573d,
roughness: 1,
flatShading: true
});
const foliageMaterials = [
new THREE.MeshStandardMaterial({
color: 0x4f805d, roughness: 1, flatShading: true
}),
new THREE.MeshStandardMaterial({
color: 0x6c9464, roughness: 1, flatShading: true
}),
new THREE.MeshStandardMaterial({
color: 0x3e705b, roughness: 1, flatShading: true
})
];
function addTree(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, -0.08, z);
group.scale.setScalar(scale);
group.rotation.y = random() * Math.PI;
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.13, 0.18, 1.2, 6),
trunkMaterial
);
trunk.position.y = 0.55;
trunk.castShadow = true;
group.add(trunk);
const foliage = new THREE.Mesh(
new THREE.ConeGeometry(0.72, 1.8, 6),
foliageMaterials[Math.floor(random() * foliageMaterials.length)]
);
foliage.position.y = 1.65;
foliage.castShadow = true;
group.add(foliage);
const top = new THREE.Mesh(
new THREE.ConeGeometry(0.5, 1.25, 6),
foliage.material
);
top.position.y = 2.45;
top.castShadow = true;
group.add(top);
scene.add(group);
}
const treeLocations = [
[-18,-5,1.05], [-18,6,0.9], [-17,13,0.85], [-10,-14,1.0],
[-1,-14,0.9], [1,-15,0.8], [13,-14,1.0], [17,-9,0.95],
[17,3,0.85], [17,15,1.1], [9,14,0.85], [5,14,0.8],
[-3,15,0.75], [-16,-12,0.8], [10,-10,0.75], [-12,-11,0.7]
];
for (const [x, z, scale] of treeLocations) addTree(x, z, scale);
const rockMaterial = new THREE.MeshStandardMaterial({
color: 0x8b9182,
roughness: 1,
flatShading: true
});
for (const [x, z, size] of [
[-16,-2,0.45], [15,-4,0.55], [15,5,0.36], [-5,-13,0.35],
[8,12,0.34], [-18,10,0.4], [6,-13,0.3]
]) {
const rock = new THREE.Mesh(
new THREE.DodecahedronGeometry(size, 0),
rockMaterial
);
rock.position.set(x, size * 0.5 - 0.1, z);
rock.rotation.set(random(), random(), random());
rock.castShadow = true;
scene.add(rock);
}
for (const [x, z, sx, sz] of [
[-19,10,1.0,0.8], [19,-10,1.1,0.8], [12,16,0.9,0.6]
]) {
const hill = new THREE.Mesh(
new THREE.DodecahedronGeometry(2.7, 0),
new THREE.MeshStandardMaterial({
color: 0x78926d,
roughness: 1,
flatShading: true
})
);
hill.position.set(x, -0.25, z);
hill.scale.set(sx, 0.48, sz);
hill.castShadow = true;
hill.receiveShadow = true;
scene.add(hill);
}
// -------------------------------------------------------------------------
// Route graphics and service guide rings
// -------------------------------------------------------------------------
const routeGroup = new THREE.Group();
const guideGroup = new THREE.Group();
scene.add(routeGroup, guideGroup);
function clearGroup(group) {
for (let i = group.children.length - 1; i >= 0; i--) {
const child = group.children[i];
group.remove(child);
child.geometry?.dispose();
if (child.material) {
if (Array.isArray(child.material)) {
child.material.forEach(m => m.dispose());
} else {
child.material.dispose();
}
}
}
}
function createGuideRing(nodeId, color) {
const node = nodeById.get(nodeId);
const points = [];
const segments = 128;
for (let i = 0; i < segments; i++) {
const angle = i / segments * Math.PI * 2;
points.push(new THREE.Vector3(
node.x + Math.cos(angle) * SERVICE_LIMIT,
0.13,
node.z + Math.sin(angle) * SERVICE_LIMIT
));
}
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineDashedMaterial({
color,
transparent: true,
opacity: 0.33,
dashSize: 0.65,
gapSize: 0.48,
depthWrite: false
});
const ring = new THREE.LineLoop(geometry, material);
ring.computeLineDistances();
guideGroup.add(ring);
}
// -------------------------------------------------------------------------
// Graph pathfinding
// -------------------------------------------------------------------------
function dijkstra(sourceId) {
const source = nodeById.get(sourceId).index;
const distance = Array(nodes.length).fill(Infinity);
const previous = Array(nodes.length).fill(-1);
const visited = Array(nodes.length).fill(false);
distance[source] = 0;
for (let iteration = 0; iteration < nodes.length; iteration++) {
let current = -1;
let currentDistance = Infinity;
for (let i = 0; i < nodes.length; i++) {
if (!visited[i] && distance[i] < currentDistance) {
current = i;
currentDistance = distance[i];
}
}
if (current === -1) break;
visited[current] = true;
for (const neighbor of adjacency[current]) {
const candidate = distance[current] + neighbor.weight;
if (candidate < distance[neighbor.to]) {
distance[neighbor.to] = candidate;
previous[neighbor.to] = current;
}
}
}
return { source, distance, previous };
}
function reconstructPath(run, targetId) {
if (!run) return [];
const target = nodeById.get(targetId).index;
const path = [target];
let current = target;
while (current !== run.source) {
current = run.previous[current];
if (current < 0) return [];
path.unshift(current);
}
return path;
}
// -------------------------------------------------------------------------
// Game state and interface
// -------------------------------------------------------------------------
const selectedServices = [];
let inspectedHome = null;
let currentEvaluation = null;
let toastTimer = null;
const labelsRoot = document.getElementById("labels");
const homeLabelElements = new Map();
const serviceLabelElements = new Map();
const homeRowElements = new Map();
function makeHomeLabel(home) {
const element = document.createElement("div");
element.className = "map-label";
const name = document.createElement("span");
name.textContent = home.name;
const distance = document.createElement("span");
distance.className = "label-distance";
distance.textContent = "No service yet";
element.append(name, distance);
labelsRoot.appendChild(element);
homeLabelElements.set(home.id, { element, distance });
}
for (const home of HOMES) makeHomeLabel(home);
for (const home of HOMES) {
const row = document.createElement("button");
row.type = "button";
row.className = "home-row";
row.innerHTML = `
<span class="status-dot"></span>
<span class="home-name"></span>
<span class="distance">—</span>
`;
row.querySelector(".home-name").textContent = home.name;
row.addEventListener("click", () => {
inspectedHome = inspectedHome === home.id ? null : home.id;
updateUI(currentEvaluation ?? evaluateCoverage());
updateRouteGraphics(currentEvaluation ?? evaluateCoverage());
});
document.getElementById("home-list").appendChild(row);
homeRowElements.set(home.id, row);
}
function evaluateCoverage() {
const runs = selectedServices.map(id => ({
serviceId: id,
...dijkstra(id)
}));
const homes = HOME_IDS.map(homeId => {
let best = null;
for (const run of runs) {
const distance = run.distance[nodeById.get(homeId).index];
if (!best || distance < best.distance) {
best = {
distance,
serviceId: run.serviceId,
run
};
}
}
if (!best) {
best = {
distance: Infinity,
serviceId: null,
run: null
};
}
return {
id: homeId,
best,
covered: best.distance <= SERVICE_LIMIT
};
});
return { runs, homes };
}
function updateUI(evaluation) {
const covered = evaluation.homes.filter(h => h.covered).length;
const placed = selectedServices.length;
document.getElementById("placed-count").textContent = `${placed} / 3`;
document.getElementById("covered-count").textContent = `${covered} / ${HOME_IDS.length}`;
document.getElementById("placement-note").textContent = placed < 3
? `Choose ${3 - placed} more`
: "Ready to check";
for (let i = 0; i < 3; i++) {
const slot = document.getElementById(`slot-${i}`);
const filled = i < placed;
slot.classList.toggle("filled", filled);
slot.style.color = filled ? SERVICE_CSS[i] : "";
slot.innerHTML = filled
? `<span class="slot-dot"></span>Service ${i + 1}`
: `<span class="slot-dot"></span>Empty`;
}
for (const homeState of evaluation.homes) {
const row = homeRowElements.get(homeState.id);
const label = homeLabelElements.get(homeState.id);
row.classList.remove("covered", "uncovered", "selected");
label.element.classList.remove("covered", "uncovered");
const distanceText = Number.isFinite(homeState.best.distance)
? `${homeState.best.distance.toFixed(1)} m`
: "—";
row.querySelector(".distance").textContent = distanceText;
label.distance.textContent = distanceText;
if (placed > 0) {
if (homeState.covered) {
row.classList.add("covered");
label.element.classList.add("covered");
} else {
row.classList.add("uncovered");
label.element.classList.add("uncovered");
}
}
if (inspectedHome === homeState.id) row.classList.add("selected");
}
const inspect = document.getElementById("inspect");
if (!inspectedHome) {
inspect.innerHTML = `
<strong>Route inspector</strong>
Click a home to reveal its shortest traversable route.
`;
} else {
const home = nodeById.get(inspectedHome);
const homeState = evaluation.homes.find(h => h.id === inspectedHome);
if (!homeState.best.run) {
inspect.innerHTML = `
<strong>${home.name}</strong>
Place a service post to calculate a route.
`;
} else {
const path = reconstructPath(homeState.best.run, inspectedHome);
const pathNames = path.map(index => nodes[index].name).join(" → ");
const serviceName = nodeById.get(homeState.best.serviceId).name;
inspect.innerHTML = `
<strong>${home.name}</strong>
${homeState.best.distance.toFixed(1)} m to ${serviceName}.<br>
${pathNames}
`;
}
}
document.getElementById("undo").disabled = placed === 0;
document.getElementById("reset").disabled = placed === 0;
}
function updateRouteGraphics(evaluation) {
clearGroup(routeGroup);
const positions = [];
const colors = [];
for (const homeState of evaluation.homes) {
if (!homeState.best.run) continue;
const path = reconstructPath(homeState.best.run, homeState.id);
const serviceIndex = selectedServices.indexOf(homeState.best.serviceId);
const color = new THREE.Color(
homeState.covered ? SERVICE_COLORS[serviceIndex] : 0xe45c61
);
for (let i = 0; i < path.length - 1; i++) {
const a = nodes[path[i]];
const b = nodes[path[i + 1]];
positions.push(a.x, 0.16, a.z, b.x, 0.16, b.z);
colors.push(color.r, color.g, color.b, color.r, color.g, color.b);
}
}
if (positions.length) {
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(colors, 3)
);
const material = new THREE.LineBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0.82,
depthWrite: false
});
routeGroup.add(new THREE.LineSegments(geometry, material));
}
if (inspectedHome) {
const state = evaluation.homes.find(h => h.id === inspectedHome);
if (state?.best.run) {
const path = reconstructPath(state.best.run, inspectedHome);
const points = path.map(index => {
const node = nodes[index];
return new THREE.Vector3(node.x, 0.23, node.z);
});
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.95,
depthWrite: false
});
routeGroup.add(new THREE.Line(geometry, material));
}
}
}
function syncServiceVisuals() {
for (const id of ROAD_IDS) {
const marker = markerById.get(id);
const selectedIndex = selectedServices.indexOf(id);
if (selectedIndex >= 0) {
marker.crystal.material.color.setHex(SERVICE_COLORS[selectedIndex]);
marker.crystal.material.emissive.setHex(SERVICE_COLORS[selectedIndex]);
marker.crystal.material.emissiveIntensity = 0.48;
marker.halo.visible = true;
marker.halo.material.color.setHex(SERVICE_COLORS[selectedIndex]);
marker.group.scale.setScalar(1.08);
} else {
marker.crystal.material.color.setHex(0x79aaa7);
marker.crystal.material.emissive.setHex(0x173f3d);
marker.crystal.material.emissiveIntensity = 0.55;
marker.halo.visible = false;
marker.group.scale.setScalar(1);
}
}
clearGroup(guideGroup);
selectedServices.forEach((id, index) => {
createGuideRing(id, SERVICE_COLORS[index]);
});
for (const [id, element] of serviceLabelElements) {
if (!selectedServices.includes(id)) {
element.remove();
serviceLabelElements.delete(id);
}
}
selectedServices.forEach((id, index) => {
let element = serviceLabelElements.get(id);
if (!element) {
element = document.createElement("div");
element.className = "map-label service-label";
element.textContent = `Service ${index + 1}`;
labelsRoot.appendChild(element);
serviceLabelElements.set(id, element);
}
element.textContent = `Service ${index + 1}`;
element.style.borderColor = SERVICE_CSS[index];
element.style.color = SERVICE_CSS[index];
});
}
function refresh() {
currentEvaluation = evaluateCoverage();
updateUI(currentEvaluation);
updateRouteGraphics(currentEvaluation);
syncServiceVisuals();
}
function clearFeedback() {
const feedback = document.getElementById("feedback");
feedback.className = "";
feedback.innerHTML = "";
}
function setFeedback(type, title, message) {
const feedback = document.getElementById("feedback");
feedback.className = `visible ${type}`;
feedback.innerHTML = `<strong>${title}</strong>${message}`;
}
function showToast(message) {
const toast = document.getElementById("toast");
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 2400);
}
// -------------------------------------------------------------------------
// Picking and direct camera controls
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function pickAt(clientX, clientY) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(pickables, false);
return hits.length ? hits[0].object.userData : null;
}
const pointerState = {
active: false,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0,
moved: false
};
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
pointerState.active = true;
pointerState.startX = event.clientX;
pointerState.startY = event.clientY;
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
pointerState.moved = false;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!pointerState.active) return;
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
const totalDistance = Math.hypot(
event.clientX - pointerState.startX,
event.clientY - pointerState.startY
);
if (totalDistance > 5) pointerState.moved = true;
if (pointerState.moved) {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi + dy * 0.005,
0.38,
1.34
);
}
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
});
renderer.domElement.addEventListener("pointerup", event => {
if (!pointerState.active) return;
const wasClick = !pointerState.moved;
pointerState.active = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
if (!wasClick) return;
const hit = pickAt(event.clientX, event.clientY);
if (!hit) return;
if (hit.kind === "service") {
const existingIndex = selectedServices.indexOf(hit.id);
if (existingIndex >= 0) {
selectedServices.splice(existingIndex, 1);
showToast("Service post removed.");
} else if (selectedServices.length >= 3) {
showToast("All three service posts are placed. Remove one first.");
return;
} else {
selectedServices.push(hit.id);
const node = nodeById.get(hit.id);
showToast(`Service placed at ${node.name}.`);
}
clearFeedback();
refresh();
}
if (hit.kind === "home") {
inspectedHome = inspectedHome === hit.id ? null : hit.id;
refresh();
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerState.active = false;
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
20,
56
);
}, { passive: false });
renderer.domElement.addEventListener("contextmenu", event => {
event.preventDefault();
});
// -------------------------------------------------------------------------
// Buttons and keyboard shortcuts
// -------------------------------------------------------------------------
document.getElementById("check").addEventListener("click", () => {
const evaluation = evaluateCoverage();
currentEvaluation = evaluation;
updateUI(evaluation);
updateRouteGraphics(evaluation);
if (selectedServices.length !== 3) {
setFeedback(
"error",
"The placement is incomplete",
`Place ${3 - selectedServices.length} more service post(s) before checking the village.`
);
return;
}
const uncovered = evaluation.homes.filter(home => !home.covered);
if (uncovered.length === 0) {
setFeedback(
"success",
"Every home is connected",
"All six homes can reach a public hearth within 16 walking metres. Bramblewick is safe and bright."
);
showToast("All homes covered! Bramblewick is connected.");
} else {
const details = uncovered
.map(home => {
const name = nodeById.get(home.id).name;
const distance = home.best.distance.toFixed(1);
return `${name} (${distance} m)`;
})
.join(", ");
setFeedback(
"error",
`${uncovered.length} home${uncovered.length === 1 ? " is" : "s are"} out of reach`,
`Shortest routes still exceed the limit for: ${details}.`
);
}
});
document.getElementById("undo").addEventListener("click", () => {
if (!selectedServices.length) return;
selectedServices.pop();
clearFeedback();
refresh();
showToast("Last service post removed.");
});
document.getElementById("reset").addEventListener("click", () => {
selectedServices.length = 0;
inspectedHome = null;
clearFeedback();
refresh();
showToast("Puzzle reset.");
});
window.addEventListener("keydown", event => {
if (event.key === "Enter") {
document.getElementById("check").click();
} else if (event.key.toLowerCase() === "u") {
document.getElementById("undo").click();
} else if (event.key.toLowerCase() === "r") {
document.getElementById("reset").click();
} else if (event.key === "Escape") {
inspectedHome = null;
refresh();
}
});
// -------------------------------------------------------------------------
// Screen-space labels and animation
// -------------------------------------------------------------------------
const projected = new THREE.Vector3();
function positionLabel(element, x, y, z, height) {
projected.set(x, height, z).project(camera);
const visible = projected.z > -1 && projected.z < 1;
element.style.display = visible ? "block" : "none";
if (!visible) return;
const screenX = (projected.x * 0.5 + 0.5) * window.innerWidth;
const screenY = (-projected.y * 0.5 + 0.5) * window.innerHeight;
element.style.left = `${screenX}px`;
element.style.top = `${screenY}px`;
}
function animate(time) {
for (const [id, marker] of markerById) {
marker.crystal.rotation.y = time * 0.0011;
marker.crystal.rotation.x = Math.sin(time * 0.0015 + id.length) * 0.12;
marker.crystal.position.y = marker.baseY + Math.sin(time * 0.002 + id.length) * 0.07;
if (marker.halo.visible) {
const pulse = 1 + Math.sin(time * 0.003) * 0.08;
marker.halo.scale.setScalar(pulse);
marker.halo.material.opacity = 0.48 + Math.sin(time * 0.003) * 0.14;
}
}
updateCamera();
for (const home of HOMES) {
const label = homeLabelElements.get(home.id);
positionLabel(label.element, home.x, home.z, 0, 3.55);
}
for (const [id, element] of serviceLabelElements) {
const node = nodeById.get(id);
positionLabel(element, node.x, node.z, 0, 2.25);
}
renderer.render(scene, camera);
}
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", resize);
refresh();
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```