Prompt specification
Build or customize the Three.js 3D scene "Sorter With Two Output Lanes" 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: Sorter With Two Output Lanes
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/sorter-with-two-output-lanes-x3526
Scene Description Prompt:
Please use Three.js from cdnjs for a low-poly scene based on this idea: sorter with two output lanes. Animate a simple sorter directing items by visible shape. Preserve counts and create a waiting queue when the required output lane is occupied. Return one self-contained HTML file.
Working Three.js Starter (sorter-with-two-output-lanes-x3526):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Low-Poly Shape Sorter</title>
<style>
:root {
--ink: #17232e;
--muted: #607080;
--panel: rgba(248, 251, 253, 0.9);
--border: rgba(28, 48, 64, 0.13);
--lane-a: #f59e0b;
--lane-b: #06b6d4;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dce5eb;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas:active {
cursor: grabbing;
}
.panel {
position: fixed;
z-index: 10;
border: 1px solid var(--border);
background: var(--panel);
box-shadow: 0 12px 35px rgba(31, 49, 63, 0.12);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
#title-panel {
top: 18px;
left: 18px;
width: min(390px, calc(100vw - 36px));
padding: 16px 18px;
border-radius: 17px;
}
.eyebrow {
margin-bottom: 5px;
color: #557080;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(21px, 2.4vw, 30px);
line-height: 1.05;
letter-spacing: -0.035em;
}
.subtitle {
margin: 9px 0 12px;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 9px 15px;
color: #344655;
font-size: 12px;
font-weight: 700;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 7px;
}
.shape {
display: inline-block;
flex: 0 0 auto;
width: 15px;
height: 15px;
}
.shape.triangle {
width: 0;
height: 0;
border-left: 8px solid transparent;
border-right: 8px solid transparent;
border-bottom: 14px solid var(--lane-a);
}
.shape.square {
border: 3px solid var(--lane-b);
border-radius: 2px;
background: rgba(6, 182, 212, 0.13);
}
#stats-panel {
top: 18px;
right: 18px;
width: min(355px, calc(100vw - 36px));
padding: 15px;
border-radius: 17px;
}
.metrics {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 7px;
}
.metric {
min-width: 0;
padding: 9px 5px;
border: 1px solid rgba(27, 46, 60, 0.08);
border-radius: 11px;
background: rgba(255, 255, 255, 0.62);
text-align: center;
}
.metric strong {
display: block;
font-size: 19px;
line-height: 1;
}
.metric span {
display: block;
margin-top: 5px;
overflow: hidden;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-overflow: ellipsis;
text-transform: uppercase;
white-space: nowrap;
}
.metric.total {
border-color: rgba(15, 118, 110, 0.24);
background: rgba(20, 184, 166, 0.09);
}
.metric.waiting {
border-color: rgba(245, 158, 11, 0.27);
background: rgba(245, 158, 11, 0.09);
}
.status-line {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 11px;
padding-top: 10px;
border-top: 1px solid var(--border);
color: #405463;
font-size: 11px;
font-weight: 700;
}
#conservation {
color: #0f766e;
white-space: nowrap;
}
#controls-panel {
bottom: 18px;
left: 50%;
width: min(760px, calc(100vw - 36px));
padding: 12px;
border-radius: 17px;
transform: translateX(-50%);
}
.controls {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
gap: 9px;
}
button {
appearance: none;
border: 1px solid rgba(23, 35, 46, 0.15);
border-radius: 11px;
padding: 10px 14px;
background: rgba(255, 255, 255, 0.84);
color: var(--ink);
font: inherit;
font-size: 12px;
font-weight: 800;
cursor: pointer;
transition:
transform 120ms ease,
background 120ms ease,
opacity 120ms ease;
}
button:hover:not(:disabled) {
transform: translateY(-1px);
background: #fff;
}
button:active:not(:disabled) {
transform: translateY(1px);
}
button:disabled {
cursor: default;
opacity: 0.48;
}
#toggle {
min-width: 94px;
border-color: rgba(15, 118, 110, 0.28);
background: #0f766e;
color: #fff;
}
.lane-button {
min-width: 150px;
text-align: left;
}
.lane-button::before {
display: inline-block;
width: 9px;
height: 9px;
margin-right: 8px;
border-radius: 50%;
background: var(--lane);
content: "";
box-shadow: 0 0 0 3px color-mix(in srgb, var(--lane) 18%, transparent);
}
#help {
margin: 9px 4px 1px;
color: var(--muted);
font-size: 11px;
line-height: 1.4;
text-align: center;
}
@media (max-width: 760px) {
#title-panel {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 12px 14px;
}
#stats-panel {
top: auto;
right: 10px;
bottom: 112px;
width: calc(100vw - 20px);
padding: 10px;
}
.subtitle {
display: none;
}
#controls-panel {
bottom: 10px;
width: calc(100vw - 20px);
padding: 9px;
}
button {
padding: 9px 10px;
font-size: 11px;
}
.lane-button {
min-width: 135px;
}
#help {
display: none;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<section id="title-panel" class="panel">
<div class="eyebrow">Low-poly logistics lab</div>
<h1>Shape Sorter</h1>
<p class="subtitle">
The scanner reads each visible shape, then the yellow diverter routes it to
the correct output. Each output lane holds one item.
</p>
<div class="legend">
<span><i class="shape triangle"></i> Triangle → Lane A</span>
<span><i class="shape square"></i> Square → Lane B</span>
</div>
</section>
<section id="stats-panel" class="panel">
<div class="metrics">
<div class="metric total"><strong id="totalCount">0</strong><span>Total</span></div>
<div class="metric"><strong id="movingCount">0</strong><span>Moving</span></div>
<div class="metric waiting"><strong id="waitingCount">0</strong><span>Waiting</span></div>
<div class="metric"><strong id="laneACount">0</strong><span>Lane A</span></div>
<div class="metric"><strong id="laneBCount">0</strong><span>Lane B</span></div>
</div>
<div class="status-line">
<span id="flowStatus">Starting…</span>
<span id="conservation">✓ count conserved</span>
</div>
</section>
<section id="controls-panel" class="panel">
<div class="controls">
<button id="toggle" type="button">Pause</button>
<button id="collectA" class="lane-button" type="button" style="--lane: #f59e0b">
Lane A — empty
</button>
<button id="collectB" class="lane-button" type="button" style="--lane: #06b6d4">
Lane B — empty
</button>
<button id="reset" type="button">Reset</button>
<button id="cameraReset" type="button">Reset camera</button>
</div>
<div id="help">
Drag to orbit · Scroll or pinch to zoom · Collect an occupied lane to release
its waiting queue · Every item remains visible in the collection bin
</div>
</section>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const sceneElement = $("scene");
// -------------------------------------------------------------------------
// Renderer, camera, and custom camera controls (no addons)
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce5eb);
scene.fog = new THREE.Fog(0xdce5eb, 27, 58);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
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;
sceneElement.appendChild(renderer.domElement);
const cameraControl = {
theta: 0.62,
phi: 0.84,
radius: 25,
target: new THREE.Vector3(0, 0.35, -0.65),
};
function updateCamera() {
const sinPhi = Math.sin(cameraControl.phi);
camera.position.set(
cameraControl.target.x +
cameraControl.radius * sinPhi * Math.sin(cameraControl.theta),
cameraControl.target.y + cameraControl.radius * Math.cos(cameraControl.phi),
cameraControl.target.z +
cameraControl.radius * sinPhi * Math.cos(cameraControl.theta)
);
camera.lookAt(cameraControl.target);
}
function resetCamera() {
cameraControl.theta = 0.62;
cameraControl.phi = 0.84;
cameraControl.radius = 25;
cameraControl.target.set(0, 0.35, -0.65);
updateCamera();
}
const pointers = new Map();
let dragPointer = null;
let lastPointerX = 0;
let lastPointerY = 0;
let pinchDistance = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY,
});
if (pointers.size === 1) {
dragPointer = event.pointerId;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
} else {
dragPointer = null;
const points = [...pointers.values()];
pinchDistance = Math.hypot(
points[0].x - points[1].x,
points[0].y - points[1].y
);
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointers.has(event.pointerId)) return;
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY,
});
if (pointers.size >= 2) {
const points = [...pointers.values()];
const distance = Math.hypot(
points[0].x - points[1].x,
points[0].y - points[1].y
);
if (pinchDistance > 0 && distance > 0) {
cameraControl.radius = THREE.MathUtils.clamp(
cameraControl.radius * (pinchDistance / distance),
13,
38
);
}
pinchDistance = distance;
} else if (dragPointer === event.pointerId) {
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
cameraControl.theta -= dx * 0.006;
cameraControl.phi = THREE.MathUtils.clamp(
cameraControl.phi - dy * 0.005,
0.3,
1.36
);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
}
});
function releasePointer(event) {
pointers.delete(event.pointerId);
if (dragPointer === event.pointerId) dragPointer = null;
if (pointers.size < 2) pinchDistance = 0;
}
renderer.domElement.addEventListener("pointerup", releasePointer);
renderer.domElement.addEventListener("pointercancel", releasePointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraControl.radius = THREE.MathUtils.clamp(
cameraControl.radius * Math.exp(event.deltaY * 0.001),
13,
38
);
},
{ passive: false }
);
$("cameraReset").addEventListener("click", resetCamera);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// -------------------------------------------------------------------------
// Lighting and environment
// -------------------------------------------------------------------------
const hemisphere = new THREE.HemisphereLight(0xf7fbff, 0x677782, 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffffff, 3.2);
sun.position.set(11, 18, 12);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -22;
sun.shadow.camera.right = 22;
sun.shadow.camera.top = 22;
sun.shadow.camera.bottom = -22;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 55;
sun.shadow.bias = -0.0003;
scene.add(sun);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(42, 36),
new THREE.MeshStandardMaterial({
color: 0xcbd6dc,
roughness: 0.95,
metalness: 0,
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.035;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(40, 40, 0x9badb8, 0xb4c2ca);
grid.position.y = -0.015;
grid.material.transparent = true;
grid.material.opacity = 0.25;
scene.add(grid);
function addBox(parent, size, color, position) {
const material =
color && color.isMaterial
? color
: new THREE.MeshStandardMaterial({
color,
roughness: 0.78,
metalness: 0.05,
flatShading: 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 = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeLabel(text, background = "#203746", foreground = "#ffffff", width = 3.8) {
const canvas = document.createElement("canvas");
canvas.width = 768;
canvas.height = 160;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = background;
context.beginPath();
context.roundRect(4, 4, 760, 152, 30);
context.fill();
context.strokeStyle = "rgba(255,255,255,0.22)";
context.lineWidth = 4;
context.stroke();
context.fillStyle = foreground;
context.font = "800 46px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2, canvas.height / 2 + 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false,
})
);
sprite.scale.set(width, width / 4.8, 1);
sprite.renderOrder = 20;
return sprite;
}
// -------------------------------------------------------------------------
// Conveyor construction
// -------------------------------------------------------------------------
const conveyors = [];
function createConveyor(start, end, width, accentColor) {
const dx = end[0] - start[0];
const dz = end[1] - start[1];
const length = Math.hypot(dx, dz);
const group = new THREE.Group();
group.position.set((start[0] + end[0]) / 2, 0, (start[1] + end[1]) / 2);
group.rotation.y = Math.atan2(dx, dz);
scene.add(group);
const beltMaterial = new THREE.MeshStandardMaterial({
color: 0x25343e,
roughness: 0.9,
metalness: 0.02,
});
const railMaterial = new THREE.MeshStandardMaterial({
color: accentColor,
roughness: 0.58,
metalness: 0.18,
flatShading: true,
});
const supportMaterial = new THREE.MeshStandardMaterial({
color: 0x657782,
roughness: 0.82,
metalness: 0.08,
flatShading: true,
});
addBox(group, [width, 0.4, length], beltMaterial, [0, 0.78, 0]);
addBox(
group,
[0.13, 0.3, length],
railMaterial,
[-width / 2 - 0.07, 1.02, 0]
);
addBox(
group,
[0.13, 0.3, length],
railMaterial,
[width / 2 + 0.07, 1.02, 0]
);
const rollerMaterial = new THREE.MeshStandardMaterial({
color: 0x9aabb4,
roughness: 0.48,
metalness: 0.45,
flatShading: true,
});
const rollerCount = Math.max(3, Math.floor(length / 0.85));
for (let i = 0; i < rollerCount; i++) {
const z = -length / 2 + 0.3 + (i / Math.max(1, rollerCount - 1)) * (length - 0.6);
const roller = new THREE.Mesh(
new THREE.CylinderGeometry(0.115, 0.115, width * 0.94, 8),
rollerMaterial
);
roller.rotation.z = Math.PI / 2;
roller.position.set(0, 0.96, z);
roller.castShadow = true;
group.add(roller);
}
for (let z = -length / 2 + 0.7; z < length / 2; z += 2.7) {
addBox(group, [0.18, 0.72, 0.18], supportMaterial, [-width * 0.36, 0.34, z]);
addBox(group, [0.18, 0.72, 0.18], supportMaterial, [width * 0.36, 0.34, z]);
}
const slats = [];
const slatMaterial = new THREE.MeshStandardMaterial({
color: 0x53626b,
roughness: 0.88,
metalness: 0.04,
});
for (let z = -length / 2 + 0.2; z < length / 2; z += 0.62) {
const slat = addBox(
group,
[width * 0.83, 0.025, 0.065],
slatMaterial,
[0, 0.997, z]
);
slat.castShadow = false;
slats.push(slat);
}
conveyors.push({ group, length, slats });
return group;
}
const MAIN_START = [0, 9.3];
const DECISION_Z = -0.45;
const MAIN_END = [0, DECISION_Z];
const BRANCH_END = [
[-4.8, -3.55],
[4.8, -3.55],
];
const LANE_END_Z = -8.35;
createConveyor(MAIN_START, MAIN_END, 3.2, 0xe6b84c);
createConveyor([0, DECISION_Z], BRANCH_END[0], 2.25, 0xf59e0b);
createConveyor([0, DECISION_Z], BRANCH_END[1], 2.25, 0x06b6d4);
createConveyor(BRANCH_END[0], [-4.8, LANE_END_Z], 2.25, 0xf59e0b);
createConveyor(BRANCH_END[1], [4.8, LANE_END_Z], 2.25, 0x06b6d4);
const inletLabel = makeLabel("INCOMING", "#284452", "#ffffff", 3.2);
inletLabel.position.set(0, 2.6, 8.65);
scene.add(inletLabel);
const laneLabelA = makeLabel("A • TRIANGLES", "#a85d00", "#ffffff", 4.15);
laneLabelA.position.set(-4.8, 2.75, -3.75);
scene.add(laneLabelA);
const laneLabelB = makeLabel("B • SQUARES", "#087d91", "#ffffff", 4.15);
laneLabelB.position.set(4.8, 2.75, -3.75);
scene.add(laneLabelB);
// -------------------------------------------------------------------------
// Scanner and visible hold beacon
// -------------------------------------------------------------------------
const scanner = new THREE.Group();
scanner.position.z = 0.72;
scene.add(scanner);
const scannerMaterial = new THREE.MeshStandardMaterial({
color: 0x344b59,
roughness: 0.6,
metalness: 0.25,
flatShading: true,
});
addBox(scanner, [0.3, 2.65, 0.38], scannerMaterial, [-1.78, 2.13, 0]);
addBox(scanner, [0.3, 2.65, 0.38], scannerMaterial, [1.78, 2.13, 0]);
addBox(scanner, [3.85, 0.34, 0.45], scannerMaterial, [0, 3.37, 0]);
const scannerSign = makeLabel("SHAPE SCANNER", "#203746", "#d9fbff", 3.55);
scannerSign.position.set(0, 3.93, 0.72);
scene.add(scannerSign);
const scanCurtain = new THREE.Mesh(
new THREE.PlaneGeometry(2.95, 1.6),
new THREE.MeshBasicMaterial({
color: 0x2de2c4,
transparent: true,
opacity: 0.095,
side: THREE.DoubleSide,
depthWrite: false,
})
);
scanCurtain.position.set(0, 1.9, 0.72);
scanner.add(scanCurtain);
const scanLine = addBox(
scanner,
[2.9, 0.028, 0.055],
new THREE.MeshBasicMaterial({ color: 0x55f5d5 }),
[0, 1.15, 0]
);
scanLine.castShadow = false;
const beaconMaterial = new THREE.MeshStandardMaterial({
color: 0x38d996,
emissive: 0x38d996,
emissiveIntensity: 0.85,
roughness: 0.35,
flatShading: true,
});
const beacon = new THREE.Mesh(
new THREE.CylinderGeometry(0.22, 0.26, 0.3, 10),
beaconMaterial
);
beacon.position.set(0, 3.67, 0.72);
scene.add(beacon);
const holdLabel = makeLabel("HOLD QUEUE", "#9a3412", "#fff7ed", 3.15);
holdLabel.position.set(2.6, 2.65, -0.25);
holdLabel.visible = false;
scene.add(holdLabel);
// -------------------------------------------------------------------------
// Single pivoting diverter
// -------------------------------------------------------------------------
const diverter = new THREE.Group();
diverter.position.set(0, 1.08, DECISION_Z);
scene.add(diverter);
const armMaterial = new THREE.MeshStandardMaterial({
color: 0xf7c948,
roughness: 0.52,
metalness: 0.18,
flatShading: true,
});
addBox(diverter, [2.05, 0.22, 0.18], armMaterial, [1.02, 0.08, 0]);
const diverterTip = new THREE.Mesh(
new THREE.ConeGeometry(0.25, 0.62, 3),
armMaterial
);
diverterTip.rotation.z = -Math.PI / 2;
diverterTip.position.set(2.27, 0.08, 0);
diverterTip.castShadow = true;
diverter.add(diverterTip);
const pivot = new THREE.Mesh(
new THREE.CylinderGeometry(0.29, 0.29, 0.35, 10),
scannerMaterial
);
diverter.add(pivot);
// -------------------------------------------------------------------------
// Collection bins: collected items remain visible, preserving the total
// -------------------------------------------------------------------------
function createCollectionBin(side, accent, title) {
const group = new THREE.Group();
group.position.set(side * 7.15, 0, -8.2);
scene.add(group);
const material = new THREE.MeshStandardMaterial({
color: accent,
roughness: 0.68,
metalness: 0.08,
flatShading: true,
});
addBox(group, [2.35, 0.28, 2.5], 0x566873, [0, 0.62, 0]);
addBox(group, [0.13, 0.85, 2.5], material, [-1.12, 0.93, 0]);
addBox(group, [0.13, 0.85, 2.5], material, [1.12, 0.93, 0]);
addBox(group, [2.35, 0.85, 0.13], material, [0, 0.93, -1.18]);
addBox(group, [2.35, 0.85, 0.13], material, [0, 0.93, 1.18]);
const label = makeLabel(title, "#314652", "#ffffff", 2.65);
label.position.set(0, 1.8, 0);
group.add(label);
}
createCollectionBin(-1, 0xf59e0b, "COLLECTED A");
createCollectionBin(1, 0x06b6d4, "COLLECTED B");
// -------------------------------------------------------------------------
// Decorative low-poly factory pieces
// -------------------------------------------------------------------------
const cabinet = new THREE.Group();
cabinet.position.set(-7.3, 0, 2.9);
cabinet.rotation.y = 0.12;
scene.add(cabinet);
addBox(cabinet, [1.8, 2.1, 1.25], 0x566975, [0, 1.05, 0]);
addBox(cabinet, [1.35, 0.72, 0.08], 0x172c38, [0, 1.45, 0.66]);
addBox(cabinet, [0.18, 0.18, 0.12], 0xf59e0b, [-0.5, 0.67, 0.69]);
addBox(cabinet, [0.18, 0.18, 0.12], 0x35c98f, [0.5, 0.67, 0.69]);
for (let i = 0; i < 3; i++) {
const crate = new THREE.Mesh(
new THREE.BoxGeometry(1.05, 0.85, 1.05),
new THREE.MeshStandardMaterial({
color: i % 2 ? 0xb88654 : 0x8b684b,
roughness: 0.95,
flatShading: true,
})
);
crate.position.set(7.4 + (i % 2) * 1.25, 0.45, 3.3 + Math.floor(i / 2) * 1.3);
crate.rotation.y = i * 0.12;
crate.castShadow = true;
crate.receiveShadow = true;
scene.add(crate);
}
// -------------------------------------------------------------------------
// Item geometry and simulation state
// -------------------------------------------------------------------------
const triangleShape = new THREE.Shape();
triangleShape.moveTo(-0.56, -0.42);
triangleShape.lineTo(0.56, -0.42);
triangleShape.lineTo(0, 0.58);
triangleShape.closePath();
const triangleGeometry = new THREE.ExtrudeGeometry(triangleShape, {
depth: 0.3,
bevelEnabled: false,
steps: 1,
});
triangleGeometry.center();
triangleGeometry.rotateX(-Math.PI / 2);
const squareGeometry = new THREE.BoxGeometry(0.96, 0.3, 0.96);
const triangleMaterial = new THREE.MeshStandardMaterial({
color: 0xf59e0b,
roughness: 0.58,
metalness: 0.08,
flatShading: true,
});
const squareMaterial = new THREE.MeshStandardMaterial({
color: 0x16c4d8,
roughness: 0.52,
metalness: 0.1,
flatShading: true,
});
const itemSequence = [
"triangle",
"square",
"triangle",
"square",
"triangle",
"square",
"triangle",
"square",
"triangle",
"triangle",
];
const items = [];
const laneBusy = [false, false];
const collectedCounts = [0, 0];
const SPEED = 2.1;
const MIN_GAP = 0.9;
const ITEM_Y = 1.2;
let activeTransfer = null;
let paused = false;
let simulationTime = 0;
let nextItemId = 1;
function routeForShape(shape) {
// Routing is determined only by the item's visible shape.
return shape === "triangle" ? 0 : 1;
}
function buildItems() {
for (const item of items) scene.remove(item.group);
items.length = 0;
laneBusy[0] = false;
laneBusy[1] = false;
collectedCounts[0] = 0;
collectedCounts[1] = 0;
activeTransfer = null;
nextItemId = 1;
itemSequence.forEach((shape, index) => {
const group = new THREE.Group();
const geometry = shape === "triangle" ? triangleGeometry : squareGeometry;
const material = shape === "triangle" ? triangleMaterial : squareMaterial;
const mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
group.add(mesh);
group.position.set(0, ITEM_Y, 0.05 + index * 0.95);
items.push({
id: nextItemId++,
shape,
lane: routeForShape(shape),
group,
state: "main",
blocked: false,
holdReason: "",
transferProgress: 0,
transferDuration: 1,
collectProgress: 0,
collectStart: new THREE.Vector3(),
collectTarget: new THREE.Vector3(),
});
});
}
function startTransfer(item) {
const end = BRANCH_END[item.lane];
item.state = "transfer";
item.blocked = false;
item.holdReason = "";
item.transferProgress = 0;
item.transferDuration =
(Math.hypot(end[0], end[1] - DECISION_Z) / SPEED) * 1.08;
item.group.position.set(0, ITEM_Y, DECISION_Z);
laneBusy[item.lane] = true;
activeTransfer = item;
}
function updateMain(dt) {
const mainItems = items
.filter((item) => item.state === "main")
.sort(
(a, b) => a.group.position.z - b.group.position.z
);
for (const item of mainItems) {
let proposedZ = item.group.position.z - SPEED * dt;
if (proposedZ <= DECISION_Z + 0.001) {
const sorterBusy = activeTransfer !== null;
const targetBusy = laneBusy[item.lane];
if (sorterBusy || targetBusy) {
item.group.position.z = DECISION_Z;
item.blocked = true;
item.holdReason = sorterBusy ? "sorter" : "occupied-lane";
continue;
}
startTransfer(item);
continue;
}
let nearestAhead = null;
for (const other of items) {
if (
other !== item &&
other.state === "main" &&
other.group.position.z < item.group.position.z &&
(!nearestAhead ||
other.group.position.z > nearestAhead.group.position.z)
) {
nearestAhead = other;
}
}
item.blocked = false;
item.holdReason = "";
if (nearestAhead) {
const maximumZ = nearestAhead.group.position.z + MIN_GAP;
proposedZ = Math.min(proposedZ, maximumZ);
if (
nearestAhead.blocked &&
proposedZ >= maximumZ - 0.025
) {
item.blocked = true;
item.holdReason = "queue";
}
}
item.group.position.z = Math.max(DECISION_Z, proposedZ);
}
}
function updateTransfer(dt) {
if (!activeTransfer) return;
const item = activeTransfer;
item.transferProgress += dt / item.transferDuration;
const t = Math.min(item.transferProgress, 1);
const end = BRANCH_END[item.lane];
item.group.position.x = end[0] * t;
item.group.position.z = DECISION_Z + (end[1] - DECISION_Z) * t;
item.group.position.y =
ITEM_Y + Math.sin(simulationTime * 9 + item.id) * 0.025;
if (item.transferProgress >= 1) {
item.group.position.set(end[0], ITEM_Y, end[1]);
item.state = "laneRun";
activeTransfer = null;
}
}
function updateLaneRuns(dt) {
for (const item of items) {
if (item.state !== "laneRun") continue;
item.group.position.z -= SPEED * dt;
item.group.position.y =
ITEM_Y + Math.sin(simulationTime * 8 + item.id) * 0.018;
if (item.group.position.z <= LANE_END_Z) {
item.group.position.z = LANE_END_Z;
item.group.position.y = ITEM_Y;
item.state = "laneOutput";
}
}
}
function collectionSlot(lane, count) {
const side = lane === 0 ? -1 : 1;
const column = count % 2;
const row = Math.floor(count / 2) % 2;
const layer = Math.floor(count / 4);
return new THREE.Vector3(
side * 7.15 + (column === 0 ? -0.36 : 0.36),
ITEM_Y + layer * 0.27,
-8.2 + (row === 0 ? -0.42 : 0.42)
);
}
function collectLane(lane) {
const item = items.find(
(candidate) =>
candidate.state === "laneOutput" && candidate.lane === lane
);
if (!item) return;
item.state = "collecting";
item.collectProgress = 0;
item.collectStart.copy(item.group.position);
item.collectTarget.copy(
collectionSlot(lane, collectedCounts[lane])
);
}
function updateCollecting(dt) {
for (const item of items) {
if (item.state !== "collecting") continue;
item.collectProgress = Math.min(item.collectProgress + dt / 0.9, 1);
const t = item.collectProgress;
item.group.position.lerpVectors(
item.collectStart,
item.collectTarget,
t
);
item.group.position.y += Math.sin(Math.PI * t) * 1.35;
if (item.collectProgress >= 1) {
item.group.position.copy(item.collectTarget);
item.state = "collected";
collectedCounts[item.lane] += 1;
laneBusy[item.lane] = false;
}
}
}
function updateConveyors(dt) {
for (const conveyor of conveyors) {
for (const slat of conveyor.slats) {
slat.position.z += dt * 1.25;
if (slat.position.z > conveyor.length / 2) {
slat.position.z -= conveyor.length;
}
}
}
}
function updateDiverter(dt) {
const targetAngle = activeTransfer
? activeTransfer.lane === 0
? 2.57
: 0.57
: 0;
const smoothing = 1 - Math.exp(-dt * 10);
diverter.rotation.y +=
(targetAngle - diverter.rotation.y) * smoothing;
}
// -------------------------------------------------------------------------
// UI and controls
// -------------------------------------------------------------------------
function updateUI() {
let moving = 0;
let waiting = 0;
const outputs = [0, 0];
let collected = 0;
let laneHoldWaiting = false;
let sorterHoldWaiting = false;
for (const item of items) {
if (item.state === "main") {
if (item.blocked) {
waiting += 1;
if (item.holdReason === "occupied-lane") laneHoldWaiting = true;
if (item.holdReason === "sorter") sorterHoldWaiting = true;
} else {
moving += 1;
}
} else if (
item.state === "transfer" ||
item.state === "laneRun" ||
item.state === "collecting"
) {
moving += 1;
} else if (item.state === "laneOutput") {
outputs[item.lane] += 1;
} else if (item.state === "collected") {
collected += 1;
}
}
const total = items.length;
const accountedFor =
moving + waiting + outputs[0] + outputs[1] + collected;
$("totalCount").textContent = total;
$("movingCount").textContent = moving;
$("waitingCount").textContent = waiting;
$("laneACount").textContent = outputs[0];
$("laneBCount").textContent = outputs[1];
$("conservation").textContent =
accountedFor === total
? "✓ count conserved"
: `⚠ ${accountedFor}/${total}`;
if (laneHoldWaiting) {
$("flowStatus").textContent =
"Queue holding: required output lane occupied";
} else if (sorterHoldWaiting) {
$("flowStatus").textContent = "Queue holding: sorter arm is routing";
} else if (activeTransfer) {
$("flowStatus").textContent = "Routing item by visible shape…";
} else {
$("flowStatus").textContent = "Flowing normally";
}
if (paused) {
$("flowStatus").textContent = "Simulation paused";
}
holdLabel.visible = waiting > 0;
if (waiting > 0) {
beaconMaterial.color.setHex(0xef4444);
beaconMaterial.emissive.setHex(0xef4444);
beaconMaterial.emissiveIntensity = 1.2;
} else {
beaconMaterial.color.setHex(0x38d996);
beaconMaterial.emissive.setHex(0x38d996);
beaconMaterial.emissiveIntensity = 0.75;
}
updateLaneButton(0, "A", outputs[0]);
updateLaneButton(1, "B", outputs[1]);
}
function updateLaneButton(lane, letter, outputCount) {
const button = lane === 0 ? $("collectA") : $("collectB");
const collecting = items.some(
(item) =>
item.state === "collecting" && item.lane === lane
);
const inTransit = items.some(
(item) =>
(item.state === "transfer" || item.state === "laneRun") &&
item.lane === lane
);
button.disabled = outputCount === 0;
if (outputCount > 0) {
button.textContent = `Collect Lane ${letter}`;
} else if (collecting) {
button.textContent = `Lane ${letter} — collecting…`;
} else if (inTransit || laneBusy[lane]) {
button.textContent = `Lane ${letter} — reserved`;
} else {
button.textContent = `Lane ${letter} — empty`;
}
}
function toggleSimulation() {
paused = !paused;
$("toggle").textContent = paused ? "Resume" : "Pause";
}
function resetSimulation() {
buildItems();
simulationTime = 0;
paused = false;
diverter.rotation.y = 0;
$("toggle").textContent = "Pause";
updateUI();
}
$("toggle").addEventListener("click", toggleSimulation);
$("reset").addEventListener("click", resetSimulation);
$("collectA").addEventListener("click", () => collectLane(0));
$("collectB").addEventListener("click", () => collectLane(1));
window.addEventListener("keydown", (event) => {
if (event.code === "Space" && event.target === document.body) {
event.preventDefault();
toggleSimulation();
}
});
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
if (!paused) {
simulationTime += dt;
updateConveyors(dt);
updateTransfer(dt);
updateLaneRuns(dt);
updateCollecting(dt);
updateMain(dt);
updateDiverter(dt);
for (const item of items) {
if (
item.state === "main" ||
item.state === "transfer" ||
item.state === "laneRun"
) {
if (item.shape === "triangle") {
item.group.rotation.y += dt * 0.32;
}
}
}
}
const scanPhase = (simulationTime * 0.8) % 1;
scanLine.position.y = 1.15 + scanPhase * 1.55;
scanCurtain.material.opacity =
0.055 + Math.sin(simulationTime * 4) * 0.025;
beacon.rotation.y += dt * 1.7;
updateCamera();
updateUI();
renderer.render(scene, camera);
}
buildItems();
resetCamera();
updateUI();
animate();
</script>
</body>
</html>
```