Prompt specification
Build or customize the Three.js 3D scene "Library Sorting Robot Character" 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: Library Sorting Robot Character
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/library-sorting-robot-character-x3743
Scene Description Prompt:
Please use Three.js from cdnjs for a voxel scene based on this idea: library sorting robot character. Build an original library scene with a wheeled robot sorting books into marked bays. Coordinate base position, arm reach, and inventory state with clear mechanical motion. Return one self-contained HTML file.
Working Three.js Starter (library-sorting-robot-character-x3743):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>STACKS — Library Sorting Robot</title>
<style>
:root {
--bg: #111522;
--panel: rgba(22, 27, 42, 0.88);
--panel-solid: #191e2e;
--line: rgba(255,255,255,.11);
--text: #eef3f7;
--muted: #9ba8ba;
--cyan: #4de1d1;
--amber: #ffd166;
--coral: #ff7a78;
--blue: #64b5ff;
--green: #9bd66f;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button, input { font: inherit; }
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
#ui {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 10;
}
.glass {
background: var(--panel);
border: 1px solid var(--line);
box-shadow: 0 16px 45px rgba(0,0,0,.28);
backdrop-filter: blur(15px);
-webkit-backdrop-filter: blur(15px);
}
#title-card {
position: absolute;
left: 22px;
top: 20px;
width: min(370px, calc(100vw - 44px));
border-radius: 18px;
padding: 17px 19px;
}
.eyebrow {
color: var(--cyan);
font: 700 11px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: .18em;
text-transform: uppercase;
}
h1 {
margin: 7px 0 5px;
font-size: 26px;
line-height: 1;
letter-spacing: -.03em;
}
#title-card p {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.title-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.unit-tag {
white-space: nowrap;
padding: 6px 8px;
border: 1px solid rgba(77,225,209,.28);
border-radius: 7px;
color: var(--cyan);
background: rgba(77,225,209,.08);
font: 700 10px/1 ui-monospace, monospace;
}
#status-panel {
position: absolute;
top: 20px;
right: 22px;
width: 285px;
border-radius: 18px;
overflow: hidden;
}
.panel-head {
padding: 13px 15px 12px;
border-bottom: 1px solid var(--line);
display: flex;
align-items: center;
justify-content: space-between;
}
.panel-head strong {
font: 700 11px/1 ui-monospace, monospace;
letter-spacing: .13em;
text-transform: uppercase;
}
.live-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px var(--cyan);
}
.status-body { padding: 14px 15px 15px; }
#state-label {
font-size: 19px;
font-weight: 760;
letter-spacing: -.02em;
margin-bottom: 4px;
}
#state-detail {
min-height: 34px;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 12px;
}
.metric {
padding: 9px 10px;
border-radius: 10px;
background: rgba(255,255,255,.045);
border: 1px solid rgba(255,255,255,.06);
}
.metric span {
display: block;
color: var(--muted);
font: 600 9px/1.2 ui-monospace, monospace;
letter-spacing: .09em;
text-transform: uppercase;
margin-bottom: 4px;
}
.metric b {
font: 700 12px/1.2 ui-monospace, monospace;
}
.reach-track {
height: 7px;
margin-top: 13px;
overflow: hidden;
border-radius: 20px;
background: rgba(255,255,255,.07);
}
#reach-fill {
height: 100%;
width: 15%;
border-radius: inherit;
background: linear-gradient(90deg, var(--cyan), #78a9ff);
transition: width .12s linear;
}
.reach-labels {
display: flex;
justify-content: space-between;
margin-top: 5px;
color: var(--muted);
font: 600 9px/1 ui-monospace, monospace;
}
#inventory {
margin-top: 14px;
padding-top: 13px;
border-top: 1px solid var(--line);
}
.section-label {
display: flex;
justify-content: space-between;
margin-bottom: 8px;
color: var(--muted);
font: 700 9px/1 ui-monospace, monospace;
letter-spacing: .12em;
text-transform: uppercase;
}
#inventory-list {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
}
.inv-item {
min-width: 0;
padding: 7px 6px;
display: flex;
align-items: center;
gap: 6px;
border: 1px solid rgba(255,255,255,.07);
border-radius: 8px;
background: rgba(255,255,255,.035);
color: var(--muted);
font: 700 9px/1 ui-monospace, monospace;
transition: .2s;
}
.inv-item .swatch {
width: 10px;
height: 16px;
border-radius: 2px;
flex: 0 0 auto;
box-shadow: inset -3px 0 rgba(0,0,0,.18);
}
.inv-item.held {
color: white;
border-color: rgba(77,225,209,.55);
background: rgba(77,225,209,.1);
}
.inv-item.sorted {
color: #d5dfcc;
opacity: .7;
}
.inv-item.sorted .swatch {
box-shadow: 0 0 8px currentColor;
}
#controls {
position: absolute;
left: 50%;
bottom: 20px;
transform: translateX(-50%);
border-radius: 16px;
padding: 10px;
display: flex;
align-items: center;
gap: 8px;
pointer-events: auto;
max-width: calc(100vw - 30px);
}
button {
border: 1px solid var(--line);
color: var(--text);
background: rgba(255,255,255,.055);
border-radius: 10px;
padding: 10px 12px;
cursor: pointer;
font-size: 11px;
font-weight: 700;
transition: background .15s, border-color .15s, transform .15s;
}
button:hover {
background: rgba(255,255,255,.1);
border-color: rgba(255,255,255,.22);
}
button:active { transform: translateY(1px); }
#play-button {
min-width: 112px;
color: #102523;
border-color: transparent;
background: var(--cyan);
}
#speed-wrap {
display: flex;
align-items: center;
gap: 8px;
padding: 0 9px;
color: var(--muted);
font: 700 10px/1 ui-monospace, monospace;
}
input[type="range"] {
width: 88px;
accent-color: var(--cyan);
}
#camera-hint {
position: absolute;
left: 22px;
bottom: 22px;
color: rgba(220,230,240,.66);
font: 600 10px/1.5 ui-monospace, monospace;
letter-spacing: .02em;
text-shadow: 0 2px 8px #000;
}
#toast {
position: absolute;
left: 50%;
top: 25px;
transform: translate(-50%, -15px);
padding: 10px 14px;
border-radius: 10px;
color: white;
background: rgba(19,25,38,.94);
border: 1px solid rgba(77,225,209,.3);
font-size: 11px;
opacity: 0;
transition: .25s;
pointer-events: none;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#loading {
position: fixed;
inset: 0;
z-index: 100;
display: grid;
place-items: center;
background: #111522;
transition: opacity .4s;
}
#loading.hide { opacity: 0; pointer-events: none; }
.loader {
width: 46px;
height: 46px;
border: 4px solid rgba(255,255,255,.12);
border-top-color: var(--cyan);
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
@media (max-width: 760px) {
#title-card {
left: 12px;
top: 12px;
width: calc(100vw - 24px);
padding: 13px 15px;
}
#title-card p { display: none; }
h1 { font-size: 21px; }
#status-panel {
top: auto;
right: 12px;
bottom: 79px;
width: 220px;
max-height: 46vh;
overflow-y: auto;
}
.status-body { padding: 10px 12px 12px; }
#state-label { font-size: 16px; }
.metrics { gap: 5px; }
.metric { padding: 7px; }
#inventory { display: none; }
#controls {
bottom: 12px;
width: calc(100vw - 24px);
justify-content: center;
flex-wrap: wrap;
}
button { padding: 9px 10px; }
#speed-wrap { padding: 0 3px; }
input[type="range"] { width: 65px; }
#camera-hint { display: none; }
}
</style>
</head>
<body>
<div id="loading"><div class="loader"></div></div>
<div id="ui">
<section id="title-card" class="glass">
<div class="title-row">
<div>
<div class="eyebrow">Municipal Archive / Floor 03</div>
<h1>STACKS Sorting Unit</h1>
</div>
<div class="unit-tag">SORT–09</div>
</div>
<p>A voxel return robot coordinating a wheeled base, articulated arm, gripper, and live book inventory.</p>
</section>
<section id="status-panel" class="glass">
<div class="panel-head">
<strong>Robot telemetry</strong>
<span class="live-dot"></span>
</div>
<div class="status-body">
<div id="state-label">Booting</div>
<div id="state-detail">Calibrating arm and drive axes.</div>
<div class="metrics">
<div class="metric"><span>Base X / Z</span><b id="base-position">0.0 / 0.0</b></div>
<div class="metric"><span>Carrying</span><b id="carrying">—</b></div>
</div>
<div class="reach-track"><div id="reach-fill"></div></div>
<div class="reach-labels"><span>ARM REACH</span><span id="reach-value">0.00 / 3.78 m</span></div>
<div id="inventory">
<div class="section-label"><span>Return inventory</span><span id="inventory-count">0 / 9</span></div>
<div id="inventory-list"></div>
</div>
</div>
</section>
<div id="controls" class="glass">
<button id="play-button">Pause motion</button>
<button id="reset-button">Reset cycle</button>
<button id="home-button">Camera home</button>
<label id="speed-wrap">SPEED <input id="speed" type="range" min="0.4" max="2" step="0.1" value="1" /><span id="speed-value">1.0×</span></label>
</div>
<div id="camera-hint">DRAG TO ORBIT · WHEEL TO ZOOM · RIGHT-DRAG TO PAN<br>CLICK A COLORED BAY TO PRIORITIZE THAT CATEGORY</div>
<div id="toast"></div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x111522);
scene.fog = new THREE.Fog(0x111522, 23, 43);
const camera = new THREE.PerspectiveCamera(39, innerWidth / innerHeight, 0.1, 100);
const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance" });
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
document.body.prepend(renderer.domElement);
const hemi = new THREE.HemisphereLight(0xb9d8ff, 0x25202c, 1.65);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff0d6, 3.0);
sun.position.set(-9, 17, 11);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -16;
sun.shadow.camera.right = 16;
sun.shadow.camera.top = 16;
sun.shadow.camera.bottom = -16;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 42;
sun.shadow.bias = -0.0005;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x64d9ff, 1.15);
rim.position.set(12, 9, -12);
scene.add(rim);
const mat = (color, roughness = 0.78, metalness = 0.02) =>
new THREE.MeshStandardMaterial({ color, roughness, metalness });
const materials = {
floor: mat(0x34394d),
floorInset: mat(0x3b4055),
wall: mat(0x444a61),
wallDark: mat(0x30364a),
wood: mat(0xa96f4d),
woodDark: mat(0x714537),
cream: mat(0xe8e5d9),
white: mat(0xeaf0f2),
dark: mat(0x202636),
rubber: mat(0x11151f, 0.95),
teal: mat(0x36c8b8, 0.5, 0.12),
tealDark: mat(0x1d827d, 0.5, 0.1),
orange: mat(0xf3a44c),
yellow: mat(0xffd166),
pages: mat(0xf1e5c7),
green: mat(0x7fb45d),
pot: mat(0xc97955),
coral: mat(0xff7a78),
blue: mat(0x64b5ff),
categoryC: mat(0xffd166)
};
function box(parent, size, position, material, cast = true, receive = true) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(size[0], size[1], size[2]), material);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = cast;
mesh.receiveShadow = receive;
parent.add(mesh);
return mesh;
}
function makeLabel(text, background = "#202638", foreground = "#eef3f7", width = 3, height = 0.65) {
const canvas = document.createElement("canvas");
canvas.width = 768;
canvas.height = 160;
const ctx = canvas.getContext("2d");
ctx.fillStyle = background;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = "rgba(255,255,255,.18)";
ctx.lineWidth = 8;
ctx.strokeRect(4, 4, canvas.width - 8, canvas.height - 8);
ctx.fillStyle = foreground;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = "700 76px ui-monospace, SFMono-Regular, Menlo, monospace";
ctx.fillText(text, canvas.width / 2, canvas.height / 2 + 3);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const mesh = new THREE.Mesh(
new THREE.PlaneGeometry(width, height),
new THREE.MeshBasicMaterial({ map: texture, side: THREE.DoubleSide })
);
return mesh;
}
/* ----------------------------- Architecture ----------------------------- */
box(scene, [24, .35, 19], [0, -.2, -.8], materials.floor);
box(scene, [24.4, 6.8, .45], [0, 3.2, -9.25], materials.wall);
box(scene, [.45, 6.8, 18.5], [-12, 3.2, -.8], materials.wallDark);
box(scene, [.45, 6.8, 18.5], [12, 3.2, -.8], materials.wallDark);
for (let x = -11; x <= 11; x += 2) {
box(scene, [.06, 6.2, .08], [x, 3.15, -8.98], materials.wallDark, false, false);
}
const grid = new THREE.GridHelper(24, 24, 0x8993aa, 0x596177);
grid.position.set(0, .006, -.8);
grid.material.transparent = true;
grid.material.opacity = .17;
scene.add(grid);
box(scene, [7.2, .08, 2.8], [-5.1, .025, 4.85], materials.floorInset, false, true);
box(scene, [4.8, .08, 4.7], [-6.3, .025, -6.5], materials.floorInset, false, true);
box(scene, [4.8, .08, 4.7], [0, .025, -6.5], materials.floorInset, false, true);
box(scene, [4.8, .08, 4.7], [6.3, .025, -6.5], materials.floorInset, false, true);
const archiveSign = makeLabel("MUNICIPAL / ARCHIVE", "#262d42", "#d9e8ef", 6.2, .8);
archiveSign.position.set(0, 5.65, -8.98);
scene.add(archiveSign);
/* ------------------------------- Bays ---------------------------------- */
const categories = {
A: { name: "FICTION", color: 0xff7a78, css: "#ff7a78", code: "A" },
B: { name: "SCIENCE", color: 0x64b5ff, css: "#64b5ff", code: "B" },
C: { name: "HISTORY", color: 0xffd166, css: "#ffd166", code: "C" }
};
const bayGroups = {};
const clickableBays = [];
function buildBay(id, x, category) {
const cat = categories[category];
const group = new THREE.Group();
group.position.set(x, 0, -7.35);
scene.add(group);
bayGroups[category] = group;
box(group, [4.35, 4.55, .22], [0, 2.45, -.72], materials.wallDark);
box(group, [.20, 4.55, 1.45], [-2.12, 2.45, 0], materials.woodDark);
box(group, [.20, 4.55, 1.45], [2.12, 2.45, 0], materials.woodDark);
box(group, [4.45, .20, 1.45], [0, 4.47, 0], materials.wood);
box(group, [4.25, .16, 1.45], [0, .55, 0], materials.wood);
box(group, [4.25, .16, 1.45], [0, 1.95, 0], materials.wood);
box(group, [4.25, .16, 1.45], [0, 3.35, 0], materials.wood);
const panel = new THREE.Mesh(
new THREE.BoxGeometry(3.5, .67, .14),
new THREE.MeshStandardMaterial({ color: cat.color, roughness: .55 })
);
panel.position.set(0, 4.02, .72);
panel.castShadow = true;
panel.userData.category = category;
group.add(panel);
clickableBays.push(panel);
const label = makeLabel(`${cat.code} ${cat.name}`, `#${cat.css}`, "#162032", 3.15, .55);
label.position.set(0, 4.02, .805);
group.add(label);
for (let i = 0; i < 3; i++) {
box(group, [.12, .10, .75], [-1.65 + i * 1.65, .68, .28], materials.cream);
}
return group;
}
buildBay("A", -6.3, "A");
buildBay("B", 0, "B");
buildBay("C", 6.3, "C");
/* ----------------------------- Intake table ---------------------------- */
const intake = new THREE.Group();
intake.position.set(-5.1, 0, 4.8);
scene.add(intake);
box(intake, [7.0, .28, 2.7], [0, 1.0, 0], materials.wood);
box(intake, [6.8, .14, 2.5], [0, 1.19, 0], materials.dark);
for (const x of [-3.0, 3.0]) {
for (const z of [-.92, .92]) {
box(intake, [.23, 1.0, .23], [x, .45, z], materials.woodDark);
}
}
for (let i = 0; i < 8; i++) {
box(intake, [.45, .055, .7], [-2.8 + i * .8, 1.29, .93], materials.cream);
}
const intakeSign = makeLabel("RETURN / INTAKE", "#173d46", "#71f0df", 3.2, .58);
intakeSign.position.set(-5.1, 2.02, 6.13);
scene.add(intakeSign);
box(scene, [.12, 1.7, .12], [-6.55, 1.0, 6.13], materials.tealDark);
box(scene, [.12, 1.7, .12], [-3.65, 1.0, 6.13], materials.tealDark);
/* ------------------------------- Books ---------------------------------- */
const bookJobs = [
{ id: "L-01", category: "A", slot: 0, source: [-6.4, 4.18] },
{ id: "L-02", category: "B", slot: 0, source: [-5.2, 4.18] },
{ id: "L-03", category: "C", slot: 0, source: [-4.0, 4.18] },
{ id: "L-04", category: "A", slot: 1, source: [-6.4, 4.80] },
{ id: "L-05", category: "B", slot: 1, source: [-5.2, 4.80] },
{ id: "L-06", category: "C", slot: 1, source: [-4.0, 4.80] },
{ id: "L-07", category: "A", slot: 2, source: [-6.4, 5.40] },
{ id: "L-08", category: "B", slot: 2, source: [-5.2, 5.40] },
{ id: "L-09", category: "C", slot: 2, source: [-4.0, 5.40] }
];
const slotX = [-1.25, 0, 1.25];
const slotY = [1.17, 2.53, 1.17];
function darkerHex(hex, amount = .68) {
const c = new THREE.Color(hex);
c.multiplyScalar(amount);
return c.getHex();
}
function createBook(job) {
const group = new THREE.Group();
const cat = categories[job.category];
const cover = mat(cat.color, .65);
const spine = mat(darkerHex(cat.color), .7);
box(group, [.58, .82, .24], [.025, 0, .015], materials.pages);
box(group, [.70, .94, .065], [0, 0, .145], cover);
box(group, [.70, .94, .065], [0, 0, -.145], cover);
box(group, [.14, .94, .34], [-.30, 0, 0], spine);
box(group, [.52, .11, .025], [0, .19, .19], materials.cream);
box(group, [.44, .035, .025], [0, -.20, .19], spine);
group.position.set(job.source[0], 1.60, job.source[1]);
group.userData.job = job;
scene.add(group);
job.book = group;
job.initialPosition = group.position.clone();
job.status = "queued";
job.targetLocal = new THREE.Vector3(slotX[job.slot], slotY[job.slot], .55);
job.targetWorld = new THREE.Vector3();
return job;
}
bookJobs.forEach(createBook);
/* --------------------------- Reading nook ------------------------------- */
const table = new THREE.Group();
table.position.set(8.2, 0, 3.2);
scene.add(table);
box(table, [3.2, .24, 2.1], [0, 1.05, 0], materials.wood);
for (const x of [-1.25, 1.25]) {
for (const z of [-.72, .72]) box(table, [.18, 1.05, .18], [x, .48, z], materials.woodDark);
}
box(table, [1.3, .08, 1.0], [-.45, 1.22, 0], mat(0x46536a));
box(table, [.85, .10, .62], [.35, 1.24, .08], materials.cream);
box(table, [.95, .12, .68], [.38, 1.34, .08], materials.blue);
function voxelPlant(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.scale.setScalar(scale);
scene.add(group);
box(group, [.8, .75, .8], [0, .38, 0], materials.pot);
box(group, [.55, .95, .55], [0, 1.15, 0], materials.green);
box(group, [.9, .45, .45], [.2, 1.42, 0], materials.green);
box(group, [.42, .8, .72], [-.28, 1.55, .12], materials.green);
box(group, [.5, .42, .9], [.18, 1.78, -.12], materials.green);
}
voxelPlant(9.2, -2.3, 1.05);
voxelPlant(-9.3, -2.6, .8);
for (let i = 0; i < 9; i++) {
box(scene, [.42, .045, .55], [-1.1 + i * .27, .055, -.05], i % 2 ? materials.teal : materials.yellow, false, true);
}
/* ------------------------------- Robot --------------------------------- */
const robot = new THREE.Group();
robot.position.set(0, 0, 1.35);
scene.add(robot);
const wheelGroups = [];
for (const x of [-.78, .78]) {
for (const z of [-.48, .48]) {
const wheel = new THREE.Group();
wheel.position.set(x, .34, z);
robot.add(wheel);
box(wheel, [.30, .56, .56], [0, 0, 0], materials.rubber);
box(wheel, [.34, .20, .20], [0, 0, 0], materials.tealDark);
wheelGroups.push(wheel);
}
}
box(robot, [1.72, .43, 1.38], [0, .67, 0], materials.dark);
box(robot, [1.78, .18, .16], [0, .70, .72], materials.teal);
box(robot, [1.26, 1.15, .92], [0, 1.32, -.04], materials.white);
box(robot, [1.04, .55, .08], [0, 1.48, .46], materials.tealDark);
box(robot, [.72, .22, .03], [0, 1.49, .51], materials.dark);
const robotLabel = makeLabel("SORT-09", "#163d42", "#9df6e8", .82, .18);
robotLabel.position.set(0, 1.10, .515);
robot.add(robotLabel);
box(robot, [1.30, .78, .91], [0, 2.19, -.03], materials.white);
box(robot, [1.12, .45, .08], [0, 2.20, .46], materials.dark);
box(robot, [.17, .12, .05], [-.27, 2.25, .515], materials.teal);
box(robot, [.17, .12, .05], [.27, 2.25, .515], materials.teal);
box(robot, [.34, .055, .04], [0, 2.08, .515], materials.tealDark);
box(robot, [.12, .24, .12], [0, 2.69, -.04], materials.dark);
box(robot, [.19, .19, .19], [0, 2.89, -.04], materials.yellow);
const L1 = 2.0;
const L2 = 1.78;
const SHOULDER_Y = 1.48;
const SHOULDER_Z = .64;
const MAX_REACH = L1 + L2;
box(robot, [.50, .50, .42], [0, SHOULDER_Y, SHOULDER_Z - .14], materials.orange);
const upperPivot = new THREE.Group();
upperPivot.position.set(0, SHOULDER_Y, SHOULDER_Z);
robot.add(upperPivot);
box(upperPivot, [.27, L1, .27], [0, L1 / 2, 0], materials.white);
box(upperPivot, [.31, .22, .31], [0, L1 * .63, 0], materials.teal);
const lowerPivot = new THREE.Group();
lowerPivot.position.set(0, L1, 0);
upperPivot.add(lowerPivot);
box(lowerPivot, [.40, .40, .40], [0, 0, 0], materials.orange);
box(lowerPivot, [.22, L2, .22], [0, L2 / 2, 0], materials.white);
box(lowerPivot, [.26, .18, .26], [0, L2 * .58, 0], materials.teal);
const gripper = new THREE.Group();
gripper.position.set(0, L2, 0);
lowerPivot.add(gripper);
box(gripper, [.64, .17, .30], [0, -.20, 0], materials.dark);
const fingers = [
box(gripper, [.10, .48, .16], [-.34, .17, 0], materials.teal),
box(gripper, [.10, .48, .16], [.34, .17, 0], materials.teal)
];
function solveArm(localEnd) {
const h = localEnd.z - SHOULDER_Z;
const v = localEnd.y - SHOULDER_Y;
let d = Math.hypot(h, v);
d = THREE.MathUtils.clamp(d, .05, MAX_REACH - .001);
const phi = Math.atan2(v, h);
const alpha = Math.acos(THREE.MathUtils.clamp(
(L1 * L1 + d * d - L2 * L2) / (2 * L1 * d), -1, 1
));
const theta1Standard = phi + alpha;
const upperX = L1 * Math.cos(theta1Standard);
const upperY = L1 * Math.sin(theta1Standard);
const lowerX = h - upperX;
const lowerY = v - upperY;
const theta2Standard = Math.atan2(lowerY, lowerX);
const theta1Three = Math.PI / 2 - theta1Standard;
const theta2Three = Math.PI / 2 - theta2Standard;
upperPivot.rotation.x = theta1Three;
lowerPivot.rotation.x = theta2Three - theta1Three;
}
const carryPose = new THREE.Vector3(0, 2.35, 1.20);
let armPose = carryPose.clone();
let armFrom = carryPose.clone();
let armTo = carryPose.clone();
solveArm(armPose);
/* --------------------------- Manual camera ------------------------------ */
const cameraHome = { radius: 24, theta: .64, phi: 1.03, target: new THREE.Vector3(-.4, 1.15, -1.0) };
const orbit = {
radius: cameraHome.radius,
theta: cameraHome.theta,
phi: cameraHome.phi,
target: cameraHome.target.clone()
};
let dragging = false;
let dragButton = 0;
let pointerX = 0;
let pointerY = 0;
let pointerMoved = 0;
renderer.domElement.addEventListener("contextmenu", e => e.preventDefault());
renderer.domElement.addEventListener("pointerdown", e => {
dragging = true;
dragButton = e.button;
pointerX = e.clientX;
pointerY = e.clientY;
pointerMoved = 0;
renderer.domElement.setPointerCapture(e.pointerId);
});
renderer.domElement.addEventListener("pointermove", e => {
if (!dragging) return;
const dx = e.clientX - pointerX;
const dy = e.clientY - pointerY;
pointerX = e.clientX;
pointerY = e.clientY;
pointerMoved += Math.abs(dx) + Math.abs(dy);
if (dragButton === 2 || e.shiftKey) {
const right = new THREE.Vector3(Math.cos(orbit.theta), 0, -Math.sin(orbit.theta));
const forward = new THREE.Vector3(-Math.sin(orbit.theta), 0, -Math.cos(orbit.theta));
const scale = orbit.radius * .0015;
orbit.target.addScaledVector(right, -dx * scale);
orbit.target.addScaledVector(forward, -dy * scale);
orbit.target.x = THREE.MathUtils.clamp(orbit.target.x, -10, 10);
orbit.target.z = THREE.MathUtils.clamp(orbit.target.z, -8, 7);
} else {
orbit.theta -= dx * .006;
orbit.phi = THREE.MathUtils.clamp(orbit.phi - dy * .005, .45, 1.38);
}
});
renderer.domElement.addEventListener("pointerup", e => {
dragging = false;
if (pointerMoved < 6 && dragButton === 0) pickBay(e);
});
renderer.domElement.addEventListener("wheel", e => {
e.preventDefault();
orbit.radius = THREE.MathUtils.clamp(orbit.radius + e.deltaY * .012, 12, 36);
}, { passive: false });
function updateCamera() {
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + orbit.radius * sinPhi * Math.sin(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + orbit.radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(orbit.target);
}
/* ---------------------------- State machine ----------------------------- */
const stateNames = {
BOOT: "Booting",
DRIVE_PICKUP: "Driving to intake",
REACH_PICKUP: "Extending to book",
GRAB: "Closing gripper",
LIFT: "Lifting payload",
DRIVE_BAY: "Driving to bay",
REACH_BAY: "Extending to bay",
RELEASE: "Releasing book",
RETRACT: "Retracting arm",
RETURN: "Returning to dock",
DONE: "Cycle complete"
};
const stateDetails = {
BOOT: "Calibrating arm and drive axes.",
DRIVE_PICKUP: "The base is aligning with the next unprocessed return.",
REACH_PICKUP: "The articulated arm is solving a two-link reach.",
GRAB: "The gripper is securing the selected volume.",
LIFT: "The payload is raised before transport.",
DRIVE_BAY: "The loaded base is moving to the marked destination.",
REACH_BAY: "The arm is placing the payload into the category bay.",
RELEASE: "The gripper is opening and the volume is settling.",
RETRACT: "The arm is returning to its compact carry pose.",
RETURN: "All volumes are sorted. The robot is returning to its dock.",
DONE: "Inventory reconciled. All returns are in their marked bays."
};
let state = "BOOT";
let stateTime = 0;
let paused = false;
let simulationSpeed = 1;
let currentJob = null;
let order = bookJobs.map(j => j.id);
let orderPosition = 0;
let clawAmount = 0;
let releaseFrom = new THREE.Vector3();
let releaseTo = new THREE.Vector3();
let releaseQuaternion = new THREE.Quaternion();
let releaseEndQuaternion = new THREE.Quaternion();
let toastTimer = 0;
const jobById = new Map(bookJobs.map(j => [j.id, j]));
function localFromWorld(worldPoint) {
robot.updateMatrixWorld(true);
return robot.worldToLocal(worldPoint.clone());
}
function setState(next) {
state = next;
stateTime = 0;
if (next === "REACH_PICKUP") {
armFrom = armPose.clone();
armTo = localFromWorld(currentJob.book.getWorldPosition(new THREE.Vector3()));
}
if (next === "GRAB") {
gripper.attach(currentJob.book);
currentJob.book.position.set(0, 0, 0);
currentJob.book.quaternion.identity();
currentJob.status = "held";
}
if (next === "REACH_BAY") {
armFrom = armPose.clone();
armTo = localFromWorld(currentJob.targetWorld);
}
if (next === "RELEASE") {
scene.attach(currentJob.book);
releaseFrom.copy(currentJob.book.position);
releaseQuaternion.copy(currentJob.book.quaternion);
releaseTo.copy(currentJob.targetWorld);
releaseEndQuaternion.identity();
}
}
function beginJob() {
if (orderPosition >= order.length) {
setState("RETURN");
return;
}
currentJob = jobById.get(order[orderPosition]);
currentJob.status = "targeted";
currentJob.targetWorld.copy(bayGroups[currentJob.category].localToWorld(currentJob.targetLocal.clone()));
setState("DRIVE_PICKUP");
}
function angleDifference(a, b) {
return Math.atan2(Math.sin(b - a), Math.cos(b - a));
}
function turnToward(current, target, amount) {
const diff = angleDifference(current, target);
if (Math.abs(diff) <= amount) return target;
return current + Math.sign(diff) * amount;
}
function moveBaseToward(target, dt) {
const dx = target.x - robot.position.x;
const dz = target.z - robot.position.z;
const distance = Math.hypot(dx, dz);
if (distance < .001) return 0;
const amount = Math.min(distance, 2.05 * dt);
robot.position.x += dx / distance * amount;
robot.position.z += dz / distance * amount;
for (const wheel of wheelGroups) wheel.rotation.x -= amount / .28;
return amount;
}
function driveTo(stand, finalTarget, dt) {
const dx = stand.x - robot.position.x;
const dz = stand.z - robot.position.z;
const distance = Math.hypot(dx, dz);
if (distance > .08) {
const heading = Math.atan2(dx, dz);
const difference = angleDifference(robot.rotation.y, heading);
if (Math.abs(difference) > .025) {
robot.rotation.y = turnToward(robot.rotation.y, heading, 1.65 * dt);
} else {
moveBaseToward(stand, dt);
}
return false;
}
const finalHeading = Math.atan2(finalTarget.x - robot.position.x, finalTarget.z - robot.position.z);
const finalDifference = angleDifference(robot.rotation.y, finalHeading);
if (Math.abs(finalDifference) > .018) {
robot.rotation.y = turnToward(robot.rotation.y, finalHeading, 1.75 * dt);
return false;
}
robot.position.x = stand.x;
robot.position.z = stand.z;
return true;
}
function smoothStep(t) {
t = THREE.MathUtils.clamp(t, 0, 1);
return t * t * (3 - 2 * t);
}
function updateSimulation(dt) {
stateTime += dt;
switch (state) {
case "BOOT":
if (stateTime > .8) beginJob();
break;
case "DRIVE_PICKUP": {
const source = currentJob.book.getWorldPosition(new THREE.Vector3());
const stand = new THREE.Vector3(source.x, 0, 1.35);
if (driveTo(stand, source, dt)) setState("REACH_PICKUP");
break;
}
case "REACH_PICKUP": {
const t = smoothStep(stateTime / 1.05);
armPose.lerpVectors(armFrom, armTo, t);
solveArm(armPose);
if (stateTime >= 1.05) setState("GRAB");
break;
}
case "GRAB":
clawAmount = smoothStep(stateTime / .45);
if (stateTime >= .45) {
clawAmount = 1;
setState("LIFT");
}
break;
case "LIFT":
armFrom = armPose.clone();
armTo = carryPose.clone();
armPose.lerpVectors(armFrom, armTo, smoothStep(stateTime / .85));
solveArm(armPose);
if (stateTime >= .85) {
armPose.copy(carryPose);
setState("DRIVE_BAY");
}
break;
case "DRIVE_BAY": {
const stand = new THREE.Vector3(currentJob.targetWorld.x, 0, -3.05);
if (driveTo(stand, currentJob.targetWorld, dt)) setState("REACH_BAY");
break;
}
case "REACH_BAY": {
const t = smoothStep(stateTime / 1.25);
armPose.lerpVectors(armFrom, armTo, t);
solveArm(armPose);
if (stateTime >= 1.25) setState("RELEASE");
break;
}
case "RELEASE": {
const t = smoothStep(stateTime / .9);
clawAmount = 1 - smoothStep(stateTime / .38);
currentJob.book.position.lerpVectors(releaseFrom, releaseTo, t);
currentJob.book.quaternion.copy(releaseQuaternion).slerp(releaseEndQuaternion, t);
if (stateTime >= .9) {
clawAmount = 0;
bayGroups[currentJob.category].attach(currentJob.book);
currentJob.book.position.copy(currentJob.targetLocal);
currentJob.book.quaternion.identity();
currentJob.status = "sorted";
setState("RETRACT");
}
break;
}
case "RETRACT":
armFrom = armPose.clone();
armTo = carryPose.clone();
armPose.lerpVectors(armFrom, armTo, smoothStep(stateTime / .8));
solveArm(armPose);
if (stateTime >= .8) {
armPose.copy(carryPose);
orderPosition++;
beginJob();
}
break;
case "RETURN": {
const dock = new THREE.Vector3(0, 0, 1.35);
if (driveTo(dock, new THREE.Vector3(0, 0, 6), dt)) setState("DONE");
break;
}
}
fingers[0].position.x = -THREE.MathUtils.lerp(.34, .22, clawAmount);
fingers[1].position.x = THREE.MathUtils.lerp(.34, .22, clawAmount);
}
/* ------------------------------- UI ------------------------------------ */
const inventoryList = document.getElementById("inventory-list");
const stateLabel = document.getElementById("state-label");
const stateDetail = document.getElementById("state-detail");
const basePosition = document.getElementById("base-position");
const carrying = document.getElementById("carrying");
const reachFill = document.getElementById("reach-fill");
const reachValue = document.getElementById("reach-value");
const inventoryCount = document.getElementById("inventory-count");
const playButton = document.getElementById("play-button");
const speedInput = document.getElementById("speed");
const speedValue = document.getElementById("speed-value");
const toast = document.getElementById("toast");
for (const job of bookJobs) {
const el = document.createElement("div");
el.className = "inv-item";
el.dataset.id = job.id;
el.innerHTML = `<span class="swatch" style="background:${categories[job.category].css}"></span><span>${job.id}</span>`;
inventoryList.appendChild(el);
}
function showToast(message) {
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 2200);
}
function updateUI() {
stateLabel.textContent = stateNames[state];
stateDetail.textContent = stateDetails[state];
basePosition.textContent = `${robot.position.x.toFixed(1)} / ${robot.position.z.toFixed(1)}`;
carrying.textContent = currentJob && currentJob.status === "held"
? `${currentJob.id} / ${categories[currentJob.category].code}`
: "—";
robot.updateMatrixWorld(true);
const shoulder = upperPivot.getWorldPosition(new THREE.Vector3());
const tip = robot.localToWorld(armPose.clone());
const reach = shoulder.distanceTo(tip);
reachFill.style.width = `${THREE.MathUtils.clamp(reach / MAX_REACH * 100, 0, 100)}%`;
reachValue.textContent = `${reach.toFixed(2)} / ${MAX_REACH.toFixed(2)} m`;
let sorted = 0;
for (const job of bookJobs) {
if (job.status === "sorted") sorted++;
const element = inventoryList.querySelector(`[data-id="${job.id}"]`);
element.classList.toggle("held", job.status === "held");
element.classList.toggle("sorted", job.status === "sorted");
}
inventoryCount.textContent = `${sorted} / ${bookJobs.length}`;
}
playButton.addEventListener("click", () => {
paused = !paused;
playButton.textContent = paused ? "Resume motion" : "Pause motion";
});
speedInput.addEventListener("input", () => {
simulationSpeed = Number(speedInput.value);
speedValue.textContent = `${simulationSpeed.toFixed(1)}×`;
});
document.getElementById("home-button").addEventListener("click", () => {
orbit.radius = cameraHome.radius;
orbit.theta = cameraHome.theta;
orbit.phi = cameraHome.phi;
orbit.target.copy(cameraHome.target);
});
document.getElementById("reset-button").addEventListener("click", resetCycle);
function resetCycle() {
for (const job of bookJobs) {
scene.attach(job.book);
job.book.position.copy(job.initialPosition);
job.book.quaternion.identity();
job.book.scale.set(1, 1, 1);
job.status = "queued";
}
currentJob = null;
order = bookJobs.map(j => j.id);
orderPosition = 0;
state = "BOOT";
stateTime = 0;
clawAmount = 0;
robot.position.set(0, 0, 1.35);
robot.rotation.y = 0;
armPose.copy(carryPose);
solveArm(armPose);
for (const wheel of wheelGroups) wheel.rotation.x = 0;
paused = false;
playButton.textContent = "Pause motion";
showToast("Sorting cycle reset");
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function pickBay(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hit = raycaster.intersectObjects(clickableBays, false)[0];
if (!hit) return;
const category = hit.object.userData.category;
const pendingIndex = order.findIndex((id, index) => {
if (index <= orderPosition) return false;
return jobById.get(id).category === category && jobById.get(id).status !== "sorted";
});
if (pendingIndex > -1) {
const id = order.splice(pendingIndex, 1)[0];
order.splice(orderPosition + 1, 0, id);
showToast(`${categories[category].name} prioritized next`);
}
}
/* ------------------------------- Loop ---------------------------------- */
const clock = new THREE.Clock();
let uiTimer = 0;
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), .05);
if (!paused) updateSimulation(dt * simulationSpeed);
updateCamera();
uiTimer += dt;
if (uiTimer > .08) {
updateUI();
uiTimer = 0;
}
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
window.addEventListener("keydown", event => {
if (event.code === "Space") {
event.preventDefault();
playButton.click();
}
if (event.key.toLowerCase() === "r") resetCycle();
});
updateCamera();
updateUI();
animate();
requestAnimationFrame(() => document.getElementById("loading").classList.add("hide"));
</script>
</body>
</html>
```