Prompt specification
Build or customize the Three.js 3D scene "Reachability counterfactual explorer" 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: Reachability counterfactual explorer
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/reachability-counterfactual-explorer-x1888
Scene Description Prompt:
Create a standalone low-poly scene in one HTML file using Three.js from cdnjs. Let users open or close a few edges and choose a start node; update reachable sets and traversal traces without letting decorative distances alter connectivity.
Working Three.js Starter (reachability-counterfactual-explorer-x1888):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Topology Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(10, 23, 39, 0.88);
--panel-border: rgba(155, 211, 230, 0.16);
--text: #edf8fb;
--muted: #91a8b6;
--cyan: #38d6c5;
--yellow: #ffe066;
--orange: #ffa62b;
--red: #ef476f;
--green: #75e6a7;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
select {
font: inherit;
}
button {
color: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
#labelLayer {
position: fixed;
inset: 0;
z-index: 2;
overflow: hidden;
pointer-events: none;
}
.node-label {
position: absolute;
display: flex;
align-items: center;
gap: 6px;
min-width: 72px;
padding: 5px 7px;
border: 1px solid rgba(56, 214, 197, 0.42);
border-radius: 8px;
background: rgba(7, 17, 31, 0.86);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.24);
transform: translate(-50%, -50%);
white-space: nowrap;
backdrop-filter: blur(7px);
}
.node-label.start {
border-color: rgba(255, 166, 43, 0.75);
}
.node-label.unreachable {
border-color: rgba(145, 168, 182, 0.25);
opacity: 0.58;
}
.node-letter {
display: grid;
width: 23px;
height: 23px;
place-items: center;
border-radius: 6px;
background: var(--cyan);
color: #062027;
font-size: 12px;
font-weight: 900;
}
.node-label.start .node-letter {
background: var(--orange);
}
.node-label.unreachable .node-letter {
background: #526474;
color: #d7e1e6;
}
.node-state {
color: #d6e8ed;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.03em;
}
.bfs-index {
display: grid;
width: 18px;
height: 18px;
margin-left: auto;
place-items: center;
border-radius: 50%;
background: rgba(255, 255, 255, 0.09);
color: #c8d8df;
font-size: 9px;
font-weight: 800;
}
.distance-label {
position: absolute;
padding: 3px 6px;
border: 1px solid rgba(145, 168, 182, 0.2);
border-radius: 999px;
background: rgba(7, 17, 31, 0.76);
color: #a9bdc8;
font-size: 9px;
font-weight: 700;
transform: translate(-50%, -50%);
white-space: nowrap;
}
.distance-label.closed {
border-color: rgba(239, 71, 111, 0.45);
color: #ff8eaa;
}
#panel {
position: fixed;
z-index: 10;
top: 16px;
left: 16px;
width: 344px;
max-height: calc(100vh - 32px);
overflow: auto;
padding: 18px;
border: 1px solid var(--panel-border);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 22px 70px rgba(0, 0, 0, 0.42);
backdrop-filter: blur(18px) saturate(130%);
scrollbar-width: thin;
scrollbar-color: #315066 transparent;
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 900;
letter-spacing: 0.18em;
}
h1 {
margin: 5px 0 7px;
font-size: 28px;
line-height: 1.05;
letter-spacing: -0.04em;
}
.intro {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.panel-section {
margin-top: 17px;
padding-top: 15px;
border-top: 1px solid rgba(155, 211, 230, 0.12);
}
.section-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 9px;
}
h2 {
margin: 0;
font-size: 12px;
font-weight: 850;
letter-spacing: 0.03em;
}
.hint {
margin: 0 0 10px;
color: #7f98a7;
font-size: 10px;
line-height: 1.45;
}
label {
display: block;
margin-bottom: 6px;
color: #b7cbd4;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.04em;
text-transform: uppercase;
}
select {
width: 100%;
padding: 10px 11px;
border: 1px solid rgba(155, 211, 230, 0.2);
border-radius: 9px;
outline: none;
background: #10263a;
color: var(--text);
font-weight: 750;
}
select:focus,
button:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 2px;
}
.mini-button,
.primary-button {
border: 0;
border-radius: 8px;
cursor: pointer;
font-weight: 800;
}
.mini-button {
padding: 6px 9px;
background: rgba(145, 168, 182, 0.11);
color: #bcd0d9;
font-size: 10px;
}
.mini-button:hover {
background: rgba(145, 168, 182, 0.19);
}
#edgeList {
display: grid;
gap: 6px;
}
.edge-button {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 8px 9px;
border: 1px solid rgba(56, 214, 197, 0.2);
border-radius: 9px;
background: rgba(56, 214, 197, 0.06);
cursor: pointer;
text-align: left;
transition:
background 150ms ease,
border-color 150ms ease,
transform 150ms ease;
}
.edge-button:hover {
transform: translateX(2px);
border-color: rgba(56, 214, 197, 0.5);
}
.edge-button.is-closed {
border-color: rgba(239, 71, 111, 0.3);
background: rgba(239, 71, 111, 0.07);
}
.edge-name {
display: flex;
align-items: center;
gap: 7px;
font-size: 11px;
font-weight: 800;
}
.edge-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 9px rgba(56, 214, 197, 0.55);
}
.is-closed .edge-dot {
background: var(--red);
box-shadow: 0 0 9px rgba(239, 71, 111, 0.45);
}
.edge-state {
color: var(--cyan);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.is-closed .edge-state {
color: #ff789b;
}
.metric {
display: flex;
align-items: baseline;
gap: 6px;
margin-bottom: 10px;
}
.metric strong {
color: var(--cyan);
font-size: 27px;
line-height: 1;
}
.metric span {
color: var(--muted);
font-size: 11px;
}
.set-row {
display: grid;
grid-template-columns: 58px 1fr;
align-items: start;
gap: 8px;
margin-top: 7px;
}
.set-label {
padding-top: 5px;
color: #8098a6;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.chips {
display: flex;
flex-wrap: wrap;
gap: 5px;
}
.chip {
display: grid;
min-width: 25px;
height: 25px;
place-items: center;
border: 1px solid rgba(56, 214, 197, 0.28);
border-radius: 7px;
background: rgba(56, 214, 197, 0.09);
color: #aef4eb;
font-size: 10px;
font-weight: 900;
}
.chip.outside {
border-color: rgba(145, 168, 182, 0.16);
background: rgba(145, 168, 182, 0.05);
color: #718894;
}
#statusLine {
margin-top: 10px;
color: #9db3bf;
font-size: 10px;
line-height: 1.45;
}
.primary-button {
width: 100%;
padding: 9px 11px;
background: linear-gradient(135deg, #2bc8ba, #42dec9);
color: #062027;
font-size: 11px;
box-shadow: 0 7px 22px rgba(43, 200, 186, 0.16);
}
.primary-button:hover {
filter: brightness(1.08);
}
#traceList {
display: grid;
gap: 5px;
max-height: 225px;
margin: 10px 0 0;
padding: 0;
overflow: auto;
list-style: none;
scrollbar-width: thin;
scrollbar-color: #315066 transparent;
}
#traceList button {
width: 100%;
display: grid;
grid-template-columns: 24px 1fr auto;
align-items: center;
gap: 8px;
padding: 7px 8px;
border: 1px solid transparent;
border-radius: 8px;
background: rgba(145, 168, 182, 0.045);
cursor: pointer;
text-align: left;
}
#traceList button:hover {
background: rgba(145, 168, 182, 0.09);
}
#traceList li.current button {
border-color: rgba(255, 224, 102, 0.58);
background: rgba(255, 224, 102, 0.1);
}
#traceList li.done button {
opacity: 0.68;
}
.step-number {
display: grid;
width: 22px;
height: 22px;
place-items: center;
border-radius: 6px;
background: rgba(145, 168, 182, 0.12);
color: #b8cbd4;
font-size: 9px;
font-weight: 900;
}
.current .step-number {
background: var(--yellow);
color: #242000;
}
.step-node {
font-size: 11px;
font-weight: 850;
}
.step-via {
color: #78919f;
font-size: 9px;
}
.distance-note {
display: flex;
gap: 9px;
margin-top: 16px;
padding: 10px;
border: 1px solid rgba(255, 166, 43, 0.23);
border-radius: 10px;
background: rgba(255, 166, 43, 0.06);
color: #d6b989;
font-size: 10px;
line-height: 1.5;
}
.distance-note strong {
color: #ffd08f;
}
#legend {
position: fixed;
z-index: 5;
right: 18px;
bottom: 18px;
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 8px 13px;
max-width: 430px;
padding: 10px 12px;
border: 1px solid rgba(155, 211, 230, 0.14);
border-radius: 10px;
background: rgba(7, 17, 31, 0.72);
color: #9db3bf;
font-size: 9px;
backdrop-filter: blur(8px);
}
.legend-item {
display: flex;
align-items: center;
gap: 5px;
}
.legend-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--cyan);
}
.legend-dot.start {
background: var(--orange);
}
.legend-dot.trace {
background: var(--yellow);
}
.legend-dot.outside {
background: #526474;
}
.legend-dot.closed {
background: var(--red);
}
#controlsHint {
position: fixed;
z-index: 4;
top: 16px;
right: 18px;
padding: 8px 11px;
border: 1px solid rgba(155, 211, 230, 0.12);
border-radius: 9px;
background: rgba(7, 17, 31, 0.68);
color: #829aa7;
font-size: 9px;
backdrop-filter: blur(8px);
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
@media (max-width: 760px) {
#panel {
top: auto;
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
max-height: 46vh;
padding: 15px;
border-radius: 15px;
}
#controlsHint {
top: 12px;
right: 12px;
left: 12px;
text-align: center;
}
#legend {
display: none;
}
.distance-label {
font-size: 8px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive low-poly graph"></canvas>
<div id="labelLayer" aria-hidden="true"></div>
<aside id="panel" aria-label="Graph controls">
<div class="eyebrow">GRAPH EXPLORER</div>
<h1>Topology Lab</h1>
<p class="intro">
Open or close paths, choose a source, and inspect the traversal.
Connectivity follows the gates—not the decorative distance badges.
</p>
<section class="panel-section">
<label for="startSelect">Start node</label>
<select id="startSelect"></select>
<p class="hint" style="margin-top: 7px">
You can also click a node directly in the scene.
</p>
</section>
<section class="panel-section">
<div class="section-head">
<h2>Edge gates</h2>
<button id="resetButton" class="mini-button" type="button">
Reset all
</button>
</div>
<p class="hint">
Click a gate to close it. Click it again to reopen it.
</p>
<div id="edgeList"></div>
</section>
<section class="panel-section">
<div class="section-head">
<h2>Reachable set</h2>
</div>
<div class="metric">
<strong id="reachableCount">0</strong>
<span>/ 8 nodes reachable</span>
</div>
<div class="set-row">
<div class="set-label">Reachable</div>
<div id="reachableSet" class="chips"></div>
</div>
<div class="set-row">
<div class="set-label">Outside</div>
<div id="unreachableSet" class="chips"></div>
</div>
<div id="statusLine" aria-live="polite"></div>
</section>
<section class="panel-section">
<div class="section-head">
<h2>BFS traversal trace</h2>
<button id="replayButton" class="mini-button" type="button">
Replay
</button>
</div>
<p class="hint">
The trace records discovery order. Click a step to inspect it.
</p>
<ol id="traceList"></ol>
</section>
<div class="distance-note">
<span aria-hidden="true">↔</span>
<div>
<strong>Distances are scenery only.</strong>
The traversal never compares these numbers; it uses only the
open/closed state of each edge.
</div>
</div>
<div id="liveStatus" class="sr-only" aria-live="polite"></div>
</aside>
<div id="controlsHint">
Drag: orbit · Shift/right-drag: pan · Wheel: zoom · Click node or edge
</div>
<div id="legend" aria-hidden="true">
<span class="legend-item">
<i class="legend-dot start"></i> Start
</span>
<span class="legend-item">
<i class="legend-dot"></i> Reachable
</span>
<span class="legend-item">
<i class="legend-dot trace"></i> Trace step
</span>
<span class="legend-item">
<i class="legend-dot outside"></i> Outside component
</span>
<span class="legend-item">
<i class="legend-dot closed"></i> Closed edge
</span>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Graph data. displayDistance is used only to draw scenery labels.
// It is intentionally never consulted by the traversal algorithm.
// -------------------------------------------------------------------------
const nodeDefinitions = [
{ id: "A", position: [-4.0, 0.65, -0.2] },
{ id: "B", position: [-1.8, 0.65, -2.2] },
{ id: "C", position: [-1.5, 0.65, 1.6] },
{ id: "D", position: [ 0.8, 0.65, -1.2] },
{ id: "E", position: [ 1.1, 0.65, 1.7] },
{ id: "F", position: [ 3.8, 0.65, -0.4] },
{ id: "G", position: [ 3.8, 0.65, 2.5] },
{ id: "H", position: [-0.4, 0.65, 3.7] }
];
const edgeDefinitions = [
{ id: "AB", from: "A", to: "B", displayDistance: 7 },
{ id: "AC", from: "A", to: "C", displayDistance: 12 },
{ id: "BD", from: "B", to: "D", displayDistance: 4 },
{ id: "DF", from: "D", to: "F", displayDistance: 6 },
{ id: "CE", from: "C", to: "E", displayDistance: 9 },
{ id: "EG", from: "E", to: "G", displayDistance: 8 },
{ id: "CH", from: "C", to: "H", displayDistance: 11 },
{ id: "HG", from: "H", to: "G", displayDistance: 5 }
];
const state = {
start: "A",
traceIndex: 0,
traversal: null
};
const nodeById = new Map();
const edgeById = new Map();
const adjacency = new Map();
const pickNodeMeshes = [];
const pickEdgeMeshes = [];
for (const definition of nodeDefinitions) {
nodeById.set(definition.id, definition);
adjacency.set(definition.id, []);
}
const edges = edgeDefinitions.map((definition) => ({
...definition,
open: true
}));
for (const edge of edges) {
edgeById.set(edge.id, edge);
adjacency.get(edge.from).push({ to: edge.to, edge });
adjacency.get(edge.to).push({ to: edge.from, edge });
}
// -------------------------------------------------------------------------
// Renderer, camera, and lighting
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const labelLayer = document.querySelector("#labelLayer");
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.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 12, 31);
const camera = new THREE.PerspectiveCamera(
48,
window.innerWidth / window.innerHeight,
0.1,
80
);
const cameraState = {
target: new THREE.Vector3(0.25, 0, 0.65),
radius: 12.2,
theta: 0.72,
phi: 0.91
};
function updateCamera() {
const { target, radius, theta, phi } = cameraState;
const horizontal = Math.sin(phi) * radius;
camera.position.set(
target.x + horizontal * Math.sin(theta),
target.y + Math.cos(phi) * radius,
target.z + horizontal * Math.cos(theta)
);
camera.lookAt(target);
camera.updateMatrixWorld();
}
updateCamera();
scene.add(new THREE.HemisphereLight(0xbfefff, 0x172334, 2.1));
const sun = new THREE.DirectionalLight(0xffefd5, 3.1);
sun.position.set(-5, 11, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.camera.left = -11;
sun.shadow.camera.right = 11;
sun.shadow.camera.top = 11;
sun.shadow.camera.bottom = -11;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 30;
sun.shadow.bias = -0.0005;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x43d9ff, 1.25);
rimLight.position.set(7, 5, -8);
scene.add(rimLight);
// -------------------------------------------------------------------------
// Low-poly environment
// -------------------------------------------------------------------------
function seededRandom(seed) {
const value = Math.sin(seed * 12.9898) * 43758.5453;
return value - Math.floor(value);
}
const floorBase = new THREE.PlaneGeometry(20, 16, 10, 8);
const floorGeometry = floorBase.toNonIndexed();
floorBase.dispose();
const floorPositions = floorGeometry.attributes.position;
const floorColors = [];
for (let i = 0; i < floorPositions.count; i += 3) {
const x = (floorPositions.getX(i) + floorPositions.getX(i + 1)) / 2;
const y = (floorPositions.getY(i) + floorPositions.getY(i + 1)) / 2;
const shade = 0.08 + seededRandom(x * 3.1 + y * 5.7) * 0.035;
const color = new THREE.Color().setHSL(
0.56 + seededRandom(x + y) * 0.035,
0.31,
shade
);
for (let j = 0; j < 3; j++) {
floorColors.push(color.r, color.g, color.b);
}
}
floorGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(floorColors, 3)
);
floorGeometry.rotateX(-Math.PI / 2);
floorGeometry.computeVertexNormals();
const floor = new THREE.Mesh(
floorGeometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
flatShading: true,
roughness: 1,
metalness: 0
})
);
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(
18,
18,
0x5ac8d8,
0x28485b
);
grid.position.y = 0.012;
grid.material.transparent = true;
grid.material.opacity = 0.16;
scene.add(grid);
function addMountain(x, z, radius, height, color) {
const mountain = new THREE.Mesh(
new THREE.ConeGeometry(radius, height, 5),
new THREE.MeshStandardMaterial({
color,
flatShading: true,
roughness: 1
})
);
mountain.position.set(x, height * 0.5 - 0.03, z);
mountain.rotation.y = seededRandom(x + z) * Math.PI;
mountain.castShadow = true;
mountain.receiveShadow = true;
scene.add(mountain);
}
addMountain(-8.0, -6.2, 2.4, 3.2, 0x17364a);
addMountain( 7.4, -5.8, 2.9, 4.1, 0x163246);
addMountain(-7.2, 5.8, 2.0, 2.8, 0x17374a);
addMountain( 8.1, 5.4, 2.5, 3.4, 0x142f42);
const rockGeometry = new THREE.DodecahedronGeometry(0.35, 0);
[
[-7.3, 0.25, 2.4],
[-6.1, 0.18, -4.7],
[ 6.2, 0.23, 4.4],
[ 5.7, 0.17, -4.4],
[ 0.0, 0.16, -6.2]
].forEach((position, index) => {
const rock = new THREE.Mesh(
rockGeometry,
new THREE.MeshStandardMaterial({
color: index % 2 ? 0x294557 : 0x203b4d,
flatShading: true,
roughness: 1
})
);
rock.position.set(...position);
rock.scale.set(1.3, 0.75, 1);
rock.rotation.set(index, index * 0.7, index * 0.3);
rock.castShadow = true;
scene.add(rock);
});
const starPositions = [];
for (let i = 0; i < 90; i++) {
starPositions.push(
seededRandom(i * 1.7) * 30 - 15,
3 + seededRandom(i * 2.3) * 10,
seededRandom(i * 3.1) * 24 - 15
);
}
const starGeometry = new THREE.BufferGeometry();
starGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(starPositions, 3)
);
scene.add(
new THREE.Points(
starGeometry,
new THREE.PointsMaterial({
color: 0x9bd9ec,
size: 0.035,
transparent: true,
opacity: 0.55
})
)
);
// -------------------------------------------------------------------------
// Nodes
// -------------------------------------------------------------------------
const sharedNodeGeometry = new THREE.IcosahedronGeometry(0.38, 0);
const sharedBaseGeometry = new THREE.CylinderGeometry(0.47, 0.54, 0.12, 8);
const sharedRingGeometry = new THREE.TorusGeometry(0.46, 0.035, 5, 24);
for (const definition of nodeDefinitions) {
const group = new THREE.Group();
group.position.set(...definition.position);
const material = new THREE.MeshStandardMaterial({
color: 0x38d6c5,
emissive: 0x0b3937,
emissiveIntensity: 0.45,
roughness: 0.64,
metalness: 0.08,
flatShading: true
});
const body = new THREE.Mesh(sharedNodeGeometry, material);
body.castShadow = true;
body.receiveShadow = true;
body.userData.kind = "node";
body.userData.nodeId = definition.id;
const outlineMaterial = new THREE.LineBasicMaterial({
color: 0xbffaf2
});
const outline = new THREE.LineSegments(
new THREE.EdgesGeometry(sharedNodeGeometry),
outlineMaterial
);
body.add(outline);
// Slightly larger invisible hit target for easy selection.
const hitMaterial = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false
});
hitMaterial.colorWrite = false;
const hitTarget = new THREE.Mesh(
new THREE.SphereGeometry(0.59, 8, 6),
hitMaterial
);
hitTarget.userData.kind = "node";
hitTarget.userData.nodeId = definition.id;
body.add(hitTarget);
const baseMaterial = new THREE.MeshStandardMaterial({
color: 0x152d3e,
roughness: 0.85,
metalness: 0.1,
flatShading: true
});
const base = new THREE.Mesh(sharedBaseGeometry, baseMaterial);
base.position.y = -0.52;
base.castShadow = true;
base.receiveShadow = true;
group.add(base);
const ringMaterial = new THREE.MeshBasicMaterial({
color: 0x38d6c5
});
const ring = new THREE.Mesh(sharedRingGeometry, ringMaterial);
ring.rotation.x = Math.PI / 2;
ring.position.y = -0.45;
group.add(ring);
group.add(body);
scene.add(group);
const label = document.createElement("div");
label.className = "node-label";
label.innerHTML = `
<span class="node-letter">${definition.id}</span>
<span class="node-state"></span>
<span class="bfs-index"></span>
`;
labelLayer.appendChild(label);
definition.group = group;
definition.body = body;
definition.material = material;
definition.outlineMaterial = outlineMaterial;
definition.ringMaterial = ringMaterial;
definition.label = label;
definition.stateElement = label.querySelector(".node-state");
definition.orderElement = label.querySelector(".bfs-index");
definition.labelAnchor = new THREE.Vector3(
definition.position[0],
definition.position[1] + 0.58,
definition.position[2]
);
pickNodeMeshes.push(body, hitTarget);
}
// -------------------------------------------------------------------------
// Edges
// -------------------------------------------------------------------------
const upAxis = new THREE.Vector3(0, 1, 0);
function cylinderBetween(start, end, radius, material) {
const direction = new THREE.Vector3().subVectors(end, start);
const length = direction.length();
const midpoint = new THREE.Vector3()
.addVectors(start, end)
.multiplyScalar(0.5);
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius, length, 8, 1, false),
material
);
mesh.position.copy(midpoint);
mesh.quaternion.setFromUnitVectors(
upAxis,
direction.normalize()
);
mesh.castShadow = true;
return mesh;
}
for (const edge of edges) {
const start = new THREE.Vector3(
...nodeById.get(edge.from).position
);
const end = new THREE.Vector3(
...nodeById.get(edge.to).position
);
const solidMaterial = new THREE.MeshStandardMaterial({
color: 0x38d6c5,
emissive: 0x123d3b,
emissiveIntensity: 0.4,
roughness: 0.58,
metalness: 0.08,
flatShading: true
});
const solid = cylinderBetween(start, end, 0.055, solidMaterial);
solid.userData.kind = "edge";
solid.userData.edgeId = edge.id;
scene.add(solid);
const dashMaterial = new THREE.MeshStandardMaterial({
color: 0xef476f,
emissive: 0x571426,
emissiveIntensity: 0.35,
roughness: 0.7,
metalness: 0.05,
flatShading: true
});
const dashMeshes = [];
const dashCount = 7;
for (let i = 0; i < dashCount; i++) {
const t0 = i / dashCount;
const t1 = (i + 0.58) / dashCount;
const p0 = new THREE.Vector3().lerpVectors(start, end, t0);
const p1 = new THREE.Vector3().lerpVectors(start, end, t1);
const dash = cylinderBetween(p0, p1, 0.062, dashMaterial);
dash.userData.kind = "edge";
dash.userData.edgeId = edge.id;
dash.visible = false;
scene.add(dash);
dashMeshes.push(dash);
pickEdgeMeshes.push(dash);
}
pickEdgeMeshes.push(solid);
const label = document.createElement("div");
label.className = "distance-label";
label.textContent = `${edge.displayDistance} m`;
labelLayer.appendChild(label);
edge.solid = solid;
edge.solidMaterial = solidMaterial;
edge.dashMaterial = dashMaterial;
edge.dashMeshes = dashMeshes;
edge.label = label;
edge.labelAnchor = new THREE.Vector3()
.addVectors(start, end)
.multiplyScalar(0.5)
.add(new THREE.Vector3(0, 0.36, 0));
}
// -------------------------------------------------------------------------
// Unweighted BFS. Distances are intentionally absent from this logic.
// -------------------------------------------------------------------------
function computeBfs(startId) {
const visited = new Set([startId]);
const depths = new Map([[startId, 0]]);
const order = [{ node: startId, via: null, depth: 0 }];
const queue = [startId];
for (let queueIndex = 0; queueIndex < queue.length; queueIndex++) {
const currentId = queue[queueIndex];
for (const link of adjacency.get(currentId)) {
// Only topology and gate state affect reachability.
// link.edge.displayDistance is never compared or accumulated.
if (!link.edge.open) continue;
if (visited.has(link.to)) continue;
visited.add(link.to);
depths.set(link.to, depths.get(currentId) + 1);
order.push({
node: link.to,
via: link.edge.id,
depth: depths.get(link.to)
});
queue.push(link.to);
}
}
return { visited, order };
}
// -------------------------------------------------------------------------
// UI construction
// -------------------------------------------------------------------------
const startSelect = document.querySelector("#startSelect");
const edgeListElement = document.querySelector("#edgeList");
const reachableSetElement = document.querySelector("#reachableSet");
const unreachableSetElement = document.querySelector("#unreachableSet");
const reachableCountElement = document.querySelector("#reachableCount");
const statusLineElement = document.querySelector("#statusLine");
const liveStatusElement = document.querySelector("#liveStatus");
const traceListElement = document.querySelector("#traceList");
for (const node of nodeDefinitions) {
const option = document.createElement("option");
option.value = node.id;
option.textContent = `Node ${node.id}`;
startSelect.appendChild(option);
}
for (const edge of edges) {
const button = document.createElement("button");
button.type = "button";
button.className = "edge-button";
button.innerHTML = `
<span class="edge-name">
<i class="edge-dot"></i>
${edge.from} — ${edge.to}
</span>
<span class="edge-state">Open</span>
`;
button.addEventListener("click", () => {
toggleEdge(edge);
});
edge.button = button;
edge.stateElement = button.querySelector(".edge-state");
edgeListElement.appendChild(button);
}
function createChip(nodeId, outside = false) {
const chip = document.createElement("span");
chip.className = outside ? "chip outside" : "chip";
chip.textContent = nodeId;
chip.title = outside
? `Node ${nodeId} is outside the reachable component`
: `Node ${nodeId} is reachable`;
return chip;
}
function renderReachability() {
reachableSetElement.replaceChildren();
unreachableSetElement.replaceChildren();
for (const step of state.traversal.order) {
reachableSetElement.appendChild(createChip(step.node));
}
for (const node of nodeDefinitions) {
if (!state.traversal.visited.has(node.id)) {
unreachableSetElement.appendChild(createChip(node.id, true));
}
}
reachableCountElement.textContent = state.traversal.visited.size;
const message =
`${state.traversal.visited.size} of ${nodeDefinitions.length} nodes ` +
`are reachable from ${state.start}.`;
statusLineElement.textContent = message;
liveStatusElement.textContent = message;
}
function renderEdgeStates() {
for (const edge of edges) {
edge.button.classList.toggle("is-open", edge.open);
edge.button.classList.toggle("is-closed", !edge.open);
edge.stateElement.textContent = edge.open ? "Open" : "Closed";
edge.button.setAttribute("aria-pressed", String(edge.open));
edge.button.setAttribute(
"aria-label",
`${edge.from} to ${edge.to}, ${edge.open ? "open" : "closed"}. ` +
"Click to change state."
);
}
}
function renderTrace() {
traceListElement.replaceChildren();
state.traversal.order.forEach((step, index) => {
const listItem = document.createElement("li");
const button = document.createElement("button");
const edge = step.via ? edgeById.get(step.via) : null;
const viaText = edge
? `via ${edge.from} → ${edge.to}`
: "source node";
button.innerHTML = `
<span class="step-number">${index + 1}</span>
<span>
<span class="step-node">${step.node}</span><br>
<span class="step-via">${viaText}</span>
</span>
<span class="step-via">d${step.depth}</span>
`;
button.addEventListener("click", () => {
stopTraceAnimation();
state.traceIndex = index;
updateTraceClasses();
updateSceneState();
});
listItem.appendChild(button);
traceListElement.appendChild(listItem);
});
updateTraceClasses();
}
function updateTraceClasses() {
const items = [...traceListElement.children];
items.forEach((item, index) => {
const isCurrent = index === state.traceIndex;
const isDone = index < state.traceIndex;
item.classList.toggle("current", isCurrent);
item.classList.toggle("done", isDone);
item.querySelector("button").setAttribute(
"aria-current",
isCurrent ? "step" : "false"
);
});
}
// -------------------------------------------------------------------------
// Scene state
// -------------------------------------------------------------------------
function updateSceneState() {
const { visited, order } = state.traversal;
const orderIndex = new Map(
order.map((step, index) => [step.node, index])
);
const currentStep = order[state.traceIndex];
const currentVia = currentStep?.via ?? null;
const usedTreeEdges = new Set(
order
.slice(0, state.traceIndex + 1)
.map((step) => step.via)
.filter(Boolean)
);
for (const node of nodeDefinitions) {
const isCurrent = currentStep?.node === node.id;
const wasVisited = orderIndex.has(node.id) &&
orderIndex.get(node.id) < state.traceIndex;
const isStart = node.id === state.start;
let color = 0x526474;
let emissive = 0x111c25;
if (isCurrent) {
color = 0xffe066;
emissive = 0x6c5a08;
} else if (wasVisited) {
color = 0x75e6a7;
emissive = 0x174c2f;
} else if (isStart) {
color = 0xffa62b;
emissive = 0x6e3806;
} else if (visited.has(node.id)) {
color = 0x38d6c5;
emissive = 0x104541;
}
node.material.color.setHex(color);
node.material.emissive.setHex(emissive);
node.material.emissiveIntensity = isCurrent ? 0.75 : 0.42;
node.outlineMaterial.color.setHex(color);
node.ringMaterial.color.setHex(color);
node.label.classList.toggle("start", isStart);
node.label.classList.toggle(
"unreachable",
!visited.has(node.id)
);
node.stateElement.textContent = isStart
? "Start"
: visited.has(node.id)
? "Reachable"
: "Outside";
node.orderElement.textContent = orderIndex.has(node.id)
? orderIndex.get(node.id) + 1
: "×";
}
for (const edge of edges) {
let color;
let emissive;
if (!edge.open) {
color = 0xef476f;
emissive = 0x571426;
} else if (edge.id === currentVia) {
color = 0xffe066;
emissive = 0x695607;
} else if (usedTreeEdges.has(edge.id)) {
color = 0x75e6a7;
emissive = 0x174c2f;
} else if (
visited.has(edge.from) &&
visited.has(edge.to)
) {
color = 0x38d6c5;
emissive = 0x104541;
} else {
color = 0x34495c;
emissive = 0x101d29;
}
edge.solidMaterial.color.setHex(color);
edge.solidMaterial.emissive.setHex(emissive);
edge.solidMaterial.emissiveIntensity = 0.42;
edge.dashMaterial.color.setHex(color);
edge.dashMaterial.emissive.setHex(emissive);
edge.solid.visible = edge.open;
for (const dash of edge.dashMeshes) {
dash.visible = !edge.open;
}
edge.label.classList.toggle("closed", !edge.open);
}
}
// -------------------------------------------------------------------------
// Trace animation
// -------------------------------------------------------------------------
let traceTimer = null;
const reduceMotion = window.matchMedia(
"(prefers-reduced-motion: reduce)"
).matches;
function stopTraceAnimation() {
if (traceTimer !== null) {
clearInterval(traceTimer);
traceTimer = null;
}
}
function startTraceAnimation() {
stopTraceAnimation();
state.traceIndex = 0;
updateTraceClasses();
updateSceneState();
const lastIndex = state.traversal.order.length - 1;
if (reduceMotion) {
state.traceIndex = lastIndex;
updateTraceClasses();
updateSceneState();
return;
}
if (lastIndex === 0) return;
traceTimer = setInterval(() => {
if (state.traceIndex >= lastIndex) {
stopTraceAnimation();
return;
}
state.traceIndex += 1;
updateTraceClasses();
updateSceneState();
if (state.traceIndex >= lastIndex) {
stopTraceAnimation();
}
}, 720);
}
function refreshState(animate = true) {
state.traversal = computeBfs(state.start);
state.traceIndex = 0;
renderEdgeStates();
renderReachability();
renderTrace();
updateSceneState();
if (animate) {
startTraceAnimation();
}
}
function setStart(nodeId) {
state.start = nodeId;
startSelect.value = nodeId;
refreshState(true);
}
function toggleEdge(edge) {
edge.open = !edge.open;
refreshState(true);
}
startSelect.addEventListener("change", (event) => {
setStart(event.target.value);
});
document.querySelector("#resetButton").addEventListener("click", () => {
for (const edge of edges) {
edge.open = true;
}
state.start = "A";
startSelect.value = "A";
refreshState(true);
});
document.querySelector("#replayButton").addEventListener("click", () => {
startTraceAnimation();
});
// -------------------------------------------------------------------------
// Custom camera controls: orbit, pan, and zoom.
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let dragState = null;
canvas.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0 && event.button !== 2) return;
event.preventDefault();
dragState = {
id: event.pointerId,
startX: event.clientX,
startY: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
moved: false,
mode: event.button === 2 || event.shiftKey ? "pan" : "orbit"
};
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragState || dragState.id !== event.pointerId) return;
const totalX = event.clientX - dragState.startX;
const totalY = event.clientY - dragState.startY;
if (Math.hypot(totalX, totalY) > 4) {
dragState.moved = true;
}
const deltaX = event.clientX - dragState.lastX;
const deltaY = event.clientY - dragState.lastY;
dragState.lastX = event.clientX;
dragState.lastY = event.clientY;
if (!dragState.moved) return;
if (dragState.mode === "orbit") {
cameraState.theta -= deltaX * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - deltaY * 0.006,
0.28,
1.42
);
} else {
updateCamera();
const right = new THREE.Vector3()
.setFromMatrixColumn(camera.matrixWorld, 0);
const up = new THREE.Vector3()
.setFromMatrixColumn(camera.matrixWorld, 1);
const panScale = cameraState.radius * 0.0014;
cameraState.target
.addScaledVector(right, -deltaX * panScale)
.addScaledVector(up, deltaY * panScale);
cameraState.target.x = THREE.MathUtils.clamp(
cameraState.target.x,
-6,
6
);
cameraState.target.z = THREE.MathUtils.clamp(
cameraState.target.z,
-5,
6
);
cameraState.target.y = 0;
}
updateCamera();
});
canvas.addEventListener("pointerup", (event) => {
if (!dragState || dragState.id !== event.pointerId) return;
const shouldPick =
!dragState.moved &&
dragState.mode === "orbit" &&
event.button === 0;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
dragState = null;
if (shouldPick) {
pickAt(event.clientX, event.clientY);
}
});
canvas.addEventListener("pointercancel", () => {
dragState = null;
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
6,
23
);
updateCamera();
},
{ passive: false }
);
function pickAt(clientX, clientY) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(
[...pickNodeMeshes, ...pickEdgeMeshes],
false
);
const nodeHit = hits.find(
(hit) => hit.object.userData.kind === "node"
);
const edgeHit = hits.find(
(hit) => hit.object.userData.kind === "edge"
);
// Give node hit targets a small priority over nearby edge surfaces.
if (
nodeHit &&
(!edgeHit || nodeHit.distance <= edgeHit.distance + 0.22)
) {
setStart(nodeHit.object.userData.nodeId);
} else if (edgeHit) {
const edge = edgeById.get(edgeHit.object.userData.edgeId);
if (edge) toggleEdge(edge);
}
}
// -------------------------------------------------------------------------
// Screen-space projection for HTML labels
// -------------------------------------------------------------------------
const projected = new THREE.Vector3();
function placeLabel(label, worldPosition) {
projected.copy(worldPosition).project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.2 &&
Math.abs(projected.y) < 1.2;
label.style.display = visible ? "flex" : "none";
if (!visible) return;
const rect = canvas.getBoundingClientRect();
label.style.left =
`${rect.left + (projected.x * 0.5 + 0.5) * rect.width}px`;
label.style.top =
`${rect.top + (-projected.y * 0.5 + 0.5) * rect.height}px`;
}
function updateLabels() {
for (const node of nodeDefinitions) {
placeLabel(node.label, node.labelAnchor);
}
for (const edge of edges) {
placeLabel(edge.label, edge.labelAnchor);
}
}
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
updateCamera();
}
window.addEventListener("resize", resize);
resize();
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const time = clock.getElapsedTime();
const currentNodeId = state.traversal?.order[state.traceIndex]?.node;
for (const node of nodeDefinitions) {
let scale = 1;
if (node.id === currentNodeId) {
scale = 1.1 + Math.sin(time * 4.2) * 0.045;
} else if (node.id === state.start) {
scale = 1.035 + Math.sin(time * 2.5) * 0.025;
}
node.body.scale.setScalar(scale);
}
updateCamera();
updateLabels();
renderer.render(scene, camera);
}
refreshState(true);
animate();
</script>
</body>
</html>
```