Prompt specification
Build or customize the Three.js 3D scene "Limiting-reactant quantity explorer" 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-reactant quantity explorer
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/limiting-reactant-quantity-explorer-x2000
Scene Description Prompt:
Limiting-reactant quantity explorer. Let users vary initial integer molecule counts for a selected balanced reaction; calculate maximum product count and leftover reactants with exact discrete bookkeeping. Please build this with Three.js from cdnjs in one self-contained HTML file, using low-poly forms.
Working Three.js Starter (limiting-reactant-quantity-explorer-x2000):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>MoleculeLab — Limiting Reactant Explorer</title>
<style>
:root {
color-scheme: dark;
--bg: #07101d;
--panel: #0b1626;
--panel-2: #101d30;
--panel-3: #14243a;
--border: rgba(148, 177, 211, 0.16);
--border-strong: rgba(148, 177, 211, 0.28);
--text: #edf5ff;
--muted: #8fa4bd;
--muted-2: #60758f;
--cyan: #42dac5;
--cyan-soft: rgba(66, 218, 197, 0.13);
--amber: #ffc266;
--amber-soft: rgba(255, 194, 102, 0.12);
--red: #ff6577;
--purple: #9585ff;
--blue: #69a8ff;
--radius: 16px;
--shadow: 0 20px 60px rgba(0, 0, 0, 0.28);
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
overflow: hidden;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
.app {
height: 100vh;
height: 100dvh;
display: flex;
flex-direction: column;
background:
radial-gradient(circle at 82% 4%, rgba(60, 139, 255, 0.08), transparent 32%),
var(--bg);
}
.topbar {
height: 72px;
flex: 0 0 72px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 0 24px;
border-bottom: 1px solid var(--border);
background: rgba(7, 16, 29, 0.82);
backdrop-filter: blur(16px);
z-index: 10;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
position: relative;
width: 39px;
height: 39px;
flex: 0 0 39px;
border: 1px solid rgba(66, 218, 197, 0.35);
border-radius: 12px;
background: linear-gradient(145deg, rgba(66, 218, 197, 0.15), rgba(105, 168, 255, 0.08));
box-shadow: inset 0 0 18px rgba(66, 218, 197, 0.08);
}
.brand-mark span {
position: absolute;
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px rgba(66, 218, 197, 0.5);
}
.brand-mark span:nth-child(1) {
left: 9px;
top: 10px;
}
.brand-mark span:nth-child(2) {
right: 9px;
top: 10px;
}
.brand-mark span:nth-child(3) {
left: 15px;
bottom: 7px;
background: var(--blue);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
height: 1px;
width: 14px;
left: 12px;
top: 14px;
background: rgba(237, 245, 255, 0.55);
transform-origin: left center;
}
.brand-mark::before {
transform: rotate(31deg);
}
.brand-mark::after {
transform: rotate(-31deg);
}
.eyebrow {
margin: 0 0 3px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 17px;
line-height: 1.15;
font-weight: 680;
letter-spacing: -0.02em;
}
.header-meta {
display: flex;
align-items: center;
gap: 10px;
}
.status-pill {
display: inline-flex;
align-items: center;
gap: 8px;
min-height: 34px;
padding: 0 12px;
border: 1px solid var(--border);
border-radius: 999px;
color: var(--muted);
background: rgba(255, 255, 255, 0.025);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.status-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 10px rgba(66, 218, 197, 0.8);
}
.main {
flex: 1;
min-height: 0;
display: grid;
grid-template-columns: 390px minmax(0, 1fr);
}
.sidebar {
position: relative;
z-index: 5;
overflow-y: auto;
padding: 20px;
border-right: 1px solid var(--border);
background:
linear-gradient(180deg, rgba(16, 29, 48, 0.78), rgba(8, 18, 31, 0.96)),
var(--panel);
scrollbar-width: thin;
scrollbar-color: #263a55 transparent;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin: 0 0 11px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.section-title span:last-child {
color: var(--muted-2);
font-size: 9px;
letter-spacing: 0.08em;
}
.reaction-list {
display: grid;
gap: 8px;
margin-bottom: 18px;
}
.reaction-option {
width: 100%;
display: grid;
grid-template-columns: 18px minmax(0, 1fr);
gap: 10px;
align-items: start;
padding: 12px;
text-align: left;
border: 1px solid var(--border);
border-radius: 13px;
background: rgba(255, 255, 255, 0.018);
cursor: pointer;
transition:
border-color 160ms ease,
background 160ms ease,
transform 160ms ease;
}
.reaction-option:hover {
transform: translateY(-1px);
border-color: var(--border-strong);
background: rgba(255, 255, 255, 0.035);
}
.reaction-option.active {
border-color: rgba(66, 218, 197, 0.45);
background: linear-gradient(135deg, rgba(66, 218, 197, 0.105), rgba(105, 168, 255, 0.035));
}
.radio {
width: 16px;
height: 16px;
margin-top: 2px;
display: grid;
place-items: center;
border: 1px solid #415672;
border-radius: 50%;
}
.reaction-option.active .radio {
border-color: var(--cyan);
}
.reaction-option.active .radio::after {
content: "";
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 9px rgba(66, 218, 197, 0.6);
}
.reaction-name {
margin-bottom: 5px;
color: var(--text);
font-size: 12px;
font-weight: 700;
}
.reaction-equation {
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
line-height: 1.45;
}
.equation-card {
padding: 14px;
margin-bottom: 18px;
border: 1px solid rgba(105, 168, 255, 0.19);
border-radius: 14px;
background:
radial-gradient(circle at 90% 0, rgba(105, 168, 255, 0.11), transparent 43%),
rgba(105, 168, 255, 0.04);
}
.equation-main {
color: var(--text);
font-size: 19px;
font-weight: 660;
line-height: 1.35;
letter-spacing: 0.01em;
}
.equation-note {
margin-top: 7px;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.count-list {
display: grid;
gap: 9px;
margin-bottom: 18px;
}
.count-row {
display: grid;
grid-template-columns: 35px minmax(0, 1fr) auto;
gap: 10px;
align-items: center;
padding: 11px;
border: 1px solid var(--border);
border-radius: 13px;
background: rgba(255, 255, 255, 0.022);
}
.coefficient {
width: 32px;
height: 32px;
display: grid;
place-items: center;
border: 1px solid rgba(105, 168, 255, 0.3);
border-radius: 10px;
color: var(--blue);
background: rgba(105, 168, 255, 0.09);
font-size: 13px;
font-weight: 800;
}
.species-name {
font-size: 14px;
font-weight: 730;
line-height: 1.1;
}
.species-detail {
margin-top: 4px;
color: var(--muted-2);
font-size: 10px;
line-height: 1.25;
}
.capacity {
display: inline-block;
margin-top: 6px;
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.03em;
}
.stepper {
display: flex;
align-items: center;
overflow: hidden;
border: 1px solid var(--border-strong);
border-radius: 10px;
background: rgba(4, 10, 18, 0.4);
}
.stepper button {
width: 28px;
height: 31px;
padding: 0;
border: 0;
background: transparent;
color: var(--muted);
cursor: pointer;
}
.stepper button:hover {
color: var(--text);
background: rgba(255, 255, 255, 0.06);
}
.stepper input {
width: 40px;
height: 31px;
padding: 0;
border: 0;
border-right: 1px solid var(--border);
border-left: 1px solid var(--border);
outline: none;
color: var(--text);
background: transparent;
text-align: center;
font-size: 12px;
font-weight: 800;
-moz-appearance: textfield;
}
.stepper input::-webkit-outer-spin-button,
.stepper input::-webkit-inner-spin-button {
margin: 0;
-webkit-appearance: none;
}
.integer-note {
margin: -8px 0 18px;
color: var(--muted-2);
font-size: 10px;
line-height: 1.45;
}
.results {
padding-top: 17px;
border-top: 1px solid var(--border);
}
.limit-card {
position: relative;
overflow: hidden;
padding: 14px;
margin-bottom: 12px;
border: 1px solid rgba(255, 194, 102, 0.25);
border-radius: 14px;
background:
radial-gradient(circle at 92% 8%, rgba(255, 194, 102, 0.14), transparent 42%),
rgba(255, 194, 102, 0.055);
}
.limit-card::before {
content: "";
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 3px;
background: var(--amber);
}
.limit-label {
color: var(--amber);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.limit-title {
margin-top: 6px;
color: var(--text);
font-size: 15px;
font-weight: 750;
}
.limit-detail {
margin-top: 5px;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.yield-card {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 6px 12px;
align-items: center;
padding: 14px;
margin-bottom: 10px;
border: 1px solid rgba(66, 218, 197, 0.22);
border-radius: 14px;
background: linear-gradient(135deg, rgba(66, 218, 197, 0.08), rgba(66, 218, 197, 0.025));
}
.yield-label {
color: var(--cyan);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.yield-total {
grid-row: span 2;
color: var(--cyan);
font-size: 35px;
font-weight: 790;
line-height: 1;
letter-spacing: -0.06em;
}
.yield-subtitle {
color: var(--muted);
font-size: 10px;
}
.product-grid,
.leftover-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
margin-bottom: 17px;
}
.mini-metric {
min-width: 0;
padding: 10px;
border: 1px solid var(--border);
border-radius: 11px;
background: rgba(255, 255, 255, 0.022);
}
.mini-metric span {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 10px;
}
.mini-metric strong {
font-size: 18px;
font-weight: 760;
}
.mini-metric small {
margin-left: 4px;
color: var(--muted-2);
font-size: 9px;
}
.leftover-grid .mini-metric {
border-color: rgba(105, 168, 255, 0.18);
background: rgba(105, 168, 255, 0.045);
}
.actions {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
}
.primary-button,
.secondary-button {
min-height: 40px;
border-radius: 11px;
cursor: pointer;
font-size: 11px;
font-weight: 800;
transition:
transform 150ms ease,
border-color 150ms ease,
background 150ms ease;
}
.primary-button {
border: 1px solid rgba(66, 218, 197, 0.45);
color: #06221e;
background: linear-gradient(135deg, #62e6d2, #3ac7b5);
box-shadow: 0 8px 25px rgba(66, 218, 197, 0.12);
}
.primary-button:hover:not(:disabled) {
transform: translateY(-1px);
background: linear-gradient(135deg, #79f0df, #48d7c4);
}
.primary-button:disabled {
opacity: 0.38;
cursor: not-allowed;
}
.secondary-button {
padding: 0 13px;
border: 1px solid var(--border-strong);
color: var(--muted);
background: rgba(255, 255, 255, 0.025);
}
.secondary-button:hover {
color: var(--text);
background: rgba(255, 255, 255, 0.06);
}
.stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #081321;
}
#scene {
position: absolute;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
cursor: grab;
touch-action: none;
}
#scene canvas:active {
cursor: grabbing;
}
.stage::after {
content: "";
position: absolute;
inset: 0;
pointer-events: none;
background:
linear-gradient(180deg, rgba(3, 9, 17, 0.15), transparent 24%, transparent 73%, rgba(3, 9, 17, 0.28)),
radial-gradient(circle at center, transparent 48%, rgba(2, 8, 15, 0.28) 100%);
z-index: 1;
}
.hud {
position: absolute;
z-index: 3;
pointer-events: none;
}
.hud-top {
top: 18px;
left: 20px;
right: 20px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
}
.view-label {
padding: 10px 12px;
border: 1px solid var(--border);
border-radius: 11px;
background: rgba(7, 16, 29, 0.62);
backdrop-filter: blur(10px);
}
.view-label strong {
display: block;
margin-bottom: 4px;
color: var(--text);
font-size: 10px;
letter-spacing: 0.11em;
}
.view-label span {
color: var(--muted);
font-size: 9px;
}
.scene-badges {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 7px;
}
.scene-badge {
padding: 8px 10px;
border: 1px solid var(--border);
border-radius: 9px;
color: var(--muted);
background: rgba(7, 16, 29, 0.62);
backdrop-filter: blur(10px);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.04em;
}
.scene-badge b {
color: var(--text);
}
.scene-badge.limit b {
color: var(--amber);
}
.scene-badge.yield b {
color: var(--cyan);
}
.camera-tools {
position: absolute;
z-index: 4;
right: 18px;
top: 82px;
display: flex;
gap: 7px;
}
.camera-button {
width: 35px;
height: 35px;
display: grid;
place-items: center;
padding: 0;
border: 1px solid var(--border);
border-radius: 10px;
color: var(--muted);
background: rgba(7, 16, 29, 0.68);
backdrop-filter: blur(10px);
cursor: pointer;
}
.camera-button:hover {
color: var(--text);
border-color: var(--border-strong);
}
.transport {
position: absolute;
z-index: 4;
left: 20px;
right: 20px;
bottom: 18px;
display: grid;
grid-template-columns: auto minmax(150px, 1fr) auto;
gap: 14px;
align-items: center;
padding: 12px 14px;
border: 1px solid var(--border);
border-radius: 14px;
background: rgba(7, 16, 29, 0.76);
backdrop-filter: blur(14px);
box-shadow: var(--shadow);
}
.transport-step {
min-width: 80px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.transport-step strong {
display: block;
margin-top: 4px;
color: var(--text);
font-size: 12px;
letter-spacing: 0;
}
.timeline-wrap {
display: flex;
align-items: center;
gap: 10px;
}
input[type="range"] {
width: 100%;
height: 4px;
appearance: none;
border-radius: 999px;
outline: none;
background:
linear-gradient(
90deg,
var(--cyan) 0%,
var(--cyan) var(--timeline, 0%),
rgba(143, 164, 189, 0.2) var(--timeline, 0%),
rgba(143, 164, 189, 0.2) 100%
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
appearance: none;
border: 3px solid #0b1928;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 0 1px rgba(66, 218, 197, 0.4);
}
input[type="range"]::-moz-range-thumb {
width: 10px;
height: 10px;
border: 3px solid #0b1928;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 0 1px rgba(66, 218, 197, 0.4);
}
.timeline-wrap span {
min-width: 38px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
text-align: right;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 12px;
color: var(--muted);
font-size: 9px;
}
.legend-item {
display: flex;
align-items: center;
gap: 5px;
}
.legend-dot {
width: 7px;
height: 7px;
border-radius: 50%;
}
.legend-dot.hydrogen {
background: #eaf4ff;
}
.legend-dot.oxygen {
background: #ff6174;
}
.legend-dot.carbon {
background: #31d6c3;
}
.legend-dot.nitrogen {
background: #9585ff;
}
.hint {
position: absolute;
z-index: 3;
left: 20px;
bottom: 92px;
padding: 7px 9px;
border-radius: 8px;
color: rgba(143, 164, 189, 0.74);
background: rgba(7, 16, 29, 0.48);
font-size: 9px;
pointer-events: none;
}
@media (max-width: 1000px) {
.main {
grid-template-columns: 345px minmax(0, 1fr);
}
.sidebar {
padding: 16px;
}
.transport {
grid-template-columns: auto minmax(120px, 1fr);
}
.legend {
display: none;
}
}
@media (max-width: 760px) {
body {
overflow: auto;
}
.app {
height: auto;
min-height: 100vh;
}
.topbar {
height: 66px;
flex-basis: 66px;
padding: 0 14px;
}
h1 {
font-size: 14px;
}
.header-meta .status-pill:first-child {
display: none;
}
.main {
display: block;
}
.sidebar {
overflow: visible;
border-right: 0;
border-bottom: 1px solid var(--border);
}
.stage {
height: 70vh;
min-height: 570px;
}
.hud-top {
left: 12px;
right: 12px;
}
.scene-badges {
max-width: 180px;
}
.transport {
left: 12px;
right: 12px;
bottom: 12px;
grid-template-columns: 1fr;
gap: 8px;
}
.transport-step {
display: flex;
align-items: center;
justify-content: space-between;
}
.transport-step strong {
margin: 0;
}
.hint {
left: 12px;
bottom: 112px;
}
}
</style>
</head>
<body>
<div class="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<span></span><span></span><span></span>
</div>
<div>
<p class="eyebrow">MoleculeLab / Stoichiometry</p>
<h1>Limiting Reactant Explorer</h1>
</div>
</div>
<div class="header-meta">
<div class="status-pill">
<span class="status-dot"></span>
Integer-safe model
</div>
<div class="status-pill">Three.js · Low-poly</div>
</div>
</header>
<main class="main">
<aside class="sidebar">
<div class="section-title">
<span>Select a reaction</span>
<span>Balanced</span>
</div>
<div id="reactionList" class="reaction-list"></div>
<div class="equation-card">
<div class="section-title">
<span>Balanced equation</span>
<span>1 reaction unit</span>
</div>
<div id="equationMain" class="equation-main"></div>
<div id="equationNote" class="equation-note"></div>
</div>
<div class="section-title">
<span>Initial reactants</span>
<span>Whole molecules</span>
</div>
<div id="countList" class="count-list"></div>
<p class="integer-note">
Counts use exact integer bookkeeping. No fractional reaction units are rounded.
</p>
<div class="results" aria-live="polite">
<div class="section-title">
<span>Exact result</span>
<span id="extentLabel">0 reaction units</span>
</div>
<div class="limit-card">
<div class="limit-label">Limiting reactant</div>
<div id="limitTitle" class="limit-title">—</div>
<div id="limitDetail" class="limit-detail"></div>
</div>
<div class="yield-card">
<div>
<div class="yield-label">Maximum product</div>
<div class="yield-subtitle">total product molecules</div>
</div>
<div id="yieldTotal" class="yield-total">0</div>
</div>
<div id="productGrid" class="product-grid"></div>
<div class="section-title">
<span>Reactants remaining</span>
<span>At maximum yield</span>
</div>
<div id="leftoverGrid" class="leftover-grid"></div>
<div class="actions">
<button id="runButton" class="primary-button">▶ Run reaction</button>
<button id="resetButton" class="secondary-button">Reset</button>
</div>
</div>
</aside>
<section class="stage" aria-label="Interactive molecular visualization">
<div id="scene"></div>
<div class="hud hud-top">
<div class="view-label">
<strong>3D MOLECULAR VIEW</strong>
<span>Reactants on the left · products on the right</span>
</div>
<div class="scene-badges">
<div class="scene-badge limit">LIMIT <b id="sceneLimit">—</b></div>
<div class="scene-badge yield">UNITS <b id="sceneUnits">0</b></div>
<div class="scene-badge">STEP <b id="sceneStep">0 / 0</b></div>
</div>
</div>
<div class="camera-tools">
<button id="cameraReset" class="camera-button" title="Reset camera" aria-label="Reset camera">
↺
</button>
</div>
<div class="hint">Drag to orbit · Scroll to zoom · Double-click to reset</div>
<div class="transport">
<div class="transport-step">
Reaction progress
<strong id="progressLabel">Step 0 of 0</strong>
</div>
<div class="timeline-wrap">
<input
id="timeline"
type="range"
min="0"
max="1"
value="0"
step="1"
aria-label="Reaction step"
/>
<span id="timelineValue">0 / 0</span>
</div>
<div class="legend">
<div class="legend-item"><span class="legend-dot hydrogen"></span>H</div>
<div class="legend-item"><span class="legend-dot oxygen"></span>O</div>
<div class="legend-item"><span class="legend-dot carbon"></span>C</div>
<div class="legend-item"><span class="legend-dot nitrogen"></span>N</div>
</div>
</div>
</section>
</main>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Molecular and reaction data
// -------------------------------------------------------------------------
const species = {
h2: {
name: "Hydrogen",
formula: "H₂",
atoms: [
{ element: "H", position: [-0.32, 0, 0] },
{ element: "H", position: [0.32, 0, 0] }
],
bonds: [[0, 1]]
},
o2: {
name: "Oxygen",
formula: "O₂",
atoms: [
{ element: "O", position: [-0.34, 0, 0] },
{ element: "O", position: [0.34, 0, 0] }
],
bonds: [[0, 1]]
},
h2o: {
name: "Water",
formula: "H₂O",
atoms: [
{ element: "O", position: [0, 0.12, 0] },
{ element: "H", position: [-0.43, -0.27, 0] },
{ element: "H", position: [0.43, -0.27, 0] }
],
bonds: [[0, 1], [0, 2]]
},
ch4: {
name: "Methane",
formula: "CH₄",
atoms: [
{ element: "C", position: [0, 0, 0] },
{ element: "H", position: [0.43, 0.32, 0.20] },
{ element: "H", position: [-0.43, 0.32, 0.20] },
{ element: "H", position: [0, -0.35, 0.47] },
{ element: "H", position: [0, -0.35, -0.47] }
],
bonds: [[0, 1], [0, 2], [0, 3], [0, 4]]
},
co2: {
name: "Carbon dioxide",
formula: "CO₂",
atoms: [
{ element: "O", position: [-0.55, 0, 0] },
{ element: "C", position: [0, 0, 0] },
{ element: "O", position: [0.55, 0, 0] }
],
bonds: [[0, 1], [1, 2]]
},
n2: {
name: "Nitrogen",
formula: "N₂",
atoms: [
{ element: "N", position: [-0.32, 0, 0] },
{ element: "N", position: [0.32, 0, 0] }
],
bonds: [[0, 1]]
},
nh3: {
name: "Ammonia",
formula: "NH₃",
atoms: [
{ element: "N", position: [0, 0.12, 0] },
{ element: "H", position: [-0.42, -0.27, 0.16] },
{ element: "H", position: [0.42, -0.27, 0.16] },
{ element: "H", position: [0, -0.32, -0.45] }
],
bonds: [[0, 1], [0, 2], [0, 3]]
}
};
const reactions = [
{
id: "water",
name: "Water formation",
equation: "2H₂ + O₂ → 2H₂O",
note: "Two hydrogen molecules combine with one oxygen molecule to form two water molecules.",
reactants: [
{ key: "h2", coefficient: 2 },
{ key: "o2", coefficient: 1 }
],
products: [
{ key: "h2o", coefficient: 2 }
],
defaults: { h2: 10, o2: 4 }
},
{
id: "combustion",
name: "Methane combustion",
equation: "CH₄ + 2O₂ → CO₂ + 2H₂O",
note: "Complete combustion produces one carbon dioxide molecule and two water molecules per methane molecule.",
reactants: [
{ key: "ch4", coefficient: 1 },
{ key: "o2", coefficient: 2 }
],
products: [
{ key: "co2", coefficient: 1 },
{ key: "h2o", coefficient: 2 }
],
defaults: { ch4: 6, o2: 8 }
},
{
id: "ammonia",
name: "Ammonia synthesis",
equation: "N₂ + 3H₂ → 2NH₃",
note: "One nitrogen molecule and three hydrogen molecules form two ammonia molecules.",
reactants: [
{ key: "n2", coefficient: 1 },
{ key: "h2", coefficient: 3 }
],
products: [
{ key: "nh3", coefficient: 2 }
],
defaults: { n2: 6, h2: 12 }
}
];
const countState = Object.fromEntries(
reactions.map((reaction) => [reaction.id, { ...reaction.defaults }])
);
const MAX_COUNT = 24;
const reactionListElement = document.querySelector("#reactionList");
const equationMainElement = document.querySelector("#equationMain");
const equationNoteElement = document.querySelector("#equationNote");
const countListElement = document.querySelector("#countList");
const extentLabelElement = document.querySelector("#extentLabel");
const limitTitleElement = document.querySelector("#limitTitle");
const limitDetailElement = document.querySelector("#limitDetail");
const yieldTotalElement = document.querySelector("#yieldTotal");
const productGridElement = document.querySelector("#productGrid");
const leftoverGridElement = document.querySelector("#leftoverGrid");
const runButton = document.querySelector("#runButton");
const resetButton = document.querySelector("#resetButton");
const timeline = document.querySelector("#timeline");
const timelineValue = document.querySelector("#timelineValue");
const progressLabel = document.querySelector("#progressLabel");
const sceneLimit = document.querySelector("#sceneLimit");
const sceneUnits = document.querySelector("#sceneUnits");
const sceneStep = document.querySelector("#sceneStep");
const cameraResetButton = document.querySelector("#cameraReset");
let selectedReactionIndex = 0;
let currentCounts = { ...countState[reactions[0].id] };
let currentCalculation = null;
let currentProgress = 0;
let isPlaying = false;
let playbackTimer = null;
// -------------------------------------------------------------------------
// Exact integer stoichiometric bookkeeping
// -------------------------------------------------------------------------
function calculate(reaction, counts) {
const capabilities = reaction.reactants.map((reactant) => {
const available = counts[reactant.key] ?? 0;
return {
...reactant,
available,
units: Math.floor(available / reactant.coefficient),
leftover: 0
};
});
const extent = capabilities.length
? Math.min(...capabilities.map((capability) => capability.units))
: 0;
const limiting = capabilities.filter(
(capability) => capability.units === extent
);
for (const capability of capabilities) {
capability.leftover =
capability.available - capability.coefficient * extent;
}
const products = reaction.products.map((product) => ({
...product,
count: product.coefficient * extent
}));
const totalProduct = products.reduce(
(sum, product) => sum + product.count,
0
);
return {
capabilities,
extent,
limiting,
products,
totalProduct
};
}
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const sceneHost = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setClearColor(0x081321, 1);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
sceneHost.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x081321, 18, 38);
const camera = new THREE.PerspectiveCamera(
42,
1,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0, 0.3, 0);
let cameraTheta = 0;
let cameraPhi = 1.16;
let cameraRadius = 18.5;
const hemisphereLight = new THREE.HemisphereLight(
0xb9dcff,
0x162033,
1.55
);
scene.add(hemisphereLight);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.25);
keyLight.position.set(-7, 11, 8);
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x4b8cff, 24, 25, 2);
rimLight.position.set(7, 3, -7);
scene.add(rimLight);
const cyanLight = new THREE.PointLight(0x42dac5, 17, 19, 2);
cyanLight.position.set(-7, 1, 4);
scene.add(cyanLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(40, 30),
new THREE.MeshStandardMaterial({
color: 0x081321,
roughness: 0.92,
metalness: 0.05
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -2.48;
scene.add(floor);
const grid = new THREE.GridHelper(
30,
30,
0x24425f,
0x14283e
);
grid.position.y = -2.455;
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
function addLanePanel(x, color) {
const panel = new THREE.Mesh(
new THREE.PlaneGeometry(5.75, 7.1),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.16,
depthWrite: false
})
);
panel.rotation.x = -Math.PI / 2;
panel.position.set(x, -2.44, 0.35);
scene.add(panel);
}
addLanePanel(-4.65, 0x3f7fff);
addLanePanel(4.65, 0x35d7bd);
const dividerGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, -2.4, -2.65),
new THREE.Vector3(0, 4.25, -2.65)
]);
const divider = new THREE.Line(
dividerGeometry,
new THREE.LineDashedMaterial({
color: 0x66809d,
dashSize: 0.16,
gapSize: 0.12,
transparent: true,
opacity: 0.45
})
);
divider.computeLineDistances();
scene.add(divider);
const pulseMaterial = new THREE.MeshBasicMaterial({
color: 0x6ce8d6,
transparent: true,
opacity: 0,
depthWrite: false
});
const pulseRing = new THREE.Mesh(
new THREE.TorusGeometry(1.15, 0.035, 6, 36),
pulseMaterial
);
pulseRing.rotation.x = Math.PI / 2;
pulseRing.position.set(0, -2.39, 0);
scene.add(pulseRing);
const modelRoot = new THREE.Group();
scene.add(modelRoot);
let molecularBatches = [];
let dynamicLabels = [];
// -------------------------------------------------------------------------
// Shared low-poly geometry and materials
// -------------------------------------------------------------------------
const atomGeometryCache = new Map();
const atomMaterialCache = new Map();
const atomColors = {
H: 0xeaf4ff,
O: 0xff6174,
C: 0x31d6c3,
N: 0x9585ff
};
const atomRadii = {
H: 0.20,
O: 0.35,
C: 0.40,
N: 0.36
};
function getAtomGeometry(element) {
if (!atomGeometryCache.has(element)) {
atomGeometryCache.set(
element,
new THREE.IcosahedronGeometry(atomRadii[element], 1)
);
}
return atomGeometryCache.get(element);
}
function getAtomMaterial(element) {
if (!atomMaterialCache.has(element)) {
const color = new THREE.Color(atomColors[element]);
atomMaterialCache.set(
element,
new THREE.MeshStandardMaterial({
color,
roughness: 0.42,
metalness: 0.08,
flatShading: true,
emissive: color.clone().multiplyScalar(0.11),
emissiveIntensity: 0.8
})
);
}
return atomMaterialCache.get(element);
}
const bondGeometry = new THREE.CylinderGeometry(0.055, 0.055, 1, 6);
const bondMaterial = new THREE.MeshStandardMaterial({
color: 0xa7b9ce,
roughness: 0.48,
metalness: 0.22,
flatShading: true
});
// -------------------------------------------------------------------------
// Instanced molecular batches
// -------------------------------------------------------------------------
const Y_AXIS = new THREE.Vector3(0, 1, 0);
const tempMatrix = new THREE.Matrix4();
const tempPosition = new THREE.Vector3();
const tempScale = new THREE.Vector3();
const tempQuaternion = new THREE.Quaternion();
const tempDirection = new THREE.Vector3();
const tempMidpoint = new THREE.Vector3();
const tempBondQuaternion = new THREE.Quaternion();
class MolecularBatch {
constructor(molecularSpecies, records) {
this.species = molecularSpecies;
this.records = records;
this.atomInstances = [];
this.bondInstances = [];
this.meshes = [];
const elementOccurrences = new Map();
molecularSpecies.atoms.forEach((atom, atomIndex) => {
if (!elementOccurrences.has(atom.element)) {
elementOccurrences.set(atom.element, []);
}
elementOccurrences.get(atom.element).push(atomIndex);
});
for (const [element, atomIndices] of elementOccurrences) {
const count = records.length * atomIndices.length;
if (!count) continue;
const mesh = new THREE.InstancedMesh(
getAtomGeometry(element),
getAtomMaterial(element),
count
);
mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
mesh.frustumCulled = false;
modelRoot.add(mesh);
this.meshes.push(mesh);
atomIndices.forEach((atomIndex, occurrenceIndex) => {
for (let recordIndex = 0; recordIndex < records.length; recordIndex++) {
this.atomInstances.push({
mesh,
instanceIndex: recordIndex * atomIndices.length + occurrenceIndex,
recordIndex,
position: new THREE.Vector3(
...molecularSpecies.atoms[atomIndex].position
)
});
}
});
}
if (molecularSpecies.bonds.length && records.length) {
const bondCount = records.length * molecularSpecies.bonds.length;
const bondMesh = new THREE.InstancedMesh(
bondGeometry,
bondMaterial,
bondCount
);
bondMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
bondMesh.frustumCulled = false;
modelRoot.add(bondMesh);
this.meshes.push(bondMesh);
molecularSpecies.bonds.forEach((bond, bondIndex) => {
for (let recordIndex = 0; recordIndex < records.length; recordIndex++) {
this.bondInstances.push({
mesh: bondMesh,
instanceIndex: recordIndex * molecularSpecies.bonds.length + bondIndex,
recordIndex,
start: new THREE.Vector3(
...molecularSpecies.atoms[bond[0]].position
),
end: new THREE.Vector3(
...molecularSpecies.atoms[bond[1]].position
)
});
}
});
}
this.update(0, true);
}
update(delta, snap = false) {
const interpolation = snap ? 1 : 1 - Math.exp(-delta * 12);
for (const record of this.records) {
record.currentScale = THREE.MathUtils.lerp(
record.currentScale,
record.targetScale,
interpolation
);
if (Math.abs(record.currentScale - record.targetScale) < 0.0005) {
record.currentScale = record.targetScale;
}
}
for (const instance of this.atomInstances) {
const record = this.records[instance.recordIndex];
const scale = record.currentScale;
tempPosition
.copy(instance.position)
.multiplyScalar(scale)
.applyQuaternion(record.quaternion)
.add(record.position);
tempQuaternion.copy(record.quaternion);
tempScale.setScalar(scale);
tempMatrix.compose(tempPosition, tempQuaternion, tempScale);
instance.mesh.setMatrixAt(instance.instanceIndex, tempMatrix);
}
for (const instance of this.bondInstances) {
const record = this.records[instance.recordIndex];
const scale = record.currentScale;
tempDirection
.copy(instance.end)
.sub(instance.start)
.multiplyScalar(scale)
.applyQuaternion(record.quaternion);
const length = tempDirection.length();
tempMidpoint
.copy(instance.start)
.add(instance.end)
.multiplyScalar(0.5)
.multiplyScalar(scale)
.applyQuaternion(record.quaternion)
.add(record.position);
if (length > 0.00001) {
tempDirection.normalize();
tempBondQuaternion.setFromUnitVectors(Y_AXIS, tempDirection);
} else {
tempBondQuaternion.identity();
}
tempScale.set(scale, length, scale);
tempMatrix.compose(
tempMidpoint,
tempBondQuaternion,
tempScale
);
instance.mesh.setMatrixAt(instance.instanceIndex, tempMatrix);
}
for (const mesh of this.meshes) {
mesh.instanceMatrix.needsUpdate = true;
}
}
}
// -------------------------------------------------------------------------
// Sprite labels created entirely with Three.js core
// -------------------------------------------------------------------------
function roundedRect(context, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
context.beginPath();
context.moveTo(x + r, y);
context.arcTo(x + width, y, x + width, y + height, r);
context.arcTo(x + width, y + height, x, y + height, r);
context.arcTo(x, y + height, x, y, r);
context.arcTo(x, y, x + width, y, r);
context.closePath();
}
function createTextSprite(text, color = "#dcecff", width = 512) {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = 128;
const context = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.userData.canvas = canvas;
sprite.userData.context = context;
sprite.userData.texture = texture;
sprite.userData.color = color;
updateTextSprite(sprite, text, color);
return sprite;
}
function updateTextSprite(sprite, text, color = sprite.userData.color) {
const { canvas, context, texture } = sprite.userData;
const width = canvas.width;
const height = canvas.height;
context.clearRect(0, 0, width, height);
context.fillStyle = "rgba(7, 16, 29, 0.76)";
roundedRect(context, 8, 8, width - 16, height - 16, 26);
context.fill();
context.strokeStyle = "rgba(143, 164, 189, 0.22)";
context.lineWidth = 2;
roundedRect(context, 8, 8, width - 16, height - 16, 26);
context.stroke();
context.fillStyle = color;
context.font = "700 36px Inter, system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, width / 2, height / 2 + 1);
texture.needsUpdate = true;
}
const reactantHeader = createTextSprite("REACTANTS / REMAINING", "#9bb8dd");
reactantHeader.position.set(-4.65, 4.12, -2.7);
reactantHeader.scale.set(3.75, 0.72, 1);
scene.add(reactantHeader);
const productHeader = createTextSprite("PRODUCTS / FORMED", "#78ddcd");
productHeader.position.set(4.65, 4.12, -2.7);
productHeader.scale.set(3.45, 0.72, 1);
scene.add(productHeader);
// -------------------------------------------------------------------------
// Molecular layout
// -------------------------------------------------------------------------
function createRecords(count, centerX, rowY) {
const records = [];
const columns = 5;
for (let index = 0; index < count; index++) {
const column = index % columns;
const row = Math.floor(index / columns);
const position = new THREE.Vector3(
centerX + (column - 2) * 1.16,
rowY + (index % 2 === 0 ? 0.02 : -0.03),
(row - 1.5) * 1.08
);
const angle = index * 2.399963;
const tilt = ((index % 3) - 1) * 0.10;
const quaternion = new THREE.Quaternion().setFromEuler(
new THREE.Euler(tilt, angle, tilt * 0.45)
);
records.push({
position,
quaternion,
targetScale: 1,
currentScale: 1
});
}
return records;
}
function disposeDynamicLabels() {
for (const label of dynamicLabels) {
scene.remove(label.sprite);
label.sprite.material.map?.dispose();
label.sprite.material.dispose();
}
dynamicLabels = [];
}
function buildModels(calculation) {
while (modelRoot.children.length) {
modelRoot.remove(modelRoot.children[0]);
}
disposeDynamicLabels();
molecularBatches = [];
const reaction = reactions[selectedReactionIndex];
reaction.reactants.forEach((reactant, rowIndex) => {
const count = currentCounts[reactant.key] ?? 0;
const rowY = 2.35 - rowIndex * 1.75;
const records = createRecords(count, -4.65, rowY);
const batch = new MolecularBatch(species[reactant.key], records);
molecularBatches.push(batch);
modelGroups.reactants.push({
key: reactant.key,
coefficient: reactant.coefficient,
initial: count,
records
});
const label = createTextSprite(
`${species[reactant.key].formula} × ${count}`,
"#b9cce4"
);
label.position.set(-4.65, rowY + 0.73, -2.55);
label.scale.set(2.6, 0.53, 1);
scene.add(label);
dynamicLabels.push({
sprite: label,
role: "reactant",
key: reactant.key
});
});
reaction.products.forEach((product, rowIndex) => {
const maximum = product.coefficient * calculation.extent;
const rowY = 2.35 - rowIndex * 1.75;
const records = createRecords(maximum, 4.65, rowY);
records.forEach((record) => {
record.targetScale = 0;
record.currentScale = 0;
});
const batch = new MolecularBatch(species[product.key], records);
molecularBatches.push(batch);
modelGroups.products.push({
key: product.key,
coefficient: product.coefficient,
maximum,
records
});
const label = createTextSprite(
`${species[product.key].formula} × 0`,
"#78ddcd"
);
label.position.set(4.65, rowY + 0.73, -2.55);
label.scale.set(2.6, 0.53, 1);
scene.add(label);
dynamicLabels.push({
sprite: label,
role: "product",
key: product.key
});
});
}
const modelGroups = {
reactants: [],
products: []
};
function setProgress(progress) {
const reaction = reactions[selectedReactionIndex];
const extent = currentCalculation?.extent ?? 0;
const nextProgress = THREE.MathUtils.clamp(
Math.round(progress),
0,
extent
);
const advanced = nextProgress > currentProgress;
currentProgress = nextProgress;
for (const group of modelGroups.reactants) {
const remaining = Math.max(
0,
group.initial - group.coefficient * currentProgress
);
group.records.forEach((record, index) => {
record.targetScale = index < remaining ? 1 : 0;
});
}
for (const group of modelGroups.products) {
const formed = group.coefficient * currentProgress;
group.records.forEach((record, index) => {
record.targetScale = index < formed ? 1 : 0;
});
}
for (const label of dynamicLabels) {
if (label.role === "reactant") {
const group = modelGroups.reactants.find(
(candidate) => candidate.key === label.key
);
const remaining = group
? Math.max(
0,
group.initial - group.coefficient * currentProgress
)
: 0;
updateTextSprite(
label.sprite,
`${species[label.key].formula} × ${remaining}`,
"#b9cce4"
);
} else {
const group = modelGroups.products.find(
(candidate) => candidate.key === label.key
);
const formed = group
? group.coefficient * currentProgress
: 0;
updateTextSprite(
label.sprite,
`${species[label.key].formula} × ${formed}`,
"#78ddcd"
);
}
}
const maximum = Math.max(extent, 1);
timeline.max = String(maximum);
timeline.value = String(currentProgress);
timeline.disabled = extent === 0;
const percentage = extent > 0
? (currentProgress / extent) * 100
: 0;
timeline.style.setProperty("--timeline", `${percentage}%`);
timelineValue.textContent = `${currentProgress} / ${extent}`;
progressLabel.textContent = `Step ${currentProgress} of ${extent}`;
sceneStep.textContent = `${currentProgress} / ${extent}`;
timeline.setAttribute(
"aria-valuetext",
`${currentProgress} of ${extent} reaction units`
);
if (advanced) {
pulseMaterial.opacity = 0.75;
pulseRing.scale.setScalar(0.65);
}
sceneUnits.textContent = String(extent);
}
// -------------------------------------------------------------------------
// Sidebar rendering
// -------------------------------------------------------------------------
function renderReactionList() {
reactionListElement.innerHTML = reactions
.map(
(reaction, index) => `
<button
class="reaction-option ${index === selectedReactionIndex ? "active" : ""}"
data-reaction-index="${index}"
aria-pressed="${index === selectedReactionIndex}"
>
<span class="radio" aria-hidden="true"></span>
<span>
<span class="reaction-name">${reaction.name}</span>
<span class="reaction-equation">${reaction.equation}</span>
</span>
</button>
`
)
.join("");
}
function renderInputs() {
const reaction = reactions[selectedReactionIndex];
countListElement.innerHTML = reaction.reactants
.map((reactant) => {
const molecularSpecies = species[reactant.key];
const count = currentCounts[reactant.key] ?? 0;
const capacity = Math.floor(count / reactant.coefficient);
return `
<div class="count-row">
<div class="coefficient" title="Stoichiometric coefficient">
${reactant.coefficient}
</div>
<div>
<div class="species-name">${molecularSpecies.formula}</div>
<div class="species-detail">
${molecularSpecies.name} · consumes ${reactant.coefficient} per unit
</div>
<div id="capacity-${reactant.key}" class="capacity">
${capacity} reaction unit${capacity === 1 ? "" : "s"} available
</div>
</div>
<div class="stepper">
<button
type="button"
data-step="-1"
data-key="${reactant.key}"
aria-label="Decrease ${molecularSpecies.formula} count"
>−</button>
<input
type="number"
min="0"
max="${MAX_COUNT}"
step="1"
inputmode="numeric"
value="${count}"
data-key="${reactant.key}"
aria-label="Initial ${molecularSpecies.formula} molecule count"
/>
<button
type="button"
data-step="1"
data-key="${reactant.key}"
aria-label="Increase ${molecularSpecies.formula} count"
>+</button>
</div>
</div>
`;
})
.join("");
}
function renderResults(calculation) {
const reaction = reactions[selectedReactionIndex];
const totalInput = calculation.capabilities.reduce(
(sum, capability) => sum + capability.available,
0
);
extentLabelElement.textContent =
`${calculation.extent} reaction unit${calculation.extent === 1 ? "" : "s"}`;
for (const capability of calculation.capabilities) {
const capacityElement = document.querySelector(
`#capacity-${capability.key}`
);
if (capacityElement) {
capacityElement.textContent =
`${capability.units} reaction unit${capability.units === 1 ? "" : "s"} available`;
}
}
if (calculation.extent > 0) {
const names = calculation.limiting
.map((limiting) => species[limiting.key].formula)
.join(" + ");
limitTitleElement.textContent =
calculation.limiting.length === 1
? `${names} is limiting`
: `${names} are tied as limiting`;
const comparison = calculation.capabilities
.map(
(capability) =>
`${species[capability.key].formula}: ⌊${capability.available}/${capability.coefficient}⌋ = ${capability.units}`
)
.join(" · ");
limitDetailElement.textContent = comparison;
sceneLimit.textContent = names;
} else if (totalInput > 0) {
const names = calculation.limiting
.map((limiting) => species[limiting.key].formula)
.join(" + ");
limitTitleElement.textContent = "No complete reaction unit";
limitDetailElement.textContent =
`At least one required reactant is missing. Check ${names}.`;
sceneLimit.textContent = "No product";
} else {
limitTitleElement.textContent = "Add reactant molecules";
limitDetailElement.textContent =
"Enter one or more whole reactant molecules to calculate the yield.";
sceneLimit.textContent = "—";
}
yieldTotalElement.textContent = String(calculation.totalProduct);
productGridElement.innerHTML = calculation.products
.map(
(product) => `
<div class="mini-metric">
<span>${species[product.key].formula} formed</span>
<strong>${product.count}</strong>
<small>molecules</small>
</div>
`
)
.join("");
leftoverGridElement.innerHTML = calculation.capabilities
.map(
(capability) => `
<div class="mini-metric">
<span>${species[capability.key].formula} left</span>
<strong>${capability.leftover}</strong>
<small>molecules</small>
</div>
`
)
.join("");
runButton.disabled = calculation.extent === 0;
runButton.textContent = isPlaying ? "Ⅱ Pause reaction" : "▶ Run reaction";
equationMainElement.textContent = reaction.equation;
equationNoteElement.textContent = reaction.note;
}
// -------------------------------------------------------------------------
// Interaction and playback
// -------------------------------------------------------------------------
function stopPlayback() {
if (playbackTimer) {
clearInterval(playbackTimer);
playbackTimer = null;
}
isPlaying = false;
runButton.textContent = "▶ Run reaction";
}
function refreshCalculation(resetProgress = true) {
stopPlayback();
const reaction = reactions[selectedReactionIndex];
currentCalculation = calculate(reaction, currentCounts);
if (resetProgress) {
currentProgress = 0;
}
buildModels(currentCalculation);
setProgress(currentProgress);
renderResults(currentCalculation);
}
function selectReaction(index) {
selectedReactionIndex = index;
const reaction = reactions[index];
currentCounts = { ...countState[reaction.id] };
renderReactionList();
renderInputs();
refreshCalculation(true);
}
reactionListElement.addEventListener("click", (event) => {
const button = event.target.closest("[data-reaction-index]");
if (!button) return;
const index = Number(button.dataset.reactionIndex);
if (index !== selectedReactionIndex) {
selectReaction(index);
}
});
countListElement.addEventListener("click", (event) => {
const button = event.target.closest("[data-step]");
if (!button) return;
const key = button.dataset.key;
const step = Number(button.dataset.step);
const next = THREE.MathUtils.clamp(
(currentCounts[key] ?? 0) + step,
0,
MAX_COUNT
);
currentCounts[key] = next;
countState[reactions[selectedReactionIndex].id][key] = next;
const input = countListElement.querySelector(
`input[data-key="${key}"]`
);
if (input) input.value = String(next);
refreshCalculation(true);
});
countListElement.addEventListener("input", (event) => {
const input = event.target.closest("input[data-key]");
if (!input) return;
const key = input.dataset.key;
const parsed = Number.parseInt(input.value, 10);
const next = Number.isFinite(parsed)
? THREE.MathUtils.clamp(parsed, 0, MAX_COUNT)
: 0;
currentCounts[key] = next;
countState[reactions[selectedReactionIndex].id][key] = next;
if (input.value !== "") {
input.value = String(next);
}
refreshCalculation(true);
});
runButton.addEventListener("click", () => {
if (!currentCalculation || currentCalculation.extent === 0) return;
if (isPlaying) {
stopPlayback();
return;
}
if (currentProgress >= currentCalculation.extent) {
currentProgress = 0;
setProgress(0);
}
isPlaying = true;
runButton.textContent = "Ⅱ Pause reaction";
playbackTimer = setInterval(() => {
currentProgress += 1;
setProgress(currentProgress);
if (currentProgress >= currentCalculation.extent) {
stopPlayback();
}
}, 620);
});
resetButton.addEventListener("click", () => {
stopPlayback();
currentProgress = 0;
setProgress(0);
});
timeline.addEventListener("input", () => {
stopPlayback();
currentProgress = Number.parseInt(timeline.value, 10) || 0;
setProgress(currentProgress);
});
// -------------------------------------------------------------------------
// Custom camera controls — no addon imports
// -------------------------------------------------------------------------
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
function updateCamera() {
const horizontalRadius = cameraRadius * Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x + horizontalRadius * Math.sin(cameraTheta),
cameraTarget.y + cameraRadius * Math.cos(cameraPhi),
cameraTarget.z + horizontalRadius * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraTheta = 0;
cameraPhi = 1.16;
cameraRadius = camera.aspect < 1 ? 23 : 18.5;
updateCamera();
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
event.preventDefault();
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - previousPointerX;
const deltaY = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
cameraTheta -= deltaX * 0.006;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi - deltaY * 0.005,
0.38,
1.43
);
event.preventDefault();
});
function endDrag(event) {
dragging = false;
if (
event.pointerId !== undefined &&
renderer.domElement.hasPointerCapture(event.pointerId)
) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
10,
28
);
event.preventDefault();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
cameraResetButton.addEventListener("click", resetCamera);
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
function resize() {
const width = sceneHost.clientWidth;
const height = sceneHost.clientHeight;
if (!width || !height) return;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(sceneHost);
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
for (const batch of molecularBatches) {
batch.update(delta);
}
if (pulseMaterial.opacity > 0) {
pulseMaterial.opacity = Math.max(
0,
pulseMaterial.opacity - delta * 1.55
);
pulseRing.scale.multiplyScalar(1 + delta * 1.5);
}
updateCamera();
renderer.render(scene, camera);
}
// Initialize.
renderReactionList();
renderInputs();
refreshCalculation(true);
resize();
resetCamera();
animate();
</script>
</body>
</html>
```