Prompt specification
Build or customize the Three.js 3D scene "Toy Factory Logistics Game" 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: Toy Factory Logistics Game
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/toy-factory-logistics-game-x3527
Scene Description Prompt:
A voxel toy factory with belts, sorters, and two machines; disconnected routes and blocked outputs cause visible backups. Three.js from cdnjs, one HTML file.
Working Three.js Starter (toy-factory-logistics-game-x3527):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Block Party — Voxel Toy Factory</title>
<style>
:root {
--ink: #17202a;
--cream: #f5efe2;
--panel: rgba(255, 252, 244, 0.94);
--orange: #f36b3d;
--yellow: #f4c44e;
--blue: #3987d5;
--green: #48a66b;
--red: #d94841;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
background: #dce8ed;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.panel {
background: var(--panel);
border: 1px solid rgba(23, 32, 42, 0.12);
box-shadow: 0 12px 35px rgba(37, 47, 56, 0.14);
backdrop-filter: blur(12px);
}
#title {
position: fixed;
top: 20px;
left: 20px;
padding: 17px 20px 16px;
border-radius: 18px;
max-width: 390px;
pointer-events: none;
}
.eyebrow {
font-size: 10px;
line-height: 1;
font-weight: 900;
letter-spacing: 0.19em;
color: var(--orange);
text-transform: uppercase;
margin-bottom: 8px;
}
h1 {
margin: 0;
font-size: clamp(22px, 3vw, 34px);
line-height: 0.95;
letter-spacing: -0.055em;
}
#title p {
margin: 9px 0 0;
font-size: 12px;
line-height: 1.45;
color: #5d6872;
max-width: 330px;
}
#stats {
position: fixed;
top: 20px;
right: 20px;
width: 230px;
padding: 16px;
border-radius: 18px;
pointer-events: none;
}
.stat-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
}
.stat-row:last-child { margin-bottom: 0; }
.stat-label {
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.12em;
font-weight: 850;
color: #68747d;
}
.stat-value {
font-size: 20px;
font-weight: 900;
letter-spacing: -0.04em;
}
.meter {
height: 6px;
background: #e7e1d5;
border-radius: 99px;
overflow: hidden;
margin: 6px 0 12px;
}
.meter:last-child { margin-bottom: 0; }
.meter > div {
height: 100%;
width: 0;
border-radius: inherit;
transition: width 0.18s ease;
}
#meterA { background: var(--green); }
#meterB { background: var(--blue); }
#meterTotal { background: var(--orange); }
#issue {
position: fixed;
left: 20px;
bottom: 145px;
padding: 10px 13px;
border-radius: 12px;
font-size: 11px;
font-weight: 800;
max-width: 390px;
pointer-events: none;
}
#controls {
position: fixed;
left: 50%;
bottom: 18px;
transform: translateX(-50%);
width: min(1080px, calc(100% - 36px));
padding: 13px;
border-radius: 19px;
display: flex;
align-items: stretch;
gap: 10px;
overflow-x: auto;
}
.control-group {
min-width: max-content;
padding: 3px 11px 3px 3px;
border-right: 1px solid #ddd6c8;
display: flex;
flex-direction: column;
justify-content: center;
gap: 7px;
}
.control-group:last-child { border-right: 0; }
.group-label {
font-size: 9px;
font-weight: 900;
letter-spacing: 0.13em;
text-transform: uppercase;
color: #7a817f;
padding-left: 4px;
}
.button-row { display: flex; gap: 6px; }
button {
border: 1px solid #d7d0c3;
background: #fffaf0;
color: var(--ink);
border-radius: 10px;
padding: 8px 10px;
font: inherit;
font-size: 11px;
font-weight: 850;
cursor: pointer;
white-space: nowrap;
transition: transform 0.12s ease, background 0.12s ease, border-color 0.12s ease;
}
button:hover {
transform: translateY(-1px);
border-color: #aaa092;
}
button:active { transform: translateY(1px); }
button.on {
color: white;
border-color: transparent;
background: var(--ink);
}
button.danger {
background: #f7d9d4;
color: #a52e29;
border-color: #e8b5ae;
}
button.danger.on {
background: var(--red);
color: white;
border-color: var(--red);
}
#machineA.on { background: var(--orange); }
#machineB.on { background: var(--blue); }
#sorterAuto.on { background: var(--yellow); color: var(--ink); }
#sorterA.on { background: var(--green); }
#sorterB.on { background: var(--blue); }
#routeB.on { background: var(--green); }
#cameraHelp {
position: fixed;
right: 20px;
bottom: 20px;
padding: 9px 12px;
border-radius: 10px;
font-size: 10px;
font-weight: 750;
color: #606a70;
pointer-events: none;
}
@media (max-width: 760px) {
#title {
top: 10px;
left: 10px;
max-width: calc(100% - 20px);
padding: 13px 15px;
}
#title p { display: none; }
#stats {
top: 104px;
right: 10px;
width: 176px;
padding: 12px;
}
#issue {
left: 10px;
bottom: 148px;
max-width: calc(100% - 20px);
}
#controls {
left: 10px;
right: 10px;
bottom: 10px;
transform: none;
width: auto;
}
#cameraHelp { display: none; }
}
</style>
</head>
<body>
<div id="title" class="panel">
<div class="eyebrow">Live production floor</div>
<h1>BLOCK PARTY<br>TOY FACTORY</h1>
<p>Two busy molding machines, one clever sorter, and a route that definitely needs attention.</p>
</div>
<div id="stats" class="panel">
<div class="stat-row">
<span class="stat-label">Waiting on floor</span>
<span class="stat-value" id="queueCount">0</span>
</div>
<div class="meter"><div id="meterTotal"></div></div>
<div class="stat-row">
<span class="stat-label">Output A</span>
<span class="stat-value" id="countA">0</span>
</div>
<div class="meter"><div id="meterA"></div></div>
<div class="stat-row">
<span class="stat-label">Output B</span>
<span class="stat-value" id="countB">0</span>
</div>
<div class="meter"><div id="meterB"></div></div>
</div>
<div id="issue" class="panel">Checking the production line…</div>
<div id="controls" class="panel">
<div class="control-group">
<div class="group-label">Machines</div>
<div class="button-row">
<button id="machineA" class="on">Machine A</button>
<button id="machineB" class="on">Machine B</button>
</div>
</div>
<div class="control-group">
<div class="group-label">Sorter</div>
<div class="button-row">
<button id="sorterAuto" class="on">Auto</button>
<button id="sorterA">A</button>
<button id="sorterB">B</button>
</div>
</div>
<div class="control-group">
<div class="group-label">Route B</div>
<div class="button-row">
<button id="routeB">Disconnected</button>
</div>
</div>
<div class="control-group">
<div class="group-label">Output gates</div>
<div class="button-row">
<button id="gateA" class="danger">Gate A closed</button>
<button id="gateB">Gate B open</button>
</div>
</div>
<div class="control-group">
<div class="group-label">Factory</div>
<div class="button-row">
<button id="pause">Pause</button>
<button id="reset">Reset</button>
</div>
</div>
</div>
<div id="cameraHelp" class="panel">Drag to orbit · Scroll to zoom · Click a machine</div>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
/* -------------------------------------------------------------------------- */
/* Scene setup */
/* -------------------------------------------------------------------------- */
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce8ed);
scene.fog = new THREE.Fog(0xdce8ed, 27, 48);
const camera = new THREE.PerspectiveCamera(38, innerWidth / innerHeight, 0.1, 100);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
document.body.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xeaf8ff, 0x9a8067, 2.25);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff0cf, 3.2);
sun.position.set(-8, 17, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -18;
sun.shadow.camera.right = 18;
sun.shadow.camera.top = 15;
sun.shadow.camera.bottom = -15;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 40;
sun.shadow.bias = -0.00025;
scene.add(sun);
const rim = new THREE.DirectionalLight(0xa8cfff, 1.1);
rim.position.set(12, 8, -12);
scene.add(rim);
function material(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.72,
metalness: 0.02,
...options
});
}
const palette = {
cream: material(0xf2eadb),
edge: material(0xcbbba3),
dark: material(0x27313a),
belt: material(0x34404a),
beltEdge: material(0x1f2930),
orange: material(0xf36b3d),
yellow: material(0xf4c44e),
blue: material(0x3987d5),
green: material(0x48a66b),
red: material(0xd94841),
white: material(0xfffdf5),
black: material(0x17202a),
wood: material(0xb9895f),
woodDark: material(0x8d6748),
glass: material(0x8ac9dd, { roughness: 0.28, metalness: 0.05 })
};
function box(parent, size, pos, mat, shadow = true) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(...size), mat);
mesh.position.set(...pos);
mesh.castShadow = shadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeLabel(text, background = "#17202a", foreground = "#ffffff", width = 2.5) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.fillStyle = background;
ctx.beginPath();
ctx.roundRect(5, 5, 502, 118, 25);
ctx.fill();
ctx.strokeStyle = "rgba(255,255,255,.25)";
ctx.lineWidth = 5;
ctx.stroke();
ctx.fillStyle = foreground;
ctx.font = "900 47px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 256, 66);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
}));
sprite.scale.set(width, width / 4, 1);
return sprite;
}
/* -------------------------------------------------------------------------- */
/* Floor and building */
/* -------------------------------------------------------------------------- */
const floorCanvas = document.createElement("canvas");
floorCanvas.width = 512;
floorCanvas.height = 512;
const floorCtx = floorCanvas.getContext("2d");
floorCtx.fillStyle = "#e8dfcf";
floorCtx.fillRect(0, 0, 512, 512);
floorCtx.strokeStyle = "rgba(100,86,68,.13)";
floorCtx.lineWidth = 2;
for (let i = 0; i <= 512; i += 64) {
floorCtx.beginPath();
floorCtx.moveTo(i, 0);
floorCtx.lineTo(i, 512);
floorCtx.stroke();
floorCtx.beginPath();
floorCtx.moveTo(0, i);
floorCtx.lineTo(512, i);
floorCtx.stroke();
}
const floorTexture = new THREE.CanvasTexture(floorCanvas);
floorTexture.colorSpace = THREE.SRGBColorSpace;
floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;
floorTexture.repeat.set(6, 4);
const floorMat = material(0xffffff, { map: floorTexture });
box(scene, [23.5, 0.42, 15.5], [0, -0.25, 0], palette.edge);
box(scene, [23.1, 0.18, 15.1], [0, -0.02, 0], floorMat);
box(scene, [23.2, 3.7, 0.32], [0, 1.75, -7.55], palette.cream);
box(scene, [0.32, 3.7, 15.2], [-11.55, 1.75, 0], palette.cream);
box(scene, [23.5, 0.24, 0.5], [0, 3.72, -7.55], palette.orange);
box(scene, [0.5, 0.24, 15.4], [-11.55, 3.72, 0], palette.blue);
for (let x = -9; x <= 9; x += 3) {
box(scene, [2.15, 1.45, 0.08], [x, 2.05, -7.34], palette.glass, false);
box(scene, [0.09, 1.55, 0.12], [x, 2.05, -7.25], palette.white);
}
for (let z = -5; z <= 5; z += 2.5) {
box(scene, [0.08, 1.35, 2.0], [-11.34, 2.05, z], palette.glass, false);
}
for (let x = -9.5; x <= 9.5; x += 1) {
box(scene, [0.22, 0.12, 0.22], [x, 0.13, -7.05], palette.woodDark);
}
// Decorative crates and storage
function makeCrate(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.scale.setScalar(scale);
box(group, [1.15, 0.85, 1.05], [0, 0.43, 0], palette.wood);
box(group, [1.22, 0.10, 0.12], [0, 0.58, 0.56], palette.woodDark);
box(group, [0.12, 0.10, 1.12], [0.42, 0.58, 0], palette.woodDark);
box(group, [0.12, 0.10, 1.12], [-0.42, 0.58, 0], palette.woodDark);
scene.add(group);
}
makeCrate(-9.5, -5.9, 1.1);
makeCrate(-8.1, -6.1, 0.82);
makeCrate(-9.2, -4.8, 0.68);
makeCrate(9.9, -5.9, 0.9);
/* -------------------------------------------------------------------------- */
/* Belts and paths */
/* -------------------------------------------------------------------------- */
const lanes = {};
const conveyorVisuals = [];
function prepareLane(id, path, speed = 1.28, color = 0x65717a) {
const segments = [];
let total = 0;
for (let i = 0; i < path.length - 1; i++) {
const a = path[i];
const b = path[i + 1];
const dx = b[0] - a[0];
const dz = b[1] - a[1];
const length = Math.hypot(dx, dz);
segments.push({ a, b, dx, dz, length, start: total });
total += length;
}
lanes[id] = {
id,
path,
segments,
total,
speed,
items: [],
color
};
}
prepareLane("feedA", [[-6.7, -3.5], [-4.1, -3.5], [-4.1, 0], [-1, 0]], 1.22, 0x65717a);
prepareLane("feedB", [[-6.7, 3.5], [-4.1, 3.5], [-4.1, 0], [-1, 0]], 1.30, 0x65717a);
prepareLane("sort", [[-1, 0], [3, 0]], 1.18, 0xb68a36);
prepareLane("outA", [[3, 0], [5.1, 0], [5.1, -3.5], [8.25, -3.5]], 1.34, 0x4b9665);
prepareLane("outB", [[3, 0], [5.1, 0], [5.1, 3.5], [8.25, 3.5]], 1.40, 0x4b78a8);
function createConveyor(lane) {
lane.segmentGroups = [];
lane.segments.forEach((segment, segmentIndex) => {
const group = new THREE.Group();
const angle = -Math.atan2(segment.dz, segment.dx);
group.position.set(
(segment.a[0] + segment.b[0]) / 2,
0,
(segment.a[1] + segment.b[1]) / 2
);
group.rotation.y = angle;
const base = box(group, [segment.length, 0.18, 1.18], [0, 0.34, 0], palette.belt);
base.receiveShadow = true;
box(group, [segment.length, 0.18, 0.10], [0, 0.49, -0.57], palette.beltEdge);
box(group, [segment.length, 0.18, 0.10], [0, 0.49, 0.57], palette.beltEdge);
const slatMat = material(lane.color, { roughness: 0.9 });
const slatCount = Math.max(2, Math.floor(segment.length / 0.48));
const slats = [];
for (let i = 0; i < slatCount; i++) {
const slat = box(group, [0.075, 0.025, 0.93], [-segment.length / 2, 0.45, 0], slatMat, false);
slat.userData.base = i * segment.length / slatCount;
slats.push(slat);
}
const legCount = Math.max(1, Math.floor(segment.length / 2.3));
for (let i = 0; i < legCount; i++) {
const x = -segment.length / 2 + (i + 0.5) * segment.length / legCount;
box(group, [0.15, 0.28, 0.15], [x, 0.14, -0.42], palette.dark);
box(group, [0.15, 0.28, 0.15], [x, 0.14, 0.42], palette.dark);
}
scene.add(group);
lane.segmentGroups.push(group);
conveyorVisuals.push({ group, segment, slats, lane, segmentIndex });
});
}
Object.values(lanes).forEach(createConveyor);
function sampleLane(lane, distance) {
const s = THREE.MathUtils.clamp(distance, 0, lane.total);
for (const segment of lane.segments) {
if (s <= segment.start + segment.length) {
const local = s - segment.start;
const t = local / segment.length;
return {
x: segment.a[0] + segment.dx * t,
z: segment.a[1] + segment.dz * t,
angle: -Math.atan2(segment.dz, segment.dx)
};
}
}
const last = lane.segments[lane.segments.length - 1];
return {
x: last.b[0],
z: last.b[1],
angle: -Math.atan2(last.dz, last.dx)
};
}
/* -------------------------------------------------------------------------- */
/* Machines, sorter, gates and bins */
/* -------------------------------------------------------------------------- */
const pickables = [];
function registerPick(group, action) {
group.userData.action = action;
group.traverse(child => {
if (child.isMesh) {
child.userData.action = action;
pickables.push(child);
}
});
}
function makeMachine(x, z, bodyMat, name, action) {
const group = new THREE.Group();
group.position.set(x, 0, z);
box(group, [2.05, 0.28, 1.95], [0, 0.18, 0], palette.dark);
box(group, [1.72, 1.42, 1.60], [-0.10, 1.02, 0], bodyMat);
box(group, [1.84, 0.18, 1.72], [-0.10, 1.82, 0], palette.white);
box(group, [0.78, 0.48, 0.07], [-0.22, 1.13, 0.83], palette.glass, false);
box(group, [0.62, 0.15, 0.58], [0.83, 0.76, 0], palette.dark);
for (const sx of [-0.68, 0.48]) {
for (const sz of [-0.52, 0.52]) {
box(group, [0.25, 0.13, 0.25], [sx, 1.96, sz], bodyMat);
}
}
const lampMat = material(0x71e38b, { emissive: 0x2c9c49, emissiveIntensity: 1.4 });
const lamp = box(group, [0.22, 0.22, 0.22], [0.30, 2.10, 0.55], lampMat, false);
const label = makeLabel(name, "#26323b", "#ffffff", 2.6);
label.position.set(-0.10, 2.75, 0);
group.add(label);
scene.add(group);
registerPick(group, action);
return { group, lamp, lampMat };
}
const machineAVisual = makeMachine(-8.25, -3.5, palette.orange, "MACHINE A", "machineA");
const machineBVisual = makeMachine(-8.25, 3.5, palette.blue, "MACHINE B", "machineB");
const sorterGroup = new THREE.Group();
sorterGroup.position.set(0.1, 0, 0);
box(sorterGroup, [0.28, 2.15, 0.28], [0, 1.15, -0.78], palette.dark);
box(sorterGroup, [0.28, 2.15, 0.28], [0, 1.15, 0.78], palette.dark);
box(sorterGroup, [0.75, 0.35, 1.85], [0, 2.18, 0], palette.yellow);
box(sorterGroup, [0.38, 0.22, 0.42], [0, 2.48, 0], palette.dark);
const sorterLightMat = material(0xf4c44e, { emissive: 0xf4c44e, emissiveIntensity: 1.8 });
const sorterLight = box(sorterGroup, [0.42, 0.12, 0.42], [0, 2.62, 0], sorterLightMat, false);
const sorterLabel = makeLabel("SORTER", "#f4c44e", "#17202a", 2.1);
sorterLabel.position.set(0, 3.05, 0);
sorterGroup.add(sorterLabel);
scene.add(sorterGroup);
registerPick(sorterGroup, "sorter");
function makeGate(lane, z, labelText) {
const group = new THREE.Group();
group.position.set(8.0, 0, z);
box(group, [0.18, 1.55, 0.18], [0, 0.78, -0.68], palette.dark);
box(group, [0.18, 1.55, 0.18], [0, 0.78, 0.68], palette.dark);
const bar = new THREE.Group();
box(bar, [0.18, 0.24, 1.42], [0, 1.08, 0], palette.red);
for (let i = -2; i <= 2; i++) {
box(bar, [0.195, 0.26, 0.12], [0, 1.08, i * 0.25], palette.yellow);
}
group.add(bar);
const lampMat = material(0x65dd85, { emissive: 0x2baf54, emissiveIntensity: 1.5 });
const lamp = box(group, [0.28, 0.28, 0.28], [0, 1.74, 0], lampMat, false);
const label = makeLabel(labelText, "#d94841", "#ffffff", 1.7);
label.position.set(0, 2.18, 0);
group.add(label);
scene.add(group);
return { group, bar, lamp, lampMat };
}
const gateAVisual = makeGate(lanes.outA, -3.5, "GATE A");
const gateBVisual = makeGate(lanes.outB, 3.5, "GATE B");
function makeBin(x, z, bodyMat, name) {
const group = new THREE.Group();
group.position.set(x, 0, z);
box(group, [1.65, 0.18, 1.70], [0, 0.10, 0], palette.dark);
box(group, [0.18, 1.15, 1.72], [-0.78, 0.68, 0], bodyMat);
box(group, [0.18, 1.15, 1.72], [0.78, 0.68, 0], bodyMat);
box(group, [1.60, 1.15, 0.18], [0, 0.68, -0.78], bodyMat);
box(group, [1.60, 0.58, 0.18], [0, 0.39, 0.78], bodyMat);
const label = makeLabel(name, "#26323b", "#ffffff", 1.9);
label.position.set(0, 1.75, 0);
group.add(label);
scene.add(group);
return group;
}
const binA = makeBin(9.35, -3.5, palette.green, "OUTPUT A");
const binB = makeBin(9.35, 3.5, palette.blue, "OUTPUT B");
// Visible missing bridge on route B.
const hazardGroup = new THREE.Group();
hazardGroup.position.set(5.1, 0, 1.75);
for (let i = 0; i < 6; i++) {
const stripe = box(hazardGroup, [0.22, 0.06, 0.34], [0, 0.08, -1.25 + i * 0.5], palette.red, false);
stripe.rotation.y = Math.PI / 4;
}
const warning = makeLabel("ROUTE OFF", "#d94841", "#ffffff", 2.0);
warning.position.set(0, 1.5, 0);
hazardGroup.add(warning);
scene.add(hazardGroup);
/* -------------------------------------------------------------------------- */
/* Toy geometry and simulation */
/* -------------------------------------------------------------------------- */
const toyGeo = {
body: new THREE.BoxGeometry(0.46, 0.34, 0.38),
head: new THREE.BoxGeometry(0.34, 0.28, 0.32),
eye: new THREE.BoxGeometry(0.035, 0.075, 0.075),
foot: new THREE.BoxGeometry(0.16, 0.12, 0.19)
};
const toyColors = [0xf36b3d, 0x3987d5, 0xf4c44e, 0x48a66b, 0x9a70c6];
const toyMaterialCache = new Map();
function toyMaterial(color) {
if (!toyMaterialCache.has(color)) {
toyMaterialCache.set(color, material(color));
}
return toyMaterialCache.get(color);
}
function makeToy(target = null) {
const group = new THREE.Group();
const color = target === "A" ? 0x48a66b : target === "B" ? 0x3987d5 : toyColors[Math.floor(Math.random() * toyColors.length)];
const body = new THREE.Mesh(toyGeo.body, toyMaterial(color));
body.position.y = 0.23;
body.castShadow = true;
group.add(body);
const head = new THREE.Mesh(toyGeo.head, toyMaterial(0xf6d6a4));
head.position.set(0.02, 0.52, 0);
head.castShadow = true;
group.add(head);
for (const z of [-0.085, 0.085]) {
const eye = new THREE.Mesh(toyGeo.eye, palette.black);
eye.position.set(0.205, 0.54, z);
group.add(eye);
}
for (const z of [-0.12, 0.12]) {
const foot = new THREE.Mesh(toyGeo.foot, palette.dark);
foot.position.set(0.02, 0.06, z);
foot.castShadow = true;
group.add(foot);
}
return group;
}
const state = {
machineA: true,
machineB: true,
sorterMode: "auto",
connectedB: false,
gateAClosed: true,
gateBClosed: false,
paused: false,
autoNext: "A",
deliveredA: 0,
deliveredB: 0,
timerA: 0.4,
timerB: 0.8
};
const SPACING = 1.04;
let itemSerial = 0;
function spawnToy(laneId) {
const lane = lanes[laneId];
if (lane.items.some(item => item.s < SPACING)) return false;
const mesh = makeToy();
scene.add(mesh);
const item = {
id: ++itemSerial,
mesh,
laneId,
s: 0,
target: null,
phase: Math.random() * Math.PI * 2
};
lane.items.push(item);
updateToyTransform(item);
return true;
}
function updateToyTransform(item) {
const lane = lanes[item.laneId];
const p = sampleLane(lane, item.s);
item.mesh.position.set(p.x, 0.61, p.z);
item.mesh.rotation.y = p.angle;
}
function canAccept(lane) {
if (!lane.items.length) return true;
const first = lane.items.reduce((a, b) => a.s < b.s ? a : b);
return first.s >= SPACING;
}
function assignTarget() {
if (state.sorterMode === "A") return "A";
if (state.sorterMode === "B") return "B";
const target = state.autoNext;
state.autoNext = target === "A" ? "B" : "A";
return target;
}
function moveLane(lane, dt, frontLimit) {
const ordered = [...lane.items].sort((a, b) => b.s - a.s);
let ahead = null;
for (const item of ordered) {
const limit = ahead ? ahead.s - SPACING : frontLimit;
item.s = Math.min(item.s + lane.speed * dt, Math.max(0, limit));
ahead = item;
}
}
function removeItem(lane, item) {
const index = lane.items.indexOf(item);
if (index !== -1) lane.items.splice(index, 1);
}
function deliverToy(item, output) {
scene.remove(item.mesh);
state.deliveredA += output === "A" ? 1 : 0;
state.deliveredB += output === "B" ? 1 : 0;
const bin = output === "A" ? binA : binB;
const stack = output === "A" ? state.deliveredA : state.deliveredB;
if (stack <= 12) {
const cube = box(
bin,
[0.43, 0.43, 0.43],
[
-0.42 + (stack % 3) * 0.42,
0.42 + Math.floor((stack - 1) / 3) * 0.43,
-0.32 + Math.floor((stack - 1) % 3) * 0.32
],
toyMaterial(output === "A" ? 0x48a66b : 0x3987d5)
);
cube.rotation.y = (stack * 0.37) % Math.PI;
}
}
function updateOutput(lane, blocked, output, dt) {
moveLane(lane, dt, blocked ? lane.total - 0.74 : lane.total);
if (!blocked && lane.items.length) {
const front = lane.items.reduce((a, b) => a.s > b.s ? a : b);
if (front.s >= lane.total - 0.001) {
removeItem(lane, front);
deliverToy(front, output);
}
}
}
function updateSorter(dt) {
const lane = lanes.sort;
const front = lane.items.length
? lane.items.reduce((a, b) => a.s > b.s ? a : b)
: null;
let exitAllowed = false;
let targetLane = null;
if (front) {
targetLane = front.target === "B" ? lanes.outB : lanes.outA;
const routeConnected = front.target !== "B" || state.connectedB;
exitAllowed = routeConnected && canAccept(targetLane);
}
moveLane(lane, dt, exitAllowed ? lane.total : lane.total - 0.76);
if (front && exitAllowed && front.s >= lane.total - 0.001) {
removeItem(lane, front);
front.laneId = targetLane.id;
front.s = 0;
targetLane.items.push(front);
updateToyTransform(front);
}
}
function updateFeed(lane, dt) {
const exitAllowed = canAccept(lanes.sort);
moveLane(lane, dt, exitAllowed ? lane.total : lane.total - 0.74);
const front = lane.items.length
? lane.items.reduce((a, b) => a.s > b.s ? a : b)
: null;
if (front && exitAllowed && front.s >= lane.total - 0.001) {
removeItem(lane, front);
front.laneId = "sort";
front.s = 0;
front.target = assignTarget();
lanes.sort.items.push(front);
updateToyTransform(front);
}
}
function updateSimulation(dt) {
if (state.paused) return;
state.timerA -= dt;
state.timerB -= dt;
if (state.timerA <= 0) {
if (state.machineA) spawnToy("feedA");
state.timerA = 1.42;
}
if (state.timerB <= 0) {
if (state.machineB) spawnToy("feedB");
state.timerB = 1.64;
}
// Downstream first so that space opens before upstream items move.
updateOutput(lanes.outA, state.gateAClosed, "A", dt);
updateOutput(lanes.outB, state.gateBClosed, "B", dt);
updateSorter(dt);
updateFeed(lanes.feedA, dt);
updateFeed(lanes.feedB, dt);
for (const lane of Object.values(lanes)) {
for (const item of lane.items) {
updateToyTransform(item);
item.mesh.position.y += Math.sin(performance.now() * 0.006 + item.phase) * 0.018;
}
}
}
/* -------------------------------------------------------------------------- */
/* Controls */
/* -------------------------------------------------------------------------- */
const ui = {
machineA: document.querySelector("#machineA"),
machineB: document.querySelector("#machineB"),
sorterAuto: document.querySelector("#sorterAuto"),
sorterA: document.querySelector("#sorterA"),
sorterB: document.querySelector("#sorterB"),
routeB: document.querySelector("#routeB"),
gateA: document.querySelector("#gateA"),
gateB: document.querySelector("#gateB"),
pause: document.querySelector("#pause"),
reset: document.querySelector("#reset")
};
function setToggle(button, on) {
button.classList.toggle("on", on);
}
function refreshControls() {
setToggle(ui.machineA, state.machineA);
setToggle(ui.machineB, state.machineB);
setToggle(ui.sorterAuto, state.sorterMode === "auto");
setToggle(ui.sorterA, state.sorterMode === "A");
setToggle(ui.sorterB, state.sorterMode === "B");
setToggle(ui.routeB, state.connectedB);
ui.routeB.textContent = state.connectedB ? "Connected" : "Disconnected";
setToggle(ui.gateA, state.gateAClosed);
ui.gateA.textContent = state.gateAClosed ? "Gate A closed" : "Gate A open";
setToggle(ui.gateB, state.gateBClosed);
ui.gateB.textContent = state.gateBClosed ? "Gate B closed" : "Gate B open";
ui.pause.classList.toggle("on", state.paused);
ui.pause.textContent = state.paused ? "Resume" : "Pause";
lanes.outB.segmentGroups[1].visible = state.connectedB;
hazardGroup.visible = !state.connectedB;
gateAVisual.bar.visible = state.gateAClosed;
gateBVisual.bar.visible = state.gateBClosed;
gateAVisual.lampMat.color.set(state.gateAClosed ? 0xff5b4f : 0x65dd85);
gateAVisual.lampMat.emissive.set(state.gateAClosed ? 0xd83c31 : 0x2baf54);
gateBVisual.lampMat.color.set(state.gateBClosed ? 0xff5b4f : 0x65dd85);
gateBVisual.lampMat.emissive.set(state.gateBClosed ? 0xd83c31 : 0x2baf54);
}
ui.machineA.addEventListener("click", () => {
state.machineA = !state.machineA;
refreshControls();
});
ui.machineB.addEventListener("click", () => {
state.machineB = !state.machineB;
refreshControls();
});
ui.sorterAuto.addEventListener("click", () => {
state.sorterMode = "auto";
state.autoNext = "A";
refreshControls();
});
ui.sorterA.addEventListener("click", () => {
state.sorterMode = "A";
refreshControls();
});
ui.sorterB.addEventListener("click", () => {
state.sorterMode = "B";
refreshControls();
});
ui.routeB.addEventListener("click", () => {
state.connectedB = !state.connectedB;
refreshControls();
});
ui.gateA.addEventListener("click", () => {
state.gateAClosed = !state.gateAClosed;
refreshControls();
});
ui.gateB.addEventListener("click", () => {
state.gateBClosed = !state.gateBClosed;
refreshControls();
});
ui.pause.addEventListener("click", () => {
state.paused = !state.paused;
refreshControls();
});
ui.reset.addEventListener("click", resetFactory);
function resetFactory() {
for (const lane of Object.values(lanes)) {
for (const item of lane.items) scene.remove(item.mesh);
lane.items.length = 0;
}
for (const bin of [binA, binB]) {
[...bin.children].forEach(child => {
if (child.isMesh && child.geometry.type === "BoxGeometry" && child.geometry.parameters.width === 0.43) {
bin.remove(child);
}
});
}
state.machineA = true;
state.machineB = true;
state.sorterMode = "auto";
state.connectedB = false;
state.gateAClosed = true;
state.gateBClosed = false;
state.paused = false;
state.autoNext = "A";
state.deliveredA = 0;
state.deliveredB = 0;
state.timerA = 0.25;
state.timerB = 0.65;
refreshControls();
}
refreshControls();
/* -------------------------------------------------------------------------- */
/* Custom camera controls */
/* -------------------------------------------------------------------------- */
const orbit = {
yaw: 0.70,
pitch: 0.61,
radius: 25,
targetYaw: 0.70,
targetPitch: 0.61,
targetRadius: 25,
target: new THREE.Vector3(-0.4, 0.5, 0)
};
let dragging = false;
let pointerX = 0;
let pointerY = 0;
let pointerMoved = 0;
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
pointerMoved = 0;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
pointerMoved += Math.abs(dx) + Math.abs(dy);
orbit.targetYaw -= dx * 0.006;
orbit.targetPitch = THREE.MathUtils.clamp(orbit.targetPitch + dy * 0.0045, 0.25, 1.22);
});
renderer.domElement.addEventListener("pointerup", event => {
dragging = false;
if (pointerMoved < 6) {
const rect = renderer.domElement.getBoundingClientRect();
const pointer = new THREE.Vector2(
((event.clientX - rect.left) / rect.width) * 2 - 1,
-((event.clientY - rect.top) / rect.height) * 2 + 1
);
const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(pickables, false);
if (hits.length) {
const action = hits[0].object.userData.action;
if (action === "machineA") ui.machineA.click();
if (action === "machineB") ui.machineB.click();
if (action === "sorter") ui.sorterAuto.click();
}
}
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
orbit.targetRadius = THREE.MathUtils.clamp(
orbit.targetRadius + event.deltaY * 0.018,
13,
36
);
}, { passive: false });
function updateCamera(dt) {
const smoothing = 1 - Math.exp(-dt * 10);
orbit.yaw = THREE.MathUtils.lerp(orbit.yaw, orbit.targetYaw, smoothing);
orbit.pitch = THREE.MathUtils.lerp(orbit.pitch, orbit.targetPitch, smoothing);
orbit.radius = THREE.MathUtils.lerp(orbit.radius, orbit.targetRadius, smoothing);
const horizontal = Math.cos(orbit.pitch) * orbit.radius;
camera.position.set(
orbit.target.x + Math.sin(orbit.yaw) * horizontal,
orbit.target.y + Math.sin(orbit.pitch) * orbit.radius,
orbit.target.z + Math.cos(orbit.yaw) * horizontal
);
camera.lookAt(orbit.target);
}
/* -------------------------------------------------------------------------- */
/* Status readouts */
/* -------------------------------------------------------------------------- */
const status = {
queue: document.querySelector("#queueCount"),
countA: document.querySelector("#countA"),
countB: document.querySelector("#countB"),
meterTotal: document.querySelector("#meterTotal"),
meterA: document.querySelector("#meterA"),
meterB: document.querySelector("#meterB"),
issue: document.querySelector("#issue")
};
let statusTimer = 0;
function updateStatus() {
const queue = Object.values(lanes).reduce((sum, lane) => sum + lane.items.length, 0);
status.queue.textContent = queue;
status.countA.textContent = state.deliveredA;
status.countB.textContent = state.deliveredB;
status.meterTotal.style.width = `${Math.min(100, queue / 24 * 100)}%`;
status.meterA.style.width = `${Math.min(100, lanes.outA.items.length / 8 * 100)}%`;
status.meterB.style.width = `${Math.min(100, lanes.outB.items.length / 8 * 100)}%`;
const issues = [];
if (!state.connectedB) issues.push("Route B disconnected");
if (state.gateAClosed) issues.push("Gate A blocked");
if (state.gateBClosed) issues.push("Gate B blocked");
if (issues.length) {
status.issue.textContent = `⚠ ${issues.join(" · ")} — toys are backing up`;
status.issue.style.background = "rgba(255, 229, 222, .95)";
status.issue.style.color = "#9e312b";
} else {
status.issue.textContent = "✓ All routes connected — production line is flowing";
status.issue.style.background = "rgba(225, 246, 229, .95)";
status.issue.style.color = "#2d7b49";
}
}
/* -------------------------------------------------------------------------- */
/* Animation loop */
/* -------------------------------------------------------------------------- */
const clock = new THREE.Clock();
let beltTime = 0;
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
beltTime += dt;
updateCamera(dt);
updateSimulation(dt);
for (const visual of conveyorVisuals) {
if (!visual.group.visible) continue;
const speed = visual.lane.speed;
for (const slat of visual.slats) {
const length = visual.segment.length;
const offset = (slat.userData.base + beltTime * speed) % length;
slat.position.x = -length / 2 + offset;
}
}
machineAVisual.lampMat.emissiveIntensity = state.machineA ? 1.2 + Math.sin(beltTime * 5) * 0.35 : 0.05;
machineBVisual.lampMat.emissiveIntensity = state.machineB ? 1.2 + Math.sin(beltTime * 5 + 2) * 0.35 : 0.05;
sorterLightMat.color.set(
state.sorterMode === "A" ? 0x48a66b :
state.sorterMode === "B" ? 0x3987d5 :
0xf4c44e
);
sorterLightMat.emissive.copy(sorterLightMat.color);
sorterLightMat.emissiveIntensity = 1.5 + Math.sin(beltTime * 7) * 0.5;
if (!state.connectedB) {
warning.position.y = 1.5 + Math.sin(beltTime * 3) * 0.08;
}
statusTimer -= dt;
if (statusTimer <= 0) {
updateStatus();
statusTimer = 0.12;
}
renderer.render(scene, camera);
}
addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
updateCamera(1);
updateStatus();
animate();
</script>
</body>
</html>
```