Prompt specification
Build or customize the Three.js 3D scene "Limiting and excess reactant 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: Limiting and excess reactant comparison
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/limiting-and-excess-reactant-comparison-x1998
Scene Description Prompt:
Please make a cutaway Three.js scene in one standalone HTML file using cdnjs. Run two starting mixtures through the same symbolic reaction rule; stop when one required reactant is exhausted and display leftover tokens without destroying them.
Working Three.js Starter (limiting-and-excess-reactant-comparison-x1998):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cutaway Symbolic Reaction Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #070b17;
--panel: rgba(13, 20, 39, 0.78);
--border: rgba(148, 163, 184, 0.22);
--text: #eef6ff;
--muted: #94a3b8;
--cyan: #48d7ff;
--pink: #ff627d;
--gold: #ffd166;
--green: #69efb1;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
canvas {
position: fixed;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.hud {
position: fixed;
inset: 0;
z-index: 2;
pointer-events: none;
}
.title-block {
position: absolute;
top: 20px;
left: 22px;
max-width: min(520px, calc(100vw - 44px));
padding: 17px 20px;
border: 1px solid var(--border);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 16px 50px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(16px);
}
.eyebrow {
margin-bottom: 6px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(21px, 3vw, 31px);
line-height: 1.1;
letter-spacing: -0.035em;
}
.subtitle {
margin-top: 9px;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.equation {
display: inline-flex;
align-items: center;
gap: 7px;
margin-top: 12px;
padding: 7px 11px;
border: 1px solid rgba(72, 215, 255, 0.22);
border-radius: 999px;
background: rgba(72, 215, 255, 0.07);
color: #dff8ff;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 13px;
font-weight: 700;
}
.controls {
position: absolute;
top: 20px;
right: 22px;
display: flex;
align-items: center;
gap: 9px;
padding: 10px;
border: 1px solid var(--border);
border-radius: 16px;
background: var(--panel);
box-shadow: 0 16px 50px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(16px);
pointer-events: auto;
}
button,
select {
min-height: 40px;
border: 1px solid rgba(148, 163, 184, 0.22);
border-radius: 11px;
background: #111b31;
color: var(--text);
font: inherit;
font-size: 13px;
font-weight: 700;
}
button {
padding: 0 15px;
cursor: pointer;
transition:
transform 140ms ease,
border-color 140ms ease,
background 140ms ease,
opacity 140ms ease;
}
button:hover:not(:disabled) {
transform: translateY(-1px);
border-color: rgba(72, 215, 255, 0.55);
background: #172541;
}
button:active:not(:disabled) {
transform: translateY(0);
}
button:disabled {
cursor: default;
opacity: 0.48;
}
#run-button {
border-color: transparent;
background: linear-gradient(135deg, #29c4ef, #6887ff);
color: #04111e;
}
#run-button:hover:not(:disabled) {
background: linear-gradient(135deg, #4cd7ff, #819aff);
}
select {
padding: 0 32px 0 11px;
cursor: pointer;
}
.legend {
position: absolute;
top: 190px;
left: 22px;
display: flex;
flex-wrap: wrap;
gap: 12px;
max-width: 460px;
padding: 11px 14px;
border: 1px solid var(--border);
border-radius: 14px;
background: rgba(13, 20, 39, 0.66);
color: var(--muted);
font-size: 12px;
backdrop-filter: blur(12px);
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 6px;
}
.dot {
width: 11px;
height: 11px;
border-radius: 50%;
box-shadow: 0 0 12px currentColor;
}
.dot.a {
color: var(--pink);
background: var(--pink);
}
.dot.b {
color: var(--cyan);
background: var(--cyan);
}
.dot.c {
color: var(--gold);
background: var(--gold);
}
.readouts {
position: absolute;
bottom: 20px;
left: 50%;
display: flex;
gap: 12px;
width: min(720px, calc(100vw - 32px));
transform: translateX(-50%);
}
.readout {
flex: 1 1 0;
min-width: 0;
padding: 14px 16px;
border: 1px solid var(--border);
border-radius: 17px;
background: var(--panel);
box-shadow: 0 16px 50px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(16px);
}
.readout-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
}
.readout h2 {
margin: 0;
font-size: 14px;
letter-spacing: -0.01em;
}
.status {
padding: 4px 8px;
border: 1px solid rgba(148, 163, 184, 0.2);
border-radius: 999px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.04em;
white-space: nowrap;
}
.status[data-state="running"] {
border-color: rgba(72, 215, 255, 0.35);
color: var(--cyan);
background: rgba(72, 215, 255, 0.08);
}
.status[data-state="stopped"] {
border-color: rgba(105, 239, 177, 0.35);
color: var(--green);
background: rgba(105, 239, 177, 0.08);
}
.counts {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.count {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 5px 8px;
border: 1px solid rgba(148, 163, 184, 0.16);
border-radius: 9px;
background: rgba(255, 255, 255, 0.025);
color: var(--muted);
font-size: 11px;
}
.count strong {
color: var(--text);
font-size: 13px;
}
.leftover {
margin-top: 9px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.leftover strong {
color: #f7fbff;
}
.camera-hint {
position: absolute;
right: 22px;
bottom: 22px;
padding: 8px 11px;
border: 1px solid rgba(148, 163, 184, 0.16);
border-radius: 10px;
background: rgba(7, 11, 23, 0.66);
color: var(--muted);
font-size: 11px;
backdrop-filter: blur(10px);
}
@media (max-width: 760px) {
.title-block {
top: 12px;
left: 12px;
right: 12px;
max-width: none;
padding: 14px;
}
.subtitle {
display: none;
}
.equation {
margin-top: 9px;
}
.controls {
top: 145px;
right: 12px;
padding: 7px;
}
.legend {
top: 145px;
left: 12px;
max-width: 190px;
gap: 8px;
padding: 9px 11px;
}
.readouts {
bottom: 10px;
width: calc(100vw - 20px);
gap: 7px;
}
.readout {
padding: 11px 10px;
}
.readout-header {
align-items: flex-start;
flex-direction: column;
gap: 6px;
}
.count {
padding: 4px 6px;
}
.camera-hint {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive cutaway reaction scene"></canvas>
<main class="hud">
<section class="title-block">
<div class="eyebrow">Symbolic reaction laboratory</div>
<h1>Cutaway Token Reaction</h1>
<div class="subtitle">
Two different starting mixtures, one shared reaction rule.
Each vessel stops independently when either required reactant reaches zero.
</div>
<div class="equation">A + B → C</div>
</section>
<section class="controls" aria-label="Simulation controls">
<button id="run-button" type="button">Run mixtures</button>
<button id="reset-button" type="button">Reset</button>
<select id="speed-select" aria-label="Reaction speed">
<option value="0.65">Slow</option>
<option value="1" selected>Normal</option>
<option value="1.6">Fast</option>
</select>
<button id="view-button" type="button">Reset view</button>
</section>
<section class="legend" aria-label="Token legend">
<span class="legend-item"><span class="dot a"></span>A reactant</span>
<span class="legend-item"><span class="dot b"></span>B reactant</span>
<span class="legend-item"><span class="dot c"></span>C product</span>
<span class="legend-item">◌ Halo = unreacted leftover</span>
</section>
<section class="readouts">
<article class="readout">
<div class="readout-header">
<h2>Mixture 1</h2>
<span id="status-1" class="status" data-state="ready" aria-live="polite">
Ready
</span>
</div>
<div class="counts">
<span class="count"><span class="dot a"></span>A <strong id="a-1">5</strong></span>
<span class="count"><span class="dot b"></span>B <strong id="b-1">4</strong></span>
<span class="count"><span class="dot c"></span>C <strong id="c-1">0</strong></span>
</div>
<div class="leftover" id="leftover-1">
Starting mixture: <strong>A×5, B×4</strong>
</div>
</article>
<article class="readout">
<div class="readout-header">
<h2>Mixture 2</h2>
<span id="status-2" class="status" data-state="ready" aria-live="polite">
Ready
</span>
</div>
<div class="counts">
<span class="count"><span class="dot a"></span>A <strong id="a-2">3</strong></span>
<span class="count"><span class="dot b"></span>B <strong id="b-2">5</strong></span>
<span class="count"><span class="dot c"></span>C <strong id="c-2">0</strong></span>
</div>
<div class="leftover" id="leftover-2">
Starting mixture: <strong>A×3, B×5</strong>
</div>
</article>
</section>
<div class="camera-hint">Drag to orbit · Scroll to zoom · Double-click to reset</div>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene setup
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x070b17);
scene.fog = new THREE.FogExp2(0x070b17, 0.027);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const clock = new THREE.Clock();
const hemisphere = new THREE.HemisphereLight(0xc8e8ff, 0x111426, 2.1);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(4.5, 8, 5.5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -8;
keyLight.shadow.camera.right = 8;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -8;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x2cc9ff, 28, 14, 2);
rimLight.position.set(-5, 3.8, -2.5);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xff6388, 22, 12, 2);
warmLight.position.set(5, 2.8, 1.5);
scene.add(warmLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(30, 30),
new THREE.MeshStandardMaterial({
color: 0x0a1020,
roughness: 0.88,
metalness: 0.08
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.09;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(20, 40, 0x23314c, 0x111a2d);
grid.position.y = -0.075;
grid.material.transparent = true;
grid.material.opacity = 0.48;
scene.add(grid);
// -------------------------------------------------------------------------
// Shared token geometry/materials
// -------------------------------------------------------------------------
const tokenGeometry = new THREE.SphereGeometry(0.16, 24, 16);
const tokenMaterials = {
A: new THREE.MeshStandardMaterial({
color: 0xff627d,
emissive: 0x5a1020,
emissiveIntensity: 0.52,
roughness: 0.28,
metalness: 0.08
}),
B: new THREE.MeshStandardMaterial({
color: 0x48d7ff,
emissive: 0x073d54,
emissiveIntensity: 0.55,
roughness: 0.28,
metalness: 0.08
}),
C: new THREE.MeshStandardMaterial({
color: 0xffd166,
emissive: 0x5a3c05,
emissiveIntensity: 0.58,
roughness: 0.24,
metalness: 0.12
})
};
const haloTexture = createHaloTexture();
// Fixed token slots keep leftover tokens stable and visible.
const TOKEN_HOMES = {
A: [
new THREE.Vector3(-0.42, 0.50, 0.26),
new THREE.Vector3(-0.70, 0.50, -0.02),
new THREE.Vector3(-0.40, 0.50, -0.30),
new THREE.Vector3(-0.68, 0.78, -0.18),
new THREE.Vector3(-0.40, 0.78, 0.14)
],
B: [
new THREE.Vector3(0.42, 0.50, 0.26),
new THREE.Vector3(0.70, 0.50, -0.02),
new THREE.Vector3(0.40, 0.50, -0.30),
new THREE.Vector3(0.68, 0.78, -0.18),
new THREE.Vector3(0.40, 0.78, 0.14)
],
C: [
new THREE.Vector3(0.00, 0.50, 0.38),
new THREE.Vector3(0.00, 0.74, 0.08),
new THREE.Vector3(0.00, 0.98, -0.22),
new THREE.Vector3(0.00, 1.22, -0.10)
]
};
const REACTION_CENTER = new THREE.Vector3(0, 0.88, 0.24);
// -------------------------------------------------------------------------
// Small procedural textures, using only the Three.js core
// -------------------------------------------------------------------------
function createTokenLabel(letter, color) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 128;
labelCanvas.height = 128;
const context = labelCanvas.getContext("2d");
context.clearRect(0, 0, 128, 128);
context.beginPath();
context.arc(64, 64, 43, 0, Math.PI * 2);
context.fillStyle = "rgba(5, 10, 23, 0.88)";
context.fill();
context.lineWidth = 5;
context.strokeStyle = color;
context.stroke();
context.fillStyle = "#ffffff";
context.font = "800 70px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(letter, 64, 66);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(0.245, 0.245, 1);
sprite.renderOrder = 20;
sprite.userData.ownsTexture = true;
return sprite;
}
function createTitleSprite(text, accent) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 128;
const context = labelCanvas.getContext("2d");
context.clearRect(0, 0, 512, 128);
context.fillStyle = "rgba(7, 13, 28, 0.88)";
context.strokeStyle = accent;
context.lineWidth = 3;
context.beginPath();
context.roundRect(5, 5, 502, 118, 32);
context.fill();
context.stroke();
context.fillStyle = "#f3f8ff";
context.font = "800 52px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 256, 66);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(1.65, 0.42, 1);
sprite.renderOrder = 30;
sprite.userData.ownsTexture = true;
return sprite;
}
function createHaloTexture() {
const haloCanvas = document.createElement("canvas");
haloCanvas.width = 128;
haloCanvas.height = 128;
const context = haloCanvas.getContext("2d");
const gradient = context.createRadialGradient(
64, 64, 25,
64, 64, 64
);
gradient.addColorStop(0, "rgba(255,255,255,0)");
gradient.addColorStop(0.53, "rgba(255,255,255,0)");
gradient.addColorStop(0.65, "rgba(255,255,255,0.92)");
gradient.addColorStop(0.76, "rgba(255,255,255,0.20)");
gradient.addColorStop(1, "rgba(255,255,255,0)");
context.fillStyle = gradient;
context.fillRect(0, 0, 128, 128);
const texture = new THREE.CanvasTexture(haloCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
// -------------------------------------------------------------------------
// Cutaway vessel construction
// -------------------------------------------------------------------------
const glassMaterial = new THREE.MeshPhysicalMaterial({
color: 0x9ddfff,
transparent: true,
opacity: 0.16,
roughness: 0.12,
metalness: 0.02,
side: THREE.DoubleSide,
depthWrite: false
});
const baseGlassMaterial = new THREE.MeshPhysicalMaterial({
color: 0x8fd8ff,
transparent: true,
opacity: 0.25,
roughness: 0.15,
metalness: 0.02,
side: THREE.DoubleSide,
depthWrite: false
});
const pedestalMaterial = new THREE.MeshStandardMaterial({
color: 0x111a2e,
roughness: 0.58,
metalness: 0.35
});
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x69e7ff,
transparent: true,
opacity: 0.88
});
function createArcLine(radius, y, start, length) {
const points = [];
for (let i = 0; i <= 90; i++) {
const theta = start + (i / 90) * length;
points.push(
new THREE.Vector3(
Math.sin(theta) * radius,
y,
Math.cos(theta) * radius
)
);
}
const geometry = new THREE.BufferGeometry().setFromPoints(points);
return new THREE.Line(geometry, edgeMaterial);
}
function createVerticalEdge(radius, height, theta) {
const points = [
new THREE.Vector3(
Math.sin(theta) * radius,
height * 0.5,
Math.cos(theta) * radius
),
new THREE.Vector3(
Math.sin(theta) * radius,
-height * 0.5,
Math.cos(theta) * radius
)
];
const geometry = new THREE.BufferGeometry().setFromPoints(points);
return new THREE.Line(geometry, edgeMaterial);
}
function buildCutawayVessel(title, accent) {
const root = new THREE.Group();
const radius = 1.04;
const height = 2.65;
// The missing front 126-degree wedge forms the cutaway opening.
const thetaStart = Math.PI * 0.35;
const thetaLength = Math.PI * 1.30;
const shell = new THREE.Mesh(
new THREE.CylinderGeometry(
radius,
radius,
height,
64,
1,
true,
thetaStart,
thetaLength
),
glassMaterial
);
shell.position.y = 1.55;
shell.renderOrder = 4;
root.add(shell);
const bottom = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius, 0.09, 64),
baseGlassMaterial
);
bottom.position.y = 0.225;
bottom.renderOrder = 3;
root.add(bottom);
const pedestal = new THREE.Mesh(
new THREE.CylinderGeometry(1.21, 1.31, 0.17, 64),
pedestalMaterial
);
pedestal.position.y = 0.085;
pedestal.castShadow = true;
pedestal.receiveShadow = true;
root.add(pedestal);
const pedestalRing = new THREE.Mesh(
new THREE.TorusGeometry(1.205, 0.012, 8, 64),
new THREE.MeshBasicMaterial({
color: accent,
transparent: true,
opacity: 0.72
})
);
pedestalRing.rotation.x = Math.PI / 2;
pedestalRing.position.y = 0.175;
root.add(pedestalRing);
root.add(createArcLine(radius, 2.875, thetaStart, thetaLength));
root.add(createArcLine(radius, 0.225, thetaStart, thetaLength));
root.add(
createVerticalEdge(
radius,
height,
thetaStart
)
);
root.add(
createVerticalEdge(
radius,
height,
thetaStart + thetaLength
)
);
const titleSprite = createTitleSprite(title, accent);
titleSprite.position.set(0, 3.20, 0);
root.add(titleSprite);
return root;
}
// -------------------------------------------------------------------------
// Mixture class
// -------------------------------------------------------------------------
class Mixture {
constructor({ index, x, initial, accent }) {
this.index = index;
this.initial = { ...initial };
this.accent = accent;
this.speed = 1;
this.root = new THREE.Group();
this.root.position.x = x;
scene.add(this.root);
this.vessel = buildCutawayVessel(`Mixture ${index}`, accent);
this.root.add(this.vessel);
this.tokenRoot = new THREE.Group();
this.root.add(this.tokenRoot);
this.ui = {
a: document.querySelector(`#a-${index}`),
b: document.querySelector(`#b-${index}`),
c: document.querySelector(`#c-${index}`),
status: document.querySelector(`#status-${index}`),
leftover: document.querySelector(`#leftover-${index}`)
};
this.reset();
}
reset() {
this.clearTokens();
this.state = { ...this.initial };
this.tokens = { A: [], B: [], C: [] };
this.phase = "ready";
this.stopReason = "";
this.reaction = null;
this.cooldown = 0;
for (const kind of ["A", "B"]) {
for (let i = 0; i < this.initial[kind]; i++) {
this.tokens[kind].push(
this.createToken(kind, TOKEN_HOMES[kind][i])
);
}
}
this.updateUI();
}
clearTokens() {
if (!this.tokens) return;
for (const list of Object.values(this.tokens)) {
for (const token of list) {
this.tokenRoot.remove(token.group);
token.group.traverse((object) => {
if (object.isSprite && object.userData.ownsTexture) {
object.material.map?.dispose();
object.material.dispose();
}
});
}
}
}
createToken(kind, home) {
const group = new THREE.Group();
group.position.copy(home);
const mesh = new THREE.Mesh(tokenGeometry, tokenMaterials[kind]);
mesh.castShadow = true;
mesh.receiveShadow = true;
group.add(mesh);
const labelColor =
kind === "A" ? "#ff627d" :
kind === "B" ? "#48d7ff" :
"#ffd166";
const label = createTokenLabel(kind, labelColor);
label.position.set(0, 0.025, 0.145);
group.add(label);
this.tokenRoot.add(group);
return {
kind,
group,
home: home.clone(),
available: true,
halo: null
};
}
start() {
if (this.phase === "ready") {
this.phase = "running";
this.cooldown = 0.08;
this.updateUI();
}
}
beginReaction() {
const a = this.tokens.A.find((token) => token.available);
const b = this.tokens.B.find((token) => token.available);
if (!a || !b) {
this.stop(
this.state.A === 0 ? "A" :
this.state.B === 0 ? "B" :
"a required reactant"
);
return;
}
a.available = false;
b.available = false;
this.reaction = {
a,
b,
elapsed: 0,
spawned: false,
product: null
};
}
spawnProduct() {
const reaction = this.reaction;
const productIndex = this.state.C;
this.state.A -= 1;
this.state.B -= 1;
this.state.C += 1;
const productHome =
TOKEN_HOMES.C[Math.min(productIndex, TOKEN_HOMES.C.length - 1)];
const product = this.createToken("C", REACTION_CENTER);
product.group.scale.setScalar(0.001);
product.home.copy(productHome);
this.tokens.C.push(product);
reaction.product = product;
reaction.spawned = true;
// Stop immediately when either required reactant is exhausted.
if (this.state.A === 0 || this.state.B === 0) {
const exhausted =
this.state.A === 0 && this.state.B === 0
? "A and B"
: this.state.A === 0
? "A"
: "B";
this.stop(exhausted);
}
this.updateUI();
}
stop(exhaustedReactant) {
this.phase = "stopped";
this.stopReason = exhaustedReactant;
this.markLeftovers();
}
markLeftovers() {
for (const kind of ["A", "B"]) {
for (const token of this.tokens[kind]) {
if (!token.available || token.halo) continue;
const halo = new THREE.Sprite(
new THREE.SpriteMaterial({
map: haloTexture,
color: 0xffffff,
transparent: true,
opacity: 0.75,
depthTest: false,
depthWrite: false,
blending: THREE.AdditiveBlending
})
);
halo.scale.set(0.50, 0.50, 1);
halo.renderOrder = 18;
token.group.add(halo);
token.halo = halo;
}
}
}
updateReaction(dt) {
const reaction = this.reaction;
if (!reaction) return;
const duration = 1.45 / this.speed;
reaction.elapsed += dt;
const progress = Math.min(reaction.elapsed / duration, 1);
const travelProgress = easeInOutCubic(
THREE.MathUtils.clamp(progress / 0.58, 0, 1)
);
reaction.a.group.position.lerpVectors(
reaction.a.home,
REACTION_CENTER,
travelProgress
);
reaction.b.group.position.lerpVectors(
reaction.b.home,
REACTION_CENTER,
travelProgress
);
const shrink = 1 - 0.48 * THREE.MathUtils.clamp(
(progress - 0.20) / 0.36,
0,
1
);
reaction.a.group.scale.setScalar(Math.max(0.05, shrink));
reaction.b.group.scale.setScalar(Math.max(0.05, shrink));
if (progress >= 0.50 && !reaction.spawned) {
this.spawnProduct();
}
if (reaction.spawned && reaction.product) {
const productProgress = easeOutCubic(
THREE.MathUtils.clamp((progress - 0.50) / 0.50, 0, 1)
);
reaction.product.group.position.lerpVectors(
REACTION_CENTER,
reaction.product.home,
productProgress
);
const productScale = easeOutBack(productProgress);
reaction.product.group.scale.setScalar(
Math.max(0.001, productScale)
);
}
if (progress >= 0.98) {
reaction.a.group.visible = false;
reaction.b.group.visible = false;
this.reaction = null;
if (this.phase === "running") {
this.cooldown = 0.12;
}
}
}
update(dt) {
if (this.reaction) {
this.updateReaction(dt);
} else if (this.phase === "running") {
this.cooldown -= dt;
if (this.cooldown <= 0) {
this.beginReaction();
}
}
// Only leftover tokens receive the pulsing halo.
for (const kind of ["A", "B"]) {
for (const token of this.tokens[kind]) {
if (token.halo) {
token.halo.material.opacity =
0.56 + Math.sin(performance.now() * 0.004) * 0.18;
}
}
}
}
updateUI() {
this.ui.a.textContent = this.state.A;
this.ui.b.textContent = this.state.B;
this.ui.c.textContent = this.state.C;
this.ui.status.dataset.state = this.phase;
if (this.phase === "ready") {
this.ui.status.textContent = "Ready";
this.ui.leftover.innerHTML =
`Starting mixture: <strong>A×${this.initial.A}, B×${this.initial.B}</strong>`;
} else if (this.phase === "running") {
this.ui.status.textContent = "Reacting…";
this.ui.leftover.innerHTML =
`Unreacted now: <strong>A×${this.state.A}, B×${this.state.B}</strong>`;
} else {
this.ui.status.textContent =
`Stopped — ${this.stopReason} exhausted`;
const leftovers = [];
if (this.state.A > 0) leftovers.push(`A×${this.state.A}`);
if (this.state.B > 0) leftovers.push(`B×${this.state.B}`);
this.ui.leftover.innerHTML = leftovers.length
? `Leftover tokens preserved: <strong>${leftovers.join(" + ")}</strong>`
: `No unreacted reactants remain. <strong>C×${this.state.C}</strong>`;
}
}
}
// -------------------------------------------------------------------------
// Easing
// -------------------------------------------------------------------------
function easeInOutCubic(value) {
return value < 0.5
? 4 * value * value * value
: 1 - Math.pow(-2 * value + 2, 3) / 2;
}
function easeOutCubic(value) {
return 1 - Math.pow(1 - value, 3);
}
function easeOutBack(value) {
const c1 = 1.70158;
const c3 = c1 + 1;
return (
1 +
c3 * Math.pow(value - 1, 3) +
c1 * Math.pow(value - 1, 2)
);
}
// -------------------------------------------------------------------------
// Create the two mixtures
// -------------------------------------------------------------------------
const mixtures = [
new Mixture({
index: 1,
x: -1.58,
initial: { A: 5, B: 4, C: 0 },
accent: "#48d7ff"
}),
new Mixture({
index: 2,
x: 1.58,
initial: { A: 3, B: 5, C: 0 },
accent: "#ff627d"
})
];
// -------------------------------------------------------------------------
// Directly implemented orbit camera controls — no addons
// -------------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 1.30, 0);
let desiredAzimuth = 0;
let desiredPolar = 1.13;
let desiredRadius = getResponsiveRadius();
let currentAzimuth = desiredAzimuth;
let currentPolar = desiredPolar;
let currentRadius = desiredRadius;
let dragging = false;
let pointerX = 0;
let pointerY = 0;
let hasUserMovedCamera = false;
function getResponsiveRadius() {
return window.innerWidth < 760 ? 11.6 : 7.35;
}
function updateCamera(dt) {
const smoothing = 1 - Math.pow(0.0008, dt);
currentAzimuth = THREE.MathUtils.lerp(
currentAzimuth,
desiredAzimuth,
smoothing
);
currentPolar = THREE.MathUtils.lerp(
currentPolar,
desiredPolar,
smoothing
);
currentRadius = THREE.MathUtils.lerp(
currentRadius,
desiredRadius,
smoothing
);
const sinPolar = Math.sin(currentPolar);
camera.position.set(
cameraTarget.x +
currentRadius * sinPolar * Math.sin(currentAzimuth),
cameraTarget.y +
currentRadius * Math.cos(currentPolar),
cameraTarget.z +
currentRadius * sinPolar * Math.cos(currentAzimuth)
);
camera.lookAt(cameraTarget);
}
function resetCameraView() {
desiredAzimuth = 0;
desiredPolar = 1.13;
desiredRadius = getResponsiveRadius();
hasUserMovedCamera = false;
}
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - pointerX;
const deltaY = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
desiredAzimuth -= deltaX * 0.006;
desiredPolar = THREE.MathUtils.clamp(
desiredPolar - deltaY * 0.005,
0.62,
1.43
);
hasUserMovedCamera = true;
});
function endPointerDrag(event) {
dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endPointerDrag);
canvas.addEventListener("pointercancel", endPointerDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
desiredRadius = THREE.MathUtils.clamp(
desiredRadius + event.deltaY * 0.006,
4.6,
14
);
hasUserMovedCamera = true;
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetCameraView);
// -------------------------------------------------------------------------
// UI controls
// -------------------------------------------------------------------------
const runButton = document.querySelector("#run-button");
const resetButton = document.querySelector("#reset-button");
const viewButton = document.querySelector("#view-button");
const speedSelect = document.querySelector("#speed-select");
let simulationHasRun = false;
runButton.addEventListener("click", () => {
if (simulationHasRun) return;
simulationHasRun = true;
runButton.disabled = true;
runButton.textContent = "Running…";
for (const mixture of mixtures) {
mixture.start();
}
});
resetButton.addEventListener("click", () => {
simulationHasRun = false;
runButton.disabled = false;
runButton.textContent = "Run mixtures";
for (const mixture of mixtures) {
mixture.reset();
}
});
viewButton.addEventListener("click", resetCameraView);
speedSelect.addEventListener("change", () => {
const speed = Number(speedSelect.value);
for (const mixture of mixtures) {
mixture.speed = speed;
}
});
window.addEventListener("keydown", (event) => {
if (event.code === "Space") {
event.preventDefault();
runButton.click();
}
if (event.key.toLowerCase() === "r") {
resetButton.click();
}
});
// -------------------------------------------------------------------------
// Resize and animation loop
// -------------------------------------------------------------------------
window.addEventListener("resize", () => {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
if (!hasUserMovedCamera) {
desiredRadius = getResponsiveRadius();
}
});
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
for (const mixture of mixtures) {
mixture.update(dt);
}
if (
simulationHasRun &&
mixtures.every((mixture) => mixture.phase === "stopped")
) {
runButton.textContent = "Run complete";
}
updateCamera(dt);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```