Prompt specification
Build or customize the Three.js 3D scene "Collision-and-reaction probability chamber" 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: Collision-and-reaction probability chamber
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/collision-and-reaction-probability-chamber-x1989
Scene Description Prompt:
Animate a cutaway toy reaction chamber where particle encounters react according to a stated probability. Track reactants and products. Three.js from cdnjs, standalone HTML.
Working Three.js Starter (collision-and-reaction-probability-chamber-x1989):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Reaction Chamber</title>
<style>
:root {
color-scheme: dark;
--bg: #070b14;
--panel: rgba(12, 19, 34, 0.82);
--line: rgba(160, 210, 235, 0.16);
--text: #edf7ff;
--muted: #91a8bd;
--cyan: #52e1ff;
--coral: #ff6d78;
--gold: #ffd166;
--green: #75f0bc;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 42%, #13243a 0%, #080d19 45%, #04060c 100%);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 2;
}
.brand {
position: absolute;
top: 24px;
left: 28px;
display: flex;
align-items: center;
gap: 14px;
text-shadow: 0 2px 18px rgba(0, 0, 0, 0.5);
}
.brand-mark {
width: 42px;
height: 42px;
border: 1px solid rgba(82, 225, 255, 0.55);
border-radius: 13px;
display: grid;
place-items: center;
background: rgba(82, 225, 255, 0.08);
box-shadow: inset 0 0 22px rgba(82, 225, 255, 0.1);
}
.brand-mark::before {
content: "";
width: 14px;
height: 14px;
border: 2px solid var(--cyan);
border-radius: 50%;
box-shadow:
7px -7px 0 -5px var(--coral),
-7px 7px 0 -5px var(--gold);
}
.eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.23em;
text-transform: uppercase;
margin-bottom: 4px;
}
h1 {
margin: 0;
font-size: clamp(20px, 2.2vw, 30px);
line-height: 1;
letter-spacing: -0.035em;
}
.subtitle {
margin-top: 6px;
color: var(--muted);
font-size: 12px;
}
.panel {
position: absolute;
top: 24px;
right: 24px;
width: 330px;
padding: 18px;
border: 1px solid var(--line);
border-radius: 18px;
background: var(--panel);
backdrop-filter: blur(18px) saturate(130%);
box-shadow:
0 20px 60px rgba(0, 0, 0, 0.35),
inset 0 1px 0 rgba(255, 255, 255, 0.04);
pointer-events: auto;
}
.panel-head,
.row,
.button-row,
.metric,
.legend {
display: flex;
align-items: center;
justify-content: space-between;
}
.panel-title {
font-size: 12px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.live {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--green);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
}
.live::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 10px currentColor;
}
.equation {
margin: 16px 0 10px;
padding: 13px;
border: 1px solid rgba(255, 255, 255, 0.07);
border-radius: 12px;
background: rgba(255, 255, 255, 0.025);
text-align: center;
font-size: 25px;
font-weight: 800;
letter-spacing: 0.08em;
}
.a {
color: var(--coral);
}
.b {
color: var(--cyan);
}
.p {
color: var(--gold);
}
.muted {
color: var(--muted);
}
.explanation {
margin: 0 0 16px;
color: #a9bac9;
font-size: 11.5px;
line-height: 1.55;
}
.control-label {
font-size: 11px;
font-weight: 700;
letter-spacing: 0.035em;
}
output {
color: var(--cyan);
font-size: 13px;
font-weight: 800;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 10px 0 17px;
appearance: none;
border-radius: 999px;
background: linear-gradient(
90deg,
var(--cyan) 0%,
var(--cyan) var(--fill, 30%),
rgba(255, 255, 255, 0.1) var(--fill, 30%),
rgba(255, 255, 255, 0.1) 100%
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
appearance: none;
border: 3px solid #0b1422;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px rgba(82, 225, 255, 0.55);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 3px solid #0b1422;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px rgba(82, 225, 255, 0.55);
}
.counts {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin: 4px 0 13px;
}
.count-card {
min-width: 0;
padding: 11px 9px;
border: 1px solid rgba(255, 255, 255, 0.075);
border-radius: 11px;
background: rgba(255, 255, 255, 0.028);
}
.count-card span {
display: block;
margin-bottom: 7px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.count-card strong {
font-size: 24px;
line-height: 1;
}
.count-card.a strong {
color: var(--coral);
}
.count-card.b strong {
color: var(--cyan);
}
.count-card.p strong {
color: var(--gold);
}
.remaining {
margin-bottom: 15px;
}
.remaining-label {
display: flex;
justify-content: space-between;
margin-bottom: 7px;
color: var(--muted);
font-size: 10px;
}
.track {
height: 5px;
overflow: hidden;
border-radius: 999px;
background: rgba(255, 255, 255, 0.08);
}
.track > div {
width: 100%;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--coral), var(--cyan));
transition: width 180ms ease;
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-bottom: 15px;
}
.metric {
flex-direction: column;
align-items: flex-start;
gap: 4px;
padding: 9px;
border-radius: 9px;
background: rgba(255, 255, 255, 0.025);
}
.metric span {
color: var(--muted);
font-size: 9px;
text-transform: uppercase;
letter-spacing: 0.06em;
}
.metric strong {
font-size: 13px;
}
.button-row {
gap: 8px;
}
button {
flex: 1;
padding: 10px 12px;
border: 1px solid rgba(255, 255, 255, 0.11);
border-radius: 10px;
background: rgba(255, 255, 255, 0.055);
color: var(--text);
font: inherit;
font-size: 11px;
font-weight: 750;
cursor: pointer;
transition: 140ms ease;
}
button:hover {
border-color: rgba(82, 225, 255, 0.45);
background: rgba(82, 225, 255, 0.1);
}
button.primary {
border-color: rgba(82, 225, 255, 0.32);
background: rgba(82, 225, 255, 0.12);
color: #bff5ff;
}
.legend {
position: absolute;
left: 28px;
bottom: 25px;
justify-content: flex-start;
gap: 9px;
padding: 9px 12px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(9, 15, 27, 0.7);
backdrop-filter: blur(12px);
}
.chip {
display: inline-flex;
align-items: center;
gap: 7px;
color: #b9c9d7;
font-size: 10px;
font-weight: 700;
}
.dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 10px currentColor;
}
.hint {
position: absolute;
right: 28px;
bottom: 26px;
color: rgba(185, 207, 222, 0.62);
font-size: 10px;
letter-spacing: 0.04em;
}
@media (max-width: 760px) {
.brand {
top: 16px;
left: 16px;
}
.brand-mark {
width: 36px;
height: 36px;
}
.subtitle {
display: none;
}
.panel {
top: auto;
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
max-height: 46vh;
overflow-y: auto;
padding: 14px;
}
.equation {
margin-top: 10px;
padding: 8px;
font-size: 21px;
}
.explanation {
margin-bottom: 10px;
}
.legend {
top: 78px;
bottom: auto;
left: 16px;
}
.hint {
display: none;
}
}
</style>
</head>
<body>
<div class="hud">
<header class="brand">
<div class="brand-mark"></div>
<div>
<div class="eyebrow">Molecular Systems Lab</div>
<h1>Reaction Chamber</h1>
<div class="subtitle">Interactive cutaway / stochastic encounter model</div>
</div>
</header>
<section class="panel" aria-label="Reaction controls and statistics">
<div class="panel-head">
<span class="panel-title">Reaction model</span>
<span class="live" id="liveStatus">LIVE</span>
</div>
<div class="equation">
<span class="a">A</span>
<span class="muted"> + </span>
<span class="b">B</span>
<span class="muted"> → </span>
<span class="p">P</span>
</div>
<p class="explanation">
Each time an A reactant encounters a B reactant, one independent random
roll is made. A successful roll consumes both reactants and creates one
P product molecule.
</p>
<div class="row">
<label class="control-label" for="probability">
Encounter reaction probability
</label>
<output id="probabilityValue" for="probability">35%</output>
</div>
<input
id="probability"
type="range"
min="5"
max="95"
step="5"
value="35"
aria-label="Encounter reaction probability"
/>
<div class="row">
<label class="control-label" for="speed">Simulation speed</label>
<output id="speedValue" for="speed">1.0×</output>
</div>
<input
id="speed"
type="range"
min="0.4"
max="2.4"
step="0.1"
value="1"
aria-label="Simulation speed"
/>
<div class="counts">
<div class="count-card a">
<span>A Reactant</span>
<strong id="countA">0</strong>
</div>
<div class="count-card b">
<span>B Reactant</span>
<strong id="countB">0</strong>
</div>
<div class="count-card p">
<span>P Product</span>
<strong id="countP">0</strong>
</div>
</div>
<div class="remaining">
<div class="remaining-label">
<span>Reactants remaining</span>
<span id="remainingText">0</span>
</div>
<div class="track"><div id="remainingBar"></div></div>
</div>
<div class="metrics">
<div class="metric">
<span>Encounters</span>
<strong id="encounterCount">0</strong>
</div>
<div class="metric">
<span>Products formed</span>
<strong id="formedCount">0</strong>
</div>
<div class="metric">
<span>Elapsed</span>
<strong id="elapsed">0.0s</strong>
</div>
</div>
<div class="button-row">
<button class="primary" id="pauseButton" type="button">Pause</button>
<button id="resetButton" type="button">Reset chamber</button>
</div>
</section>
<div class="legend" aria-label="Particle legend">
<span class="chip"><i class="dot" style="color:#ff6d78"></i>A reactant</span>
<span class="chip"><i class="dot" style="color:#52e1ff"></i>B reactant</span>
<span class="chip"><i class="dot" style="color:#ffd166"></i>P product</span>
</div>
<div class="hint">Drag to orbit · Scroll to zoom</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x070b14);
scene.fog = new THREE.FogExp2(0x070b14, 0.018);
const camera = new THREE.PerspectiveCamera(
42,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
document.body.prepend(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xa7ddff, 0x111523, 1.7));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(4, 7, 8);
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x39dfff, 38, 18, 2);
cyanLight.position.set(-5, 2, 4);
scene.add(cyanLight);
const pinkLight = new THREE.PointLight(0xff5577, 32, 18, 2);
pinkLight.position.set(5, -1, 3);
scene.add(pinkLight);
const backLight = new THREE.PointLight(0xffcc66, 24, 16, 2);
backLight.position.set(0, 2, -5);
scene.add(backLight);
// -------------------------------------------------------------------------
// Direct camera controls: orbit and zoom, without examples/addons
// -------------------------------------------------------------------------
const controls = {
azimuth: 0,
elevation: 0.08,
radius: 13.2,
targetAzimuth: 0,
targetElevation: 0.08,
targetRadius: 13.2,
dragging: false,
lastX: 0,
lastY: 0
};
renderer.domElement.addEventListener("pointerdown", (event) => {
controls.dragging = true;
controls.lastX = event.clientX;
controls.lastY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!controls.dragging) return;
const dx = event.clientX - controls.lastX;
const dy = event.clientY - controls.lastY;
controls.lastX = event.clientX;
controls.lastY = event.clientY;
controls.targetAzimuth -= dx * 0.006;
controls.targetElevation = THREE.MathUtils.clamp(
controls.targetElevation + dy * 0.0045,
-0.52,
0.78
);
});
function stopDragging(event) {
controls.dragging = false;
if (event?.pointerId !== undefined) {
try {
renderer.domElement.releasePointerCapture(event.pointerId);
} catch (_) {}
}
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
controls.targetRadius = THREE.MathUtils.clamp(
controls.targetRadius + event.deltaY * 0.009,
8.4,
18
);
},
{ passive: false }
);
function updateCamera(dt) {
const smoothing = 1 - Math.pow(0.0008, dt);
controls.azimuth +=
(controls.targetAzimuth - controls.azimuth) * smoothing;
controls.elevation +=
(controls.targetElevation - controls.elevation) * smoothing;
controls.radius +=
(controls.targetRadius - controls.radius) * smoothing;
const horizontal = controls.radius * Math.cos(controls.elevation);
camera.position.set(
horizontal * Math.sin(controls.azimuth),
controls.radius * Math.sin(controls.elevation) + 0.15,
horizontal * Math.cos(controls.azimuth)
);
camera.lookAt(0, 0.05, 0);
}
// -------------------------------------------------------------------------
// Procedural textures
// -------------------------------------------------------------------------
function makeHaloTexture() {
const canvas = document.createElement("canvas");
canvas.width = canvas.height = 128;
const ctx = canvas.getContext("2d");
const gradient = ctx.createRadialGradient(64, 64, 4, 64, 64, 64);
gradient.addColorStop(0, "rgba(255,255,255,0.95)");
gradient.addColorStop(0.16, "rgba(255,255,255,0.42)");
gradient.addColorStop(0.48, "rgba(255,255,255,0.10)");
gradient.addColorStop(1, "rgba(255,255,255,0)");
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 128, 128);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
function makeRingTexture() {
const canvas = document.createElement("canvas");
canvas.width = canvas.height = 128;
const ctx = canvas.getContext("2d");
const gradient = ctx.createRadialGradient(64, 64, 18, 64, 64, 60);
gradient.addColorStop(0, "rgba(255,255,255,0)");
gradient.addColorStop(0.55, "rgba(255,255,255,0.08)");
gradient.addColorStop(0.72, "rgba(255,255,255,1)");
gradient.addColorStop(0.82, "rgba(255,255,255,0.34)");
gradient.addColorStop(1, "rgba(255,255,255,0)");
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 128, 128);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
function makeEquationSprite() {
const canvas = document.createElement("canvas");
canvas.width = 1024;
canvas.height = 192;
const ctx = canvas.getContext("2d");
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = "700 76px Inter, Arial, sans-serif";
ctx.fillStyle = "#ff6d78";
ctx.fillText("A", 278, 94);
ctx.fillStyle = "#91a8bd";
ctx.fillText("+", 456, 94);
ctx.fillStyle = "#52e1ff";
ctx.fillText("B", 590, 94);
ctx.fillStyle = "#91a8bd";
ctx.fillText("→", 754, 94);
ctx.fillStyle = "#ffd166";
ctx.fillText("P", 904, 94);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false,
depthTest: false
});
const sprite = new THREE.Sprite(material);
sprite.position.set(0, 5.65, 0);
sprite.scale.set(4.8, 0.9, 1);
sprite.renderOrder = 20;
return sprite;
}
const haloTexture = makeHaloTexture();
const ringTexture = makeRingTexture();
// -------------------------------------------------------------------------
// Cutaway reaction chamber
// -------------------------------------------------------------------------
const CHAMBER_RADIUS = 4.8;
const PARTICLE_LIMIT = 4.35;
const CENTER_Y = 0.2;
const chamber = new THREE.Group();
chamber.position.y = CENTER_Y;
scene.add(chamber);
// Remove a 120-degree wedge facing the camera to expose the interior.
const cutStart = 2.59;
const cutLength = Math.PI * 2 - 2.09;
const shellGeometry = new THREE.SphereGeometry(
CHAMBER_RADIUS,
72,
48,
cutStart,
cutLength,
0,
Math.PI
);
const shellMaterial = new THREE.MeshPhysicalMaterial({
color: 0x9bdcf1,
emissive: 0x102d3a,
emissiveIntensity: 0.38,
metalness: 0.08,
roughness: 0.22,
transparent: true,
opacity: 0.18,
transmission: 0.08,
clearcoat: 0.8,
clearcoatRoughness: 0.2,
side: THREE.DoubleSide,
depthWrite: false
});
const shell = new THREE.Mesh(shellGeometry, shellMaterial);
shell.renderOrder = 3;
chamber.add(shell);
const innerShell = new THREE.Mesh(
shellGeometry,
new THREE.MeshBasicMaterial({
color: 0x143652,
transparent: true,
opacity: 0.055,
side: THREE.BackSide,
depthWrite: false
})
);
innerShell.renderOrder = 0;
chamber.add(innerShell);
function spherePoint(phi, theta, radius = CHAMBER_RADIUS) {
const sinTheta = Math.sin(theta);
return new THREE.Vector3(
-radius * Math.cos(phi) * sinTheta,
radius * Math.cos(theta),
radius * Math.sin(phi) * sinTheta
);
}
function addTube(points, radius, color, opacity = 1) {
const curve = new THREE.CatmullRomCurve3(points);
const geometry = new THREE.TubeGeometry(curve, 72, radius, 8, false);
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.65,
transparent: opacity < 1,
opacity,
roughness: 0.35,
metalness: 0.55
});
const mesh = new THREE.Mesh(geometry, material);
chamber.add(mesh);
return mesh;
}
// Bright cut edges.
for (const phi of [cutStart, cutStart + cutLength]) {
const points = [];
for (let i = 0; i <= 64; i++) {
const theta = (i / 64) * Math.PI;
points.push(spherePoint(phi, theta));
}
addTube(points, 0.055, 0x6ee8ff, 0.9);
}
// Latitude rings on the remaining shell.
for (let ring = 1; ring <= 6; ring++) {
const theta = (ring / 7) * Math.PI;
const points = [];
for (let i = 0; i <= 80; i++) {
const phi = cutStart + (i / 80) * cutLength;
points.push(spherePoint(phi, theta));
}
addTube(points, 0.012, 0x4ac8e8, 0.19);
}
// Structural equatorial band.
const equatorPoints = [];
for (let i = 0; i <= 96; i++) {
const phi = cutStart + (i / 96) * cutLength;
equatorPoints.push(spherePoint(phi, Math.PI / 2));
}
addTube(equatorPoints, 0.07, 0x2b8098, 0.62);
// Base and pedestal.
const baseMaterial = new THREE.MeshStandardMaterial({
color: 0x162638,
metalness: 0.8,
roughness: 0.3
});
const base = new THREE.Mesh(
new THREE.CylinderGeometry(2.25, 2.65, 0.42, 64),
baseMaterial
);
base.position.y = -5.22;
scene.add(base);
const baseRing = new THREE.Mesh(
new THREE.TorusGeometry(2.27, 0.085, 10, 80),
new THREE.MeshStandardMaterial({
color: 0x4dd8f5,
emissive: 0x1c91aa,
emissiveIntensity: 1.2,
metalness: 0.7,
roughness: 0.25
})
);
baseRing.rotation.x = Math.PI / 2;
baseRing.position.y = -4.99;
scene.add(baseRing);
for (const x of [-1.55, 1.55]) {
const support = new THREE.Mesh(
new THREE.CylinderGeometry(0.12, 0.17, 0.85, 18),
baseMaterial
);
support.position.set(x, -4.72, 0.2);
support.rotation.z = x < 0 ? -0.2 : 0.2;
scene.add(support);
}
const grid = new THREE.GridHelper(24, 24, 0x247c8b, 0x14283b);
grid.position.y = -5.45;
grid.material.transparent = true;
grid.material.opacity = 0.19;
scene.add(grid);
scene.add(makeEquationSprite());
// -------------------------------------------------------------------------
// Particle model
// -------------------------------------------------------------------------
const particleLayer = new THREE.Group();
const effectLayer = new THREE.Group();
scene.add(particleLayer, effectLayer);
const typeConfig = {
A: {
color: 0xff6d78,
emissive: 0xa9152b,
radius: 0.23
},
B: {
color: 0x52e1ff,
emissive: 0x087da5,
radius: 0.23
},
P: {
color: 0xffd166,
emissive: 0xd87508,
radius: 0.31
}
};
const geometryA = new THREE.DodecahedronGeometry(0.22, 1);
const geometryB = new THREE.OctahedronGeometry(0.25, 1);
const geometryProductCenter = new THREE.IcosahedronGeometry(0.17, 1);
const geometryProductLobe = new THREE.SphereGeometry(0.105, 14, 10);
const materialA = new THREE.MeshStandardMaterial({
color: typeConfig.A.color,
emissive: typeConfig.A.emissive,
emissiveIntensity: 0.72,
metalness: 0.18,
roughness: 0.25
});
const materialB = new THREE.MeshStandardMaterial({
color: typeConfig.B.color,
emissive: typeConfig.B.emissive,
emissiveIntensity: 0.72,
metalness: 0.18,
roughness: 0.25
});
const materialProduct = new THREE.MeshStandardMaterial({
color: typeConfig.P.color,
emissive: typeConfig.P.emissive,
emissiveIntensity: 0.9,
metalness: 0.25,
roughness: 0.2
});
let particles = [];
let effects = [];
const state = {
paused: false,
probability: 0.35,
speed: 1,
encounters: 0,
formed: 0,
elapsed: 0,
dirty: true
};
function makeParticle(type) {
const group = new THREE.Group();
const config = typeConfig[type];
if (type === "A") {
group.add(new THREE.Mesh(geometryA, materialA));
} else if (type === "B") {
group.add(new THREE.Mesh(geometryB, materialB));
} else {
const center = new THREE.Mesh(
geometryProductCenter,
materialProduct
);
const left = new THREE.Mesh(
geometryProductLobe,
materialProduct
);
const right = new THREE.Mesh(
geometryProductLobe,
materialProduct
);
left.position.x = -0.145;
right.position.x = 0.145;
group.add(center, left, right);
}
const haloMaterial = new THREE.SpriteMaterial({
map: haloTexture,
color: config.color,
transparent: true,
opacity: 0.47,
blending: THREE.AdditiveBlending,
depthWrite: false
});
const halo = new THREE.Sprite(haloMaterial);
halo.scale.setScalar(type === "P" ? 1.25 : 0.92);
halo.renderOrder = 2;
group.add(halo);
return {
type,
mesh: group,
halo,
radius: config.radius,
velocity: new THREE.Vector3(),
spin: new THREE.Vector3(
Math.random() * 2 - 1,
Math.random() * 2 - 1,
Math.random() * 2 - 1
),
dead: false
};
}
function randomUnitVector() {
const z = Math.random() * 2 - 1;
const angle = Math.random() * Math.PI * 2;
const radius = Math.sqrt(1 - z * z);
return new THREE.Vector3(
radius * Math.cos(angle),
z,
radius * Math.sin(angle)
);
}
function randomInteriorPosition() {
const direction = randomUnitVector();
const radius = Math.cbrt(Math.random()) * 3.92;
return direction.multiplyScalar(radius);
}
function initializeParticles() {
for (const particle of particles) {
particle.halo.material.dispose();
particleLayer.remove(particle.mesh);
}
particles = [];
const initialA = 32;
const initialB = 32;
for (let i = 0; i < initialA + initialB; i++) {
const type = i < initialA ? "A" : "B";
const particle = makeParticle(type);
let position = randomInteriorPosition();
let attempts = 0;
// Avoid severe initial overlaps.
while (attempts++ < 80) {
let overlaps = false;
for (const other of particles) {
const dx = position.x - other.mesh.position.x;
const dy = position.y - other.mesh.position.y;
const dz = position.z - other.mesh.position.z;
if (dx * dx + dy * dy + dz * dz < 0.42) {
overlaps = true;
break;
}
}
if (!overlaps) break;
position = randomInteriorPosition();
}
particle.mesh.position.set(
position.x,
position.y + CENTER_Y,
position.z
);
const velocity = randomUnitVector();
velocity.y *= 0.65;
velocity.x += -position.z * 0.09;
velocity.z += position.x * 0.09;
velocity.normalize().multiplyScalar(0.8 + Math.random() * 0.65);
particle.velocity.copy(velocity);
particleLayer.add(particle.mesh);
particles.push(particle);
}
state.encounters = 0;
state.formed = 0;
state.elapsed = 0;
state.dirty = true;
updateHUD();
}
function createReactionEffect(position) {
const material = new THREE.SpriteMaterial({
map: ringTexture,
color: 0xffd166,
transparent: true,
opacity: 0.95,
blending: THREE.AdditiveBlending,
depthWrite: false,
depthTest: false
});
const sprite = new THREE.Sprite(material);
sprite.position.copy(position);
sprite.scale.setScalar(0.65);
sprite.renderOrder = 15;
effectLayer.add(sprite);
effects.push({
sprite,
age: 0,
life: 0.72
});
}
function updateEffects(dt) {
for (let i = effects.length - 1; i >= 0; i--) {
const effect = effects[i];
effect.age += dt;
const t = Math.min(effect.age / effect.life, 1);
effect.sprite.scale.setScalar(0.65 + t * 2.4);
effect.sprite.material.opacity = (1 - t) * 0.95;
effect.sprite.position.y += dt * 0.32;
if (t >= 1) {
effectLayer.remove(effect.sprite);
effect.sprite.material.dispose();
effects.splice(i, 1);
}
}
}
// -------------------------------------------------------------------------
// Collision and reaction simulation
// -------------------------------------------------------------------------
function simulate(dt) {
const pendingProducts = [];
// Move particles and reflect them from the spherical boundary.
for (const particle of particles) {
if (particle.dead) continue;
particle.mesh.position.addScaledVector(particle.velocity, dt);
particle.mesh.rotation.x += particle.spin.x * dt;
particle.mesh.rotation.y += particle.spin.y * dt;
particle.mesh.rotation.z += particle.spin.z * dt;
let dx = particle.mesh.position.x;
let dy = particle.mesh.position.y - CENTER_Y;
let dz = particle.mesh.position.z;
let distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
const limit = PARTICLE_LIMIT - particle.radius;
if (distance > limit) {
const nx = dx / distance;
const ny = dy / distance;
const nz = dz / distance;
const normalVelocity =
particle.velocity.x * nx +
particle.velocity.y * ny +
particle.velocity.z * nz;
if (normalVelocity > 0) {
particle.velocity.x -= 2 * normalVelocity * nx;
particle.velocity.y -= 2 * normalVelocity * ny;
particle.velocity.z -= 2 * normalVelocity * nz;
}
particle.mesh.position.set(
nx * limit,
CENTER_Y + ny * limit,
nz * limit
);
}
}
// A small attraction field helps opposing reactants find one another.
// It does not change the encounter probability.
for (let i = 0; i < particles.length; i++) {
const a = particles[i];
if (a.dead || a.type === "P") continue;
for (let j = i + 1; j < particles.length; j++) {
const b = particles[j];
if (b.dead || b.type === "P") continue;
if (a.type === b.type) continue;
const dx = b.mesh.position.x - a.mesh.position.x;
const dy = b.mesh.position.y - a.mesh.position.y;
const dz = b.mesh.position.z - a.mesh.position.z;
const d2 = dx * dx + dy * dy + dz * dz;
if (d2 < 1.69 && d2 > 0.0001) {
const distance = Math.sqrt(d2);
const force = 0.32 * dt / distance;
a.velocity.x += dx * force;
a.velocity.y += dy * force;
a.velocity.z += dz * force;
b.velocity.x -= dx * force;
b.velocity.y -= dy * force;
b.velocity.z -= dz * force;
}
}
}
// Detect encounters and resolve collisions.
for (let i = 0; i < particles.length; i++) {
const a = particles[i];
if (a.dead) continue;
for (let j = i + 1; j < particles.length; j++) {
const b = particles[j];
if (b.dead) continue;
const dx = b.mesh.position.x - a.mesh.position.x;
const dy = b.mesh.position.y - a.mesh.position.y;
const dz = b.mesh.position.z - a.mesh.position.z;
const combinedRadius = a.radius + b.radius;
const d2 = dx * dx + dy * dy + dz * dz;
if (d2 >= combinedRadius * combinedRadius) continue;
let distance = Math.sqrt(d2);
let nx;
let ny;
let nz;
if (distance < 0.0001) {
const random = randomUnitVector();
nx = random.x;
ny = random.y;
nz = random.z;
distance = 0.0001;
} else {
nx = dx / distance;
ny = dy / distance;
nz = dz / distance;
}
const relativeNormalVelocity =
(b.velocity.x - a.velocity.x) * nx +
(b.velocity.y - a.velocity.y) * ny +
(b.velocity.z - a.velocity.z) * nz;
// A contact counts only while the particles are approaching.
if (relativeNormalVelocity >= 0) continue;
const isReactantPair =
(a.type === "A" && b.type === "B") ||
(a.type === "B" && b.type === "A");
if (isReactantPair) {
state.encounters++;
if (Math.random() < state.probability) {
const product = makeParticle("P");
product.mesh.position.set(
(a.mesh.position.x + b.mesh.position.x) * 0.5,
(a.mesh.position.y + b.mesh.position.y) * 0.5,
(a.mesh.position.z + b.mesh.position.z) * 0.5
);
product.velocity.set(
(a.velocity.x + b.velocity.x) * 0.5,
(a.velocity.y + b.velocity.y) * 0.5,
(a.velocity.z + b.velocity.z) * 0.5
);
product.velocity.x += nx * 0.24;
product.velocity.y += ny * 0.24;
product.velocity.z += nz * 0.24;
a.dead = true;
b.dead = true;
state.formed++;
particleLayer.remove(a.mesh, b.mesh);
a.halo.material.dispose();
b.halo.material.dispose();
createReactionEffect(product.mesh.position);
pendingProducts.push(product);
state.dirty = true;
continue;
}
}
// Elastic collision response for non-reacting contacts.
const impulse =
-(1.0 + 0.88) * relativeNormalVelocity * 0.5;
a.velocity.x -= impulse * nx;
a.velocity.y -= impulse * ny;
a.velocity.z -= impulse * nz;
b.velocity.x += impulse * nx;
b.velocity.y += impulse * ny;
b.velocity.z += impulse * nz;
}
}
// Apply a gentle speed limit after attraction and collision impulses.
for (const particle of particles) {
if (particle.dead) continue;
const speed = particle.velocity.length();
if (speed > 2.35) {
particle.velocity.multiplyScalar(2.35 / speed);
}
}
particles = particles.filter((particle) => !particle.dead);
for (const product of pendingProducts) {
particleLayer.add(product.mesh);
particles.push(product);
}
}
// -------------------------------------------------------------------------
// HUD
// -------------------------------------------------------------------------
const probabilityInput = document.querySelector("#probability");
const speedInput = document.querySelector("#speed");
const probabilityValue = document.querySelector("#probabilityValue");
const speedValue = document.querySelector("#speedValue");
const pauseButton = document.querySelector("#pauseButton");
const resetButton = document.querySelector("#resetButton");
const liveStatus = document.querySelector("#liveStatus");
function setRangeFill(input) {
const percent =
100 * (Number(input.value) - Number(input.min)) /
(Number(input.max) - Number(input.min));
input.style.setProperty("--fill", `${percent}%`);
}
probabilityInput.addEventListener("input", () => {
state.probability = Number(probabilityInput.value) / 100;
probabilityValue.value = `${probabilityInput.value}%`;
setRangeFill(probabilityInput);
});
speedInput.addEventListener("input", () => {
state.speed = Number(speedInput.value);
speedValue.value = `${state.speed.toFixed(1)}×`;
setRangeFill(speedInput);
});
pauseButton.addEventListener("click", () => {
state.paused = !state.paused;
pauseButton.textContent = state.paused ? "Resume" : "Pause";
liveStatus.textContent = state.paused ? "PAUSED" : "LIVE";
liveStatus.style.color = state.paused ? "#ffd166" : "#75f0bc";
});
resetButton.addEventListener("click", () => {
for (const effect of effects) {
effectLayer.remove(effect.sprite);
effect.sprite.material.dispose();
}
effects = [];
initializeParticles();
});
function updateHUD() {
let countA = 0;
let countB = 0;
let countP = 0;
for (const particle of particles) {
if (particle.type === "A") countA++;
else if (particle.type === "B") countB++;
else countP++;
}
document.querySelector("#countA").textContent = countA;
document.querySelector("#countB").textContent = countB;
document.querySelector("#countP").textContent = countP;
document.querySelector("#encounterCount").textContent = state.encounters;
document.querySelector("#formedCount").textContent = state.formed;
document.querySelector("#elapsed").textContent =
`${state.elapsed.toFixed(1)}s`;
const remaining = countA + countB;
const initialRemaining = 64;
const percent = (remaining / initialRemaining) * 100;
document.querySelector("#remainingText").textContent =
`${remaining} / ${initialRemaining}`;
document.querySelector("#remainingBar").style.width =
`${Math.max(0, percent)}%`;
state.dirty = false;
}
setRangeFill(probabilityInput);
setRangeFill(speedInput);
initializeParticles();
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
});
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const rawDelta = Math.min(clock.getDelta(), 0.05);
updateCamera(rawDelta);
if (!state.paused) {
const scaledDelta = rawDelta * state.speed;
const substeps = Math.max(1, Math.ceil(scaledDelta / 0.014));
const stepDelta = scaledDelta / substeps;
for (let i = 0; i < substeps; i++) {
simulate(stepDelta);
}
updateEffects(scaledDelta);
state.elapsed += scaledDelta;
state.dirty = true;
}
if (state.dirty) updateHUD();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```