Prompt specification
Build or customize the Three.js 3D scene "Recycling Demonstrator With Known Materials" 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: Recycling Demonstrator With Known Materials
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/recycling-demonstrator-with-known-materials-x2043
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows a voxel recycling demonstrator with known material labels. Build a short conveyor, a reading station, three sorting gates, and collection bins. Give each item explicit material metadata displayed on a small tag; include two similarly shaped items with different labels so appearance alone cannot determine the route. The gates should use those labels according to a stated toy sorting scheme. Add one deliberately mislabeled item whose route can be inspected and corrected. Track every object through the line, and avoid presenting the scene's categories as universal real-world recycling instructions.
Working Three.js Starter (recycling-demonstrator-with-known-materials-x2043):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Recycling Demonstrator</title>
<style>
:root {
color-scheme: dark;
--bg: #080d18;
--panel: rgba(12, 19, 34, 0.94);
--panel-border: rgba(255, 255, 255, 0.12);
--text: #edf4ff;
--muted: #9eacc2;
--paper: #43d9ff;
--glass: #ffc857;
--metal: #ff668a;
--good: #76e6a5;
--warn: #ffcf67;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
select,
input {
font: inherit;
}
button,
select {
border: 1px solid var(--panel-border);
border-radius: 9px;
background: #19253a;
color: var(--text);
}
button {
cursor: pointer;
transition:
transform 120ms ease,
border-color 120ms ease,
background 120ms ease;
}
button:hover {
border-color: rgba(255, 255, 255, 0.35);
background: #22314a;
}
button:active {
transform: translateY(1px);
}
button:disabled {
opacity: 0.45;
cursor: default;
}
#scene {
position: fixed;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.topbar {
position: fixed;
z-index: 5;
top: 18px;
left: 20px;
width: min(660px, calc(100vw - 430px));
pointer-events: none;
}
.eyebrow {
margin-bottom: 5px;
color: #7ddfff;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(23px, 3vw, 39px);
line-height: 1.02;
letter-spacing: -0.04em;
text-shadow: 0 4px 24px #000;
}
.subtitle {
margin-top: 8px;
max-width: 610px;
color: #b7c3d7;
font-size: 13px;
line-height: 1.45;
text-shadow: 0 2px 10px #000;
}
.disclaimer {
position: fixed;
z-index: 6;
left: 20px;
bottom: 18px;
width: min(660px, calc(100vw - 430px));
padding: 12px 14px;
border: 1px solid rgba(255, 207, 103, 0.35);
border-radius: 12px;
background: rgba(39, 31, 16, 0.9);
color: #ffe8ac;
font-size: 12px;
line-height: 1.45;
backdrop-filter: blur(12px);
}
.disclaimer strong {
color: #fff2c8;
}
.panel {
position: fixed;
z-index: 10;
top: 12px;
right: 12px;
bottom: 12px;
width: 390px;
overflow: auto;
padding: 16px;
border: 1px solid var(--panel-border);
border-radius: 17px;
background: var(--panel);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.42);
backdrop-filter: blur(18px);
scrollbar-width: thin;
scrollbar-color: #40506b transparent;
}
.panel section {
padding-bottom: 15px;
margin-bottom: 15px;
border-bottom: 1px solid rgba(255, 255, 255, 0.09);
}
.panel section:last-child {
padding-bottom: 0;
margin-bottom: 0;
border-bottom: 0;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 10px;
font-size: 12px;
font-weight: 850;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.section-title small {
color: var(--muted);
font-size: 10px;
font-weight: 600;
letter-spacing: 0.03em;
text-transform: none;
}
.control-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.control-grid button {
min-height: 37px;
padding: 8px 10px;
font-size: 12px;
font-weight: 750;
}
.control-grid .primary {
border-color: rgba(67, 217, 255, 0.5);
background: #14516a;
}
.control-grid .primary:hover {
background: #19647f;
}
.speed-row {
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
gap: 9px;
margin-top: 11px;
color: var(--muted);
font-size: 11px;
}
input[type="range"] {
width: 100%;
accent-color: #43d9ff;
}
.scheme {
display: grid;
grid-template-columns: 1fr auto auto;
gap: 7px 10px;
align-items: center;
padding: 10px;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 11px;
background: rgba(255, 255, 255, 0.035);
font-size: 11px;
}
.scheme .head {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.material {
display: inline-flex;
align-items: center;
gap: 7px;
font-weight: 800;
letter-spacing: 0.05em;
}
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
box-shadow: 0 0 12px currentColor;
}
.paper {
color: var(--paper);
}
.glass {
color: var(--glass);
}
.metal {
color: var(--metal);
}
.note {
margin: 9px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.note strong {
color: #d8e5f7;
}
.inspector {
padding: 12px;
border: 1px solid rgba(125, 223, 255, 0.22);
border-radius: 12px;
background: linear-gradient(
145deg,
rgba(67, 217, 255, 0.07),
rgba(255, 255, 255, 0.025)
);
}
.inspector-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 10px;
}
.item-id {
font-size: 24px;
font-weight: 900;
letter-spacing: -0.04em;
}
.status-pill {
padding: 5px 8px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 999px;
background: rgba(0, 0, 0, 0.2);
color: #bcd0e8;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.facts {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.fact {
min-height: 54px;
padding: 8px;
border-radius: 8px;
background: rgba(0, 0, 0, 0.2);
}
.fact span {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.fact b {
font-size: 12px;
}
.journey {
margin: 9px 0;
color: #b9c8dc;
font-size: 10px;
line-height: 1.55;
}
.inspector-actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-top: 8px;
}
.inspector-actions button {
min-height: 33px;
padding: 7px 8px;
font-size: 10px;
font-weight: 800;
}
.correction-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 7px;
margin-top: 8px;
}
.correction-row select {
width: 100%;
min-height: 35px;
padding: 6px 8px;
font-size: 11px;
}
.correction-row button {
min-height: 35px;
padding: 7px 11px;
border-color: rgba(118, 230, 165, 0.45);
background: #174a36;
font-size: 10px;
font-weight: 850;
}
.mismatch {
color: var(--warn) !important;
}
.track-list {
display: grid;
gap: 6px;
max-height: 280px;
overflow: auto;
padding-right: 2px;
}
.track-row {
display: grid;
grid-template-columns: 29px 1fr auto;
gap: 8px;
align-items: center;
width: 100%;
padding: 8px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 9px;
background: rgba(255, 255, 255, 0.025);
text-align: left;
}
.track-row.selected {
border-color: rgba(67, 217, 255, 0.65);
background: rgba(67, 217, 255, 0.09);
}
.track-row .box-id {
display: grid;
place-items: center;
width: 27px;
height: 27px;
border-radius: 7px;
background: #26344c;
font-size: 11px;
font-weight: 900;
}
.track-row .row-main b {
display: block;
margin-bottom: 2px;
font-size: 10px;
letter-spacing: 0.04em;
}
.track-row .row-main small {
display: block;
color: var(--muted);
font-size: 9px;
}
.route-badge {
min-width: 29px;
padding: 4px 6px;
border-radius: 6px;
background: rgba(255, 255, 255, 0.07);
color: #d7e6f8;
font-size: 9px;
font-weight: 900;
text-align: center;
}
.log {
display: grid;
gap: 5px;
max-height: 170px;
overflow: auto;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9px;
line-height: 1.4;
}
.log-entry {
display: grid;
grid-template-columns: 43px 1fr;
gap: 7px;
padding: 5px 6px;
border-radius: 6px;
background: rgba(255, 255, 255, 0.025);
color: #aebed2;
}
.log-entry time {
color: #63d8f5;
}
.scene-hint {
position: fixed;
z-index: 4;
left: 50%;
bottom: 106px;
transform: translateX(-50%);
padding: 7px 11px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 999px;
background: rgba(8, 13, 24, 0.7);
color: #afbed1;
font-size: 10px;
pointer-events: none;
backdrop-filter: blur(8px);
}
@media (max-width: 900px) {
.topbar {
top: 12px;
left: 12px;
width: calc(100vw - 24px);
}
.subtitle {
display: none;
}
.panel {
top: auto;
left: 8px;
right: 8px;
bottom: 8px;
width: auto;
max-height: 47vh;
border-radius: 14px;
}
.disclaimer {
left: 8px;
bottom: calc(47vh + 16px);
width: calc(100vw - 16px);
padding: 8px 10px;
font-size: 10px;
}
.scene-hint {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<header class="topbar">
<div class="eyebrow">Metadata-driven toy demonstrator</div>
<h1>Voxel Recycling Line</h1>
<div class="subtitle">
Printed material tags—not shape or color—control the route. Items A and B
have identical voxel bodies and colors but different metadata.
</div>
</header>
<aside class="panel">
<section>
<div class="section-title">
Simulation
<small id="clock">t = 0.0 s</small>
</div>
<div class="control-grid">
<button id="runPause" class="primary">Pause line</button>
<button id="reset">Reset demo</button>
<button id="step">Step 0.5 s</button>
<button id="selectE">Select test item E</button>
</div>
<div class="speed-row">
<span>Speed</span>
<input id="speed" type="range" min="0.5" max="2" value="1" step="0.1" />
<b id="speedValue">1.0×</b>
</div>
</section>
<section>
<div class="section-title">
Stated toy sorting scheme
<small>printed tag → gate → bin</small>
</div>
<div class="scheme">
<div class="head">Tag</div>
<div class="head">Gate</div>
<div class="head">Collection</div>
<div class="material paper">
<span class="dot" style="background: var(--paper)"></span>PAPER
</div>
<div>G1</div>
<div>Paper bin</div>
<div class="material glass">
<span class="dot" style="background: var(--glass)"></span>GLASS
</div>
<div>G2</div>
<div>Glass bin</div>
<div class="material metal">
<span class="dot" style="background: var(--metal)"></span>METAL
</div>
<div>G3</div>
<div>Metal bin</div>
</div>
<p class="note">
<strong>Routing rule:</strong> the gate compares the item's current
printed metadata with its own label. The physical body is never used
to infer a route.
</p>
</section>
<section>
<div class="section-title">
Item inspector
<small>click an item or a tracked row</small>
</div>
<div class="inspector">
<div class="inspector-head">
<div>
<span class="item-id" id="selectedId">E</span>
<span id="selectedForm" class="status-pill">metal voxel</span>
</div>
<span id="selectedStatus" class="status-pill">queued</span>
</div>
<div class="facts">
<div class="fact">
<span>Current printed tag</span>
<b id="selectedTag">GLASS</b>
</div>
<div class="fact">
<span>Planned route</span>
<b id="selectedRoute">G2 → Glass bin</b>
</div>
<div class="fact">
<span>Ground truth</span>
<b id="selectedTruth">Hidden</b>
</div>
<div class="fact">
<span>Executed route</span>
<b id="selectedExecuted">Not yet</b>
</div>
</div>
<div id="selectedJourney" class="journey"></div>
<div class="inspector-actions">
<button id="revealTruth">Reveal ground truth</button>
<button id="centerCamera">Center camera</button>
</div>
<div class="correction-row">
<select id="correctionSelect" aria-label="Corrected material label">
<option value="PAPER">PAPER</option>
<option value="GLASS">GLASS</option>
<option value="METAL">METAL</option>
</select>
<button id="applyCorrection">Apply tag</button>
</div>
<p class="note" id="auditNote">
Item E is the deliberate mislabeled test case.
</p>
</div>
</section>
<section>
<div class="section-title">
Every object tracker
<small id="objectCount">0 / 9 tracked</small>
</div>
<div id="trackList" class="track-list"></div>
</section>
<section>
<div class="section-title">
Event log
<small>simulation time</small>
</div>
<div id="eventLog" class="log"></div>
</section>
</aside>
<div class="disclaimer">
<strong>Toy demonstration only.</strong>
PAPER, GLASS, and METAL here are fictional demonstration categories and
this routing table is not universal real-world recycling guidance.
Local facilities may accept different materials, use different containers,
or reject contaminated items.
</div>
<div class="scene-hint">
Drag to orbit · wheel to zoom · click an object to inspect
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Configuration
// -------------------------------------------------------------------------
const COLORS = {
PAPER: 0x43d9ff,
GLASS: 0xffc857,
METAL: 0xff668a
};
const SCHEME = {
PAPER: { gate: "G1", bin: "Paper bin", short: "Paper" },
GLASS: { gate: "G2", bin: "Glass bin", short: "Glass" },
METAL: { gate: "G3", bin: "Metal bin", short: "Metal" }
};
const GATES = [
{ id: "G1", label: "PAPER", x: -2.7 },
{ id: "G2", label: "GLASS", x: 0.4 },
{ id: "G3", label: "METAL", x: 3.5 }
];
const READER_X = -7.6;
const SPAWN_X = -10.7;
const END_X = 8.4;
const BELT_Y = 1.48;
const BIN_Z = 4.15;
const ITEM_CONFIGS = [
{ id: "A", actual: "PAPER", declared: "PAPER", form: "cube", delay: 0 },
{ id: "B", actual: "GLASS", declared: "GLASS", form: "cube", delay: 2 },
{ id: "C", actual: "METAL", declared: "METAL", form: "metal", delay: 4 },
{ id: "D", actual: "PAPER", declared: "PAPER", form: "flat", delay: 6 },
{ id: "E", actual: "METAL", declared: "GLASS", form: "metal", delay: 8 },
{ id: "F", actual: "GLASS", declared: "GLASS", form: "bottle", delay: 10 },
{ id: "G", actual: "METAL", declared: "METAL", form: "metal", delay: 12 },
{ id: "H", actual: "PAPER", declared: "PAPER", form: "cube", delay: 14 },
{ id: "I", actual: "GLASS", declared: "GLASS", form: "flat", delay: 16 }
];
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false
});
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.08;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x080d18);
scene.fog = new THREE.Fog(0x080d18, 27, 58);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
// Camera controls are implemented here rather than importing an addon.
const cameraState = {
target: new THREE.Vector3(-0.6, 1.1, 1.15),
radius: 20.5,
theta: 0.67,
phi: 0.88
};
function updateCamera() {
const { target, radius, theta, phi } = cameraState;
camera.position.set(
target.x + radius * Math.sin(phi) * Math.cos(theta),
target.y + radius * Math.cos(phi),
target.z + radius * Math.sin(phi) * Math.sin(theta)
);
camera.lookAt(target);
}
updateCamera();
scene.add(new THREE.HemisphereLight(0xbddcff, 0x172033, 1.65));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.5);
keyLight.position.set(5, 13, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -18;
keyLight.shadow.camera.right = 18;
keyLight.shadow.camera.top = 13;
keyLight.shadow.camera.bottom = -13;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 40;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x43d9ff, 1.05);
rimLight.position.set(-10, 5, -9);
scene.add(rimLight);
// -------------------------------------------------------------------------
// Small drawing helpers
// -------------------------------------------------------------------------
function roundedRect(ctx, x, y, w, h, r) {
const radius = Math.min(r, w / 2, h / 2);
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + w - radius, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + radius);
ctx.lineTo(x + w, y + h - radius);
ctx.quadraticCurveTo(x + w, y + h, x + w - radius, y + h);
ctx.lineTo(x + radius, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
}
function makeTextSprite(
lines,
{
width = 512,
height = 128,
background = "rgba(7,13,25,0.92)",
border = "#43d9ff",
textColor = "#edf7ff",
scale = [3.2, 0.8]
} = {}
) {
const c = document.createElement("canvas");
c.width = width;
c.height = height;
const ctx = c.getContext("2d");
roundedRect(ctx, 4, 4, width - 8, height - 8, 20);
ctx.fillStyle = background;
ctx.fill();
ctx.strokeStyle = border;
ctx.lineWidth = 5;
ctx.stroke();
const list = Array.isArray(lines) ? lines : [lines];
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = textColor;
if (list.length === 1) {
ctx.font = `800 ${Math.floor(height * 0.43)}px system-ui`;
ctx.fillText(list[0], width / 2, height / 2 + 1);
} else {
ctx.font = `900 ${Math.floor(height * 0.35)}px system-ui`;
ctx.fillText(list[0], width / 2, height * 0.36);
ctx.font = `800 ${Math.floor(height * 0.25)}px system-ui`;
ctx.fillText(list[1], width / 2, height * 0.72);
}
const texture = new THREE.CanvasTexture(c);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false,
depthTest: false,
toneMapped: false
})
);
sprite.scale.set(scale[0], scale[1], 1);
sprite.renderOrder = 20;
return sprite;
}
function addBox(
width,
height,
depth,
color,
x,
y,
z,
options = {}
) {
const geometry = new THREE.BoxGeometry(width, height, depth);
const material = new THREE.MeshStandardMaterial({
color,
roughness: options.roughness ?? 0.68,
metalness: options.metalness ?? 0.08,
emissive: options.emissive ?? 0x000000,
emissiveIntensity: options.emissiveIntensity ?? 0,
transparent: options.transparent ?? false,
opacity: options.opacity ?? 1
});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(x, y, z);
mesh.castShadow = options.castShadow ?? true;
mesh.receiveShadow = options.receiveShadow ?? true;
scene.add(mesh);
return mesh;
}
function addCylinder(
radius,
height,
color,
x,
y,
z,
radialSegments = 12,
options = {}
) {
const geometry = new THREE.CylinderGeometry(
radius,
radius,
height,
radialSegments
);
const material = new THREE.MeshStandardMaterial({
color,
roughness: options.roughness ?? 0.62,
metalness: options.metalness ?? 0.12,
emissive: options.emissive ?? 0x000000,
emissiveIntensity: options.emissiveIntensity ?? 0
});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
return mesh;
}
function cssColor(hex) {
return `#${hex.toString(16).padStart(6, "0")}`;
}
// -------------------------------------------------------------------------
// World: floor, conveyor, reader, gates, and bins
// -------------------------------------------------------------------------
const ground = addBox(
80,
0.15,
80,
0x0b1220,
0,
-0.12,
0,
{ castShadow: false }
);
const grid = new THREE.GridHelper(60, 60, 0x22314a, 0x142033);
grid.position.y = -0.035;
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
const beltCenter = (SPAWN_X + END_X) / 2;
const beltLength = END_X - SPAWN_X;
addBox(
beltLength,
0.34,
2.9,
0x111a2b,
beltCenter,
0.9,
0,
{ roughness: 0.88 }
);
addBox(
beltLength,
0.14,
3.15,
0x26354b,
beltCenter,
0.67,
0
);
for (const side of [-1, 1]) {
addBox(
beltLength,
0.18,
0.12,
0x53647e,
beltCenter,
1.19,
side * 1.5
);
}
for (let x = SPAWN_X + 0.8; x < END_X; x += 3) {
for (const side of [-1, 1]) {
addBox(0.28, 1.35, 0.28, 0x29374c, x, 0.55, side * 1.18);
}
addBox(0.35, 0.16, 2.6, 0x35445a, x, 0.32, 0);
}
const beltSlats = [];
for (let i = 0; i < 28; i++) {
const slat = addBox(
0.035,
0.025,
2.65,
i % 4 === 0 ? 0x3c506a : 0x26374d,
SPAWN_X + i * (beltLength / 28),
1.085,
0,
{ castShadow: false }
);
beltSlats.push(slat);
}
function addFloorArrow(x, z, color) {
const shape = new THREE.Shape();
shape.moveTo(-0.45, -0.12);
shape.lineTo(0.05, -0.12);
shape.lineTo(0.05, -0.32);
shape.lineTo(0.48, 0);
shape.lineTo(0.05, 0.32);
shape.lineTo(0.05, 0.12);
shape.lineTo(-0.45, 0.12);
shape.closePath();
const mesh = new THREE.Mesh(
new THREE.ShapeGeometry(shape),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.6,
side: THREE.DoubleSide
})
);
mesh.rotation.x = -Math.PI / 2;
mesh.position.set(x, 1.1, z);
scene.add(mesh);
}
for (let x = -9.5; x < 8; x += 4.1) {
addFloorArrow(x, 0, 0x7893b2);
}
// Reading station.
for (const side of [-1, 1]) {
addBox(0.32, 3.55, 0.32, 0x40536c, READER_X, 2.0, side * 1.72);
addBox(0.55, 0.18, 0.55, 0x43d9ff, READER_X, 0.34, side * 1.72);
}
addBox(0.38, 0.34, 3.75, 0x354d67, READER_X, 3.72, 0);
const scannerMaterial = new THREE.MeshBasicMaterial({
color: COLORS.PAPER,
transparent: true,
opacity: 0.13,
depthWrite: false
});
const scannerPlane = new THREE.Mesh(
new THREE.BoxGeometry(0.055, 2.65, 2.75),
scannerMaterial
);
scannerPlane.position.set(READER_X, 2.0, 0);
scene.add(scannerPlane);
const readerSign = makeTextSprite(
["READ", "PRINTED METADATA"],
{
border: "#43d9ff",
scale: [3.25, 0.83]
}
);
readerSign.position.set(READER_X, 4.42, 0);
scene.add(readerSign);
let scanFlash = 0;
// Gate and bin visuals.
const gateVisuals = [];
for (const gate of GATES) {
const color = COLORS[gate.label];
for (const side of [-1, 1]) {
addBox(
0.34,
2.95,
0.34,
0x34445b,
gate.x,
2.05,
side * 1.7,
{ metalness: 0.2 }
);
addBox(
0.48,
0.22,
0.48,
color,
gate.x,
3.55,
side * 1.7,
{
emissive: color,
emissiveIntensity: 0.35,
metalness: 0.25
}
);
addBox(
0.56,
0.16,
0.56,
0x28374d,
gate.x,
0.33,
side * 1.7
);
}
addBox(
0.38,
0.34,
3.72,
color,
gate.x,
3.55,
0,
{
emissive: color,
emissiveIntensity: 0.2,
metalness: 0.22
}
);
addBox(
0.5,
0.025,
2.8,
color,
gate.x,
1.105,
0,
{
castShadow: false,
emissive: color,
emissiveIntensity: 0.25
}
);
const sign = makeTextSprite([gate.id, gate.label], {
border: cssColor(color),
textColor: cssColor(color),
scale: [2.35, 0.72]
});
sign.position.set(gate.x, 4.25, 0);
scene.add(sign);
// A visible diverter arm, aligned with the belt at rest.
const armPivot = new THREE.Group();
armPivot.position.set(gate.x, 1.35, 1.16);
armPivot.rotation.y = Math.PI / 2;
scene.add(armPivot);
const arm = new THREE.Mesh(
new THREE.BoxGeometry(0.16, 0.16, 1.35),
new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.22,
roughness: 0.42,
metalness: 0.45
})
);
arm.position.z = 0.67;
arm.castShadow = true;
armPivot.add(arm);
gateVisuals.push({ gate, armPivot, activity: 0 });
// Chute from the gate toward the collection bin.
const chute = addBox(
1.15,
0.12,
3.2,
0x26364c,
gate.x + 0.22,
1.02,
2.48,
{ metalness: 0.28 }
);
chute.rotation.x = 0.115;
for (const side of [-1, 1]) {
addBox(
0.08,
0.24,
3.15,
color,
gate.x + 0.22 + side * 0.6,
1.08,
2.48,
{
emissive: color,
emissiveIntensity: 0.16
}
);
}
// Open-top collection bin.
const binX = gate.x + 0.22;
const binColor = new THREE.Color(color).multiplyScalar(0.42).getHex();
addBox(
1.9,
0.18,
1.75,
binColor,
binX,
0.26,
BIN_Z
);
addBox(
1.9,
0.95,
0.15,
binColor,
binX,
0.72,
BIN_Z - 0.82
);
addBox(
1.9,
0.72,
0.15,
binColor,
binX,
0.6,
BIN_Z + 0.82
);
for (const side of [-1, 1]) {
addBox(
0.15,
1.05,
1.65,
binColor,
binX + side * 0.88,
0.7,
BIN_Z
);
addBox(
0.11,
0.11,
1.8,
color,
binX + side * 0.92,
1.25,
BIN_Z,
{
emissive: color,
emissiveIntensity: 0.3
}
);
}
const binSign = makeTextSprite(
[gate.id + " BIN", SCHEME[gate.label].bin],
{
border: cssColor(color),
textColor: cssColor(color),
scale: [2.55, 0.72]
}
);
binSign.position.set(binX, 2.3, BIN_Z + 0.85);
scene.add(binSign);
}
// -------------------------------------------------------------------------
// Voxel items and metadata tags
// -------------------------------------------------------------------------
const itemGroups = [];
const pickableMeshes = [];
function makeTagTexture() {
const c = document.createElement("canvas");
c.width = 360;
c.height = 104;
const texture = new THREE.CanvasTexture(c);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
return { canvas: c, texture };
}
function drawItemTag(item, label) {
const ctx = item.tagCanvas.getContext("2d");
const color = cssColor(COLORS[label]);
ctx.clearRect(0, 0, 360, 104);
roundedRect(ctx, 4, 4, 352, 96, 18);
ctx.fillStyle = "rgba(6, 12, 24, 0.96)";
ctx.fill();
ctx.strokeStyle = color;
ctx.lineWidth = 6;
ctx.stroke();
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#ffffff";
ctx.font = "900 27px system-ui";
ctx.fillText(item.id, 48, 51);
ctx.textAlign = "left";
ctx.fillStyle = color;
ctx.font = "900 31px system-ui";
ctx.fillText(label, 94, 51);
item.tagTexture.needsUpdate = true;
}
function createBody(form, itemId) {
const group = new THREE.Group();
const common = { roughness: 0.58, metalness: 0.12 };
if (form === "cube") {
// A and B intentionally use exactly the same body shape and color.
const body = new THREE.Mesh(
new THREE.BoxGeometry(0.72, 0.72, 0.72),
new THREE.MeshStandardMaterial({
color: 0x718cff,
...common
})
);
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const topPixel = new THREE.Mesh(
new THREE.BoxGeometry(0.23, 0.08, 0.23),
new THREE.MeshStandardMaterial({
color: 0xa8baff,
roughness: 0.5
})
);
topPixel.position.y = 0.39;
topPixel.castShadow = true;
group.add(topPixel);
} else if (form === "metal") {
const body = new THREE.Mesh(
new THREE.CylinderGeometry(0.34, 0.34, 0.7, 10),
new THREE.MeshStandardMaterial({
color: 0xf2647f,
roughness: 0.36,
metalness: 0.62
})
);
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const band = new THREE.Mesh(
new THREE.CylinderGeometry(0.355, 0.355, 0.16, 10),
new THREE.MeshStandardMaterial({
color: 0xffd0da,
roughness: 0.3,
metalness: 0.48
})
);
band.position.y = 0.09;
band.castShadow = true;
group.add(band);
const top = new THREE.Mesh(
new THREE.BoxGeometry(0.24, 0.055, 0.12),
new THREE.MeshStandardMaterial({
color: 0x9eafc6,
metalness: 0.72,
roughness: 0.3
})
);
top.position.y = 0.375;
group.add(top);
} else if (form === "flat") {
const body = new THREE.Mesh(
new THREE.BoxGeometry(0.92, 0.22, 0.67),
new THREE.MeshStandardMaterial({
color: 0x67c998,
roughness: 0.84
})
);
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
for (let i = 0; i < 3; i++) {
const sheet = new THREE.Mesh(
new THREE.BoxGeometry(0.82, 0.035, 0.57),
new THREE.MeshStandardMaterial({
color: 0xb9f0c7,
roughness: 0.9
})
);
sheet.position.set(0, 0.13 + i * 0.035, 0);
sheet.castShadow = true;
group.add(sheet);
}
} else {
// A block-built bottle.
const body = new THREE.Mesh(
new THREE.BoxGeometry(0.5, 0.52, 0.5),
new THREE.MeshStandardMaterial({
color: 0xffc857,
roughness: 0.45
})
);
body.castShadow = true;
group.add(body);
const shoulder = new THREE.Mesh(
new THREE.BoxGeometry(0.32, 0.2, 0.32),
new THREE.MeshStandardMaterial({
color: 0xffd77c,
roughness: 0.45
})
);
shoulder.position.y = 0.35;
shoulder.castShadow = true;
group.add(shoulder);
const neck = new THREE.Mesh(
new THREE.BoxGeometry(0.18, 0.2, 0.18),
new THREE.MeshStandardMaterial({
color: 0xffe0a0,
roughness: 0.45
})
);
neck.position.y = 0.54;
neck.castShadow = true;
group.add(neck);
}
group.traverse((child) => {
if (child.isMesh) {
child.userData.itemId = itemId;
pickableMeshes.push(child);
}
});
return group;
}
const items = ITEM_CONFIGS.map((config) => {
const group = new THREE.Group();
const body = createBody(config.form, config.id);
group.add(body);
const { canvas: tagCanvas, texture: tagTexture } = makeTagTexture();
const tag = new THREE.Sprite(
new THREE.SpriteMaterial({
map: tagTexture,
transparent: true,
depthTest: false,
depthWrite: false,
toneMapped: false
})
);
tag.position.y = 1.05;
tag.scale.set(2.05, 0.59, 1);
tag.renderOrder = 30;
group.add(tag);
scene.add(group);
itemGroups.push(group);
return {
...config,
group,
body,
tag,
tagCanvas,
tagTexture,
state: "waiting",
x: SPAWN_X,
y: BELT_Y,
z: 0,
previousX: SPAWN_X,
declared: config.declared,
actual: config.actual,
actualRoute: null,
activeGate: null,
readerTimer: 0,
divertTimer: 0,
dropTimer: 0,
history: ["Queued"]
};
});
const selectionRing = new THREE.Mesh(
new THREE.TorusGeometry(0.57, 0.035, 6, 32),
new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.9,
depthTest: false
})
);
selectionRing.rotation.x = Math.PI / 2;
selectionRing.renderOrder = 25;
scene.add(selectionRing);
// -------------------------------------------------------------------------
// UI state and event log
// -------------------------------------------------------------------------
const ui = {
running: true,
speed: 1,
elapsed: 0,
selectedId: "E",
revealed: new Set(),
log: []
};
const elements = {
runPause: document.querySelector("#runPause"),
reset: document.querySelector("#reset"),
step: document.querySelector("#step"),
selectE: document.querySelector("#selectE"),
speed: document.querySelector("#speed"),
speedValue: document.querySelector("#speedValue"),
clock: document.querySelector("#clock"),
selectedId: document.querySelector("#selectedId"),
selectedForm: document.querySelector("#selectedForm"),
selectedStatus: document.querySelector("#selectedStatus"),
selectedTag: document.querySelector("#selectedTag"),
selectedRoute: document.querySelector("#selectedRoute"),
selectedTruth: document.querySelector("#selectedTruth"),
selectedExecuted: document.querySelector("#selectedExecuted"),
selectedJourney: document.querySelector("#selectedJourney"),
auditNote: document.querySelector("#auditNote"),
revealTruth: document.querySelector("#revealTruth"),
centerCamera: document.querySelector("#centerCamera"),
correctionSelect: document.querySelector("#correctionSelect"),
applyCorrection: document.querySelector("#applyCorrection"),
trackList: document.querySelector("#trackList"),
objectCount: document.querySelector("#objectCount"),
eventLog: document.querySelector("#eventLog")
};
function formatTime(seconds) {
return `${seconds.toFixed(1)} s`;
}
function addLog(text) {
ui.log.unshift({ time: formatTime(ui.elapsed), text });
ui.log = ui.log.slice(0, 9);
renderLog();
}
function renderLog() {
elements.eventLog.innerHTML = ui.log
.map(
(entry) =>
`<div class="log-entry"><time>${entry.time}</time><span>${entry.text}</span></div>`
)
.join("");
}
function itemHistory(item, message) {
item.history.push(message);
if (item.history.length > 8) item.history.shift();
}
function plannedGate(item) {
return GATES.find((gate) => gate.label === item.declared);
}
function routeDescription(gateId) {
const gate = GATES.find((g) => g.id === gateId);
if (!gate) return "Not yet";
return `${gate.id} → ${SCHEME[gate.label].bin}`;
}
function statusDescription(item) {
switch (item.state) {
case "waiting":
return "Queued";
case "reader":
return "Reading tag";
case "belt":
return "On conveyor";
case "divert":
return `Diverting to ${item.activeGate.id}`;
case "drop":
return `Dropping into ${item.activeGate.id}`;
case "collected":
return `Collected in ${item.activeGate.id}`;
default:
return item.state;
}
}
const rowRefs = new Map();
for (const item of items) {
const row = document.createElement("button");
row.className = "track-row";
row.dataset.id = item.id;
row.innerHTML = `
<span class="box-id">${item.id}</span>
<span class="row-main">
<b></b>
<small></small>
</span>
<span class="route-badge"></span>
`;
row.addEventListener("click", () => selectItem(item.id));
elements.trackList.appendChild(row);
rowRefs.set(item.id, row);
}
function selectItem(id) {
ui.selectedId = id;
const item = items.find((entry) => entry.id === id);
elements.correctionSelect.value = item.declared;
updateUI();
}
function revealGroundTruth() {
ui.revealed.add(ui.selectedId);
const item = items.find((entry) => entry.id === ui.selectedId);
addLog(
`${item.id}: audit ground truth is ${item.actual}; printed tag is ${item.declared}.`
);
updateUI();
}
function applyCorrection() {
const item = items.find((entry) => entry.id === ui.selectedId);
const newLabel = elements.correctionSelect.value;
const targetGate = GATES.find((gate) => gate.label === newLabel);
if (!targetGate) return;
if (newLabel === item.declared) {
addLog(`${item.id}: correction skipped; tag is already ${newLabel}.`);
return;
}
const wasLate =
item.state === "divert" ||
item.state === "drop" ||
item.state === "collected";
const mustRecall =
wasLate || item.x > targetGate.x - 0.38;
item.declared = newLabel;
item.actualRoute = null;
item.activeGate = null;
item.divertTimer = 0;
item.dropTimer = 0;
if (mustRecall) {
item.state = "belt";
item.x = targetGate.x - 0.42;
item.previousX = item.x;
item.y = BELT_Y;
item.z = 0;
item.group.visible = true;
item.group.rotation.set(0, 0, 0);
}
drawItemTag(item, item.declared);
itemHistory(item, `Tag corrected → ${item.declared}`);
addLog(
`${item.id}: tag corrected to ${item.declared}; planned route ${targetGate.id}.` +
(mustRecall ? " Item recalled to the correct gate." : "")
);
updateUI();
}
function updateInspector() {
const item = items.find((entry) => entry.id === ui.selectedId);
if (!item) return;
const gate = plannedGate(item);
const isMismatch = item.declared !== item.actual;
elements.selectedId.textContent = item.id;
elements.selectedForm.textContent = `${item.form} voxel`;
elements.selectedStatus.textContent = statusDescription(item);
elements.selectedTag.textContent = item.declared;
elements.selectedTag.className = isMismatch ? "mismatch" : "";
elements.selectedRoute.textContent = routeDescription(gate.id);
elements.selectedExecuted.textContent = item.actualRoute
? routeDescription(item.actualRoute)
: "Not yet";
elements.selectedTruth.textContent = ui.revealed.has(item.id)
? item.actual
: "Hidden — use audit button";
elements.selectedTruth.className = ui.revealed.has(item.id) && isMismatch
? "mismatch"
: "";
elements.selectedJourney.textContent =
"Journey: " + item.history.join(" → ");
elements.revealTruth.textContent = ui.revealed.has(item.id)
? "Ground truth revealed"
: "Reveal ground truth";
if (isMismatch) {
elements.auditNote.innerHTML =
"<strong>Mismatch detected.</strong> The printed tag and audited ground truth differ. " +
"Changing the tag updates the planned route; a completed route is recalled to the matching gate.";
} else {
elements.auditNote.innerHTML =
"The printed tag agrees with the audited ground truth. You may still demonstrate a correction.";
}
}
function updateUI() {
elements.clock.textContent = `t = ${ui.elapsed.toFixed(1)} s`;
let tracked = 0;
for (const item of items) {
const row = rowRefs.get(item.id);
const gate = plannedGate(item);
const mismatch = item.declared !== item.actual;
row.classList.toggle("selected", item.id === ui.selectedId);
row.classList.toggle("mismatch", mismatch && ui.revealed.has(item.id));
row.querySelector("b").textContent = item.declared;
row.querySelector("small").textContent = statusDescription(item);
row.querySelector(".route-badge").textContent = gate.id;
if (item.state !== "waiting") tracked++;
}
elements.objectCount.textContent = `${tracked} / ${items.length} tracked`;
updateInspector();
}
// -------------------------------------------------------------------------
// Simulation
// -------------------------------------------------------------------------
function resetSimulation() {
ui.elapsed = 0;
ui.log = [];
ui.revealed.clear();
ui.selectedId = "E";
ui.running = true;
for (const item of items) {
item.state = "waiting";
item.x = SPAWN_X;
item.previousX = SPAWN_X;
item.y = BELT_Y;
item.z = 0;
item.declared = item.config?.declared ?? ITEM_CONFIGS.find(
(config) => config.id === item.id
).declared;
item.actualRoute = null;
item.activeGate = null;
item.readerTimer = 0;
item.divertTimer = 0;
item.dropTimer = 0;
item.history = ["Queued"];
item.group.visible = false;
item.group.position.set(item.x, item.y, item.z);
item.group.rotation.set(0, 0, 0);
drawItemTag(item, item.declared);
}
elements.correctionSelect.value = "GLASS";
elements.runPause.textContent = "Pause line";
addLog("Line reset. All nine objects returned to the queue.");
updateUI();
}
function startDivert(item, gate) {
item.state = "divert";
item.activeGate = gate;
item.actualRoute = gate.id;
item.divertTimer = 0;
item.x = gate.x + 0.18;
item.previousX = gate.x;
itemHistory(item, `Diverted at ${gate.id}`);
addLog(
`${item.id}: tag ${item.declared} matched ${gate.id}; diverting to ${SCHEME[gate.label].bin}.`
);
const visual = gateVisuals.find((entry) => entry.gate.id === gate.id);
if (visual) visual.activity = 1;
}
function advanceSimulation(dt) {
ui.elapsed += dt;
for (const item of items) {
if (item.state === "waiting") {
if (ui.elapsed >= item.delay) {
item.state = "belt";
item.group.visible = true;
itemHistory(item, "Entered line");
addLog(`${item.id}: entered the conveyor.`);
}
continue;
}
if (item.state === "reader") {
item.readerTimer += dt;
scanFlash = 1;
scannerMaterial.color.setHex(COLORS[item.declared]);
scannerMaterial.opacity = 0.16 + scanFlash * 0.5;
if (item.readerTimer >= 0.55) {
item.state = "belt";
item.x = READER_X + 0.08;
item.previousX = item.x;
itemHistory(item, `Read ${item.declared}`);
addLog(
`${item.id}: reader read ${item.declared}; planned route ${SCHEME[item.declared].gate}.`
);
}
continue;
}
if (item.state === "belt") {
item.previousX = item.x;
item.x += 1.72 * dt;
if (
item.previousX < READER_X &&
item.x >= READER_X &&
item.state === "belt"
) {
item.x = READER_X;
item.state = "reader";
item.readerTimer = 0;
scanFlash = 1;
scannerMaterial.color.setHex(COLORS[item.declared]);
itemHistory(item, "At reader");
continue;
}
for (const gate of GATES) {
if (item.previousX < gate.x && item.x >= gate.x) {
if (item.declared === gate.label) {
startDivert(item, gate);
} else {
itemHistory(item, `Passed ${gate.id}`);
}
break;
}
}
if (item.state === "belt" && item.x > END_X) {
item.state = "overflow";
itemHistory(item, "Overflow — no matching gate");
addLog(
`${item.id}: overflow. No remaining gate matched tag ${item.declared}.`
);
}
continue;
}
if (item.state === "divert") {
item.divertTimer += dt;
const u = Math.min(1, item.divertTimer / 1.25);
const eased = u * u * (3 - 2 * u);
item.x = item.activeGate.x + 0.18 + eased * 0.36;
item.z = eased * BIN_Z;
item.y = BELT_Y - eased * 0.08;
item.group.rotation.y += dt * 1.25;
if (u >= 1) {
item.state = "drop";
item.dropTimer = 0;
itemHistory(item, `Dropping into ${item.activeGate.id}`);
}
continue;
}
if (item.state === "drop") {
item.dropTimer += dt;
const u = Math.min(1, item.dropTimer / 0.82);
const eased = 1 - Math.pow(1 - u, 3);
item.x = item.activeGate.x + 0.54;
item.z = BIN_Z;
item.y = BELT_Y - 0.08 - eased * (BELT_Y - 0.08 - 0.73);
if (u >= 1) {
item.state = "collected";
itemHistory(item, `Bin ${item.activeGate.id}`);
addLog(
`${item.id}: collected in ${SCHEME[item.activeGate.label].bin}.`
);
}
}
}
}
function updateVisuals(dt) {
for (let i = 0; i < beltSlats.length; i++) {
const slat = beltSlats[i];
slat.position.x += 1.72 * dt * ui.speed;
if (slat.position.x > END_X) {
slat.position.x = SPAWN_X;
}
}
scanFlash = Math.max(0, scanFlash - dt * 2.4);
scannerMaterial.opacity = 0.12 + scanFlash * 0.48;
for (const visual of gateVisuals) {
visual.activity = Math.max(0, visual.activity - dt * 1.8);
const targetRotation = visual.activity > 0 ? 0 : Math.PI / 2;
visual.armPivot.rotation.y = THREE.MathUtils.lerp(
visual.armPivot.rotation.y,
targetRotation,
Math.min(1, dt * 8)
);
}
for (const item of items) {
item.group.position.set(item.x, item.y, item.z);
if (item.state === "belt" || item.state === "reader") {
item.group.rotation.y = Math.sin(item.x * 0.8) * 0.055;
item.group.rotation.z = 0;
}
item.group.visible = item.state !== "waiting";
}
const selected = items.find((item) => item.id === ui.selectedId);
selectionRing.visible = Boolean(selected && selected.state !== "waiting");
if (selected) {
selectionRing.position.set(
selected.x,
Math.max(0.06, selected.y - 0.69),
selected.z
);
const pulse = 1 + Math.sin(performance.now() * 0.006) * 0.06;
selectionRing.scale.set(pulse, pulse, pulse);
}
}
// -------------------------------------------------------------------------
// Direct pointer camera controls and item picking
// -------------------------------------------------------------------------
const pointer = {
down: false,
dragging: false,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0
};
const raycaster = new THREE.Raycaster();
const pointerNdc = new THREE.Vector2();
canvas.addEventListener("pointerdown", (event) => {
pointer.down = true;
pointer.dragging = false;
pointer.startX = pointer.lastX = event.clientX;
pointer.startY = pointer.lastY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!pointer.down) return;
const dx = event.clientX - pointer.lastX;
const dy = event.clientY - pointer.lastY;
if (
Math.abs(event.clientX - pointer.startX) +
Math.abs(event.clientY - pointer.startY) >
5
) {
pointer.dragging = true;
}
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi + dy * 0.005,
0.35,
1.34
);
pointer.lastX = event.clientX;
pointer.lastY = event.clientY;
updateCamera();
});
canvas.addEventListener("pointerup", (event) => {
pointer.down = false;
if (!pointer.dragging) {
const rect = canvas.getBoundingClientRect();
pointerNdc.x =
((event.clientX - rect.left) / rect.width) * 2 - 1;
pointerNdc.y =
-((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointerNdc, camera);
const hits = raycaster.intersectObjects(pickableMeshes, false);
if (hits.length && hits[0].object.userData.itemId) {
selectItem(hits[0].object.userData.itemId);
}
}
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
11,
32
);
updateCamera();
},
{ passive: false }
);
// -------------------------------------------------------------------------
// UI bindings
// -------------------------------------------------------------------------
elements.runPause.addEventListener("click", () => {
ui.running = !ui.running;
elements.runPause.textContent = ui.running ? "Pause line" : "Run line";
});
elements.reset.addEventListener("click", resetSimulation);
elements.step.addEventListener("click", () => {
ui.running = false;
elements.runPause.textContent = "Run line";
advanceSimulation(0.5 * ui.speed);
updateUI();
});
elements.selectE.addEventListener("click", () => {
selectItem("E");
ui.running = false;
elements.runPause.textContent = "Run line";
addLog(
"Item E selected and line paused. Reveal its truth or apply a corrected tag."
);
updateUI();
});
elements.speed.addEventListener("input", () => {
ui.speed = Number(elements.speed.value);
elements.speedValue.textContent = `${ui.speed.toFixed(1)}×`;
});
elements.revealTruth.addEventListener("click", revealGroundTruth);
elements.applyCorrection.addEventListener("click", applyCorrection);
elements.centerCamera.addEventListener("click", () => {
cameraState.target.set(-0.6, 1.1, 1.15);
cameraState.radius = 20.5;
cameraState.theta = 0.67;
cameraState.phi = 0.88;
updateCamera();
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
// -------------------------------------------------------------------------
// Main loop
// -------------------------------------------------------------------------
resetSimulation();
let previousTime = performance.now();
let uiTimer = 0;
function animate(now) {
requestAnimationFrame(animate);
const realDt = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (ui.running) {
advanceSimulation(realDt * ui.speed);
}
updateVisuals(realDt);
updateCamera();
uiTimer += realDt;
if (uiTimer >= 0.16) {
uiTimer = 0;
updateUI();
}
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```