Prompt specification
Build or customize the Three.js 3D scene "Diffusion through a narrow connector" 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: Diffusion through a narrow connector
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/diffusion-through-a-narrow-connector-x0838
Scene Description Prompt:
Diffusion through a narrow connector. Join two particle chambers with a short passage; animate random motion through the opening and plot population counts, distinguishing individual randomness from average spreading. Please build this with Three.js from cdnjs in one self-contained HTML file, using stylized solid shapes.
Working Three.js Starter (diffusion-through-a-narrow-connector-x0838):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Diffusion Through a Narrow Connector</title>
<style>
:root {
--bg: #09111e;
--panel: #111c2d;
--panel-2: #162338;
--line: #26364c;
--text: #edf3fb;
--muted: #93a5bd;
--left: #ff7657;
--right: #48d7bd;
--mean: #f5ca69;
--radius: 18px;
}
* { box-sizing: border-box; }
body {
margin: 0;
min-width: 320px;
min-height: 100vh;
color: var(--text);
background:
radial-gradient(circle at 15% 0%, #172944 0, transparent 38%),
var(--bg);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input { font: inherit; }
button {
color: var(--text);
border: 1px solid var(--line);
background: var(--panel-2);
border-radius: 10px;
padding: 9px 13px;
cursor: pointer;
transition: border-color 150ms ease, background 150ms ease, transform 150ms ease;
}
button:hover {
border-color: #4d6687;
background: #1c2c43;
}
button:active { transform: translateY(1px); }
button.primary {
color: #08131e;
border-color: var(--right);
background: var(--right);
font-weight: 750;
}
input[type="range"] {
accent-color: var(--right);
cursor: pointer;
}
input[type="checkbox"] {
width: 16px;
height: 16px;
accent-color: var(--right);
}
.app {
width: min(1500px, 100%);
margin: 0 auto;
padding: 24px;
}
header {
display: flex;
justify-content: space-between;
align-items: flex-end;
gap: 28px;
margin-bottom: 20px;
}
.eyebrow {
margin: 0 0 8px;
color: var(--right);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(28px, 4vw, 52px);
line-height: 1;
letter-spacing: -0.045em;
}
.subtitle {
max-width: 650px;
margin: 12px 0 0;
color: var(--muted);
line-height: 1.55;
}
.header-note {
max-width: 330px;
padding: 14px 16px;
border: 1px solid var(--line);
border-radius: 14px;
color: #b8c6d8;
background: rgba(17, 28, 45, 0.72);
font-size: 13px;
line-height: 1.5;
}
.header-note strong { color: var(--text); }
.layout {
display: grid;
grid-template-columns: minmax(0, 1fr) 390px;
gap: 18px;
align-items: start;
}
.stage-card,
.panel {
overflow: hidden;
border: 1px solid var(--line);
border-radius: var(--radius);
background: var(--panel);
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
}
.stage {
position: relative;
height: clamp(440px, 63vh, 690px);
min-height: 420px;
overflow: hidden;
background: #0c1524;
}
.stage canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
.stage canvas:active { cursor: grabbing; }
.stage-hud {
position: absolute;
z-index: 3;
top: 16px;
left: 16px;
display: flex;
gap: 8px;
pointer-events: none;
}
.chip {
display: inline-flex;
align-items: center;
min-height: 30px;
padding: 6px 10px;
border: 1px solid rgba(150, 175, 207, 0.18);
border-radius: 999px;
color: #c9d5e5;
background: rgba(7, 14, 25, 0.72);
backdrop-filter: blur(8px);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.03em;
}
.scene-legend {
position: absolute;
z-index: 3;
top: 16px;
right: 16px;
display: flex;
gap: 12px;
flex-wrap: wrap;
justify-content: flex-end;
max-width: 340px;
pointer-events: none;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
color: #b8c7d9;
font-size: 11px;
}
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 12px currentColor;
}
.dot.left { color: var(--left); }
.dot.right { color: var(--right); }
.dot.passage { color: var(--mean); }
.orbit-hint {
position: absolute;
z-index: 3;
right: 15px;
bottom: 14px;
color: #8497b1;
font-size: 11px;
pointer-events: none;
}
.world-label {
position: absolute;
z-index: 2;
transform: translate(-50%, -50%);
padding: 6px 9px;
border: 1px solid rgba(179, 201, 227, 0.17);
border-radius: 8px;
color: #dce7f5;
background: rgba(9, 17, 30, 0.76);
box-shadow: 0 8px 22px rgba(0, 0, 0, 0.18);
backdrop-filter: blur(6px);
text-align: center;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
pointer-events: none;
white-space: nowrap;
}
.world-label small {
display: block;
margin-top: 3px;
color: #91a3ba;
font-size: 9px;
font-weight: 600;
letter-spacing: 0;
}
.control-strip {
display: flex;
align-items: center;
gap: 16px;
flex-wrap: wrap;
padding: 14px 16px;
border-top: 1px solid var(--line);
background: #101b2b;
}
.control-strip label {
display: flex;
align-items: center;
gap: 8px;
color: #aebed1;
font-size: 12px;
}
.range-control {
display: grid;
grid-template-columns: auto 105px auto;
align-items: center;
gap: 9px;
}
.range-control output {
min-width: 42px;
color: var(--text);
font-variant-numeric: tabular-nums;
text-align: right;
}
.switch {
position: relative;
}
aside {
display: grid;
gap: 18px;
}
.panel { padding: 18px; }
.panel-head {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 12px;
margin-bottom: 14px;
}
.panel-head h2 {
margin: 0;
font-size: 16px;
letter-spacing: -0.015em;
}
.panel-head p {
margin: 5px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.population-stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin-bottom: 14px;
}
.population-stat {
padding: 10px;
border: 1px solid var(--line);
border-radius: 12px;
background: #0e1828;
}
.population-stat span {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
}
.population-stat strong {
font-size: 21px;
font-variant-numeric: tabular-nums;
}
.population-stat.left strong { color: var(--left); }
.population-stat.right strong { color: var(--right); }
.population-stat.passage strong { color: var(--mean); }
.chart-wrap {
width: 100%;
min-height: 250px;
border: 1px solid var(--line);
border-radius: 13px;
overflow: hidden;
background: #0d1726;
}
#populationChart {
display: block;
width: 100%;
height: auto;
}
#populationChart .grid-line {
stroke: #26364a;
stroke-width: 1;
vector-effect: non-scaling-stroke;
}
#populationChart .axis-text {
fill: #8295ad;
font-size: 10px;
font-family: inherit;
}
#populationChart .series {
fill: none;
stroke-linecap: round;
stroke-linejoin: round;
vector-effect: non-scaling-stroke;
}
#populationChart .left-series { stroke: var(--left); stroke-width: 2.2; }
#populationChart .right-series { stroke: var(--right); stroke-width: 2.2; }
#populationChart .mean-series {
stroke: var(--mean);
stroke-width: 2;
stroke-dasharray: 7 6;
opacity: 0.95;
}
.chart-legend {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin: 12px 1px 0;
}
.chart-legend span {
display: flex;
align-items: center;
gap: 6px;
color: #9fb0c5;
font-size: 10px;
}
.line-key {
width: 19px;
height: 0;
border-top: 2px solid currentColor;
}
.line-key.dashed { border-top-style: dashed; }
.metric-title {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.metric-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin-top: 15px;
color: #b7c5d7;
font-size: 12px;
}
.metric-row strong {
color: var(--text);
font-size: 15px;
font-variant-numeric: tabular-nums;
}
.spread-track {
position: relative;
height: 9px;
margin-top: 9px;
overflow: visible;
border-radius: 99px;
background: #26354a;
}
#actualSpread {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #2eaf99, var(--right));
transition: width 120ms linear;
}
#meanMarker {
position: absolute;
top: -4px;
left: 0;
width: 2px;
height: 17px;
border-radius: 2px;
background: var(--mean);
box-shadow: 0 0 9px rgba(245, 202, 105, 0.45);
transition: left 120ms linear;
}
.metric-key {
display: flex;
justify-content: space-between;
margin-top: 8px;
color: #7f92aa;
font-size: 10px;
}
.comparison {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin-top: 16px;
}
.comparison-card {
padding: 12px;
border: 1px solid var(--line);
border-radius: 12px;
background: #0e1828;
}
.comparison-card h3 {
display: flex;
align-items: center;
gap: 7px;
margin: 0 0 7px;
font-size: 12px;
}
.comparison-card p {
margin: 0;
color: #91a3ba;
font-size: 10px;
line-height: 1.55;
}
.solid-key,
.dashed-key {
display: inline-block;
width: 18px;
border-top: 2px solid var(--right);
}
.solid-key.coral { border-color: var(--left); }
.dashed-key { border-color: var(--mean); border-top-style: dashed; }
.small-note {
margin: 14px 0 0;
padding-top: 13px;
border-top: 1px solid var(--line);
color: #8094ad;
font-size: 10px;
line-height: 1.55;
}
footer {
margin-top: 15px;
color: #61748d;
font-size: 10px;
text-align: right;
}
@media (max-width: 1050px) {
.layout { grid-template-columns: 1fr; }
aside { grid-template-columns: 1fr 1fr; }
aside .small-note { grid-column: 1 / -1; }
}
@media (max-width: 720px) {
.app { padding: 14px; }
header { align-items: flex-start; flex-direction: column; }
.header-note { max-width: none; }
.stage { height: 54vh; min-height: 380px; }
.scene-legend { top: 54px; left: 16px; right: auto; justify-content: flex-start; }
aside { grid-template-columns: 1fr; }
.control-strip { gap: 11px; }
.range-control { grid-template-columns: auto 88px auto; }
.comparison { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<div class="app">
<header>
<div>
<p class="eyebrow">Stochastic transport laboratory</p>
<h1>Diffusion through a narrow connector</h1>
<p class="subtitle">
Each tracer follows its own random path through a constricted passage.
Solid population curves show one finite realization; the dashed curve
shows the smooth average expected for equivalent unbiased walkers.
</p>
</div>
<div class="header-note">
<strong>Individual randomness ≠ collective spreading.</strong><br>
A tracer may cross early, late, or not at all, while the chamber
population changes according to an average diffusion trend.
</div>
</header>
<main class="layout">
<section class="stage-card" aria-label="Interactive particle simulation">
<div class="stage" id="stage">
<div class="stage-hud">
<span class="chip" id="tracerChip">140 tracers</span>
<span class="chip" id="clockChip">t = 00:00.0</span>
</div>
<div class="scene-legend">
<span class="legend-item"><i class="dot left"></i>Left chamber</span>
<span class="legend-item"><i class="dot passage"></i>Passage</span>
<span class="legend-item"><i class="dot right"></i>Right chamber</span>
</div>
<div class="world-label" id="leftWorldLabel">
LEFT CHAMBER
<small id="leftLabelCount">0 tracers</small>
</div>
<div class="world-label" id="connectorWorldLabel">
NARROW CONNECTOR
<small>stochastic bottleneck</small>
</div>
<div class="world-label" id="rightWorldLabel">
RIGHT CHAMBER
<small id="rightLabelCount">0 tracers</small>
</div>
<div class="orbit-hint">Drag to orbit · scroll to zoom</div>
</div>
<div class="control-strip">
<button class="primary" id="playButton" type="button">Pause</button>
<button id="resetButton" type="button">Reset</button>
<label class="range-control">
<span>Tracers</span>
<input id="countInput" type="range" min="60" max="240" step="10" value="140">
<output id="countValue">140</output>
</label>
<label class="range-control">
<span>Speed</span>
<input id="speedInput" type="range" min="0.4" max="2.6" step="0.1" value="1">
<output id="speedValue">1.0×</output>
</label>
<label class="switch">
<input id="trailsToggle" type="checkbox" checked>
Trails
</label>
<label class="switch">
<input id="meanToggle" type="checkbox" checked>
Mean overlay
</label>
</div>
</section>
<aside>
<section class="panel">
<div class="panel-head">
<div>
<h2>Population balance</h2>
<p>Counts sampled four times per simulated second.</p>
</div>
</div>
<div class="population-stats">
<div class="population-stat left">
<span>LEFT</span>
<strong id="leftCount">140</strong>
</div>
<div class="population-stat passage">
<span>PASSAGE</span>
<strong id="passageCount">0</strong>
</div>
<div class="population-stat right">
<span>RIGHT</span>
<strong id="rightCount">0</strong>
</div>
</div>
<div class="chart-wrap">
<svg id="populationChart" viewBox="0 0 640 270" role="img"
aria-label="Population counts over time">
<defs>
<clipPath id="plotClip">
<rect x="54" y="18" width="570" height="214"></rect>
</clipPath>
</defs>
<g id="chartGrid"></g>
<g clip-path="url(#plotClip)">
<path id="meanPath" class="series mean-series"></path>
<path id="leftPath" class="series left-series"></path>
<path id="rightPath" class="series right-series"></path>
</g>
<g id="chartAxis"></g>
</svg>
</div>
<div class="chart-legend">
<span><i class="line-key coral"></i>Left, this run</span>
<span><i class="line-key"></i>Right, this run</span>
<span><i class="line-key dashed"></i>Mean-field right</span>
</div>
</section>
<section class="panel">
<div class="metric-title">Right-side spread</div>
<div class="metric-row">
<span>Actual population</span>
<strong id="actualShare">0%</strong>
</div>
<div class="spread-track">
<div id="actualSpread"></div>
<div id="meanMarker" title="Mean-field estimate"></div>
</div>
<div class="metric-key">
<span>Actual fill</span>
<span>Gold tick = mean</span>
</div>
<div class="metric-row">
<span>Mean-field estimate</span>
<strong id="meanShare">0%</strong>
</div>
<div class="comparison">
<div class="comparison-card">
<h3><i class="solid-key coral"></i>Individual randomness</h3>
<p>
Solid lines record one finite sample. Crossing times differ,
so the population curves are jagged and may briefly reverse.
</p>
</div>
<div class="comparison-card">
<h3><i class="dashed-key"></i>Average spreading</h3>
<p>
The gold dashed line is a symmetric mean-field forecast:
the expected population over many equivalent random runs.
</p>
</div>
</div>
<p class="small-note">
Tracers are treated as independent point-like walkers with momentum,
random acceleration, and elastic wall collisions. The mean-field
curve is a reference model, not a second measured realization.
</p>
</section>
</aside>
</main>
<footer>
Three.js core · custom camera controls · no external assets
</footer>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = id => document.getElementById(id);
const stage = $("stage");
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute("aria-label", "Three-dimensional particle diffusion simulation");
stage.prepend(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0c1524);
scene.fog = new THREE.Fog(0x0c1524, 18, 31);
const camera = new THREE.PerspectiveCamera(38, 1, 0.1, 80);
const cameraTarget = new THREE.Vector3(0, 2.8, 0);
const cameraState = {
yaw: 0,
pitch: 0.08,
radius: 18.8
};
function updateCamera() {
const { yaw, pitch, radius } = cameraState;
camera.position.set(
cameraTarget.x + radius * Math.sin(yaw) * Math.cos(pitch),
cameraTarget.y + radius * Math.sin(pitch),
cameraTarget.z + radius * Math.cos(yaw) * Math.cos(pitch)
);
camera.lookAt(cameraTarget);
}
updateCamera();
scene.add(new THREE.HemisphereLight(0xd9e8ff, 0x08101d, 1.65));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.5);
keyLight.position.set(5, 10, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -11;
keyLight.shadow.camera.right = 11;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -6;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 30;
scene.add(keyLight);
const passageLight = new THREE.PointLight(0xf5ca69, 9, 7, 2);
passageLight.position.set(0, 2.8, 2.3);
scene.add(passageLight);
const materials = {
base: new THREE.MeshStandardMaterial({
color: 0x293a52, roughness: 0.72, metalness: 0.08
}),
back: new THREE.MeshStandardMaterial({
color: 0x172338, roughness: 0.9, metalness: 0.02
}),
wall: new THREE.MeshStandardMaterial({
color: 0x35465e, roughness: 0.65, metalness: 0.08
}),
divider: new THREE.MeshStandardMaterial({
color: 0x41536c, roughness: 0.6, metalness: 0.1
}),
passage: new THREE.MeshStandardMaterial({
color: 0x806b42, roughness: 0.58, metalness: 0.14
}),
gold: new THREE.MeshStandardMaterial({
color: 0xf5ca69,
emissive: 0x6b4d12,
emissiveIntensity: 0.48,
roughness: 0.38,
metalness: 0.25
})
};
function makeBox(width, height, depth, x, y, z, material) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
return mesh;
}
const bulkL = -1.55;
const bulkR = 1.55;
const apertureBottom = 2.15;
const apertureTop = 3.35;
// Shared base and chamber floors.
makeBox(16.6, 0.38, 1.4, 0, 0.02, -0.08, materials.base);
// Dark solid back panels make the chambers read as cutaway volumes.
makeBox(6.25, 6.0, 0.25, -4.84, 3.0, -0.62, materials.back);
makeBox(6.25, 6.0, 0.25, 4.84, 3.0, -0.62, materials.back);
makeBox(3.10, 1.20, 0.25, 0.00, 2.75, -0.62, materials.back);
// Outer walls and top rails.
makeBox(0.36, 6.0, 1.0, -8.12, 3.0, -0.18, materials.wall);
makeBox(0.36, 6.0, 1.0, 8.12, 3.0, -0.18, materials.wall);
makeBox(6.45, 0.18, 0.48, -4.84, 6.02, -0.20, materials.wall);
makeBox(6.45, 0.18, 0.48, 4.84, 6.02, -0.20, materials.wall);
// Vertical bulkheads, each split around the narrow opening.
for (const x of [bulkL, bulkR]) {
makeBox(0.34, 2.15, 0.68, x, 1.075, -0.18, materials.divider);
makeBox(0.34, 2.65, 0.68, x, 4.675, -0.18, materials.divider);
}
// Solid floor and ceiling of the connector.
makeBox(3.10, 0.24, 1.05, 0, 2.03, -0.14, materials.passage);
makeBox(3.10, 0.24, 1.05, 0, 3.47, -0.14, materials.passage);
// Gold jambs emphasize the constriction.
makeBox(0.07, 1.20, 0.08, bulkL, 2.75, 0.20, materials.gold);
makeBox(0.07, 1.20, 0.08, bulkR, 2.75, 0.20, materials.gold);
// -------------------------------------------------------------------------
// Particle simulation
// -------------------------------------------------------------------------
const MAX_PARTICLES = 240;
const PARTICLE_RADIUS = 0.13;
const CLEAR_MIN_Y = apertureBottom + PARTICLE_RADIUS;
const CLEAR_MAX_Y = apertureTop - PARTICLE_RADIUS;
const TRAIL_LENGTH = 7;
const particleGeometry = new THREE.IcosahedronGeometry(PARTICLE_RADIUS, 1);
const particleMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.42,
metalness: 0.05,
flatShading: true
});
const particleMesh = new THREE.InstancedMesh(
particleGeometry,
particleMaterial,
MAX_PARTICLES
);
particleMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
particleMesh.castShadow = true;
particleMesh.receiveShadow = true;
particleMesh.frustumCulled = false;
scene.add(particleMesh);
const trailVertexCapacity = MAX_PARTICLES * (TRAIL_LENGTH - 1) * 2;
const trailPositions = new Float32Array(trailVertexCapacity * 3);
const trailColors = new Float32Array(trailVertexCapacity * 3);
const trailGeometry = new THREE.BufferGeometry();
trailGeometry.setAttribute(
"position",
new THREE.BufferAttribute(trailPositions, 3).setUsage(THREE.DynamicDrawUsage)
);
trailGeometry.setAttribute(
"color",
new THREE.BufferAttribute(trailColors, 3).setUsage(THREE.DynamicDrawUsage)
);
const trailMaterial = new THREE.LineBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0.38,
depthWrite: false
});
const trailLines = new THREE.LineSegments(trailGeometry, trailMaterial);
trailLines.frustumCulled = false;
scene.add(trailLines);
const COLORS = {
left: new THREE.Color(0xff7657),
passage: new THREE.Color(0xf5ca69),
right: new THREE.Color(0x48d7bd)
};
const dummy = new THREE.Object3D();
const particles = [];
let particleCount = 140;
let running = true;
let elapsed = 0;
let speed = 1;
let simulationAccumulator = 0;
let trailAccumulator = 0;
let sampleAccumulator = 0;
let completedCrossings = 0;
let returnCrossings = 0;
let leftPopulation = particleCount;
let passagePopulation = 0;
let rightPopulation = 0;
function randomBetween(min, max) {
return min + Math.random() * (max - min);
}
function initializeParticle(p, index) {
p.x = randomBetween(-7.60, -1.95);
p.y = randomBetween(0.48, 5.52);
p.z = randomBetween(0.29, 0.46);
const angle = randomBetween(0, Math.PI * 2);
const velocity = randomBetween(0.65, 1.30);
p.vx = Math.cos(angle) * velocity;
p.vy = Math.sin(angle) * velocity;
p.state = "left";
p.color = COLORS.left.clone().offsetHSL(
randomBetween(-0.018, 0.018),
randomBetween(-0.04, 0.03),
randomBetween(-0.04, 0.04)
);
p.trail = Array.from({ length: TRAIL_LENGTH }, () => ({
x: p.x,
y: p.y
}));
p.phase = index * 0.73;
}
function resetSimulation() {
particleCount = Number($("countInput").value);
$("countValue").textContent = particleCount;
particles.length = 0;
for (let i = 0; i < particleCount; i++) {
const p = {};
initializeParticle(p, i);
particles.push(p);
particleMesh.setColorAt(i, p.color);
}
particleMesh.count = particleCount;
particleMesh.instanceMatrix.needsUpdate = true;
if (particleMesh.instanceColor) {
particleMesh.instanceColor.needsUpdate = true;
}
elapsed = 0;
simulationAccumulator = 0;
trailAccumulator = 0;
sampleAccumulator = 0;
completedCrossings = 0;
returnCrossings = 0;
history = [{
t: 0,
left: particleCount,
passage: 0,
right: 0
}];
updateParticlesVisual(0);
updateTrailGeometry();
updatePopulationCounts();
drawChart();
updateHud();
}
function insideAperture(y) {
return y >= CLEAR_MIN_Y && y <= CLEAR_MAX_Y;
}
function stepParticles(dt) {
const damping = Math.exp(-0.18 * dt);
const maxSpeed = 1.75;
for (const p of particles) {
const oldX = p.x;
const oldY = p.y;
// Random acceleration plus weak momentum gives visible, irregular paths.
p.vx += (Math.random() - 0.5) * 2.65 * dt;
p.vy += (Math.random() - 0.5) * 2.65 * dt;
p.vx *= damping;
p.vy *= damping;
const speedNow = Math.hypot(p.vx, p.vy);
if (speedNow > maxSpeed) {
p.vx = p.vx / speedNow * maxSpeed;
p.vy = p.vy / speedNow * maxSpeed;
}
let newX = p.x + p.vx * dt;
let newY = p.y + p.vy * dt;
// Outer chamber walls.
if (newX < -7.82 + PARTICLE_RADIUS) {
newX = -7.82 + PARTICLE_RADIUS;
p.vx = Math.abs(p.vx);
}
if (newX > 7.82 - PARTICLE_RADIUS) {
newX = 7.82 - PARTICLE_RADIUS;
p.vx = -Math.abs(p.vx);
}
if (newY < 0.30 + PARTICLE_RADIUS) {
newY = 0.30 + PARTICLE_RADIUS;
p.vy = Math.abs(p.vy);
}
if (newY > 5.72 - PARTICLE_RADIUS) {
newY = 5.72 - PARTICLE_RADIUS;
p.vy = -Math.abs(p.vy);
}
// The two bulkheads can only be crossed through the opening.
for (const wall of [bulkL, bulkR]) {
const crossed =
(oldX < wall && newX > wall) ||
(oldX > wall && newX < wall);
if (!crossed) continue;
if (insideAperture(newY)) {
newX = oldX < wall
? wall + PARTICLE_RADIUS
: wall - PARTICLE_RADIUS;
if (wall === bulkL && oldX < wall) {
// Entering the passage from the left chamber.
} else if (wall === bulkL && oldX > wall) {
returnCrossings++;
} else if (wall === bulkR && oldX < wall) {
completedCrossings++;
}
} else {
newX = oldX < wall
? wall - PARTICLE_RADIUS
: wall + PARTICLE_RADIUS;
p.vx = -p.vx;
}
}
// While inside the connector, particles bounce from its floor/ceiling.
const insideConnector =
newX > bulkL + PARTICLE_RADIUS &&
newX < bulkR - PARTICLE_RADIUS;
if (insideConnector) {
if (oldY >= CLEAR_MIN_Y && newY < CLEAR_MIN_Y) {
newY = CLEAR_MIN_Y;
p.vy = Math.abs(p.vy);
} else if (oldY <= CLEAR_MAX_Y && newY > CLEAR_MAX_Y) {
newY = CLEAR_MAX_Y;
p.vy = -Math.abs(p.vy);
} else if (newY < CLEAR_MIN_Y) {
newY = CLEAR_MIN_Y;
p.vy = Math.abs(p.vy);
} else if (newY > CLEAR_MAX_Y) {
newY = CLEAR_MAX_Y;
p.vy = -Math.abs(p.vy);
}
}
p.x = newX;
p.y = newY;
if (p.x < bulkL) p.state = "left";
else if (p.x > bulkR) p.state = "right";
else p.state = "passage";
}
}
function updateParticlesVisual(dt) {
const colorBlend = 1 - Math.exp(-8 * Math.max(dt, 0));
for (let i = 0; i < particles.length; i++) {
const p = particles[i];
const target = COLORS[p.state];
p.color.lerp(target, colorBlend);
dummy.position.set(p.x, p.y, p.z);
dummy.rotation.set(
0,
elapsed * 0.45 + p.phase,
p.phase + elapsed * 0.25
);
const pulse = p.state === "passage"
? 1 + 0.08 * Math.sin(elapsed * 5 + p.phase)
: 1;
dummy.scale.setScalar(pulse);
dummy.updateMatrix();
particleMesh.setMatrixAt(i, dummy.matrix);
particleMesh.setColorAt(i, p.color);
}
particleMesh.instanceMatrix.needsUpdate = true;
if (particleMesh.instanceColor) {
particleMesh.instanceColor.needsUpdate = true;
}
}
function updateTrailGeometry() {
let vertex = 0;
for (let i = 0; i < particles.length; i++) {
const p = particles[i];
for (let j = 0; j < TRAIL_LENGTH - 1; j++) {
const a = p.trail[j];
const b = p.trail[j + 1];
trailPositions[vertex * 3] = a.x;
trailPositions[vertex * 3 + 1] = a.y;
trailPositions[vertex * 3 + 2] = 0.24;
trailColors[vertex * 3] = p.color.r;
trailColors[vertex * 3 + 1] = p.color.g;
trailColors[vertex * 3 + 2] = p.color.b;
vertex++;
trailPositions[vertex * 3] = b.x;
trailPositions[vertex * 3 + 1] = b.y;
trailPositions[vertex * 3 + 2] = 0.24;
trailColors[vertex * 3] = p.color.r;
trailColors[vertex * 3 + 1] = p.color.g;
trailColors[vertex * 3 + 2] = p.color.b;
vertex++;
}
}
trailGeometry.setDrawRange(0, vertex);
trailGeometry.attributes.position.needsUpdate = true;
trailGeometry.attributes.color.needsUpdate = true;
}
function sampleTrails() {
for (const p of particles) {
p.trail.pop();
p.trail.unshift({ x: p.x, y: p.y });
}
updateTrailGeometry();
}
function updatePopulationCounts() {
leftPopulation = 0;
passagePopulation = 0;
rightPopulation = 0;
for (const p of particles) {
if (p.state === "left") leftPopulation++;
else if (p.state === "passage") passagePopulation++;
else rightPopulation++;
}
}
// -------------------------------------------------------------------------
// Symmetric mean-field model
//
// States: left chamber, passage, right chamber.
// Rates are chosen for equal, unbiased transfer between symmetric chambers.
// -------------------------------------------------------------------------
const RATES = {
leftToPassage: 0.075,
passageToLeft: 0.075,
passageToRight: 0.32,
rightToPassage: 0.32
};
function meanDerivatives(s) {
const [left, passage, right] = s;
return [
-RATES.leftToPassage * left + RATES.passageToLeft * passage,
RATES.leftToPassage * left
- (RATES.passageToLeft + RATES.passageToRight) * passage
+ RATES.rightToPassage * right,
RATES.passageToRight * passage - RATES.rightToPassage * right
];
}
function addScaled(s, k, scale) {
return [
s[0] + k[0] * scale,
s[1] + k[1] * scale,
s[2] + k[2] * scale
];
}
function buildMeanModel(maxTime = 600) {
const samples = [];
let state = [1, 0, 0];
const dt = 0.05;
let t = 0;
samples.push({ t: 0, left: 1, passage: 0, right: 0 });
while (t < maxTime) {
const k1 = meanDerivatives(state);
const k2 = meanDerivatives(addScaled(state, k1, dt / 2));
const k3 = meanDerivatives(addScaled(state, k2, dt / 2));
const k4 = meanDerivatives(addScaled(state, k3, dt));
state = state.map((value, i) =>
value + dt * (k1[i] + 2 * k2[i] + 2 * k3[i] + k4[i]) / 6
);
t += dt;
if (samples.length === 0 || t - samples[samples.length - 1].t >= 0.25 - 1e-8) {
samples.push({
t,
left: state[0],
passage: state[1],
right: state[2]
});
}
}
return samples;
}
const meanModel = buildMeanModel();
function meanRightAt(time) {
if (time <= 0) return 0;
const index = Math.min(
meanModel.length - 2,
Math.max(0, Math.floor(time / 0.25))
);
const a = meanModel[index];
const b = meanModel[index + 1];
const fraction = (time - a.t) / Math.max(0.0001, b.t - a.t);
return a.right + (b.right - a.right) * fraction;
}
// -------------------------------------------------------------------------
// Chart
// -------------------------------------------------------------------------
const SVG_NS = "http://www.w3.org/2000/svg";
const chartGrid = $("chartGrid");
const chartAxis = $("chartAxis");
const leftPath = $("leftPath");
const rightPath = $("rightPath");
const meanPath = $("meanPath");
let history = [];
function chartScales() {
const width = 640;
const height = 270;
const margin = { left: 54, right: 16, top: 18, bottom: 38 };
const plotWidth = width - margin.left - margin.right;
const plotHeight = height - margin.top - margin.bottom;
const end = Math.max(60, elapsed);
const start = Math.max(0, end - 60);
const maxY = Math.max(10, particleCount);
return {
width, height, margin, plotWidth, plotHeight,
start, end, maxY,
x: t => margin.left + ((t - start) / (end - start)) * plotWidth,
y: value => margin.top + plotHeight - (value / maxY) * plotHeight
};
}
function makeSvgElement(tag, attrs = {}) {
const element = document.createElementNS(SVG_NS, tag);
for (const [key, value] of Object.entries(attrs)) {
element.setAttribute(key, value);
}
return element;
}
function pathForSamples(samples, accessor, scales) {
const points = [];
for (const sample of samples) {
const time = sample.t;
if (time < scales.start || time > scales.end) continue;
points.push(`${scales.x(time).toFixed(2)},${scales.y(accessor(sample)).toFixed(2)}`);
}
return points.length ? `M ${points.join(" L ")}` : "";
}
function drawChart() {
const scales = chartScales();
chartGrid.replaceChildren();
chartAxis.replaceChildren();
// Horizontal grid and y-axis labels.
for (let i = 0; i <= 4; i++) {
const value = scales.maxY * i / 4;
const y = scales.y(value);
chartGrid.appendChild(makeSvgElement("line", {
x1: scales.margin.left,
x2: scales.width - scales.margin.right,
y1: y,
y2: y,
class: "grid-line"
}));
const label = makeSvgElement("text", {
x: scales.margin.left - 9,
y: y + 3,
"text-anchor": "end",
class: "axis-text"
});
label.textContent = Math.round(value);
chartAxis.appendChild(label);
}
// Time labels.
const tickCount = 4;
for (let i = 0; i <= tickCount; i++) {
const time = scales.start + (scales.end - scales.start) * i / tickCount;
const x = scales.x(time);
chartAxis.appendChild(makeSvgElement("line", {
x1: x,
x2: x,
y1: scales.margin.top,
y2: scales.margin.top + scales.plotHeight,
class: "grid-line",
opacity: "0.28"
}));
const label = makeSvgElement("text", {
x,
y: scales.height - 15,
"text-anchor": i === 0 ? "start" : i === tickCount ? "end" : "middle",
class: "axis-text"
});
label.textContent = `${time.toFixed(0)}s`;
chartAxis.appendChild(label);
}
const populationLabel = makeSvgElement("text", {
x: 12,
y: 13,
class: "axis-text"
});
populationLabel.textContent = "tracers";
chartAxis.appendChild(populationLabel);
leftPath.setAttribute("d", pathForSamples(history, s => s.left, scales));
rightPath.setAttribute("d", pathForSamples(history, s => s.right, scales));
meanPath.setAttribute("d", pathForSamples(meanModel, s => s.right, scales));
meanPath.style.display = $("meanToggle").checked ? "" : "none";
}
function samplePopulation() {
history.push({
t: elapsed,
left: leftPopulation,
passage: passagePopulation,
right: rightPopulation
});
const earliest = Math.max(0, elapsed - 65);
while (history.length && history[0].t < earliest) history.shift();
drawChart();
}
// -------------------------------------------------------------------------
// HUD and controls
// -------------------------------------------------------------------------
function formatClock(seconds) {
const minutes = Math.floor(seconds / 60);
const remainder = seconds - minutes * 60;
return `${String(minutes).padStart(2, "0")}:${remainder.toFixed(1).padStart(4, "0")}`;
}
function updateHud() {
$("leftCount").textContent = leftPopulation;
$("passageCount").textContent = passagePopulation;
$("rightCount").textContent = rightPopulation;
$("tracerChip").textContent = `${particleCount} tracers`;
$("clockChip").textContent = `t = ${formatClock(elapsed)}`;
$("leftLabelCount").textContent = `${leftPopulation} tracers`;
$("rightLabelCount").textContent = `${rightPopulation} tracers`;
const actualFraction = rightPopulation / Math.max(1, particleCount);
const meanFraction = meanRightAt(elapsed);
$("actualShare").textContent = `${(actualFraction * 100).toFixed(1)}%`;
$("meanShare").textContent = `${(meanFraction * 100).toFixed(1)}%`;
$("actualSpread").style.width = `${actualFraction * 100}%`;
$("meanMarker").style.left = `${meanFraction * 100}%`;
}
$("playButton").addEventListener("click", () => {
running = !running;
$("playButton").textContent = running ? "Pause" : "Resume";
});
$("resetButton").addEventListener("click", resetSimulation);
$("countInput").addEventListener("input", () => {
$("countValue").textContent = $("countInput").value;
resetSimulation();
});
$("speedInput").addEventListener("input", () => {
speed = Number($("speedInput").value);
$("speedValue").textContent = `${speed.toFixed(1)}×`;
});
$("trailsToggle").addEventListener("change", () => {
trailLines.visible = $("trailsToggle").checked;
});
$("meanToggle").addEventListener("change", drawChart);
window.addEventListener("keydown", event => {
const tag = document.activeElement?.tagName;
if (["INPUT", "TEXTAREA", "SELECT"].includes(tag)) return;
if (event.code === "Space") {
event.preventDefault();
$("playButton").click();
}
if (event.key.toLowerCase() === "r") {
resetSimulation();
}
});
// -------------------------------------------------------------------------
// Direct camera controls: no Three.js addons
// -------------------------------------------------------------------------
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
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;
cameraState.yaw = THREE.MathUtils.clamp(
cameraState.yaw - dx * 0.004,
-0.38,
0.38
);
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.003,
-0.07,
0.36
);
});
function endDrag(event) {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.012,
13.5,
25
);
}, { passive: false });
renderer.domElement.addEventListener("contextmenu", event => event.preventDefault());
// -------------------------------------------------------------------------
// Projected labels and resize handling
// -------------------------------------------------------------------------
const worldLabels = [
{
element: $("leftWorldLabel"),
position: new THREE.Vector3(-4.75, 6.35, 0)
},
{
element: $("connectorWorldLabel"),
position: new THREE.Vector3(0, 3.95, 0)
},
{
element: $("rightWorldLabel"),
position: new THREE.Vector3(4.75, 6.35, 0)
}
];
const projected = new THREE.Vector3();
function updateWorldLabels() {
const width = stage.clientWidth;
const height = stage.clientHeight;
for (const item of worldLabels) {
projected.copy(item.position).project(camera);
const visible = projected.z > -1 && projected.z < 1;
item.element.style.display = visible ? "" : "none";
if (!visible) continue;
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
item.element.style.left = `${x}px`;
item.element.style.top = `${y}px`;
}
}
function resize() {
const width = stage.clientWidth;
const height = stage.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / Math.max(1, height);
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(stage);
resize();
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
const FIXED_STEP = 1 / 60;
let previousTime = performance.now();
function animate(now) {
requestAnimationFrame(animate);
const realDt = Math.min(0.05, (now - previousTime) / 1000);
previousTime = now;
if (running) {
const simulatedDt = realDt * speed;
simulationAccumulator += simulatedDt;
while (simulationAccumulator >= FIXED_STEP) {
stepParticles(FIXED_STEP);
elapsed += FIXED_STEP;
simulationAccumulator -= FIXED_STEP;
trailAccumulator += FIXED_STEP;
if (trailAccumulator >= 0.08) {
trailAccumulator -= 0.08;
sampleTrails();
}
sampleAccumulator += FIXED_STEP;
if (sampleAccumulator >= 0.25) {
sampleAccumulator -= 0.25;
updatePopulationCounts();
samplePopulation();
}
}
}
updateParticlesVisual(running ? realDt : 0);
updatePopulationCounts();
updateHud();
updateCamera();
updateWorldLabels();
renderer.render(scene, camera);
}
resetSimulation();
requestAnimationFrame(animate);
</script>
</body>
</html>
```