Prompt specification
Build or customize the Three.js 3D scene "Node-and-edge neighborhood graph" 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: Node-and-edge neighborhood graph
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/node-and-edge-neighborhood-graph-x1885
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring a low-poly neighborhood graph on a tabletop. Place six small building-like nodes at irregular positions and connect selected pairs with raised paths. Include two nodes that are close together but have no direct edge, and a more distant pair that does have one. Clicking a node highlights only its actual neighbors. Let a small traveler follow a selected valid route, stopping when no connection exists rather than crossing the empty gap. Use different node shapes and a neutral base so topology stays clear. The arrangement should make geometric proximity and graph adjacency visibly different without relying on a long explanation.
Working Three.js Starter (node-and-edge-neighborhood-graph-x1885):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Neighborhood Topology</title>
<style>
:root {
color-scheme: light;
--ink: #292b29;
--muted: #70736d;
--panel: rgba(248, 246, 240, 0.92);
--line: rgba(48, 51, 47, 0.14);
--amber: #d78b2d;
--teal: #258d89;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e8e4dc;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.panel {
position: fixed;
z-index: 5;
top: 22px;
left: 22px;
width: min(340px, calc(100vw - 44px));
padding: 20px;
border: 1px solid rgba(255, 255, 255, 0.72);
border-radius: 18px;
background: var(--panel);
box-shadow:
0 18px 50px rgba(57, 54, 47, 0.13),
inset 0 0 0 1px rgba(40, 43, 39, 0.04);
backdrop-filter: blur(14px);
user-select: none;
}
.eyebrow {
margin-bottom: 7px;
color: var(--teal);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 28px;
line-height: 1.05;
letter-spacing: -0.045em;
}
.subtitle {
margin: 10px 0 17px;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.field-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
label {
display: block;
margin-bottom: 6px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
select {
width: 100%;
height: 38px;
padding: 0 30px 0 10px;
border: 1px solid var(--line);
border-radius: 9px;
outline: none;
background: rgba(255, 255, 255, 0.72);
color: var(--ink);
font: inherit;
font-size: 13px;
font-weight: 650;
}
button {
border: 0;
border-radius: 9px;
cursor: pointer;
font: inherit;
font-weight: 750;
transition: transform 120ms ease, background 120ms ease;
}
button:hover { transform: translateY(-1px); }
button:active { transform: translateY(0); }
#send {
width: 100%;
height: 40px;
margin-top: 10px;
background: var(--ink);
color: white;
}
.presets {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin-top: 9px;
}
.presets button {
min-height: 48px;
padding: 7px 5px;
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.58);
color: #444742;
font-size: 10px;
line-height: 1.25;
}
.presets strong {
display: block;
margin-bottom: 2px;
color: var(--ink);
font-size: 12px;
}
.divider {
height: 1px;
margin: 17px 0 13px;
background: var(--line);
}
.status {
min-height: 39px;
margin: 10px 0 0;
color: #50534e;
font-size: 12px;
line-height: 1.45;
}
#inspection {
margin-top: 5px;
color: var(--muted);
font-size: 11px;
line-height: 1.4;
}
.route {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 5px;
min-height: 25px;
margin-top: 10px;
}
.node-pill {
display: inline-flex;
align-items: center;
justify-content: center;
width: 25px;
height: 25px;
border-radius: 50%;
background: var(--teal);
color: white;
font-size: 11px;
font-weight: 850;
box-shadow: 0 3px 9px rgba(37, 141, 137, 0.2);
}
.node-pill.stop {
background: #bd604f;
box-shadow: 0 3px 9px rgba(189, 96, 79, 0.2);
}
.arrow {
color: #91958e;
font-size: 13px;
font-weight: 800;
}
.legend {
display: grid;
gap: 7px;
margin-top: 13px;
color: var(--muted);
font-size: 10px;
}
.legend-row {
display: flex;
align-items: center;
gap: 8px;
}
.swatch {
width: 18px;
height: 5px;
border-radius: 99px;
}
.swatch.amber { background: var(--amber); }
.swatch.teal { background: var(--teal); }
.gap-icon {
position: relative;
width: 18px;
height: 5px;
}
.gap-icon::before,
.gap-icon::after {
position: absolute;
top: 0;
width: 6px;
height: 5px;
border-radius: 99px;
background: #a5a49e;
content: "";
}
.gap-icon::before { left: 0; }
.gap-icon::after { right: 0; }
.footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-top: 15px;
color: #858881;
font-size: 10px;
}
#reset {
padding: 6px 9px;
border: 1px solid var(--line);
background: transparent;
color: #656861;
font-size: 10px;
}
.hint {
position: fixed;
z-index: 4;
right: 22px;
bottom: 20px;
padding: 9px 12px;
border: 1px solid rgba(255, 255, 255, 0.62);
border-radius: 999px;
background: rgba(248, 246, 240, 0.76);
color: #777a74;
font-size: 10px;
letter-spacing: 0.03em;
backdrop-filter: blur(10px);
pointer-events: none;
}
@media (max-width: 680px) {
.panel {
top: 12px;
left: 12px;
width: min(320px, calc(100vw - 24px));
padding: 15px;
}
h1 { font-size: 23px; }
.subtitle { margin-bottom: 12px; }
.divider { margin: 13px 0 10px; }
.hint { display: none; }
}
</style>
</head>
<body>
<div class="panel">
<div class="eyebrow">Graph / Spatial Study</div>
<h1>Neighborhood<br>Topology</h1>
<p class="subtitle">
Six forms. Four links. Close buildings are not always connected.
</p>
<div class="field-row">
<div>
<label for="start">Start</label>
<select id="start"></select>
</div>
<div>
<label for="destination">Destination</label>
<select id="destination"></select>
</div>
</div>
<button id="send">Send traveler</button>
<div class="presets">
<button data-preset="near"><strong>A → B</strong>near, no edge</button>
<button data-preset="far"><strong>C → D</strong>far, direct edge</button>
<button data-preset="gap"><strong>F → E</strong>stop at gap</button>
</div>
<div class="divider"></div>
<div id="status" class="status" aria-live="polite">
Choose a route or use a preset.
</div>
<div id="inspection">
Click a building to reveal its direct neighbors.
</div>
<div id="route" class="route"></div>
<div class="legend">
<div class="legend-row">
<span class="swatch amber"></span>
<span>Direct graph neighbors only</span>
</div>
<div class="legend-row">
<span class="swatch teal"></span>
<span>Traveler's selected route</span>
</div>
<div class="legend-row">
<span class="gap-icon"></span>
<span>Empty space without a connection</span>
</div>
</div>
<div class="footer">
<span>Drag to orbit · scroll to zoom</span>
<button id="reset">Reset view</button>
</div>
</div>
<div class="hint">Click a building to inspect adjacency</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene and renderer
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe8e4dc);
scene.fog = new THREE.Fog(0xe8e4dc, 18, 32);
const camera = new THREE.PerspectiveCamera(
42,
innerWidth / innerHeight,
0.1,
60
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
document.body.prepend(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xfffbef, 0x8d938a, 2.0));
const sun = new THREE.DirectionalLight(0xfff7e9, 3.2);
sun.position.set(-5, 11, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -9;
sun.shadow.camera.right = 9;
sun.shadow.camera.top = 8;
sun.shadow.camera.bottom = -8;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 30;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xd9e9ef, 0.8);
fill.position.set(8, 5, -8);
scene.add(fill);
// -------------------------------------------------------------------------
// Graph definition
// -------------------------------------------------------------------------
const nodeDefs = [
{ id: "A", shape: "house", x: -4.80, z: -2.45, color: 0xb86f55 },
{ id: "B", shape: "tower", x: -2.90, z: -1.35, color: 0x617f83 },
{ id: "C", shape: "steps", x: 0.25, z: 0.15, color: 0xc29a4b },
{ id: "D", shape: "wedge", x: 3.75, z: 2.55, color: 0x6d735f },
{ id: "E", shape: "dome", x: 4.75, z: -2.15, color: 0x8c7184 },
{ id: "F", shape: "twin", x: -0.65, z: 3.45, color: 0x638c78 }
];
// A and B are close but have no direct edge.
// C and D are farther apart but do have a direct edge.
// E is isolated, making the stop-before-gap behavior visible.
const edgeDefs = [
["A", "C"],
["B", "C"],
["C", "D"],
["D", "F"]
];
const nodes = new Map(nodeDefs.map(node => [node.id, node]));
const adjacency = Object.fromEntries(nodeDefs.map(node => [node.id, []]));
for (const [a, b] of edgeDefs) {
adjacency[a].push(b);
adjacency[b].push(a);
}
const edgeKey = (a, b) => [a, b].sort().join("-");
// -------------------------------------------------------------------------
// Neutral tabletop
// -------------------------------------------------------------------------
const baseMaterial = new THREE.MeshStandardMaterial({
color: 0xcbc6bc,
roughness: 0.94
});
const base = new THREE.Mesh(
new THREE.BoxGeometry(13.4, 0.38, 9.25),
baseMaterial
);
base.position.y = -0.23;
base.receiveShadow = true;
scene.add(base);
const tabletopMaterial = new THREE.MeshStandardMaterial({
color: 0xded9cf,
roughness: 0.96
});
const tabletop = new THREE.Mesh(
new THREE.BoxGeometry(13.22, 0.12, 9.08),
tabletopMaterial
);
tabletop.position.y = -0.035;
tabletop.receiveShadow = true;
scene.add(tabletop);
// A restrained grid helps compare geometric distance without competing
// with the graph paths.
const gridPositions = [];
for (let x = -6; x <= 6; x += 1) {
gridPositions.push(x, 0.032, -4.45, x, 0.032, 4.45);
}
for (let z = -4; z <= 4; z += 1) {
gridPositions.push(-6.55, 0.032, z, 6.55, 0.032, z);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridPositions, 3)
);
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0xb8b3aa,
transparent: true,
opacity: 0.22
})
);
scene.add(grid);
// -------------------------------------------------------------------------
// Node construction
// -------------------------------------------------------------------------
const pickables = [];
const nodeRecords = new Map();
function makeLabel(letter) {
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 128;
const context = canvas.getContext("2d");
context.clearRect(0, 0, 128, 128);
context.beginPath();
context.arc(64, 64, 45, 0, Math.PI * 2);
context.fillStyle = "rgba(250,248,241,0.96)";
context.fill();
context.lineWidth = 6;
context.strokeStyle = "rgba(42,45,41,0.72)";
context.stroke();
context.fillStyle = "#292b29";
context.font = "800 52px system-ui";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(letter, 64, 67);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
})
);
sprite.scale.set(0.52, 0.52, 0.52);
sprite.renderOrder = 10;
return sprite;
}
function addMesh(parent, geometry, material, x, y, z, rotationY = 0) {
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(x, y, z);
mesh.rotation.y = rotationY;
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function createNode(def) {
const root = new THREE.Group();
root.position.set(def.x, 0, def.z);
scene.add(root);
const trackedMaterials = [];
const track = material => {
trackedMaterials.push({
material,
color: material.color.clone()
});
return material;
};
const pedestalMaterial = track(new THREE.MeshStandardMaterial({
color: 0xcfc9be,
roughness: 0.9,
flatShading: true
}));
let pedestalGeometry;
switch (def.shape) {
case "house":
pedestalGeometry = new THREE.CylinderGeometry(0.82, 0.82, 0.16, 6);
break;
case "tower":
pedestalGeometry = new THREE.CylinderGeometry(0.75, 0.78, 0.16, 8);
break;
case "steps":
pedestalGeometry = new THREE.BoxGeometry(1.48, 0.16, 1.35);
break;
case "wedge":
pedestalGeometry = new THREE.CylinderGeometry(0.85, 0.85, 0.16, 3);
break;
case "dome":
pedestalGeometry = new THREE.CylinderGeometry(0.78, 0.82, 0.16, 6);
break;
default:
pedestalGeometry = new THREE.BoxGeometry(1.48, 0.16, 1.40);
}
addMesh(root, pedestalGeometry, pedestalMaterial, 0, 0.08, 0);
const bodyMaterial = track(new THREE.MeshStandardMaterial({
color: def.color,
roughness: 0.78,
metalness: 0.02,
flatShading: true
}));
const roofMaterial = track(new THREE.MeshStandardMaterial({
color: new THREE.Color(def.color).multiplyScalar(0.76),
roughness: 0.84,
flatShading: true
}));
const doorMaterial = new THREE.MeshStandardMaterial({
color: 0x343a38,
roughness: 0.72
});
let labelHeight = 1.9;
switch (def.shape) {
case "house": {
addMesh(
root,
new THREE.BoxGeometry(0.86, 0.76, 0.78),
bodyMaterial,
0, 0.54, 0
);
addMesh(
root,
new THREE.ConeGeometry(0.72, 0.48, 4),
roofMaterial,
0, 1.16, 0,
Math.PI / 4
);
addMesh(
root,
new THREE.BoxGeometry(0.19, 0.34, 0.035),
doorMaterial,
0, 0.33, 0.405
);
break;
}
case "tower": {
addMesh(
root,
new THREE.CylinderGeometry(0.43, 0.52, 1.12, 8),
bodyMaterial,
0, 0.72, 0
);
addMesh(
root,
new THREE.CylinderGeometry(0.58, 0.58, 0.13, 8),
roofMaterial,
0, 1.34, 0
);
addMesh(
root,
new THREE.BoxGeometry(0.17, 0.34, 0.035),
doorMaterial,
0, 0.33, 0.525
);
break;
}
case "steps": {
addMesh(
root,
new THREE.BoxGeometry(1.03, 0.43, 0.88),
bodyMaterial,
0, 0.375, 0
);
addMesh(
root,
new THREE.BoxGeometry(0.72, 0.43, 0.66),
roofMaterial,
-0.10, 0.80, 0
);
addMesh(
root,
new THREE.BoxGeometry(0.40, 0.33, 0.48),
bodyMaterial,
-0.18, 1.16, 0
);
addMesh(
root,
new THREE.BoxGeometry(0.18, 0.31, 0.035),
doorMaterial,
0.16, 0.31, 0.46
);
break;
}
case "wedge": {
addMesh(
root,
new THREE.CylinderGeometry(0.66, 0.66, 1.12, 3),
bodyMaterial,
0, 0.72, 0,
Math.PI / 6
);
addMesh(
root,
new THREE.CylinderGeometry(0.27, 0.34, 0.28, 3),
roofMaterial,
0, 1.40, 0,
Math.PI / 6
);
addMesh(
root,
new THREE.BoxGeometry(0.18, 0.32, 0.035),
doorMaterial,
0, 0.32, 0.48
);
break;
}
case "dome": {
addMesh(
root,
new THREE.CylinderGeometry(0.53, 0.57, 0.72, 6),
bodyMaterial,
0, 0.52, 0
);
addMesh(
root,
new THREE.SphereGeometry(
0.54, 8, 4,
0, Math.PI * 2,
0, Math.PI / 2
),
roofMaterial,
0, 0.88, 0
);
addMesh(
root,
new THREE.BoxGeometry(0.18, 0.34, 0.035),
doorMaterial,
0, 0.33, 0.565
);
break;
}
case "twin": {
addMesh(
root,
new THREE.BoxGeometry(0.73, 0.68, 0.72),
bodyMaterial,
-0.22, 0.50, 0
);
addMesh(
root,
new THREE.BoxGeometry(0.62, 0.94, 0.63),
roofMaterial,
0.30, 0.63, -0.04
);
addMesh(
root,
new THREE.BoxGeometry(0.68, 0.12, 0.69),
bodyMaterial,
0.30, 1.16, -0.04
);
addMesh(
root,
new THREE.BoxGeometry(0.18, 0.34, 0.035),
doorMaterial,
-0.22, 0.33, 0.375
);
labelHeight = 2.0;
break;
}
}
const halo = new THREE.Mesh(
new THREE.TorusGeometry(0.91, 0.035, 6, 40),
new THREE.MeshBasicMaterial({
color: 0xd78b2d,
transparent: true,
opacity: 0.95,
depthWrite: false
})
);
halo.rotation.x = Math.PI / 2;
halo.position.y = 0.04;
halo.visible = false;
root.add(halo);
const label = makeLabel(def.id);
label.position.set(0, labelHeight, 0);
root.add(label);
root.traverse(object => {
object.userData.nodeId = def.id;
if (object.isMesh || object.isSprite) pickables.push(object);
});
nodeRecords.set(def.id, {
def,
root,
trackedMaterials,
halo
});
}
nodeDefs.forEach(createNode);
// -------------------------------------------------------------------------
// Raised graph paths
// -------------------------------------------------------------------------
const edges = new Map();
const PATH_Y = 0.215;
const edgeBaseColor = new THREE.Color(0x918477);
const edgeAmberColor = new THREE.Color(0xd78b2d);
const edgeTealColor = new THREE.Color(0x258d89);
function createEdge(a, b) {
const nodeA = nodes.get(a);
const nodeB = nodes.get(b);
const dx = nodeB.x - nodeA.x;
const dz = nodeB.z - nodeA.z;
const length = Math.hypot(dx, dz);
const group = new THREE.Group();
group.position.set(
(nodeA.x + nodeB.x) / 2,
0,
(nodeA.z + nodeB.z) / 2
);
group.rotation.y = -Math.atan2(dz, dx);
const material = new THREE.MeshStandardMaterial({
color: edgeBaseColor,
roughness: 0.84,
metalness: 0.02,
emissive: 0x000000,
emissiveIntensity: 0
});
const beam = new THREE.Mesh(
new THREE.BoxGeometry(length, 0.14, 0.28),
material
);
beam.position.y = 0.10;
beam.castShadow = true;
beam.receiveShadow = true;
group.add(beam);
const stripe = new THREE.Mesh(
new THREE.BoxGeometry(length - 0.06, 0.025, 0.11),
material
);
stripe.position.y = 0.184;
stripe.castShadow = true;
group.add(stripe);
scene.add(group);
edges.set(edgeKey(a, b), {
a,
b,
group,
material
});
}
edgeDefs.forEach(([a, b]) => createEdge(a, b));
const routeEdgeKeys = new Set();
let selectedNode = null;
function refreshEdgeMaterials() {
for (const edge of edges.values()) {
const incidentToSelection = selectedNode &&
(edge.a === selectedNode || edge.b === selectedNode);
const isRoute = routeEdgeKeys.has(edgeKey(edge.a, edge.b));
if (incidentToSelection) {
edge.material.color.copy(edgeAmberColor);
edge.material.emissive.set(0x6f3a00);
edge.material.emissiveIntensity = 0.28;
} else if (isRoute) {
edge.material.color.copy(edgeTealColor);
edge.material.emissive.set(0x0e4e4b);
edge.material.emissiveIntensity = 0.32;
} else {
edge.material.color.copy(edgeBaseColor);
edge.material.emissive.set(0x000000);
edge.material.emissiveIntensity = 0;
}
}
}
function inspectNode(id) {
selectedNode = id;
for (const [nodeId, record] of nodeRecords) {
const isSelected = nodeId === id;
const isNeighbor = adjacency[id].includes(nodeId);
record.halo.visible = isSelected || isNeighbor;
record.halo.material.color.set(
isSelected ? 0xfaf7ef : 0xd78b2d
);
for (const tracked of record.trackedMaterials) {
tracked.material.color.copy(tracked.color);
tracked.material.emissive.set(0x000000);
tracked.material.emissiveIntensity = 0;
if (isNeighbor) {
tracked.material.emissive.set(0x713600);
tracked.material.emissiveIntensity = 0.36;
}
}
}
const direct = adjacency[id];
document.getElementById("inspection").textContent = direct.length
? `${id} → direct neighbors: ${direct.join(", ")}.`
: `${id} → no direct connection.`;
refreshEdgeMaterials();
}
// -------------------------------------------------------------------------
// Traveler
// -------------------------------------------------------------------------
const traveler = new THREE.Group();
const travelerBodyMaterial = new THREE.MeshStandardMaterial({
color: 0xf2b33b,
roughness: 0.58,
flatShading: true
});
const travelerHeadMaterial = new THREE.MeshStandardMaterial({
color: 0xfff0cf,
roughness: 0.72,
flatShading: true
});
const travelerBody = new THREE.Mesh(
new THREE.ConeGeometry(0.17, 0.34, 6),
travelerBodyMaterial
);
travelerBody.position.y = 0.22;
travelerBody.castShadow = true;
traveler.add(travelerBody);
const travelerHead = new THREE.Mesh(
new THREE.SphereGeometry(0.115, 8, 5),
travelerHeadMaterial
);
travelerHead.position.y = 0.46;
travelerHead.castShadow = true;
traveler.add(travelerHead);
const travelerHat = new THREE.Mesh(
new THREE.CylinderGeometry(0.16, 0.16, 0.035, 8),
travelerBodyMaterial
);
travelerHat.position.y = 0.55;
travelerHat.castShadow = true;
traveler.add(travelerHat);
// A tiny forward marker makes direction readable.
const travelerNose = new THREE.Mesh(
new THREE.BoxGeometry(0.075, 0.075, 0.17),
travelerHeadMaterial
);
travelerNose.position.set(0, 0.22, 0.13);
traveler.add(travelerNose);
scene.add(traveler);
let trip = null;
function perimeterPoint(id, towardId, radius = 0.82) {
const node = nodes.get(id);
const target = nodes.get(towardId);
const dx = target.x - node.x;
const dz = target.z - node.z;
const length = Math.hypot(dx, dz);
return new THREE.Vector3(
node.x + dx / length * radius,
PATH_Y,
node.z + dz / length * radius
);
}
function buildTravelWaypoints(path) {
const waypoints = [];
for (let i = 0; i < path.length - 1; i++) {
const a = path[i];
const b = path[i + 1];
const start = perimeterPoint(a, b);
const end = perimeterPoint(b, a);
if (i === 0) waypoints.push(start);
waypoints.push(end);
// Travel around the shared building rather than through it.
if (i < path.length - 2) {
const next = path[i + 2];
const nodeB = nodes.get(b);
const nodeA = nodes.get(a);
const nodeNext = nodes.get(next);
const incomingAngle = Math.atan2(
nodeA.z - nodeB.z,
nodeA.x - nodeB.x
);
const outgoingAngle = Math.atan2(
nodeNext.z - nodeB.z,
nodeNext.x - nodeB.x
);
let delta = outgoingAngle - incomingAngle;
while (delta > Math.PI) delta -= Math.PI * 2;
while (delta < -Math.PI) delta += Math.PI * 2;
for (let step = 1; step <= 5; step++) {
const angle = incomingAngle + delta * step / 5;
waypoints.push(new THREE.Vector3(
nodeB.x + Math.cos(angle) * 0.82,
PATH_Y,
nodeB.z + Math.sin(angle) * 0.82
));
}
}
}
return waypoints;
}
function shortestPath(start, goal) {
if (start === goal) return [start];
const queue = [start];
const parent = new Map([[start, null]]);
while (queue.length) {
const current = queue.shift();
for (const neighbor of adjacency[current]) {
if (parent.has(neighbor)) continue;
parent.set(neighbor, current);
if (neighbor === goal) {
const result = [goal];
let cursor = goal;
while (parent.get(cursor) !== null) {
cursor = parent.get(cursor);
result.unshift(cursor);
}
return result;
}
queue.push(neighbor);
}
}
return null;
}
function reachableFrom(start) {
const reached = new Set([start]);
const queue = [start];
while (queue.length) {
const current = queue.shift();
for (const neighbor of adjacency[current]) {
if (!reached.has(neighbor)) {
reached.add(neighbor);
queue.push(neighbor);
}
}
}
return reached;
}
function planarDistance(a, b) {
return Math.hypot(a.x - b.x, a.z - b.z);
}
function planRoute(start, goal) {
const validPath = shortestPath(start, goal);
if (validPath) {
return {
path: validPath,
valid: true,
stopAt: goal,
message: validPath.length === 2
? `${start} and ${goal} have a direct graph edge.`
: `${start} and ${goal} are connected by ${validPath.join(" → ")}.`
};
}
// No graph path exists. Move only along real edges to the reachable
// boundary node geometrically closest to the requested destination.
const reachable = reachableFrom(start);
let boundary = start;
let closest = Infinity;
for (const id of reachable) {
const distance = planarDistance(nodes.get(id), nodes.get(goal));
if (distance < closest) {
closest = distance;
boundary = id;
}
}
const boundaryPath = shortestPath(start, boundary) || [start];
return {
path: boundaryPath,
valid: false,
stopAt: boundary,
message:
`No graph route reaches ${goal}. Following ` +
`${boundaryPath.join(" → ")} and stopping before the empty gap.`
};
}
function routePills(path, stopAt, valid, destination) {
const container = document.getElementById("route");
container.innerHTML = "";
path.forEach((id, index) => {
if (index > 0) {
const arrow = document.createElement("span");
arrow.className = "arrow";
arrow.textContent = "→";
container.appendChild(arrow);
}
const pill = document.createElement("span");
pill.className = "node-pill";
pill.textContent = id;
container.appendChild(pill);
});
if (!valid) {
const arrow = document.createElement("span");
arrow.className = "arrow";
arrow.textContent = "↛";
container.appendChild(arrow);
const pill = document.createElement("span");
pill.className = "node-pill stop";
pill.textContent = destination;
container.appendChild(pill);
}
}
function startTrip(plan, destination) {
routeEdgeKeys.clear();
for (let i = 0; i < plan.path.length - 1; i++) {
routeEdgeKeys.add(edgeKey(plan.path[i], plan.path[i + 1]));
}
refreshEdgeMaterials();
routePills(plan.path, plan.stopAt, plan.valid, destination);
const status = document.getElementById("status");
status.textContent = plan.message;
const waypoints = buildTravelWaypoints(plan.path);
if (waypoints.length < 2) {
const node = nodes.get(plan.path[0]);
traveler.position.set(node.x, PATH_Y, node.z);
traveler.visible = true;
trip = null;
status.textContent = plan.valid
? "The traveler is already at the destination."
: `${plan.path[0]} has no outgoing connection toward ${plan.stopAt}.`;
return;
}
traveler.position.copy(waypoints[0]);
traveler.visible = true;
trip = {
waypoints,
index: 0,
elapsed: 0,
duration: 0,
plan
};
}
function sendRoute() {
const start = document.getElementById("start").value;
const destination = document.getElementById("destination").value;
if (start === destination) {
document.getElementById("status").textContent =
"Choose two different buildings for the traveler.";
document.getElementById("route").innerHTML = "";
trip = null;
return;
}
const plan = planRoute(start, destination);
startTrip(plan, destination);
}
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
const startSelect = document.getElementById("start");
const destinationSelect = document.getElementById("destination");
for (const node of nodeDefs) {
const startOption = document.createElement("option");
startOption.value = node.id;
startOption.textContent = `${node.id} · ${node.shape}`;
startSelect.appendChild(startOption);
const destinationOption = document.createElement("option");
destinationOption.value = node.id;
destinationOption.textContent = `${node.id} · ${node.shape}`;
destinationSelect.appendChild(destinationOption);
}
startSelect.value = "A";
destinationSelect.value = "B";
document.getElementById("send").addEventListener("click", sendRoute);
document.querySelectorAll("[data-preset]").forEach(button => {
button.addEventListener("click", () => {
const preset = button.dataset.preset;
if (preset === "near") {
startSelect.value = "A";
destinationSelect.value = "B";
} else if (preset === "far") {
startSelect.value = "C";
destinationSelect.value = "D";
} else {
startSelect.value = "F";
destinationSelect.value = "E";
}
sendRoute();
});
});
// -------------------------------------------------------------------------
// Direct camera controls: orbit and zoom
// -------------------------------------------------------------------------
const orbit = {
theta: 0.67,
phi: 0.82,
radius: 14.4,
target: new THREE.Vector3(0.35, 0.38, 0.05)
};
function updateCamera() {
const horizontal = orbit.radius * Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + horizontal * Math.cos(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + horizontal * Math.sin(orbit.theta)
);
camera.lookAt(orbit.target);
}
updateCamera();
document.getElementById("reset").addEventListener("click", () => {
orbit.theta = 0.67;
orbit.phi = 0.82;
orbit.radius = 14.4;
orbit.target.set(0.35, 0.38, 0.05);
updateCamera();
});
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let pointerState = null;
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
pointerState = {
x: event.clientX,
y: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
moved: false
};
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!pointerState) return;
const totalDistance = Math.hypot(
event.clientX - pointerState.x,
event.clientY - pointerState.y
);
if (totalDistance > 4) pointerState.moved = true;
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
orbit.theta -= dx * 0.006;
orbit.phi = THREE.MathUtils.clamp(
orbit.phi + dy * 0.005,
0.34,
1.30
);
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
updateCamera();
});
renderer.domElement.addEventListener("pointerup", event => {
if (!pointerState) return;
const wasClick = !pointerState.moved;
pointerState = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
if (!wasClick) return;
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(pickables, false);
if (intersections.length) {
const nodeId = intersections[0].object.userData.nodeId;
if (nodeId) inspectNode(nodeId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerState = null;
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius + event.deltaY * 0.012,
8.5,
22
);
updateCamera();
}, { passive: false });
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
function resize() {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
}
addEventListener("resize", resize);
const clock = new THREE.Clock();
let elapsed = 0;
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
elapsed += delta;
if (trip) {
const a = trip.waypoints[trip.index];
const b = trip.waypoints[trip.index + 1];
if (!b) {
const finished = trip.plan;
trip = null;
document.getElementById("status").textContent = finished.valid
? `Traveler completed ${finished.path.join(" → ")} using only graph edges.`
: `Traveler stopped at ${finished.stopAt}. No edge continues to the destination, so the empty gap was not crossed.`;
} else {
trip.elapsed += delta;
if (trip.duration === 0) {
trip.duration = THREE.MathUtils.clamp(
a.distanceTo(b) * 0.42 + 0.35,
0.72,
1.55
);
}
const progress = Math.min(trip.elapsed / trip.duration, 1);
traveler.position.lerpVectors(a, b, progress);
const direction = new THREE.Vector3().subVectors(b, a);
if (direction.lengthSq() > 0.0001) {
traveler.rotation.y = Math.atan2(direction.x, direction.z);
}
if (progress >= 1) {
trip.index++;
trip.elapsed = 0;
trip.duration = 0;
}
}
}
if (selectedNode) {
const halo = nodeRecords.get(selectedNode).halo;
const pulse = 1 + Math.sin(elapsed * 3.1) * 0.035;
halo.scale.setScalar(pulse);
}
renderer.render(scene, camera);
}
animate();
// Begin with the close-but-not-adjacent pair so the distinction is visible.
setTimeout(() => {
startSelect.value = "A";
destinationSelect.value = "B";
sendRoute();
}, 650);
</script>
</body>
</html>
```