Prompt specification
Build or customize the Three.js 3D scene "Sortable height-block rack" 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: Sortable height-block rack
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/sortable-height-block-rack-x1905
Scene Description Prompt:
Sort low-poly numbered blocks by key while preserving identities, including blocks with equal keys. Create one HTML file with Three.js from cdnjs.
Working Three.js Starter (sortable-height-block-rack-x1905):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stable Sort — Numbered Blocks</title>
<style>
:root {
--ink: #14213d;
--muted: #61708a;
--panel: rgba(255, 255, 255, 0.82);
--border: rgba(35, 55, 85, 0.13);
--accent: #3157d5;
--accent-dark: #213fa6;
--shadow: 0 18px 50px rgba(37, 56, 91, 0.16);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
background:
radial-gradient(circle at 72% 18%, #ffffff 0%, #f2f6ff 32%, #dce7f7 100%);
}
button,
input {
font: inherit;
}
button {
border: 0;
}
#scene {
position: fixed;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
outline: none;
}
#scene:active {
cursor: grabbing;
}
.panel {
position: fixed;
z-index: 10;
border: 1px solid var(--border);
border-radius: 22px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(18px) saturate(135%);
-webkit-backdrop-filter: blur(18px) saturate(135%);
}
.header {
top: 18px;
left: 18px;
width: min(570px, calc(100vw - 36px));
padding: 20px 22px 18px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 7px;
color: var(--accent);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.eyebrow::before {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 0 5px rgba(49, 87, 213, 0.12);
content: "";
}
h1 {
margin: 0;
font-size: clamp(24px, 3vw, 34px);
line-height: 1.05;
letter-spacing: -0.04em;
}
.subtitle {
max-width: 510px;
margin: 9px 0 16px;
color: var(--muted);
font-size: 14px;
line-height: 1.5;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.action {
min-height: 38px;
padding: 9px 13px;
border: 1px solid rgba(35, 55, 85, 0.12);
border-radius: 11px;
color: var(--ink);
background: rgba(255, 255, 255, 0.75);
cursor: pointer;
font-size: 12px;
font-weight: 750;
transition:
transform 150ms ease,
box-shadow 150ms ease,
background 150ms ease,
opacity 150ms ease;
}
.action:hover:not(:disabled) {
transform: translateY(-1px);
background: #fff;
box-shadow: 0 7px 18px rgba(37, 56, 91, 0.12);
}
.action:active:not(:disabled) {
transform: translateY(0);
}
.action.primary {
border-color: transparent;
color: white;
background: var(--accent);
}
.action.primary:hover:not(:disabled) {
background: var(--accent-dark);
}
.action:disabled {
cursor: wait;
opacity: 0.48;
}
.keys-panel {
bottom: 18px;
left: 18px;
width: 320px;
max-height: calc(100vh - 36px);
padding: 18px;
overflow: auto;
}
.panel-heading {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}
.panel-heading h2 {
margin: 0;
font-size: 16px;
letter-spacing: -0.02em;
}
.stable-badge {
padding: 4px 7px;
border-radius: 999px;
color: #16664c;
background: #dff7ed;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.key-list {
display: grid;
gap: 6px;
}
.key-row {
display: grid;
grid-template-columns: 13px 1fr auto 58px;
align-items: center;
gap: 9px;
min-height: 38px;
padding: 6px 8px;
border: 1px solid transparent;
border-radius: 10px;
background: rgba(231, 237, 247, 0.68);
font-size: 12px;
font-weight: 700;
cursor: pointer;
transition: background 150ms ease;
}
.key-row:hover,
.key-row:focus-within {
border-color: rgba(49, 87, 213, 0.18);
background: rgba(255, 255, 255, 0.95);
}
.swatch {
width: 11px;
height: 24px;
border-radius: 5px;
background: var(--block-color);
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.08);
}
.key-arrow {
color: #91a0b8;
font-weight: 500;
}
.key-row input {
width: 58px;
padding: 6px 7px;
border: 1px solid rgba(35, 55, 85, 0.15);
border-radius: 8px;
outline: none;
color: var(--ink);
background: white;
text-align: center;
font-size: 12px;
font-weight: 800;
}
.key-row input:focus {
border-color: var(--accent);
box-shadow: 0 0 0 3px rgba(49, 87, 213, 0.12);
}
details {
margin-top: 14px;
border-top: 1px solid var(--border);
padding-top: 12px;
}
summary {
color: var(--muted);
cursor: pointer;
font-size: 12px;
font-weight: 750;
}
pre {
margin: 10px 0 0;
padding: 11px;
overflow: auto;
border-radius: 10px;
color: #d8e5ff;
background: #17233c;
font-size: 10px;
line-height: 1.55;
}
.status-panel {
right: 18px;
bottom: 18px;
width: min(350px, calc(100vw - 36px));
padding: 18px;
}
.order {
margin: 9px 0 12px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 14px;
font-weight: 800;
line-height: 1.65;
}
.lanes {
display: grid;
gap: 6px;
}
.lane {
display: flex;
align-items: center;
gap: 9px;
padding: 7px 9px;
border-radius: 9px;
color: var(--muted);
background: rgba(231, 237, 247, 0.68);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
}
.key-chip {
flex: 0 0 auto;
padding: 3px 6px;
border-radius: 6px;
color: #2447ae;
background: #e1e9ff;
font-family: inherit;
font-weight: 800;
}
.hint {
margin-top: 12px;
color: #8390a5;
font-size: 11px;
line-height: 1.5;
}
.message {
min-height: 34px;
margin-top: 12px;
padding-top: 11px;
border-top: 1px solid var(--border);
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
@media (max-width: 760px) {
.header {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 15px;
border-radius: 17px;
}
h1 {
font-size: 23px;
}
.subtitle {
margin: 7px 0 12px;
font-size: 12px;
}
.actions {
gap: 6px;
}
.action {
min-height: 34px;
padding: 7px 10px;
font-size: 11px;
}
.keys-panel {
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 34vh;
padding: 13px;
border-radius: 17px;
}
.key-list {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.status-panel {
display: none;
}
}
@media (max-width: 430px) {
.key-list {
grid-template-columns: 1fr;
}
.subtitle {
display: none;
}
}
</style>
</head>
<body>
<canvas
id="scene"
aria-label="Interactive three-dimensional numbered blocks. Drag to orbit, scroll to zoom, and click a block to select it."
></canvas>
<header class="panel header">
<div class="eyebrow">Stable sort laboratory</div>
<h1>Numbered blocks, stable by design.</h1>
<p class="subtitle">
Sort by key without losing identity. Equal-key blocks keep their previous
relative order because the original position is used as the tie-breaker.
</p>
<div class="actions">
<button class="action primary" id="sortAsc" data-action>
Sort ascending
</button>
<button class="action" id="sortDesc" data-action>
Sort descending
</button>
<button class="action" id="reverse" data-action>
Reverse order
</button>
<button class="action" id="shuffle" data-action>
Shuffle keys
</button>
<button class="action" id="reset" data-action>
Reset
</button>
</div>
</header>
<aside class="panel keys-panel">
<div class="panel-heading">
<h2>Block keys</h2>
<span class="stable-badge">Stable</span>
</div>
<div id="keyList" class="key-list"></div>
<details>
<summary>How equal keys are preserved</summary>
<pre><code>items
.map((item, index) => ({ item, index }))
.sort((a, b) =>
(a.item.key - b.item.key) ||
(a.index - b.index)
)
.map(({ item }) => item);</code></pre>
</details>
</aside>
<aside class="panel status-panel" aria-live="polite">
<div class="eyebrow">Identity check</div>
<div id="currentOrder" class="order"></div>
<div id="equalKeys" class="lanes"></div>
<div class="hint">
Drag to orbit · Scroll to zoom · Click a block to select it
</div>
<div id="message" class="message"></div>
</aside>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Data and stable sort
// -------------------------------------------------------------------------
const initialData = [
{ id: "B01", number: 1, key: 3, color: 0xff6b6b },
{ id: "B02", number: 2, key: 1, color: 0x4d96ff },
{ id: "B03", number: 3, key: 2, color: 0xf9c74f },
{ id: "B04", number: 4, key: 1, color: 0x9b5de5 },
{ id: "B05", number: 5, key: 4, color: 0x43aa8b },
{ id: "B06", number: 6, key: 2, color: 0xf8961e },
{ id: "B07", number: 7, key: 1, color: 0x00b894 },
{ id: "B08", number: 8, key: 3, color: 0xe76fbb }
];
let blocks = initialData.map((block) => ({ ...block }));
let blockById = new Map(blocks.map((block) => [block.id, block]));
/**
* A stable sort implemented with the decorate-sort-undecorate pattern.
* The original object references are retained, and equal keys use original
* position as a deterministic tie-breaker.
*/
function stableSortByKey(items, direction = 1) {
return items
.map((item, index) => ({ item, index }))
.sort((a, b) => {
const keyDifference =
(Number(a.item.key) - Number(b.item.key)) * direction;
return keyDifference !== 0
? keyDifference
: a.index - b.index;
})
.map(({ item }) => item);
}
// -------------------------------------------------------------------------
// DOM
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const keyList = document.querySelector("#keyList");
const currentOrder = document.querySelector("#currentOrder");
const equalKeys = document.querySelector("#equalKeys");
const message = document.querySelector("#message");
const sortAsc = document.querySelector("#sortAsc");
const sortDesc = document.querySelector("#sortDesc");
const reverse = document.querySelector("#reverse");
const shuffle = document.querySelector("#shuffle");
const reset = document.querySelector("#reset");
const keyRows = new Map();
for (const block of initialData) {
const row = document.createElement("label");
row.className = "key-row";
row.style.setProperty(
"--block-color",
`#${block.color.toString(16).padStart(6, "0")}`
);
const swatch = document.createElement("span");
swatch.className = "swatch";
swatch.setAttribute("aria-hidden", "true");
const name = document.createElement("span");
name.textContent = `Block ${String(block.number).padStart(2, "0")}`;
const arrow = document.createElement("span");
arrow.className = "key-arrow";
arrow.textContent = "→";
arrow.setAttribute("aria-hidden", "true");
const input = document.createElement("input");
input.type = "number";
input.step = "1";
input.value = String(block.key);
input.setAttribute(
"aria-label",
`Sort key for block ${String(block.number).padStart(2, "0")}`
);
input.addEventListener("input", (event) => {
const parsed = Number.parseInt(event.target.value, 10);
const currentBlock = blockById.get(block.id);
if (currentBlock) {
currentBlock.key = Number.isFinite(parsed) ? parsed : 0;
paintBlockLabel(block.id, currentBlock);
updateStatus("Key changed. Sort again to apply it.");
}
});
input.addEventListener("blur", () => {
const currentBlock = blockById.get(block.id);
if (currentBlock) input.value = String(currentBlock.key);
});
row.append(swatch, name, arrow, input);
keyList.append(row);
keyRows.set(block.id, row);
}
function reorderKeyRows() {
for (const block of blocks) {
keyList.append(keyRows.get(block.id));
}
}
function updateInputs() {
for (const block of blocks) {
const row = keyRows.get(block.id);
if (row) row.querySelector("input").value = String(block.key);
}
}
function updateStatus(text = "") {
currentOrder.textContent = blocks
.map((block) => String(block.number).padStart(2, "0"))
.join(" → ");
const groups = new Map();
for (const block of blocks) {
if (!groups.has(block.key)) groups.set(block.key, []);
groups.get(block.key).push(
String(block.number).padStart(2, "0")
);
}
const equalGroups = [...groups.entries()]
.filter(([, values]) => values.length > 1)
.sort((a, b) => a[0] - b[0]);
equalKeys.replaceChildren();
if (equalGroups.length === 0) {
const empty = document.createElement("div");
empty.className = "lane";
empty.textContent = "No equal keys in the current order.";
equalKeys.append(empty);
} else {
for (const [key, values] of equalGroups) {
const lane = document.createElement("div");
lane.className = "lane";
const chip = document.createElement("span");
chip.className = "key-chip";
chip.textContent = `key ${key}`;
const names = document.createElement("span");
names.textContent = values.join(" · ");
lane.append(chip, names);
equalKeys.append(lane);
}
}
if (text) message.textContent = text;
}
// -------------------------------------------------------------------------
// Three.js renderer, scene, camera, and lights
// -------------------------------------------------------------------------
let renderer;
try {
renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
} catch (error) {
message.textContent =
"WebGL could not be initialized. Please try a WebGL-capable browser.";
throw error;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
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();
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0, 0.05, 0);
const reducedMotion = window.matchMedia(
"(prefers-reduced-motion: reduce)"
).matches;
let cameraTheta = 0;
let cameraPhi = 1.03;
let cameraRadius = window.innerWidth < 760 ? 34 : 16.5;
function updateCamera() {
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x + cameraRadius * sinPhi * Math.sin(cameraTheta),
cameraTarget.y + cameraRadius * Math.cos(cameraPhi),
cameraTarget.z + cameraRadius * sinPhi * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(
0xffffff,
0x718096,
2.15
);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(6, 12, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -12;
keyLight.shadow.camera.right = 12;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.0002;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0x9abfff, 1.15);
fillLight.position.set(-8, 5, -5);
scene.add(fillLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(60, 60),
new THREE.MeshStandardMaterial({
color: 0xdfe7f3,
roughness: 1,
metalness: 0
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.94;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(
32,
32,
0x91a3bd,
0xb2bfd0
);
grid.position.y = -0.925;
grid.material.transparent = true;
grid.material.opacity = 0.2;
grid.material.depthWrite = false;
scene.add(grid);
// -------------------------------------------------------------------------
// Low-poly chamfered block geometry
// -------------------------------------------------------------------------
function createChamferedBox(width, height, depth, chamfer) {
const hx = width / 2;
const hy = height / 2;
const hz = depth / 2;
const positions = [];
function addPolygon(inputPoints) {
const points = inputPoints.map(
(point) => new THREE.Vector3(...point)
);
const edgeA = new THREE.Vector3().subVectors(
points[1],
points[0]
);
const edgeB = new THREE.Vector3().subVectors(
points[2],
points[0]
);
const normal = new THREE.Vector3().crossVectors(edgeA, edgeB);
const centroid = points
.reduce(
(sum, point) => sum.add(point),
new THREE.Vector3()
)
.multiplyScalar(1 / points.length);
// Orient each face outward.
if (normal.dot(centroid) < 0) points.reverse();
for (let i = 1; i < points.length - 1; i++) {
positions.push(
points[0].x,
points[0].y,
points[0].z,
points[i].x,
points[i].y,
points[i].z,
points[i + 1].x,
points[i + 1].y,
points[i + 1].z
);
}
}
// Six main faces.
addPolygon([
[hx, hy - chamfer, hz - chamfer],
[hx, -hy + chamfer, hz - chamfer],
[hx, -hy + chamfer, -hz + chamfer],
[hx, hy - chamfer, -hz + chamfer]
]);
addPolygon([
[-hx, hy - chamfer, hz - chamfer],
[-hx, hy - chamfer, -hz + chamfer],
[-hx, -hy + chamfer, -hz + chamfer],
[-hx, -hy + chamfer, hz - chamfer]
]);
addPolygon([
[-hx + chamfer, hy, hz - chamfer],
[hx - chamfer, hy, hz - chamfer],
[hx - chamfer, hy, -hz + chamfer],
[-hx + chamfer, hy, -hz + chamfer]
]);
addPolygon([
[-hx + chamfer, -hy, hz - chamfer],
[-hx + chamfer, -hy, -hz + chamfer],
[hx - chamfer, -hy, -hz + chamfer],
[hx - chamfer, -hy, hz - chamfer]
]);
addPolygon([
[-hx + chamfer, -hy + chamfer, hz],
[hx - chamfer, -hy + chamfer, hz],
[hx - chamfer, hy - chamfer, hz],
[-hx + chamfer, hy - chamfer, hz]
]);
addPolygon([
[-hx + chamfer, hy - chamfer, -hz],
[hx - chamfer, hy - chamfer, -hz],
[hx - chamfer, -hy + chamfer, -hz],
[-hx + chamfer, -hy + chamfer, -hz]
]);
// Beveled edges parallel to Z.
for (const sx of [-1, 1]) {
for (const sy of [-1, 1]) {
addPolygon([
[sx * hx, sy * (hy - chamfer), hz - chamfer],
[sx * hx, sy * (hy - chamfer), -hz + chamfer],
[sx * (hx - chamfer), sy * hy, -hz + chamfer],
[sx * (hx - chamfer), sy * hy, hz - chamfer]
]);
}
}
// Beveled edges parallel to Y.
for (const sx of [-1, 1]) {
for (const sz of [-1, 1]) {
addPolygon([
[sx * hx, hy - chamfer, sz * hz],
[sx * hx, -hy + chamfer, sz * hz],
[sx * (hx - chamfer), -hy + chamfer, sz * hz],
[sx * (hx - chamfer), hy - chamfer, sz * hz]
]);
}
}
// Beveled edges parallel to X.
for (const sy of [-1, 1]) {
for (const sz of [-1, 1]) {
addPolygon([
[hx - chamfer, sy * hy, sz * (hz - chamfer)],
[-hx + chamfer, sy * hy, sz * (hz - chamfer)],
[-hx + chamfer, sy * (hy - chamfer), sz * hz],
[hx - chamfer, sy * (hy - chamfer), sz * hz]
]);
}
}
// Triangular corner facets.
for (const sx of [-1, 1]) {
for (const sy of [-1, 1]) {
for (const sz of [-1, 1]) {
addPolygon([
[sx * (hx - chamfer), sy * hy, sz * hz],
[sx * hx, sy * (hy - chamfer), sz * hz],
[sx * hx, sy * hy, sz * (hz - chamfer)]
]);
}
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.computeVertexNormals();
geometry.computeBoundingSphere();
return geometry;
}
const blockWidth = 1.25;
const blockHeight = 1.8;
const blockDepth = 1.25;
const blockGeometry = createChamferedBox(
blockWidth,
blockHeight,
blockDepth,
0.14
);
const edgeGeometry = new THREE.EdgesGeometry(blockGeometry, 15);
const labelGeometry = new THREE.PlaneGeometry(1, 1);
const blockVisuals = new Map();
const blockMeshes = [];
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 createLabelCanvas() {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 512;
return labelCanvas;
}
function paintBlockLabel(blockId, block) {
const visual = blockVisuals.get(blockId);
if (!visual) return;
const context = visual.labelContext;
context.clearRect(0, 0, 512, 512);
roundedRect(context, 32, 32, 448, 448, 52);
context.fillStyle = "rgba(10, 17, 31, 0.84)";
context.fill();
context.lineWidth = 3;
context.strokeStyle = "rgba(255,255,255,0.14)";
context.stroke();
roundedRect(context, 145, 61, 222, 80, 24);
context.fillStyle = "rgba(255,255,255,0.13)";
context.fill();
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = "rgba(255,255,255,0.72)";
context.font = "700 24px ui-sans-serif, system-ui, sans-serif";
context.fillText("KEY", 256, 87);
context.fillStyle = "#ffffff";
context.font = "800 47px ui-sans-serif, system-ui, sans-serif";
context.fillText(String(block.key), 256, 119);
context.fillStyle = "#ffffff";
context.font =
"800 158px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";
context.fillText(
String(block.number).padStart(2, "0"),
256,
286
);
context.fillStyle = "rgba(255,255,255,0.58)";
context.font = "700 23px ui-sans-serif, system-ui, sans-serif";
context.fillText("BLOCK", 256, 402);
visual.labelTexture.needsUpdate = true;
}
function slotX(index) {
return (index - (blocks.length - 1) / 2) * 1.72;
}
for (let index = 0; index < initialData.length; index++) {
const block = initialData[index];
const group = new THREE.Group();
group.position.x = slotX(index);
const material = new THREE.MeshStandardMaterial({
color: block.color,
roughness: 0.58,
metalness: 0.025,
flatShading: true
});
const mesh = new THREE.Mesh(blockGeometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.userData.blockId = block.id;
group.add(mesh);
const lineMaterial = new THREE.LineBasicMaterial({
color: 0x17233b,
transparent: true,
opacity: 0.32,
depthWrite: false
});
const outline = new THREE.LineSegments(
edgeGeometry,
lineMaterial
);
outline.renderOrder = 2;
group.add(outline);
const labelCanvas = createLabelCanvas();
const labelTexture = new THREE.CanvasTexture(labelCanvas);
labelTexture.colorSpace = THREE.SRGBColorSpace;
labelTexture.anisotropy = Math.min(
8,
renderer.capabilities.getMaxAnisotropy()
);
const labelMaterial = new THREE.MeshBasicMaterial({
map: labelTexture,
transparent: true,
toneMapped: false
});
const frontLabel = new THREE.Mesh(
labelGeometry,
labelMaterial
);
frontLabel.position.z = blockDepth / 2 + 0.014;
group.add(frontLabel);
const backLabel = new THREE.Mesh(
labelGeometry,
labelMaterial
);
backLabel.position.z = -blockDepth / 2 - 0.014;
backLabel.rotation.y = Math.PI;
group.add(backLabel);
scene.add(group);
blockMeshes.push(mesh);
blockVisuals.set(block.id, {
group,
mesh,
outline,
labelCanvas,
labelContext: labelCanvas.getContext("2d"),
labelTexture
});
paintBlockLabel(block.id, block);
}
function syncVisual(block) {
const visual = blockVisuals.get(block.id);
if (!visual) return;
visual.mesh.material.color.setHex(block.color);
paintBlockLabel(block.id, block);
}
// -------------------------------------------------------------------------
// Sorting animation
// -------------------------------------------------------------------------
let activeAnimation = null;
function setBusy(isBusy) {
document.querySelectorAll("[data-action]").forEach((button) => {
button.disabled = isBusy;
});
}
function moveToOrder(nextOrder, statusText) {
if (activeAnimation) return false;
const previousPositions = new Map();
for (const block of blocks) {
previousPositions.set(
block.id,
blockVisuals.get(block.id).group.position.clone()
);
}
blocks = nextOrder;
blockById = new Map(blocks.map((block) => [block.id, block]));
reorderKeyRows();
updateStatus(statusText);
setBusy(true);
const duration = reducedMotion ? 1 : 820;
activeAnimation = {
start: performance.now(),
duration,
items: blocks.map((block, index) => ({
group: blockVisuals.get(block.id).group,
from: previousPositions.get(block.id),
to: new THREE.Vector3(slotX(index), 0, 0),
delay: index * 18
}))
};
return true;
}
function easeInOutCubic(value) {
return value < 0.5
? 4 * value * value * value
: 1 - Math.pow(-2 * value + 2, 3) / 2;
}
// -------------------------------------------------------------------------
// Controls
// -------------------------------------------------------------------------
sortAsc.addEventListener("click", () => {
const next = stableSortByKey(blocks, 1);
moveToOrder(
next,
"Sorted ascending. Equal-key blocks retained their previous relative order."
);
});
sortDesc.addEventListener("click", () => {
const next = stableSortByKey(blocks, -1);
moveToOrder(
next,
"Sorted descending. Equal-key blocks retained their previous relative order."
);
});
reverse.addEventListener("click", () => {
const next = blocks.slice().reverse();
moveToOrder(
next,
"Order reversed without changing block identities or keys."
);
});
shuffle.addEventListener("click", () => {
// Deliberately include duplicate keys.
const bag = [1, 1, 1, 2, 2, 3, 3, 4];
for (let i = bag.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[bag[i], bag[j]] = [bag[j], bag[i]];
}
blocks.forEach((block, index) => {
block.key = bag[index];
syncVisual(block);
});
updateInputs();
updateStatus(
"Keys shuffled with duplicates. Block identities and current order are unchanged."
);
});
reset.addEventListener("click", () => {
const resetBlocks = initialData.map((block) => ({ ...block }));
if (
moveToOrder(
resetBlocks,
"Reset to the original blocks and keys."
)
) {
resetBlocks.forEach(syncVisual);
updateInputs();
}
});
// -------------------------------------------------------------------------
// Selection
// -------------------------------------------------------------------------
let selectedId = null;
function updateSelection() {
for (const [id, visual] of blockVisuals) {
const selected = id === selectedId;
visual.mesh.material.emissive.setHex(
selected ? 0xffffff : 0x000000
);
visual.mesh.material.emissiveIntensity = selected ? 0.13 : 0;
visual.outline.material.opacity = selected ? 0.9 : 0.32;
visual.group.scale.setScalar(selected ? 1.06 : 1);
}
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function selectBlockAt(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(blockMeshes, false);
if (hits.length > 0) {
selectedId = hits[0].object.userData.blockId;
updateSelection();
const block = blockById.get(selectedId);
if (block) {
message.textContent =
`Selected block ${String(block.number).padStart(2, "0")} ` +
`(${block.id}), key ${block.key}.`;
}
}
}
// -------------------------------------------------------------------------
// Custom orbit and zoom controls — no addons
// -------------------------------------------------------------------------
let dragging = false;
let pointerStartX = 0;
let pointerStartY = 0;
let previousPointerX = 0;
let previousPointerY = 0;
let dragDistance = 0;
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
dragDistance = 0;
pointerStartX = previousPointerX = event.clientX;
pointerStartY = previousPointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - previousPointerX;
const deltaY = event.clientY - previousPointerY;
dragDistance += Math.abs(deltaX) + Math.abs(deltaY);
cameraTheta -= deltaX * 0.006;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi - deltaY * 0.005,
0.42,
1.43
);
previousPointerX = event.clientX;
previousPointerY = event.clientY;
updateCamera();
});
canvas.addEventListener("pointerup", (event) => {
if (!dragging) return;
dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
if (
dragDistance < 6 &&
Math.abs(event.clientX - pointerStartX) < 6 &&
Math.abs(event.clientY - pointerStartY) < 6
) {
selectBlockAt(event.clientX, event.clientY);
}
});
canvas.addEventListener("pointercancel", () => {
dragging = false;
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius + event.deltaY * 0.012,
10,
48
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", () => {
cameraTheta = 0;
cameraPhi = 1.03;
cameraRadius = window.innerWidth < 760 ? 34 : 16.5;
updateCamera();
});
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
window.addEventListener("resize", () => {
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
});
function animate(now) {
requestAnimationFrame(animate);
if (activeAnimation) {
const animation = activeAnimation;
const elapsed = now - animation.start;
let finished = true;
for (const item of animation.items) {
const localTime = elapsed - item.delay;
const progress = THREE.MathUtils.clamp(
localTime / animation.duration,
0,
1
);
if (progress < 1) finished = false;
const eased = easeInOutCubic(progress);
const arc = Math.sin(Math.PI * progress);
item.group.position.x = THREE.MathUtils.lerp(
item.from.x,
item.to.x,
eased
);
item.group.position.y = arc * 0.62;
item.group.position.z = arc * 0.12;
item.group.rotation.y = arc * 0.1;
if (progress === 1) {
item.group.position.copy(item.to);
item.group.rotation.y = 0;
}
}
if (finished) {
activeAnimation = null;
setBusy(false);
}
}
renderer.render(scene, camera);
}
reorderKeyRows();
updateInputs();
updateStatus(
"Try reversing the order before sorting to see how equal-key blocks retain their relative order."
);
requestAnimationFrame(animate);
</script>
</body>
</html>
```