Prompt specification
Build or customize the Three.js 3D scene "Funnel opening and particle flow comparison" 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: Funnel opening and particle flow comparison
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/funnel-opening-and-particle-flow-comparison-x1390
Scene Description Prompt:
Please make a stylized Three.js scene in one standalone HTML file using cdnjs. Show a few grains passing through broad and narrow openings under a bounded toy collision model; distinguish intermittent clogging examples from universal granular-flow predictions.
Working Three.js Starter (funnel-opening-and-particle-flow-comparison-x1390):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Two Openings — A Bounded Granular Toy</title>
<style>
:root {
--bg: #071018;
--panel: rgba(10, 22, 31, 0.82);
--panel-strong: rgba(9, 20, 28, 0.93);
--line: rgba(168, 214, 225, 0.16);
--line-strong: rgba(168, 214, 225, 0.28);
--text: #eef8f8;
--muted: #91a8af;
--cyan: #58dfd1;
--amber: #ffb45d;
--red: #ff7568;
--shadow: 0 20px 60px rgba(0, 0, 0, 0.32);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 47% 36%, rgba(26, 73, 88, 0.24), transparent 38%),
radial-gradient(circle at 79% 74%, rgba(102, 62, 25, 0.11), transparent 30%),
linear-gradient(145deg, #071018 0%, #08131c 54%, #050c12 100%);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button:focus-visible,
input:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 3px;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene.dragging {
cursor: grabbing;
}
.topbar {
position: fixed;
z-index: 5;
top: 20px;
left: 22px;
right: 22px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 20px;
pointer-events: none;
}
.title-block {
max-width: 640px;
text-shadow: 0 2px 20px rgba(0, 0, 0, 0.5);
}
.eyebrow {
margin-bottom: 7px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.2em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(24px, 3vw, 38px);
font-weight: 650;
letter-spacing: -0.045em;
line-height: 1.02;
}
.subtitle {
margin: 9px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.claim-badge {
pointer-events: auto;
display: flex;
align-items: center;
gap: 9px;
padding: 10px 13px;
border: 1px solid rgba(255, 180, 93, 0.28);
border-radius: 999px;
background: rgba(31, 24, 17, 0.7);
color: #ffd39c;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
white-space: nowrap;
backdrop-filter: blur(14px);
}
.claim-badge::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--amber);
box-shadow: 0 0 16px rgba(255, 180, 93, 0.8);
content: "";
}
.panel {
position: fixed;
z-index: 4;
border: 1px solid var(--line);
border-radius: 18px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(20px) saturate(125%);
}
.controls {
top: 108px;
left: 20px;
width: 282px;
padding: 18px;
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 16px;
}
.panel-heading h2 {
margin: 0;
font-size: 14px;
font-weight: 700;
letter-spacing: -0.01em;
}
.tiny-tag {
padding: 4px 7px;
border: 1px solid var(--line);
border-radius: 6px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.control {
margin-bottom: 17px;
}
.control-row {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 8px;
font-size: 11px;
}
.control-row label {
color: #c5d5d8;
font-weight: 600;
}
output {
color: var(--cyan);
font-variant-numeric: tabular-nums;
font-weight: 700;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
border-radius: 999px;
accent-color: var(--cyan);
cursor: pointer;
}
.range-ends {
display: flex;
justify-content: space-between;
margin-top: 6px;
color: #647d85;
font-size: 9px;
}
.toggle-row {
display: flex;
align-items: center;
justify-content: space-between;
margin: 2px 0 16px;
color: #b8c9cd;
font-size: 11px;
}
.toggle-row input {
accent-color: var(--cyan);
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
button {
min-height: 38px;
padding: 0 11px;
border: 1px solid var(--line-strong);
border-radius: 10px;
background: rgba(255, 255, 255, 0.045);
color: var(--text);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.035em;
cursor: pointer;
transition:
transform 140ms ease,
border-color 140ms ease,
background 140ms ease;
}
button:hover {
border-color: rgba(88, 223, 209, 0.48);
background: rgba(88, 223, 209, 0.09);
transform: translateY(-1px);
}
button.primary {
border-color: rgba(88, 223, 209, 0.38);
background: rgba(88, 223, 209, 0.13);
color: #b9fff7;
}
.divider {
height: 1px;
margin: 17px 0;
background: var(--line);
}
.status-readout {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 11px;
border: 1px solid rgba(255, 180, 93, 0.2);
border-radius: 10px;
background: rgba(255, 180, 93, 0.055);
}
.status-dot {
width: 8px;
height: 8px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--amber);
box-shadow: 0 0 12px rgba(255, 180, 93, 0.6);
}
.status-dot.blocked {
background: var(--red);
box-shadow: 0 0 12px rgba(255, 117, 104, 0.75);
}
.status-copy {
display: flex;
flex-direction: column;
gap: 2px;
font-size: 9px;
color: var(--muted);
}
.status-copy b {
color: #f1d8b8;
font-size: 11px;
}
.model-list {
display: grid;
gap: 7px;
margin: 0;
color: var(--muted);
font-size: 10px;
}
.model-list div {
display: flex;
justify-content: space-between;
gap: 12px;
}
.model-list dt {
color: #789099;
}
.model-list dd {
margin: 0;
color: #c5d7da;
text-align: right;
}
.scene-label {
position: fixed;
z-index: 2;
min-width: 158px;
padding: 9px 11px 9px 12px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(7, 17, 24, 0.75);
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.24);
pointer-events: none;
transform: translate(-50%, -100%);
backdrop-filter: blur(12px);
}
.scene-label::after {
position: absolute;
bottom: -7px;
left: 50%;
width: 1px;
height: 7px;
background: var(--line-strong);
content: "";
}
.scene-label .label-title {
display: flex;
align-items: center;
gap: 7px;
margin-bottom: 3px;
font-size: 11px;
font-weight: 750;
}
.scene-label .label-index {
display: inline-grid;
width: 18px;
height: 18px;
place-items: center;
border-radius: 5px;
background: rgba(88, 223, 209, 0.12);
color: var(--cyan);
font-size: 9px;
}
.scene-label.narrow .label-index {
background: rgba(255, 180, 93, 0.13);
color: var(--amber);
}
.scene-label .label-meta {
color: var(--muted);
font-size: 9px;
}
.scene-label .label-state {
color: #c6dadd;
}
.interpretation {
right: 20px;
bottom: 20px;
width: 356px;
padding: 18px;
background: var(--panel-strong);
}
.interpretation h2 {
margin: 0 0 8px;
font-size: 17px;
letter-spacing: -0.025em;
}
.interpretation > p {
margin: 0 0 14px;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.claim-grid {
display: grid;
gap: 9px;
}
.claim {
padding: 10px 11px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.claim.observed {
border-color: rgba(88, 223, 209, 0.18);
}
.claim.universal {
border-color: rgba(255, 117, 104, 0.18);
}
.claim-title {
display: flex;
align-items: center;
gap: 7px;
margin-bottom: 6px;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.observed .claim-title {
color: var(--cyan);
}
.universal .claim-title {
color: var(--red);
}
.claim p {
margin: 0;
color: #a7bbc0;
font-size: 10px;
line-height: 1.5;
}
.guardrail {
margin-top: 12px;
color: #7f979e;
font-size: 9px;
line-height: 1.45;
}
.bottom-hud {
position: fixed;
z-index: 4;
bottom: 20px;
left: 50%;
display: flex;
align-items: stretch;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(9, 20, 28, 0.79);
box-shadow: var(--shadow);
transform: translateX(-50%);
backdrop-filter: blur(16px);
}
.metric {
min-width: 105px;
padding: 10px 14px;
border-right: 1px solid var(--line);
}
.metric:last-child {
border-right: 0;
}
.metric span {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 8px;
font-weight: 750;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.metric b {
display: block;
font-size: 15px;
font-variant-numeric: tabular-nums;
}
.metric small {
color: #708990;
font-size: 9px;
}
.interaction-hint {
position: fixed;
z-index: 3;
bottom: 22px;
left: 20px;
color: #657d84;
font-size: 9px;
letter-spacing: 0.04em;
pointer-events: none;
}
@media (max-width: 1120px) {
.bottom-hud {
left: 20px;
transform: none;
}
.interaction-hint {
display: none;
}
.controls {
max-height: calc(100vh - 128px);
overflow-y: auto;
}
}
@media (max-width: 820px) {
.topbar {
top: 14px;
left: 14px;
right: 14px;
}
.claim-badge {
display: none;
}
.subtitle {
max-width: 520px;
}
.controls {
top: 102px;
left: 12px;
width: 248px;
padding: 14px;
}
.interpretation {
right: 12px;
bottom: 12px;
width: 310px;
padding: 14px;
}
.bottom-hud {
left: 12px;
bottom: 12px;
}
.metric {
min-width: 88px;
padding: 8px 10px;
}
}
@media (max-width: 620px) {
h1 {
font-size: 25px;
}
.subtitle {
font-size: 11px;
}
.controls {
top: 94px;
width: calc(100% - 24px);
max-height: 38vh;
}
.model-list,
.controls .divider {
display: none;
}
.interpretation {
right: 12px;
bottom: 70px;
width: calc(100% - 24px);
}
.claim-grid {
grid-template-columns: 1fr 1fr;
}
.bottom-hud {
right: 12px;
bottom: 10px;
left: 12px;
}
.metric {
flex: 1;
min-width: 0;
}
.metric b {
font-size: 13px;
}
.scene-label {
min-width: 132px;
padding: 7px 9px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive 3D visualization of grains passing through broad and narrow openings"></canvas>
<header class="topbar">
<div class="title-block">
<div class="eyebrow">Opening study / bounded contact model</div>
<h1>Two openings. Two observed behaviors.</h1>
<p class="subtitle">
Equal circular grains move through a wide slot and a tighter slot.
The pause in the narrow channel is an example from this setup—not a universal granular-flow law.
</p>
</div>
<div class="claim-badge">Illustrative run · no universal claim</div>
</header>
<aside class="panel controls" aria-label="Simulation controls">
<div class="panel-heading">
<h2>Toy parameters</h2>
<span class="tiny-tag">2D contacts</span>
</div>
<div class="control">
<div class="control-row">
<label for="gap">Narrow opening</label>
<output id="gapOutput" for="gap">2.1 d</output>
</div>
<input id="gap" type="range" min="1.6" max="2.8" step="0.1" value="2.1" />
<div class="range-ends">
<span>1.6 grain diameters</span>
<span>2.8 diameters</span>
</div>
</div>
<div class="control">
<div class="control-row">
<label for="gravity">Gravity</label>
<output id="gravityOutput" for="gravity">3.2 units/s²</output>
</div>
<input id="gravity" type="range" min="1" max="5" step="0.1" value="3.2" />
</div>
<div class="control">
<div class="control-row">
<label for="speed">Playback</label>
<output id="speedOutput" for="speed">1.0×</output>
</div>
<input id="speed" type="range" min="0.25" max="2" step="0.25" value="1" />
</div>
<label class="toggle-row">
<span>Velocity streaks</span>
<input id="paths" type="checkbox" checked />
</label>
<div class="button-row">
<button id="pause" class="primary" type="button">Pause</button>
<button id="reset" type="button">Reset run</button>
<button id="seed" type="button">New seed</button>
<button id="view" type="button">Reset view</button>
</div>
<div class="divider"></div>
<div class="status-readout">
<span id="narrowDot" class="status-dot"></span>
<div class="status-copy">
Narrow-slot run diagnostic
<b id="narrowStatus">Waiting for flow</b>
</div>
</div>
<div class="divider"></div>
<dl class="model-list">
<div><dt>Broad opening</dt><dd>4.1 d</dd></div>
<div><dt>Grains</dt><dd>64 equal disks</dd></div>
<div><dt>Integration</dt><dd>fixed 120 Hz</dd></div>
<div><dt>Contacts</dt><dd>normal + friction</dd></div>
<div><dt>Boundary</dt><dd>closed, recycled loop</dd></div>
</dl>
</aside>
<div id="broadLabel" class="scene-label">
<div class="label-title">
<span class="label-index">01</span>
Broad opening
</div>
<div class="label-meta">4.1 d · <span id="broadLabelState">waiting</span></div>
</div>
<div id="narrowLabel" class="scene-label narrow">
<div class="label-title">
<span class="label-index">02</span>
Narrow opening
</div>
<div class="label-meta"><span id="narrowRatio">2.1 d</span> · <span id="narrowLabelState">waiting</span></div>
</div>
<aside class="panel interpretation" aria-label="Scientific interpretation">
<div class="eyebrow">Read the claim correctly</div>
<h2>Observation is not prediction.</h2>
<p>
The scene shows one seeded, finite, equal-disk model. The narrow slot can
lose throughput when a contact configuration blocks the opening.
</p>
<div class="claim-grid">
<section class="claim observed">
<div class="claim-title">What this run shows</div>
<p>
Throughput and intermittent arch-like pauses for a particular geometry,
seed, friction value, drive, and grain size.
</p>
</section>
<section class="claim universal">
<div class="claim-title">What is not inferred</div>
<p>
No universal critical width, jamming phase line, or Beverloo-type law.
The model omits shape, rotation, polydispersity, cohesion, and 3-D contacts.
</p>
</section>
</div>
<div class="guardrail">
Status dots are run diagnostics based on recent crossings and local occupancy,
not measurements of a real granular phase transition.
</div>
</aside>
<div class="bottom-hud" aria-live="polite">
<div class="metric">
<span>Broad crossings</span>
<b id="broadCount">0</b>
<small id="broadState">quiet</small>
</div>
<div class="metric">
<span>Narrow crossings</span>
<b id="narrowCount">0</b>
<small id="narrowState">waiting</small>
</div>
<div class="metric">
<span>Arch-like pauses</span>
<b id="pauseCount">0</b>
<small>detected in this run</small>
</div>
<div class="metric">
<span>Model time</span>
<b id="modelTime">0.0 s</b>
<small>seed <span id="seedValue">7</span></small>
</div>
</div>
<div class="interaction-hint">Drag to orbit · Scroll to zoom · Double-click to reset view</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------
// Scene and renderer
// ---------------------------------------------------------------------
const canvas = document.getElementById("scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setClearColor(0x000000, 0);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(38, 1, 0.1, 100);
const ambient = new THREE.AmbientLight(0xa8d5df, 1.25);
scene.add(ambient);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.4);
keyLight.position.set(-5, 9, 9);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x78d9e6, 1.35);
rimLight.position.set(8, 1, 5);
scene.add(rimLight);
const cyanLight = new THREE.PointLight(0x52e0d1, 26, 18, 2);
cyanLight.position.set(-6, 4, 5);
scene.add(cyanLight);
const amberLight = new THREE.PointLight(0xffa84e, 24, 18, 2);
amberLight.position.set(6, 2, 5);
scene.add(amberLight);
const world = new THREE.Group();
scene.add(world);
const backdrop = new THREE.Mesh(
new THREE.PlaneGeometry(34, 22),
new THREE.MeshBasicMaterial({
color: 0x0c1e29,
transparent: true,
opacity: 0.28,
depthWrite: false
})
);
backdrop.position.set(0, 0, -1.4);
world.add(backdrop);
// ---------------------------------------------------------------------
// Bounded toy-model constants
// ---------------------------------------------------------------------
const GRAIN_RADIUS = 0.22;
const GRAIN_DIAMETER = GRAIN_RADIUS * 2;
const GRAINS_PER_CHANNEL = 32;
const FIXED_DT = 1 / 120;
const SHELF_TOP = 0.56;
const SHELF_BOTTOM = 0.30;
const RECYCLE_Y = -5.28;
const channels = [
{
id: "broad",
center: -3,
xL: -5.25,
xR: -0.75,
gap: GRAIN_DIAMETER * 4.1,
color: 0x58dfd1,
crossings: 0,
pauses: 0,
lastCross: -100,
status: "quiet",
visual: null
},
{
id: "narrow",
center: 3,
xL: 0.75,
xR: 5.25,
gap: GRAIN_DIAMETER * 2.1,
color: 0xffb45d,
crossings: 0,
pauses: 0,
lastCross: -100,
status: "waiting",
visual: null
}
];
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const wallMaterial = new THREE.MeshStandardMaterial({
color: 0x19313d,
metalness: 0.35,
roughness: 0.62
});
const shelfMaterial = new THREE.MeshStandardMaterial({
color: 0x29404b,
metalness: 0.28,
roughness: 0.58
});
// ---------------------------------------------------------------------
// Build the two channels
// ---------------------------------------------------------------------
function addChannelGrid(channel) {
const positions = [];
const left = channel.xL;
const right = channel.xR;
const bottom = -5.05;
const top = 5.0;
for (let x = left; x <= right + 0.001; x += 0.5) {
positions.push(x, bottom, -0.64, x, top, -0.64);
}
for (let y = bottom; y <= top + 0.001; y += 0.5) {
positions.push(left, y, -0.64, right, y, -0.64);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
const lines = new THREE.LineSegments(
geometry,
new THREE.LineBasicMaterial({
color: 0x8cbdc8,
transparent: true,
opacity: 0.075,
depthWrite: false
})
);
world.add(lines);
}
function buildChannel(channel) {
const width = channel.xR - channel.xL;
const centerX = (channel.xL + channel.xR) * 0.5;
const back = new THREE.Mesh(
new THREE.BoxGeometry(width, 10.35, 0.08),
new THREE.MeshBasicMaterial({
color: 0x0b1d28,
transparent: true,
opacity: 0.64,
depthWrite: false
})
);
back.position.set(centerX, -0.03, -0.78);
world.add(back);
const edgeGeometry = new THREE.EdgesGeometry(
new THREE.BoxGeometry(width, 10.35, 0.08)
);
const edges = new THREE.LineSegments(
edgeGeometry,
new THREE.LineBasicMaterial({
color: 0x6f9ca8,
transparent: true,
opacity: 0.16
})
);
edges.position.copy(back.position);
world.add(edges);
addChannelGrid(channel);
const leftWall = new THREE.Mesh(unitBox, wallMaterial);
leftWall.position.set(channel.xL, -0.05, 0);
leftWall.scale.set(0.15, 10.45, 0.8);
world.add(leftWall);
const rightWall = new THREE.Mesh(unitBox, wallMaterial);
rightWall.position.set(channel.xR, -0.05, 0);
rightWall.scale.set(0.15, 10.45, 0.8);
world.add(rightWall);
const leftShelf = new THREE.Mesh(unitBox, shelfMaterial);
const rightShelf = new THREE.Mesh(unitBox, shelfMaterial);
leftShelf.position.z = 0;
rightShelf.position.z = 0;
leftShelf.scale.z = 0.82;
rightShelf.scale.z = 0.82;
world.add(leftShelf, rightShelf);
const glowMaterial = new THREE.MeshBasicMaterial({
color: channel.color,
transparent: true,
opacity: 0.72,
depthWrite: false
});
const openingGlow = new THREE.Mesh(unitBox, glowMaterial);
openingGlow.position.set(centerX, SHELF_BOTTOM - 0.025, 0.43);
openingGlow.scale.set(channel.gap, 0.026, 0.06);
openingGlow.renderOrder = 4;
world.add(openingGlow);
const outletGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(channel.xL + 0.15, -5.1, 0.1),
new THREE.Vector3(channel.xR - 0.15, -5.1, 0.1)
]);
const outlet = new THREE.Line(
outletGeometry,
new THREE.LineBasicMaterial({
color: channel.color,
transparent: true,
opacity: 0.34
})
);
world.add(outlet);
channel.visual = {
leftShelf,
rightShelf,
openingGlow,
glowMaterial
};
}
channels.forEach(buildChannel);
// A visible cue for a detected narrow-channel pause.
const archPositions = new Float32Array(17 * 3);
const archGeometry = new THREE.BufferGeometry();
archGeometry.setAttribute(
"position",
new THREE.BufferAttribute(archPositions, 3)
);
const archCue = new THREE.Line(
archGeometry,
new THREE.LineBasicMaterial({
color: 0xff7568,
transparent: true,
opacity: 0.95,
depthTest: false
})
);
archCue.position.z = 0.48;
archCue.renderOrder = 8;
archCue.visible = false;
world.add(archCue);
function updateOpeningMeshes() {
for (const channel of channels) {
const visual = channel.visual;
const gapLeft = channel.center - channel.gap * 0.5;
const gapRight = channel.center + channel.gap * 0.5;
const leftLength = Math.max(0.01, gapLeft - channel.xL);
const rightLength = Math.max(0.01, channel.xR - gapRight);
visual.leftShelf.scale.x = leftLength;
visual.leftShelf.position.set(
channel.xL + leftLength * 0.5,
(SHELF_TOP + SHELF_BOTTOM) * 0.5,
0
);
visual.rightShelf.scale.x = rightLength;
visual.rightShelf.position.set(
gapRight + rightLength * 0.5,
(SHELF_TOP + SHELF_BOTTOM) * 0.5,
0
);
visual.openingGlow.scale.x = channel.gap;
visual.openingGlow.position.x = channel.center;
}
const narrow = channels[1];
const positions = archGeometry.attributes.position.array;
for (let i = 0; i < 17; i++) {
const t = i / 16;
positions[i * 3] =
narrow.center - narrow.gap * 0.5 + t * narrow.gap;
positions[i * 3 + 1] =
0.64 + Math.sin(t * Math.PI) * 0.42;
positions[i * 3 + 2] = 0;
}
archGeometry.attributes.position.needsUpdate = true;
}
updateOpeningMeshes();
// ---------------------------------------------------------------------
// Instanced grains and motion streaks
// ---------------------------------------------------------------------
const MAX_GRAINS = GRAINS_PER_CHANNEL * channels.length;
const grainGeometry = new THREE.SphereGeometry(GRAIN_RADIUS, 18, 12);
const grainMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.36,
metalness: 0.08
});
const grainMesh = new THREE.InstancedMesh(
grainGeometry,
grainMaterial,
MAX_GRAINS
);
grainMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
grainMesh.frustumCulled = false;
grainMesh.renderOrder = 3;
world.add(grainMesh);
const shadowMesh = new THREE.InstancedMesh(
grainGeometry,
new THREE.MeshBasicMaterial({
color: 0x000000,
transparent: true,
opacity: 0.18,
depthWrite: false
}),
MAX_GRAINS
);
shadowMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
shadowMesh.frustumCulled = false;
world.add(shadowMesh);
const pathPositions = new Float32Array(MAX_GRAINS * 2 * 3);
const pathColors = new Float32Array(MAX_GRAINS * 2 * 3);
const pathGeometry = new THREE.BufferGeometry();
pathGeometry.setAttribute(
"position",
new THREE.BufferAttribute(pathPositions, 3)
);
pathGeometry.setAttribute(
"color",
new THREE.BufferAttribute(pathColors, 3)
);
const paths = new THREE.LineSegments(
pathGeometry,
new THREE.LineBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0.4,
depthWrite: false
})
);
paths.frustumCulled = false;
world.add(paths);
const dummy = new THREE.Object3D();
const broadColor = new THREE.Color(0x58dfd1);
const narrowColor = new THREE.Color(0xffb45d);
const blockedColor = new THREE.Color(0xff7568);
// ---------------------------------------------------------------------
// Simulation state
// ---------------------------------------------------------------------
let bodies = [];
let seed = 7;
let random = mulberry32(seed);
let simulationTime = 0;
let accumulator = 0;
let paused = false;
let gravity = 3.2;
let playbackSpeed = 1;
function mulberry32(a) {
return function () {
let t = (a += 0x6d2b79f5);
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function overlaps(x, y, channelIndex, radius = GRAIN_RADIUS * 2.05) {
for (const body of bodies) {
if (body.channel !== channelIndex) continue;
const dx = body.x - x;
const dy = body.y - y;
if (dx * dx + dy * dy < radius * radius) return true;
}
return false;
}
function resetSimulation() {
random = mulberry32(seed);
bodies = [];
simulationTime = 0;
accumulator = 0;
for (const channel of channels) {
channel.crossings = 0;
channel.pauses = 0;
channel.lastCross = -100;
channel.status = channel.id === "broad" ? "quiet" : "waiting";
}
for (let channelIndex = 0; channelIndex < channels.length; channelIndex++) {
const channel = channels[channelIndex];
for (let i = 0; i < GRAINS_PER_CHANNEL; i++) {
let x = 0;
let y = 0;
let found = false;
for (let attempt = 0; attempt < 250; attempt++) {
x = THREE.MathUtils.lerp(
channel.xL + GRAIN_RADIUS + 0.08,
channel.xR - GRAIN_RADIUS - 0.08,
random()
);
y = 1.05 + random() * 3.65;
if (!overlaps(x, y, channelIndex)) {
found = true;
break;
}
}
if (!found) continue;
bodies.push({
id: bodies.length,
channel: channelIndex,
x,
y,
z: (random() - 0.5) * 0.38,
vx: (random() - 0.5) * 0.22,
vy: -random() * 0.3,
crossed: false,
tint: 0.86 + random() * 0.23
});
}
}
updateOpeningMeshes();
updateHud();
}
function recycle(body) {
const channel = channels[body.channel];
let found = false;
for (let attempt = 0; attempt < 60; attempt++) {
const x = THREE.MathUtils.lerp(
channel.xL + GRAIN_RADIUS + 0.08,
channel.xR - GRAIN_RADIUS - 0.08,
random()
);
const y = 4.52 + random() * 0.34;
if (!overlaps(x, y, body.channel)) {
body.x = x;
body.y = y;
found = true;
break;
}
}
if (!found) {
body.x = channel.center;
body.y = 5.0;
}
body.z = (random() - 0.5) * 0.38;
body.vx = (random() - 0.5) * 0.16;
body.vy = -0.25 - random() * 0.25;
body.crossed = false;
}
// Circle against an axis-aligned rectangular wall/shelf.
function collideRect(body, rect) {
const closestX = THREE.MathUtils.clamp(
body.x,
rect.minX,
rect.maxX
);
const closestY = THREE.MathUtils.clamp(
body.y,
rect.minY,
rect.maxY
);
let dx = body.x - closestX;
let dy = body.y - closestY;
let distanceSq = dx * dx + dy * dy;
if (distanceSq >= GRAIN_RADIUS * GRAIN_RADIUS) return;
let nx;
let ny;
let penetration;
if (distanceSq > 1e-12) {
const distance = Math.sqrt(distanceSq);
nx = dx / distance;
ny = dy / distance;
penetration = GRAIN_RADIUS - distance;
} else {
// The center is inside the rectangle: escape through the nearest face.
const toLeft = body.x - rect.minX;
const toRight = rect.maxX - body.x;
const toBottom = body.y - rect.minY;
const toTop = rect.maxY - body.y;
const nearest = Math.min(toLeft, toRight, toBottom, toTop);
if (nearest === toLeft) {
nx = -1;
ny = 0;
penetration = GRAIN_RADIUS + toLeft;
} else if (nearest === toRight) {
nx = 1;
ny = 0;
penetration = GRAIN_RADIUS + toRight;
} else if (nearest === toBottom) {
nx = 0;
ny = -1;
penetration = GRAIN_RADIUS + toBottom;
} else {
nx = 0;
ny = 1;
penetration = GRAIN_RADIUS + toTop;
}
}
body.x += nx * penetration;
body.y += ny * penetration;
const normalVelocity = body.vx * nx + body.vy * ny;
if (normalVelocity < 0) {
const restitution = 0.045;
body.vx -= (1 + restitution) * normalVelocity * nx;
body.vy -= (1 + restitution) * normalVelocity * ny;
// Tangential wall friction, deliberately modest and bounded.
const tx = -ny;
const ty = nx;
const tangentVelocity = body.vx * tx + body.vy * ty;
body.vx -= tangentVelocity * 0.16 * tx;
body.vy -= tangentVelocity * 0.16 * ty;
}
}
function resolveGrainPairs() {
const minimumDistance = GRAIN_RADIUS * 2;
for (let i = 0; i < bodies.length; i++) {
const a = bodies[i];
for (let j = i + 1; j < bodies.length; j++) {
const b = bodies[j];
if (a.channel !== b.channel) continue;
let dx = b.x - a.x;
let dy = b.y - a.y;
let distanceSq = dx * dx + dy * dy;
if (distanceSq >= minimumDistance * minimumDistance) continue;
let distance = Math.sqrt(distanceSq);
let nx;
let ny;
if (distance < 1e-8) {
const angle = ((a.id * 17 + b.id * 31) % 360) * Math.PI / 180;
nx = Math.cos(angle);
ny = Math.sin(angle);
distance = 0;
} else {
nx = dx / distance;
ny = dy / distance;
}
const overlap = minimumDistance - distance;
const correction = overlap * 0.51;
a.x -= nx * correction;
a.y -= ny * correction;
b.x += nx * correction;
b.y += ny * correction;
const rvx = b.vx - a.vx;
const rvy = b.vy - a.vy;
const normalVelocity = rvx * nx + rvy * ny;
if (normalVelocity < 0) {
const restitution = 0.08;
const impulse = (-(1 + restitution) * normalVelocity) / 2;
a.vx -= impulse * nx;
a.vy -= impulse * ny;
b.vx += impulse * nx;
b.vy += impulse * ny;
// Bounded Coulomb-like tangential impulse.
const tx = -ny;
const ty = nx;
const tangentVelocity =
(b.vx - a.vx) * tx + (b.vy - a.vy) * ty;
const frictionLimit = impulse * 0.22;
const frictionImpulse = THREE.MathUtils.clamp(
-tangentVelocity * 0.5,
-frictionLimit,
frictionLimit
);
a.vx -= frictionImpulse * tx;
a.vy -= frictionImpulse * ty;
b.vx += frictionImpulse * tx;
b.vy += frictionImpulse * ty;
}
}
}
}
function stepSimulation(dt) {
simulationTime += dt;
for (const body of bodies) {
body.vy -= gravity * dt;
body.vx *= 0.999;
body.x += body.vx * dt;
body.y += body.vy * dt;
}
resolveGrainPairs();
for (const body of bodies) {
const channel = channels[body.channel];
const gapLeft = channel.center - channel.gap * 0.5;
const gapRight = channel.center + channel.gap * 0.5;
const solids = [
{
minX: channel.xL - 0.075,
maxX: channel.xL + 0.075,
minY: -5.3,
maxY: 5.12
},
{
minX: channel.xR - 0.075,
maxX: channel.xR + 0.075,
minY: -5.3,
maxY: 5.12
},
{
minX: channel.xL,
maxX: gapLeft,
minY: SHELF_BOTTOM,
maxY: SHELF_TOP
},
{
minX: gapRight,
maxX: channel.xR,
minY: SHELF_BOTTOM,
maxY: SHELF_TOP
}
];
for (const solid of solids) {
collideRect(body, solid);
}
if (
!body.crossed &&
body.vy < 0 &&
body.y < SHELF_BOTTOM - 0.015 &&
body.x > gapLeft &&
body.x < gapRight
) {
body.crossed = true;
channel.crossings++;
channel.lastCross = simulationTime;
if (channel.status === "clogged") {
channel.status = "flowing";
}
}
if (body.y < RECYCLE_Y) {
recycle(body);
}
}
assessFlow();
}
function assessFlow() {
const broad = channels[0];
const narrow = channels[1];
broad.status =
simulationTime - broad.lastCross < 1.35 ? "flowing" : "quiet";
const nearOpening = bodies.filter((body) => {
if (body.channel !== 1) return false;
const channel = narrow;
return (
body.x > channel.center - channel.gap * 0.5 - GRAIN_RADIUS &&
body.x < channel.center + channel.gap * 0.5 + GRAIN_RADIUS &&
body.y > SHELF_BOTTOM - GRAIN_RADIUS &&
body.y < 1.45
);
});
const likelyBlocked =
simulationTime - narrow.lastCross > 1.9 &&
nearOpening.length >= 2;
if (likelyBlocked && narrow.status !== "clogged") {
narrow.status = "clogged";
narrow.pauses++;
} else if (narrow.status === "clogged" && !likelyBlocked) {
narrow.status = "flowing";
} else if (narrow.status !== "clogged") {
narrow.status =
simulationTime - narrow.lastCross < 1.35
? "flowing"
: "intermittent";
}
}
// ---------------------------------------------------------------------
// Visual updates
// ---------------------------------------------------------------------
function updateVisuals() {
grainMesh.count = bodies.length;
shadowMesh.count = bodies.length;
for (let i = 0; i < bodies.length; i++) {
const body = bodies[i];
const channel = channels[body.channel];
dummy.position.set(body.x, body.y, body.z);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
grainMesh.setMatrixAt(i, dummy.matrix);
dummy.position.set(body.x + 0.055, body.y - 0.065, -0.57);
dummy.scale.set(1.03, 1.03, 0.55);
dummy.updateMatrix();
shadowMesh.setMatrixAt(i, dummy.matrix);
const nearNarrowOpening =
body.channel === 1 &&
Math.abs(body.x - channel.center) <
channel.gap * 0.5 + GRAIN_RADIUS &&
body.y > SHELF_BOTTOM - GRAIN_RADIUS &&
body.y < 1.45;
const baseColor =
body.channel === 0 ? broadColor : narrowColor;
const color =
body.channel === 1 &&
nearNarrowOpening &&
channel.status === "clogged"
? blockedColor
: baseColor;
color.multiplyScalar(body.tint);
grainMesh.setColorAt(i, color);
const p = i * 6;
const trailLength = 0.075;
pathPositions[p] = body.x - body.vx * trailLength;
pathPositions[p + 1] = body.y - body.vy * trailLength;
pathPositions[p + 2] = body.z - 0.02;
pathPositions[p + 3] = body.x;
pathPositions[p + 4] = body.y;
pathPositions[p + 5] = body.z;
const pathColor =
body.channel === 1 && channel.status === "clogged"
? blockedColor
: baseColor;
pathColors[p] = pathColor.r;
pathColors[p + 1] = pathColor.g;
pathColors[p + 2] = pathColor.b;
pathColors[p + 3] = pathColor.r;
pathColors[p + 4] = pathColor.g;
pathColors[p + 5] = pathColor.b;
}
grainMesh.instanceMatrix.needsUpdate = true;
shadowMesh.instanceMatrix.needsUpdate = true;
if (grainMesh.instanceColor) {
grainMesh.instanceColor.needsUpdate = true;
}
pathGeometry.attributes.position.needsUpdate = true;
pathGeometry.attributes.color.needsUpdate = true;
paths.visible = document.getElementById("paths").checked;
const narrow = channels[1];
const narrowColorNow =
narrow.status === "clogged" ? blockedColor : narrowColor;
narrow.visual.glowMaterial.color.copy(narrowColorNow);
narrow.visual.glowMaterial.opacity =
narrow.status === "clogged"
? 0.78 + Math.sin(simulationTime * 5) * 0.16
: 0.66;
archCue.visible = narrow.status === "clogged";
}
function updateHud() {
const broad = channels[0];
const narrow = channels[1];
document.getElementById("broadCount").textContent = broad.crossings;
document.getElementById("narrowCount").textContent = narrow.crossings;
document.getElementById("pauseCount").textContent = narrow.pauses;
document.getElementById("modelTime").textContent =
`${simulationTime.toFixed(1)} s`;
document.getElementById("seedValue").textContent = seed;
const broadState =
broad.status === "flowing" ? "recent flow" : "low throughput";
const narrowState =
narrow.status === "clogged"
? "arch-like pause"
: narrow.status;
document.getElementById("broadState").textContent = broadState;
document.getElementById("narrowState").textContent = narrowState;
document.getElementById("broadLabelState").textContent = broadState;
const narrowLabelState =
narrow.status === "clogged"
? "arch-like pause"
: narrow.status === "flowing"
? "grain-by-grain flow"
: "between crossings";
document.getElementById("narrowLabelState").textContent =
narrowLabelState;
const statusText =
narrow.status === "clogged"
? "Arch-like pause detected"
: narrow.status === "flowing"
? "Recent grain-by-grain flow"
: "Between crossings";
document.getElementById("narrowStatus").textContent = statusText;
document
.getElementById("narrowDot")
.classList.toggle("blocked", narrow.status === "clogged");
}
// ---------------------------------------------------------------------
// Camera controls implemented without addons
// ---------------------------------------------------------------------
const orbit = {
theta: -0.08,
phi: Math.PI / 2,
zoom: 1
};
const cameraTarget = new THREE.Vector3(0, 0, 0);
let baseRadius = 17.4;
let dragging = false;
let pointerX = 0;
let pointerY = 0;
function updateCamera() {
const radius = baseRadius * orbit.zoom;
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
cameraTarget.x + radius * sinPhi * Math.sin(orbit.theta),
cameraTarget.y + radius * Math.cos(orbit.phi),
cameraTarget.z + radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(cameraTarget);
camera.updateMatrixWorld();
}
function resetView() {
orbit.theta = -0.08;
orbit.phi = Math.PI / 2;
orbit.zoom = 1;
updateCamera();
}
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
canvas.classList.add("dragging");
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
orbit.theta = THREE.MathUtils.clamp(
orbit.theta - dx * 0.005,
-0.8,
0.8
);
orbit.phi = THREE.MathUtils.clamp(
orbit.phi - dy * 0.004,
1.27,
1.82
);
updateCamera();
});
function endDrag(event) {
dragging = false;
canvas.classList.remove("dragging");
if (event.pointerId !== undefined && canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.zoom = THREE.MathUtils.clamp(
orbit.zoom * Math.exp(event.deltaY * 0.001),
0.72,
1.42
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetView);
const broadAnchor = new THREE.Vector3(-3, 5.48, 0.25);
const narrowAnchor = new THREE.Vector3(3, 5.48, 0.25);
function positionLabel(element, worldPosition) {
const projected = worldPosition.clone().project(camera);
element.style.left = `${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
element.style.top = `${(-projected.y * 0.5 + 0.5) * window.innerHeight}px`;
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height, false);
camera.aspect = aspect;
camera.updateProjectionMatrix();
if (aspect < 0.8) {
baseRadius = 30;
} else if (aspect < 1.2) {
baseRadius = 23;
} else {
baseRadius = 17.4;
}
updateCamera();
}
window.addEventListener("resize", resize);
// ---------------------------------------------------------------------
// UI events
// ---------------------------------------------------------------------
const gapInput = document.getElementById("gap");
const gapOutput = document.getElementById("gapOutput");
const gravityInput = document.getElementById("gravity");
const gravityOutput = document.getElementById("gravityOutput");
const speedInput = document.getElementById("speed");
const speedOutput = document.getElementById("speedOutput");
const pauseButton = document.getElementById("pause");
let gapResetTimer = null;
gapInput.addEventListener("input", () => {
const ratio = parseFloat(gapInput.value);
gapOutput.textContent = `${ratio.toFixed(1)} d`;
document.getElementById("narrowRatio").textContent =
`${ratio.toFixed(1)} d`;
channels[1].gap = ratio * GRAIN_DIAMETER;
updateOpeningMeshes();
clearTimeout(gapResetTimer);
gapResetTimer = setTimeout(() => resetSimulation(), 100);
});
gravityInput.addEventListener("input", () => {
gravity = parseFloat(gravityInput.value);
gravityOutput.textContent = `${gravity.toFixed(1)} units/s²`;
});
speedInput.addEventListener("input", () => {
playbackSpeed = parseFloat(speedInput.value);
speedOutput.textContent = `${playbackSpeed.toFixed(2).replace(/0$/, "")}×`;
});
pauseButton.addEventListener("click", () => {
paused = !paused;
pauseButton.textContent = paused ? "Resume" : "Pause";
});
document.getElementById("reset").addEventListener("click", () => {
resetSimulation();
});
document.getElementById("seed").addEventListener("click", () => {
seed++;
resetSimulation();
});
document.getElementById("view").addEventListener("click", resetView);
window.addEventListener("keydown", (event) => {
if (
event.target instanceof HTMLInputElement ||
event.target instanceof HTMLButtonElement
) {
return;
}
if (event.code === "Space") {
event.preventDefault();
pauseButton.click();
} else if (event.key.toLowerCase() === "r") {
resetSimulation();
}
});
// ---------------------------------------------------------------------
// Animation loop
// ---------------------------------------------------------------------
let previousTime = performance.now();
let lastHudUpdate = 0;
function animate(now) {
requestAnimationFrame(animate);
const frameDelta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (!paused) {
accumulator += frameDelta * playbackSpeed;
let steps = 0;
while (accumulator >= FIXED_DT && steps < 12) {
stepSimulation(FIXED_DT);
accumulator -= FIXED_DT;
steps++;
}
}
updateVisuals();
if (now - lastHudUpdate > 90) {
updateHud();
lastHudUpdate = now;
}
positionLabel(document.getElementById("broadLabel"), broadAnchor);
positionLabel(document.getElementById("narrowLabel"), narrowAnchor);
renderer.render(scene, camera);
}
document.addEventListener("visibilitychange", () => {
previousTime = performance.now();
});
resize();
resetSimulation();
requestAnimationFrame(animate);
</script>
</body>
</html>
```