Prompt specification
Build or customize the Three.js 3D scene "Budding population observation 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: Budding population observation chamber
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/budding-population-observation-chamber-x0880
Scene Description Prompt:
Please use Three.js from cdnjs for a low-poly scene based on this idea: budding population observation chamber. Run a small explicitly synthetic yeast lineage simulation with selectable observation interval; distinguish cell number, average size, and generation count while keeping the population bounded. Return one self-contained HTML file.
Working Three.js Starter (budding-population-observation-chamber-x0880):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Budding Population — Synthetic Observation Chamber</title>
<style>
:root {
color-scheme: dark;
--ink: #e9f7f1;
--muted: #8da99e;
--dim: #5f7e73;
--panel: rgba(8, 22, 18, 0.72);
--panel-strong: rgba(7, 20, 16, 0.9);
--line: rgba(164, 224, 202, 0.14);
--accent: #8ee8c0;
--gold: #f5ca72;
--blue: #79c6ff;
--purple: #c7a2ff;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #06100d;
}
body {
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
font-size: 14px;
-webkit-font-smoothing: antialiased;
}
button,
select {
font: inherit;
}
button,
select,
input {
accent-color: var(--accent);
}
button {
color: inherit;
}
button:focus-visible,
select:focus-visible,
input:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#viewport canvas:active {
cursor: grabbing;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 50% 48%, transparent 40%, rgba(1, 7, 5, 0.44) 100%),
linear-gradient(180deg, rgba(2, 8, 6, 0.2), transparent 22%, transparent 78%, rgba(2, 8, 6, 0.42));
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
}
.topbar {
position: absolute;
top: 20px;
left: 24px;
right: 24px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
position: relative;
width: 42px;
height: 42px;
flex: 0 0 auto;
border: 1px solid rgba(142, 232, 192, 0.3);
border-radius: 50%;
box-shadow: inset 0 0 22px rgba(83, 224, 173, 0.08);
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 14px rgba(142, 232, 192, 0.45);
}
.brand-mark::before {
width: 12px;
height: 12px;
left: 9px;
top: 10px;
}
.brand-mark::after {
width: 7px;
height: 7px;
right: 7px;
bottom: 7px;
background: var(--gold);
}
.eyebrow {
display: block;
margin-bottom: 3px;
color: var(--accent);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.19em;
text-transform: uppercase;
}
h1 {
margin: 0;
overflow: hidden;
font-size: clamp(19px, 2vw, 25px);
font-weight: 570;
letter-spacing: -0.025em;
text-overflow: ellipsis;
white-space: nowrap;
}
.subtitle {
margin: 3px 0 0;
color: var(--muted);
font-size: 12px;
}
.top-actions {
display: flex;
align-items: center;
gap: 8px;
pointer-events: auto;
}
.synthetic-badge {
display: flex;
align-items: center;
gap: 8px;
min-height: 36px;
padding: 0 12px;
border: 1px solid rgba(245, 202, 114, 0.2);
border-radius: 999px;
background: rgba(33, 31, 16, 0.58);
color: #ddc98f;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
backdrop-filter: blur(14px);
}
.synthetic-badge::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--gold);
box-shadow: 0 0 10px rgba(245, 202, 114, 0.7);
}
#seedLabel {
color: #f8e3a8;
font-variant-numeric: tabular-nums;
letter-spacing: 0.07em;
}
.icon-button,
.soft-button,
.primary-button {
min-height: 38px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(13, 31, 25, 0.76);
cursor: pointer;
transition:
border-color 160ms ease,
background 160ms ease,
transform 160ms ease;
}
.icon-button:hover,
.soft-button:hover,
.primary-button:hover {
border-color: rgba(142, 232, 192, 0.38);
background: rgba(21, 48, 38, 0.9);
}
.icon-button:active,
.soft-button:active,
.primary-button:active {
transform: translateY(1px);
}
.icon-button {
width: 38px;
padding: 0;
color: #b8d2c7;
font-size: 18px;
}
.soft-button,
.primary-button {
padding: 0 13px;
font-size: 12px;
font-weight: 650;
}
.primary-button {
border-color: rgba(142, 232, 192, 0.38);
background: rgba(56, 128, 98, 0.32);
color: #ddfff0;
}
.metrics {
position: absolute;
top: 104px;
left: 24px;
display: grid;
grid-template-columns: repeat(3, minmax(150px, 176px));
gap: 10px;
}
.metric-card {
position: relative;
min-height: 158px;
overflow: hidden;
padding: 15px 15px 11px;
border: 1px solid var(--line);
border-radius: 15px;
background:
linear-gradient(145deg, rgba(15, 38, 30, 0.78), rgba(6, 18, 14, 0.72));
box-shadow:
0 16px 42px rgba(0, 0, 0, 0.18),
inset 0 1px rgba(255, 255, 255, 0.025);
backdrop-filter: blur(18px);
}
.metric-card::after {
content: "";
position: absolute;
right: -22px;
top: -28px;
width: 80px;
height: 80px;
border-radius: 50%;
background: var(--metric-color);
opacity: 0.055;
filter: blur(8px);
}
.metric-label {
display: flex;
align-items: center;
gap: 7px;
color: #abc5ba;
font-size: 11px;
font-weight: 650;
letter-spacing: 0.055em;
text-transform: uppercase;
}
.metric-label::before {
content: "";
width: 5px;
height: 5px;
border-radius: 50%;
background: var(--metric-color);
box-shadow: 0 0 9px color-mix(in srgb, var(--metric-color) 55%, transparent);
}
.metric-value-row {
display: flex;
align-items: baseline;
gap: 7px;
margin-top: 10px;
}
.metric-value {
font-size: 35px;
font-weight: 560;
font-variant-numeric: tabular-nums;
letter-spacing: -0.045em;
line-height: 1;
}
.metric-unit {
color: var(--muted);
font-size: 11px;
font-weight: 600;
}
.metric-caption {
margin-top: 6px;
color: var(--dim);
font-size: 10px;
}
.spark {
display: block;
width: 100%;
height: 33px;
margin-top: 9px;
}
.capacity-track {
height: 3px;
margin-top: 10px;
overflow: hidden;
border-radius: 99px;
background: rgba(255, 255, 255, 0.06);
}
#capacityFill {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #77d6ad, #f1cb71);
transition: width 300ms ease;
}
.observation-panel {
position: absolute;
top: 104px;
right: 24px;
width: 274px;
padding: 16px;
border: 1px solid var(--line);
border-radius: 15px;
background: var(--panel);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(18px);
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 13px;
}
.panel-heading h2 {
margin: 0;
font-size: 12px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.panel-tag {
color: var(--dim);
font-size: 9px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
#generationBars {
display: grid;
gap: 7px;
min-height: 70px;
}
.generation-row {
display: grid;
grid-template-columns: 24px 1fr 25px;
align-items: center;
gap: 8px;
color: var(--muted);
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.generation-track {
height: 6px;
overflow: hidden;
border-radius: 99px;
background: rgba(255, 255, 255, 0.045);
}
.generation-fill {
height: 100%;
min-width: 2px;
border-radius: inherit;
transition: width 250ms ease;
}
.toggle-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 14px;
padding-top: 12px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 11px;
}
.toggle-row label {
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
}
.toggle-row input {
width: 14px;
height: 14px;
margin: 0;
}
.specimen {
margin-top: 15px;
padding: 12px;
border: 1px solid rgba(142, 232, 192, 0.1);
border-radius: 11px;
background: rgba(255, 255, 255, 0.025);
}
.specimen-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
color: var(--dim);
font-size: 9px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
#selectedId {
color: var(--ink);
font-size: 12px;
font-weight: 700;
letter-spacing: 0.04em;
}
.specimen-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px 12px;
margin-top: 11px;
}
.specimen-field span {
display: block;
margin-bottom: 3px;
color: var(--dim);
font-size: 8px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.specimen-field strong {
display: block;
overflow: hidden;
color: #c8ddd4;
font-size: 10px;
font-weight: 600;
text-overflow: ellipsis;
white-space: nowrap;
}
.model-note {
margin-top: 13px;
color: var(--dim);
font-size: 10px;
line-height: 1.5;
}
.model-note summary {
color: #91aa9f;
cursor: pointer;
user-select: none;
}
.model-note p {
margin: 8px 0 0;
}
.control-dock {
position: absolute;
left: 50%;
bottom: 22px;
display: flex;
align-items: center;
gap: 11px;
width: max-content;
max-width: calc(100vw - 32px);
padding: 11px 12px;
border: 1px solid rgba(164, 224, 202, 0.16);
border-radius: 16px;
background: var(--panel-strong);
box-shadow:
0 20px 60px rgba(0, 0, 0, 0.42),
inset 0 1px rgba(255, 255, 255, 0.025);
pointer-events: auto;
backdrop-filter: blur(22px);
}
.run-button {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
min-width: 94px;
min-height: 42px;
padding: 0 14px;
border: 1px solid rgba(142, 232, 192, 0.36);
border-radius: 11px;
background: rgba(61, 145, 108, 0.3);
color: #e5fff3;
font-size: 12px;
font-weight: 700;
cursor: pointer;
}
#playIcon {
width: 11px;
font-size: 12px;
text-align: center;
}
.dock-divider {
width: 1px;
height: 38px;
background: var(--line);
}
.interval-control {
display: grid;
gap: 5px;
}
.control-label {
color: var(--dim);
font-size: 8px;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
}
select {
min-height: 27px;
padding: 0 28px 0 9px;
border: 1px solid var(--line);
border-radius: 7px;
background: #10241d;
color: #d4e7de;
font-size: 11px;
cursor: pointer;
}
.clock-readout {
display: grid;
gap: 5px;
min-width: 86px;
}
#clock {
color: #cfe2d9;
font-size: 11px;
font-variant-numeric: tabular-nums;
font-weight: 600;
}
.status {
display: flex;
align-items: center;
gap: 7px;
color: var(--dim);
font-size: 9px;
white-space: nowrap;
}
.status-dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 9px rgba(142, 232, 192, 0.7);
}
.status-dot.paused {
background: var(--gold);
box-shadow: 0 0 9px rgba(245, 202, 114, 0.6);
}
.footer-note {
position: absolute;
left: 24px;
bottom: 26px;
max-width: 260px;
color: #607d72;
font-size: 10px;
line-height: 1.45;
}
.footer-note strong {
color: #a89159;
font-weight: 650;
}
.interaction-hint {
position: absolute;
right: 24px;
bottom: 28px;
color: #567168;
font-size: 10px;
}
#webgl-error {
position: fixed;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
padding: 30px;
background: #06100d;
color: #d9eee5;
text-align: center;
}
#webgl-error[hidden] {
display: none;
}
@media (max-width: 980px) {
.observation-panel {
display: none;
}
.metrics {
grid-template-columns: repeat(3, minmax(145px, 180px));
}
.footer-note,
.interaction-hint {
display: none;
}
}
@media (max-width: 720px) {
.topbar {
top: 13px;
left: 13px;
right: 13px;
}
.brand-mark {
width: 36px;
height: 36px;
}
.brand-mark::before {
left: 7px;
top: 8px;
}
.brand-mark::after {
right: 5px;
bottom: 5px;
}
.subtitle,
#seedLabel,
.synthetic-badge {
display: none;
}
.top-actions {
gap: 5px;
}
.icon-button {
width: 34px;
min-height: 34px;
}
.metrics {
top: 70px;
left: 12px;
right: 12px;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 6px;
}
.metric-card {
min-height: 130px;
padding: 11px 10px 8px;
border-radius: 12px;
}
.metric-label {
font-size: 9px;
}
.metric-value {
font-size: 27px;
}
.metric-unit {
font-size: 9px;
}
.metric-caption {
min-height: 24px;
font-size: 8px;
}
.spark {
height: 26px;
}
.control-dock {
bottom: 12px;
flex-wrap: wrap;
justify-content: center;
width: calc(100vw - 24px);
gap: 8px;
padding: 9px;
}
.dock-divider {
display: none;
}
.run-button {
min-height: 38px;
}
.interval-control {
grid-template-columns: auto auto;
align-items: center;
gap: 7px;
}
.clock-readout {
min-width: 74px;
}
.status {
display: none;
}
}
@media (max-width: 440px) {
.metrics {
grid-template-columns: 1fr 1fr;
}
.metric-card:last-child {
grid-column: 1 / -1;
min-height: 92px;
}
.metric-card:last-child .spark {
position: absolute;
right: 8px;
bottom: 7px;
width: 42%;
}
.soft-button {
padding: 0 10px;
}
}
</style>
</head>
<body>
<div id="viewport" aria-label="Interactive 3D synthetic yeast population chamber"></div>
<div class="vignette"></div>
<main class="hud">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<span class="eyebrow">Synthetic observation system</span>
<h1>Budding Population</h1>
<p class="subtitle">Yeast-like lineage / sealed chamber 03</p>
</div>
</div>
<div class="top-actions">
<div class="synthetic-badge" title="This is not biological data">
Synthetic · Seed <span id="seedLabel">00000000</span>
</div>
<button class="icon-button" id="zoomOut" aria-label="Zoom out" title="Zoom out">−</button>
<button class="icon-button" id="zoomIn" aria-label="Zoom in" title="Zoom in">+</button>
<button class="icon-button" id="resetView" aria-label="Reset camera" title="Reset camera">⌂</button>
</div>
</header>
<section class="metrics" aria-label="Population measurements">
<article class="metric-card" style="--metric-color: #f5ca72">
<div class="metric-label">Cell number</div>
<div class="metric-value-row">
<span class="metric-value" id="cellCount">0</span>
<span class="metric-unit">cells</span>
</div>
<div class="metric-caption" id="cellMeta">mother + bud cells</div>
<canvas class="spark" id="cellSpark" aria-label="Cell number history"></canvas>
<div class="capacity-track"><div id="capacityFill"></div></div>
</article>
<article class="metric-card" style="--metric-color: #8ee8c0">
<div class="metric-label">Average size</div>
<div class="metric-value-row">
<span class="metric-value" id="averageSize">0.00</span>
<span class="metric-unit">µm*</span>
</div>
<div class="metric-caption">synthetic radius-equivalent</div>
<canvas class="spark" id="sizeSpark" aria-label="Average size history"></canvas>
</article>
<article class="metric-card" style="--metric-color: #c7a2ff">
<div class="metric-label">Generation count</div>
<div class="metric-value-row">
<span class="metric-value" id="generationCount">0</span>
<span class="metric-unit">gens</span>
</div>
<div class="metric-caption">deepest living lineage branch</div>
<canvas class="spark" id="generationSpark" aria-label="Generation count history"></canvas>
</article>
</section>
<aside class="observation-panel">
<div class="panel-heading">
<h2>Generation census</h2>
<span class="panel-tag">Living cells</span>
</div>
<div id="generationBars" aria-label="Generation distribution"></div>
<div class="toggle-row">
<label>
<input type="checkbox" id="lineageToggle" checked>
Lineage links
</label>
<span>Hard cap 144</span>
</div>
<div class="specimen">
<div class="specimen-title">
<span>Selected specimen</span>
<strong id="selectedId">—</strong>
</div>
<div class="specimen-grid">
<div class="specimen-field">
<span>Generation</span>
<strong id="selectedGeneration">—</strong>
</div>
<div class="specimen-field">
<span>Parent</span>
<strong id="selectedParent">—</strong>
</div>
<div class="specimen-field">
<span>Age</span>
<strong id="selectedAge">—</strong>
</div>
<div class="specimen-field">
<span>State</span>
<strong id="selectedState">—</strong>
</div>
</div>
</div>
<details class="model-note">
<summary>Simulation model</summary>
<p>
Every observation advances one synthetic reproductive cycle. Mature cells
may form one attached bud; buds separate after two or three cycles.
Cells eventually expire. Births stop at 144 living cells. All values are
model-generated and are not biological measurements.
</p>
</details>
</aside>
<section class="control-dock" aria-label="Simulation controls">
<button class="run-button" id="toggleRun" aria-pressed="true">
<span id="playIcon">Ⅱ</span>
<span id="playText">Pause</span>
</button>
<button class="soft-button" id="stepButton" title="Pause and advance one observation">
Step
</button>
<div class="dock-divider"></div>
<label class="interval-control">
<span class="control-label">Observation interval</span>
<select id="intervalSelect" aria-label="Observation interval">
<option value="500">0.5 seconds</option>
<option value="1000" selected>1.0 second</option>
<option value="2000">2.0 seconds</option>
<option value="5000">5.0 seconds</option>
</select>
</label>
<div class="dock-divider"></div>
<div class="clock-readout">
<span class="control-label">Synthetic clock</span>
<output id="clock">Cycle 000</output>
</div>
<div class="status">
<span class="status-dot" id="statusDot"></span>
<span id="statusText">Observing every 1.0 s</span>
</div>
<div class="dock-divider"></div>
<button class="soft-button" id="resetButton" title="Restore the current seed">
Reset
</button>
<button class="primary-button" id="newSeedButton" title="Start a different synthetic lineage">
New seed
</button>
</section>
<div class="footer-note">
<strong>Explicitly synthetic.</strong>
Procedural cells, sizes, lifetimes, and lineage depths; not experimental observations.
</div>
<div class="interaction-hint">Drag to orbit · Scroll to zoom · Click a cell to inspect</div>
</main>
<div id="webgl-error" hidden>
<div>
<h2>WebGL is unavailable</h2>
<p>This observation chamber requires a browser with WebGL enabled.</p>
</div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const viewport = $("viewport");
const MAX_CELLS = 144;
const INITIAL_CELLS = 14;
const CHAMBER_RADIUS = 7.45;
const CELL_FLOOR = 0.43;
const CELL_CEILING = 5.85;
let seed = 0x5eedc0de;
let random = mulberry32(seed);
let nextId = 1;
let cycle = 0;
let running = true;
let intervalSeconds = 1;
let observationAccumulator = 0;
let selectedId = null;
let showLineage = true;
const cells = [];
const cellMap = new Map();
const visuals = new Map();
const history = {
count: [],
size: [],
generation: []
};
const clamp = THREE.MathUtils.clamp;
function mulberry32(initialSeed) {
let state = initialSeed >>> 0;
return function () {
state |= 0;
state = (state + 0x6d2b79f5) | 0;
let value = Math.imul(state ^ (state >>> 15), 1 | state);
value = (value + Math.imul(value ^ (value >>> 7), 61 | value)) ^ value;
return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
};
}
function randomUnitVector() {
const vector = new THREE.Vector3(
random() - 0.5,
random() - 0.5,
random() - 0.5
);
if (vector.lengthSq() < 0.001) vector.set(1, 0, 0);
return vector.normalize();
}
function generationHue(generation) {
return (0.12 + generation * 0.115) % 1;
}
function generationColor(generation) {
return new THREE.Color().setHSL(
generationHue(generation),
0.72,
0.63
);
}
function generationCss(generation) {
return `hsl(${Math.round(generationHue(generation) * 360)} 72% 64%)`;
}
// Scene ---------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x06100d);
scene.fog = new THREE.FogExp2(0x06100d, 0.027);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
100
);
let renderer;
try {
renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
} catch (error) {
$("webgl-error").hidden = false;
throw error;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.8));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
viewport.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xc9f5e6, 0x07100d, 1.55);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffefd1, 2.35);
keyLight.position.set(4.5, 9, 5.5);
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x52d9c0, 16, 24, 2);
cyanLight.position.set(-5.5, 3.4, 3.8);
scene.add(cyanLight);
const violetLight = new THREE.PointLight(0x8c75ff, 11, 22, 2);
violetLight.position.set(5.4, 2.2, -4.5);
scene.add(violetLight);
const chamber = new THREE.Group();
scene.add(chamber);
const floorMaterial = new THREE.MeshStandardMaterial({
color: 0x0c1d17,
roughness: 0.76,
metalness: 0.16,
flatShading: true
});
const base = new THREE.Mesh(
new THREE.CylinderGeometry(7.75, 7.95, 0.46, 64, 1, false),
floorMaterial
);
base.position.y = -0.24;
chamber.add(base);
const innerFloor = new THREE.Mesh(
new THREE.CircleGeometry(7.5, 64),
new THREE.MeshStandardMaterial({
color: 0x0a1c16,
roughness: 0.86,
metalness: 0.08
})
);
innerFloor.rotation.x = -Math.PI / 2;
innerFloor.position.y = 0.002;
chamber.add(innerFloor);
const centerDisc = new THREE.Mesh(
new THREE.CircleGeometry(0.42, 32),
new THREE.MeshBasicMaterial({
color: 0x4ebd9d,
transparent: true,
opacity: 0.14,
depthWrite: false
})
);
centerDisc.rotation.x = -Math.PI / 2;
centerDisc.position.y = 0.008;
chamber.add(centerDisc);
function makeCircleLine(radius, y, color, opacity) {
const points = [];
for (let index = 0; index < 96; index++) {
const angle = (index / 96) * Math.PI * 2;
points.push(
new THREE.Vector3(
Math.cos(angle) * radius,
y,
Math.sin(angle) * radius
)
);
}
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({
color,
transparent: true,
opacity,
depthWrite: false
});
return new THREE.LineLoop(geometry, material);
}
for (let radius = 1; radius <= 7; radius++) {
chamber.add(makeCircleLine(radius, 0.014, 0x66bda1, radius === 7 ? 0.22 : 0.105));
}
const radialPositions = [];
for (let index = 0; index < 16; index++) {
const angle = (index / 16) * Math.PI * 2;
radialPositions.push(
0, 0.016, 0,
Math.cos(angle) * 7.35, 0.016, Math.sin(angle) * 7.35
);
}
const radialGeometry = new THREE.BufferGeometry();
radialGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(radialPositions, 3)
);
chamber.add(
new THREE.LineSegments(
radialGeometry,
new THREE.LineBasicMaterial({
color: 0x65b89e,
transparent: true,
opacity: 0.09,
depthWrite: false
})
)
);
const shell = new THREE.Mesh(
new THREE.CylinderGeometry(CHAMBER_RADIUS, CHAMBER_RADIUS, 6.3, 64, 1, true),
new THREE.MeshBasicMaterial({
color: 0x8de6ca,
transparent: true,
opacity: 0.025,
side: THREE.DoubleSide,
depthWrite: false
})
);
shell.position.y = 3.15;
shell.renderOrder = -2;
chamber.add(shell);
function makeChamberRing(y, opacity, tube = 0.025) {
const ring = new THREE.Mesh(
new THREE.TorusGeometry(CHAMBER_RADIUS, tube, 6, 96),
new THREE.MeshStandardMaterial({
color: 0x70bba2,
emissive: 0x17382c,
emissiveIntensity: 0.7,
roughness: 0.5,
metalness: 0.35,
transparent: true,
opacity
})
);
ring.rotation.x = Math.PI / 2;
ring.position.y = y;
chamber.add(ring);
return ring;
}
makeChamberRing(0.22, 0.72, 0.038);
makeChamberRing(6.08, 0.48, 0.028);
const scanRing = makeChamberRing(2.7, 0.19, 0.018);
const strutPositions = [];
for (let index = 0; index < 8; index++) {
const angle = (index / 8) * Math.PI * 2 + Math.PI / 8;
const x = Math.cos(angle) * CHAMBER_RADIUS;
const z = Math.sin(angle) * CHAMBER_RADIUS;
strutPositions.push(x, 0.2, z, x, 6.08, z);
}
const strutGeometry = new THREE.BufferGeometry();
strutGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(strutPositions, 3)
);
chamber.add(
new THREE.LineSegments(
strutGeometry,
new THREE.LineBasicMaterial({
color: 0x77bda5,
transparent: true,
opacity: 0.12,
depthWrite: false
})
)
);
const dustPositions = [];
for (let index = 0; index < 180; index++) {
const angle = random() * Math.PI * 2;
const radius = Math.sqrt(random()) * 7.1;
dustPositions.push(
Math.cos(angle) * radius,
0.2 + random() * 5.8,
Math.sin(angle) * radius
);
}
const dustGeometry = new THREE.BufferGeometry();
dustGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(dustPositions, 3)
);
const dust = new THREE.Points(
dustGeometry,
new THREE.PointsMaterial({
color: 0x9de7d2,
size: 0.035,
transparent: true,
opacity: 0.32,
depthWrite: false,
sizeAttenuation: true
})
);
scene.add(dust);
// Cell rendering ------------------------------------------------------
const cellGeometry = new THREE.IcosahedronGeometry(1, 1);
const neckGeometry = new THREE.CylinderGeometry(1, 1, 1, 6, 1, false);
const generationMaterials = new Map();
function getGenerationMaterial(generation) {
if (!generationMaterials.has(generation)) {
const color = generationColor(generation);
generationMaterials.set(
generation,
new THREE.MeshStandardMaterial({
color,
emissive: color.clone().multiplyScalar(0.12),
emissiveIntensity: 0.8,
roughness: 0.42,
metalness: 0.035,
flatShading: true
})
);
}
return generationMaterials.get(generation);
}
function createCellVisual(cell) {
const group = new THREE.Group();
const material = getGenerationMaterial(cell.generation);
const body = new THREE.Mesh(cellGeometry, material);
body.userData.cellId = cell.id;
body.scale.set(cell.size * 1.07, cell.size * 0.94, cell.size);
group.add(body);
const neck = new THREE.Mesh(neckGeometry, material);
neck.visible = false;
group.add(neck);
group.position.copy(cell.position);
scene.add(group);
visuals.set(cell.id, { group, body, neck });
}
const shadowGeometry = new THREE.CircleGeometry(1, 20);
const shadowMaterial = new THREE.MeshBasicMaterial({
color: 0x000000,
transparent: true,
opacity: 0.13,
depthWrite: false
});
const shadowMesh = new THREE.InstancedMesh(
shadowGeometry,
shadowMaterial,
MAX_CELLS
);
shadowMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
shadowMesh.count = 0;
shadowMesh.frustumCulled = false;
shadowMesh.renderOrder = 1;
scene.add(shadowMesh);
const shadowDummy = new THREE.Object3D();
const selectionShell = new THREE.Mesh(
cellGeometry,
new THREE.MeshBasicMaterial({
color: 0xf2fff8,
wireframe: true,
transparent: true,
opacity: 0.62,
depthWrite: false,
depthTest: false
})
);
selectionShell.visible = false;
selectionShell.renderOrder = 20;
scene.add(selectionShell);
const lineageGeometry = new THREE.BufferGeometry();
const lineagePositions = new Float32Array(MAX_CELLS * 2 * 3);
const lineageColors = new Float32Array(MAX_CELLS * 2 * 3);
const lineagePositionAttribute = new THREE.BufferAttribute(
lineagePositions,
3
).setUsage(THREE.DynamicDrawUsage);
const lineageColorAttribute = new THREE.BufferAttribute(
lineageColors,
3
).setUsage(THREE.DynamicDrawUsage);
lineageGeometry.setAttribute("position", lineagePositionAttribute);
lineageGeometry.setAttribute("color", lineageColorAttribute);
lineageGeometry.setDrawRange(0, 0);
const lineageLines = new THREE.LineSegments(
lineageGeometry,
new THREE.LineBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0.28,
depthWrite: false
})
);
lineageLines.frustumCulled = false;
scene.add(lineageLines);
// Population model ----------------------------------------------------
function findFreePosition() {
const candidate = new THREE.Vector3();
for (let attempt = 0; attempt < 60; attempt++) {
const angle = random() * Math.PI * 2;
const radius = Math.sqrt(random()) * 6.35;
candidate.set(
Math.cos(angle) * radius,
CELL_FLOOR + random() * (CELL_CEILING - CELL_FLOOR),
Math.sin(angle) * radius
);
let clear = true;
for (const existing of cells) {
if (candidate.distanceToSquared(existing.position) < 0.9 * 0.9) {
clear = false;
break;
}
}
if (clear) return candidate.clone();
}
const angle = random() * Math.PI * 2;
const radius = Math.sqrt(random()) * 6.35;
return new THREE.Vector3(
Math.cos(angle) * radius,
CELL_FLOOR + random() * (CELL_CEILING - CELL_FLOOR),
Math.sin(angle) * radius
);
}
function createCell({
generation = 0,
parent = null,
age = 0,
size = null,
matureSize = null,
attach = false
} = {}) {
const targetSize = clamp(
matureSize ?? (0.66 + random() * 0.25),
0.58,
0.94
);
const initialSize =
size ??
(generation === 0
? targetSize * (0.82 + random() * 0.1)
: targetSize * (0.72 + random() * 0.18));
const cell = {
id: nextId++,
parentId: parent ? parent.id : null,
generation,
age,
size: initialSize,
matureSize: targetSize,
maturityAge: 2 + Math.floor(random() * 4),
cooldown: 1 + Math.floor(random() * 4),
lifespan: 15 + Math.floor(random() * 10),
direction: randomUnitVector(),
position: new THREE.Vector3(),
velocity: new THREE.Vector3(),
attachment: null
};
if (parent && attach) {
const remaining = 2 + Math.floor(random() * 2);
cell.attachment = {
parentId: parent.id,
remaining,
total: remaining
};
cell.position
.copy(parent.position)
.addScaledVector(cell.direction, parent.size + 0.08);
} else {
cell.position.copy(findFreePosition());
cell.velocity.set(
(random() - 0.5) * 0.055,
(random() - 0.5) * 0.025,
(random() - 0.5) * 0.055
);
}
cells.push(cell);
cellMap.set(cell.id, cell);
createCellVisual(cell);
return cell;
}
function createInitialPopulation() {
const roots = [];
for (let index = 0; index < 3; index++) {
roots.push(
createCell({
generation: 0,
age: Math.floor(random() * 6)
})
);
}
const generationOne = [];
for (let index = 0; index < 4; index++) {
generationOne.push(
createCell({
generation: 1,
parent: roots[index % roots.length],
age: Math.floor(random() * 5)
})
);
}
const generationTwo = [];
for (let index = 0; index < 5; index++) {
generationTwo.push(
createCell({
generation: 2,
parent: generationOne[index % generationOne.length],
age: Math.floor(random() * 4)
})
);
}
for (let index = 0; index < 2; index++) {
createCell({
generation: 3,
parent: generationTwo[index % generationTwo.length],
age: Math.floor(random() * 3)
});
}
}
function detachCell(cell) {
if (!cell.attachment) return;
cell.attachment = null;
cell.velocity.set(
(random() - 0.5) * 0.09,
(random() - 0.5) * 0.035,
(random() - 0.5) * 0.09
);
}
function removeCell(cell) {
const index = cells.indexOf(cell);
if (index !== -1) cells.splice(index, 1);
cellMap.delete(cell.id);
const visual = visuals.get(cell.id);
if (visual) {
scene.remove(visual.group);
visuals.delete(cell.id);
}
for (const other of cells) {
if (other.attachment?.parentId === cell.id) {
detachCell(other);
}
}
if (selectedId === cell.id) {
selectedId = null;
selectionShell.visible = false;
updateSelectedInfo();
}
}
function birthFrom(parent) {
if (cells.length >= MAX_CELLS || !cellMap.has(parent.id)) return;
const childMatureSize = clamp(
parent.matureSize * (0.9 + random() * 0.13),
0.58,
0.94
);
createCell({
generation: parent.generation + 1,
parent,
age: 0,
size: 0.3 + random() * 0.07,
matureSize: childMatureSize,
attach: true
});
parent.size = Math.max(0.45, parent.size - 0.17);
parent.cooldown = 3 + Math.floor(random() * 4);
}
function simulateObservation() {
cycle++;
const snapshot = [...cells];
let birthBudget = 6;
for (const cell of snapshot) {
if (!cellMap.has(cell.id)) continue;
cell.age++;
if (cell.cooldown > 0) cell.cooldown--;
cell.size += (cell.matureSize - cell.size) * 0.18;
if (cell.attachment) {
cell.attachment.remaining--;
if (cell.attachment.remaining <= 0) detachCell(cell);
}
if (cell.age >= cell.lifespan) {
removeCell(cell);
continue;
}
if (cell.age >= cell.maturityAge && cell.cooldown <= 0) {
const roomAvailable = cells.length < MAX_CELLS;
if (roomAvailable && birthBudget > 0 && random() < 0.74) {
birthFrom(cell);
birthBudget--;
} else {
cell.cooldown = 1;
}
}
}
updateStats();
}
// Statistics and charts ----------------------------------------------
function recordSnapshot(count, averageSize, generationCount) {
history.count.push(count);
history.size.push(averageSize);
history.generation.push(generationCount);
for (const key of Object.keys(history)) {
if (history[key].length > 80) history[key].shift();
}
drawSpark($("cellSpark"), history.count, "#f5ca72");
drawSpark($("sizeSpark"), history.size, "#8ee8c0");
drawSpark($("generationSpark"), history.generation, "#c7a2ff");
}
function drawSpark(canvas, values, color) {
const width = Math.max(1, canvas.clientWidth);
const height = Math.max(1, canvas.clientHeight);
const ratio = Math.min(window.devicePixelRatio || 1, 2);
if (
canvas.width !== Math.floor(width * ratio) ||
canvas.height !== Math.floor(height * ratio)
) {
canvas.width = Math.floor(width * ratio);
canvas.height = Math.floor(height * ratio);
}
const context = canvas.getContext("2d");
context.setTransform(ratio, 0, 0, ratio, 0, 0);
context.clearRect(0, 0, width, height);
if (!values.length) return;
let minimum = Math.min(...values);
let maximum = Math.max(...values);
const spread = maximum - minimum;
if (spread < 0.0001) {
minimum -= 0.5;
maximum += 0.5;
}
const padding = 3;
const usableHeight = height - padding * 2;
const points = values.map((value, index) => {
const x =
values.length === 1
? width / 2
: (index / (values.length - 1)) * width;
const y =
padding +
(1 - (value - minimum) / (maximum - minimum)) * usableHeight;
return { x, y };
});
const fillGradient = context.createLinearGradient(0, 0, 0, height);
fillGradient.addColorStop(0, `${color}38`);
fillGradient.addColorStop(1, `${color}00`);
context.beginPath();
context.moveTo(points[0].x, height);
for (const point of points) context.lineTo(point.x, point.y);
context.lineTo(points[points.length - 1].x, height);
context.closePath();
context.fillStyle = fillGradient;
context.fill();
context.beginPath();
points.forEach((point, index) => {
if (index === 0) context.moveTo(point.x, point.y);
else context.lineTo(point.x, point.y);
});
context.strokeStyle = color;
context.lineWidth = 1.6;
context.lineJoin = "round";
context.stroke();
const last = points[points.length - 1];
context.beginPath();
context.arc(last.x, last.y, 2.3, 0, Math.PI * 2);
context.fillStyle = color;
context.fill();
}
function updateStats() {
const count = cells.length;
const averageSize =
count === 0
? 0
: cells.reduce((sum, cell) => sum + cell.size, 0) / count;
const generationCount = cells.reduce(
(maximum, cell) => Math.max(maximum, cell.generation),
0
);
$("cellCount").textContent = count.toString();
$("averageSize").textContent = averageSize.toFixed(2);
$("generationCount").textContent = generationCount.toString();
$("cellMeta").textContent =
count >= MAX_CELLS
? "hard population cap reached"
: `${MAX_CELLS - count} population slots remain`;
$("capacityFill").style.width = `${(count / MAX_CELLS) * 100}%`;
$("clock").textContent = `Cycle ${String(cycle).padStart(3, "0")}`;
recordSnapshot(count, averageSize, generationCount);
updateGenerationCensus();
updateSelectedInfo();
}
function updateGenerationCensus() {
const maximumGeneration = cells.reduce(
(maximum, cell) => Math.max(maximum, cell.generation),
0
);
const counts = Array(maximumGeneration + 1).fill(0);
for (const cell of cells) counts[cell.generation]++;
const largestGroup = Math.max(1, ...counts);
$("generationBars").innerHTML = counts
.map((count, generation) => {
const width = (count / largestGroup) * 100;
const color = generationCss(generation);
return `
<div class="generation-row">
<span>G${generation}</span>
<div class="generation-track">
<div
class="generation-fill"
style="width:${width}%;background:${color};box-shadow:0 0 8px ${color}55"
></div>
</div>
<span style="text-align:right">${count}</span>
</div>
`;
})
.join("");
}
function updateSelectedInfo() {
const cell = selectedId === null ? null : cellMap.get(selectedId);
if (!cell) {
$("selectedId").textContent = "—";
$("selectedGeneration").textContent = "—";
$("selectedParent").textContent = "—";
$("selectedAge").textContent = "—";
$("selectedState").textContent = "Click a cell";
return;
}
$("selectedId").textContent = `C-${String(cell.id).padStart(4, "0")}`;
$("selectedGeneration").textContent = `G${cell.generation}`;
$("selectedParent").textContent = cell.parentId
? `C-${String(cell.parentId).padStart(4, "0")}`
: "Founder";
$("selectedAge").textContent = `${cell.age} cycles`;
$("selectedState").textContent = cell.attachment
? "Attached bud"
: "Detached";
}
function selectCell(id) {
selectedId = id;
updateSelectedInfo();
}
// Camera controls implemented directly, without addons ----------------
const orbit = {
current: {
theta: 0.72,
phi: 1.04,
radius: 16
},
goal: {
theta: 0.72,
phi: 1.04,
radius: 16
},
target: new THREE.Vector3(0, 2.45, 0)
};
const canvas = renderer.domElement;
let pointerState = null;
canvas.addEventListener("pointerdown", (event) => {
if (!event.isPrimary) return;
pointerState = {
id: event.pointerId,
x: event.clientX,
y: event.clientY,
moved: false
};
try {
canvas.setPointerCapture(event.pointerId);
} catch (_) {}
});
canvas.addEventListener("pointermove", (event) => {
if (!pointerState || pointerState.id !== event.pointerId) return;
const deltaX = event.clientX - pointerState.x;
const deltaY = event.clientY - pointerState.y;
if (Math.abs(deltaX) + Math.abs(deltaY) > 2) {
pointerState.moved = true;
}
orbit.goal.theta -= deltaX * 0.006;
orbit.goal.phi = clamp(orbit.goal.phi + deltaY * 0.005, 0.55, 1.42);
pointerState.x = event.clientX;
pointerState.y = event.clientY;
});
canvas.addEventListener("pointerup", (event) => {
if (!pointerState || pointerState.id !== event.pointerId) return;
const wasClick = !pointerState.moved;
pointerState = null;
try {
canvas.releasePointerCapture(event.pointerId);
} catch (_) {}
if (!wasClick) return;
const rectangle = canvas.getBoundingClientRect();
const pointer = new THREE.Vector2(
((event.clientX - rectangle.left) / rectangle.width) * 2 - 1,
-((event.clientY - rectangle.top) / rectangle.height) * 2 + 1
);
const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(pointer, camera);
const pickables = Array.from(visuals.values()).map((visual) => visual.body);
const intersection = raycaster.intersectObjects(pickables, false)[0];
if (intersection) {
selectCell(intersection.object.userData.cellId);
}
});
canvas.addEventListener("pointercancel", () => {
pointerState = null;
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.goal.radius = clamp(
orbit.goal.radius + event.deltaY * 0.012,
10.5,
24
);
},
{ passive: false }
);
function resetCamera() {
orbit.goal.theta = 0.72;
orbit.goal.phi = 1.04;
orbit.goal.radius = 16;
}
function updateCamera(deltaSeconds) {
const smoothing = 1 - Math.exp(-8 * deltaSeconds);
orbit.current.theta +=
(orbit.goal.theta - orbit.current.theta) * smoothing;
orbit.current.phi +=
(orbit.goal.phi - orbit.current.phi) * smoothing;
orbit.current.radius +=
(orbit.goal.radius - orbit.current.radius) * smoothing;
const { theta, phi, radius } = orbit.current;
const horizontal = Math.sin(phi) * radius;
camera.position.set(
orbit.target.x + horizontal * Math.sin(theta),
orbit.target.y + Math.cos(phi) * radius,
orbit.target.z + horizontal * Math.cos(theta)
);
camera.lookAt(orbit.target);
}
// Animation ------------------------------------------------------------
const upAxis = new THREE.Vector3(0, 1, 0);
function updateCells(deltaSeconds, elapsedSeconds) {
const followAlpha = 1 - Math.exp(-10 * deltaSeconds);
let shadowIndex = 0;
for (const cell of cells) {
let parent = null;
if (cell.attachment) {
parent = cellMap.get(cell.attachment.parentId) || null;
if (parent) {
const desired = parent.position
.clone()
.addScaledVector(
cell.direction,
parent.size * 0.78 + cell.size * 0.25
);
desired.y = clamp(desired.y, CELL_FLOOR, CELL_CEILING);
cell.position.lerp(desired, followAlpha);
cell.velocity.set(0, 0, 0);
} else {
detachCell(cell);
}
} else {
cell.position.addScaledVector(cell.velocity, deltaSeconds);
cell.velocity.multiplyScalar(Math.exp(-0.52 * deltaSeconds));
cell.velocity.x +=
Math.sin(elapsedSeconds * 0.27 + cell.id * 1.71) *
deltaSeconds *
0.004;
cell.velocity.z +=
Math.cos(elapsedSeconds * 0.23 + cell.id * 1.13) *
deltaSeconds *
0.004;
if (cell.position.y < CELL_FLOOR) {
cell.position.y = CELL_FLOOR;
cell.velocity.y = Math.abs(cell.velocity.y);
} else if (cell.position.y > CELL_CEILING) {
cell.position.y = CELL_CEILING;
cell.velocity.y = -Math.abs(cell.velocity.y);
}
const radialDistance = Math.hypot(cell.position.x, cell.position.z);
const radialLimit = 6.65;
if (radialDistance > radialLimit) {
const normalX = cell.position.x / radialDistance;
const normalZ = cell.position.z / radialDistance;
cell.position.x = normalX * radialLimit;
cell.position.z = normalZ * radialLimit;
const outwardVelocity =
cell.velocity.x * normalX + cell.velocity.z * normalZ;
if (outwardVelocity > 0) {
cell.velocity.x -= 2 * outwardVelocity * normalX;
cell.velocity.z -= 2 * outwardVelocity * normalZ;
}
}
}
const visual = visuals.get(cell.id);
if (!visual) continue;
visual.group.position.copy(cell.position);
const pulse = 1 + Math.sin(elapsedSeconds * 0.9 + cell.id) * 0.018;
visual.body.scale.set(
cell.size * 1.07 * pulse,
cell.size * 0.94 * pulse,
cell.size * pulse
);
visual.body.rotation.x +=
deltaSeconds * (0.075 + (cell.id % 5) * 0.008);
visual.body.rotation.y +=
deltaSeconds * (0.095 + (cell.id % 7) * 0.006);
if (parent) {
const toParent = parent.position.clone().sub(cell.position);
const distance = Math.max(0.001, toParent.length());
visual.neck.visible = true;
visual.neck.position.copy(toParent).multiplyScalar(0.5);
visual.neck.quaternion.setFromUnitVectors(
upAxis,
toParent.normalize()
);
visual.neck.scale.set(
cell.size * 0.12,
distance,
cell.size * 0.12
);
} else {
visual.neck.visible = false;
}
const shadowScale =
cell.size * (1.08 + (cell.position.y - CELL_FLOOR) * 0.075);
shadowDummy.position.set(cell.position.x, 0.013, cell.position.z);
shadowDummy.rotation.set(-Math.PI / 2, 0, 0);
shadowDummy.scale.set(shadowScale, shadowScale, 1);
shadowDummy.updateMatrix();
shadowMesh.setMatrixAt(shadowIndex, shadowDummy.matrix);
shadowIndex++;
}
shadowMesh.count = shadowIndex;
shadowMesh.instanceMatrix.needsUpdate = true;
}
function updateLineageLines() {
lineageLines.visible = showLineage;
if (!showLineage) return;
let edgeCount = 0;
for (const cell of cells) {
if (cell.parentId === null) continue;
const parent = cellMap.get(cell.parentId);
if (!parent) continue;
const positionOffset = edgeCount * 6;
const color = generationColor(cell.generation);
parent.position.toArray(lineagePositions, positionOffset);
cell.position.toArray(lineagePositions, positionOffset + 3);
color.toArray(lineageColors, positionOffset);
color.toArray(lineageColors, positionOffset + 3);
edgeCount++;
}
lineageGeometry.setDrawRange(0, edgeCount * 2);
lineagePositionAttribute.needsUpdate = true;
lineageColorAttribute.needsUpdate = true;
}
function updateSelectionShell() {
if (selectedId === null) {
selectionShell.visible = false;
return;
}
const visual = visuals.get(selectedId);
if (!visual) {
selectionShell.visible = false;
return;
}
selectionShell.visible = true;
selectionShell.position.copy(visual.group.position);
selectionShell.rotation.copy(visual.body.rotation);
selectionShell.scale.copy(visual.body.scale).multiplyScalar(1.075);
}
// UI and lifecycle ------------------------------------------------------
function updateStatus() {
const intervalText = $("intervalSelect").selectedOptions[0].textContent;
$("playIcon").textContent = running ? "Ⅱ" : "▶";
$("playText").textContent = running ? "Pause" : "Resume";
$("toggleRun").setAttribute("aria-pressed", String(running));
$("statusDot").classList.toggle("paused", !running);
$("statusText").textContent = running
? `Observing every ${intervalText}`
: "Observation paused";
}
function resetSimulation(useNewSeed = false) {
if (useNewSeed) {
seed = (seed + 0x9e3779b9) >>> 0;
}
random = mulberry32(seed);
nextId = 1;
cycle = 0;
observationAccumulator = 0;
selectedId = null;
for (const visual of visuals.values()) scene.remove(visual.group);
visuals.clear();
cellMap.clear();
cells.length = 0;
history.count.length = 0;
history.size.length = 0;
history.generation.length = 0;
$("seedLabel").textContent = seed
.toString(16)
.padStart(8, "0")
.toUpperCase();
createInitialPopulation();
updateStats();
updateStatus();
selectionShell.visible = false;
}
$("toggleRun").addEventListener("click", () => {
running = !running;
observationAccumulator = 0;
updateStatus();
});
$("stepButton").addEventListener("click", () => {
running = false;
simulateObservation();
updateStatus();
});
$("intervalSelect").addEventListener("change", (event) => {
intervalSeconds = Number(event.target.value) / 1000;
observationAccumulator = 0;
updateStatus();
});
$("resetButton").addEventListener("click", () => resetSimulation(false));
$("newSeedButton").addEventListener("click", () => resetSimulation(true));
$("lineageToggle").addEventListener("change", (event) => {
showLineage = event.target.checked;
lineageLines.visible = showLineage;
});
$("resetView").addEventListener("click", resetCamera);
$("zoomIn").addEventListener("click", () => {
orbit.goal.radius = clamp(orbit.goal.radius - 1.2, 10.5, 24);
});
$("zoomOut").addEventListener("click", () => {
orbit.goal.radius = clamp(orbit.goal.radius + 1.2, 10.5, 24);
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.8));
renderer.setSize(window.innerWidth, window.innerHeight, false);
drawSpark($("cellSpark"), history.count, "#f5ca72");
drawSpark($("sizeSpark"), history.size, "#8ee8c0");
drawSpark($("generationSpark"), history.generation, "#c7a2ff");
});
resetSimulation(false);
let previousTime = performance.now();
function animate(now) {
requestAnimationFrame(animate);
const deltaSeconds = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
const elapsedSeconds = now / 1000;
if (running) {
observationAccumulator += deltaSeconds;
while (observationAccumulator >= intervalSeconds) {
observationAccumulator -= intervalSeconds;
simulateObservation();
}
}
updateCamera(deltaSeconds);
updateCells(deltaSeconds, elapsedSeconds);
updateLineageLines();
updateSelectionShell();
dust.rotation.y = elapsedSeconds * 0.006;
dust.position.y = Math.sin(elapsedSeconds * 0.17) * 0.035;
scanRing.material.opacity = 0.14 + Math.sin(elapsedSeconds * 0.7) * 0.045;
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```