Prompt specification
Build or customize the Three.js 3D scene "Sort Sticks by Length" 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: Sort Sticks by Length
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/sort-sticks-by-length-x3366
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts comparison and ordering by object attributes. Animate sticks reordered by geometric length with stable endpoints and a shared scale. Include equal lengths and display ties rather than inventing an arbitrary size difference. Voxel style.
Working Three.js Starter (sort-sticks-by-length-x3366):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Attribute Ordering</title>
<style>
:root {
color-scheme: dark;
--bg: #08111f;
--panel: rgba(10, 20, 35, 0.9);
--line: #263a53;
--text: #eef6ff;
--muted: #8fa5bd;
--accent: #67dcff;
--tie: #ffd166;
}
* {
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, sans-serif;
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#viewport canvas.dragging {
cursor: grabbing;
}
.title-card {
position: fixed;
top: 24px;
left: 26px;
z-index: 5;
width: min(440px, calc(100vw - 390px));
pointer-events: none;
text-shadow: 0 2px 18px #000;
}
.eyebrow,
.panel-kicker,
.status {
font: 700 11px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.eyebrow {
color: var(--accent);
}
h1 {
margin: 8px 0 8px;
font-size: clamp(26px, 3vw, 44px);
line-height: 1.02;
letter-spacing: -0.045em;
}
.title-card p {
max-width: 420px;
margin: 0;
color: #b5c5d6;
font-size: 14px;
line-height: 1.55;
}
.scale-pill {
display: inline-flex;
align-items: center;
gap: 8px;
margin-top: 14px;
padding: 7px 10px;
border: 1px solid #294059;
border-radius: 3px;
background: rgba(8, 17, 31, 0.72);
color: #c8d8e9;
font: 600 11px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.scale-pill::before {
content: "";
width: 8px;
height: 8px;
background: var(--accent);
box-shadow: 0 0 12px var(--accent);
}
.panel {
position: fixed;
z-index: 6;
top: 24px;
right: 24px;
width: 330px;
padding: 17px;
border: 1px solid var(--line);
border-radius: 5px;
background: var(--panel);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(14px);
}
.panel-kicker {
display: flex;
justify-content: space-between;
gap: 12px;
color: var(--muted);
font-size: 9px;
}
.panel h2 {
margin: 8px 0 12px;
font-size: 20px;
letter-spacing: -0.025em;
}
.scale-line {
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
gap: 8px;
margin-bottom: 12px;
color: var(--muted);
font: 600 10px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.scale-track {
position: relative;
height: 5px;
border: 1px solid #38506b;
background: repeating-linear-gradient(
90deg,
#38506b 0,
#38506b 9%,
transparent 9%,
transparent 10%
);
}
.scale-track i {
position: absolute;
inset: -3px 0 -3px 0;
border-top: 1px solid var(--accent);
border-bottom: 1px solid var(--accent);
}
.measurement-header,
.measurement-row {
display: grid;
grid-template-columns: 35px 1fr 62px 42px;
align-items: center;
gap: 7px;
}
.measurement-header {
padding: 0 5px 7px;
color: #728ba6;
font: 700 9px ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#rows {
border-top: 1px solid var(--line);
border-bottom: 1px solid var(--line);
}
.measurement-row {
min-height: 45px;
padding: 6px 5px;
border-bottom: 1px solid rgba(38, 58, 83, 0.7);
transition: background 150ms ease;
}
.measurement-row:last-child {
border-bottom: 0;
}
.measurement-row:hover {
background: rgba(103, 220, 255, 0.07);
}
.rank {
color: #90a8c0;
font: 700 12px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.object {
display: grid;
grid-template-columns: 12px 20px 1fr;
align-items: center;
gap: 7px;
min-width: 0;
}
.swatch {
width: 10px;
height: 10px;
border-radius: 1px;
box-shadow: 0 0 8px currentColor;
}
.object b {
font: 800 13px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.object small {
overflow: hidden;
color: #7f96ae;
font: 500 10px ui-monospace, SFMono-Regular, Menlo, monospace;
text-overflow: ellipsis;
white-space: nowrap;
}
.value {
text-align: right;
color: #e9f5ff;
font: 700 12px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.tie-chip {
padding: 3px 4px;
border: 1px solid #6f5a25;
border-radius: 2px;
background: rgba(255, 209, 102, 0.09);
color: var(--tie);
text-align: center;
font: 800 9px ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.06em;
}
#tie-note {
margin-top: 12px;
padding: 10px;
border-left: 3px solid var(--tie);
background: rgba(255, 209, 102, 0.07);
color: #c9d6e4;
font-size: 11px;
line-height: 1.5;
}
#tie-note strong {
color: var(--tie);
}
.stability {
margin-top: 12px;
color: #849bb3;
font-size: 10px;
line-height: 1.5;
}
.stability b {
display: block;
margin-bottom: 3px;
color: #b9cadd;
font: 700 9px ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.1em;
}
.status {
position: fixed;
z-index: 5;
top: 26px;
left: 50%;
padding: 8px 11px;
border: 1px solid #2b4059;
border-radius: 3px;
background: rgba(8, 17, 31, 0.76);
color: #91a6bc;
transform: translateX(-50%);
pointer-events: none;
}
.status.sorted {
border-color: #326378;
color: #7ee6ff;
}
.controls {
position: fixed;
z-index: 6;
bottom: 22px;
left: 26px;
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
button {
appearance: none;
padding: 9px 12px;
border: 1px solid #30465f;
border-radius: 3px;
background: rgba(11, 23, 40, 0.92);
color: #cbdbea;
font: 700 11px ui-monospace, SFMono-Regular, Menlo, monospace;
cursor: pointer;
transition:
border-color 140ms ease,
color 140ms ease,
background 140ms ease,
transform 140ms ease;
}
button:hover,
button:focus-visible {
border-color: var(--accent);
background: #10263b;
color: #fff;
outline: none;
}
button:active {
transform: translateY(1px);
}
button.primary {
border-color: #3c7992;
background: #12354a;
color: #bff3ff;
}
.hint {
margin-left: 3px;
color: #718aa3;
font: 500 10px ui-monospace, SFMono-Regular, Menlo, monospace;
}
@media (max-width: 900px) {
.title-card {
width: calc(100vw - 340px);
}
.title-card p {
display: none;
}
.panel {
width: 290px;
}
.status {
display: none;
}
}
@media (max-width: 700px) {
.title-card {
top: 15px;
left: 15px;
width: calc(100vw - 30px);
}
.title-card h1 {
margin-top: 5px;
font-size: 25px;
}
.scale-pill {
margin-top: 9px;
}
.panel {
top: auto;
right: 12px;
bottom: 78px;
left: 12px;
width: auto;
max-height: 34vh;
overflow: auto;
padding: 12px;
}
.panel h2,
.scale-line,
.stability {
display: none;
}
.measurement-row {
min-height: 36px;
}
.controls {
right: 12px;
bottom: 12px;
left: 12px;
}
.hint {
display: none;
}
}
</style>
</head>
<body>
<div id="viewport"></div>
<header class="title-card">
<div class="eyebrow">Attribute comparison / geometry</div>
<h1>Length is the order key.</h1>
<p>
Five voxel sticks are reordered by the exact distance between their
endpoints. The sticks translate between lanes without scaling or bending.
</p>
<div class="scale-pill">1 voxel = 1.00 unit · one shared scale</div>
</header>
<div id="status" class="status" aria-live="polite">Unsorted · lengths measured</div>
<aside class="panel">
<div class="panel-kicker">
<span>Object attribute</span>
<span>L = |end − start|</span>
</div>
<h2>Geometric length</h2>
<div class="scale-line">
<span>0</span>
<div class="scale-track"><i></i></div>
<span>12 u</span>
</div>
<div class="measurement-header">
<span>Rank</span>
<span>Object</span>
<span style="text-align:right">Length</span>
<span></span>
</div>
<div id="rows"></div>
<div id="tie-note"></div>
<div class="stability">
<b>Stable endpoints</b>
Only each stick’s vertical lane changes. Its two endpoint X coordinates
remain fixed on the common ruler throughout the reorder.
</div>
</aside>
<nav class="controls" aria-label="Scene controls">
<button class="primary" id="sort-asc">Sort ↑ by length</button>
<button id="sort-desc">Sort ↓ by length</button>
<button id="shuffle">Shuffle order</button>
<button id="reset-camera">Reset camera</button>
<span class="hint">Drag to orbit · wheel to zoom · hover to inspect</span>
</nav>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const viewport = document.querySelector("#viewport");
const rowsElement = document.querySelector("#rows");
const tieNoteElement = document.querySelector("#tie-note");
const statusElement = document.querySelector("#status");
const UNIT = 0.48;
const MAX_LENGTH = 12;
const LANES = [4.25, 2.125, 0, -2.125, -4.25];
const definitions = [
{ id: "A", length: 4, color: 0x55d6ff },
{ id: "B", length: 7, color: 0xffa552 },
{ id: "C", length: 7, color: 0xffd166 },
{ id: "D", length: 10, color: 0x9b8cff },
{ id: "E", length: 12, color: 0x5ee6a8 }
];
const definitionById = new Map(
definitions.map((definition) => [definition.id, definition])
);
const initialOrder = ["E", "C", "A", "D", "B"];
const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;
const worldScene = new THREE.Scene();
worldScene.background = new THREE.Color(0x08111f);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false
});
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
viewport.appendChild(renderer.domElement);
renderer.domElement.setAttribute(
"aria-label",
"Interactive three-dimensional voxel sticks ordered by geometric length"
);
const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 100);
const cameraTarget = new THREE.Vector3(2.7, -0.15, 0);
const cameraRadius = 24;
let cameraYaw = 0;
let cameraPitch = 0.08;
let cameraZoom = 1;
function updateCamera() {
camera.position.set(
cameraTarget.x +
Math.sin(cameraYaw) * Math.cos(cameraPitch) * cameraRadius,
cameraTarget.y + Math.sin(cameraPitch) * cameraRadius,
cameraTarget.z +
Math.cos(cameraYaw) * Math.cos(cameraPitch) * cameraRadius
);
camera.lookAt(cameraTarget);
camera.zoom = cameraZoom;
camera.updateProjectionMatrix();
}
function resize() {
const width = innerWidth;
const height = innerHeight;
const aspect = width / height;
renderer.setSize(width, height, false);
const viewHeight =
aspect < 0.75 ? 16 :
aspect < 1.15 ? 13.5 :
11.4;
camera.left = (-viewHeight * aspect) / 2;
camera.right = (viewHeight * aspect) / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
}
addEventListener("resize", resize);
resize();
updateCamera();
const hemisphere = new THREE.HemisphereLight(
0xcbe6ff,
0x101722,
2.1
);
worldScene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(4, 8, 12);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -10;
keyLight.shadow.camera.right = 10;
keyLight.shadow.camera.top = 9;
keyLight.shadow.camera.bottom = -9;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.0003;
worldScene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4da8ff, 1.1);
rimLight.position.set(-7, 3, 4);
worldScene.add(rimLight);
// Voxel-tiled backdrop.
const tileSize = 0.62;
const wallColumns = 16;
const wallRows = 18;
const wallGeometry = new THREE.BoxGeometry(
tileSize * 0.94,
tileSize * 0.94,
0.16
);
const wallMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 1,
metalness: 0
});
const wall = new THREE.InstancedMesh(
wallGeometry,
wallMaterial,
wallColumns * wallRows
);
const matrixHelper = new THREE.Object3D();
const tileColorA = new THREE.Color(0x101c2b);
const tileColorB = new THREE.Color(0x132234);
let tileIndex = 0;
for (let row = 0; row < wallRows; row++) {
for (let column = 0; column < wallColumns; column++) {
matrixHelper.position.set(
-0.9 + column * tileSize,
-5.12 + row * tileSize,
-1.05
);
matrixHelper.updateMatrix();
wall.setMatrixAt(tileIndex, matrixHelper.matrix);
wall.setColorAt(
tileIndex,
(row + column) % 2 === 0 ? tileColorA : tileColorB
);
tileIndex++;
}
}
wall.instanceMatrix.needsUpdate = true;
wall.instanceColor.needsUpdate = true;
wall.receiveShadow = true;
worldScene.add(wall);
// Raised voxel platform.
const platform = new THREE.Mesh(
new THREE.BoxGeometry(11.6, 0.48, 3.0),
new THREE.MeshStandardMaterial({
color: 0x15283b,
roughness: 0.92
})
);
platform.position.set(2.8, -5.95, -0.15);
platform.receiveShadow = true;
platform.castShadow = true;
worldScene.add(platform);
const platformTileGeometry = new THREE.BoxGeometry(0.53, 0.08, 0.53);
const platformTileMaterial = new THREE.MeshStandardMaterial({
color: 0x20364b,
roughness: 0.9
});
const platformTiles = new THREE.InstancedMesh(
platformTileGeometry,
platformTileMaterial,
20 * 5
);
tileIndex = 0;
for (let row = 0; row < 5; row++) {
for (let column = 0; column < 20; column++) {
matrixHelper.position.set(
-1.5 + column * 0.56,
-5.67,
-1.25 + row * 0.56
);
matrixHelper.updateMatrix();
platformTiles.setMatrixAt(tileIndex, matrixHelper.matrix);
tileIndex++;
}
}
platformTiles.instanceMatrix.needsUpdate = true;
platformTiles.receiveShadow = true;
worldScene.add(platformTiles);
function roundedRect(context, x, y, width, height, radius) {
context.beginPath();
context.moveTo(x + radius, y);
context.lineTo(x + width - radius, y);
context.quadraticCurveTo(x + width, y, x + width, y + radius);
context.lineTo(x + width, y + height - radius);
context.quadraticCurveTo(
x + width,
y + height,
x + width - radius,
y + height
);
context.lineTo(x + radius, y + height);
context.quadraticCurveTo(x, y + height, x, y + height - radius);
context.lineTo(x, y + radius);
context.quadraticCurveTo(x, y, x + radius, y);
context.closePath();
}
function createLabelSprite(accent, initialText, initialBadge = "—", tie = false) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.renderOrder = 30;
function setText(text, badge = "—", isTie = false) {
context.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(context, 3, 5, 506, 118, 12);
context.fillStyle = "rgba(7, 15, 27, 0.91)";
context.fill();
context.strokeStyle = isTie ? "#ffd166" : "#34506d";
context.lineWidth = isTie ? 4 : 2;
context.stroke();
context.fillStyle = accent;
context.fillRect(14, 18, 7, 92);
context.fillStyle = "#f1f8ff";
context.font = "700 34px ui-monospace, SFMono-Regular, Menlo, monospace";
context.textBaseline = "middle";
context.fillText(text, 35, 48);
context.textAlign = "center";
context.font = "800 23px ui-monospace, SFMono-Regular, Menlo, monospace";
context.fillStyle = isTie ? "#ffd166" : "#b9cde0";
context.fillText(badge, 433, 48);
if (isTie) {
context.textAlign = "left";
context.font = "800 18px ui-monospace, SFMono-Regular, Menlo, monospace";
context.fillStyle = "#ffd166";
context.fillText("EXACT TIE", 35, 91);
}
texture.needsUpdate = true;
}
setText(initialText, initialBadge, tie);
return { sprite, setText };
}
function createStaticSprite(text, color = "#829ab3", scale = 0.5) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 96;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = color;
context.font = "700 34px ui-monospace, SFMono-Regular, Menlo, monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 128, 48);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(scale, scale * 0.375, 1);
sprite.renderOrder = 25;
return sprite;
}
// Segmented lane guides.
const guideMaterial = new THREE.MeshBasicMaterial({
color: 0x263d55,
transparent: true,
opacity: 0.75
});
const guideGeometry = new THREE.BoxGeometry(0.37, 0.035, 0.07);
const maximumX = MAX_LENGTH * UNIT;
for (const laneY of LANES) {
for (let x = -0.28; x < maximumX + 0.65; x += 0.46) {
const guide = new THREE.Mesh(guideGeometry, guideMaterial);
guide.position.set(x, laneY, -0.42);
worldScene.add(guide);
}
}
// Shared vertical origin.
const originGeometry = new THREE.BoxGeometry(0.055, 0.28, 0.07);
const originMaterial = new THREE.MeshBasicMaterial({
color: 0x4a7897
});
for (let y = -4.75; y < 4.9; y += 0.38) {
const originDash = new THREE.Mesh(originGeometry, originMaterial);
originDash.position.set(0, y, -0.39);
worldScene.add(originDash);
}
// Shared horizontal ruler.
const rulerY = -5.18;
const rulerBaseMaterial = new THREE.MeshBasicMaterial({
color: 0x36516c
});
for (let x = 0; x <= maximumX; x += 0.43) {
const segment = new THREE.Mesh(
new THREE.BoxGeometry(0.34, 0.045, 0.08),
rulerBaseMaterial
);
segment.position.set(x, rulerY, 0.02);
worldScene.add(segment);
}
for (let unit = 0; unit <= MAX_LENGTH; unit++) {
const major = unit % 2 === 0;
const tick = new THREE.Mesh(
new THREE.BoxGeometry(0.035, major ? 0.22 : 0.12, 0.09),
new THREE.MeshBasicMaterial({
color: major ? 0x78dfff : 0x4c6e89
})
);
tick.position.set(unit * UNIT, rulerY + 0.09, 0.05);
worldScene.add(tick);
if (major) {
const label = createStaticSprite(String(unit), "#8ea6bd", 0.46);
label.position.set(unit * UNIT, rulerY - 0.38, 0.12);
worldScene.add(label);
}
}
const scaleLabel = createStaticSprite("1 VOXEL = 1 u", "#67dcff", 1.45);
scaleLabel.position.set(maximumX + 0.65, rulerY - 0.38, 0.12);
worldScene.add(scaleLabel);
const bodyGeometry = new THREE.BoxGeometry(UNIT, 0.48, 0.58);
const endpointGeometry = new THREE.BoxGeometry(0.15, 0.27, 0.66);
const endpointMaterial = new THREE.MeshStandardMaterial({
color: 0xf4fbff,
emissive: 0x8ecfff,
emissiveIntensity: 0.2,
roughness: 0.38,
metalness: 0.08
});
const sticks = [];
const bodyMeshes = [];
for (const definition of definitions) {
const group = new THREE.Group();
group.position.set(0, LANES[initialOrder.indexOf(definition.id)], 0);
const accent = `#${definition.color.toString(16).padStart(6, "0")}`;
for (let index = 0; index < definition.length; index++) {
const color = new THREE.Color(definition.color);
color.offsetHSL(0, 0, index % 2 === 0 ? 0.025 : -0.025);
const material = new THREE.MeshStandardMaterial({
color,
roughness: 0.7,
metalness: 0.04,
flatShading: true,
emissive: 0x000000,
emissiveIntensity: 0
});
const cube = new THREE.Mesh(bodyGeometry, material);
cube.position.set((index + 0.5) * UNIT, 0, 0);
cube.castShadow = true;
cube.receiveShadow = true;
cube.userData.stickId = definition.id;
group.add(cube);
bodyMeshes.push(cube);
}
// These two markers define the measured geometric segment.
const startMarker = new THREE.Mesh(endpointGeometry, endpointMaterial);
startMarker.position.set(0, 0, 0.03);
startMarker.castShadow = true;
group.add(startMarker);
const endMarker = new THREE.Mesh(endpointGeometry, endpointMaterial);
endMarker.position.set(definition.length * UNIT, 0, 0.03);
endMarker.castShadow = true;
group.add(endMarker);
const label = createLabelSprite(
accent,
`${definition.id} | ${definition.length.toFixed(1)} u`,
"RAW"
);
label.sprite.scale.set(2.75, 0.69, 1);
label.sprite.position.set(0.32, 0.59, 0.24);
group.add(label.sprite);
worldScene.add(group);
sticks.push({
definition,
group,
label
});
}
const stickById = new Map(
sticks.map((stick) => [stick.definition.id, stick])
);
// Detect exact ties from the source attributes. No epsilon is introduced.
const lengthBuckets = new Map();
for (const definition of definitions) {
if (!lengthBuckets.has(definition.length)) {
lengthBuckets.set(definition.length, []);
}
lengthBuckets.get(definition.length).push(definition.id);
}
const tieGroups = [...lengthBuckets.entries()]
.filter(([, ids]) => ids.length > 1)
.map(([length, ids]) => ({ length, ids }));
const tieBrackets = [];
for (const tie of tieGroups) {
const group = new THREE.Group();
const endpointX = tie.length * UNIT;
const bracketX = endpointX + 0.3;
const bracketMaterial = new THREE.MeshBasicMaterial({
color: 0xffd166,
depthTest: false
});
const connectors = tie.ids.map(() => {
const connector = new THREE.Mesh(
new THREE.BoxGeometry(0.3, 0.075, 0.075),
bracketMaterial
);
connector.position.x = endpointX + 0.15;
connector.renderOrder = 28;
group.add(connector);
return connector;
});
const dashCount = 11;
const dashes = [];
for (let index = 0; index < dashCount; index++) {
const dash = new THREE.Mesh(
new THREE.BoxGeometry(0.09, 0.09, 0.09),
bracketMaterial
);
dash.position.x = bracketX;
dash.renderOrder = 28;
group.add(dash);
dashes.push(dash);
}
const label = createLabelSprite(
"#ffd166",
`TIE · ${tie.length.toFixed(1)} u`,
"EXACT",
true
);
label.sprite.scale.set(1.65, 0.42, 1);
label.sprite.position.set(bracketX + 0.78, 0, 0.35);
group.add(label.sprite);
worldScene.add(group);
tieBrackets.push({
tie,
group,
connectors,
dashes,
label
});
}
function updateTieBrackets() {
for (const bracket of tieBrackets) {
const endpointYs = bracket.tie.ids.map(
(id) => stickById.get(id).group.position.y
);
const minimumY = Math.min(...endpointYs);
const maximumY = Math.max(...endpointYs);
bracket.connectors.forEach((connector, index) => {
connector.position.y = endpointYs[index];
});
bracket.dashes.forEach((dash, index) => {
dash.position.y = THREE.MathUtils.lerp(
minimumY,
maximumY,
(index + 0.5) / bracket.dashes.length
);
});
bracket.label.sprite.position.y = (minimumY + maximumY) / 2;
}
}
function isTieId(id) {
const length = definitionById.get(id).length;
return lengthBuckets.get(length).length > 1;
}
function computeRanks(order) {
const ranks = new Map();
let previousLength = null;
let currentRank = 0;
order.forEach((id, index) => {
const length = definitionById.get(id).length;
if (length !== previousLength) {
currentRank = index + 1;
}
ranks.set(id, currentRank);
previousLength = length;
});
return ranks;
}
function updateStickLabels(ranks) {
for (const stick of sticks) {
const { id, length } = stick.definition;
const badge = ranks ? `#${ranks.get(id)}` : "RAW";
stick.label.setText(
`${id} | ${length.toFixed(1)} u`,
badge,
isTieId(id)
);
}
}
function updatePanel(order, ranks = null) {
rowsElement.replaceChildren();
for (const id of order) {
const definition = definitionById.get(id);
const row = document.createElement("div");
row.className = "measurement-row";
row.dataset.id = id;
const accent = `#${definition.color.toString(16).padStart(6, "0")}`;
const rank = ranks ? `#${ranks.get(id)}` : "—";
row.innerHTML = `
<div class="rank">${rank}</div>
<div class="object">
<span class="swatch" style="background:${accent};color:${accent}"></span>
<b>${id}</b>
<small>${definition.length} cells</small>
</div>
<div class="value">${definition.length.toFixed(1)} u</div>
<div>${isTieId(id) ? '<span class="tie-chip">TIE</span>' : ""}</div>
`;
row.addEventListener("pointerenter", () => setHover(id));
row.addEventListener("pointerleave", () => setHover(null));
rowsElement.appendChild(row);
}
}
function updateTieNote() {
if (tieGroups.length === 0) {
tieNoteElement.textContent = "No equal lengths detected.";
return;
}
const descriptions = tieGroups.map((tie) => {
const values = tie.ids
.map((id) => `${id} = ${tie.length.toFixed(1)} u`)
.join(" and ");
return `<strong>${values}</strong>`;
});
tieNoteElement.innerHTML = `
${descriptions.join("<br>")}
<br>Identical geometry receives identical rank. No tiny offset or
epsilon difference is added.
`;
}
updateTieNote();
let animation = null;
let currentOrder = initialOrder.slice();
function transitionTo(order, duration = 1000) {
const from = new Map(
sticks.map((stick) => [
stick.definition.id,
stick.group.position.y
])
);
const to = new Map(
order.map((id, index) => [id, LANES[index]])
);
if (reducedMotion || duration === 0) {
for (const stick of sticks) {
stick.group.position.y = to.get(stick.definition.id);
}
animation = null;
return;
}
animation = {
from,
to,
start: performance.now(),
duration
};
}
function applyOrder(order, sorted, modeName, duration = 1000) {
currentOrder = order.slice();
const ranks = sorted ? computeRanks(order) : null;
transitionTo(order, duration);
updateStickLabels(ranks);
updatePanel(order, ranks);
statusElement.textContent = sorted
? `Sorted · ${modeName} length`
: "Unsorted · lengths measured";
statusElement.classList.toggle("sorted", sorted);
}
function sortByLength(mode) {
const sorted = [...definitions].sort((a, b) => {
const difference =
mode === "asc" ? a.length - b.length : b.length - a.length;
// IDs only stabilize traversal among exact ties; they do not change rank.
return difference || a.id.localeCompare(b.id);
});
applyOrder(
sorted.map((definition) => definition.id),
true,
mode === "asc" ? "ascending" : "descending",
1050
);
}
function shuffleOrder() {
const shuffled = [...currentOrder];
for (let index = shuffled.length - 1; index > 0; index--) {
const swapIndex = Math.floor(Math.random() * (index + 1));
[shuffled[index], shuffled[swapIndex]] = [
shuffled[swapIndex],
shuffled[index]
];
}
applyOrder(shuffled, false, "", 850);
}
applyOrder(initialOrder, false, "", 0);
let userInteracted = false;
document.querySelector("#sort-asc").addEventListener("click", () => {
userInteracted = true;
sortByLength("asc");
});
document.querySelector("#sort-desc").addEventListener("click", () => {
userInteracted = true;
sortByLength("desc");
});
document.querySelector("#shuffle").addEventListener("click", () => {
userInteracted = true;
shuffleOrder();
});
document.querySelector("#reset-camera").addEventListener("click", () => {
cameraYaw = 0;
cameraPitch = 0.08;
cameraZoom = 1;
updateCamera();
});
// Demonstrate the reorder automatically, unless the user acts first.
setTimeout(() => {
if (!userInteracted) {
sortByLength("asc");
}
}, 1400);
// Hover inspection.
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let hoveredId = null;
function setHover(id) {
if (hoveredId === id) return;
hoveredId = id;
for (const mesh of bodyMeshes) {
const active = mesh.userData.stickId === id;
mesh.material.emissive.setHex(active ? 0xffffff : 0x000000);
mesh.material.emissiveIntensity = active ? 0.15 : 0;
}
renderer.domElement.style.cursor = id ? "pointer" : "grab";
}
// Camera controls are implemented directly without addons.
let dragging = false;
let previousX = 0;
let previousY = 0;
let movedWhileDragging = false;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
movedWhileDragging = false;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.classList.add("dragging");
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (dragging) {
const deltaX = event.clientX - previousX;
const deltaY = event.clientY - previousY;
if (Math.abs(deltaX) + Math.abs(deltaY) > 2) {
movedWhileDragging = true;
}
previousX = event.clientX;
previousY = event.clientY;
cameraYaw -= deltaX * 0.006;
cameraPitch = THREE.MathUtils.clamp(
cameraPitch + deltaY * 0.004,
-0.35,
0.5
);
updateCamera();
return;
}
const bounds = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - bounds.left) / bounds.width) * 2 - 1;
pointer.y = -((event.clientY - bounds.top) / bounds.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(bodyMeshes, false);
setHover(
intersections.length
? intersections[0].object.userData.stickId
: null
);
});
function endPointer(event) {
dragging = false;
renderer.domElement.classList.remove("dragging");
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener("pointerleave", () => {
if (!dragging) setHover(null);
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraZoom = THREE.MathUtils.clamp(
cameraZoom * Math.exp(-event.deltaY * 0.001),
0.65,
1.65
);
updateCamera();
},
{ passive: false }
);
function render(now) {
requestAnimationFrame(render);
if (animation) {
const progress = THREE.MathUtils.clamp(
(now - animation.start) / animation.duration,
0,
1
);
const eased =
progress < 0.5
? 4 * progress * progress * progress
: 1 - Math.pow(-2 * progress + 2, 3) / 2;
for (const stick of sticks) {
const id = stick.definition.id;
stick.group.position.y = THREE.MathUtils.lerp(
animation.from.get(id),
animation.to.get(id),
eased
);
}
if (progress >= 1) {
animation = null;
}
}
updateTieBrackets();
renderer.render(worldScene, camera);
}
requestAnimationFrame(render);
</script>
</body>
</html>
```