Prompt specification
Build or customize the Three.js 3D scene "Bottleneck severity comparison 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: Bottleneck severity comparison explorer
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/bottleneck-severity-comparison-explorer-x0888
Scene Description Prompt:
Compare low-poly synthetic population bottlenecks with randomly selected survivor counts; repeat trials to reveal variation loss. Three.js from cdnjs, one HTML file.
Working Three.js Starter (bottleneck-severity-comparison-explorer-x0888):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Founder — Population Bottleneck Lab</title>
<style>
:root {
--bg: #071116;
--panel: rgba(12, 25, 31, 0.88);
--panel-solid: #0c191f;
--line: rgba(160, 216, 226, 0.13);
--text: #e8f5f5;
--muted: #8da9af;
--cyan: #55e5ff;
--violet: #a78bfa;
--amber: #ffca68;
--coral: #ff7695;
--green: #74e3ad;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input, select { font: inherit; }
button {
border: 1px solid var(--line);
border-radius: 9px;
padding: 9px 11px;
color: var(--text);
background: rgba(255,255,255,0.045);
cursor: pointer;
transition: 0.18s ease;
}
button:hover {
border-color: rgba(85,229,255,0.45);
background: rgba(85,229,255,0.08);
transform: translateY(-1px);
}
button:active { transform: translateY(0); }
button.primary {
color: #041116;
border-color: transparent;
background: linear-gradient(135deg, #6cecff, #8cc7ff);
font-weight: 750;
}
button.secondary {
background: rgba(167,139,250,0.12);
border-color: rgba(167,139,250,0.28);
}
button.active {
color: #061217;
border-color: transparent;
background: var(--cyan);
}
#app {
display: grid;
grid-template-columns: minmax(0, 1fr) 340px;
grid-template-rows: 62px minmax(0, 1fr);
width: 100%;
height: 100%;
}
header {
grid-column: 1 / -1;
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
padding: 0 20px;
border-bottom: 1px solid var(--line);
background: rgba(7,17,22,0.94);
z-index: 20;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-mark {
position: relative;
width: 30px;
height: 30px;
border: 1px solid rgba(85,229,255,0.55);
border-radius: 8px;
transform: rotate(45deg);
box-shadow: inset 0 0 15px rgba(85,229,255,0.12);
flex: none;
}
.brand-mark::after {
content: "";
position: absolute;
inset: 7px;
border-radius: 4px;
background: var(--cyan);
box-shadow: 0 0 14px rgba(85,229,255,0.65);
}
.brand h1 {
margin: 0;
font-size: 17px;
font-weight: 760;
letter-spacing: 0.02em;
white-space: nowrap;
}
.brand p {
margin: 2px 0 0;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.header-note {
color: var(--muted);
font-size: 12px;
text-align: right;
}
.header-note strong { color: var(--cyan); }
main {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
isolation: isolate;
}
#sceneWrap {
position: absolute;
inset: 0;
overflow: hidden;
background:
radial-gradient(circle at 48% 38%, rgba(25,76,89,0.31), transparent 34%),
radial-gradient(circle at 50% 100%, rgba(111,76,150,0.12), transparent 42%),
linear-gradient(145deg, #09161c, #050d12 72%);
}
#sceneWrap::after {
content: "";
position: absolute;
inset: 0;
pointer-events: none;
background-image:
linear-gradient(rgba(255,255,255,0.012) 1px, transparent 1px),
linear-gradient(90deg, rgba(255,255,255,0.012) 1px, transparent 1px);
background-size: 38px 38px;
mask-image: linear-gradient(to bottom, black, transparent 85%);
}
#sceneWrap canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#sceneWrap canvas.dragging { cursor: grabbing; }
.glass {
border: 1px solid var(--line);
background: var(--panel);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
box-shadow: 0 15px 40px rgba(0,0,0,0.22);
}
.hud {
position: absolute;
z-index: 5;
top: 16px;
left: 16px;
min-width: 285px;
padding: 13px 14px;
border-radius: 13px;
pointer-events: none;
}
.hud-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
margin-bottom: 10px;
}
.phase {
display: inline-flex;
align-items: center;
gap: 7px;
color: var(--cyan);
font-size: 12px;
font-weight: 750;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.phase::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 10px currentColor;
}
#trialText {
color: var(--muted);
font-size: 11px;
}
.hud-stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
}
.hud-stat {
border-left: 1px solid var(--line);
padding-left: 9px;
}
.hud-stat:first-child {
border-left: 0;
padding-left: 0;
}
.hud-stat span {
display: block;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.hud-stat strong {
display: block;
margin-top: 3px;
font-size: 15px;
font-variant-numeric: tabular-nums;
}
.camera-tools {
position: absolute;
z-index: 6;
top: 16px;
right: 16px;
display: flex;
gap: 6px;
}
.camera-tools button {
width: 34px;
height: 34px;
padding: 0;
border-radius: 9px;
background: rgba(8,20,26,0.78);
backdrop-filter: blur(12px);
}
.legend {
position: absolute;
z-index: 5;
left: 16px;
top: 126px;
width: 285px;
padding: 11px 13px;
border-radius: 12px;
pointer-events: none;
}
.legend-title {
margin-bottom: 8px;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.gradient {
height: 7px;
border-radius: 10px;
background: linear-gradient(90deg, #4ee4ff, #8a75ff 50%, #ff7898);
}
.legend-labels {
display: flex;
justify-content: space-between;
margin-top: 5px;
color: var(--muted);
font-size: 10px;
}
.legend-row {
display: flex;
gap: 12px;
margin-top: 9px;
color: #b1c6ca;
font-size: 10px;
}
.legend-row span {
display: inline-flex;
align-items: center;
gap: 5px;
}
.dot {
width: 7px;
height: 7px;
border-radius: 50%;
display: inline-block;
}
.chart-card {
position: absolute;
z-index: 7;
left: 16px;
bottom: 16px;
width: min(480px, calc(100% - 32px));
padding: 13px 13px 10px;
border-radius: 14px;
}
.chart-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 6px;
}
.chart-heading strong {
font-size: 12px;
letter-spacing: 0.03em;
}
.chart-heading small {
color: var(--muted);
font-size: 9px;
}
.chart-legend {
display: flex;
flex-wrap: wrap;
gap: 10px;
color: var(--muted);
font-size: 9px;
}
.chart-legend span {
display: inline-flex;
align-items: center;
gap: 4px;
}
.line-key {
width: 13px;
height: 2px;
border-radius: 3px;
}
#chart {
display: block;
width: 100%;
height: 150px;
}
.chart-tip {
position: absolute;
z-index: 12;
display: none;
min-width: 178px;
padding: 9px 10px;
border: 1px solid rgba(85,229,255,0.24);
border-radius: 9px;
color: var(--text);
background: rgba(5,15,20,0.95);
box-shadow: 0 8px 25px rgba(0,0,0,0.35);
pointer-events: none;
font-size: 10px;
line-height: 1.55;
}
.chart-tip b { color: var(--cyan); }
.interaction-hint {
position: absolute;
z-index: 4;
right: 16px;
bottom: 16px;
padding: 7px 10px;
border-radius: 9px;
color: var(--muted);
background: rgba(7,17,22,0.66);
font-size: 10px;
pointer-events: none;
}
aside {
grid-column: 2;
grid-row: 2;
min-height: 0;
overflow-y: auto;
border-left: 1px solid var(--line);
background: rgba(8,19,24,0.96);
scrollbar-width: thin;
scrollbar-color: rgba(85,229,255,0.25) transparent;
}
aside::-webkit-scrollbar { width: 7px; }
aside::-webkit-scrollbar-thumb {
background: rgba(85,229,255,0.2);
border-radius: 10px;
}
.control-section {
padding: 17px 18px;
border-bottom: 1px solid var(--line);
}
.section-title {
margin: 0 0 14px;
color: #b8ccd0;
font-size: 10px;
font-weight: 760;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.control {
margin-bottom: 15px;
}
.control:last-child { margin-bottom: 0; }
.control-label {
display: flex;
justify-content: space-between;
align-items: center;
gap: 10px;
margin-bottom: 7px;
color: #c9dadd;
font-size: 11px;
}
output {
min-width: 42px;
padding: 3px 6px;
border-radius: 6px;
color: var(--cyan);
background: rgba(85,229,255,0.08);
text-align: center;
font-size: 10px;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 7px 0;
accent-color: var(--cyan);
cursor: pointer;
}
select {
width: 100%;
padding: 9px 10px;
border: 1px solid var(--line);
border-radius: 8px;
color: var(--text);
background: #102129;
outline: none;
font-size: 11px;
}
.switch-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 13px;
color: #c9dadd;
font-size: 11px;
}
.switch {
position: relative;
width: 35px;
height: 19px;
flex: none;
}
.switch input {
position: absolute;
opacity: 0;
}
.switch-track {
position: absolute;
inset: 0;
border: 1px solid var(--line);
border-radius: 20px;
background: rgba(255,255,255,0.06);
transition: 0.2s;
cursor: pointer;
}
.switch-track::after {
content: "";
position: absolute;
top: 3px;
left: 3px;
width: 11px;
height: 11px;
border-radius: 50%;
background: #91a8ad;
transition: 0.2s;
}
.switch input:checked + .switch-track {
border-color: rgba(85,229,255,0.45);
background: rgba(85,229,255,0.18);
}
.switch input:checked + .switch-track::after {
left: 19px;
background: var(--cyan);
box-shadow: 0 0 9px rgba(85,229,255,0.65);
}
.two-col {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 11px;
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.buttons .wide {
grid-column: 1 / -1;
}
.results {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.result-card {
min-height: 73px;
padding: 11px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255,255,255,0.025);
}
.result-card span {
display: block;
color: var(--muted);
font-size: 9px;
line-height: 1.25;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.result-card strong {
display: block;
margin-top: 7px;
font-size: 19px;
font-variant-numeric: tabular-nums;
}
.result-card.cyan strong { color: var(--cyan); }
.result-card.violet strong { color: var(--violet); }
.result-card.green strong { color: var(--green); }
.result-card.amber strong { color: var(--amber); }
.result-note {
margin-top: 9px;
color: var(--muted);
font-size: 9px;
line-height: 1.5;
}
details {
color: var(--muted);
font-size: 10px;
line-height: 1.6;
}
summary {
cursor: pointer;
color: #c9dadd;
font-size: 11px;
}
details p { margin: 10px 0 0; }
.toast {
position: fixed;
z-index: 50;
top: 76px;
left: 50%;
transform: translate(-50%, -8px);
padding: 9px 13px;
border: 1px solid rgba(85,229,255,0.25);
border-radius: 9px;
color: #d9f9ff;
background: rgba(8,25,31,0.94);
opacity: 0;
pointer-events: none;
transition: 0.22s;
font-size: 11px;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
.hidden { display: none !important; }
@media (max-width: 900px) {
#app {
grid-template-columns: 1fr;
grid-template-rows: 56px minmax(310px, 53vh) minmax(0, 1fr);
}
header { padding: 0 14px; }
.header-note { display: none; }
aside {
grid-column: 1;
grid-row: 3;
border-left: 0;
border-top: 1px solid var(--line);
}
.hud { top: 10px; left: 10px; min-width: 245px; }
.legend { display: none; }
.camera-tools { top: 10px; right: 10px; }
.chart-card { left: 10px; bottom: 10px; width: calc(100% - 20px); }
.interaction-hint { display: none; }
#chart { height: 125px; }
}
@media (max-width: 520px) {
.brand p { display: none; }
.hud { min-width: 215px; padding: 10px; }
.hud-stats { gap: 5px; }
.hud-stat strong { font-size: 13px; }
.chart-heading small { display: none; }
.control-section { padding: 15px; }
}
</style>
</head>
<body>
<div id="app">
<header>
<div class="brand">
<div class="brand-mark"></div>
<div>
<h1>FOUNDER</h1>
<p>Population bottleneck laboratory</p>
</div>
</div>
<div class="header-note">
Random selection · stochastic drift · <strong>low-poly genetics</strong>
</div>
</header>
<main>
<div id="sceneWrap"></div>
<div class="hud glass">
<div class="hud-top">
<div class="phase" id="phaseText">Source population</div>
<div id="trialText">Ready</div>
</div>
<div class="hud-stats">
<div class="hud-stat">
<span>Population</span>
<strong id="populationStat">120</strong>
</div>
<div class="hud-stat">
<span>Survivors</span>
<strong id="survivorStat">—</strong>
</div>
<div class="hud-stat">
<span>Descendant H</span>
<strong id="descendantStat">—</strong>
</div>
</div>
</div>
<div class="camera-tools">
<button id="zoomIn" title="Zoom in">+</button>
<button id="zoomOut" title="Zoom out">−</button>
<button id="resetCamera" title="Reset camera">⌂</button>
</div>
<div class="legend glass">
<div class="legend-title" id="legendTitle">Polygenic score</div>
<div class="gradient"></div>
<div class="legend-labels">
<span>Lower</span>
<span>Higher</span>
</div>
<div class="legend-row">
<span><i class="dot" style="background:#55e5ff"></i> Allele A</span>
<span><i class="dot" style="background:#ff7695"></i> Allele B</span>
</div>
</div>
<div class="chart-card glass">
<div class="chart-heading">
<strong>Variation retained across trials</strong>
<small>100% = unbottlenecked reference</small>
</div>
<div class="chart-legend">
<span><i class="line-key" style="background:#55e5ff"></i> Allelic richness</span>
<span><i class="line-key" style="background:#a78bfa"></i> Trait variance</span>
<span><i class="line-key" style="background:#ffca68"></i> Heterozygosity</span>
</div>
<canvas id="chart"></canvas>
<div class="chart-tip" id="chartTip"></div>
</div>
<div class="interaction-hint">Drag to orbit · wheel to zoom · double-click to reset</div>
</main>
<aside>
<section class="control-section">
<h2 class="section-title">Synthetic population</h2>
<div class="control">
<div class="control-label">
<span>Starting population</span>
<output id="populationOut">120</output>
</div>
<input id="population" type="range" min="40" max="180" value="120">
</div>
<div class="control">
<div class="control-label">
<span>Genetic loci</span>
<output id="lociOut">6</output>
</div>
<input id="loci" type="range" min="2" max="10" value="6">
</div>
<div class="control">
<div class="control-label">
<span>Body color encoding</span>
</div>
<select id="traitMode">
<option value="polygenic">Polygenic score</option>
<option value="first">First locus allele</option>
<option value="last">Last locus allele</option>
</select>
</div>
</section>
<section class="control-section">
<h2 class="section-title">Bottleneck</h2>
<div class="switch-row">
<span>Randomize survivor count</span>
<label class="switch">
<input id="randomCount" type="checkbox" checked>
<span class="switch-track"></span>
</label>
</div>
<div id="randomRange">
<div class="two-col">
<div class="control">
<div class="control-label">
<span>Minimum</span>
<output id="randomMinOut">4</output>
</div>
<input id="randomMin" type="range" min="2" max="180" value="4">
</div>
<div class="control">
<div class="control-label">
<span>Maximum</span>
<output id="randomMaxOut">24</output>
</div>
<input id="randomMax" type="range" min="2" max="180" value="24">
</div>
</div>
</div>
<div id="fixedRange" class="hidden">
<div class="control">
<div class="control-label">
<span>Fixed survivors</span>
<output id="fixedOut">12</output>
</div>
<input id="fixedCount" type="range" min="2" max="180" value="12">
</div>
</div>
<div class="control">
<div class="control-label">
<span>Animation speed</span>
<output id="speedOut">1.0×</output>
</div>
<input id="speed" type="range" min="0.5" max="2.5" step="0.1" value="1">
</div>
</section>
<section class="control-section">
<h2 class="section-title">Experiments</h2>
<div class="buttons">
<button id="runTrial" class="primary">Run trial</button>
<button id="autoRepeat">Auto repeat</button>
<button id="runBurst" class="secondary wide">Run 20 fast trials</button>
<button id="resetExperiment" class="wide">Reset experiment</button>
</div>
</section>
<section class="control-section">
<h2 class="section-title">Latest / mean results</h2>
<div class="results">
<div class="result-card cyan">
<span>Actual bottleneck</span>
<strong id="actualK">—</strong>
</div>
<div class="result-card green">
<span>Mean allelic richness</span>
<strong id="meanRichness">—</strong>
</div>
<div class="result-card violet">
<span>Mean trait variance</span>
<strong id="meanVariance">—</strong>
</div>
<div class="result-card amber">
<span>Mean alleles lost</span>
<strong id="meanLost">—</strong>
</div>
</div>
<div class="result-note">
Metrics compare the random survivor sample with the original population.
The descendant pool inherits only alleles present in those survivors.
</div>
</section>
<section class="control-section">
<details>
<summary>Model notes</summary>
<p>
Every person carries two alleles at each locus. A uniformly random subset
survives. The outer ring is then repopulated by random survivor pairs.
Body color shows a polygenic score or one locus; the diamond above each
head shows the first locus allele.
</p>
<p>
Allelic richness measures the fraction of original distinct alleles still
present. Trait variance measures polygenic-score variance. Observed
heterozygosity measures mixed allele pairs and may fluctuate in either
direction because of sampling.
</p>
</details>
</section>
</aside>
</div>
<div id="toast" class="toast"></div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
/* --------------------------------------------------------------------------
DOM and utilities
-------------------------------------------------------------------------- */
const $ = id => document.getElementById(id);
const clamp = THREE.MathUtils.clamp;
const lerp = THREE.MathUtils.lerp;
const easeOutCubic = t => 1 - Math.pow(1 - t, 3);
const populationInput = $("population");
const lociInput = $("loci");
const randomCountInput = $("randomCount");
const randomMinInput = $("randomMin");
const randomMaxInput = $("randomMax");
const fixedCountInput = $("fixedCount");
const speedInput = $("speed");
const traitModeInput = $("traitMode");
const chart = $("chart");
const chartContext = chart.getContext("2d");
const chartTip = $("chartTip");
let toastTimer;
function toast(message) {
$("toast").textContent = message;
$("toast").classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => $("toast").classList.remove("show"), 1700);
}
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function shuffle(values) {
const result = values.slice();
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}
function average(values) {
if (!values.length) return 0;
return values.reduce((sum, value) => sum + value, 0) / values.length;
}
function percent(value) {
return Number.isFinite(value) ? `${(value * 100).toFixed(1)}%` : "—";
}
/* --------------------------------------------------------------------------
Three.js scene
-------------------------------------------------------------------------- */
const sceneWrap = $("sceneWrap");
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x071116, 10, 20);
const camera = new THREE.PerspectiveCamera(39, 1, 0.1, 50);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setClearColor(0x000000, 0);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
sceneWrap.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xa4ecff, 0x142026, 1.65);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.35);
keyLight.position.set(4.5, 8.5, 5.5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -7;
keyLight.shadow.camera.right = 7;
keyLight.shadow.camera.top = 7;
keyLight.shadow.camera.bottom = -7;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 22;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x9274ff, 20, 13, 2);
rimLight.position.set(-4, 3.2, -3.5);
scene.add(rimLight);
const cyanLight = new THREE.PointLight(0x42dfff, 13, 10, 2);
cyanLight.position.set(3, 1.5, 4);
scene.add(cyanLight);
const platformMaterial = new THREE.MeshStandardMaterial({
color: 0x10272e,
roughness: 0.9,
metalness: 0.08,
flatShading: true
});
const platform = new THREE.Mesh(
new THREE.CylinderGeometry(5.35, 5.65, 0.22, 48),
platformMaterial
);
platform.position.y = -0.13;
platform.receiveShadow = true;
scene.add(platform);
const innerPlatform = new THREE.Mesh(
new THREE.CylinderGeometry(2.48, 2.55, 0.07, 40),
new THREE.MeshStandardMaterial({
color: 0x15343c,
roughness: 0.92,
metalness: 0.04
})
);
innerPlatform.position.y = -0.005;
innerPlatform.receiveShadow = true;
scene.add(innerPlatform);
function addRing(radius, opacity, color = 0x3e8797) {
const ring = new THREE.Mesh(
new THREE.TorusGeometry(radius, 0.015, 4, 96),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity,
depthWrite: false
})
);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.025;
scene.add(ring);
}
addRing(4.62, 0.33);
addRing(2.49, 0.23, 0x8c73d9);
const gridVertices = [];
for (let i = 0; i < 16; i++) {
const angle = (i / 16) * Math.PI * 2;
gridVertices.push(
Math.cos(angle) * 2.52, 0.025, Math.sin(angle) * 2.52,
Math.cos(angle) * 4.58, 0.025, Math.sin(angle) * 4.58
);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute("position", new THREE.Float32BufferAttribute(gridVertices, 3));
const gridLines = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x4d8b98,
transparent: true,
opacity: 0.13,
depthWrite: false
})
);
scene.add(gridLines);
/* --------------------------------------------------------------------------
Instanced low-poly people
-------------------------------------------------------------------------- */
const MAX_POPULATION = 180;
const MAX_SLOTS = MAX_POPULATION * 2;
function translatedGeometry(geometry, x, y, z) {
geometry.translate(x, y, z);
return geometry;
}
function createInstancedPart(geometry) {
const material = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.78,
metalness: 0.025,
flatShading: true
});
const mesh = new THREE.InstancedMesh(geometry, material, MAX_SLOTS);
mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.frustumCulled = false;
scene.add(mesh);
return mesh;
}
const parts = {
body: createInstancedPart(translatedGeometry(
new THREE.CylinderGeometry(0.15, 0.19, 0.50, 5),
0, 0.53, 0
)),
head: createInstancedPart(translatedGeometry(
new THREE.IcosahedronGeometry(0.135, 0),
0, 0.94, 0
)),
leftLeg: createInstancedPart(translatedGeometry(
new THREE.BoxGeometry(0.10, 0.34, 0.12),
-0.085, 0.17, 0
)),
rightLeg: createInstancedPart(translatedGeometry(
new THREE.BoxGeometry(0.10, 0.34, 0.12),
0.085, 0.17, 0
)),
leftArm: createInstancedPart(translatedGeometry(
new THREE.BoxGeometry(0.075, 0.30, 0.085),
-0.225, 0.57, 0
)),
rightArm: createInstancedPart(translatedGeometry(
new THREE.BoxGeometry(0.075, 0.30, 0.085),
0.225, 0.57, 0
)),
badge: createInstancedPart(translatedGeometry(
new THREE.OctahedronGeometry(0.058, 0),
0, 1.16, 0
))
};
const partMeshes = Object.values(parts);
const dummy = new THREE.Object3D();
const hiddenPosition = new THREE.Vector3(0, -100, 0);
function hideInstance(index) {
dummy.position.copy(hiddenPosition);
dummy.rotation.set(0, 0, 0);
dummy.scale.setScalar(0);
dummy.updateMatrix();
for (const mesh of partMeshes) mesh.setMatrixAt(index, dummy.matrix);
}
for (let i = 0; i < MAX_SLOTS; i++) hideInstance(i);
const skinColors = [
new THREE.Color("#f0c7a4"),
new THREE.Color("#d9a77c"),
new THREE.Color("#b87954"),
new THREE.Color("#82523d"),
new THREE.Color("#edb890")
];
const pantsColor = new THREE.Color("#1b2933");
const culledColor = new THREE.Color("#26343b");
const alleleAColor = new THREE.Color("#55e5ff");
const alleleBColor = new THREE.Color("#ff7695");
const colorA = new THREE.Color("#4ee4ff");
const colorB = new THREE.Color("#8a75ff");
const colorC = new THREE.Color("#ff7898");
function colorForTrait(value) {
const color = new THREE.Color();
if (value <= 0.5) {
color.copy(colorA).lerp(colorB, value * 2);
} else {
color.copy(colorB).lerp(colorC, (value - 0.5) * 2);
}
return color;
}
function phyllotaxis(count, radius, rotation = 0) {
const points = [];
const goldenAngle = Math.PI * (3 - Math.sqrt(5));
for (let i = 0; i < count; i++) {
const r = radius * Math.sqrt((i + 0.5) / count);
const angle = i * goldenAngle + rotation;
points.push({
x: Math.cos(angle) * r,
z: Math.sin(angle) * r,
angle
});
}
return points;
}
/* --------------------------------------------------------------------------
Custom orbit camera — no addons
-------------------------------------------------------------------------- */
const cameraState = {
yaw: 0.42,
pitch: 0.86,
distance: 12.6,
target: new THREE.Vector3(0, 0.24, 0)
};
function resetCamera() {
cameraState.yaw = 0.42;
cameraState.pitch = 0.86;
cameraState.distance = 12.6;
cameraState.target.set(0, 0.24, 0);
}
function updateCamera() {
const horizontal = cameraState.distance * Math.cos(cameraState.pitch);
camera.position.set(
cameraState.target.x + Math.sin(cameraState.yaw) * horizontal,
cameraState.target.y + Math.sin(cameraState.pitch) * cameraState.distance,
cameraState.target.z + Math.cos(cameraState.yaw) * horizontal
);
camera.lookAt(cameraState.target);
}
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.classList.add("dragging");
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.yaw -= dx * 0.006;
cameraState.pitch = clamp(cameraState.pitch + dy * 0.0045, 0.32, 1.38);
});
function stopDragging(event) {
dragging = false;
renderer.domElement.classList.remove("dragging");
if (event?.pointerId !== undefined) {
try { renderer.domElement.releasePointerCapture(event.pointerId); }
catch (_) {}
}
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.distance = clamp(
cameraState.distance * Math.exp(event.deltaY * 0.001),
7.2,
19
);
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
$("zoomIn").addEventListener("click", () => {
cameraState.distance = clamp(cameraState.distance - 0.8, 7.2, 19);
});
$("zoomOut").addEventListener("click", () => {
cameraState.distance = clamp(cameraState.distance + 0.8, 7.2, 19);
});
$("resetCamera").addEventListener("click", resetCamera);
/* --------------------------------------------------------------------------
Genetics and statistics
-------------------------------------------------------------------------- */
function getSettings() {
const population = Number(populationInput.value);
const randomMin = Math.min(Number(randomMinInput.value), population);
const randomMax = Math.min(Math.max(Number(randomMaxInput.value), randomMin), population);
return {
population,
loci: Number(lociInput.value),
randomCount: randomCountInput.checked,
randomMin,
randomMax,
fixedCount: Math.min(Number(fixedCountInput.value), population),
speed: Number(speedInput.value),
traitMode: traitModeInput.value
};
}
function displayTrait(individual, settings) {
if (settings.traitMode === "first") {
return individual.genes[0][0] + individual.genes[0][1];
}
if (settings.traitMode === "last") {
const last = individual.genes[settings.loci - 1];
return last[0] + last[1];
}
return individual.polygenic;
}
function refreshColors(trial) {
if (!trial) return;
for (const individual of [...trial.parents, ...trial.children]) {
individual.trait = displayTrait(individual, trial.settings);
individual.color = colorForTrait(individual.trait);
individual.badgeColor = individual.genes[0][0]
? alleleAColor.clone()
: alleleBColor.clone();
}
}
function analyzePopulation(group, loci) {
if (!group.length) {
return {
heterozygosity: 0,
expectedHeterozygosity: 0,
variance: 0,
richness: 0,
richnessCount: 0
};
}
let heterozygosity = 0;
let expectedHeterozygosity = 0;
let richnessCount = 0;
const meanTrait = average(group.map(individual => individual.polygenic));
const variance = average(
group.map(individual => (individual.polygenic - meanTrait) ** 2)
);
for (let locus = 0; locus < loci; locus++) {
let alleleOneCount = 0;
const presence = [false, false];
for (const individual of group) {
const pair = individual.genes[locus];
alleleOneCount += pair[0] + pair[1];
if (pair[0] === pair[1]) heterozygosity++;
presence[pair[0]] = true;
presence[pair[1]] = true;
}
const frequency = alleleOneCount / (group.length * 2);
expectedHeterozygosity += 2 * frequency * (1 - frequency);
richnessCount += Number(presence[0]) + Number(presence[1]);
}
return {
heterozygosity: heterozygosity / (group.length * loci),
expectedHeterozygosity: expectedHeterozygosity / loci,
variance,
richness: richnessCount / (loci * 2),
richnessCount
};
}
function createTrial(settings) {
const n = settings.population;
const loci = settings.loci;
const parentPositions = phyllotaxis(n, 4.55);
const parents = [];
for (let i = 0; i < n; i++) {
const genes = [];
let polygenic = 0;
for (let locus = 0; locus < loci; locus++) {
// Slightly different starting allele frequencies at each locus.
const frequency = 0.5 + Math.sin((locus + 1) * 1.71) * 0.09;
const pair = [
Math.random() < frequency ? 1 : 0,
Math.random() < frequency ? 1 : 0
];
genes.push(pair);
polygenic += (pair[0] + pair[1]) / 2;
}
polygenic /= loci;
const position = parentPositions[i];
const radialJitter = 0.06 + Math.random() * 0.10;
const angle = position.angle + (Math.random() - 0.5) * 0.06;
const individual = {
genes,
polygenic,
trait: 0,
color: new THREE.Color(),
badgeColor: new THREE.Color(),
skin: skinColors[randomInt(0, skinColors.length - 1)].clone(),
outer: new THREE.Vector3(
Math.cos(angle) * (Math.hypot(position.x, position.z) + radialJitter),
0,
Math.sin(angle) * (Math.hypot(position.x, position.z) + radialJitter)
),
central: null,
yaw: Math.random() * Math.PI * 2
};
parents.push(individual);
}
const survivorCount = settings.randomCount
? randomInt(settings.randomMin, settings.randomMax)
: settings.fixedCount;
const survivorIndices = shuffle(
Array.from({ length: n }, (_, index) => index)
).slice(0, survivorCount);
const survivorSet = new Set(survivorIndices);
const centralRadius = survivorCount <= 24
? 1.45
: survivorCount <= 60
? 1.95
: 2.30;
const centralPositions = phyllotaxis(
survivorCount,
centralRadius,
0.37
);
survivorIndices.forEach((parentIndex, index) => {
const point = centralPositions[index];
parents[parentIndex].central = new THREE.Vector3(point.x, 0, point.z);
});
const survivorGroup = survivorIndices.map(index => parents[index]);
const children = [];
const childPositions = phyllotaxis(n, 4.64, 0.12);
for (let i = 0; i < n; i++) {
const parentA = survivorGroup[randomInt(0, survivorCount - 1)];
const parentB = survivorGroup[randomInt(0, survivorCount - 1)];
const genes = [];
for (let locus = 0; locus < loci; locus++) {
const alleleA = parentA.genes[locus][randomInt(0, 1)];
const alleleB = parentB.genes[locus][randomInt(0, 1)];
genes.push([alleleA, alleleB]);
}
const point = childPositions[i];
const radialJitter = 0.04 + Math.random() * 0.12;
const radius = Math.hypot(point.x, point.z) + radialJitter;
const angle = point.angle + (Math.random() - 0.5) * 0.08;
const polygenic = genes.reduce(
(sum, pair) => sum + (pair[0] + pair[1]) / 2,
0
) / loci;
const child = {
genes,
polygenic,
trait: 0,
color: new THREE.Color(),
badgeColor: new THREE.Color(),
skin: parentA.skin.clone().lerp(parentB.skin, 0.5),
outer: new THREE.Vector3(
Math.cos(angle) * radius,
0,
Math.sin(angle) * radius
),
central: null,
yaw: Math.random() * Math.PI * 2
};
children.push(child);
}
const initialStats = analyzePopulation(parents, loci);
const survivorStats = analyzePopulation(survivorGroup, loci);
const childStats = analyzePopulation(children, loci);
const trial = {
n,
settings,
parents,
children,
survivorIndices,
survivorSet,
survivorCount,
initialStats,
survivorStats,
childStats,
metrics: {
k: survivorCount,
n,
loci,
richnessRetained: survivorStats.richness / initialStats.richness,
varianceRetained: survivorStats.variance / initialStats.variance,
heterozygosityRetained: survivorStats.heterozygosity / initialStats.heterozygosity,
descendantExpectedHeterozygosity:
childStats.expectedHeterozygosity / initialStats.expectedHeterozygosity,
lostAlleles: initialStats.richnessCount - survivorStats.richnessCount
}
};
refreshColors(trial);
return trial;
}
/* --------------------------------------------------------------------------
Experiment state and animation
-------------------------------------------------------------------------- */
let currentTrial = null;
let history = [];
let phase = "idle";
let phaseStart = 0;
let autoRepeat = false;
let autoTimer = null;
const SELECT_DURATION = 760;
const REPRODUCE_DURATION = 850;
function phaseLabel() {
if (phase === "select") return "Sampling bottleneck";
if (phase === "reproduce") return "Rebuilding descendants";
if (phase === "complete") return "Founder effect visible";
return "Source population";
}
function updateStageUI() {
$("phaseText").textContent = phaseLabel();
$("trialText").textContent = history.length
? `Trial ${history.length}`
: "Ready";
$("populationStat").textContent = currentTrial?.n ?? "—";
$("survivorStat").textContent = currentTrial
? `${currentTrial.survivorCount}`
: "—";
$("descendantStat").textContent = currentTrial
? percent(currentTrial.metrics.descendantExpectedHeterozygosity)
: "—";
}
function updateResults() {
if (!history.length) {
$("actualK").textContent = "—";
$("meanRichness").textContent = "—";
$("meanVariance").textContent = "—";
$("meanLost").textContent = "—";
return;
}
const last = history[history.length - 1];
$("actualK").textContent = `${last.k} / ${last.n}`;
$("meanRichness").textContent = percent(
average(history.map(item => item.richnessRetained))
);
$("meanVariance").textContent = percent(
average(history.map(item => item.varianceRetained))
);
$("meanLost").textContent = average(
history.map(item => item.lostAlleles)
).toFixed(1);
}
function startAnimatedTrial() {
if (autoTimer) {
clearTimeout(autoTimer);
autoTimer = null;
}
const settings = getSettings();
currentTrial = createTrial(settings);
history.push({
...currentTrial.metrics,
trial: history.length + 1
});
phase = "select";
phaseStart = performance.now();
updateStageUI();
updateResults();
drawChart();
}
function stopAuto() {
autoRepeat = false;
$("autoRepeat").classList.remove("active");
$("autoRepeat").textContent = "Auto repeat";
if (autoTimer) {
clearTimeout(autoTimer);
autoTimer = null;
}
}
function resetExperiment(showToast = true) {
stopAuto();
history = [];
phase = "idle";
phaseStart = 0;
currentTrial = createTrial(getSettings());
updateStageUI();
updateResults();
drawChart();
if (showToast) toast("Experiment reset");
}
function runFastTrials(count = 20) {
stopAuto();
const settings = getSettings();
for (let i = 0; i < count; i++) {
const trial = createTrial(settings);
history.push({
...trial.metrics,
trial: history.length + 1
});
currentTrial = trial;
}
phase = "complete";
phaseStart = performance.now();
updateStageUI();
updateResults();
drawChart();
toast(`${count} trials completed`);
}
$("runTrial").addEventListener("click", () => {
stopAuto();
startAnimatedTrial();
});
$("autoRepeat").addEventListener("click", () => {
if (autoRepeat) {
stopAuto();
return;
}
autoRepeat = true;
$("autoRepeat").classList.add("active");
$("autoRepeat").textContent = "Stop auto";
if (phase === "idle" || phase === "complete") {
startAnimatedTrial();
}
});
$("runBurst").addEventListener("click", () => runFastTrials(20));
$("resetExperiment").addEventListener("click", () => resetExperiment());
/* --------------------------------------------------------------------------
Instance animation
-------------------------------------------------------------------------- */
let lastSlots = 0;
function writePerson(index, position, scale, bodyColor, skinColor, badgeColor, yaw) {
dummy.position.copy(position);
dummy.rotation.set(0, yaw, 0);
dummy.scale.setScalar(scale);
dummy.updateMatrix();
for (const mesh of partMeshes) mesh.setMatrixAt(index, dummy.matrix);
parts.body.setColorAt(index, bodyColor);
parts.head.setColorAt(index, skinColor);
parts.leftArm.setColorAt(index, skinColor);
parts.rightArm.setColorAt(index, skinColor);
parts.leftLeg.setColorAt(index, pantsColor);
parts.rightLeg.setColorAt(index, pantsColor);
parts.badge.setColorAt(index, badgeColor);
}
const temporaryColor = new THREE.Color();
const temporaryPosition = new THREE.Vector3();
function updateInstances(now) {
const slots = currentTrial ? currentTrial.n * 2 : 0;
if (lastSlots > slots) {
for (let index = slots; index < lastSlots; index++) hideInstance(index);
}
if (!currentTrial) {
for (const mesh of partMeshes) {
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
}
return;
}
const trial = currentTrial;
const speed = trial.settings.speed;
const selectionProgress = phase === "select"
? clamp((now - phaseStart) / (SELECT_DURATION / speed), 0, 1)
: phase === "idle" ? 0 : 1;
const childProgress = phase === "reproduce"
? clamp((now - phaseStart) / (REPRODUCE_DURATION / speed), 0, 1)
: phase === "complete" ? 1 : 0;
const easedSelection = easeOutCubic(selectionProgress);
const easedChild = easeOutCubic(childProgress);
for (let i = 0; i < trial.n; i++) {
const individual = trial.parents[i];
const survivor = trial.survivorSet.has(i);
let scale = 1;
let y = 0;
temporaryPosition.copy(individual.outer);
if (phase === "select" && !survivor) {
scale = Math.max(0, 1 - easedSelection);
y = -0.48 * easedSelection;
} else if (phase === "select" && survivor) {
temporaryPosition.lerp(individual.central, easedSelection);
scale = 1 + Math.sin(easedSelection * Math.PI) * 0.06;
} else if (phase === "reproduce" || phase === "complete") {
if (survivor) {
temporaryPosition.copy(individual.central);
scale = 0.76;
} else {
scale = 0;
}
}
temporaryColor.copy(individual.color);
if (phase === "select" && !survivor) {
temporaryColor.lerp(culledColor, easedSelection * 0.88);
}
temporaryPosition.y += y;
writePerson(
i,
temporaryPosition,
scale,
temporaryColor,
individual.skin,
individual.badgeColor,
individual.yaw
);
}
for (let i = 0; i < trial.n; i++) {
const child = trial.children[i];
temporaryPosition.copy(child.outer);
temporaryPosition.y += childProgress > 0
? Math.sin(now * 0.002 + i * 0.7) * 0.012
: 0;
writePerson(
trial.n + i,
temporaryPosition,
easedChild,
child.color,
child.skin,
child.badgeColor,
child.yaw
);
}
for (const mesh of partMeshes) {
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
}
lastSlots = slots;
}
function updatePhase(now) {
if (phase === "select") {
const duration = SELECT_DURATION / getSettings().speed;
if (now - phaseStart >= duration) {
phase = "reproduce";
phaseStart = now;
updateStageUI();
}
} else if (phase === "reproduce") {
const duration = REPRODUCE_DURATION / getSettings().speed;
if (now - phaseStart >= duration) {
phase = "complete";
phaseStart = now;
updateStageUI();
if (autoRepeat) {
autoTimer = setTimeout(
startAnimatedTrial,
380 / getSettings().speed
);
}
}
}
}
/* --------------------------------------------------------------------------
Trial chart
-------------------------------------------------------------------------- */
let chartWidth = 0;
let chartHeight = 0;
function resizeChart() {
const rect = chart.getBoundingClientRect();
if (!rect.width || !rect.height) return;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
chartWidth = rect.width;
chartHeight = rect.height;
chart.width = Math.round(rect.width * dpr);
chart.height = Math.round(rect.height * dpr);
chartContext.setTransform(dpr, 0, 0, dpr, 0, 0);
}
function chartX(index, plot) {
if (history.length <= 1) return plot.left + plot.width / 2;
return plot.left + (index / (history.length - 1)) * plot.width;
}
function drawChart() {
if (!chartWidth || !chartHeight) resizeChart();
if (!chartWidth || !chartHeight) return;
const ctx = chartContext;
ctx.clearRect(0, 0, chartWidth, chartHeight);
const plot = {
left: 35,
top: 12,
right: chartWidth - 10,
bottom: chartHeight - 24
};
plot.width = plot.right - plot.left;
plot.height = plot.bottom - plot.top;
const maxY = 1.5;
const yFor = value => plot.bottom - (clamp(value, 0, maxY) / maxY) * plot.height;
ctx.font = "9px ui-sans-serif, system-ui";
ctx.textBaseline = "middle";
for (const tick of [0, 0.25, 0.5, 0.75, 1, 1.25, 1.5]) {
const y = yFor(tick);
ctx.strokeStyle = tick === 1
? "rgba(220,240,240,0.25)"
: "rgba(170,210,220,0.09)";
ctx.lineWidth = tick === 1 ? 1.2 : 1;
ctx.setLineDash(tick === 1 ? [4, 4] : []);
ctx.beginPath();
ctx.moveTo(plot.left, y);
ctx.lineTo(plot.right, y);
ctx.stroke();
ctx.setLineDash([]);
ctx.fillStyle = tick === 1 ? "#b8d1d5" : "#6f8b91";
ctx.textAlign = "right";
ctx.fillText(`${Math.round(tick * 100)}%`, plot.left - 7, y);
}
if (!history.length) {
ctx.fillStyle = "#708d93";
ctx.textAlign = "center";
ctx.fillText(
"Run trials to reveal sampling variation",
plot.left + plot.width / 2,
plot.top + plot.height / 2
);
return;
}
function drawSeries(key, color) {
ctx.strokeStyle = color;
ctx.fillStyle = color;
ctx.lineWidth = 1.8;
ctx.beginPath();
history.forEach((item, index) => {
const x = chartX(index, plot);
const y = yFor(item[key]);
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.stroke();
history.forEach((item, index) => {
const x = chartX(index, plot);
const y = yFor(item[key]);
ctx.beginPath();
ctx.arc(x, y, 2.5, 0, Math.PI * 2);
ctx.fill();
});
}
drawSeries("richnessRetained", "#55e5ff");
drawSeries("varianceRetained", "#a78bfa");
drawSeries("heterozygosityRetained", "#ffca68");
ctx.fillStyle = "#6f8b91";
ctx.textAlign = "left";
ctx.fillText("1", plot.left, chartHeight - 9);
ctx.textAlign = "right";
ctx.fillText(String(history.length), plot.right, chartHeight - 9);
}
chart.addEventListener("pointermove", event => {
if (!history.length || !chartWidth) return;
const rect = chart.getBoundingClientRect();
const x = event.clientX - rect.left;
const plotLeft = 35;
const plotWidth = chartWidth - 45;
let closestIndex = 0;
let closestDistance = Infinity;
history.forEach((_, index) => {
const pointX = history.length === 1
? plotLeft + plotWidth / 2
: plotLeft + (index / (history.length - 1)) * plotWidth;
const distance = Math.abs(x - pointX);
if (distance < closestDistance) {
closestDistance = distance;
closestIndex = index;
}
});
if (closestDistance > 28) {
chartTip.style.display = "none";
return;
}
const item = history[closestIndex];
chartTip.innerHTML = `
<b>Trial ${item.trial}</b> · k = ${item.k}/${item.n}<br>
Allelic richness: ${percent(item.richnessRetained)}<br>
Trait variance: ${percent(item.varianceRetained)}<br>
Heterozygosity: ${percent(item.heterozygosityRetained)}<br>
Descendant expected H: ${percent(item.descendantExpectedHeterozygosity)}
`;
const cardRect = chart.parentElement.getBoundingClientRect();
const pointX = history.length === 1
? plotLeft + plotWidth / 2
: plotLeft + (closestIndex / (history.length - 1)) * plotWidth;
chartTip.style.display = "block";
chartTip.style.left = `${clamp(pointX - 88, 4, cardRect.width - 188)}px`;
chartTip.style.top = `${clamp(event.clientY - cardRect.top - 92, 4, cardRect.height - 125)}px`;
});
chart.addEventListener("pointerleave", () => {
chartTip.style.display = "none";
});
/* --------------------------------------------------------------------------
Controls
-------------------------------------------------------------------------- */
function updateControlLabels() {
const population = Number(populationInput.value);
$("populationOut").textContent = population;
$("lociOut").textContent = lociInput.value;
$("randomMinOut").textContent = randomMinInput.value;
$("randomMaxOut").textContent = randomMaxInput.value;
$("fixedOut").textContent = fixedCountInput.value;
$("speedOut").textContent = `${Number(speedInput.value).toFixed(1)}×`;
$("randomRange").classList.toggle("hidden", !randomCountInput.checked);
$("fixedRange").classList.toggle("hidden", randomCountInput.checked);
populationInput.max = MAX_POPULATION;
randomMinInput.max = population;
randomMaxInput.max = population;
fixedCountInput.max = population;
if (Number(randomMinInput.value) > Number(randomMaxInput.value)) {
randomMaxInput.value = randomMinInput.value;
}
if (traitModeInput.value === "first") {
$("legendTitle").textContent = "First locus allele";
} else if (traitModeInput.value === "last") {
$("legendTitle").textContent = "Last locus allele";
} else {
$("legendTitle").textContent = "Polygenic score";
}
}
[
populationInput,
lociInput,
randomMinInput,
randomMaxInput,
fixedCountInput,
speedInput
].forEach(input => {
input.addEventListener("input", updateControlLabels);
});
randomCountInput.addEventListener("change", updateControlLabels);
[
populationInput,
lociInput,
randomMinInput,
randomMaxInput,
fixedCountInput
].forEach(input => {
input.addEventListener("change", () => {
updateControlLabels();
resetExperiment(false);
});
});
traitModeInput.addEventListener("change", () => {
updateControlLabels();
refreshColors(currentTrial);
});
/* --------------------------------------------------------------------------
Resize and main loop
-------------------------------------------------------------------------- */
function resizeScene() {
const width = sceneWrap.clientWidth;
const height = sceneWrap.clientHeight;
if (!width || !height) return;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(() => {
resizeScene();
resizeChart();
drawChart();
});
resizeObserver.observe(sceneWrap);
resizeObserver.observe(chart.parentElement);
function animate(now) {
requestAnimationFrame(animate);
updatePhase(now);
updateInstances(now);
updateCamera();
renderer.render(scene, camera);
}
updateControlLabels();
resetExperiment(false);
resizeScene();
resizeChart();
drawChart();
requestAnimationFrame(animate);
</script>
</body>
</html>
```