Prompt specification
Build or customize the Three.js 3D scene "Deadlock in a Circular Conveyor" 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: Deadlock in a Circular Conveyor
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/deadlock-in-a-circular-conveyor-x3528
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows conveyor routing, sorting, and deadlocks. Create a small logistics puzzle where a full cycle prevents progress. Let users add a buffer or reroute items and demonstrate why the revised layout clears the blockage. Voxel style.
Working Three.js Starter (deadlock-in-a-circular-conveyor-x3528):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Deadlock Depot — Voxel Logistics Puzzle</title>
<style>
:root {
--ink: #122033;
--muted: #667085;
--paper: #f4f0e6;
--panel: #101a2b;
--panel-2: #17243a;
--line: rgba(255, 255, 255, 0.12);
--cyan: #4ed9c4;
--yellow: #ffd166;
--red: #ff6b6b;
--green: #72e2a1;
--blue: #66b7ff;
--purple: #b99aff;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e9e4d8;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input { font: inherit; }
#viewport {
position: fixed;
inset: 0 370px 0 0;
overflow: hidden;
background:
radial-gradient(circle at 48% 42%, #f7f3e9 0, #e7e1d4 72%);
}
canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
}
.brand {
position: fixed;
z-index: 5;
top: 18px;
left: 18px;
display: flex;
align-items: center;
gap: 12px;
pointer-events: none;
}
.brand-icon {
width: 44px;
height: 44px;
display: grid;
place-items: center;
background: var(--ink);
color: var(--cyan);
border: 3px solid var(--ink);
box-shadow: 4px 4px 0 rgba(18, 32, 51, 0.18);
font: 900 22px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.brand h1 {
margin: 0;
font-size: 19px;
line-height: 1.05;
letter-spacing: -0.04em;
text-transform: uppercase;
}
.brand p {
margin: 5px 0 0;
color: #526071;
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.12em;
text-transform: uppercase;
}
#statusPill {
position: fixed;
z-index: 5;
top: 18px;
right: 388px;
min-width: 172px;
padding: 11px 14px;
display: flex;
align-items: center;
gap: 9px;
border: 2px solid var(--ink);
background: rgba(255, 255, 255, 0.86);
box-shadow: 4px 4px 0 rgba(18, 32, 51, 0.13);
font: 900 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.06em;
pointer-events: none;
}
#statusDot {
width: 10px;
height: 10px;
background: var(--yellow);
box-shadow: 0 0 0 3px rgba(255, 209, 102, 0.22);
}
#statusPill.deadlock #statusDot {
background: var(--red);
box-shadow: 0 0 0 3px rgba(255, 107, 107, 0.22);
animation: blink 0.85s steps(2) infinite;
}
#statusPill.clear #statusDot {
background: var(--green);
box-shadow: 0 0 0 3px rgba(114, 226, 161, 0.2);
}
@keyframes blink { 50% { opacity: 0.38; } }
#panel {
position: fixed;
z-index: 10;
top: 0;
right: 0;
bottom: 0;
width: 370px;
overflow-y: auto;
padding: 20px;
color: #f7f8fb;
background: var(--panel);
border-left: 4px solid #070d18;
scrollbar-width: thin;
scrollbar-color: #43516a transparent;
}
.eyebrow {
margin: 0 0 7px;
color: var(--cyan);
font: 800 10px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.15em;
text-transform: uppercase;
}
#panel h2 {
margin: 0;
font-size: 27px;
line-height: 1.02;
letter-spacing: -0.045em;
}
.intro {
margin: 12px 0 17px;
color: #b7c0cf;
font-size: 13px;
line-height: 1.55;
}
.mission {
padding: 13px;
background: #1a2940;
border: 1px solid rgba(255, 255, 255, 0.09);
border-left: 4px solid var(--yellow);
margin-bottom: 14px;
}
.mission strong {
display: block;
margin-bottom: 5px;
color: var(--yellow);
font: 800 11px/1.3 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.mission p {
margin: 0;
color: #c8d0dc;
font-size: 12px;
line-height: 1.5;
}
.section-title {
display: flex;
justify-content: space-between;
align-items: center;
margin: 17px 0 9px;
color: #aab4c5;
font: 800 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.section-title span:last-child {
color: #68758b;
font-size: 9px;
}
.cycle-box {
padding: 12px;
border: 1px solid rgba(255, 107, 107, 0.35);
background: rgba(255, 107, 107, 0.07);
}
#cycleFlow {
display: flex;
align-items: center;
justify-content: space-between;
gap: 4px;
margin-bottom: 10px;
}
.chain-node {
flex: 1;
min-width: 0;
padding: 8px 3px;
text-align: center;
color: white;
background: #25324a;
border: 1px solid #3b4960;
font: 900 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.chain-node.hot {
color: #2b1114;
background: var(--red);
border-color: var(--red);
}
.chain-arrow {
color: var(--red);
font-weight: 900;
}
#waitRows {
display: grid;
gap: 5px;
}
.wait-row {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 8px;
color: #bec8d7;
background: rgba(0, 0, 0, 0.14);
font: 700 10px/1.25 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.parcel-dot {
width: 9px;
height: 9px;
flex: 0 0 auto;
background: var(--dot, white);
box-shadow: 2px 2px 0 rgba(0, 0, 0, 0.22);
}
.button-stack {
display: grid;
gap: 9px;
margin-top: 11px;
}
.action {
width: 100%;
min-height: 47px;
padding: 11px 13px;
border: 0;
border-bottom: 4px solid rgba(0, 0, 0, 0.32);
color: var(--ink);
background: var(--cyan);
cursor: pointer;
text-align: left;
font: 900 11px/1.25 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.035em;
transition: transform 0.1s, filter 0.1s;
}
.action:hover:not(:disabled) {
filter: brightness(1.06);
transform: translateY(-1px);
}
.action:active:not(:disabled) {
transform: translateY(2px);
border-bottom-width: 2px;
}
.action.secondary {
color: white;
background: #26354d;
border-bottom-color: #0c1422;
}
.action.yellow {
background: var(--yellow);
}
.action:disabled {
cursor: not-allowed;
opacity: 0.36;
filter: grayscale(0.4);
}
.action small {
display: block;
margin-top: 4px;
opacity: 0.72;
font-size: 9px;
font-weight: 700;
letter-spacing: 0;
}
.selection-card {
display: flex;
align-items: center;
gap: 10px;
margin-top: 10px;
padding: 10px;
background: #0c1422;
border: 1px solid var(--line);
}
#selectionSwatch {
width: 17px;
height: 17px;
flex: 0 0 auto;
background: var(--red);
box-shadow: 3px 3px 0 rgba(0, 0, 0, 0.3);
}
#selectionName {
margin: 0;
font: 800 10px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace;
}
#selectionHint {
margin: 3px 0 0;
color: #7f8ca0;
font-size: 10px;
line-height: 1.35;
}
.proof {
margin-top: 14px;
padding: 13px;
background: #0b1423;
border: 1px solid var(--line);
}
#proofTitle {
margin: 0 0 7px;
color: var(--yellow);
font: 900 11px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#proofText {
margin: 0;
color: #b6c0cf;
font-size: 11.5px;
line-height: 1.55;
}
#proofSteps {
margin: 11px 0 0;
padding-left: 19px;
color: #bff5df;
font: 700 10px/1.75 ui-monospace, SFMono-Regular, Menlo, monospace;
}
#proofSteps[hidden] { display: none; }
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-top: 14px;
}
.stat {
padding: 9px 7px;
text-align: center;
background: #17243a;
border: 1px solid var(--line);
}
.stat b {
display: block;
color: white;
font: 900 18px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.stat span {
display: block;
margin-top: 5px;
color: #7f8da3;
font: 800 8px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.controls {
position: fixed;
z-index: 7;
left: 18px;
bottom: 18px;
display: flex;
align-items: center;
gap: 8px;
padding: 8px;
background: rgba(255, 255, 255, 0.9);
border: 2px solid var(--ink);
box-shadow: 4px 4px 0 rgba(18, 32, 51, 0.15);
backdrop-filter: blur(8px);
}
.small-button {
min-width: 74px;
height: 35px;
border: 0;
color: white;
background: var(--ink);
cursor: pointer;
font: 900 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
text-transform: uppercase;
}
.small-button:hover { background: #263750; }
.speed-wrap {
display: flex;
align-items: center;
gap: 8px;
height: 35px;
padding: 0 10px;
color: #455267;
font: 800 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
text-transform: uppercase;
}
input[type="range"] {
width: 80px;
accent-color: var(--ink);
}
.hint {
position: fixed;
z-index: 5;
left: 19px;
bottom: 73px;
padding: 7px 9px;
color: #5d6879;
background: rgba(255, 255, 255, 0.72);
font: 700 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
pointer-events: none;
}
#toast {
position: fixed;
z-index: 20;
left: 50%;
top: 84px;
max-width: 420px;
padding: 11px 15px;
color: white;
background: var(--ink);
border-left: 5px solid var(--cyan);
box-shadow: 5px 5px 0 rgba(18, 32, 51, 0.18);
transform: translate(-50%, -20px);
opacity: 0;
pointer-events: none;
transition: opacity 0.2s, transform 0.2s;
font: 800 11px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;
text-align: center;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 900px) {
#viewport {
inset: 0 0 45vh 0;
}
#panel {
top: auto;
left: 0;
width: 100%;
height: 45vh;
border-left: 0;
border-top: 4px solid #070d18;
padding: 15px;
}
#statusPill {
top: 70px;
right: 12px;
}
.brand { top: 12px; left: 12px; }
.brand h1 { font-size: 15px; }
.brand p { display: none; }
.brand-icon { width: 37px; height: 37px; font-size: 18px; }
.controls {
left: 10px;
bottom: calc(45vh + 10px);
}
.hint { display: none; }
#toast { top: 116px; width: calc(100% - 30px); }
}
</style>
</head>
<body>
<div id="viewport" aria-label="Interactive three-dimensional conveyor puzzle"></div>
<div class="brand">
<div class="brand-icon">DD</div>
<div>
<h1>Deadlock Depot</h1>
<p>Voxel routing puzzle</p>
</div>
</div>
<div id="statusPill" aria-live="polite">
<span id="statusDot"></span>
<span id="statusText">ROUTING</span>
</div>
<div class="hint">DRAG TO ORBIT · SCROLL TO ZOOM · CLICK A PARCEL</div>
<div class="controls">
<button id="runBtn" class="small-button">Pause</button>
<label class="speed-wrap">
Speed
<input id="speed" type="range" min="0.4" max="2" step="0.1" value="1">
</label>
</div>
<div id="toast" role="status"></div>
<aside id="panel">
<p class="eyebrow">Logistics exercise / 01</p>
<h2>Break the circular wait.</h2>
<p class="intro">
Four color-coded parcels have filled every sorting cell. Each cell is
holding one parcel while waiting for the next cell to become empty.
</p>
<div class="mission">
<strong>Your objective</strong>
<p>
Add a one-parcel bypass buffer and send Parcel P1 through it.
Preserve the rest of the sorting loop.
</p>
</div>
<div class="section-title">
<span>Wait-for graph</span>
<span>Live state</span>
</div>
<div class="cycle-box">
<div id="cycleFlow">
<span class="chain-node hot">A</span>
<span class="chain-arrow">→</span>
<span class="chain-node hot">B</span>
<span class="chain-arrow">→</span>
<span class="chain-node hot">C</span>
<span class="chain-arrow">→</span>
<span class="chain-node hot">D</span>
<span class="chain-arrow">→</span>
<span class="chain-node hot">A</span>
</div>
<div id="waitRows"></div>
</div>
<div class="section-title">
<span>Layout tools</span>
<span>Two actions</span>
</div>
<div class="button-stack">
<button id="bufferBtn" class="action">
+ ADD BYPASS BUFFER
<small>Creates one free staging position between Sort A and Sort B.</small>
</button>
<button id="rerouteBtn" class="action yellow" disabled>
REROUTE SELECTED PARCEL
<small>Send the parcel in Sort A into the new buffer.</small>
</button>
<button id="resetBtn" class="action secondary">
RESET PUZZLE
<small>Restore the original full cycle.</small>
</button>
</div>
<div class="selection-card">
<span id="selectionSwatch"></span>
<div>
<p id="selectionName">P1 · SORT A</p>
<p id="selectionHint">Selected parcel. Click another parcel to change.</p>
</div>
</div>
<div class="proof">
<h3 id="proofTitle">Why it is stuck</h3>
<p id="proofText">
A waits for B, B waits for C, C waits for D, and D waits for A.
Every destination is occupied, so no parcel can take the first step.
</p>
<ol id="proofSteps" hidden>
<li>P1 leaves A through the buffer.</li>
<li>P4 moves D → A, freeing D.</li>
<li>P3 moves C → D, freeing C.</li>
<li>P2 moves B → C, freeing B.</li>
<li>The wait-for chain unwinds in reverse.</li>
</ol>
</div>
<div class="stats">
<div class="stat"><b id="statBelts">4</b><span>Cells occupied</span></div>
<div class="stat"><b id="statWaiting">4</b><span>Parcels waiting</span></div>
<div class="stat"><b id="statMoves">0</b><span>Transfers</span></div>
</div>
</aside>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// DOM and constants
// -------------------------------------------------------------------------
const viewport = document.getElementById("viewport");
const statusPill = document.getElementById("statusPill");
const statusText = document.getElementById("statusText");
const waitRows = document.getElementById("waitRows");
const cycleFlow = document.getElementById("cycleFlow");
const selectionName = document.getElementById("selectionName");
const selectionHint = document.getElementById("selectionHint");
const selectionSwatch = document.getElementById("selectionSwatch");
const proofTitle = document.getElementById("proofTitle");
const proofText = document.getElementById("proofText");
const proofSteps = document.getElementById("proofSteps");
const bufferBtn = document.getElementById("bufferBtn");
const rerouteBtn = document.getElementById("rerouteBtn");
const resetBtn = document.getElementById("resetBtn");
const runBtn = document.getElementById("runBtn");
const speedInput = document.getElementById("speed");
const toast = document.getElementById("toast");
const COLORS = {
ink: 0x122033,
floor: 0xe7e1d4,
platform: 0xd8d0c0,
belt: 0x26374b,
beltSide: 0x172537,
roller: 0xc8d2d8,
cyan: 0x4ed9c4,
yellow: 0xffd166,
red: 0xff6b6b,
green: 0x72e2a1,
blue: 0x66b7ff,
purple: 0xb99aff,
parcel1: 0xff6b6b,
parcel2: 0x66b7ff,
parcel3: 0xffd166,
parcel4: 0xb99aff
};
const itemColors = [
COLORS.parcel1,
COLORS.parcel2,
COLORS.parcel3,
COLORS.parcel4
];
const hexCss = (hex) => `#${hex.toString(16).padStart(6, "0")}`;
// -------------------------------------------------------------------------
// Renderer, scene, lighting and direct camera controls
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(COLORS.floor);
scene.fog = new THREE.Fog(COLORS.floor, 24, 42);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
viewport.appendChild(renderer.domElement);
const camera = new THREE.OrthographicCamera(-10, 10, 10, -10, 0.1, 100);
const cameraTarget = new THREE.Vector3(-0.6, 0.3, 0);
const cameraState = {
azimuth: 0.72,
polar: 0.76,
radius: 19,
zoom: 1
};
function updateCamera() {
const s = Math.sin(cameraState.polar);
camera.position.set(
cameraTarget.x + cameraState.radius * s * Math.cos(cameraState.azimuth),
cameraTarget.y + cameraState.radius * Math.cos(cameraState.polar),
cameraTarget.z + cameraState.radius * s * Math.sin(cameraState.azimuth)
);
camera.lookAt(cameraTarget);
camera.zoom = cameraState.zoom;
camera.updateProjectionMatrix();
}
function resize() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
const aspect = width / height;
const viewHeight = 11.5;
camera.left = -viewHeight * aspect;
camera.right = viewHeight * aspect;
camera.top = viewHeight;
camera.bottom = -viewHeight;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
updateCamera();
}
window.addEventListener("resize", resize);
scene.add(new THREE.HemisphereLight(0xfff8e9, 0x607086, 2.1));
const sun = new THREE.DirectionalLight(0xfff1d6, 3.2);
sun.position.set(-7, 13, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -15;
sun.shadow.camera.right = 15;
sun.shadow.camera.top = 15;
sun.shadow.camera.bottom = -15;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 40;
sun.shadow.bias = -0.0005;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xaed8ff, 0.8);
fill.position.set(9, 6, -9);
scene.add(fill);
// -------------------------------------------------------------------------
// World and reusable voxel construction helpers
// -------------------------------------------------------------------------
const world = new THREE.Group();
scene.add(world);
function material(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: options.roughness ?? 0.84,
metalness: options.metalness ?? 0.03,
emissive: options.emissive ?? 0x000000,
emissiveIntensity: options.emissiveIntensity ?? 0,
transparent: options.transparent ?? false,
opacity: options.opacity ?? 1
});
}
const floorMaterial = material(COLORS.floor);
const platformMaterial = material(COLORS.platform);
const crateMaterial = material(0xb99068);
const crateTapeMaterial = material(0xe7d8b8);
const floor = new THREE.Mesh(
new THREE.BoxGeometry(23, 0.35, 18),
floorMaterial
);
floor.position.y = -0.46;
floor.receiveShadow = true;
world.add(floor);
const platform = new THREE.Mesh(
new THREE.BoxGeometry(17.7, 0.18, 13.3),
platformMaterial
);
platform.position.y = -0.2;
platform.receiveShadow = true;
world.add(platform);
// A pixel-like apron of raised square pads around the conveyor.
const padMaterials = [
material(0xded7c9),
material(0xe4ded1),
material(0xd7d0c2)
];
for (let x = -8; x <= 7; x += 1.25) {
for (let z = -6; z <= 6; z += 1.25) {
if (x > -7 && x < 5 && z > -5 && z < 5) continue;
const pad = new THREE.Mesh(
new THREE.BoxGeometry(1.02, 0.08, 1.02),
padMaterials[Math.abs(Math.round(x + z)) % padMaterials.length]
);
pad.position.set(x, -0.245, z);
pad.receiveShadow = true;
world.add(pad);
}
}
function addCrate(x, z, scale = 1, tint = 0xb99068) {
const group = new THREE.Group();
const body = new THREE.Mesh(
new THREE.BoxGeometry(1.15 * scale, 0.8 * scale, 1.15 * scale),
material(tint)
);
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const tape = new THREE.Mesh(
new THREE.BoxGeometry(0.19 * scale, 0.83 * scale, 1.17 * scale),
crateTapeMaterial
);
tape.castShadow = true;
group.add(tape);
group.position.set(x, 0.21 + 0.4 * scale, z);
world.add(group);
}
addCrate(-8.1, -5.4, 0.9);
addCrate(-6.9, -5.5, 0.72, 0x9b7658);
addCrate(7.9, 5.2, 0.95, 0xc59c6e);
addCrate(6.7, 5.5, 0.68, 0x9f7d61);
function makeLabel(text, accent = "#4ed9c4", scale = 2.25) {
const canvas = document.createElement("canvas");
canvas.width = 320;
canvas.height = 88;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#101a2b";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = accent;
ctx.fillRect(0, 0, 9, canvas.height);
ctx.strokeStyle = "rgba(255,255,255,.22)";
ctx.lineWidth = 3;
ctx.strokeRect(1.5, 1.5, canvas.width - 3, canvas.height - 3);
ctx.font = "900 34px ui-monospace, SFMono-Regular, Menlo, monospace";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#ffffff";
ctx.fillText(text, canvas.width / 2 + 4, canvas.height / 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(scale, scale * 0.275, 1);
sprite.renderOrder = 20;
return sprite;
}
// -------------------------------------------------------------------------
// Conveyor graph
//
// A: J0 -> J1
// B: J1 -> J2
// C: J2 -> J3
// D: J3 -> J0
//
// Buffer: J1 -> J2, physically bypassing the original B conveyor.
// -------------------------------------------------------------------------
const nodes = {
J0: new THREE.Vector3(-5.2, 0, -3.35),
J1: new THREE.Vector3(3.25, 0, -3.35),
J2: new THREE.Vector3(3.25, 0, 3.35),
J3: new THREE.Vector3(-5.2, 0, 3.35)
};
let pickables = [];
const packageMeshes = [];
const alertFrames = [];
const edgeDefs = {
A: {
id: "A",
name: "SORT A",
next: "B",
path: [nodes.J0.clone(), nodes.J1.clone()],
accent: COLORS.red
},
B: {
id: "B",
name: "SORT B",
next: "C",
path: [nodes.J1.clone(), nodes.J2.clone()],
accent: COLORS.blue
},
C: {
id: "C",
name: "SORT C",
next: "D",
path: [nodes.J2.clone(), nodes.J3.clone()],
accent: COLORS.yellow
},
D: {
id: "D",
name: "SORT D",
next: "A",
path: [nodes.J3.clone(), nodes.J0.clone()],
accent: COLORS.purple
}
};
const edgeState = {};
function pathMetrics(path) {
const cumulative = [0];
let total = 0;
for (let i = 1; i < path.length; i++) {
total += path[i].distanceTo(path[i - 1]);
cumulative.push(total);
}
return { cumulative, total };
}
function pointOnPath(path, cumulative, total, t) {
const distance = THREE.MathUtils.clamp(t, 0, 1) * total;
for (let i = 1; i < path.length; i++) {
if (distance <= cumulative[i]) {
const segmentLength = cumulative[i] - cumulative[i - 1];
const local = segmentLength === 0
? 0
: (distance - cumulative[i - 1]) / segmentLength;
return path[i - 1].clone().lerp(path[i], local);
}
}
return path[path.length - 1].clone();
}
function makeArrow() {
const group = new THREE.Group();
const arrowMaterial = new THREE.MeshStandardMaterial({
color: COLORS.yellow,
roughness: 0.6,
emissive: 0x5b4200,
emissiveIntensity: 0.18
});
const shaft = new THREE.Mesh(
new THREE.BoxGeometry(0.48, 0.055, 0.12),
arrowMaterial
);
shaft.position.x = -0.22;
group.add(shaft);
const diagonalA = new THREE.Mesh(
new THREE.BoxGeometry(0.43, 0.055, 0.12),
arrowMaterial
);
diagonalA.position.set(0.12, 0, 0.15);
diagonalA.rotation.y = Math.PI / 4;
group.add(diagonalA);
const diagonalB = diagonalA.clone();
diagonalB.position.z = -0.15;
diagonalB.rotation.y = -Math.PI / 4;
group.add(diagonalB);
return group;
}
function createBelt(edge, isBuffer = false) {
const group = new THREE.Group();
edge.group = group;
edge.pickMeshes = [];
edge.metrics = pathMetrics(edge.path);
const baseMaterial = material(
isBuffer ? 0x235b59 : COLORS.belt,
{ roughness: 0.9 }
);
const sideMaterial = material(
isBuffer ? 0x153e3d : COLORS.beltSide
);
const rollerMaterial = material(
isBuffer ? 0x77dfcf : COLORS.roller,
{ roughness: 0.72 }
);
const arrowMaterial = material(COLORS.yellow, {
emissive: 0x5b4200,
emissiveIntensity: 0.16
});
for (let i = 1; i < edge.path.length; i++) {
const from = edge.path[i - 1];
const to = edge.path[i];
const direction = to.clone().sub(from);
const length = direction.length();
const yaw = -Math.atan2(direction.z, direction.x);
const midpoint = from.clone().add(to).multiplyScalar(0.5);
const base = new THREE.Mesh(
new THREE.BoxGeometry(length + 0.12, 0.31, 1.55),
baseMaterial
);
base.position.set(midpoint.x, 0.34, midpoint.z);
base.rotation.y = yaw;
base.castShadow = true;
base.receiveShadow = true;
base.userData.edgeId = edge.id;
group.add(base);
edge.pickMeshes.push(base);
pickables.push(base);
for (const side of [-1, 1]) {
const rail = new THREE.Mesh(
new THREE.BoxGeometry(length + 0.08, 0.18, 0.13),
sideMaterial
);
rail.position.set(midpoint.x, 0.58, midpoint.z);
rail.rotation.y = yaw;
const offset = new THREE.Vector3(0, 0, side * 0.77);
offset.applyAxisAngle(new THREE.Vector3(0, 1, 0), yaw);
rail.position.add(offset);
rail.castShadow = true;
group.add(rail);
}
const rollerCount = Math.max(2, Math.floor(length / 0.48));
for (let r = 0; r <= rollerCount; r++) {
const t = r / rollerCount;
const point = from.clone().lerp(to, t);
const roller = new THREE.Mesh(
new THREE.BoxGeometry(0.13, 0.12, 1.19),
rollerMaterial
);
roller.position.set(point.x, 0.555, point.z);
roller.rotation.y = yaw;
roller.castShadow = true;
group.add(roller);
}
if (length > 2) {
for (const t of [0.28, 0.68]) {
const point = from.clone().lerp(to, t);
const arrow = new THREE.Group();
const shaft = new THREE.Mesh(
new THREE.BoxGeometry(0.4, 0.045, 0.1),
arrowMaterial
);
shaft.position.x = -0.16;
arrow.add(shaft);
const d1 = new THREE.Mesh(
new THREE.BoxGeometry(0.34, 0.045, 0.1),
arrowMaterial
);
d1.position.set(0.12, 0, 0.11);
d1.rotation.y = Math.PI / 4;
arrow.add(d1);
const d2 = d1.clone();
d2.position.z = -0.11;
d2.rotation.y = -Math.PI / 4;
arrow.add(d2);
arrow.position.set(point.x, 0.66, point.z);
arrow.rotation.y = yaw;
group.add(arrow);
}
}
}
world.add(group);
return edge;
}
for (const edge of Object.values(edgeDefs)) {
createBelt(edge);
edgeState[edge.id] = { occupant: null };
}
// -------------------------------------------------------------------------
// Sorting stations and alert frames
// -------------------------------------------------------------------------
function createStation(position, name, accent, labelPosition) {
const group = new THREE.Group();
group.position.copy(position);
const base = new THREE.Mesh(
new THREE.BoxGeometry(1.55, 0.36, 1.55),
material(0xb9b1a2)
);
base.position.y = 0.38;
base.castShadow = true;
base.receiveShadow = true;
group.add(base);
const column = new THREE.Mesh(
new THREE.BoxGeometry(0.65, 0.9, 0.65),
material(accent)
);
column.position.y = 0.98;
column.castShadow = true;
group.add(column);
const scanner = new THREE.Mesh(
new THREE.BoxGeometry(0.88, 0.24, 0.88),
material(0x1b2a3c)
);
scanner.position.y = 1.55;
scanner.castShadow = true;
group.add(scanner);
const light = new THREE.Mesh(
new THREE.BoxGeometry(0.36, 0.08, 0.36),
new THREE.MeshStandardMaterial({
color: accent,
emissive: accent,
emissiveIntensity: 1.1
})
);
light.position.y = 1.71;
group.add(light);
const label = makeLabel(name, hexCss(accent), 2.05);
label.position.copy(labelPosition);
scene.add(label);
world.add(group);
}
createStation(
nodes.J0, "SORT A", COLORS.red,
new THREE.Vector3(-1.1, 1.9, -4.65)
);
createStation(
nodes.J1, "SORT B", COLORS.blue,
new THREE.Vector3(4.65, 1.9, 0)
);
createStation(
nodes.J2, "SORT C", COLORS.yellow,
new THREE.Vector3(0.9, 1.9, 4.7)
);
createStation(
nodes.J3, "SORT D", COLORS.purple,
new THREE.Vector3(-6.65, 1.9, 0)
);
function createAlertFrame(position) {
const group = new THREE.Group();
group.position.copy(position);
group.position.y = 0.07;
const frameMaterial = new THREE.MeshBasicMaterial({
color: COLORS.red,
transparent: true,
opacity: 0
});
const size = 1.9;
const thickness = 0.075;
const parts = [
[size, thickness, 0, -size / 2],
[size, thickness, 0, size / 2],
[thickness, size, -size / 2, 0],
[thickness, size, size / 2, 0]
];
for (const [w, d, x, z] of parts) {
const bar = new THREE.Mesh(
new THREE.BoxGeometry(w, 0.025, d),
frameMaterial
);
bar.position.set(x, 0, z);
group.add(bar);
}
group.visible = false;
world.add(group);
alertFrames.push({ group, material: frameMaterial });
}
for (const position of Object.values(nodes)) createAlertFrame(position);
// -------------------------------------------------------------------------
// Parcels
// -------------------------------------------------------------------------
const items = [];
function createParcel(id, edgeId, color, destination) {
const group = new THREE.Group();
const bodyMaterial = material(color, {
roughness: 0.66,
emissive: 0x000000,
emissiveIntensity: 0
});
const body = new THREE.Mesh(
new THREE.BoxGeometry(0.72, 0.72, 0.72),
bodyMaterial
);
body.castShadow = true;
body.receiveShadow = true;
body.userData.itemId = id;
group.add(body);
packageMeshes.push(body);
const tape = new THREE.Mesh(
new THREE.BoxGeometry(0.16, 0.74, 0.74),
material(0xf0e5c9)
);
tape.castShadow = true;
group.add(tape);
const sticker = new THREE.Mesh(
new THREE.BoxGeometry(0.31, 0.18, 0.025),
material(0xffffff)
);
sticker.position.set(0.13, 0.07, 0.37);
group.add(sticker);
world.add(group);
const item = {
id,
label: `P${id}`,
destination,
color,
current: edgeId,
t: 0.9,
route: null,
transition: null,
group,
body,
bodyMaterial
};
items.push(item);
edgeState[edgeId].occupant = item;
return item;
}
createParcel(1, "A", itemColors[0], "WEST");
createParcel(2, "B", itemColors[1], "NORTH");
createParcel(3, "C", itemColors[2], "EAST");
createParcel(4, "D", itemColors[3], "SOUTH");
// Selection marker built from four voxel bars.
const selectionMarker = new THREE.Group();
const markerMaterial = new THREE.MeshBasicMaterial({
color: COLORS.yellow,
transparent: true,
opacity: 0.9,
depthTest: false
});
for (let i = 0; i < 4; i++) {
const bar = new THREE.Mesh(
new THREE.BoxGeometry(i % 2 ? 0.06 : 1.08, 0.035, i % 2 ? 1.08 : 0.06),
markerMaterial
);
bar.position.set(
i === 0 ? -0.51 : i === 1 ? 0.51 : 0,
0,
i === 2 ? -0.51 : i === 3 ? 0.51 : 0
);
selectionMarker.add(bar);
}
selectionMarker.renderOrder = 12;
world.add(selectionMarker);
let selectedId = 1;
// A temporary marker at the diverter when a route is changed.
const routePulse = new THREE.Mesh(
new THREE.BoxGeometry(0.24, 2.4, 0.24),
new THREE.MeshBasicMaterial({
color: COLORS.green,
transparent: true,
opacity: 0
})
);
routePulse.position.copy(nodes.J1);
routePulse.position.y = 1.4;
world.add(routePulse);
// -------------------------------------------------------------------------
// Puzzle state and simulation
// -------------------------------------------------------------------------
let bufferEdge = null;
let running = true;
let speed = 1;
let transfers = 0;
let rerouted = false;
let deadlockCycle = [];
let pulseTime = 0;
function getTarget(item) {
if (item.current === "A" && item.route === "buffer" && bufferEdge) {
return "buffer";
}
if (item.current === "buffer") return "C";
return edgeDefs[item.current].next;
}
function startTransfer(item, targetId) {
const target = edgeState[targetId];
if (!target || target.occupant) return false;
target.occupant = item;
item.transition = {
from: item.current,
to: targetId,
u: 0
};
return true;
}
function completeTransfer(item) {
const transition = item.transition;
if (!transition) return;
if (edgeState[transition.from].occupant === item) {
edgeState[transition.from].occupant = null;
}
item.current = transition.to;
item.t = 0;
item.transition = null;
transfers++;
if (item.current === "buffer") {
item.route = null;
}
}
function findDeadlockCycle() {
const waitingItems = items.filter(
(item) => !item.transition && item.t >= 0.995
);
const waitingSet = new Set(waitingItems);
for (const start of waitingItems) {
const seen = new Map();
let current = start;
let steps = 0;
while (current && steps < items.length + 2) {
if (seen.has(current.id)) {
return waitingItems.slice(seen.get(current.id), steps);
}
seen.set(current.id, steps);
const targetId = getTarget(current);
const target = edgeState[targetId];
const owner = target?.occupant;
if (!owner || owner === current || !waitingSet.has(owner)) break;
current = owner;
steps++;
}
}
return [];
}
function simulate(dt) {
if (!running) return;
for (const item of items) {
if (item.transition) {
item.transition.u += dt / 0.72;
if (item.transition.u >= 1) {
completeTransfer(item);
}
continue;
}
item.t = Math.min(1, item.t + dt * 0.115 * speed);
if (item.t >= 0.999) {
const targetId = getTarget(item);
startTransfer(item, targetId);
}
}
deadlockCycle = findDeadlockCycle();
}
// -------------------------------------------------------------------------
// Actions
// -------------------------------------------------------------------------
let toastTimer = 0;
function showToast(message) {
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 2600);
}
function addBuffer() {
if (bufferEdge) return;
bufferEdge = {
id: "buffer",
name: "BYPASS BUFFER",
next: "C",
path: [
nodes.J1.clone(),
new THREE.Vector3(0.95, 0, -3.35),
new THREE.Vector3(0.95, 0, 3.35),
nodes.J2.clone()
],
accent: COLORS.cyan
};
createBelt(bufferEdge, true);
edgeState.buffer = { occupant: null };
const label = makeLabel("BYPASS BUFFER", "#4ed9c4", 2.6);
label.position.set(0.95, 2.0, 0);
bufferEdge.group.add(label);
label.position.sub(bufferEdge.group.position);
bufferBtn.disabled = true;
bufferBtn.innerHTML =
"✓ BYPASS BUFFER INSTALLED<small>The buffer is free, but no parcel is using it yet.</small>";
proofTitle.textContent = "A free destination exists";
proofText.textContent =
"The new buffer can hold one parcel, but capacity alone does not break the cycle. Reroute P1 from Sort A into the buffer so it can take the first step.";
showToast("BYPASS BUFFER ADDED · NOW REROUTE P1");
updateUI();
}
function rerouteSelected() {
if (!bufferEdge) return;
const item = items.find((candidate) => candidate.id === selectedId);
if (!item || item.current !== "A" || item.transition) return;
item.route = "buffer";
rerouted = true;
pulseTime = 1.3;
proofTitle.textContent = "The cycle is being broken";
proofText.textContent =
"P1 now waits for the free buffer instead of occupied Sort B. When P1 leaves A, D gains a free destination and the circular wait starts to unwind.";
showToast("P1 REROUTED · A → BUFFER");
updateUI();
}
function resetPuzzle() {
if (bufferEdge) {
world.remove(bufferEdge.group);
for (const mesh of bufferEdge.pickMeshes) {
const index = pickables.indexOf(mesh);
if (index >= 0) pickables.splice(index, 1);
}
// The buffer group contains unique geometries; dispose them.
bufferEdge.group.traverse((object) => {
if (object.geometry) object.geometry.dispose();
});
}
bufferEdge = null;
delete edgeState.buffer;
for (const edge of Object.values(edgeDefs)) {
edgeState[edge.id].occupant = null;
}
const initialEdges = ["A", "B", "C", "D"];
items.forEach((item, index) => {
item.current = initialEdges[index];
item.t = 0.9;
item.route = null;
item.transition = null;
edgeState[item.current].occupant = item;
});
transfers = 0;
rerouted = false;
deadlockCycle = [];
selectedId = 1;
running = true;
runBtn.textContent = "Pause";
speedInput.value = "1";
speed = 1;
bufferBtn.disabled = false;
bufferBtn.innerHTML =
"+ ADD BYPASS BUFFER<small>Creates one free staging position between Sort A and Sort B.</small>";
proofTitle.textContent = "Why it is stuck";
proofText.textContent =
"A waits for B, B waits for C, C waits for D, and D waits for A. Every destination is occupied, so no parcel can take the first step.";
proofSteps.hidden = true;
showToast("PUZZLE RESET");
updateUI();
}
bufferBtn.addEventListener("click", addBuffer);
rerouteBtn.addEventListener("click", rerouteSelected);
resetBtn.addEventListener("click", resetPuzzle);
runBtn.addEventListener("click", () => {
running = !running;
runBtn.textContent = running ? "Pause" : "Run";
updateUI();
});
speedInput.addEventListener("input", () => {
speed = Number(speedInput.value);
});
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLInputElement) return;
if (event.code === "Space") {
event.preventDefault();
runBtn.click();
} else if (event.key.toLowerCase() === "b") {
addBuffer();
} else if (event.key.toLowerCase() === "x") {
rerouteSelected();
}
});
// -------------------------------------------------------------------------
// Pointer picking and direct orbit controls
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const pointerDown = { x: 0, y: 0, dragging: false };
let activePointer = null;
function setPointer(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function pick(event) {
setPointer(event);
raycaster.setFromCamera(pointer, camera);
const parcelHits = raycaster.intersectObjects(packageMeshes, false);
if (parcelHits.length) {
selectedId = parcelHits[0].object.userData.itemId;
updateUI();
return;
}
const beltHits = raycaster.intersectObjects(pickables, false);
if (!beltHits.length) return;
const edgeId = beltHits[0].object.userData.edgeId;
if (edgeId === "buffer") {
rerouteSelected();
return;
}
const occupant = edgeState[edgeId]?.occupant;
if (occupant) {
selectedId = occupant.id;
updateUI();
}
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
activePointer = event.pointerId;
pointerDown.x = event.clientX;
pointerDown.y = event.clientY;
pointerDown.dragging = false;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (activePointer !== event.pointerId) return;
const dx = event.clientX - pointerDown.x;
const dy = event.clientY - pointerDown.y;
if (Math.abs(dx) + Math.abs(dy) > 5) {
pointerDown.dragging = true;
}
if (pointerDown.dragging) {
cameraState.azimuth -= dx * 0.007;
cameraState.polar = THREE.MathUtils.clamp(
cameraState.polar + dy * 0.005,
0.34,
1.18
);
updateCamera();
pointerDown.x = event.clientX;
pointerDown.y = event.clientY;
} else {
setPointer(event);
raycaster.setFromCamera(pointer, camera);
const hovering =
raycaster.intersectObjects(packageMeshes, false).length > 0 ||
raycaster.intersectObjects(pickables, false).length > 0;
renderer.domElement.style.cursor = hovering ? "pointer" : "grab";
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (activePointer !== event.pointerId) return;
if (!pointerDown.dragging) pick(event);
activePointer = null;
});
renderer.domElement.addEventListener("pointercancel", () => {
activePointer = null;
pointerDown.dragging = false;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * (event.deltaY > 0 ? 0.92 : 1.08),
0.68,
1.7
);
updateCamera();
},
{ passive: false }
);
// -------------------------------------------------------------------------
// UI updates
// -------------------------------------------------------------------------
function updateUI() {
const selected = items.find((item) => item.id === selectedId);
const waiting = items.filter(
(item) => !item.transition && item.t >= 0.995
).length;
const occupied = Object.values(edgeState).filter(
(state) => state.occupant
).length;
document.getElementById("statBelts").textContent = occupied;
document.getElementById("statWaiting").textContent = waiting;
document.getElementById("statMoves").textContent = transfers;
if (selected) {
const edgeName =
selected.current === "buffer"
? "BYPASS BUFFER"
: edgeDefs[selected.current].name;
selectionName.textContent = `${selected.label} · ${edgeName}`;
selectionSwatch.style.background = hexCss(selected.color);
selectionHint.textContent =
selected.current === "A"
? "This parcel can use the bypass after the buffer is installed."
: "The bypass can receive a parcel only from Sort A.";
}
const canReroute =
bufferEdge &&
selected &&
selected.current === "A" &&
!selected.transition &&
selected.route !== "buffer";
rerouteBtn.disabled = !canReroute;
if (!running) {
statusPill.className = "";
statusText.textContent = "PAUSED";
} else if (deadlockCycle.length >= 2) {
statusPill.className = "deadlock";
statusText.textContent = "DEADLOCK";
} else if (rerouted && transfers > 0) {
statusPill.className = "clear";
statusText.textContent = "FLOW RESTORED";
} else if (rerouted) {
statusPill.className = "";
statusText.textContent = "REROUTED";
} else if (bufferEdge) {
statusPill.className = "deadlock";
statusText.textContent = "BYPASS READY";
} else {
statusPill.className = "";
statusText.textContent = "ROUTING";
}
const rows = [];
for (const item of items) {
if (item.transition || item.t < 0.995) continue;
const targetId = getTarget(item);
const owner = edgeState[targetId]?.occupant;
if (owner && owner !== item) {
rows.push(`
<div class="wait-row">
<span class="parcel-dot" style="--dot:${hexCss(item.color)}"></span>
<span>${item.label} / ${item.current}</span>
<span style="margin-left:auto;color:#ff9b9b">WAITS FOR ${owner.label}</span>
</div>
`);
}
}
waitRows.innerHTML = rows.join("");
if (deadlockCycle.length >= 2) {
const hotEdges = new Set(deadlockCycle.map((item) => item.current));
cycleFlow.querySelectorAll(".chain-node").forEach((node, index) => {
const edgeIds = ["A", "B", "C", "D", "A"];
node.classList.toggle("hot", hotEdges.has(edgeIds[index]));
});
} else if (rerouted && transfers > 0) {
cycleFlow.innerHTML = `
<span class="chain-node" style="background:#24685f;border-color:#4ed9c4">A</span>
<span class="chain-arrow" style="color:#72e2a1">→</span>
<span class="chain-node" style="background:#24685f;border-color:#4ed9c4">BUF</span>
<span class="chain-arrow" style="color:#72e2a1">→</span>
<span class="chain-node" style="background:#24685f;border-color:#4ed9c4">C</span>
<span class="chain-arrow" style="color:#72e2a1">→</span>
<span class="chain-node" style="background:#24685f;border-color:#4ed9c4">FLOW</span>
`;
}
if (rerouted && transfers > 0) {
proofTitle.textContent = "Why the revised layout clears";
proofText.textContent =
"P1's bypass destination is free, so P1 can move first. Vacating A releases D; the chain then unwinds through D → A, C → D and B → C. Because no parcel can close the old circular wait, all cells resume moving.";
proofSteps.hidden = false;
}
}
// -------------------------------------------------------------------------
// Visual update
// -------------------------------------------------------------------------
function itemWorldPosition(item) {
if (item.transition) {
const fromEdge = item.transition.from === "buffer"
? bufferEdge
: edgeDefs[item.transition.from];
const toEdge = item.transition.to === "buffer"
? bufferEdge
: edgeDefs[item.transition.to];
const start = pointOnPath(
fromEdge.path,
fromEdge.metrics.cumulative,
fromEdge.metrics.total,
1
);
const end = pointOnPath(
toEdge.path,
toEdge.metrics.cumulative,
toEdge.metrics.total,
0
);
const t = THREE.MathUtils.smoothstep(item.transition.u, 0, 1);
return start.lerp(end, t);
}
const edge = item.current === "buffer"
? bufferEdge
: edgeDefs[item.current];
return pointOnPath(
edge.path,
edge.metrics.cumulative,
edge.metrics.total,
item.t
);
}
function updateVisuals(time, dt) {
for (const item of items) {
const position = itemWorldPosition(item);
item.group.position.set(position.x, 0.99, position.z);
const isSelected = item.id === selectedId;
const isWaiting = !item.transition && item.t >= 0.995;
item.bodyMaterial.emissive.setHex(isSelected ? 0x7f5a00 : 0x000000);
item.bodyMaterial.emissiveIntensity = isSelected ? 0.42 : isWaiting ? 0.08 : 0;
const pulse = isSelected ? 1 + Math.sin(time * 5) * 0.035 : 1;
item.group.scale.setScalar(pulse);
}
if (selectedId !== null) {
const selected = items.find((item) => item.id === selectedId);
if (selected) {
const position = itemWorldPosition(selected);
selectionMarker.position.set(position.x, 0.67, position.z);
selectionMarker.rotation.y = time * 0.7;
}
}
const showAlert = deadlockCycle.length >= 2;
const showSuccess = rerouted && transfers > 0 && !showAlert;
for (const frame of alertFrames) {
frame.group.visible = showAlert || showSuccess;
frame.material.color.setHex(showSuccess ? COLORS.green : COLORS.red);
frame.material.opacity = showAlert
? 0.22 + Math.sin(time * 5) * 0.13
: 0.3;
}
if (pulseTime > 0) {
pulseTime = Math.max(0, pulseTime - dt);
routePulse.material.opacity = Math.min(0.9, pulseTime * 2);
routePulse.scale.y = 1 + Math.sin((1.3 - pulseTime) * 12) * 0.18;
} else {
routePulse.material.opacity = 0;
}
}
// -------------------------------------------------------------------------
// Main loop
// -------------------------------------------------------------------------
let previousTime = performance.now();
let uiTimer = 0;
function animate(now) {
requestAnimationFrame(animate);
const dt = Math.min(0.05, (now - previousTime) / 1000);
previousTime = now;
const time = now / 1000;
simulate(dt);
updateVisuals(time, dt);
uiTimer += dt;
if (uiTimer > 0.1) {
updateUI();
uiTimer = 0;
}
renderer.render(scene, camera);
}
resize();
updateUI();
requestAnimationFrame(animate);
</script>
</body>
</html>
```