Prompt specification
Build or customize the Three.js 3D scene "Broken Hierarchy Repair Puzzle" 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: Broken Hierarchy Repair Puzzle
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/broken-hierarchy-repair-puzzle-x3736
Scene Description Prompt:
Make one HTML file using Three.js from cdnjs for this voxel scene: Create an interactive puppet whose hand is intentionally parented incorrectly. Let users fix the transform hierarchy and compare the resulting motion under identical joint inputs.
Working Three.js Starter (broken-hierarchy-repair-puzzle-x3736):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Transform Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #0b1020;
--panel: #121a2d;
--panel-2: #182238;
--line: #2a3753;
--text: #edf3ff;
--muted: #91a2bf;
--cyan: #58e6c7;
--orange: #ffb547;
--purple: #8b7cff;
--red: #ff6f7d;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
height: 100vh;
display: grid;
grid-template-rows: 72px minmax(0, 1fr) 220px;
overflow: hidden;
}
button,
input {
font: inherit;
}
button {
border: 1px solid var(--line);
border-radius: 9px;
padding: 10px 13px;
color: var(--text);
background: #202c45;
cursor: pointer;
font-weight: 700;
transition: transform 120ms ease, border-color 120ms ease, background 120ms ease;
}
button:hover:not(:disabled) {
transform: translateY(-1px);
border-color: #607399;
background: #293752;
}
button:disabled {
cursor: not-allowed;
opacity: 0.42;
}
button.primary {
color: #08251e;
border-color: var(--cyan);
background: var(--cyan);
}
button.primary:hover:not(:disabled) {
background: #78f0d7;
}
button.danger {
color: #ffd8dc;
border-color: #69313d;
background: #3a1d28;
}
header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 22px;
border-bottom: 1px solid var(--line);
background: rgba(13, 19, 35, 0.96);
z-index: 5;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-icon {
display: grid;
grid-template-columns: repeat(2, 10px);
grid-template-rows: repeat(2, 10px);
gap: 3px;
transform: rotate(-8deg);
}
.brand-icon i {
display: block;
background: var(--purple);
border-radius: 2px;
}
.brand-icon i:nth-child(2) {
background: var(--cyan);
}
.brand-icon i:nth-child(3) {
background: var(--orange);
}
.brand-icon i:nth-child(4) {
background: #526de0;
}
h1 {
margin: 0;
font-size: 17px;
letter-spacing: 0.02em;
}
.subtitle {
margin-top: 3px;
color: var(--muted);
font-size: 12px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.header-actions {
display: flex;
align-items: center;
gap: 12px;
}
.sync-pill {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 11px;
border: 1px solid #254e4a;
border-radius: 999px;
color: #9cf3df;
background: #122c2c;
font: 700 11px ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.05em;
white-space: nowrap;
}
.sync-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 10px var(--cyan);
}
main {
min-height: 0;
display: grid;
grid-template-columns: minmax(0, 1fr) 320px;
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #0e1527;
}
#canvas-wrap {
position: absolute;
inset: 0;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
canvas:active {
cursor: grabbing;
}
.view-label {
position: absolute;
z-index: 2;
display: flex;
align-items: center;
gap: 9px;
transform: translateX(-50%);
padding: 9px 12px;
border: 1px solid rgba(101, 120, 157, 0.45);
border-radius: 10px;
background: rgba(12, 18, 33, 0.78);
backdrop-filter: blur(8px);
pointer-events: none;
font-size: 12px;
white-space: nowrap;
}
.view-label.a {
top: 14px;
left: 25%;
}
.view-label.b {
top: 14px;
left: 75%;
}
.view-letter {
display: grid;
place-items: center;
width: 24px;
height: 24px;
border-radius: 6px;
font-weight: 900;
color: #10182a;
background: var(--orange);
}
.view-label.b .view-letter {
background: var(--cyan);
}
.view-label strong {
display: block;
font-size: 12px;
}
.view-label small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 10px;
}
.state-pill {
display: inline-block;
margin-left: 4px;
padding: 3px 6px;
border-radius: 5px;
font: 800 9px ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.06em;
}
.state-pill.bad {
color: #ffd9a1;
background: #5d3814;
}
.state-pill.good {
color: #b6ffeb;
background: #174b43;
}
.split-line {
position: absolute;
z-index: 1;
top: 0;
bottom: 0;
left: 50%;
width: 1px;
background: linear-gradient(
to bottom,
transparent,
rgba(126, 146, 184, 0.38) 12%,
rgba(126, 146, 184, 0.38) 88%,
transparent
);
pointer-events: none;
}
#stage.vertical .view-label.a {
top: 14px;
left: 50%;
}
#stage.vertical .view-label.b {
top: calc(50% + 14px);
left: 50%;
}
#stage.vertical .split-line {
top: 50%;
bottom: auto;
left: 0;
width: 100%;
height: 1px;
background: linear-gradient(
to right,
transparent,
rgba(126, 146, 184, 0.38) 12%,
rgba(126, 146, 184, 0.38) 88%,
transparent
);
}
.camera-hint {
position: absolute;
z-index: 2;
bottom: 12px;
left: 50%;
transform: translateX(-50%);
color: #a4b2c9;
background: rgba(10, 16, 29, 0.75);
border: 1px solid rgba(95, 112, 146, 0.35);
border-radius: 999px;
padding: 7px 11px;
font-size: 10px;
pointer-events: none;
white-space: nowrap;
}
#toast {
position: absolute;
z-index: 5;
left: 50%;
bottom: 48px;
transform: translate(-50%, 10px);
padding: 10px 14px;
border: 1px solid #3a6e65;
border-radius: 9px;
color: #caffef;
background: rgba(16, 49, 45, 0.94);
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.3);
opacity: 0;
pointer-events: none;
transition: opacity 180ms ease, transform 180ms ease;
font-size: 12px;
text-align: center;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#loading {
position: absolute;
inset: 0;
display: grid;
place-items: center;
z-index: 4;
color: var(--muted);
background: #0e1527;
font: 13px ui-monospace, SFMono-Regular, Menlo, monospace;
}
#inspector {
min-height: 0;
overflow: auto;
padding: 17px;
border-left: 1px solid var(--line);
background: var(--panel);
}
.eyebrow {
margin-bottom: 7px;
color: #8fa2c1;
font: 800 10px ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.12em;
}
h2,
h3 {
margin: 0;
}
h2 {
font-size: 18px;
}
h3 {
font-size: 13px;
}
.card {
margin-top: 15px;
padding: 14px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(24, 34, 56, 0.72);
}
.instructions {
margin: 9px 0 12px;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.instructions strong {
color: #d8e2f5;
}
#tree {
padding: 8px;
overflow: hidden;
border: 1px solid #25314b;
border-radius: 9px;
background: #0d1425;
font: 11px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.tree-row {
position: relative;
min-height: 27px;
display: flex;
align-items: center;
gap: 6px;
padding-right: 7px;
color: #b7c6dd;
border-radius: 5px;
user-select: none;
}
.tree-row::before {
content: "";
position: absolute;
left: calc(5px + var(--depth) * 16px);
top: 0;
bottom: 0;
width: 1px;
background: #26334b;
}
.tree-icon {
position: relative;
z-index: 1;
width: 13px;
color: #7183a1;
}
.tree-row.hand {
color: #ffd899;
background: rgba(255, 181, 71, 0.08);
cursor: grab;
}
.tree-row.hand.selected {
outline: 1px solid rgba(255, 181, 71, 0.48);
background: rgba(255, 181, 71, 0.14);
}
.tree-row.drop-target {
outline: 1px dashed #4e668d;
outline-offset: -1px;
}
.tree-row.drop-hover {
color: #baffeb;
outline: 2px solid var(--cyan);
background: rgba(88, 230, 199, 0.13);
}
.tree-row.dragging {
opacity: 0.45;
}
.parent-tag {
margin-left: auto;
padding: 2px 5px;
border-radius: 4px;
color: #94a6c2;
background: #1b263e;
font-size: 9px;
white-space: nowrap;
}
.status-box {
margin: 11px 0;
padding: 10px;
border: 1px solid #603d20;
border-radius: 8px;
color: #ffd49a;
background: rgba(110, 65, 20, 0.19);
font-size: 11px;
line-height: 1.45;
}
.status-box.good {
border-color: #275e55;
color: #b7f8e8;
background: rgba(20, 91, 78, 0.19);
}
.button-row {
display: flex;
gap: 8px;
margin-top: 10px;
}
.button-row button {
flex: 1;
padding: 9px 8px;
font-size: 11px;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 11px;
}
.metric {
padding: 10px;
border: 1px solid #283650;
border-radius: 8px;
background: #10192c;
}
.metric-label {
color: var(--muted);
font-size: 9px;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.metric-value {
margin-top: 4px;
font: 800 18px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.metric-value.good {
color: var(--cyan);
}
.metric-value.bad {
color: var(--orange);
}
.legend {
display: flex;
gap: 13px;
margin-top: 11px;
color: var(--muted);
font-size: 10px;
}
.legend span::before {
content: "";
display: inline-block;
width: 14px;
height: 3px;
margin-right: 5px;
vertical-align: middle;
border-radius: 3px;
background: var(--orange);
}
.legend span:last-child::before {
background: var(--cyan);
}
#controls {
display: grid;
grid-template-columns: minmax(0, 1.5fr) minmax(220px, 0.85fr) minmax(220px, 0.85fr);
gap: 14px;
padding: 16px 20px;
border-top: 1px solid var(--line);
background: #10182a;
z-index: 5;
}
.control-panel {
min-width: 0;
padding: 13px 15px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(24, 34, 56, 0.65);
}
.control-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 13px;
}
.control-header small {
color: var(--muted);
font-size: 10px;
}
.joint-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 14px;
}
.joint label {
display: flex;
justify-content: space-between;
gap: 8px;
color: #c5d1e4;
font-size: 11px;
font-weight: 700;
}
.joint output {
color: var(--cyan);
font: 700 11px ui-monospace, SFMono-Regular, Menlo, monospace;
}
input[type="range"] {
width: 100%;
margin: 10px 0 0;
accent-color: var(--cyan);
cursor: pointer;
}
.transport {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.transport button {
flex: 1;
min-width: 90px;
font-size: 11px;
}
.speed-row {
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
gap: 9px;
margin-top: 13px;
color: var(--muted);
font-size: 10px;
}
.speed-row output {
color: #dbe7fa;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
.readout {
margin-top: 11px;
padding: 9px;
border-radius: 7px;
color: #b9c9df;
background: #0e1627;
font: 10px/1.55 ui-monospace, SFMono-Regular, Menlo, monospace;
white-space: pre-line;
}
@media (max-width: 920px) {
body {
height: auto;
min-height: 100vh;
display: block;
overflow: auto;
}
header {
min-height: 72px;
padding: 12px 16px;
}
.sync-pill {
display: none;
}
main {
display: block;
}
#stage {
height: 760px;
}
#inspector {
overflow: visible;
border-top: 1px solid var(--line);
border-left: 0;
}
#controls {
grid-template-columns: 1fr;
}
}
@media (max-width: 560px) {
.subtitle {
max-width: 230px;
}
#run-sweep {
padding: 9px;
font-size: 11px;
}
.joint-grid {
grid-template-columns: 1fr;
gap: 8px;
}
.view-label {
padding: 7px 9px;
}
.camera-hint {
font-size: 9px;
}
}
</style>
</head>
<body>
<header>
<div class="brand">
<div class="brand-icon" aria-hidden="true">
<i></i><i></i><i></i><i></i>
</div>
<div>
<h1>VOXEL TRANSFORM LAB</h1>
<div class="subtitle">Repair the hand hierarchy, then compare both puppets under one joint stream.</div>
</div>
</div>
<div class="header-actions">
<div class="sync-pill">
<span class="sync-dot"></span>
IDENTICAL INPUT STREAM
</div>
<button id="run-sweep">Run synchronized sweep</button>
</div>
</header>
<main>
<section id="stage" aria-label="Interactive voxel puppet comparison">
<div id="canvas-wrap">
<canvas id="scene"></canvas>
<div id="loading">Building voxel scene…</div>
<div class="view-label a">
<span class="view-letter">A</span>
<div>
<strong>Candidate <span id="candidate-state" class="state-pill bad">BROKEN</span></strong>
<small>Editable hierarchy</small>
</div>
</div>
<div class="view-label b">
<span class="view-letter">B</span>
<div>
<strong>Reference <span class="state-pill good">CORRECT</span></strong>
<small>Hand parented to forearm</small>
</div>
</div>
<div class="split-line"></div>
<div class="camera-hint">Drag to orbit · Scroll to zoom · Double-click to reset</div>
<div id="toast"></div>
</div>
</section>
<aside id="inspector">
<div class="eyebrow">SCENE GRAPH</div>
<h2>Transform hierarchy</h2>
<section class="card">
<h3>Repair the hand</h3>
<p class="instructions">
Candidate A’s hand is incorrectly parented to the
<strong>UpperArm</strong>. Select the hand, then re-parent it to the
<strong>ForearmJoint</strong>. You can also drag its tree row onto the forearm.
</p>
<div id="tree" aria-label="Three.js transform hierarchy"></div>
<div id="hierarchy-status" class="status-box"></div>
<div class="button-row">
<button id="repair-button" class="primary">Re-parent Hand → Forearm</button>
<button id="break-button" class="danger" disabled>Restore fault</button>
</div>
</section>
<section class="card">
<h3>Motion comparison</h3>
<p class="instructions">
Both puppets receive the exact same shoulder, elbow, and wrist values.
The trails record each hand tip.
</p>
<div class="metric-grid">
<div class="metric">
<div class="metric-label">Hand offset</div>
<div id="offset-value" class="metric-value bad">0.00</div>
</div>
<div class="metric">
<div class="metric-label">RMS path error</div>
<div id="rms-value" class="metric-value">0.00</div>
</div>
</div>
<div class="legend">
<span>Candidate trail</span>
<span>Reference trail</span>
</div>
</section>
<section class="card">
<h3>Keyboard shortcuts</h3>
<div class="readout">R Repair hierarchy
B Restore incorrect parent
Space Play / pause
Double-click canvas Reset camera</div>
</section>
</aside>
</main>
<footer id="controls">
<section class="control-panel">
<div class="control-header">
<h3>Shared joint inputs</h3>
<small>Moving a slider pauses the automatic sweep.</small>
</div>
<div class="joint-grid">
<div class="joint">
<label for="shoulder">Shoulder <output id="shoulder-output">0°</output></label>
<input id="shoulder" type="range" min="-100" max="100" step="1" value="0">
</div>
<div class="joint">
<label for="elbow">Elbow <output id="elbow-output">0°</output></label>
<input id="elbow" type="range" min="-110" max="110" step="1" value="0">
</div>
<div class="joint">
<label for="wrist">Wrist <output id="wrist-output">0°</output></label>
<input id="wrist" type="range" min="-110" max="110" step="1" value="0">
</div>
</div>
</section>
<section class="control-panel">
<div class="control-header">
<h3>Motion transport</h3>
<small id="time-value">0.00 s</small>
</div>
<div class="transport">
<button id="play-button" class="primary">Pause</button>
<button id="sweep-button">Reset sweep</button>
</div>
<div class="speed-row">
<span>Speed</span>
<input id="speed" type="range" min="0.25" max="1.75" step="0.05" value="1">
<output id="speed-output">1.00×</output>
</div>
</section>
<section class="control-panel">
<div class="control-header">
<h3>Input monitor</h3>
<small>Applied to A and B</small>
</div>
<div id="input-readout" class="readout"></div>
<div class="button-row">
<button id="select-hand-button">Select candidate hand</button>
<button id="reset-camera-button">Reset camera</button>
</div>
</section>
</footer>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// DOM and shared state
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const canvasWrap = document.querySelector("#canvas-wrap");
const stage = document.querySelector("#stage");
const loading = document.querySelector("#loading");
const toast = document.querySelector("#toast");
const shoulderInput = document.querySelector("#shoulder");
const elbowInput = document.querySelector("#elbow");
const wristInput = document.querySelector("#wrist");
const shoulderOutput = document.querySelector("#shoulder-output");
const elbowOutput = document.querySelector("#elbow-output");
const wristOutput = document.querySelector("#wrist-output");
const speedInput = document.querySelector("#speed");
const speedOutput = document.querySelector("#speed-output");
const timeValue = document.querySelector("#time-value");
const inputReadout = document.querySelector("#input-readout");
const playButton = document.querySelector("#play-button");
const candidateState = document.querySelector("#candidate-state");
const hierarchyStatus = document.querySelector("#hierarchy-status");
const repairButton = document.querySelector("#repair-button");
const breakButton = document.querySelector("#break-button");
const offsetValue = document.querySelector("#offset-value");
const rmsValue = document.querySelector("#rms-value");
const state = {
time: 0,
speed: 1,
playing: true,
manual: false,
shoulder: 0,
elbow: 0,
wrist: 0
};
const degreesToRadians = THREE.MathUtils.degToRad;
const radiansToDegrees = THREE.MathUtils.radToDeg;
// -------------------------------------------------------------------------
// Renderer and camera
// -------------------------------------------------------------------------
let renderer;
try {
renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
} catch (error) {
loading.textContent = "WebGL could not be initialized in this browser.";
throw error;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const cameraTarget = new THREE.Vector3(0, 1.95, 0);
const orbit = {
yaw: -0.04,
pitch: 0.19,
radius: 9.4
};
function updateCamera() {
const horizontalRadius = Math.cos(orbit.pitch) * orbit.radius;
camera.position.set(
cameraTarget.x + Math.sin(orbit.yaw) * horizontalRadius,
cameraTarget.y + Math.sin(orbit.pitch) * orbit.radius,
cameraTarget.z + Math.cos(orbit.yaw) * horizontalRadius
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
orbit.yaw = -0.04;
orbit.pitch = 0.19;
orbit.radius = 9.4;
updateCamera();
}
updateCamera();
// -------------------------------------------------------------------------
// Materials and voxel construction
// -------------------------------------------------------------------------
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x11182a,
transparent: true,
opacity: 0.34
});
function standardMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.76,
metalness: 0.04,
flatShading: true,
...options
});
}
function addBox(parent, size, position, material, edges = true) {
const geometry = new THREE.BoxGeometry(...size);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(...position);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
if (edges) {
const outline = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry),
edgeMaterial
);
mesh.add(outline);
}
return mesh;
}
function createScene(background) {
const scene = new THREE.Scene();
scene.background = new THREE.Color(background);
scene.fog = new THREE.Fog(background, 13, 27);
const hemisphere = new THREE.HemisphereLight(0xc8e8ff, 0x171329, 2.0);
scene.add(hemisphere);
const key = new THREE.DirectionalLight(0xfff2db, 3.2);
key.position.set(4.5, 8, 6);
key.castShadow = true;
key.shadow.mapSize.set(1024, 1024);
key.shadow.camera.left = -5;
key.shadow.camera.right = 5;
key.shadow.camera.top = 6;
key.shadow.camera.bottom = -2;
key.shadow.camera.near = 0.5;
key.shadow.camera.far = 20;
key.shadow.bias = -0.0008;
scene.add(key);
const rim = new THREE.DirectionalLight(0x7f9cff, 1.5);
rim.position.set(-5, 4, -4);
scene.add(rim);
const fill = new THREE.PointLight(0x58e6c7, 1.2, 12);
fill.position.set(-3, 3.5, 4);
scene.add(fill);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(30, 30),
standardMaterial(0x111a2b, { roughness: 0.95 })
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.04;
ground.receiveShadow = true;
scene.add(ground);
addBox(
scene,
[3.25, 0.2, 2.15],
[0, -0.13, 0],
standardMaterial(0x26324b),
true
);
const grid = new THREE.GridHelper(20, 40, 0x425271, 0x25334d);
grid.position.y = -0.025;
grid.material.transparent = true;
grid.material.opacity = 0.36;
scene.add(grid);
return scene;
}
function createRig(scene) {
const root = new THREE.Group();
root.name = "Puppet_ROOT";
scene.add(root);
const bodyMaterial = standardMaterial(0x5d75dc);
const bodyDarkMaterial = standardMaterial(0x35489a);
const pantsMaterial = standardMaterial(0x29345b);
const skinMaterial = standardMaterial(0xffd4a5);
const hairMaterial = standardMaterial(0x28243d);
const eyeMaterial = standardMaterial(0x111526);
const accentMaterial = standardMaterial(0xffcf68);
const handMaterial = standardMaterial(0xffb547, {
emissive: 0x000000,
emissiveIntensity: 0
});
const body = new THREE.Group();
body.name = "Body";
root.add(body);
// Torso and pelvis.
addBox(body, [1.08, 1.18, 0.66], [0, 2.17, 0], bodyMaterial);
addBox(body, [1.18, 0.76, 0.73], [0, 1.32, 0], bodyDarkMaterial);
addBox(body, [1.13, 0.18, 0.78], [0, 1.7, 0], accentMaterial);
addBox(body, [0.35, 0.29, 0.12], [0, 2.35, 0.39], accentMaterial, false);
// Neck and head.
addBox(body, [0.3, 0.28, 0.3], [0, 2.91, 0], skinMaterial);
addBox(body, [0.92, 0.88, 0.76], [0, 3.47, 0], skinMaterial);
addBox(body, [0.97, 0.23, 0.81], [0, 3.95, -0.01], hairMaterial);
addBox(body, [0.18, 0.28, 0.18], [0, 4.19, 0], accentMaterial);
// Face.
addBox(body, [0.13, 0.16, 0.09], [-0.22, 3.56, 0.42], eyeMaterial, false);
addBox(body, [0.13, 0.16, 0.09], [0.22, 3.56, 0.42], eyeMaterial, false);
addBox(body, [0.08, 0.08, 0.05], [-0.2, 3.58, 0.475], standardMaterial(0x7adfff), false);
addBox(body, [0.08, 0.08, 0.05], [0.24, 3.58, 0.475], standardMaterial(0x7adfff), false);
addBox(body, [0.13, 0.08, 0.06], [-0.12, 3.27, 0.42], eyeMaterial, false);
addBox(body, [0.13, 0.08, 0.06], [0, 3.25, 0.42], eyeMaterial, false);
addBox(body, [0.13, 0.08, 0.06], [0.12, 3.27, 0.42], eyeMaterial, false);
// Legs and boots.
addBox(root, [0.38, 0.82, 0.44], [-0.29, 0.67, 0], pantsMaterial);
addBox(root, [0.38, 0.82, 0.44], [0.29, 0.67, 0], pantsMaterial);
addBox(root, [0.49, 0.25, 0.68], [-0.29, 0.16, 0.09], bodyDarkMaterial);
addBox(root, [0.49, 0.25, 0.68], [0.29, 0.16, 0.09], bodyDarkMaterial);
// Static opposite arm.
const staticArm = new THREE.Group();
staticArm.position.set(-0.72, 2.62, 0);
root.add(staticArm);
addBox(staticArm, [0.5, 0.46, 0.5], [0, 0, 0], bodyDarkMaterial);
addBox(staticArm, [0.38, 1.02, 0.4], [0, -0.53, 0], bodyMaterial);
addBox(staticArm, [0.43, 0.42, 0.42], [0, -1.18, 0], skinMaterial);
// Animated arm hierarchy:
// UpperArm -> ForearmJoint -> Forearm mesh -> Hand (correct state).
const upper = new THREE.Group();
upper.name = "UpperArm";
upper.position.set(0.72, 2.62, 0);
root.add(upper);
addBox(upper, [0.52, 0.47, 0.52], [0, 0, 0], bodyDarkMaterial);
addBox(upper, [0.4, 1.04, 0.42], [0, -0.54, 0], bodyMaterial);
const forearm = new THREE.Group();
forearm.name = "ForearmJoint";
forearm.position.set(0, -1.06, 0);
upper.add(forearm);
addBox(forearm, [0.43, 0.43, 0.43], [0, 0, 0], accentMaterial);
addBox(forearm, [0.36, 0.9, 0.38], [0, -0.47, 0], bodyMaterial);
const hand = new THREE.Group();
hand.name = "Hand_R";
hand.userData.isHand = true;
addBox(hand, [0.48, 0.42, 0.42], [0, -0.2, 0], handMaterial);
addBox(hand, [0.12, 0.28, 0.34], [-0.14, -0.51, 0], handMaterial);
addBox(hand, [0.12, 0.28, 0.34], [0, -0.51, 0], handMaterial);
addBox(hand, [0.12, 0.28, 0.34], [0.14, -0.51, 0], handMaterial);
addBox(hand, [0.13, 0.28, 0.32], [0.27, -0.18, 0], handMaterial);
hand.traverse((object) => {
if (object.isMesh) {
object.userData.handPart = true;
}
});
const tipMaterial = new THREE.MeshBasicMaterial({ color: 0xffb547 });
const handTip = new THREE.Mesh(
new THREE.BoxGeometry(0.065, 0.065, 0.065),
tipMaterial
);
handTip.position.set(0, -0.67, 0);
hand.add(handTip);
return {
root,
upper,
forearm,
hand,
handTip,
handMaterial,
tipMaterial,
fixed: false,
selected: false
};
}
const candidateScene = createScene(0x10182a);
const referenceScene = createScene(0x0d1928);
const candidate = createRig(candidateScene);
const reference = createRig(referenceScene);
// The intentional fault: Hand_R is parented to UpperArm.
candidate.upper.add(candidate.hand);
candidate.hand.position.set(0, -1.92, 0);
candidate.hand.rotation.set(0, 0, 0);
// Correct reference hierarchy: Hand_R is parented to ForearmJoint.
reference.forearm.add(reference.hand);
reference.hand.position.set(0, -0.86, 0);
reference.hand.rotation.set(0, 0, 0);
reference.fixed = true;
reference.handMaterial.color.setHex(0x58e6c7);
reference.tipMaterial.color.setHex(0x58e6c7);
// -------------------------------------------------------------------------
// Hand trails
// -------------------------------------------------------------------------
const MAX_TRAIL_POINTS = 100;
function createTrail(scene, color) {
const positions = new Float32Array(MAX_TRAIL_POINTS * 3);
const geometry = new THREE.BufferGeometry();
const attribute = new THREE.BufferAttribute(positions, 3);
attribute.setUsage(THREE.DynamicDrawUsage);
geometry.setAttribute("position", attribute);
geometry.setDrawRange(0, 0);
const material = new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.72
});
const line = new THREE.Line(geometry, material);
line.frustumCulled = false;
scene.add(line);
return {
positions,
attribute,
geometry,
line,
count: 0
};
}
candidate.trail = createTrail(candidateScene, 0xffb547);
reference.trail = createTrail(referenceScene, 0x58e6c7);
function clearTrail(trail) {
trail.count = 0;
trail.geometry.setDrawRange(0, 0);
}
function pushTrail(trail, position) {
if (trail.count < MAX_TRAIL_POINTS) {
const index = trail.count++;
trail.positions[index * 3] = position.x;
trail.positions[index * 3 + 1] = position.y;
trail.positions[index * 3 + 2] = position.z;
} else {
trail.positions.copyWithin(0, 3);
const index = MAX_TRAIL_POINTS - 1;
trail.positions[index * 3] = position.x;
trail.positions[index * 3 + 1] = position.y;
trail.positions[index * 3 + 2] = position.z;
}
trail.attribute.needsUpdate = true;
trail.geometry.setDrawRange(0, trail.count);
}
// -------------------------------------------------------------------------
// Hierarchy editing
// -------------------------------------------------------------------------
let toastTimer = 0;
function showToast(message) {
toast.textContent = message;
toast.classList.add("show");
window.clearTimeout(toastTimer);
toastTimer = window.setTimeout(() => {
toast.classList.remove("show");
}, 2200);
}
function setHandParent(rig, fixed) {
if (fixed) {
rig.forearm.remove(rig.hand);
rig.forearm.add(rig.hand);
rig.hand.position.set(0, -0.86, 0);
} else {
rig.forearm.remove(rig.hand);
rig.upper.add(rig.hand);
rig.hand.position.set(0, -1.92, 0);
}
rig.hand.rotation.set(0, 0, 0);
rig.fixed = fixed;
}
function updateHandAppearance() {
const color = candidate.fixed ? 0x58e6c7 : 0xffb547;
candidate.handMaterial.color.setHex(color);
candidate.tipMaterial.color.setHex(color);
if (candidate.selected) {
candidate.handMaterial.emissive.setHex(
candidate.fixed ? 0x0b5f52 : 0x713100
);
candidate.handMaterial.emissiveIntensity = 0.75;
} else {
candidate.handMaterial.emissive.setHex(0x000000);
candidate.handMaterial.emissiveIntensity = 0;
}
}
let metricSamples = 0;
let metricSquaredSum = 0;
function resetMetrics() {
metricSamples = 0;
metricSquaredSum = 0;
offsetValue.textContent = "0.00";
rmsValue.textContent = "0.00";
}
function repairHierarchy() {
if (candidate.fixed) {
return;
}
setHandParent(candidate, true);
candidate.selected = true;
clearTrail(candidate.trail);
resetMetrics();
updateHandAppearance();
refreshInspector();
showToast("Hand re-parented to ForearmJoint. Its motion now inherits the elbow.");
}
function restoreFault() {
if (!candidate.fixed) {
return;
}
setHandParent(candidate, false);
clearTrail(candidate.trail);
resetMetrics();
updateHandAppearance();
refreshInspector();
showToast("Incorrect parent restored: Hand_R is now under UpperArm.");
}
function selectHand() {
candidate.selected = true;
updateHandAppearance();
refreshInspector();
showToast("Candidate hand selected.");
}
// -------------------------------------------------------------------------
// Inspector tree
// -------------------------------------------------------------------------
function createTreeRow(label, depth, options = {}) {
const row = document.createElement("div");
row.className = "tree-row";
row.style.setProperty("--depth", depth);
row.style.paddingLeft = `${10 + depth * 16}px`;
const icon = document.createElement("span");
icon.className = "tree-icon";
icon.textContent = options.icon || "◇";
const text = document.createElement("span");
text.textContent = label;
row.append(icon, text);
if (options.tag) {
const tag = document.createElement("span");
tag.className = "parent-tag";
tag.textContent = options.tag;
row.append(tag);
}
if (options.className) {
row.classList.add(...options.className.split(/\s+/).filter(Boolean));
}
return row;
}
function renderTree() {
const tree = document.querySelector("#tree");
tree.replaceChildren();
tree.append(createTreeRow("Puppet_ROOT", 0, { icon: "▣" }));
tree.append(createTreeRow("Body", 1, { icon: "▤" }));
tree.append(createTreeRow("Arm_R", 1, { icon: "⌁" }));
tree.append(createTreeRow("UpperArm", 2, { icon: "▥" }));
const forearmRow = createTreeRow("ForearmJoint", 2, {
icon: "↳",
className: "drop-target"
});
forearmRow.addEventListener("dragover", (event) => {
event.preventDefault();
event.dataTransfer.dropEffect = "move";
forearmRow.classList.add("drop-hover");
});
forearmRow.addEventListener("dragleave", () => {
forearmRow.classList.remove("drop-hover");
});
forearmRow.addEventListener("drop", (event) => {
event.preventDefault();
forearmRow.classList.remove("drop-hover");
if (event.dataTransfer.getData("text/plain") === "move-hand") {
repairHierarchy();
}
});
tree.append(forearmRow);
tree.append(createTreeRow("Forearm voxels", 3, { icon: "▦" }));
const handRow = createTreeRow("Hand_R", candidate.fixed ? 3 : 2, {
icon: "✋",
tag: candidate.fixed ? "ForearmJoint" : "UpperArm",
className: `hand ${candidate.selected ? "selected" : ""}`
});
handRow.draggable = true;
handRow.title = "Click to select or drag onto ForearmJoint";
handRow.addEventListener("click", selectHand);
handRow.addEventListener("dragstart", (event) => {
event.dataTransfer.setData("text/plain", "move-hand");
event.dataTransfer.effectAllowed = "move";
handRow.classList.add("dragging");
});
handRow.addEventListener("dragend", () => {
handRow.classList.remove("dragging");
});
tree.append(handRow);
}
function refreshInspector() {
renderTree();
if (candidate.fixed) {
candidateState.textContent = "FIXED";
candidateState.className = "state-pill good";
hierarchyStatus.className = "status-box good";
hierarchyStatus.textContent =
"CORRECT: Hand_R → ForearmJoint. The hand inherits both shoulder and elbow motion.";
repairButton.disabled = true;
breakButton.disabled = false;
} else {
candidateState.textContent = "BROKEN";
candidateState.className = "state-pill bad";
hierarchyStatus.className = "status-box";
hierarchyStatus.textContent =
"INCORRECT: Hand_R → UpperArm. Rotating the forearm does not carry the hand.";
repairButton.disabled = false;
breakButton.disabled = true;
}
updateHandAppearance();
}
repairButton.addEventListener("click", repairHierarchy);
breakButton.addEventListener("click", restoreFault);
document.querySelector("#select-hand-button").addEventListener("click", selectHand);
document.querySelector("#reset-camera-button").addEventListener("click", resetCamera);
// -------------------------------------------------------------------------
// Joint input and transport
// -------------------------------------------------------------------------
function readManualInputs() {
state.shoulder = degreesToRadians(Number(shoulderInput.value));
state.elbow = degreesToRadians(Number(elbowInput.value));
state.wrist = degreesToRadians(Number(wristInput.value));
state.manual = true;
state.playing = false;
}
[shoulderInput, elbowInput, wristInput].forEach((input) => {
input.addEventListener("input", readManualInputs);
});
function updateJointValues(delta) {
if (state.playing && !state.manual) {
state.time += delta * state.speed;
const t = state.time;
state.shoulder = Math.sin(t * 1.06) * 0.82;
state.elbow = 0.48 + Math.sin(t * 0.88 + 0.72) * 0.72;
state.wrist = Math.sin(t * 1.48 + 0.25) * 0.88;
}
const shoulderDegrees = Math.round(radiansToDegrees(state.shoulder));
const elbowDegrees = Math.round(radiansToDegrees(state.elbow));
const wristDegrees = Math.round(radiansToDegrees(state.wrist));
if (!state.manual) {
shoulderInput.value = shoulderDegrees;
elbowInput.value = elbowDegrees;
wristInput.value = wristDegrees;
}
shoulderOutput.textContent = `${shoulderDegrees}°`;
elbowOutput.textContent = `${elbowDegrees}°`;
wristOutput.textContent = `${wristDegrees}°`;
timeValue.textContent = `${state.time.toFixed(2)} s`;
inputReadout.textContent =
`A: ${shoulderDegrees}, ${elbowDegrees}, ${wristDegrees}\n` +
`B: ${shoulderDegrees}, ${elbowDegrees}, ${wristDegrees}\n` +
`Parity: 3 / 3 channels`;
playButton.textContent = state.playing ? "Pause" : "Play";
}
function applyPose(rig) {
rig.upper.rotation.z = state.shoulder;
rig.forearm.rotation.z = state.elbow;
rig.hand.rotation.z = state.wrist;
}
function startSweep() {
state.time = 0;
state.playing = true;
state.manual = false;
clearTrail(candidate.trail);
clearTrail(reference.trail);
resetMetrics();
}
playButton.addEventListener("click", () => {
if (state.playing) {
state.playing = false;
} else {
state.playing = true;
state.manual = false;
}
});
document.querySelector("#sweep-button").addEventListener("click", startSweep);
document.querySelector("#run-sweep").addEventListener("click", startSweep);
speedInput.addEventListener("input", () => {
state.speed = Number(speedInput.value);
speedOutput.textContent = `${state.speed.toFixed(2)}×`;
});
// -------------------------------------------------------------------------
// Direct camera controls and hand picking
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let dragging = false;
let pointerStartX = 0;
let pointerStartY = 0;
let previousX = 0;
let previousY = 0;
let dragDistance = 0;
let verticalLayout = false;
let viewWidth = 1;
let viewHeight = 1;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
pointerStartX = event.clientX;
pointerStartY = event.clientY;
previousX = event.clientX;
previousY = event.clientY;
dragDistance = 0;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) {
return;
}
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
dragDistance += Math.abs(dx) + Math.abs(dy);
orbit.yaw -= dx * 0.006;
orbit.pitch = THREE.MathUtils.clamp(
orbit.pitch + dy * 0.005,
-0.08,
0.72
);
updateCamera();
});
canvas.addEventListener("pointerup", (event) => {
dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
if (
dragDistance < 7 &&
Math.abs(event.clientX - pointerStartX) < 7 &&
Math.abs(event.clientY - pointerStartY) < 7
) {
pickHand(event);
}
});
canvas.addEventListener("pointercancel", () => {
dragging = false;
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
6.2,
14.5
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetCamera);
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
function getViewInfo(event) {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
if (verticalLayout) {
const isCandidate = y < rect.height / 2;
return {
isCandidate,
x,
y: isCandidate ? y : y - rect.height / 2,
width: rect.width,
height: rect.height / 2
};
}
const isCandidate = x < rect.width / 2;
return {
isCandidate,
x: isCandidate ? x : x - rect.width / 2,
y,
width: rect.width / 2,
height: rect.height
};
}
function pickHand(event) {
const view = getViewInfo(event);
if (!view.isCandidate) {
showToast("Reference B is intentionally fixed. Edit candidate A.");
return;
}
pointer.x = (view.x / view.width) * 2 - 1;
pointer.y = -(view.y / view.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(
candidateScene.children,
true
);
const handHit = intersections.find((intersection) => {
let object = intersection.object;
while (object) {
if (object.userData.isHand) {
return true;
}
object = object.parent;
}
return false;
});
if (handHit) {
selectHand();
}
}
window.addEventListener("keydown", (event) => {
const target = event.target;
if (
target instanceof HTMLInputElement ||
target instanceof HTMLButtonElement
) {
return;
}
if (event.code === "Space") {
event.preventDefault();
playButton.click();
} else if (event.key.toLowerCase() === "r") {
repairHierarchy();
} else if (event.key.toLowerCase() === "b") {
restoreFault();
}
});
// -------------------------------------------------------------------------
// Resize and rendering
// -------------------------------------------------------------------------
function resize() {
viewWidth = Math.max(1, canvasWrap.clientWidth);
viewHeight = Math.max(1, canvasWrap.clientHeight);
renderer.setSize(viewWidth, viewHeight, false);
verticalLayout = viewWidth < 820;
stage.classList.toggle("vertical", verticalLayout);
camera.aspect = verticalLayout
? viewWidth / (viewHeight / 2)
: (viewWidth / 2) / viewHeight;
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(canvasWrap);
resize();
const candidateTipPosition = new THREE.Vector3();
const referenceTipPosition = new THREE.Vector3();
const clock = new THREE.Clock();
let frame = 0;
function updateMetrics() {
candidate.root.updateMatrixWorld(true);
reference.root.updateMatrixWorld(true);
candidate.handTip.getWorldPosition(candidateTipPosition);
reference.handTip.getWorldPosition(referenceTipPosition);
const distance = candidateTipPosition.distanceTo(referenceTipPosition);
metricSamples++;
metricSquaredSum += distance * distance;
const rms = Math.sqrt(metricSquaredSum / Math.max(1, metricSamples));
offsetValue.textContent = distance.toFixed(2);
rmsValue.textContent = rms.toFixed(2);
const aligned = distance < 0.015;
offsetValue.className = `metric-value ${aligned ? "good" : "bad"}`;
rmsValue.className = `metric-value ${aligned ? "good" : "bad"}`;
if (frame % 2 === 0) {
pushTrail(candidate.trail, candidateTipPosition);
pushTrail(reference.trail, referenceTipPosition);
}
}
function renderScenes() {
renderer.setScissorTest(false);
renderer.setViewport(0, 0, viewWidth, viewHeight);
renderer.clear();
renderer.setScissorTest(true);
if (!verticalLayout) {
const leftWidth = Math.floor(viewWidth / 2);
const rightWidth = viewWidth - leftWidth;
renderer.setViewport(0, 0, leftWidth, viewHeight);
renderer.setScissor(0, 0, leftWidth, viewHeight);
renderer.render(candidateScene, camera);
renderer.setViewport(leftWidth, 0, rightWidth, viewHeight);
renderer.setScissor(leftWidth, 0, rightWidth, viewHeight);
renderer.render(referenceScene, camera);
} else {
const bottomHeight = Math.floor(viewHeight / 2);
const topHeight = viewHeight - bottomHeight;
// Candidate A occupies the top half in CSS coordinates.
renderer.setViewport(0, bottomHeight, viewWidth, topHeight);
renderer.setScissor(0, bottomHeight, viewWidth, topHeight);
renderer.render(candidateScene, camera);
// Reference B occupies the bottom half.
renderer.setViewport(0, 0, viewWidth, bottomHeight);
renderer.setScissor(0, 0, viewWidth, bottomHeight);
renderer.render(referenceScene, camera);
}
}
function animate() {
const delta = Math.min(clock.getDelta(), 0.05);
updateJointValues(delta);
// The exact same state object drives both rigs.
applyPose(candidate);
applyPose(reference);
updateMetrics();
renderScenes();
frame++;
}
refreshInspector();
renderer.setAnimationLoop(animate);
loading.style.display = "none";
</script>
</body>
</html>
```