Prompt specification
Build or customize the Three.js 3D scene "Tree insertion and lookup 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: Tree insertion and lookup explorer
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/tree-insertion-and-lookup-explorer-x1916
Scene Description Prompt:
Tree insertion and lookup explorer. Let users insert distinct keys into a bounded search tree, then trace comparisons; verify the ordering invariant and state how duplicate keys are handled. Please build this with Three.js from cdnjs in one self-contained HTML file, using visible voxel blocks.
Working Three.js Starter (tree-insertion-and-lookup-explorer-x1916):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Search Tree Explorer</title>
<style>
:root {
color-scheme: dark;
--bg: #070b14;
--panel: rgba(13, 19, 33, 0.96);
--panel-2: rgba(21, 29, 48, 0.78);
--line: rgba(148, 163, 184, 0.15);
--text: #eef4ff;
--muted: #8e9bb4;
--cyan: #4be3cf;
--blue: #7188ff;
--violet: #b67cff;
--red: #ff6b83;
--amber: #ffc857;
--green: #60e6a8;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 82% 12%, rgba(83, 70, 180, 0.16), transparent 32%),
radial-gradient(circle at 22% 90%, rgba(28, 170, 167, 0.10), transparent 35%),
var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input,
select {
font: inherit;
}
button {
color: inherit;
}
#app {
display: grid;
grid-template-columns: 350px minmax(0, 1fr);
width: 100%;
height: 100dvh;
}
.sidebar {
position: relative;
z-index: 5;
overflow-y: auto;
padding: 24px 22px 28px;
border-right: 1px solid var(--line);
background:
linear-gradient(180deg, rgba(18, 26, 44, 0.97), rgba(9, 14, 25, 0.98)),
var(--panel);
box-shadow: 18px 0 45px rgba(0, 0, 0, 0.16);
scrollbar-width: thin;
scrollbar-color: #34415c transparent;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
margin-bottom: 20px;
}
.brand-mark {
position: relative;
width: 42px;
height: 42px;
flex: 0 0 auto;
}
.brand-mark i {
position: absolute;
display: block;
width: 18px;
height: 18px;
border: 1px solid rgba(255, 255, 255, 0.25);
border-radius: 3px;
transform: rotate(30deg) skew(-8deg, -8deg);
box-shadow: inset -3px -3px 0 rgba(0, 0, 0, 0.18);
}
.brand-mark i:nth-child(1) {
left: 1px;
top: 13px;
background: var(--violet);
}
.brand-mark i:nth-child(2) {
left: 20px;
top: 2px;
background: var(--blue);
}
.brand-mark i:nth-child(3) {
left: 20px;
top: 23px;
background: var(--cyan);
}
h1 {
margin: 0;
font-size: 19px;
line-height: 1.15;
letter-spacing: -0.02em;
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font-size: 12px;
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.section {
margin-top: 22px;
padding-top: 20px;
border-top: 1px solid var(--line);
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}
.section-heading h2 {
margin: 0;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.section-heading small {
color: var(--muted);
font-size: 10px;
}
.key-row {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 9px;
}
.key-input {
min-width: 0;
height: 44px;
padding: 0 13px;
border: 1px solid #34415b;
border-radius: 10px;
outline: none;
background: #0b1220;
color: var(--text);
font: 700 15px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
transition: border-color 150ms, box-shadow 150ms;
}
.key-input:focus {
border-color: var(--cyan);
box-shadow: 0 0 0 3px rgba(75, 227, 207, 0.11);
}
.button {
min-height: 40px;
padding: 0 13px;
border: 1px solid #34415b;
border-radius: 9px;
background: #182238;
color: var(--text);
cursor: pointer;
font-size: 12px;
font-weight: 750;
transition: transform 120ms, border-color 120ms, background 120ms, opacity 120ms;
}
.button:hover:not(:disabled) {
border-color: #64769a;
background: #202c46;
transform: translateY(-1px);
}
.button:active:not(:disabled) {
transform: translateY(0);
}
.button:disabled {
cursor: wait;
opacity: 0.45;
}
.button.primary {
border-color: rgba(75, 227, 207, 0.65);
background: linear-gradient(135deg, #31cbb9, #4599e8);
color: #05121d;
box-shadow: 0 8px 22px rgba(48, 194, 186, 0.13);
}
.button.primary:hover:not(:disabled) {
border-color: #92fff0;
background: linear-gradient(135deg, #50e3d0, #69a9f2);
}
.button.danger {
color: #ff9aaa;
}
.button-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-top: 9px;
}
.full {
width: 100%;
}
.quick-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 7px;
margin-top: 11px;
}
.quick-row > span {
margin-right: 2px;
color: var(--muted);
font-size: 10px;
}
.quick-key {
padding: 5px 9px;
border: 1px solid #34415b;
border-radius: 7px;
background: rgba(24, 34, 56, 0.72);
color: #cbd8ef;
cursor: pointer;
font: 700 11px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.quick-key:hover:not(:disabled) {
border-color: var(--cyan);
color: var(--cyan);
}
.field-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.field-label {
display: block;
margin-bottom: 6px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
}
select {
width: 100%;
height: 38px;
padding: 0 10px;
border: 1px solid #34415b;
border-radius: 8px;
outline: none;
background: #0b1220;
color: var(--text);
cursor: pointer;
font-size: 12px;
}
.hint {
margin: 10px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.hint strong {
color: #cbd7ec;
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
}
.stat {
padding: 10px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(8, 14, 26, 0.55);
}
.stat span {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.stat strong {
font: 750 14px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.trace-box {
min-height: 150px;
max-height: 330px;
overflow-y: auto;
padding: 12px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(5, 10, 20, 0.72);
scrollbar-width: thin;
scrollbar-color: #34415c transparent;
}
.trace-placeholder {
padding: 18px 7px;
color: #72809a;
font-size: 11px;
line-height: 1.6;
text-align: center;
}
.trace-step {
display: grid;
grid-template-columns: 25px minmax(0, 1fr);
gap: 9px;
padding: 9px 0;
border-bottom: 1px solid rgba(148, 163, 184, 0.09);
animation: trace-in 220ms ease-out;
}
.trace-step:last-child {
border-bottom: 0;
}
.step-number {
display: grid;
width: 24px;
height: 24px;
place-items: center;
border: 1px solid #394761;
border-radius: 6px;
background: #121c2f;
color: #95a5c1;
font: 750 9px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.trace-step b {
display: block;
color: #e6eeff;
font: 750 12px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.trace-step small {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.trace-step.left .step-number {
border-color: rgba(182, 124, 255, 0.55);
color: var(--violet);
}
.trace-step.right .step-number {
border-color: rgba(75, 227, 207, 0.55);
color: var(--cyan);
}
.trace-step.match .step-number {
border-color: rgba(96, 230, 168, 0.55);
color: var(--green);
}
.trace-step.duplicate .step-number,
.trace-step.error .step-number {
border-color: rgba(255, 107, 131, 0.55);
color: var(--red);
}
.trace-step.outcome b {
color: var(--cyan);
}
.invariant-card {
padding: 13px;
border: 1px solid rgba(96, 230, 168, 0.24);
border-radius: 10px;
background: rgba(32, 103, 79, 0.09);
}
.invariant-card.failed {
border-color: rgba(255, 107, 131, 0.32);
background: rgba(140, 37, 57, 0.10);
}
.invariant-title {
display: flex;
align-items: center;
gap: 8px;
color: var(--green);
font-size: 12px;
font-weight: 850;
letter-spacing: 0.08em;
}
.invariant-card.failed .invariant-title {
color: var(--red);
}
.invariant-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 13px currentColor;
}
.invariant-card p {
margin: 8px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.55;
}
.formula {
margin-top: 10px !important;
padding: 9px;
border: 1px solid var(--line);
border-radius: 7px;
background: rgba(4, 9, 17, 0.45);
color: #c7d4ed !important;
font: 11px ui-monospace, SFMono-Regular, Menlo, monospace;
text-align: center;
}
.stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 45%, rgba(38, 51, 80, 0.16), transparent 46%),
linear-gradient(145deg, rgba(13, 19, 33, 0.35), rgba(5, 9, 17, 0.2));
}
#viewport {
position: absolute;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
}
.stage-toolbar {
position: absolute;
z-index: 3;
top: 18px;
left: 20px;
right: 20px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 14px;
pointer-events: none;
}
.status-card {
max-width: min(500px, calc(100% - 130px));
padding: 11px 14px;
border: 1px solid rgba(132, 151, 184, 0.19);
border-radius: 11px;
background: rgba(8, 13, 24, 0.78);
box-shadow: 0 10px 28px rgba(0, 0, 0, 0.18);
backdrop-filter: blur(12px);
pointer-events: auto;
}
.status-head {
display: flex;
align-items: center;
gap: 8px;
color: var(--cyan);
font-size: 11px;
font-weight: 850;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.status-head::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 12px currentColor;
content: "";
}
.status-card.success .status-head {
color: var(--green);
}
.status-card.warning .status-head {
color: var(--amber);
}
.status-card.error .status-head {
color: var(--red);
}
.status-detail {
margin-top: 5px;
color: #9aa9c2;
font-size: 10px;
line-height: 1.45;
}
.view-buttons {
display: flex;
gap: 7px;
pointer-events: auto;
}
.view-button {
min-height: 35px;
padding: 0 11px;
border: 1px solid rgba(132, 151, 184, 0.22);
border-radius: 8px;
background: rgba(8, 13, 24, 0.78);
color: #c3d0e6;
cursor: pointer;
font-size: 10px;
font-weight: 750;
backdrop-filter: blur(10px);
}
.view-button:hover {
border-color: var(--cyan);
color: var(--cyan);
}
.legend {
position: absolute;
z-index: 3;
right: 20px;
bottom: 18px;
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 13px;
max-width: calc(100% - 40px);
padding: 9px 12px;
border: 1px solid rgba(132, 151, 184, 0.16);
border-radius: 9px;
background: rgba(8, 13, 24, 0.7);
color: #9cabc3;
font-size: 9px;
backdrop-filter: blur(10px);
pointer-events: none;
}
.legend span {
display: flex;
align-items: center;
gap: 6px;
}
.legend i {
width: 8px;
height: 8px;
border-radius: 2px;
}
.controls-hint {
position: absolute;
z-index: 3;
left: 20px;
bottom: 18px;
color: rgba(174, 188, 210, 0.65);
font-size: 9px;
pointer-events: none;
}
.node-popover {
position: absolute;
z-index: 8;
display: none;
width: 190px;
padding: 12px;
border: 1px solid rgba(148, 163, 184, 0.25);
border-radius: 10px;
background: rgba(8, 13, 24, 0.94);
box-shadow: 0 16px 38px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(14px);
pointer-events: auto;
}
.node-popover.visible {
display: block;
}
.node-popover strong {
display: block;
margin-bottom: 7px;
color: var(--amber);
font: 800 13px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.node-popover p {
margin: 0;
color: #aab8cf;
font-size: 10px;
line-height: 1.55;
}
.popover-close {
position: absolute;
top: 6px;
right: 8px;
border: 0;
background: transparent;
color: #77859d;
cursor: pointer;
font-size: 15px;
}
.toast {
position: absolute;
z-index: 12;
left: 50%;
bottom: 56px;
max-width: calc(100% - 40px);
padding: 10px 14px;
border: 1px solid rgba(75, 227, 207, 0.3);
border-radius: 8px;
background: rgba(9, 19, 31, 0.94);
color: #dce9f8;
font-size: 11px;
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.34);
transform: translate(-50%, 12px);
opacity: 0;
pointer-events: none;
transition: opacity 180ms, transform 180ms;
}
.toast.show {
transform: translate(-50%, 0);
opacity: 1;
}
@keyframes trace-in {
from {
opacity: 0;
transform: translateY(4px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@media (max-width: 900px) {
html,
body {
overflow: auto;
}
#app {
display: flex;
flex-direction: column;
height: auto;
min-height: 100dvh;
}
.stage {
order: 1;
height: 64dvh;
min-height: 470px;
}
.sidebar {
order: 2;
overflow: visible;
border-top: 1px solid var(--line);
border-right: 0;
}
.controls-hint {
display: none;
}
}
@media (max-width: 560px) {
.stage-toolbar {
top: 10px;
left: 10px;
right: 10px;
}
.status-card {
max-width: calc(100% - 85px);
}
.view-button {
padding: 0 9px;
}
.legend {
right: 10px;
bottom: 10px;
}
.sidebar {
padding: 20px 16px 28px;
}
}
</style>
</head>
<body>
<div id="app">
<aside class="sidebar">
<header class="brand">
<div class="brand-mark" aria-hidden="true"><i></i><i></i><i></i></div>
<div>
<h1>Voxel Search Tree</h1>
<p>Insert, search, and inspect ordering</p>
</div>
</header>
<section class="section">
<div class="section-heading">
<h2>Key Operations</h2>
<small>Distinct integers</small>
</div>
<div class="key-row">
<input
id="keyInput"
class="key-input"
type="number"
min="-999"
max="999"
step="1"
value="55"
aria-label="Integer key"
>
<button id="insertButton" class="button primary action-btn">Insert</button>
</div>
<div class="button-grid">
<button id="lookupButton" class="button action-btn">Look up key</button>
<button id="verifyButton" class="button action-btn">Verify order</button>
</div>
<div class="quick-row">
<span>Quick insert</span>
<button class="quick-key action-btn" data-key="55">55</button>
<button class="quick-key action-btn" data-key="24">24</button>
<button class="quick-key action-btn" data-key="68">68</button>
<button class="quick-key action-btn" data-key="36">36</button>
</div>
<p class="hint">
<strong>Duplicate policy:</strong> duplicates are rejected. The original node
and its position are preserved; a repeated key never creates a second node.
</p>
</section>
<section class="section">
<div class="section-heading">
<h2>Tree Bounds</h2>
<small>Changing bounds clears the tree</small>
</div>
<div class="field-grid">
<label>
<span class="field-label">Maximum nodes</span>
<select id="maxNodesSelect">
<option value="12">12 nodes</option>
<option value="20">20 nodes</option>
<option value="31" selected>31 nodes</option>
</select>
</label>
<label>
<span class="field-label">Maximum levels</span>
<select id="maxLevelsSelect">
<option value="5">5 levels</option>
<option value="6">6 levels</option>
<option value="7" selected>7 levels</option>
</select>
</label>
</div>
<p class="hint">
An insertion is rejected if it would exceed either bound.
Lookup remains available for any integer in the range −999 to 999.
</p>
</section>
<section class="section">
<div class="section-heading">
<h2>Tree State</h2>
<small id="capacityText">0 / 31 nodes</small>
</div>
<div class="stats">
<div class="stat">
<span>Nodes</span>
<strong id="nodeCount">0</strong>
</div>
<div class="stat">
<span>Levels</span>
<strong id="treeHeight">0</strong>
</div>
<div class="stat">
<span>Order</span>
<strong id="orderStat">—</strong>
</div>
</div>
</section>
<section class="section">
<div class="section-heading">
<h2>Comparison Trace</h2>
<small id="traceTarget">No target</small>
</div>
<div id="traceBox" class="trace-box">
<div class="trace-placeholder">
Insert or look up a key to see every comparison.
</div>
</div>
</section>
<section class="section">
<div class="section-heading">
<h2>Ordering Invariant</h2>
<small>Subtree bounds</small>
</div>
<div id="invariantCard" class="invariant-card">
<div class="invariant-title">
<span class="invariant-dot"></span>
<span id="invariantTitle">EMPTY TREE</span>
</div>
<p id="invariantDetail">The invariant is vacuously true for an empty tree.</p>
<p class="formula">keys(left(n)) < n.key < keys(right(n))</p>
</div>
</section>
<section class="section">
<div class="button-grid">
<button id="sampleButton" class="button action-btn">Load sample</button>
<button id="clearButton" class="button danger action-btn">Clear tree</button>
</div>
</section>
</aside>
<main class="stage" id="stage">
<div id="viewport"></div>
<div class="stage-toolbar">
<div id="statusCard" class="status-card">
<div id="statusTitle" class="status-head">Ready</div>
<div id="statusDetail" class="status-detail">
Insert a distinct integer key to begin.
</div>
</div>
<div class="view-buttons">
<button id="fitButton" class="view-button">Fit view</button>
</div>
</div>
<div class="controls-hint">
Drag to orbit · Shift/right-drag to pan · Scroll to zoom · Click a voxel to inspect
</div>
<div class="legend">
<span><i style="background:#b67cff"></i>left comparison</span>
<span><i style="background:#4be3cf"></i>right comparison</span>
<span><i style="background:#60e6a8"></i>match / inserted</span>
<span><i style="background:#ff6b83"></i>duplicate</span>
</div>
<div id="nodePopover" class="node-popover">
<button id="popoverClose" class="popover-close" aria-label="Close">×</button>
<strong id="popoverKey">KEY</strong>
<p id="popoverInfo"></p>
</div>
<div id="toast" class="toast"></div>
</main>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// DOM and state
// -------------------------------------------------------------------------
const $ = (id) => document.getElementById(id);
const viewport = $("viewport");
const stage = $("stage");
const keyInput = $("keyInput");
const insertButton = $("insertButton");
const lookupButton = $("lookupButton");
const verifyButton = $("verifyButton");
const maxNodesSelect = $("maxNodesSelect");
const maxLevelsSelect = $("maxLevelsSelect");
const traceBox = $("traceBox");
const traceTarget = $("traceTarget");
const invariantCard = $("invariantCard");
const invariantTitle = $("invariantTitle");
const invariantDetail = $("invariantDetail");
const statusCard = $("statusCard");
const statusTitle = $("statusTitle");
const statusDetail = $("statusDetail");
const nodePopover = $("nodePopover");
const popoverKey = $("popoverKey");
const popoverInfo = $("popoverInfo");
const toastElement = $("toast");
class TreeNode {
constructor(key) {
this.key = key;
this.left = null;
this.right = null;
}
}
const state = {
root: null,
count: 0,
maxNodes: 31,
maxDepth: 6,
operationToken: 0,
busy: false,
nodeMeshes: new Map(),
edgeMeshes: new Map(),
positions: new Map(),
interactiveMeshes: [],
selectedKey: null,
lastVerification: null
};
const COLORS = {
violet: 0xb67cff,
cyan: 0x4be3cf,
green: 0x60e6a8,
red: 0xff6b83,
amber: 0xffc857,
edge: 0x50658d,
edgeLeft: 0x8c63c9,
edgeRight: 0x278f88
};
const NODE_PALETTE = [
0x6957d9,
0x3974c9,
0x138f89,
0x8650cf,
0xb64f82,
0x3f8eac
];
// -------------------------------------------------------------------------
// Three.js setup
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.fog = new THREE.FogExp2(0x08101d, 0.014);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 200);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute("aria-label", "Interactive three-dimensional search tree");
viewport.appendChild(renderer.domElement);
const ambient = new THREE.HemisphereLight(0xb9d7ff, 0x11101d, 1.45);
scene.add(ambient);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.4);
keyLight.position.set(8, 14, 12);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -30;
keyLight.shadow.camera.right = 30;
keyLight.shadow.camera.top = 25;
keyLight.shadow.camera.bottom = -25;
keyLight.shadow.camera.near = 0.1;
keyLight.shadow.camera.far = 70;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x6e7dff, 1.25);
rimLight.position.set(-12, 5, -10);
scene.add(rimLight);
const cyanLight = new THREE.PointLight(0x39e0ce, 18, 40, 2);
cyanLight.position.set(-10, 3, 9);
scene.add(cyanLight);
const unitCubeGeometry = new THREE.BoxGeometry(1, 1, 1);
const floorMaterial = new THREE.MeshStandardMaterial({
color: 0x0a1220,
roughness: 0.92,
metalness: 0.05,
transparent: true,
opacity: 0.72
});
const floor = new THREE.Mesh(new THREE.PlaneGeometry(100, 100), floorMaterial);
floor.rotation.x = -Math.PI / 2;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(80, 80, 0x293957, 0x142137);
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
function updateFloor() {
const rootY = 4.4;
const levelGap = 1.45;
const floorY = rootY - state.maxDepth * levelGap - 0.74;
floor.position.y = floorY;
grid.position.y = floorY + 0.012;
}
updateFloor();
// -------------------------------------------------------------------------
// Camera controls implemented directly in this file
// -------------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(0, 1.5, 0),
radius: 15,
yaw: -0.08,
pitch: 0.11
};
function updateCamera() {
const cp = Math.cos(cameraState.pitch);
camera.position.set(
cameraState.target.x +
cameraState.radius * Math.sin(cameraState.yaw) * cp,
cameraState.target.y +
cameraState.radius * Math.sin(cameraState.pitch),
cameraState.target.z +
cameraState.radius * Math.cos(cameraState.yaw) * cp
);
camera.lookAt(cameraState.target);
camera.updateMatrixWorld();
}
function fitCamera() {
const points = [...state.positions.values()];
if (!points.length) {
cameraState.target.set(0, 1.4, 0);
cameraState.radius = 14;
cameraState.yaw = -0.08;
cameraState.pitch = 0.11;
updateCamera();
return;
}
const xs = points.map((p) => p.x);
const ys = points.map((p) => p.y);
const minX = Math.min(...xs);
const maxX = Math.max(...xs);
const minY = Math.min(...ys);
const maxY = Math.max(...ys);
const width = maxX - minX + 1.7;
const height = maxY - minY + 1.5;
const verticalFov = THREE.MathUtils.degToRad(camera.fov);
const distance = Math.max(
width / (2 * Math.tan(verticalFov / 2) * camera.aspect),
height / (2 * Math.tan(verticalFov / 2))
) * 1.12 + 1.5;
cameraState.target.set((minX + maxX) / 2, (minY + maxY) / 2, 0);
cameraState.radius = THREE.MathUtils.clamp(distance, 6, 90);
cameraState.yaw = -0.08;
cameraState.pitch = 0.11;
updateCamera();
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const drag = {
active: false,
moved: false,
button: 0,
startX: 0,
startY: 0,
previousX: 0,
previousY: 0
};
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
drag.active = true;
drag.moved = false;
drag.button = event.button;
drag.startX = event.clientX;
drag.startY = event.clientY;
drag.previousX = event.clientX;
drag.previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!drag.active) return;
const dx = event.clientX - drag.previousX;
const dy = event.clientY - drag.previousY;
drag.previousX = event.clientX;
drag.previousY = event.clientY;
if (
Math.hypot(
event.clientX - drag.startX,
event.clientY - drag.startY
) > 5
) {
drag.moved = true;
}
const wantsPan = drag.button === 2 || event.shiftKey;
if (wantsPan) {
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0);
const up = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 1);
const panScale = cameraState.radius * 0.0012;
cameraState.target
.addScaledVector(right, -dx * panScale)
.addScaledVector(up, dy * panScale);
} else {
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
-0.62,
1.18
);
}
updateCamera();
hidePopover();
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (!drag.active) return;
drag.active = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
if (!drag.moved) {
inspectNodeAt(event);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
drag.active = false;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
4,
90
);
updateCamera();
},
{ passive: false }
);
// -------------------------------------------------------------------------
// Tree operations
// -------------------------------------------------------------------------
function findPath(key) {
const path = [];
let node = state.root;
while (node) {
path.push(node);
if (key === node.key) {
return { path, found: true };
}
node = key < node.key ? node.left : node.right;
}
return { path, found: false };
}
function insertIntoModel(key) {
const node = new TreeNode(key);
if (!state.root) {
state.root = node;
} else {
const { path } = findPath(key);
const parent = path[path.length - 1];
const direction = key > parent.key ? "right" : "left";
parent[direction] = node;
}
state.count += 1;
}
function getTreeHeight() {
if (!state.root) return 0;
function height(node) {
if (!node) return 0;
return 1 + Math.max(height(node.left), height(node.right));
}
return height(state.root);
}
function verifyTree() {
const issues = [];
const nodeOrder = [];
const issueNodeKeys = new Set();
let checks = 0;
function walk(node) {
if (!node) {
return {
min: Infinity,
max: -Infinity,
size: 0
};
}
nodeOrder.push(node.key);
const left = walk(node.left);
const right = walk(node.right);
if (left.size > 0) {
checks += 1;
if (!(left.max < node.key)) {
const message = `Node ${node.key}: left subtree maximum ${left.max} is not smaller.`;
issues.push(message);
issueNodeKeys.add(node.key);
}
}
if (right.size > 0) {
checks += 1;
if (!(right.min > node.key)) {
const message = `Node ${node.key}: right subtree minimum ${right.min} is not larger.`;
issues.push(message);
issueNodeKeys.add(node.key);
}
}
return {
min: Math.min(node.key, left.min, right.min),
max: Math.max(node.key, left.max, right.max),
size: left.size + right.size + 1
};
}
walk(state.root);
const inorder = [];
function inorderWalk(node) {
if (!node) return;
inorderWalk(node.left);
inorder.push(node.key);
inorderWalk(node.right);
}
inorderWalk(state.root);
for (let i = 1; i < inorder.length; i += 1) {
if (inorder[i] <= inorder[i - 1]) {
issues.push(
`In-order traversal is not strictly increasing near ${inorder[i - 1]} and ${inorder[i]}.`
);
break;
}
}
return {
valid: issues.length === 0,
issues,
nodeOrder,
issueNodeKeys,
checks,
inorder
};
}
// -------------------------------------------------------------------------
// Voxel rendering
// -------------------------------------------------------------------------
function createLabelTexture(key) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "rgba(5, 11, 23, 0.94)";
ctx.fillRect(8, 20, 240, 88);
ctx.strokeStyle = "rgba(220, 235, 255, 0.32)";
ctx.lineWidth = 4;
ctx.strokeRect(8, 20, 240, 88);
ctx.fillStyle = "#f3f7ff";
ctx.font = "bold 56px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(String(key), 128, 65);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
return texture;
}
function disposeMaterial(material) {
if (!material) return;
if (Array.isArray(material)) {
material.forEach(disposeMaterial);
return;
}
if (material.map) material.map.dispose();
material.dispose();
}
function createNodeGroup(node, depth) {
const group = new THREE.Group();
group.userData.key = node.key;
const baseColor = new THREE.Color(
NODE_PALETTE[depth % NODE_PALETTE.length]
);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: baseColor,
roughness: 0.42,
metalness: 0.22,
emissive: 0x000000,
emissiveIntensity: 0
});
const capMaterial = new THREE.MeshStandardMaterial({
color: baseColor.clone().lerp(new THREE.Color(0xffffff), 0.38),
roughness: 0.38,
metalness: 0.18
});
const portMaterial = new THREE.MeshStandardMaterial({
color: baseColor.clone().lerp(new THREE.Color(0x07101d), 0.42),
roughness: 0.55,
metalness: 0.25
});
const body = new THREE.Mesh(unitCubeGeometry, bodyMaterial);
body.scale.set(0.74, 0.74, 0.74);
body.castShadow = true;
body.receiveShadow = true;
body.userData.key = node.key;
group.add(body);
const cap = new THREE.Mesh(unitCubeGeometry, capMaterial);
cap.position.y = 0.48;
cap.scale.set(0.42, 0.2, 0.42);
cap.castShadow = true;
cap.userData.key = node.key;
group.add(cap);
const foot = new THREE.Mesh(unitCubeGeometry, portMaterial);
foot.position.y = -0.45;
foot.scale.set(0.38, 0.16, 0.38);
foot.castShadow = true;
group.add(foot);
const leftPort = new THREE.Mesh(unitCubeGeometry, portMaterial);
leftPort.position.x = -0.48;
leftPort.scale.set(0.18, 0.22, 0.18);
leftPort.userData.key = node.key;
group.add(leftPort);
const rightPort = new THREE.Mesh(unitCubeGeometry, portMaterial);
rightPort.position.x = 0.48;
rightPort.scale.set(0.18, 0.22, 0.18);
rightPort.userData.key = node.key;
group.add(rightPort);
const labelMaterial = new THREE.SpriteMaterial({
map: createLabelTexture(node.key),
transparent: true,
depthTest: false,
depthWrite: false
});
const label = new THREE.Sprite(labelMaterial);
label.position.set(0, 0, 0.49);
label.scale.set(0.76, 0.38, 1);
label.renderOrder = 20;
group.add(label);
group.userData.bodyMaterial = bodyMaterial;
group.userData.body = body;
return group;
}
function createEdge(parentPosition, childPosition, childKey) {
const direction = new THREE.Vector3().subVectors(
childPosition,
parentPosition
);
const length = direction.length();
const material = new THREE.MeshStandardMaterial({
color: COLORS.edge,
roughness: 0.55,
metalness: 0.25,
transparent: true,
opacity: 0.62,
emissive: 0x000000,
emissiveIntensity: 0
});
const edge = new THREE.Mesh(unitCubeGeometry, material);
edge.position.copy(parentPosition).add(childPosition).multiplyScalar(0.5);
edge.scale.set(0.075, length, 0.075);
edge.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
edge.userData.childKey = childKey;
edge.castShadow = true;
return edge;
}
function rebuildScene() {
for (const group of state.nodeMeshes.values()) {
group.traverse((object) => {
if (object.material) disposeMaterial(object.material);
});
scene.remove(group);
}
for (const edge of state.edgeMeshes.values()) {
disposeMaterial(edge.material);
scene.remove(edge);
}
state.nodeMeshes.clear();
state.edgeMeshes.clear();
state.positions.clear();
state.interactiveMeshes = [];
if (!state.root) {
hidePopover();
return;
}
const ordered = [];
const depths = new Map();
function collect(node, depth) {
if (!node) return;
depths.set(node.key, depth);
collect(node.left, depth + 1);
ordered.push(node);
collect(node.right, depth + 1);
}
collect(state.root, 0);
const levelGap = 1.45;
const xGap = 1.22;
const rootY = 4.4;
ordered.forEach((node, index) => {
const depth = depths.get(node.key);
const position = new THREE.Vector3(
(index - (ordered.length - 1) / 2) * xGap,
rootY - depth * levelGap,
0
);
const group = createNodeGroup(node, depth);
group.position.copy(position);
group.userData.depth = depth;
state.nodeMeshes.set(node.key, group);
state.positions.set(node.key, position);
state.interactiveMeshes.push(group.userData.body);
scene.add(group);
});
for (const node of ordered) {
for (const child of [node.left, node.right]) {
if (!child) continue;
const edge = createEdge(
state.positions.get(node.key),
state.positions.get(child.key),
child.key
);
state.edgeMeshes.set(child.key, edge);
scene.add(edge);
}
}
}
function setNodeHighlight(key, color, intensity = 0.62) {
const group = state.nodeMeshes.get(key);
if (!group) return;
group.userData.bodyMaterial.emissive.setHex(color);
group.userData.bodyMaterial.emissiveIntensity = intensity;
}
function setEdgeHighlight(childKey, color) {
const edge = state.edgeMeshes.get(childKey);
if (!edge) return;
edge.material.color.setHex(color);
edge.material.emissive.setHex(color);
edge.material.emissiveIntensity = 0.34;
edge.material.opacity = 0.95;
}
function clearHighlights() {
for (const group of state.nodeMeshes.values()) {
group.userData.bodyMaterial.emissive.setHex(0x000000);
group.userData.bodyMaterial.emissiveIntensity = 0;
}
for (const edge of state.edgeMeshes.values()) {
edge.material.color.setHex(COLORS.edge);
edge.material.emissive.setHex(0x000000);
edge.material.emissiveIntensity = 0;
edge.material.opacity = 0.62;
}
}
const tweens = [];
function tweenScale(object, to, duration = 500) {
tweens.push({
object,
from: object.scale.x,
to,
start: performance.now(),
duration
});
}
function updateTweens(now) {
for (let i = tweens.length - 1; i >= 0; i -= 1) {
const tween = tweens[i];
const t = THREE.MathUtils.clamp(
(now - tween.start) / tween.duration,
0,
1
);
const eased = 1 - Math.pow(1 - t, 3);
const value = THREE.MathUtils.lerp(tween.from, tween.to, eased);
tween.object.scale.setScalar(value);
if (t >= 1) tweens.splice(i, 1);
}
}
// -------------------------------------------------------------------------
// Trace and status UI
// -------------------------------------------------------------------------
const sleep = (milliseconds) =>
new Promise((resolve) => setTimeout(resolve, milliseconds));
function setBusy(busy) {
state.busy = busy;
document.querySelectorAll(".action-btn").forEach((button) => {
button.disabled = busy;
});
}
function setStatus(kind, title, detail) {
statusCard.className = `status-card ${kind}`;
statusTitle.textContent = title;
statusDetail.textContent = detail;
}
function beginTrace(title, key) {
traceBox.innerHTML = "";
traceTarget.textContent = key === null ? "No target" : `Target: ${key}`;
const heading = document.createElement("div");
heading.className = "trace-step outcome";
heading.innerHTML = `
<span class="step-number">→</span>
<div>
<b>${title}</b>
<small>Comparing from the root and following BST branches.</small>
</div>
`;
traceBox.appendChild(heading);
}
function appendTraceRow(title, detail, type = "") {
const rows = traceBox.querySelectorAll(".trace-step");
const row = document.createElement("div");
row.className = `trace-step ${type}`;
const number = document.createElement("span");
number.className = "step-number";
number.textContent = String(rows.length).padStart(2, "0");
const content = document.createElement("div");
const strong = document.createElement("b");
const small = document.createElement("small");
strong.textContent = title;
small.textContent = detail;
content.append(strong, small);
row.append(number, content);
traceBox.appendChild(row);
traceBox.scrollTop = traceBox.scrollHeight;
}
function updateStats() {
$("nodeCount").textContent = state.count;
$("treeHeight").textContent = state.count
? `${getTreeHeight()} / ${state.maxDepth + 1}`
: `0 / ${state.maxDepth + 1}`;
$("capacityText").textContent = `${state.count} / ${state.maxNodes} nodes`;
}
function renderInvariant(result) {
state.lastVerification = result;
if (!state.count) {
invariantCard.classList.remove("failed");
invariantTitle.textContent = "EMPTY TREE";
invariantDetail.textContent =
"The invariant is vacuously true for an empty tree.";
$("orderStat").textContent = "EMPTY";
return;
}
if (result.valid) {
invariantCard.classList.remove("failed");
invariantTitle.textContent = "VERIFIED";
invariantDetail.textContent =
`${state.count} nodes; ${result.checks} subtree bounds hold; ` +
"the in-order traversal is strictly increasing.";
$("orderStat").textContent = "OK";
} else {
invariantCard.classList.add("failed");
invariantTitle.textContent = "FAILED";
invariantDetail.textContent = result.issues.join(" ");
$("orderStat").textContent = "BAD";
}
}
function toast(message) {
toastElement.textContent = message;
toastElement.classList.add("show");
clearTimeout(toast.toastTimer);
toast.toastTimer = setTimeout(() => {
toastElement.classList.remove("show");
}, 2400);
}
function highlightComparison(node, direction, color) {
setNodeHighlight(node.key, color, 0.72);
if (direction === "left" && node.left) {
setEdgeHighlight(node.left.key, COLORS.edgeLeft);
}
if (direction === "right" && node.right) {
setEdgeHighlight(node.right.key, COLORS.edgeRight);
}
}
async function runComparisonTrace(key, mode) {
const token = ++state.operationToken;
setBusy(true);
clearHighlights();
hidePopover();
beginTrace(
mode === "insert" ? "Insertion comparison trace" : "Lookup comparison trace",
key
);
setStatus(
"running",
mode === "insert" ? "Tracing insertion" : "Searching",
`Following the search path for key ${key}.`
);
const { path, found } = findPath(key);
for (const node of path) {
if (token !== state.operationToken) return null;
if (key === node.key) {
const isInsert = mode === "insert";
appendTraceRow(
`${key} = ${node.key}`,
isInsert
? "Duplicate rejected. The first occurrence remains unchanged."
: "Exact key match found.",
isInsert ? "duplicate" : "match"
);
setNodeHighlight(node.key, isInsert ? COLORS.red : COLORS.green, 0.8);
await sleep(360);
return { found: true, path, token };
}
if (key < node.key) {
appendTraceRow(
`${key} < ${node.key}`,
"The target is smaller, so descend into the left subtree.",
"left"
);
highlightComparison(node, "left", COLORS.violet);
} else {
appendTraceRow(
`${key} > ${node.key}`,
"The target is larger, so descend into the right subtree.",
"right"
);
highlightComparison(node, "right", COLORS.cyan);
}
await sleep(390);
}
if (token !== state.operationToken) return null;
appendTraceRow(
`Empty child reached for ${key}`,
"No remaining branch can contain the target key.",
"error"
);
await sleep(220);
return { found: false, path, token };
}
async function insertKey(rawKey) {
if (state.busy) return;
const key = Number(rawKey);
if (!Number.isInteger(key) || key < -999 || key > 999) {
setStatus(
"error",
"Invalid key",
"Use a distinct integer from −999 through 999."
);
toast("Keys must be integers between −999 and 999.");
return;
}
const result = await runComparisonTrace(key, "insert");
if (!result) return;
if (result.found) {
setStatus(
"warning",
"Duplicate rejected",
`Key ${key} already exists. The original node is preserved.`
);
setBusy(false);
return;
}
if (state.count >= state.maxNodes) {
appendTraceRow(
"Node capacity reached",
`The tree is bounded at ${state.maxNodes} nodes; insertion was rejected.`,
"duplicate"
);
setStatus(
"error",
"Capacity reached",
`The bounded tree cannot accept another node.`
);
setBusy(false);
return;
}
if (result.path.length > state.maxDepth) {
appendTraceRow(
"Depth capacity reached",
`The tree is bounded at ${state.maxDepth + 1} levels; insertion was rejected.`,
"duplicate"
);
setStatus(
"error",
"Depth limit reached",
`The key would require level ${result.path.length + 1}, beyond the bound.`
);
setBusy(false);
return;
}
insertIntoModel(key);
rebuildScene();
fitCamera();
const insertedGroup = state.nodeMeshes.get(key);
if (insertedGroup) {
insertedGroup.scale.setScalar(0.01);
tweenScale(insertedGroup, 1, 520);
setNodeHighlight(key, COLORS.green, 0.58);
}
const parent = result.path[result.path.length - 1];
const relation = parent
? key < parent.key
? "left"
: "right"
: "root";
appendTraceRow(
`Inserted ${key}`,
parent
? `Placed as the ${relation} child of ${parent.key}.`
: "Placed as the root of the tree.",
"outcome"
);
updateStats();
renderInvariant(verifyTree());
setStatus(
"success",
"Insertion complete",
`Key ${key} was inserted as a new voxel node.`
);
setBusy(false);
}
async function lookupKey(rawKey) {
if (state.busy) return;
const key = Number(rawKey);
if (!Number.isInteger(key) || key < -999 || key > 999) {
setStatus(
"error",
"Invalid key",
"Use an integer from −999 through 999."
);
return;
}
const result = await runComparisonTrace(key, "lookup");
if (!result) return;
if (result.found) {
setStatus(
"success",
"Key found",
`Key ${key} exists in the tree.`
);
} else {
setStatus(
"error",
"Key not found",
`Key ${key} is absent. The comparison path ended at an empty child.`
);
}
setBusy(false);
}
async function verifyOrdering(animated = true) {
if (state.busy) return;
const token = ++state.operationToken;
setBusy(true);
clearHighlights();
beginTrace("Ordering invariant verification", null);
const result = verifyTree();
renderInvariant(result);
setStatus(
"running",
"Verifying ordering",
"Checking every left and right subtree bound."
);
if (animated) {
for (const key of result.nodeOrder) {
if (token !== state.operationToken) return;
const isBad = result.issueNodeKeys.has(key);
setNodeHighlight(key, isBad ? COLORS.red : COLORS.green, 0.56);
await sleep(52);
}
}
if (result.valid) {
appendTraceRow(
"Strict BST ordering verified",
"Every left subtree is smaller, every right subtree is larger, " +
"and the in-order traversal is strictly increasing.",
"outcome"
);
setStatus(
"success",
"Invariant verified",
`${result.checks} subtree bounds hold across ${state.count} nodes.`
);
} else {
appendTraceRow(
"Ordering invariant failed",
result.issues.join(" "),
"error"
);
setStatus(
"error",
"Invariant failed",
result.issues.join(" ")
);
}
setBusy(false);
}
// -------------------------------------------------------------------------
// Reset, sample, and node inspection
// -------------------------------------------------------------------------
function clearTree(showMessage = true) {
state.operationToken += 1;
state.busy = false;
state.root = null;
state.count = 0;
state.selectedKey = null;
rebuildScene();
fitCamera();
updateStats();
renderInvariant(verifyTree());
setBusy(false);
traceBox.innerHTML = `
<div class="trace-placeholder">
Insert or look up a key to see every comparison.
</div>
`;
traceTarget.textContent = "No target";
if (showMessage) {
setStatus(
"success",
"Tree cleared",
"The model and voxel visualization are ready for new keys."
);
}
}
function loadSample(showMessage = true) {
clearTree(false);
const sample = [42, 20, 65, 12, 31, 54, 72, 7, 17];
for (const key of sample) {
insertIntoModel(key);
}
rebuildScene();
fitCamera();
updateStats();
renderInvariant(verifyTree());
beginTrace("Sample tree loaded", null);
appendTraceRow(
`${sample.length} sample keys inserted`,
"Keys were inserted in sequence: 42, 20, 65, 12, 31, 54, 72, 7, 17.",
"outcome"
);
appendTraceRow(
"Ordering checked",
"The current tree satisfies the strict BST subtree invariant.",
"outcome"
);
if (showMessage) {
setStatus(
"success",
"Sample tree loaded",
"Try inserting 55, 24, 68, or looking up an existing key."
);
}
}
function inspectNodeAt(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x =
((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y =
-((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(state.interactiveMeshes, false);
if (!hits.length) {
hidePopover();
return;
}
const key = hits[0].object.userData.key;
const node = findNode(key);
if (!node) return;
state.selectedKey = key;
setNodeHighlight(key, COLORS.amber, 0.72);
const left = node.left ? node.left.key : "—";
const right = node.right ? node.right.key : "—";
const depth = getNodeDepth(key);
popoverKey.textContent = `KEY ${key}`;
popoverInfo.textContent =
`Depth ${depth} • left: ${left} • right: ${right}`;
const position = state.positions.get(key).clone();
position.project(camera);
const x = (position.x * 0.5 + 0.5) * rect.width + 14;
const y = (-position.y * 0.5 + 0.5) * rect.height - 20;
nodePopover.style.left = `${Math.min(x, rect.width - 205)}px`;
nodePopover.style.top = `${Math.max(10, y)}px`;
nodePopover.classList.add("visible");
}
function findNode(key) {
let node = state.root;
while (node) {
if (node.key === key) return node;
node = key < node.key ? node.left : node.right;
}
return null;
}
function getNodeDepth(key) {
let node = state.root;
let depth = 0;
while (node) {
if (node.key === key) return depth;
node = key < node.key ? node.left : node.right;
depth += 1;
}
return depth;
}
function hidePopover() {
nodePopover.classList.remove("visible");
}
// -------------------------------------------------------------------------
// Events
// -------------------------------------------------------------------------
insertButton.addEventListener("click", () => {
insertKey(keyInput.value);
});
lookupButton.addEventListener("click", () => {
lookupKey(keyInput.value);
});
verifyButton.addEventListener("click", () => {
verifyOrdering(true);
});
keyInput.addEventListener("keydown", (event) => {
if (event.key === "Enter") {
event.preventDefault();
insertKey(keyInput.value);
}
});
document.querySelectorAll(".quick-key").forEach((button) => {
button.addEventListener("click", () => {
keyInput.value = button.dataset.key;
insertKey(button.dataset.key);
});
});
maxNodesSelect.addEventListener("change", () => {
state.maxNodes = Number(maxNodesSelect.value);
clearTree(false);
updateFloor();
fitCamera();
setStatus(
"info",
"Bounds updated",
`The tree is now limited to ${state.maxNodes} nodes.`
);
});
maxLevelsSelect.addEventListener("change", () => {
state.maxDepth = Number(maxLevelsSelect.value) - 1;
clearTree(false);
updateFloor();
fitCamera();
setStatus(
"info",
"Bounds updated",
`The tree is now limited to ${state.maxDepth + 1} levels.`
);
});
$("sampleButton").addEventListener("click", () => loadSample(true));
$("clearButton").addEventListener("click", () => clearTree(true));
$("fitButton").addEventListener("click", fitCamera);
$("popoverClose").addEventListener("click", hidePopover);
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
let previousAspect = 1;
function resize() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
if (Math.abs(camera.aspect - previousAspect) > 0.12) {
previousAspect = camera.aspect;
fitCamera();
}
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(viewport);
resize();
previousAspect = camera.aspect;
loadSample(false);
fitCamera();
updateCamera();
function animate(now) {
requestAnimationFrame(animate);
updateTweens(now);
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```