Prompt specification
Build or customize the Three.js 3D scene "Concentration and encounter-frequency 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: Concentration and encounter-frequency comparison
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/concentration-and-encounter-frequency-comparison-x1990
Scene Description Prompt:
Compare particle encounters in equal-volume cutaway toy chambers with different concentrations and identical motion rules. Three.js from cdnjs, standalone HTML.
Working Three.js Starter (concentration-and-encounter-frequency-comparison-x1990):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1"
/>
<title>Encounter Chambers</title>
<style>
:root {
color-scheme: light;
--ink: #243044;
--muted: #6f7888;
--panel: rgba(255, 255, 255, 0.82);
--line: rgba(56, 68, 88, 0.12);
--shadow: 0 14px 40px rgba(52, 61, 79, 0.12);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #f1eee8;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#app,
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.header {
position: absolute;
z-index: 5;
top: 24px;
left: 28px;
max-width: 510px;
pointer-events: none;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 8px;
color: #687386;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.eyebrow::before {
width: 24px;
height: 3px;
border-radius: 999px;
background: linear-gradient(
90deg,
#37c8b4 0 33%,
#f4b72d 33% 66%,
#ef6077 66%
);
content: "";
}
h1 {
margin: 0;
font-size: clamp(27px, 3.1vw, 44px);
font-weight: 760;
letter-spacing: -0.045em;
line-height: 1;
}
.subtitle {
max-width: 470px;
margin: 10px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.clock {
display: inline-flex;
align-items: center;
gap: 6px;
margin-top: 10px;
color: #7b8493;
font-size: 11px;
font-variant-numeric: tabular-nums;
}
.clock strong {
min-width: 39px;
color: #4f5b6d;
font-weight: 750;
}
.controls {
position: absolute;
z-index: 8;
top: 24px;
right: 26px;
display: grid;
grid-template-columns: repeat(3, auto);
gap: 7px;
padding: 8px;
border: 1px solid var(--line);
border-radius: 16px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
}
.controls button {
min-height: 34px;
padding: 0 12px;
border: 1px solid rgba(64, 76, 95, 0.12);
border-radius: 10px;
background: rgba(255, 255, 255, 0.92);
color: #3f4b5e;
font-size: 12px;
font-weight: 700;
cursor: pointer;
transition:
transform 120ms ease,
background 120ms ease,
border-color 120ms ease;
}
.controls button:hover {
transform: translateY(-1px);
border-color: rgba(64, 76, 95, 0.25);
background: #fff;
}
.controls button:active {
transform: translateY(0);
}
#pause {
min-width: 86px;
color: #fff;
border-color: transparent;
background: #344158;
}
#pause:hover {
background: #273249;
}
.tempo {
grid-column: 1 / -1;
display: flex;
align-items: center;
gap: 9px;
padding: 3px 5px 1px;
color: var(--muted);
font-size: 11px;
font-weight: 700;
}
.tempo input {
flex: 1;
min-width: 80px;
accent-color: #4a5870;
cursor: pointer;
}
.tempo output {
width: 36px;
color: #3f4b5e;
text-align: right;
font-variant-numeric: tabular-nums;
}
.rules {
grid-column: 1 / -1;
margin-top: 1px;
padding: 4px 5px 1px;
border-top: 1px solid rgba(64, 76, 95, 0.08);
color: #8a92a0;
font-size: 9px;
font-weight: 650;
letter-spacing: 0.02em;
text-align: center;
}
.legend {
position: absolute;
z-index: 5;
top: 28px;
left: 50%;
display: flex;
align-items: center;
gap: 15px;
transform: translateX(-50%);
color: #737d8c;
font-size: 10px;
font-weight: 700;
pointer-events: none;
}
.legend span {
display: flex;
align-items: center;
gap: 6px;
white-space: nowrap;
}
.legend i {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
background: #566278;
box-shadow: 0 0 0 3px rgba(86, 98, 120, 0.1);
}
.legend .ring {
width: 11px;
height: 11px;
border: 2px solid #ef6077;
border-radius: 50%;
background: transparent;
box-shadow: none;
}
#labels {
position: absolute;
z-index: 4;
inset: 0;
overflow: hidden;
pointer-events: none;
}
.chamber-label {
position: absolute;
min-width: 112px;
padding: 8px 11px;
border: 1px solid rgba(61, 74, 93, 0.11);
border-radius: 11px;
background: rgba(255, 255, 255, 0.78);
box-shadow: 0 7px 22px rgba(57, 66, 81, 0.08);
transform: translate(-50%, -100%);
text-align: center;
backdrop-filter: blur(9px);
will-change: left, top;
}
.chamber-label::after {
position: absolute;
top: 100%;
left: 50%;
width: 1px;
height: 17px;
background: rgba(67, 79, 96, 0.25);
content: "";
}
.chamber-label strong {
display: block;
color: #364154;
font-size: 12px;
font-weight: 800;
}
.chamber-label small {
display: block;
margin-top: 2px;
color: #818a98;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.03em;
}
.stats {
position: absolute;
z-index: 7;
bottom: 20px;
left: 50%;
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 9px;
width: min(850px, calc(100% - 40px));
transform: translateX(-50%);
}
.stat-card {
position: relative;
overflow: hidden;
padding: 13px 15px 12px;
border: 1px solid var(--line);
border-radius: 15px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
}
.stat-card::before {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 3px;
background: var(--accent);
content: "";
}
.card-head {
display: flex;
align-items: center;
gap: 7px;
}
.swatch {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 16%, transparent);
}
.card-head strong {
color: #3e4a5d;
font-size: 12px;
}
.factor {
margin-left: auto;
padding: 3px 7px;
border-radius: 999px;
background: color-mix(in srgb, var(--accent) 12%, white);
color: color-mix(in srgb, var(--accent) 78%, #283347);
font-size: 9px;
font-weight: 850;
}
.total {
margin-top: 7px;
color: #283449;
font-size: 27px;
font-weight: 780;
line-height: 1;
font-variant-numeric: tabular-nums;
}
.metric-label {
margin-top: 2px;
color: #8a92a0;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric-row {
display: flex;
justify-content: space-between;
gap: 8px;
margin-top: 9px;
padding-top: 8px;
border-top: 1px solid rgba(64, 76, 95, 0.08);
color: #818a98;
font-size: 10px;
}
.metric-row b {
color: #485469;
font-weight: 800;
font-variant-numeric: tabular-nums;
}
.hint {
position: absolute;
z-index: 5;
right: 27px;
bottom: 19px;
color: rgba(82, 93, 108, 0.58);
font-size: 10px;
font-weight: 650;
pointer-events: none;
}
@media (max-width: 1050px) {
.legend {
display: none;
}
.hint {
display: none;
}
}
@media (max-width: 760px) {
.header {
top: 16px;
left: 16px;
max-width: calc(100% - 32px);
}
.eyebrow {
margin-bottom: 6px;
font-size: 9px;
}
h1 {
font-size: 27px;
}
.subtitle {
max-width: 310px;
margin-top: 7px;
font-size: 11px;
}
.clock {
display: none;
}
.controls {
top: 118px;
right: 12px;
grid-template-columns: repeat(3, auto);
padding: 6px;
}
.controls button {
min-height: 30px;
padding: 0 8px;
font-size: 10px;
}
#pause {
min-width: 72px;
}
.rules {
display: none;
}
.tempo {
padding: 2px 3px 0;
font-size: 9px;
}
.stats {
bottom: 10px;
width: calc(100% - 20px);
gap: 5px;
}
.stat-card {
padding: 11px 9px 9px;
border-radius: 12px;
}
.card-head {
gap: 5px;
}
.card-head strong {
font-size: 10px;
}
.factor {
padding: 2px 5px;
font-size: 8px;
}
.total {
font-size: 21px;
}
.metric-label {
font-size: 7px;
}
.metric-row {
display: block;
margin-top: 6px;
padding-top: 5px;
font-size: 8px;
}
.metric-row b {
display: block;
margin-top: 1px;
}
.chamber-label {
min-width: 86px;
padding: 6px 8px;
}
.chamber-label strong {
font-size: 10px;
}
.chamber-label small {
font-size: 8px;
}
}
@media (max-height: 620px) {
.subtitle,
.rules {
display: none;
}
.controls {
top: 14px;
}
.stats {
bottom: 10px;
}
}
</style>
</head>
<body>
<div id="app">
<div id="scene"></div>
<header class="header">
<div class="eyebrow">Kinetic comparison toy</div>
<h1>Encounter Chambers</h1>
<p class="subtitle">
Equal 17.6 u³ cutaway chambers. Every mote moves at the same speed and
reflects from the walls identically. Only concentration changes.
</p>
<div class="clock">
Simulation time <strong id="clock">00:00</strong>
</div>
</header>
<div class="controls" aria-label="Simulation controls">
<button id="pause" type="button" aria-pressed="false">
<span id="pauseIcon">Ⅱ</span> <span id="pauseText">Pause</span>
</button>
<button id="reset" type="button" title="Reset simulation">
Reset
</button>
<button id="view" type="button" title="Recenter camera">
Recenter
</button>
<label class="tempo">
Tempo
<input
id="tempo"
type="range"
min="0.25"
max="2"
step="0.05"
value="1"
aria-label="Simulation speed"
/>
<output id="tempoValue">1.0×</output>
</label>
<div class="rules">
1.40 u/s · fixed speed · 0.17 u close-pass radius
</div>
</div>
<div class="legend" aria-hidden="true">
<span><i></i> mote</span>
<span><i class="ring"></i> encounter</span>
<span>Drag to orbit · wheel to zoom</span>
</div>
<div id="labels" aria-hidden="true"></div>
<div id="stats" class="stats" aria-live="polite"></div>
<div class="hint">Drag to orbit · wheel to zoom · Space to pause</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const sceneHost = document.querySelector("#scene");
const statsHost = document.querySelector("#stats");
const labelsHost = document.querySelector("#labels");
const CHAMBER_WIDTH = 3.2;
const CHAMBER_HEIGHT = 2.45;
const CHAMBER_DEPTH = 2.25;
const CHAMBER_SPACING = 4.15;
const PARTICLE_RADIUS = 0.075;
const BASE_SPEED = 1.4;
const ENCOUNTER_DISTANCE = 0.17;
const TRAIL_LENGTH = 0.25;
const chamberDefinitions = [
{
name: "Low",
factor: 1,
count: 24,
color: "#35c7b2"
},
{
name: "Medium",
factor: 2,
count: 48,
color: "#efb52d"
},
{
name: "High",
factor: 4,
count: 96,
color: "#ed6076"
}
];
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute(
"aria-label",
"Three cutaway particle chambers with equal volume and different concentrations"
);
renderer.domElement.tabIndex = 0;
sceneHost.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xf1eee8);
scene.fog = new THREE.Fog(0xf1eee8, 23, 43);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const hemisphere = new THREE.HemisphereLight(
0xffffff,
0xaeb8c8,
2.05
);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(6, 10, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -10;
keyLight.shadow.camera.right = 10;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -5;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 28;
keyLight.shadow.bias = -0.0003;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0xb9d7ff, 1.0);
fillLight.position.set(-8, 5, -6);
scene.add(fillLight);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(60, 60),
new THREE.MeshStandardMaterial({
color: 0xe8e4dc,
roughness: 0.96,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.19;
ground.receiveShadow = true;
scene.add(ground);
const plinth = new THREE.Mesh(
new THREE.BoxGeometry(12.8, 0.16, 3.25),
new THREE.MeshStandardMaterial({
color: 0xfbfaf7,
roughness: 0.7,
metalness: 0.02
})
);
plinth.position.y = -0.12;
plinth.receiveShadow = true;
plinth.castShadow = true;
scene.add(plinth);
const dummy = new THREE.Object3D();
const chambers = [];
function mulberry32(seed) {
let value = seed >>> 0;
return function random() {
value += 0x6d2b79f5;
let result = value;
result = Math.imul(result ^ (result >>> 15), result | 1);
result ^= result + Math.imul(result ^ (result >>> 7), result | 61);
return ((result ^ (result >>> 14)) >>> 0) / 4294967296;
};
}
function createParticleSet(count, seed) {
const random = mulberry32(seed);
const particles = [];
const minimumSeparation = PARTICLE_RADIUS * 2.3;
for (let i = 0; i < count; i++) {
let position;
for (let attempt = 0; attempt < 300; attempt++) {
const candidate = new THREE.Vector3(
THREE.MathUtils.randFloat(
-CHAMBER_WIDTH / 2 + PARTICLE_RADIUS,
CHAMBER_WIDTH / 2 - PARTICLE_RADIUS
),
THREE.MathUtils.randFloat(
PARTICLE_RADIUS + 0.025,
CHAMBER_HEIGHT - PARTICLE_RADIUS
),
THREE.MathUtils.randFloat(
-CHAMBER_DEPTH / 2 + PARTICLE_RADIUS,
CHAMBER_DEPTH / 2 - PARTICLE_RADIUS
)
);
const separated = particles.every((particle) => {
return candidate.distanceToSquared(particle.position) >
minimumSeparation * minimumSeparation;
});
if (separated) {
position = candidate;
break;
}
}
if (!position) {
position = new THREE.Vector3(
THREE.MathUtils.randFloat(
-CHAMBER_WIDTH / 2 + PARTICLE_RADIUS,
CHAMBER_WIDTH / 2 - PARTICLE_RADIUS
),
THREE.MathUtils.randFloat(
PARTICLE_RADIUS + 0.025,
CHAMBER_HEIGHT - PARTICLE_RADIUS
),
THREE.MathUtils.randFloat(
-CHAMBER_DEPTH / 2 + PARTICLE_RADIUS,
CHAMBER_DEPTH / 2 - PARTICLE_RADIUS
)
);
}
const direction = new THREE.Vector3(
random() * 2 - 1,
random() * 2 - 1,
random() * 2 - 1
).normalize();
particles.push({
position,
velocity: direction.multiplyScalar(BASE_SPEED)
});
}
return particles;
}
function createChamber(definition, index) {
const group = new THREE.Group();
group.position.set(
(index - 1) * CHAMBER_SPACING,
0,
0
);
scene.add(group);
const color = new THREE.Color(definition.color);
const floor = new THREE.Mesh(
new THREE.BoxGeometry(
CHAMBER_WIDTH + 0.12,
0.16,
CHAMBER_DEPTH + 0.12
),
new THREE.MeshStandardMaterial({
color: 0xfbfaf7,
roughness: 0.76,
metalness: 0.02
})
);
floor.position.y = -0.1;
floor.castShadow = true;
floor.receiveShadow = true;
group.add(floor);
const backMaterial = new THREE.MeshStandardMaterial({
color,
transparent: true,
opacity: 0.065,
roughness: 0.5,
depthWrite: false,
side: THREE.DoubleSide
});
const back = new THREE.Mesh(
new THREE.BoxGeometry(
CHAMBER_WIDTH,
CHAMBER_HEIGHT,
0.035
),
backMaterial
);
back.position.set(0, CHAMBER_HEIGHT / 2, -CHAMBER_DEPTH / 2);
back.renderOrder = 0;
group.add(back);
const sideMaterial = backMaterial.clone();
sideMaterial.opacity = 0.035;
for (const side of [-1, 1]) {
const wall = new THREE.Mesh(
new THREE.BoxGeometry(
0.035,
CHAMBER_HEIGHT,
CHAMBER_DEPTH
),
sideMaterial
);
wall.position.set(
side * CHAMBER_WIDTH / 2,
CHAMBER_HEIGHT / 2,
0
);
wall.renderOrder = 0;
group.add(wall);
}
const edgeGeometry = new THREE.EdgesGeometry(
new THREE.BoxGeometry(
CHAMBER_WIDTH,
CHAMBER_HEIGHT,
CHAMBER_DEPTH
)
);
const edges = new THREE.LineSegments(
edgeGeometry,
new THREE.LineBasicMaterial({
color: 0x8792a3,
transparent: true,
opacity: 0.56
})
);
edges.position.y = CHAMBER_HEIGHT / 2;
edges.renderOrder = 3;
group.add(edges);
const particleGeometry = new THREE.SphereGeometry(
PARTICLE_RADIUS,
12,
8
);
const particleMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
emissive: color,
emissiveIntensity: 0.18,
roughness: 0.27,
metalness: 0.05
});
const particleMesh = new THREE.InstancedMesh(
particleGeometry,
particleMaterial,
definition.count
);
particleMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
particleMesh.castShadow = true;
particleMesh.frustumCulled = false;
particleMesh.renderOrder = 2;
for (let i = 0; i < definition.count; i++) {
const instanceColor = color.clone();
instanceColor.offsetHSL(
0,
0,
(((i % 7) - 3) * 0.012)
);
particleMesh.setColorAt(i, instanceColor);
}
particleMesh.instanceColor.needsUpdate = true;
group.add(particleMesh);
const trailPositions = new Float32Array(
definition.count * 2 * 3
);
const trailGeometry = new THREE.BufferGeometry();
trailGeometry.setAttribute(
"position",
new THREE.BufferAttribute(trailPositions, 3)
.setUsage(THREE.DynamicDrawUsage)
);
const trails = new THREE.LineSegments(
trailGeometry,
new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.24,
depthWrite: false
})
);
trails.frustumCulled = false;
trails.renderOrder = 1;
group.add(trails);
const label = document.createElement("div");
label.className = "chamber-label";
label.innerHTML = `
<strong>${definition.name}</strong>
<small>${definition.factor}× concentration · ${definition.count} motes</small>
`;
labelsHost.appendChild(label);
const card = document.createElement("article");
card.className = "stat-card";
card.style.setProperty("--accent", definition.color);
card.innerHTML = `
<div class="card-head">
<span class="swatch"></span>
<strong>${definition.name}</strong>
<span class="factor">${definition.factor}×</span>
</div>
<div class="total" data-total>0</div>
<div class="metric-label">encounters</div>
<div class="metric-row">
<span>Last 10 s</span>
<b data-recent>0</b>
</div>
<div class="metric-row">
<span>All mote pairs</span>
<b>${(definition.count * (definition.count - 1)) / 2}</b>
</div>
`;
statsHost.appendChild(card);
const chamber = {
definition,
group,
color,
particleMesh,
trails,
trailPositions,
particles: [],
activePairs: new Set(),
total: 0,
eventTimes: [],
label,
labelAnchor: new THREE.Vector3(
group.position.x,
CHAMBER_HEIGHT + 0.55,
group.position.z
),
totalElement: card.querySelector("[data-total]"),
recentElement: card.querySelector("[data-recent]")
};
chambers.push(chamber);
return chamber;
}
chamberDefinitions.forEach((definition, index) => {
createChamber(definition, index);
});
// Shared pool of encounter rings.
const pulseRoot = new THREE.Group();
scene.add(pulseRoot);
const pulseGeometry = new THREE.RingGeometry(0.82, 1, 28);
const pulses = [];
for (let i = 0; i < 96; i++) {
const pulse = new THREE.Mesh(
pulseGeometry,
new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0,
depthWrite: false,
side: THREE.DoubleSide
})
);
pulse.visible = false;
pulse.userData.age = 0;
pulse.userData.life = 0.58;
pulseRoot.add(pulse);
pulses.push(pulse);
}
let pulseCursor = 0;
function spawnPulse(chamber, position) {
const pulse = pulses[pulseCursor];
pulseCursor = (pulseCursor + 1) % pulses.length;
pulse.position.copy(position);
pulse.material.color.copy(chamber.color);
pulse.material.opacity = 0.88;
pulse.scale.setScalar(0.09);
pulse.visible = true;
pulse.userData.age = 0;
}
function updateParticleVisuals(chamber) {
const {
particles,
particleMesh,
trails,
trailPositions
} = chamber;
for (let i = 0; i < particles.length; i++) {
const particle = particles[i];
dummy.position.copy(particle.position);
dummy.scale.setScalar(1);
dummy.updateMatrix();
particleMesh.setMatrixAt(i, dummy.matrix);
const offset = i * 6;
const inverseSpeed = 1 / BASE_SPEED;
trailPositions[offset] =
particle.position.x - particle.velocity.x * inverseSpeed * TRAIL_LENGTH;
trailPositions[offset + 1] =
particle.position.y - particle.velocity.y * inverseSpeed * TRAIL_LENGTH;
trailPositions[offset + 2] =
particle.position.z - particle.velocity.z * inverseSpeed * TRAIL_LENGTH;
trailPositions[offset + 3] = particle.position.x;
trailPositions[offset + 4] = particle.position.y;
trailPositions[offset + 5] = particle.position.z;
}
particleMesh.instanceMatrix.needsUpdate = true;
trails.geometry.attributes.position.needsUpdate = true;
}
function updateParticlePositions(chamber, delta) {
const minimumX = -CHAMBER_WIDTH / 2 + PARTICLE_RADIUS;
const maximumX = CHAMBER_WIDTH / 2 - PARTICLE_RADIUS;
const minimumY = PARTICLE_RADIUS + 0.02;
const maximumY = CHAMBER_HEIGHT - PARTICLE_RADIUS;
const minimumZ = -CHAMBER_DEPTH / 2 + PARTICLE_RADIUS;
const maximumZ = CHAMBER_DEPTH / 2 - PARTICLE_RADIUS;
for (const particle of chamber.particles) {
particle.position.addScaledVector(particle.velocity, delta);
if (particle.position.x < minimumX) {
particle.position.x = minimumX + (minimumX - particle.position.x);
particle.velocity.x = Math.abs(particle.velocity.x);
} else if (particle.position.x > maximumX) {
particle.position.x = maximumX - (particle.position.x - maximumX);
particle.velocity.x = -Math.abs(particle.velocity.x);
}
if (particle.position.y < minimumY) {
particle.position.y = minimumY + (minimumY - particle.position.y);
particle.velocity.y = Math.abs(particle.velocity.y);
} else if (particle.position.y > maximumY) {
particle.position.y = maximumY - (particle.position.y - maximumY);
particle.velocity.y = -Math.abs(particle.velocity.y);
}
if (particle.position.z < minimumZ) {
particle.position.z = minimumZ + (minimumZ - particle.position.z);
particle.velocity.z = Math.abs(particle.velocity.z);
} else if (particle.position.z > maximumZ) {
particle.position.z = maximumZ - (particle.position.z - maximumZ);
particle.velocity.z = -Math.abs(particle.velocity.z);
}
}
}
/*
Relative swept-segment test:
Finds the closest simultaneous distance between two moving motes
over one frame. This prevents fast crossings from being missed.
*/
function detectEncounters(chamber, delta) {
const particles = chamber.particles;
const thresholdSquared =
ENCOUNTER_DISTANCE * ENCOUNTER_DISTANCE;
for (let i = 0; i < particles.length; i++) {
const a = particles[i];
for (let j = i + 1; j < particles.length; j++) {
const b = particles[j];
const dx = b.position.x - a.position.x;
const dy = b.position.y - a.position.y;
const dz = b.position.z - a.position.z;
const vx = (b.velocity.x - a.velocity.x) * delta;
const vy = (b.velocity.y - a.velocity.y) * delta;
const vz = (b.velocity.z - a.velocity.z) * delta;
const velocitySquared = vx * vx + vy * vy + vz * vz;
let time = 0;
if (velocitySquared > 1e-12) {
time = THREE.MathUtils.clamp(
-(dx * vx + dy * vy + dz * vz) /
velocitySquared,
0,
1
);
}
const closestX = dx + vx * time;
const closestY = dy + vy * time;
const closestZ = dz + vz * time;
const close =
closestX * closestX +
closestY * closestY +
closestZ * closestZ <=
thresholdSquared;
const key = i * chamber.particles.length + j;
if (close) {
if (!chamber.activePairs.has(key)) {
chamber.total += 1;
chamber.eventTimes.push(simulationTime + delta * time);
const midpoint = new THREE.Vector3(
a.position.x + a.velocity.x * delta * time +
b.position.x + b.velocity.x * delta * time,
a.position.y + a.velocity.y * delta * time +
b.position.y + b.velocity.y * delta * time,
a.position.z + a.velocity.z * delta * time +
b.position.z + b.velocity.z * delta * time
).multiplyScalar(0.5);
const worldPosition = chamber.group.localToWorld(midpoint);
spawnPulse(chamber, worldPosition);
}
chamber.activePairs.add(key);
} else {
chamber.activePairs.delete(key);
}
}
}
}
function resetSimulation() {
simulationTime = 0;
chambers.forEach((chamber, index) => {
chamber.particles = createParticleSet(
chamber.definition.count,
20250317 + index * 1013
);
chamber.activePairs.clear();
chamber.total = 0;
chamber.eventTimes = [];
updateParticleVisuals(chamber);
});
pulses.forEach((pulse) => {
pulse.visible = false;
});
updateStats();
}
function updateStats() {
for (const chamber of chambers) {
chamber.eventTimes = chamber.eventTimes.filter(
(time) => simulationTime - time <= 10
);
chamber.totalElement.textContent =
chamber.total.toLocaleString();
chamber.recentElement.textContent =
chamber.eventTimes.length.toLocaleString();
}
const minutes = Math.floor(simulationTime / 60);
const seconds = Math.floor(simulationTime % 60);
document.querySelector("#clock").textContent =
`${String(minutes).padStart(2, "0")}:` +
`${String(seconds).padStart(2, "0")}`;
}
// Camera state and custom orbit controls.
let fitRadius = 14.6;
let userMovedCamera = false;
const cameraState = {
yaw: 0.28,
pitch: 0.48,
radius: fitRadius,
targetYaw: 0.28,
targetPitch: 0.48,
targetRadius: fitRadius,
target: new THREE.Vector3(0, 1.12, 0)
};
function getFitRadius() {
const aspect = window.innerWidth / window.innerHeight;
if (aspect < 0.7) return 33;
if (aspect < 1.1) return 23;
if (aspect < 1.5) return 17.5;
return 14.6;
}
function resetCamera(immediate = false) {
fitRadius = getFitRadius();
cameraState.targetYaw = 0.28;
cameraState.targetPitch = 0.48;
cameraState.targetRadius = fitRadius;
if (immediate) {
cameraState.yaw = cameraState.targetYaw;
cameraState.pitch = cameraState.targetPitch;
cameraState.radius = cameraState.targetRadius;
}
}
function updateCamera(delta) {
const smoothing = 1 - Math.exp(-delta * 9);
cameraState.yaw = THREE.MathUtils.lerp(
cameraState.yaw,
cameraState.targetYaw,
smoothing
);
cameraState.pitch = THREE.MathUtils.lerp(
cameraState.pitch,
cameraState.targetPitch,
smoothing
);
cameraState.radius = THREE.MathUtils.lerp(
cameraState.radius,
cameraState.targetRadius,
smoothing
);
const horizontalRadius =
cameraState.radius * Math.cos(cameraState.pitch);
camera.position.set(
cameraState.target.x +
horizontalRadius * Math.sin(cameraState.yaw),
cameraState.target.y +
cameraState.radius * Math.sin(cameraState.pitch),
cameraState.target.z +
horizontalRadius * Math.cos(cameraState.yaw)
);
camera.lookAt(cameraState.target);
camera.updateMatrixWorld();
}
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - previousPointerX;
const deltaY = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
cameraState.targetYaw -= deltaX * 0.005;
cameraState.targetPitch = THREE.MathUtils.clamp(
cameraState.targetPitch + deltaY * 0.004,
0.18,
1.15
);
userMovedCamera = true;
});
function endDragging(event) {
dragging = false;
if (
renderer.domElement.hasPointerCapture &&
renderer.domElement.hasPointerCapture(event.pointerId)
) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDragging);
renderer.domElement.addEventListener("pointercancel", endDragging);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.targetRadius = THREE.MathUtils.clamp(
cameraState.targetRadius * Math.exp(event.deltaY * 0.001),
9,
38
);
userMovedCamera = true;
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
userMovedCamera = false;
resetCamera();
});
let paused = false;
let timeScale = 1;
let simulationTime = 0;
const pauseButton = document.querySelector("#pause");
const pauseIcon = document.querySelector("#pauseIcon");
const pauseText = document.querySelector("#pauseText");
const tempoInput = document.querySelector("#tempo");
const tempoValue = document.querySelector("#tempoValue");
function togglePause() {
paused = !paused;
pauseButton.setAttribute("aria-pressed", String(paused));
pauseIcon.textContent = paused ? "▶" : "Ⅱ";
pauseText.textContent = paused ? "Resume" : "Pause";
}
pauseButton.addEventListener("click", togglePause);
document.querySelector("#reset").addEventListener("click", () => {
resetSimulation();
});
document.querySelector("#view").addEventListener("click", () => {
userMovedCamera = false;
resetCamera();
});
tempoInput.addEventListener("input", () => {
timeScale = Number(tempoInput.value);
tempoValue.textContent = `${timeScale.toFixed(2).replace(/0$/, "")}×`;
});
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLInputElement) return;
if (event.code === "Space") {
event.preventDefault();
togglePause();
} else if (event.key.toLowerCase() === "r") {
resetSimulation();
} else if (event.key.toLowerCase() === "c") {
userMovedCamera = false;
resetCamera();
}
});
function resize() {
const oldFitRadius = fitRadius;
fitRadius = getFitRadius();
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(
Math.min(window.devicePixelRatio || 1, 2)
);
if (!userMovedCamera) {
resetCamera(true);
} else {
cameraState.targetRadius *= fitRadius / oldFitRadius;
}
}
window.addEventListener("resize", resize);
const projectedPosition = new THREE.Vector3();
function updateLabels() {
for (const chamber of chambers) {
projectedPosition
.copy(chamber.labelAnchor)
.project(camera);
const visible =
projectedPosition.z > -1 &&
projectedPosition.z < 1 &&
projectedPosition.x > -1.12 &&
projectedPosition.x < 1.12 &&
projectedPosition.y > -1.12 &&
projectedPosition.y < 1.12;
chamber.label.style.display = visible ? "block" : "none";
if (!visible) continue;
const x =
(projectedPosition.x * 0.5 + 0.5) *
window.innerWidth;
const y =
(-projectedPosition.y * 0.5 + 0.5) *
window.innerHeight;
chamber.label.style.left = `${x}px`;
chamber.label.style.top = `${y}px`;
}
}
function updatePulses(delta) {
for (const pulse of pulses) {
if (!pulse.visible) continue;
pulse.userData.age += delta;
const progress = Math.min(
pulse.userData.age / pulse.userData.life,
1
);
const eased = 1 - Math.pow(1 - progress, 2);
pulse.scale.setScalar(0.09 + eased * 0.32);
pulse.material.opacity = (1 - progress) * 0.88;
pulse.quaternion.copy(camera.quaternion);
if (progress >= 1) {
pulse.visible = false;
}
}
}
resetSimulation();
resetCamera(true);
updateCamera(1);
const clock = new THREE.Clock();
let statsTimer = 0;
renderer.setAnimationLoop(() => {
const realDelta = Math.min(clock.getDelta(), 0.05);
if (!paused) {
const simulationDelta = realDelta * timeScale;
// Detect on swept relative trajectories before moving the motes.
for (const chamber of chambers) {
detectEncounters(chamber, simulationDelta);
}
// All chambers use precisely the same update and speed rules.
for (const chamber of chambers) {
updateParticlePositions(chamber, simulationDelta);
updateParticleVisuals(chamber);
}
simulationTime += simulationDelta;
}
updateCamera(realDelta);
updatePulses(realDelta);
updateLabels();
statsTimer += realDelta;
if (statsTimer >= 0.15) {
statsTimer = 0;
updateStats();
}
renderer.render(scene, camera);
});
</script>
</body>
</html>
```