Prompt specification
Build or customize the Three.js 3D scene "Equipment case organization 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: Equipment case organization puzzle
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/equipment-case-organization-puzzle-x0311
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing socket adapters. Build an open maintenance case with labeled recesses and mixed adapters; users place components in matching cavities and assemble one tool path from selected pieces. Stylized solid forms.
Working Three.js Starter (equipment-case-organization-puzzle-x0311):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Socket Adapter Maintenance Case</title>
<style>
:root {
--ink: #eef7f5;
--muted: #9eb3b0;
--panel: rgba(18, 30, 35, 0.88);
--panel-border: rgba(180, 221, 214, 0.16);
--accent: #58e0ca;
--accent-dark: #173e3b;
--danger: #ff806f;
--shadow: 0 20px 60px rgba(3, 10, 13, 0.28);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #cbd4d0;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
background:
radial-gradient(circle at 47% 32%, #eef4f0 0, #d5ded9 42%, #aab8b2 100%);
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.panel {
position: fixed;
z-index: 10;
border: 1px solid var(--panel-border);
border-radius: 18px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(18px) saturate(125%);
-webkit-backdrop-filter: blur(18px) saturate(125%);
}
.intro {
top: 24px;
left: 24px;
width: min(390px, calc(100vw - 48px));
padding: 22px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 13px;
color: var(--accent);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
width: 8px;
height: 8px;
border-radius: 2px;
background: var(--accent);
box-shadow: 0 0 16px rgba(88, 224, 202, 0.65);
content: "";
}
h1 {
max-width: 330px;
margin: 0;
font-size: clamp(28px, 3.2vw, 43px);
font-weight: 720;
line-height: 0.98;
letter-spacing: -0.055em;
}
.intro p {
margin: 15px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.progress-block {
margin-top: 20px;
padding-top: 17px;
border-top: 1px solid rgba(255, 255, 255, 0.09);
}
.progress-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 9px;
font-size: 11px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.progress-row span:last-child {
color: var(--accent);
}
.progress-track {
height: 5px;
overflow: hidden;
border-radius: 99px;
background: rgba(255, 255, 255, 0.09);
}
#progress-fill {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #42bda9, #7bf0d8);
transition: width 350ms ease;
}
.objective {
min-height: 34px;
margin-top: 12px;
color: #c4d4d1;
font-size: 12px;
line-height: 1.45;
}
.manifest {
top: 24px;
right: 24px;
width: 350px;
max-height: calc(100vh - 48px);
overflow: auto;
padding: 18px;
}
.manifest-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
margin-bottom: 12px;
}
.manifest-header h2 {
margin: 0 0 4px;
font-size: 17px;
letter-spacing: -0.02em;
}
.manifest-header p {
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 1.4;
}
.case-count {
flex: 0 0 auto;
padding: 6px 8px;
border: 1px solid rgba(88, 224, 202, 0.24);
border-radius: 8px;
background: rgba(88, 224, 202, 0.08);
color: var(--accent);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
}
.part-list {
display: grid;
gap: 7px;
}
.part-row {
display: grid;
grid-template-columns: 1fr 48px;
min-height: 58px;
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.075);
border-radius: 11px;
background: rgba(255, 255, 255, 0.035);
transition:
border-color 180ms ease,
background 180ms ease,
transform 180ms ease;
}
.part-row.active {
border-color: rgba(88, 224, 202, 0.72);
background: rgba(88, 224, 202, 0.09);
transform: translateX(-2px);
}
.part-row.seated {
background: rgba(255, 255, 255, 0.055);
}
.part-main {
display: grid;
grid-template-columns: 8px 1fr;
align-items: center;
gap: 11px;
min-width: 0;
padding: 9px 10px;
border: 0;
color: inherit;
text-align: left;
background: transparent;
cursor: pointer;
}
.swatch {
width: 8px;
height: 34px;
border-radius: 99px;
background: var(--swatch);
box-shadow: 0 0 12px color-mix(in srgb, var(--swatch), transparent 55%);
}
.part-copy {
min-width: 0;
}
.part-name {
display: block;
overflow: hidden;
font-size: 12px;
font-weight: 680;
text-overflow: ellipsis;
white-space: nowrap;
}
.part-meta {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 10px;
letter-spacing: 0.025em;
}
.use-toggle {
display: grid;
place-items: center;
border: 0;
border-left: 1px solid rgba(255, 255, 255, 0.07);
color: #718784;
background: transparent;
cursor: pointer;
transition: 160ms ease;
}
.use-toggle span {
font-size: 8px;
font-weight: 900;
letter-spacing: 0.09em;
}
.use-toggle:disabled {
cursor: default;
opacity: 0.3;
}
.use-toggle:not(:disabled):hover,
.use-toggle.chosen {
color: #071b19;
background: var(--accent);
}
.assembly-area {
margin-top: 14px;
padding-top: 14px;
border-top: 1px solid rgba(255, 255, 255, 0.09);
}
.assembly-status {
min-height: 34px;
margin-bottom: 10px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.primary-button,
.secondary-button,
.view-button {
border-radius: 10px;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.035em;
cursor: pointer;
transition:
transform 150ms ease,
opacity 150ms ease,
background 150ms ease;
}
.primary-button {
width: 100%;
padding: 12px 13px;
border: 0;
color: #09201e;
background: var(--accent);
box-shadow: 0 8px 24px rgba(41, 170, 150, 0.18);
}
.primary-button:not(:disabled):hover {
transform: translateY(-1px);
background: #76ecd8;
}
.primary-button:disabled {
cursor: not-allowed;
opacity: 0.34;
box-shadow: none;
}
.secondary-button {
width: 100%;
margin-top: 7px;
padding: 9px 12px;
border: 1px solid rgba(255, 255, 255, 0.13);
color: var(--ink);
background: rgba(255, 255, 255, 0.045);
}
.secondary-button:hover {
background: rgba(255, 255, 255, 0.09);
}
.secondary-button[hidden] {
display: none;
}
.scene-hint {
position: fixed;
z-index: 8;
left: 50%;
bottom: 25px;
display: flex;
align-items: center;
gap: 10px;
max-width: calc(100vw - 40px);
padding: 10px 14px;
transform: translateX(-50%);
border: 1px solid rgba(21, 44, 45, 0.12);
border-radius: 99px;
color: #334944;
background: rgba(244, 249, 246, 0.82);
box-shadow: 0 10px 30px rgba(32, 51, 46, 0.12);
backdrop-filter: blur(12px);
font-size: 11px;
font-weight: 650;
white-space: nowrap;
}
.hint-dot {
width: 7px;
height: 7px;
flex: 0 0 auto;
border-radius: 50%;
background: #1caa93;
box-shadow: 0 0 0 4px rgba(28, 170, 147, 0.14);
}
.view-tools {
position: fixed;
z-index: 8;
right: 24px;
bottom: 24px;
display: flex;
gap: 7px;
}
.view-button {
padding: 9px 11px;
border: 1px solid rgba(21, 44, 45, 0.13);
color: #304a45;
background: rgba(244, 249, 246, 0.84);
box-shadow: 0 8px 20px rgba(32, 51, 46, 0.1);
backdrop-filter: blur(12px);
}
.view-button:hover {
transform: translateY(-1px);
background: rgba(255, 255, 255, 0.96);
}
#toast {
position: fixed;
z-index: 30;
left: 50%;
top: 24px;
max-width: min(480px, calc(100vw - 32px));
padding: 11px 16px;
transform: translate(-50%, -22px);
border: 1px solid rgba(88, 224, 202, 0.3);
border-radius: 10px;
color: #ecfffa;
background: rgba(18, 42, 40, 0.94);
box-shadow: var(--shadow);
opacity: 0;
pointer-events: none;
font-size: 12px;
font-weight: 650;
transition:
opacity 180ms ease,
transform 180ms ease;
}
#toast.visible {
transform: translate(-50%, 0);
opacity: 1;
}
#toast.error {
border-color: rgba(255, 128, 111, 0.45);
color: #ffe5e0;
background: rgba(66, 29, 29, 0.95);
}
@media (max-width: 900px) {
.intro {
top: 12px;
left: 12px;
width: min(340px, calc(100vw - 24px));
padding: 17px;
}
.intro p {
display: none;
}
.progress-block {
margin-top: 14px;
padding-top: 12px;
}
.manifest {
top: auto;
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
max-height: 42vh;
padding: 14px;
}
.part-list {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.scene-hint {
display: none;
}
.view-tools {
right: 12px;
bottom: calc(42vh + 23px);
}
}
@media (max-width: 540px) {
h1 {
font-size: 28px;
}
.manifest-header p {
display: none;
}
.part-list {
grid-template-columns: 1fr;
}
.part-row {
min-height: 49px;
}
.view-tools {
bottom: calc(42vh + 23px);
}
}
</style>
</head>
<body>
<div id="scene" aria-label="Interactive 3D socket adapter maintenance case"></div>
<section class="panel intro">
<div class="eyebrow">Service Bench / Kit 07</div>
<h1>Pack it. Connect it. Build the path.</h1>
<p>
Select a loose component, then place it in its matching labeled recess.
Once the case is packed, choose the pieces for a single working tool path.
</p>
<div class="progress-block">
<div class="progress-row">
<span>Case packing</span>
<span id="progress-text">0 / 6 seated</span>
</div>
<div class="progress-track"><div id="progress-fill"></div></div>
<div id="objective" class="objective">
Select a component from the manifest or on the bench.
</div>
</div>
</section>
<aside class="panel manifest">
<div class="manifest-header">
<div>
<h2>Component manifest</h2>
<p>Select to place. Toggle PATH after seating.</p>
</div>
<div id="case-count" class="case-count">0 / 6</div>
</div>
<div id="part-list" class="part-list"></div>
<div class="assembly-area">
<div id="assembly-status" class="assembly-status">
Seat components, then select two or more for the tool path.
</div>
<button id="assemble-button" class="primary-button" disabled>
Assemble tool path
</button>
<button id="return-button" class="secondary-button" hidden>
Return path pieces to case
</button>
</div>
</aside>
<div class="scene-hint">
<span class="hint-dot"></span>
<span id="hint-text">Drag a part into a matching recess · Drag background to orbit · Scroll to zoom</span>
</div>
<div class="view-tools">
<button id="reset-view" class="view-button">Reset view</button>
<button id="reset-layout" class="view-button">Reset case</button>
</div>
<div id="toast" role="status" aria-live="polite"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene setup
// -------------------------------------------------------------------------
const sceneHost = document.getElementById("scene");
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0xcbd4d0, 23, 48);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.domElement.setAttribute("tabindex", "0");
sceneHost.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraState = {
yaw: 0.57,
pitch: 0.50,
distance: 18.8,
target: new THREE.Vector3(0, 1.15, 0.75)
};
function updateCamera() {
const { yaw, pitch, distance, target } = cameraState;
const horizontal = Math.cos(pitch) * distance;
camera.position.set(
target.x + Math.sin(yaw) * horizontal,
target.y + Math.sin(pitch) * distance,
target.z + Math.cos(yaw) * horizontal
);
camera.lookAt(target);
}
updateCamera();
const hemi = new THREE.HemisphereLight(0xf2fff9, 0x43514e, 2.1);
scene.add(hemi);
const keyLight = new THREE.DirectionalLight(0xfff8e9, 3.1);
keyLight.position.set(-8, 15, 10);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -15;
keyLight.shadow.camera.right = 15;
keyLight.shadow.camera.top = 14;
keyLight.shadow.camera.bottom = -14;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 38;
keyLight.shadow.bias = -0.0005;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0x8fd8e0, 1.25);
fillLight.position.set(9, 7, 3);
scene.add(fillLight);
const rimLight = new THREE.DirectionalLight(0xffc27b, 0.9);
rimLight.position.set(0, 8, -12);
scene.add(rimLight);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(70, 70),
new THREE.MeshStandardMaterial({
color: 0xaebbb5,
roughness: 0.96,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.16;
ground.receiveShadow = true;
scene.add(ground);
// -------------------------------------------------------------------------
// Geometry helpers
// -------------------------------------------------------------------------
function roundedRectShape(width, height, radius) {
const x = -width / 2;
const y = -height / 2;
const r = Math.min(radius, width / 2, height / 2);
const shape = new THREE.Shape();
shape.moveTo(x + r, y);
shape.lineTo(x + width - r, y);
shape.quadraticCurveTo(x + width, y, x + width, y + r);
shape.lineTo(x + width, y + height - r);
shape.quadraticCurveTo(
x + width,
y + height,
x + width - r,
y + height
);
shape.lineTo(x + r, y + height);
shape.quadraticCurveTo(x, y + height, x, y + height - r);
shape.lineTo(x, y + r);
shape.quadraticCurveTo(x, y, x + r, y);
return shape;
}
function roundedPrism(
width,
height,
depth,
radius,
material,
horizontal = true
) {
const geometry = new THREE.ExtrudeGeometry(
roundedRectShape(width, height, radius),
{
depth,
steps: 1,
bevelEnabled: true,
bevelSegments: 3,
bevelSize: Math.min(0.08, depth * 0.25),
bevelThickness: Math.min(0.08, depth * 0.25)
}
);
geometry.center();
if (horizontal) {
geometry.rotateX(Math.PI / 2);
}
const mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
function standardMaterial(color, metalness = 0.65, roughness = 0.32) {
return new THREE.MeshStandardMaterial({
color,
metalness,
roughness
});
}
function makeCanvasTexture(draw, width = 1024, height = 256) {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const context = canvas.getContext("2d");
draw(context, width, height);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(
8,
renderer.capabilities.getMaxAnisotropy()
);
return texture;
}
function makeFlatLabel(title, subtitle, width, height) {
const texture = makeCanvasTexture((ctx, w, h) => {
ctx.clearRect(0, 0, w, h);
ctx.fillStyle = "rgba(17, 29, 35, 0.88)";
ctx.strokeStyle = "rgba(120, 180, 171, 0.28)";
ctx.lineWidth = 5;
ctx.beginPath();
ctx.roundRect(5, 5, w - 10, h - 10, 24);
ctx.fill();
ctx.stroke();
ctx.fillStyle = "#e8f5f1";
ctx.font = "800 54px system-ui, sans-serif";
ctx.textAlign = "left";
ctx.textBaseline = "middle";
ctx.fillText(title, 32, subtitle ? h * 0.41 : h * 0.52);
if (subtitle) {
ctx.fillStyle = "#8ba6a1";
ctx.font = "650 28px system-ui, sans-serif";
ctx.fillText(subtitle, 34, h * 0.72);
}
});
const mesh = new THREE.Mesh(
new THREE.PlaneGeometry(width, height),
new THREE.MeshBasicMaterial({
map: texture,
transparent: true,
depthWrite: false,
toneMapped: false
})
);
mesh.rotation.x = -Math.PI / 2;
mesh.renderOrder = 3;
return mesh;
}
function makeVerticalLabel(title, subtitle, width, height) {
const texture = makeCanvasTexture((ctx, w, h) => {
ctx.clearRect(0, 0, w, h);
ctx.fillStyle = "#d9e9e4";
ctx.font = "800 48px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(title, w / 2, subtitle ? h * 0.4 : h * 0.5);
if (subtitle) {
ctx.fillStyle = "#78928d";
ctx.font = "650 26px system-ui, sans-serif";
ctx.fillText(subtitle, w / 2, h * 0.71);
}
});
return new THREE.Mesh(
new THREE.PlaneGeometry(width, height),
new THREE.MeshBasicMaterial({
map: texture,
transparent: true,
depthWrite: false,
toneMapped: false
})
);
}
// -------------------------------------------------------------------------
// Open maintenance case
// -------------------------------------------------------------------------
const caseMaterial = standardMaterial(0x315d56, 0.24, 0.48);
const caseEdgeMaterial = standardMaterial(0x193d38, 0.3, 0.44);
const foamMaterial = standardMaterial(0x18282f, 0.02, 0.93);
const pocketMaterial = standardMaterial(0x101c22, 0.02, 0.95);
const benchMaterial = standardMaterial(0x6b7d76, 0.18, 0.72);
const base = roundedPrism(12.4, 8.2, 0.62, 0.5, caseMaterial);
base.position.set(0, 0.27, 0);
scene.add(base);
const lowerTrim = roundedPrism(
12.55,
8.35,
0.16,
0.52,
caseEdgeMaterial
);
lowerTrim.position.set(0, -0.06, 0);
scene.add(lowerTrim);
const foam = roundedPrism(11.55, 7.35, 0.17, 0.38, foamMaterial);
foam.position.set(0, 0.68, 0);
scene.add(foam);
const lid = roundedPrism(
12.4,
8.2,
0.34,
0.5,
caseMaterial,
false
);
lid.position.set(0, 4.2, -4.25);
scene.add(lid);
const lidInset = roundedPrism(
11.55,
7.35,
0.15,
0.38,
foamMaterial,
false
);
lidInset.position.set(0, 4.2, -4.03);
scene.add(lidInset);
for (const x of [-3.55, 0, 3.55]) {
const pocket = roundedPrism(
2.72,
5.45,
0.055,
0.25,
pocketMaterial,
false
);
pocket.position.set(x, 4.05, -3.91);
scene.add(pocket);
}
const lidTitle = makeVerticalLabel(
"FIELD SERVICE",
"SOCKET ADAPTER KIT / 07",
4.6,
0.9
);
lidTitle.position.set(0, 7.25, -3.89);
scene.add(lidTitle);
const hingeMaterial = standardMaterial(0x4d5d5a, 0.8, 0.28);
for (const x of [-3.5, 3.5]) {
const hinge = new THREE.Mesh(
new THREE.CylinderGeometry(0.18, 0.18, 1.15, 24),
hingeMaterial
);
hinge.rotation.z = Math.PI / 2;
hinge.position.set(x, 0.35, -4.05);
hinge.castShadow = true;
scene.add(hinge);
}
const stagingTray = roundedPrism(
14.5,
3.15,
0.17,
0.35,
benchMaterial
);
stagingTray.position.set(0, -0.02, 5.28);
scene.add(stagingTray);
const screwMaterial = standardMaterial(0x6e7f79, 0.9, 0.28);
for (const [x, z] of [
[-5.25, -3.1],
[5.25, -3.1],
[-5.25, 3.1],
[5.25, 3.1]
]) {
const screw = new THREE.Mesh(
new THREE.CylinderGeometry(0.07, 0.07, 0.035, 16),
screwMaterial
);
screw.position.set(x, 0.79, z);
scene.add(screw);
}
// -------------------------------------------------------------------------
// Recesses and component definitions
// -------------------------------------------------------------------------
const cavityHitMeshes = [];
const cavities = new Map();
function addCircularCavity(id, code, title, x, z, radius, color) {
const pocket = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius * 0.96, 0.09, 40),
pocketMaterial
);
pocket.position.set(x, 0.81, z);
pocket.receiveShadow = true;
pocket.userData.cavityId = id;
scene.add(pocket);
cavityHitMeshes.push(pocket);
const rimMaterial = new THREE.MeshBasicMaterial({
color: 0x61dec9,
transparent: true,
opacity: 0.17,
depthWrite: false
});
const rim = new THREE.Mesh(
new THREE.TorusGeometry(radius + 0.035, 0.038, 8, 48),
rimMaterial
);
rim.rotation.x = Math.PI / 2;
rim.position.set(x, 0.875, z);
rim.renderOrder = 4;
scene.add(rim);
const label = makeFlatLabel(code, title, 1.85, 0.48);
label.position.set(x, 0.865, z + radius + 0.42);
scene.add(label);
cavities.set(id, {
id,
code,
title,
x,
z,
radius,
hit: pocket,
rim,
color
});
}
function addSlotCavity(id, code, title, x, z, width, depth, color) {
const pocket = new THREE.Mesh(
new THREE.BoxGeometry(width, 0.09, depth),
pocketMaterial
);
pocket.position.set(x, 0.81, z);
pocket.receiveShadow = true;
pocket.userData.cavityId = id;
scene.add(pocket);
cavityHitMeshes.push(pocket);
const rimMaterial = new THREE.MeshBasicMaterial({
color: 0x61dec9,
transparent: true,
opacity: 0.17,
depthWrite: false
});
const rim = new THREE.Mesh(
new THREE.TorusGeometry(1, 0.04, 8, 64),
rimMaterial
);
rim.rotation.x = Math.PI / 2;
rim.scale.set(width * 0.53, depth * 0.63, 1);
rim.position.set(x, 0.875, z);
rim.renderOrder = 4;
scene.add(rim);
const label = makeFlatLabel(code, title, 2.3, 0.48);
label.position.set(x, 0.865, z + depth * 0.5 + 0.42);
scene.add(label);
cavities.set(id, {
id,
code,
title,
x,
z,
radius: Math.max(width, depth) * 0.5,
hit: pocket,
rim,
color
});
}
addCircularCavity(
"drive",
"A1",
"1/2 IN DRIVE",
-4.25,
-1.65,
0.77,
0xe96b58
);
addCircularCavity(
"reducer",
"A2",
"3/8 IN REDUCER",
-1.9,
-1.65,
0.71,
0x4d9fd0
);
addSlotCavity(
"extension",
"A3",
"90 MM EXTENSION",
0.7,
-1.65,
2.8,
0.62,
0xe6ad48
);
addCircularCavity(
"socket10",
"S1",
"10 MM SOCKET",
3.65,
-1.65,
0.64,
0xd8bc55
);
addCircularCavity(
"socket13",
"S2",
"13 MM SOCKET",
-3.1,
1.2,
0.77,
0x5bbd83
);
addCircularCavity(
"impact",
"I1",
"15 MM IMPACT",
0.15,
1.2,
0.82,
0x66747e
);
const partDefinitions = [
{
id: "drive",
name: "1/2 in Drive Adapter",
code: "DRIVE",
cavity: "drive",
color: 0xe96b58,
type: "adapter",
width: 1.18,
radius: 0.74,
height: 1.12,
loose: new THREE.Vector3(-5.2, 0.57, 5.15)
},
{
id: "reducer",
name: "3/8 in Reducer",
code: "REDUCER",
cavity: "reducer",
color: 0x4d9fd0,
type: "adapter",
width: 1.18,
radius: 0.68,
height: 1.12,
loose: new THREE.Vector3(-3.05, 0.53, 5.15)
},
{
id: "extension",
name: "90 mm Extension",
code: "EXT 90",
cavity: "extension",
color: 0xe6ad48,
type: "extension",
width: 2.45,
radius: 0.22,
height: 2.45,
loose: new THREE.Vector3(-0.35, 0.23, 5.12)
},
{
id: "socket10",
name: "10 mm Socket",
code: "10 MM",
cavity: "socket10",
color: 0xd8bc55,
type: "socket",
width: 0.92,
radius: 0.56,
height: 0.92,
loose: new THREE.Vector3(2.2, 0.48, 5.15)
},
{
id: "socket13",
name: "13 mm Socket",
code: "13 MM",
cavity: "socket13",
color: 0x5bbd83,
type: "socket",
width: 1.08,
radius: 0.68,
height: 1.08,
loose: new THREE.Vector3(3.9, 0.58, 5.15)
},
{
id: "impact",
name: "15 mm Impact Socket",
code: "15 IMPACT",
cavity: "impact",
color: 0x66747e,
type: "impact",
width: 1.1,
radius: 0.72,
height: 1.1,
loose: new THREE.Vector3(5.6, 0.61, 5.15)
}
];
const parts = new Map();
const allPartMeshes = [];
const chrome = standardMaterial(0xd2dadd, 0.88, 0.22);
const darkSteel = standardMaterial(0x4a555d, 0.82, 0.28);
const recessMaterial = standardMaterial(0x11191e, 0.65, 0.45);
const squareDriveMaterial = standardMaterial(0xaeb8bb, 0.9, 0.24);
function tagPart(root, id) {
root.traverse((child) => {
if (child.isMesh) {
child.userData.partId = id;
allPartMeshes.push(child);
}
});
}
function createSocket(definition, impact = false) {
const group = new THREE.Group();
const bodyMaterial = impact ? darkSteel.clone() : chrome.clone();
const accentMaterial = standardMaterial(definition.color, 0.58, 0.29);
const r = definition.radius;
const h = definition.height;
const body = new THREE.Mesh(
new THREE.CylinderGeometry(r * 0.86, r * 0.98, h * 0.72, 36),
bodyMaterial
);
group.add(body);
const lower = new THREE.Mesh(
new THREE.CylinderGeometry(r * 0.99, r * 0.94, h * 0.22, 36),
bodyMaterial
);
lower.position.y = -h * 0.34;
group.add(lower);
const band = new THREE.Mesh(
new THREE.CylinderGeometry(r * 0.96, r * 0.96, h * 0.16, 36),
accentMaterial
);
band.position.y = -h * 0.18;
group.add(band);
const rim = new THREE.Mesh(
new THREE.TorusGeometry(r * 0.58, 0.065, 10, 40),
chrome
);
rim.rotation.x = Math.PI / 2;
rim.position.y = h * 0.37;
group.add(rim);
const opening = new THREE.Mesh(
new THREE.CylinderGeometry(r * 0.49, r * 0.49, 0.05, impact ? 6 : 12),
recessMaterial
);
opening.position.y = h * 0.38;
group.add(opening);
const lowerRing = new THREE.Mesh(
new THREE.TorusGeometry(r * 0.87, 0.025, 8, 36),
darkSteel
);
lowerRing.rotation.x = Math.PI / 2;
lowerRing.position.y = -h * 0.42;
group.add(lowerRing);
return group;
}
function createAdapter(definition) {
const group = new THREE.Group();
const body = standardMaterial(0xc7d1d4, 0.86, 0.25);
const accent = standardMaterial(definition.color, 0.58, 0.3);
const lower = new THREE.Mesh(
new THREE.CylinderGeometry(
definition.radius * 0.88,
definition.radius,
0.38,
36
),
body
);
lower.position.y = -0.29;
group.add(lower);
const upper = new THREE.Mesh(
new THREE.CylinderGeometry(0.43, 0.5, 0.63, 36),
body
);
upper.position.y = 0.22;
group.add(upper);
const collar = new THREE.Mesh(
new THREE.CylinderGeometry(0.54, 0.54, 0.17, 36),
accent
);
collar.position.y = -0.08;
group.add(collar);
const square = new THREE.Mesh(
new THREE.BoxGeometry(0.29, 0.22, 0.29),
squareDriveMaterial
);
square.position.y = 0.61;
group.add(square);
const opening = new THREE.Mesh(
new THREE.CylinderGeometry(0.21, 0.21, 0.04, 12),
recessMaterial
);
opening.position.y = 0.73;
group.add(opening);
return group;
}
function createExtension(definition) {
const group = new THREE.Group();
const bodyMaterial = standardMaterial(0xc9d2d4, 0.9, 0.23);
const accent = standardMaterial(definition.color, 0.64, 0.3);
const bar = new THREE.Mesh(
new THREE.CylinderGeometry(0.14, 0.14, 2.25, 28),
bodyMaterial
);
group.add(bar);
for (const y of [-1.03, 1.03]) {
const collar = new THREE.Mesh(
new THREE.CylinderGeometry(0.22, 0.22, 0.28, 28),
accent
);
collar.position.y = y;
group.add(collar);
const lip = new THREE.Mesh(
new THREE.TorusGeometry(0.18, 0.035, 8, 28),
chrome
);
lip.rotation.x = Math.PI / 2;
lip.position.y = y + (y > 0 ? 0.14 : -0.14);
group.add(lip);
}
return group;
}
for (const definition of partDefinitions) {
let root;
if (definition.type === "socket") {
root = createSocket(definition, false);
} else if (definition.type === "impact") {
root = createSocket(definition, true);
} else if (definition.type === "adapter") {
root = createAdapter(definition);
} else {
root = createExtension(definition);
}
root.position.copy(definition.loose);
root.rotation.z = Math.PI / 2;
root.userData.partId = definition.id;
tagPart(root, definition.id);
scene.add(root);
const label = makeFlatLabel(
definition.code,
"",
definition.type === "extension" ? 1.65 : 1.45,
0.36
);
label.position.set(
definition.loose.x,
0.085,
definition.loose.z + 0.78
);
scene.add(label);
parts.set(definition.id, {
...definition,
root,
seated: false,
placing: false,
assembled: false,
looseQuaternion: root.quaternion.clone()
});
}
const haloMaterial = new THREE.MeshBasicMaterial({
color: 0x5be7cf,
transparent: true,
opacity: 0.85,
depthWrite: false
});
const selectionHalo = new THREE.Mesh(
new THREE.TorusGeometry(1, 0.025, 8, 64),
haloMaterial
);
selectionHalo.rotation.x = Math.PI / 2;
selectionHalo.visible = false;
selectionHalo.renderOrder = 5;
scene.add(selectionHalo);
// -------------------------------------------------------------------------
// Application state
// -------------------------------------------------------------------------
const state = {
selectedPart: null,
seatedCount: 0,
pathSelection: new Set(),
assembled: false,
assembledParts: new Set(),
mode: "idle",
pointerDown: null,
dragPlane: new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.45)
};
const tweens = [];
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPoint = new THREE.Vector3();
const partList = document.getElementById("part-list");
const progressFill = document.getElementById("progress-fill");
const progressText = document.getElementById("progress-text");
const caseCount = document.getElementById("case-count");
const objective = document.getElementById("objective");
const assemblyStatus = document.getElementById("assembly-status");
const assembleButton = document.getElementById("assemble-button");
const returnButton = document.getElementById("return-button");
const toast = document.getElementById("toast");
const hintText = document.getElementById("hint-text");
let toastTimer = 0;
function showToast(message, isError = false) {
toast.textContent = message;
toast.classList.toggle("error", isError);
toast.classList.add("visible");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toast.classList.remove("visible");
}, 2600);
}
for (const definition of partDefinitions) {
const row = document.createElement("div");
row.className = "part-row";
row.dataset.id = definition.id;
const mainButton = document.createElement("button");
mainButton.className = "part-main";
mainButton.type = "button";
mainButton.innerHTML = `
<span class="swatch" style="--swatch:#${definition.color.toString(16).padStart(6, "0")}"></span>
<span class="part-copy">
<span class="part-name">${definition.name}</span>
<span class="part-meta">${cavities.get(definition.cavity).code} · ${cavities.get(definition.cavity).title}</span>
</span>
`;
const pathButton = document.createElement("button");
pathButton.className = "use-toggle";
pathButton.type = "button";
pathButton.disabled = true;
pathButton.title = "Include this component in the tool path";
pathButton.innerHTML = "<span>PATH</span>";
mainButton.addEventListener("click", () => {
selectPart(definition.id);
});
pathButton.addEventListener("click", (event) => {
event.stopPropagation();
togglePathPart(definition.id);
});
row.append(mainButton, pathButton);
partList.appendChild(row);
}
function updateUI() {
const seated = [...parts.values()].filter((part) => part.seated).length;
state.seatedCount = seated;
progressFill.style.width = `${(seated / parts.size) * 100}%`;
progressText.textContent = `${seated} / ${parts.size} seated`;
caseCount.textContent = `${seated} / ${parts.size}`;
if (seated === parts.size) {
objective.textContent =
"Case packed. Select two or more PATH pieces to assemble a tool path.";
} else if (state.selectedPart) {
const part = parts.get(state.selectedPart);
const cavity = cavities.get(part.cavity);
objective.textContent = `Place ${part.name} in recess ${cavity.code}.`;
} else {
objective.textContent =
"Select a component from the manifest or on the bench.";
}
for (const definition of partDefinitions) {
const part = parts.get(definition.id);
const row = partList.querySelector(`[data-id="${definition.id}"]`);
const pathButton = row.querySelector(".use-toggle");
row.classList.toggle("active", state.selectedPart === definition.id);
row.classList.toggle("seated", part.seated);
pathButton.disabled = !part.seated || state.assembled;
pathButton.classList.toggle(
"chosen",
state.pathSelection.has(definition.id)
);
}
const selectedPathParts = [...state.pathSelection]
.map((id) => parts.get(id))
.filter((part) => part.seated);
if (state.assembled) {
assembleButton.disabled = true;
assembleButton.textContent = "Tool path assembled ✓";
returnButton.hidden = false;
assemblyStatus.textContent =
`Connected: ${selectedPathParts.map((part) => part.name).join(" → ")}.`;
} else {
assembleButton.disabled = selectedPathParts.length < 2;
assembleButton.textContent =
selectedPathParts.length < 2
? "Select 2+ path pieces"
: `Assemble ${selectedPathParts.length}-piece tool path`;
returnButton.hidden = true;
if (selectedPathParts.length < 2) {
assemblyStatus.textContent =
"Seat components, then select two or more for the tool path.";
} else {
assemblyStatus.textContent =
`Ready to connect: ${selectedPathParts.map((part) => part.code).join(" → ")}.`;
}
}
}
function clearPartGlow(part) {
part.root.traverse((child) => {
if (child.isMesh && child.material?.emissive) {
child.material.emissive.set(0x000000);
child.material.emissiveIntensity = 0;
}
});
}
function glowPart(part) {
part.root.traverse((child) => {
if (child.isMesh && child.material?.emissive) {
child.material.emissive.set(0x21bba8);
child.material.emissiveIntensity = 0.28;
}
});
}
function updateCavityHighlights() {
for (const cavity of cavities.values()) {
const isMatch =
state.selectedPart &&
parts.get(state.selectedPart).cavity === cavity.id;
cavity.rim.material.color.set(isMatch ? 0x69f1d7 : 0x61dec9);
cavity.rim.material.opacity = isMatch ? 0.95 : 0.17;
cavity.rim.scale.z = isMatch ? 1.12 : 1;
}
}
function selectPart(id) {
const part = parts.get(id);
if (!part) return;
if (part.seated) {
showToast(`${part.name} is already seated in the case.`);
return;
}
if (state.selectedPart && state.selectedPart !== id) {
clearPartGlow(parts.get(state.selectedPart));
}
state.selectedPart = id;
glowPart(part);
selectionHalo.visible = true;
selectionHalo.position.set(part.root.position.x, 0.12, part.root.position.z);
selectionHalo.scale.set(
Math.max(part.width * 0.55, part.radius * 1.2),
Math.max(part.radius * 1.15, 0.42),
1
);
updateCavityHighlights();
updateUI();
hintText.textContent =
`${part.name} selected · Drop it into the highlighted matching recess`;
}
function clearSelection() {
if (state.selectedPart) {
clearPartGlow(parts.get(state.selectedPart));
}
state.selectedPart = null;
selectionHalo.visible = false;
updateCavityHighlights();
updateUI();
hintText.textContent =
"Drag a part into a matching recess · Drag background to orbit · Scroll to zoom";
}
function togglePathPart(id) {
const part = parts.get(id);
if (!part.seated || state.assembled) return;
if (state.pathSelection.has(id)) {
state.pathSelection.delete(id);
} else {
state.pathSelection.add(id);
}
updateUI();
}
function seatedPosition(part) {
const cavity = cavities.get(part.cavity);
if (part.type === "extension") {
return {
position: new THREE.Vector3(cavity.x, 1.02, cavity.z),
quaternion: new THREE.Quaternion().setFromEuler(
new THREE.Euler(0, 0, Math.PI / 2)
)
};
}
return {
position: new THREE.Vector3(
cavity.x,
0.86 + part.height * 0.5,
cavity.z
),
quaternion: new THREE.Quaternion()
};
}
function tweenPart(part, destination, duration = 720, onComplete = null) {
tweens.push({
part,
fromPosition: part.root.position.clone(),
toPosition: destination.position.clone(),
fromQuaternion: part.root.quaternion.clone(),
toQuaternion: destination.quaternion.clone(),
elapsed: 0,
duration,
onComplete
});
}
function flashWrongCavity(cavityId) {
const cavity = cavities.get(cavityId);
cavity.rim.material.color.set(0xff7968);
cavity.rim.material.opacity = 1;
cavity.rim.scale.z = 1.28;
setTimeout(() => {
updateCavityHighlights();
cavity.rim.scale.z = 1;
}, 700);
}
function tryPlace(partId, cavityId) {
const part = parts.get(partId);
const cavity = cavities.get(cavityId);
if (!part || !cavity || part.seated) return;
if (part.cavity !== cavityId) {
flashWrongCavity(cavityId);
showToast(
`${part.name} does not match recess ${cavity.code}. Check the label.`,
true
);
return;
}
state.selectedPart = null;
selectionHalo.visible = false;
updateCavityHighlights();
part.placing = true;
part.seated = true;
const destination = seatedPosition(part);
tweenPart(part, destination, 760, () => {
part.placing = false;
showToast(`${part.name} seated in recess ${cavity.code}.`);
updateUI();
});
updateUI();
}
// -------------------------------------------------------------------------
// Tool path
// -------------------------------------------------------------------------
const pathGroup = new THREE.Group();
scene.add(pathGroup);
function clearPathVisual() {
while (pathGroup.children.length) {
const child = pathGroup.children.pop();
child.geometry?.dispose();
if (Array.isArray(child.material)) {
child.material.forEach((material) => material.dispose());
} else {
child.material?.dispose();
}
}
}
function buildPathVisual(startX, endX, z, y) {
clearPathVisual();
const geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(startX, y, z),
new THREE.Vector3(endX, y, z)
]);
const line = new THREE.Line(
geometry,
new THREE.LineDashedMaterial({
color: 0x4ce0c5,
dashSize: 0.18,
gapSize: 0.09,
transparent: true,
opacity: 0.95
})
);
line.computeLineDistances();
pathGroup.add(line);
const tube = new THREE.Mesh(
new THREE.TubeGeometry(
new THREE.LineCurve3(
new THREE.Vector3(startX, y, z),
new THREE.Vector3(endX, y, z)
),
1,
0.018,
8,
false
),
new THREE.MeshBasicMaterial({
color: 0x91f4df,
transparent: true,
opacity: 0.55,
depthWrite: false
})
);
pathGroup.add(tube);
const arrow = new THREE.Mesh(
new THREE.ConeGeometry(0.13, 0.34, 20),
new THREE.MeshBasicMaterial({ color: 0x5ce6cc })
);
arrow.rotation.z = -Math.PI / 2;
arrow.position.set(endX + 0.1, y, z);
pathGroup.add(arrow);
}
const pathOrder = [
"drive",
"reducer",
"extension",
"socket10",
"socket13",
"impact"
];
function assembleToolPath() {
if (state.assembled) return;
const selected = pathOrder
.filter((id) => state.pathSelection.has(id))
.map((id) => parts.get(id))
.filter((part) => part.seated);
if (selected.length < 2) {
showToast("Select at least two seated components for the path.", true);
return;
}
const gap = 0.1;
const totalWidth =
selected.reduce((sum, part) => sum + part.width, 0) +
gap * (selected.length - 1);
let cursor = -totalWidth / 2;
const z = -0.52;
const y = 1.9;
const startX = cursor;
state.assembled = true;
state.assembledParts = new Set(selected.map((part) => part.id));
for (const part of selected) {
part.assembled = true;
const destination = {
position: new THREE.Vector3(cursor + part.width / 2, y, z),
quaternion: new THREE.Quaternion().setFromEuler(
new THREE.Euler(0, 0, Math.PI / 2)
)
};
tweenPart(part, destination, 950);
cursor += part.width + gap;
}
buildPathVisual(startX, cursor - gap, z, 1.43);
clearSelection();
updateUI();
showToast(
`Tool path assembled with ${selected.length} selected components.`
);
}
function returnPathToCase() {
if (!state.assembled) return;
for (const id of state.assembledParts) {
const part = parts.get(id);
part.assembled = false;
tweenPart(part, seatedPosition(part), 850);
}
state.assembled = false;
state.assembledParts.clear();
state.pathSelection.clear();
clearPathVisual();
updateUI();
showToast("Path components returned to their labeled recesses.");
}
assembleButton.addEventListener("click", assembleToolPath);
returnButton.addEventListener("click", returnPathToCase);
// -------------------------------------------------------------------------
// Reset behavior
// -------------------------------------------------------------------------
function resetCamera() {
cameraState.yaw = 0.57;
cameraState.pitch = 0.5;
cameraState.distance = 18.8;
cameraState.target.set(0, 1.15, 0.75);
updateCamera();
}
function resetLayout() {
tweens.length = 0;
clearPathVisual();
state.assembled = false;
state.assembledParts.clear();
state.pathSelection.clear();
for (const part of parts.values()) {
part.seated = false;
part.placing = false;
part.assembled = false;
part.root.position.copy(part.loose);
part.root.quaternion.copy(part.looseQuaternion);
clearPartGlow(part);
}
clearSelection();
updateUI();
showToast("Case reset. All components are back on the staging tray.");
}
document.getElementById("reset-view").addEventListener("click", resetCamera);
document.getElementById("reset-layout").addEventListener("click", resetLayout);
// -------------------------------------------------------------------------
// Direct camera controls and object interaction
// -------------------------------------------------------------------------
function setPointer(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function findPartHit() {
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(allPartMeshes, false);
for (const hit of hits) {
const id = hit.object.userData.partId;
const part = parts.get(id);
if (part && !part.seated && !part.placing) {
return { part, hit };
}
}
return null;
}
function findCavityHit() {
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(cavityHitMeshes, false);
if (!hits.length) return null;
return cavities.get(hits[0].object.userData.cavityId);
}
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.setPointerCapture(event.pointerId);
setPointer(event);
const partHit = event.button === 0 ? findPartHit() : null;
state.pointerDown = {
x: event.clientX,
y: event.clientY,
button: event.button,
moved: false,
part: partHit?.part ?? null
};
if (event.button === 0 && partHit) {
state.mode = "drag";
selectPart(partHit.part.id);
state.dragPlane.constant = -partHit.part.root.position.y;
} else if (event.button === 2) {
state.mode = "pan";
} else {
state.mode = "orbit";
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
const down = state.pointerDown;
if (!down) {
setPointer(event);
const hoverPart = findPartHit();
renderer.domElement.style.cursor = hoverPart ? "grab" : "default";
return;
}
const dx = event.clientX - down.x;
const dy = event.clientY - down.y;
if (Math.abs(dx) + Math.abs(dy) > 4) {
down.moved = true;
}
if (state.mode === "orbit") {
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
0.22,
1.12
);
updateCamera();
} else if (state.mode === "pan") {
cameraState.target.x -= dx * 0.012;
cameraState.target.z -= dy * 0.012;
cameraState.target.x = THREE.MathUtils.clamp(
cameraState.target.x,
-4,
4
);
cameraState.target.z = THREE.MathUtils.clamp(
cameraState.target.z,
-3,
4
);
updateCamera();
} else if (state.mode === "drag" && down.part) {
setPointer(event);
raycaster.setFromCamera(pointer, camera);
if (raycaster.ray.intersectPlane(state.dragPlane, dragPoint)) {
down.part.root.position.x = THREE.MathUtils.clamp(
dragPoint.x,
-6,
6
);
down.part.root.position.z = THREE.MathUtils.clamp(
dragPoint.z,
-3.2,
6.7
);
down.part.root.position.y = down.part.loose.y + 0.28;
selectionHalo.position.set(
down.part.root.position.x,
0.12,
down.part.root.position.z
);
}
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
const down = state.pointerDown;
if (!down) return;
setPointer(event);
if (state.mode === "drag" && down.part) {
const cavity = findCavityHit();
if (cavity) {
tryPlace(down.part.id, cavity.id);
} else {
tweenPart(
down.part,
{
position: down.part.loose.clone(),
quaternion: down.part.looseQuaternion.clone()
},
420
);
showToast("Drop the part on a labeled recess to seat it.", true);
}
} else if (
state.mode === "orbit" &&
!down.moved &&
down.button === 0 &&
state.selectedPart
) {
const cavity = findCavityHit();
if (cavity) {
tryPlace(state.selectedPart, cavity.id);
}
}
state.pointerDown = null;
state.mode = "idle";
renderer.domElement.style.cursor = "default";
});
renderer.domElement.addEventListener("pointercancel", () => {
state.pointerDown = null;
state.mode = "idle";
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance + event.deltaY * 0.012,
11,
29
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
window.addEventListener("keydown", (event) => {
if (event.key.toLowerCase() === "r") resetCamera();
if (event.key === "Escape") {
if (state.pointerDown?.part) {
const part = state.pointerDown.part;
tweenPart(
part,
{
position: part.loose.clone(),
quaternion: part.looseQuaternion.clone()
},
350
);
}
clearSelection();
}
});
// -------------------------------------------------------------------------
// Animation and resize
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
for (let index = tweens.length - 1; index >= 0; index--) {
const tween = tweens[index];
tween.elapsed += delta * 1000;
const t = Math.min(tween.elapsed / tween.duration, 1);
const eased =
t < 0.5
? 4 * t * t * t
: 1 - Math.pow(-2 * t + 2, 3) / 2;
tween.part.root.position.lerpVectors(
tween.fromPosition,
tween.toPosition,
eased
);
tween.part.root.quaternion.slerpQuaternions(
tween.fromQuaternion,
tween.toQuaternion,
eased
);
if (t >= 1) {
tween.onComplete?.();
tweens.splice(index, 1);
}
}
if (selectionHalo.visible) {
haloMaterial.opacity =
0.68 + Math.sin(clock.elapsedTime * 4.5) * 0.17;
}
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
updateUI();
animate();
</script>
</body>
</html>
```