Prompt specification
Build or customize the Three.js 3D scene "Repeated drift trial 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: Repeated drift trial explorer
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/repeated-drift-trial-explorer-x0916
Scene Description Prompt:
Compare repeated neutral genetic-drift trials in a voxel toy model, varying population size and random seed. Three.js from cdnjs, standalone HTML.
Working Three.js Starter (repeated-drift-trial-explorer-x0916):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Genetic Drift Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #070a12;
--panel: #101521;
--panel-2: #151b29;
--line: #252d3e;
--text: #edf2ff;
--muted: #929db4;
--a: #54d7ff;
--b: #ff7b68;
--accent: #9b87ff;
--good: #66e3b4;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-width: 320px;
min-height: 100vh;
background:
radial-gradient(circle at 12% 0%, rgba(84, 215, 255, 0.09), transparent 28rem),
radial-gradient(circle at 85% 15%, rgba(155, 135, 255, 0.09), transparent 30rem),
var(--bg);
color: var(--text);
font: 14px/1.45 Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button,
input,
select {
font: inherit;
}
button,
select,
input[type="number"],
input[type="text"] {
color: var(--text);
background: #0c111c;
border: 1px solid var(--line);
border-radius: 9px;
}
button {
cursor: pointer;
transition: border-color 150ms ease, background 150ms ease, transform 150ms ease;
}
button:hover:not(:disabled) {
border-color: #4d5870;
background: #182033;
}
button:active:not(:disabled) {
transform: translateY(1px);
}
button:disabled {
cursor: wait;
opacity: 0.65;
}
input:focus-visible,
select:focus-visible,
button:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.app {
width: min(1540px, 100%);
margin: 0 auto;
padding: 22px;
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
margin-bottom: 18px;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
}
.brand-mark {
display: grid;
grid-template-columns: repeat(3, 8px);
grid-template-rows: repeat(3, 8px);
gap: 3px;
padding: 10px;
border: 1px solid #2b354b;
border-radius: 13px;
background: #101725;
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.25);
}
.brand-mark i {
display: block;
width: 8px;
height: 8px;
border-radius: 2px;
background: #253047;
}
.brand-mark i:nth-child(1),
.brand-mark i:nth-child(5),
.brand-mark i:nth-child(8) {
background: var(--a);
box-shadow: 0 0 10px rgba(84, 215, 255, 0.45);
}
.brand-mark i:nth-child(3),
.brand-mark i:nth-child(6) {
background: var(--b);
}
h1,
h2,
h3,
p {
margin: 0;
}
h1 {
font-size: clamp(20px, 3vw, 28px);
letter-spacing: -0.035em;
}
.brand p {
margin-top: 2px;
color: var(--muted);
font-size: 13px;
}
.top-actions {
display: flex;
align-items: center;
gap: 9px;
}
.top-actions button {
padding: 9px 12px;
}
.pill {
padding: 7px 10px;
border: 1px solid #2a3448;
border-radius: 999px;
color: #bac5db;
background: rgba(18, 24, 37, 0.8);
white-space: nowrap;
font-size: 12px;
}
.layout {
display: grid;
grid-template-columns: minmax(0, 1.45fr) minmax(370px, 0.8fr);
gap: 18px;
align-items: start;
}
.card {
overflow: hidden;
border: 1px solid var(--line);
border-radius: 16px;
background: rgba(16, 21, 33, 0.94);
box-shadow: 0 22px 60px rgba(0, 0, 0, 0.18);
}
.section-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
min-height: 58px;
padding: 12px 15px;
border-bottom: 1px solid var(--line);
}
.section-head h2 {
font-size: 14px;
font-weight: 650;
letter-spacing: -0.01em;
}
.section-head p {
margin-top: 2px;
color: var(--muted);
font-size: 11px;
}
.stage-card {
min-width: 0;
}
.viewport-wrap {
position: relative;
}
#viewport {
position: relative;
height: clamp(460px, 64vh, 720px);
overflow: hidden;
background: #090d18;
touch-action: none;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
}
#viewport canvas:active {
cursor: grabbing;
}
.hud {
position: absolute;
z-index: 2;
pointer-events: none;
border: 1px solid rgba(75, 90, 120, 0.48);
border-radius: 12px;
background: rgba(8, 12, 22, 0.72);
backdrop-filter: blur(12px);
}
.hud-left {
top: 14px;
left: 14px;
width: 205px;
padding: 13px;
}
.hud-right {
top: 14px;
right: 14px;
min-width: 150px;
padding: 12px 14px;
}
.eyebrow {
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
}
#pAValue {
margin: 3px 0 8px;
font-size: 29px;
font-weight: 720;
letter-spacing: -0.045em;
}
.frequency-bar {
height: 6px;
overflow: hidden;
border-radius: 999px;
background: var(--b);
}
.frequency-bar i {
display: block;
width: 50%;
height: 100%;
background: var(--a);
box-shadow: 0 0 10px rgba(84, 215, 255, 0.35);
}
.count-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 10px;
}
.count-grid div {
display: flex;
align-items: center;
justify-content: space-between;
color: var(--muted);
font-size: 11px;
}
.count-grid b {
color: var(--text);
font-size: 13px;
}
.dot {
display: inline-block;
width: 7px;
height: 7px;
margin-right: 5px;
border-radius: 50%;
vertical-align: 1px;
}
.dot.a {
background: var(--a);
box-shadow: 0 0 8px rgba(84, 215, 255, 0.55);
}
.dot.b {
background: var(--b);
}
.hud-value {
margin: 3px 0 8px;
font-size: 20px;
font-weight: 700;
}
.status-line {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
color: var(--muted);
font-size: 11px;
}
#populationState {
color: var(--text);
font-weight: 650;
}
.viewport-footer {
position: absolute;
z-index: 2;
right: 14px;
bottom: 13px;
left: 14px;
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 12px;
pointer-events: none;
}
.legend {
display: flex;
gap: 12px;
padding: 8px 10px;
border: 1px solid rgba(75, 90, 120, 0.4);
border-radius: 9px;
background: rgba(8, 12, 22, 0.7);
color: #c8d0e1;
font-size: 11px;
backdrop-filter: blur(10px);
}
.camera-tip {
padding: 7px 9px;
border-radius: 8px;
background: rgba(8, 12, 22, 0.65);
color: #7f8ba3;
font-size: 10px;
}
.transport {
padding: 12px 14px 14px;
border-top: 1px solid var(--line);
background: #0e131e;
}
.transport-row,
.trial-row {
display: flex;
align-items: center;
gap: 8px;
}
.trial-row {
justify-content: space-between;
margin-top: 10px;
padding-top: 10px;
border-top: 1px solid #202839;
}
.transport button {
min-width: 35px;
height: 34px;
padding: 0 10px;
}
.transport #playButton {
min-width: 76px;
border-color: #50488a;
background: rgba(155, 135, 255, 0.13);
color: #d8d1ff;
}
#generationSlider {
min-width: 80px;
flex: 1;
accent-color: var(--accent);
}
#generationCompact {
min-width: 64px;
color: var(--muted);
text-align: right;
font-size: 11px;
}
#speedSelect {
height: 34px;
padding: 0 8px;
}
.trial-nav {
display: flex;
align-items: center;
gap: 8px;
}
.trial-nav button {
width: 31px;
height: 31px;
padding: 0;
}
#trialLabel {
min-width: 104px;
color: #c7d0e1;
text-align: center;
font-size: 12px;
}
#liveSeed {
color: var(--accent);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.sidebar {
display: grid;
gap: 18px;
min-width: 0;
}
.controls-body {
display: grid;
gap: 16px;
padding: 15px;
}
.field {
display: grid;
gap: 7px;
}
.field-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.field label,
.field-title {
color: #c8d1e2;
font-size: 12px;
font-weight: 620;
}
.field output {
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
}
.field input[type="range"] {
width: 100%;
margin: 0;
accent-color: var(--accent);
}
.field input[type="number"],
.field input[type="text"],
.field select {
width: 100%;
height: 38px;
padding: 0 10px;
}
.field input[type="number"] {
min-width: 0;
}
.help {
color: #7f8ba3;
font-size: 10px;
}
.two-fields {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 11px;
}
.seed-input {
display: grid;
grid-template-columns: 1fr 38px;
gap: 7px;
}
.seed-input button {
font-size: 17px;
}
.run-button {
width: 100%;
min-height: 42px;
border-color: #6759ae;
background: linear-gradient(135deg, rgba(155, 135, 255, 0.22), rgba(84, 215, 255, 0.1));
color: #f1efff;
font-weight: 680;
}
.run-button:hover:not(:disabled) {
border-color: #8d7ee4;
background: linear-gradient(135deg, rgba(155, 135, 255, 0.3), rgba(84, 215, 255, 0.14));
}
.results-body {
padding: 14px 15px 16px;
}
.summary-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin-bottom: 14px;
}
.summary-card {
min-width: 0;
padding: 10px;
border: 1px solid #252e41;
border-radius: 10px;
background: #0c111b;
}
.summary-card span {
display: block;
overflow: hidden;
color: var(--muted);
font-size: 9px;
text-overflow: ellipsis;
text-transform: uppercase;
white-space: nowrap;
}
.summary-card b {
display: block;
margin-top: 3px;
font-size: 19px;
letter-spacing: -0.03em;
}
.summary-card.fixed b {
color: var(--a);
}
.summary-card.lost b {
color: var(--b);
}
.summary-card.mixed b {
color: #c1c8d6;
}
.chart-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin: 4px 0 5px;
}
.chart-title h3 {
font-size: 12px;
}
#snapshotInfo {
color: var(--muted);
font-size: 9px;
text-align: right;
}
#snapshotInfo.dirty {
color: #ffd081;
}
#trajectoryChart {
display: block;
width: 100%;
height: 230px;
}
.chart-legend {
display: flex;
flex-wrap: wrap;
gap: 10px 14px;
margin: 3px 0 16px;
color: var(--muted);
font-size: 10px;
}
.chart-legend span {
display: flex;
align-items: center;
gap: 5px;
}
.line-swatch {
width: 17px;
height: 2px;
background: #f5f7ff;
}
.line-swatch.mean {
background: var(--accent);
}
.line-swatch.p0 {
height: 0;
border-top: 1px dashed #8c98ae;
background: none;
}
.band-swatch {
width: 17px;
height: 8px;
border-radius: 2px;
background: rgba(155, 135, 255, 0.2);
}
.comparison-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin: 4px 0 9px;
}
.comparison-head h3 {
font-size: 12px;
}
.comparison-head span {
color: var(--muted);
font-size: 9px;
}
.table-wrap {
overflow-x: auto;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 10px;
}
th,
td {
padding: 9px 5px;
border-bottom: 1px solid #222a3a;
text-align: right;
white-space: nowrap;
}
th {
color: #7f8ba3;
font-size: 9px;
font-weight: 600;
text-transform: uppercase;
}
th:first-child,
td:first-child {
text-align: left;
}
td strong {
font-size: 11px;
}
.outcome-bar {
display: flex;
width: 116px;
height: 6px;
overflow: hidden;
margin: 0 0 4px auto;
border-radius: 999px;
background: #242c3d;
}
.outcome-bar i {
display: block;
height: 100%;
}
.outcome-bar .fixed {
background: var(--a);
}
.outcome-bar .mixed {
background: #697386;
}
.outcome-bar .lost {
background: var(--b);
}
.outcome-labels {
color: var(--muted);
font-size: 8px;
}
.method {
margin-top: 18px;
padding: 15px 18px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(14, 19, 30, 0.72);
color: var(--muted);
font-size: 11px;
}
.method strong {
color: #c9d2e2;
}
@media (max-width: 1050px) {
.layout {
grid-template-columns: 1fr;
}
.sidebar {
grid-template-columns: minmax(280px, 0.8fr) minmax(380px, 1.2fr);
align-items: start;
}
}
@media (max-width: 720px) {
.app {
padding: 12px;
}
.topbar {
align-items: flex-start;
}
.top-actions .pill {
display: none;
}
.sidebar {
grid-template-columns: 1fr;
}
#viewport {
height: 500px;
}
.hud-left {
width: 174px;
}
.hud-right {
top: auto;
right: 14px;
bottom: 58px;
}
.camera-tip {
display: none;
}
.transport-row {
flex-wrap: wrap;
}
#generationSlider {
order: 8;
flex-basis: calc(100% - 10px);
}
}
</style>
</head>
<body>
<div class="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<i></i><i></i><i></i>
<i></i><i></i><i></i>
<i></i><i></i><i></i>
</div>
<div>
<h1>Genetic Drift Lab</h1>
<p>Repeated neutral Wright–Fisher trials in voxel space</p>
</div>
</div>
<div class="top-actions">
<span class="pill">Haploid · 2 neutral alleles · no selection</span>
<button id="resetCameraButton" type="button">Reset view</button>
</div>
</header>
<main class="layout">
<section class="card stage-card">
<div class="section-head">
<div>
<h2>Live voxel population</h2>
<p>Each cube represents one individual carrying allele A or B.</p>
</div>
<span class="pill" id="stagePopulationBadge">N = 32</span>
</div>
<div class="viewport-wrap">
<div id="viewport" aria-label="Interactive 3D voxel population"></div>
<div class="hud hud-left">
<div class="eyebrow">Allele A frequency</div>
<div id="pAValue">50.0%</div>
<div class="frequency-bar"><i id="pABar"></i></div>
<div class="count-grid">
<div><span><i class="dot a"></i>A</span><b id="aCount">16</b></div>
<div><span><i class="dot b"></i>B</span><b id="bCount">16</b></div>
</div>
</div>
<div class="hud hud-right">
<div class="eyebrow">Generation</div>
<div class="hud-value" id="generationValue">0 / 120</div>
<div class="status-line">
<span>State</span>
<span id="populationState">Segregating</span>
</div>
</div>
<div class="viewport-footer">
<div class="legend">
<span><i class="dot a"></i>Allele A</span>
<span><i class="dot b"></i>Allele B</span>
</div>
<div class="camera-tip">Drag to orbit · wheel to zoom · Shift/right-drag to pan</div>
</div>
</div>
<div class="transport">
<div class="transport-row">
<button id="resetGenerationButton" type="button" title="Restart generation">↺</button>
<button id="previousGenerationButton" type="button" title="Previous generation">−</button>
<button id="playButton" type="button">▶ Play</button>
<button id="nextGenerationButton" type="button" title="Next generation">+</button>
<input
id="generationSlider"
type="range"
min="0"
max="120"
value="0"
aria-label="Current generation"
>
<span id="generationCompact">0 / 120</span>
<select id="speedSelect" aria-label="Playback speed">
<option value="1">1 gen/s</option>
<option value="4">4 gen/s</option>
<option value="8" selected>8 gen/s</option>
<option value="16">16 gen/s</option>
<option value="30">30 gen/s</option>
</select>
</div>
<div class="trial-row">
<div class="trial-nav">
<button id="previousTrialButton" type="button" title="Previous trial">‹</button>
<span id="trialLabel">Trial 1 / 50</span>
<button id="nextTrialButton" type="button" title="Next trial">›</button>
</div>
<div>Seed <span id="liveSeed">—</span></div>
</div>
</div>
</section>
<aside class="sidebar">
<section class="card">
<div class="section-head">
<div>
<h2>Experiment controls</h2>
<p>Compare many deterministic seeds at several population sizes.</p>
</div>
</div>
<div class="controls-body">
<div class="two-fields">
<div class="field">
<div class="field-row">
<label for="populationSelect">Live population</label>
</div>
<select id="populationSelect">
<option value="8">8 individuals</option>
<option value="16">16 individuals</option>
<option value="32" selected>32 individuals</option>
<option value="64">64 individuals</option>
<option value="128">128 individuals</option>
<option value="256">256 individuals</option>
</select>
</div>
<div class="field">
<div class="field-row">
<label for="repetitions">Trials per size</label>
<output id="repetitionsValue">50</output>
</div>
<input id="repetitions" type="range" min="10" max="100" step="10" value="50">
</div>
</div>
<div class="field">
<div class="field-row">
<label for="initialFrequency">Initial A frequency</label>
<output id="initialFrequencyValue">0.50</output>
</div>
<input id="initialFrequency" type="range" min="0.05" max="0.95" step="0.05" value="0.5">
</div>
<div class="field">
<div class="field-row">
<label for="generationCount">Generations</label>
<output id="generationCountValue">120</output>
</div>
<input id="generationCount" type="range" min="20" max="300" step="10" value="120">
</div>
<div class="two-fields">
<div class="field">
<label for="baseSeed">Base seed</label>
<div class="seed-input">
<input id="baseSeed" type="number" min="0" max="4294967295" value="2025">
<button id="shuffleSeedButton" type="button" title="Choose a new base seed">⚄</button>
</div>
</div>
<div class="field">
<label for="populationLadder">Population sizes</label>
<input id="populationLadder" type="text" value="16, 32, 64, 128">
<div class="help">Comma-separated sizes compared in the batch.</div>
</div>
</div>
<button id="runBatchButton" class="run-button" type="button">
Run comparison
</button>
</div>
</section>
<section class="card">
<div class="section-head">
<div>
<h2>Monte Carlo comparison</h2>
<p>Outcome rates and drift magnitude at the selected horizon.</p>
</div>
</div>
<div class="results-body">
<div class="summary-grid">
<div class="summary-card fixed">
<span>A fixed</span>
<b id="fixedRate">—</b>
</div>
<div class="summary-card lost">
<span>A lost</span>
<b id="lostRate">—</b>
</div>
<div class="summary-card mixed">
<span>Still mixed</span>
<b id="mixedRate">—</b>
</div>
</div>
<div class="chart-title">
<h3>Allele-frequency trajectories</h3>
<span id="snapshotInfo">Preparing experiment…</span>
</div>
<canvas id="trajectoryChart" aria-label="Allele A frequency trajectory chart"></canvas>
<div class="chart-legend">
<span><i class="line-swatch"></i>Selected trial</span>
<span><i class="line-swatch mean"></i>Batch mean</span>
<span><i class="band-swatch"></i>10th–90th percentile</span>
<span><i class="line-swatch p0"></i>Initial frequency</span>
</div>
<div class="comparison-head">
<h3>Population-size comparison</h3>
<span>Outcome at final generation</span>
</div>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>N</th>
<th>Outcome</th>
<th>Mean |Δp|</th>
<th>Median absorption</th>
</tr>
</thead>
<tbody id="comparisonBody">
<tr><td colspan="4">No results yet.</td></tr>
</tbody>
</table>
</div>
</div>
</section>
</aside>
</main>
<footer class="method">
<strong>Model:</strong>
Every generation is a haploid Wright–Fisher bottleneck: each of N offspring
independently copies one uniformly chosen allele from the previous generation
of N individuals. There is no selection, mutation, or migration. Fixation and
loss therefore occur solely through random sampling. Trial seeds are derived
deterministically from the base seed, population size, and trial index.
</footer>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Application state
// -------------------------------------------------------------------------
const $ = (id) => document.getElementById(id);
const elements = {
viewport: $("viewport"),
populationSelect: $("populationSelect"),
repetitions: $("repetitions"),
repetitionsValue: $("repetitionsValue"),
initialFrequency: $("initialFrequency"),
initialFrequencyValue: $("initialFrequencyValue"),
generationCount: $("generationCount"),
generationCountValue: $("generationCountValue"),
baseSeed: $("baseSeed"),
shuffleSeedButton: $("shuffleSeedButton"),
populationLadder: $("populationLadder"),
runBatchButton: $("runBatchButton"),
resetCameraButton: $("resetCameraButton"),
pAValue: $("pAValue"),
pABar: $("pABar"),
aCount: $("aCount"),
bCount: $("bCount"),
generationValue: $("generationValue"),
populationState: $("populationState"),
stagePopulationBadge: $("stagePopulationBadge"),
generationSlider: $("generationSlider"),
generationCompact: $("generationCompact"),
speedSelect: $("speedSelect"),
resetGenerationButton: $("resetGenerationButton"),
previousGenerationButton: $("previousGenerationButton"),
playButton: $("playButton"),
nextGenerationButton: $("nextGenerationButton"),
previousTrialButton: $("previousTrialButton"),
nextTrialButton: $("nextTrialButton"),
trialLabel: $("trialLabel"),
liveSeed: $("liveSeed"),
fixedRate: $("fixedRate"),
lostRate: $("lostRate"),
mixedRate: $("mixedRate"),
trajectoryChart: $("trajectoryChart"),
snapshotInfo: $("snapshotInfo"),
comparisonBody: $("comparisonBody")
};
const state = {
population: 32,
repetitions: 50,
initialFrequency: 0.5,
generations: 120,
baseSeed: 2025,
populationLadder: [16, 32, 64, 128],
trialIndex: 0,
generation: 0,
playing: false,
speed: 8,
liveTrial: null,
batch: new Map(),
dirty: false
};
const ALLELE_A = new THREE.Color(0x54d7ff);
const ALLELE_B = new THREE.Color(0xff7b68);
// -------------------------------------------------------------------------
// Seeded random number generator and simulation
// -------------------------------------------------------------------------
function mulberry32(seed) {
let value = seed >>> 0;
return function random() {
value |= 0;
value = (value + 0x6d2b79f5) | 0;
let t = Math.imul(value ^ (value >>> 15), 1 | value);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function deriveSeed(baseSeed, population, trialIndex) {
let value = (
(baseSeed >>> 0) ^
Math.imul(population, 0x9e3779b1) ^
Math.imul(trialIndex + 1, 0x85ebca6b)
) >>> 0;
value ^= value >>> 16;
value = Math.imul(value, 0x7feb352d);
value ^= value >>> 13;
value = Math.imul(value, 0xc2b2ae35);
value ^= value >>> 16;
return value >>> 0;
}
function simulateTrial({
population,
generations,
initialFrequency,
seed,
captureSnapshots = false
}) {
const random = mulberry32(seed);
let alleles = new Uint8Array(population);
let countA = 0;
for (let i = 0; i < population; i++) {
alleles[i] = random() < initialFrequency ? 1 : 0;
countA += alleles[i];
}
const frequencies = new Float64Array(generations + 1);
const snapshots = captureSnapshots ? new Array(generations + 1) : null;
frequencies[0] = countA / population;
if (snapshots) snapshots[0] = alleles.slice();
let absorbedAt = -1;
let absorbedType = null;
for (let generation = 1; generation <= generations; generation++) {
if (absorbedAt === -1) {
const nextAlleles = new Uint8Array(population);
let nextCountA = 0;
for (let i = 0; i < population; i++) {
const parent = Math.floor(random() * population);
nextAlleles[i] = alleles[parent];
nextCountA += nextAlleles[i];
}
alleles = nextAlleles;
countA = nextCountA;
if (countA === 0 || countA === population) {
absorbedAt = generation;
absorbedType = countA === population ? "fixed" : "lost";
}
}
frequencies[generation] = countA / population;
if (snapshots) snapshots[generation] = alleles.slice();
}
return {
seed,
frequencies,
snapshots,
absorbedAt,
absorbedType,
finalFrequency: frequencies[generations]
};
}
function quantile(sortedValues, q) {
if (!sortedValues.length) return 0;
const index = (sortedValues.length - 1) * q;
const lower = Math.floor(index);
const upper = Math.ceil(index);
const fraction = index - lower;
return sortedValues[lower] * (1 - fraction) + sortedValues[upper] * fraction;
}
function median(values) {
if (!values.length) return null;
const sorted = [...values].sort((a, b) => a - b);
const middle = Math.floor(sorted.length / 2);
return sorted.length % 2
? sorted[middle]
: (sorted[middle - 1] + sorted[middle]) / 2;
}
function parsePopulationLadder() {
const parsed = elements.populationLadder.value
.split(",")
.map((value) => Number(value.trim()))
.filter((value) => Number.isInteger(value) && value >= 4 && value <= 512);
const sizes = [...new Set([...parsed, state.population])].sort((a, b) => a - b);
return sizes;
}
function markDirty() {
state.dirty = true;
elements.snapshotInfo.textContent = "Parameters changed · run to refresh";
elements.snapshotInfo.classList.add("dirty");
}
function markClean() {
state.dirty = false;
elements.snapshotInfo.classList.remove("dirty");
const sizeCount = state.batch.size;
elements.snapshotInfo.textContent =
`${state.repetitions} trials × ${sizeCount} sizes · base seed ${state.baseSeed}`;
}
// -------------------------------------------------------------------------
// Three.js voxel scene
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x090d18);
scene.fog = new THREE.Fog(0x090d18, 13, 30);
const camera = new THREE.PerspectiveCamera(
42,
1,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
elements.viewport.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0x9bc9ff, 0x171221, 1.55);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.1);
keyLight.position.set(6, 9, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 35;
keyLight.shadow.camera.left = -10;
keyLight.shadow.camera.right = 10;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x6655ff, 28, 24, 2);
rimLight.position.set(-6, 3, -5);
scene.add(rimLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(30, 30),
new THREE.MeshStandardMaterial({
color: 0x0c111d,
roughness: 0.9,
metalness: 0.08
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -1.18;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(24, 48, 0x29354c, 0x172033);
grid.position.y = -1.165;
grid.material.transparent = true;
grid.material.opacity = 0.48;
scene.add(grid);
const voxelRoot = new THREE.Group();
scene.add(voxelRoot);
const voxelGeometry = new THREE.BoxGeometry(0.78, 0.78, 0.78);
const voxelMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.38,
metalness: 0.08
});
let voxelMesh = null;
let currentDimensions = { x: 1, y: 1, z: 1 };
function findVoxelDimensions(population) {
let best = null;
let bestScore = Infinity;
for (let x = 1; x <= 12; x++) {
for (let y = x; y <= 12; y++) {
for (let z = y; z <= 12; z++) {
const volume = x * y * z;
if (volume < population) continue;
const fillPenalty = (volume / population - 1) * 0.5;
const aspectPenalty = Math.abs(y - x) * 0.025;
const score = z + fillPenalty + aspectPenalty;
if (score < bestScore) {
bestScore = score;
best = { x, y, z };
}
}
}
}
return best || { x: population, y: 1, z: 1 };
}
function buildVoxelMesh(population) {
if (voxelMesh) {
voxelRoot.remove(voxelMesh);
voxelMesh.dispose?.();
}
const dimensions = findVoxelDimensions(population);
currentDimensions = dimensions;
voxelMesh = new THREE.InstancedMesh(
voxelGeometry,
voxelMaterial,
population
);
voxelMesh.instanceMatrix.setUsage(THREE.StaticDrawUsage);
voxelMesh.castShadow = true;
voxelMesh.receiveShadow = true;
const matrix = new THREE.Matrix4();
const planeSize = dimensions.x * dimensions.y;
for (let i = 0; i < population; i++) {
const ix = i % dimensions.x;
const iy = Math.floor(i / dimensions.x) % dimensions.y;
const iz = Math.floor(i / planeSize);
const x = ix - (dimensions.x - 1) / 2;
const y = iy - (dimensions.y - 1) / 2;
const z = iz - (dimensions.z - 1) / 2;
matrix.makeTranslation(x, y, z);
voxelMesh.setMatrixAt(i, matrix);
voxelMesh.setColorAt(i, ALLELE_A);
}
voxelMesh.instanceMatrix.needsUpdate = true;
voxelMesh.instanceColor.needsUpdate = true;
voxelRoot.add(voxelMesh);
}
function updateVoxelColors(alleles) {
if (!voxelMesh || !alleles) return;
for (let i = 0; i < alleles.length; i++) {
voxelMesh.setColorAt(i, alleles[i] ? ALLELE_A : ALLELE_B);
}
voxelMesh.instanceColor.needsUpdate = true;
}
// -------------------------------------------------------------------------
// Custom camera controls: orbit, pan, and zoom
// -------------------------------------------------------------------------
const cameraTarget = new THREE.Vector3();
let cameraTheta = 0.72;
let cameraPhi = 1.07;
let cameraRadius = 9;
let dragging = false;
let dragMode = "orbit";
let lastPointerX = 0;
let lastPointerY = 0;
function updateCamera() {
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x + cameraRadius * sinPhi * Math.sin(cameraTheta),
cameraTarget.y + cameraRadius * Math.cos(cameraPhi),
cameraTarget.z + cameraRadius * sinPhi * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
const largestDimension = Math.max(
currentDimensions.x,
currentDimensions.y,
currentDimensions.z
);
cameraTheta = 0.72;
cameraPhi = 1.07;
cameraTarget.set(0, 0, 0);
cameraRadius = THREE.MathUtils.clamp(largestDimension * 1.65 + 2.5, 5.5, 16);
updateCamera();
}
elements.viewport.addEventListener("pointerdown", (event) => {
dragging = true;
dragMode = event.button === 2 || event.shiftKey ? "pan" : "orbit";
lastPointerX = event.clientX;
lastPointerY = event.clientY;
elements.viewport.setPointerCapture(event.pointerId);
});
elements.viewport.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
if (dragMode === "orbit") {
cameraTheta -= dx * 0.008;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi - dy * 0.008,
0.22,
Math.PI - 0.22
);
} else {
const right = new THREE.Vector3(1, 0, 0).applyQuaternion(camera.quaternion);
const up = new THREE.Vector3(0, 1, 0).applyQuaternion(camera.quaternion);
const panScale = cameraRadius * 0.0015;
cameraTarget.addScaledVector(right, -dx * panScale);
cameraTarget.addScaledVector(up, dy * panScale);
}
updateCamera();
});
function stopDragging(event) {
dragging = false;
if (event?.pointerId !== undefined) {
if (elements.viewport.hasPointerCapture(event.pointerId)) {
elements.viewport.releasePointerCapture(event.pointerId);
}
}
}
elements.viewport.addEventListener("pointerup", stopDragging);
elements.viewport.addEventListener("pointercancel", stopDragging);
elements.viewport.addEventListener("contextmenu", (event) => event.preventDefault());
elements.viewport.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
3.5,
24
);
updateCamera();
},
{ passive: false }
);
elements.resetCameraButton.addEventListener("click", resetCamera);
const resizeObserver = new ResizeObserver(() => {
const width = elements.viewport.clientWidth;
const height = elements.viewport.clientHeight;
camera.aspect = width / Math.max(height, 1);
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
});
resizeObserver.observe(elements.viewport);
// -------------------------------------------------------------------------
// Live trial and playback
// -------------------------------------------------------------------------
function loadLiveTrial(resetGeneration = true) {
state.trialIndex = Math.max(
0,
Math.min(state.trialIndex, state.repetitions - 1)
);
const seed = deriveSeed(
state.baseSeed,
state.population,
state.trialIndex
);
state.liveTrial = simulateTrial({
population: state.population,
generations: state.generations,
initialFrequency: state.initialFrequency,
seed,
captureSnapshots: true
});
if (resetGeneration) state.generation = 0;
buildVoxelMesh(state.population);
resetCamera();
renderLiveTrial();
}
function renderLiveTrial() {
if (!state.liveTrial) return;
const snapshot = state.liveTrial.snapshots[state.generation];
let countA = 0;
for (let i = 0; i < snapshot.length; i++) countA += snapshot[i];
const countB = snapshot.length - countA;
const frequency = countA / snapshot.length;
const absorbed = countA === 0 || countB === 0;
updateVoxelColors(snapshot);
elements.pAValue.textContent = `${(frequency * 100).toFixed(1)}%`;
elements.pABar.style.width = `${frequency * 100}%`;
elements.aCount.textContent = countA;
elements.bCount.textContent = countB;
elements.generationValue.textContent = `${state.generation} / ${state.generations}`;
elements.generationCompact.textContent = `${state.generation} / ${state.generations}`;
elements.generationSlider.max = String(state.generations);
elements.generationSlider.value = String(state.generation);
elements.populationState.textContent = absorbed
? countA === 0 ? "A lost" : "A fixed"
: "Segregating";
elements.stagePopulationBadge.textContent = `N = ${state.population}`;
elements.trialLabel.textContent =
`Trial ${state.trialIndex + 1} / ${state.repetitions}`;
elements.liveSeed.textContent =
`0x${state.liveTrial.seed.toString(16).padStart(8, "0")}`;
drawTrajectoryChart();
}
function setGeneration(generation) {
if (!state.liveTrial) return;
state.generation = THREE.MathUtils.clamp(
generation,
0,
state.generations
);
renderLiveTrial();
}
function nextGeneration() {
if (state.generation >= state.generations) {
state.playing = false;
elements.playButton.textContent = "▶ Play";
return;
}
setGeneration(state.generation + 1);
}
function togglePlayback() {
state.playing = !state.playing;
if (state.playing && state.generation >= state.generations) {
state.generation = 0;
}
elements.playButton.textContent = state.playing ? "❚❚ Pause" : "▶ Play";
lastPlaybackTime = 0;
}
let lastPlaybackTime = 0;
elements.playButton.addEventListener("click", togglePlayback);
elements.nextGenerationButton.addEventListener("click", nextGeneration);
elements.previousGenerationButton.addEventListener("click", () => {
setGeneration(state.generation - 1);
});
elements.resetGenerationButton.addEventListener("click", () => {
setGeneration(0);
});
elements.generationSlider.addEventListener("input", () => {
setGeneration(Number(elements.generationSlider.value));
});
elements.speedSelect.addEventListener("change", () => {
state.speed = Number(elements.speedSelect.value);
});
elements.previousTrialButton.addEventListener("click", () => {
state.trialIndex = (state.trialIndex - 1 + state.repetitions) % state.repetitions;
loadLiveTrial(true);
});
elements.nextTrialButton.addEventListener("click", () => {
state.trialIndex = (state.trialIndex + 1) % state.repetitions;
loadLiveTrial(true);
});
// -------------------------------------------------------------------------
// Batch comparison
// -------------------------------------------------------------------------
async function runBatch() {
elements.runBatchButton.disabled = true;
elements.runBatchButton.textContent = "Running trials…";
elements.snapshotInfo.textContent = "Simulating seeded trials…";
elements.snapshotInfo.classList.remove("dirty");
await new Promise((resolve) => setTimeout(resolve, 40));
try {
const sizes = parsePopulationLadder();
const repetitions = state.repetitions;
const generations = state.generations;
const initialFrequency = state.initialFrequency;
const baseSeed = state.baseSeed;
const batch = new Map();
for (const population of sizes) {
const trials = [];
const frequencyRows = Array.from(
{ length: generations + 1 },
() => []
);
let fixed = 0;
let lost = 0;
let mixed = 0;
let absoluteChanges = 0;
const absorptionTimes = [];
for (let trialIndex = 0; trialIndex < repetitions; trialIndex++) {
const seed = deriveSeed(baseSeed, population, trialIndex);
const trial = simulateTrial({
population,
generations,
initialFrequency,
seed,
captureSnapshots: false
});
trials.push(trial);
for (let generation = 0; generation <= generations; generation++) {
frequencyRows[generation].push(trial.frequencies[generation]);
}
const finalFrequency = trial.finalFrequency;
if (finalFrequency === 1) {
fixed++;
} else if (finalFrequency === 0) {
lost++;
} else {
mixed++;
}
absoluteChanges += Math.abs(finalFrequency - initialFrequency);
if (trial.absorbedAt !== -1) {
absorptionTimes.push(trial.absorbedAt);
}
}
const mean = new Float64Array(generations + 1);
const lower = new Float64Array(generations + 1);
const upper = new Float64Array(generations + 1);
for (let generation = 0; generation <= generations; generation++) {
const sorted = frequencyRows[generation].sort((a, b) => a - b);
mean[generation] =
frequencyRows[generation].reduce((sum, value) => sum + value, 0) /
frequencyRows[generation].length;
lower[generation] = quantile(sorted, 0.1);
upper[generation] = quantile(sorted, 0.9);
}
batch.set(population, {
trials,
mean,
lower,
upper,
fixed,
lost,
mixed,
meanAbsoluteChange: absoluteChanges / repetitions,
medianAbsorption: median(absorptionTimes)
});
}
state.batch = batch;
state.trialIndex = Math.min(state.trialIndex, repetitions - 1);
loadLiveTrial(true);
renderComparison();
renderSummary();
markClean();
} finally {
elements.runBatchButton.disabled = false;
elements.runBatchButton.textContent = "Run comparison";
}
}
function renderSummary() {
const entry = state.batch.get(state.population);
if (!entry) {
elements.fixedRate.textContent = "—";
elements.lostRate.textContent = "—";
elements.mixedRate.textContent = "—";
return;
}
const total = entry.fixed + entry.lost + entry.mixed;
elements.fixedRate.textContent =
`${((entry.fixed / total) * 100).toFixed(1)}%`;
elements.lostRate.textContent =
`${((entry.lost / total) * 100).toFixed(1)}%`;
elements.mixedRate.textContent =
`${((entry.mixed / total) * 100).toFixed(1)}%`;
}
function renderComparison() {
const rows = [];
for (const [population, entry] of state.batch) {
const total = entry.fixed + entry.lost + entry.mixed;
const fixedPercent = (entry.fixed / total) * 100;
const lostPercent = (entry.lost / total) * 100;
const mixedPercent = (entry.mixed / total) * 100;
const medianText = entry.medianAbsorption === null
? "—"
: `${entry.medianAbsorption.toFixed(1)} gen`;
rows.push(`
<tr>
<td><strong>${population}</strong></td>
<td>
<div
class="outcome-bar"
title="A fixed ${fixedPercent.toFixed(1)}%, mixed ${mixedPercent.toFixed(1)}%, A lost ${lostPercent.toFixed(1)}%"
>
<i class="fixed" style="width:${fixedPercent}%"></i>
<i class="mixed" style="width:${mixedPercent}%"></i>
<i class="lost" style="width:${lostPercent}%"></i>
</div>
<div class="outcome-labels">
${fixedPercent.toFixed(0)} fixed · ${mixedPercent.toFixed(0)} mixed · ${lostPercent.toFixed(0)} lost
</div>
</td>
<td>${entry.meanAbsoluteChange.toFixed(3)}</td>
<td>${medianText}</td>
</tr>
`);
}
elements.comparisonBody.innerHTML = rows.join("");
}
elements.runBatchButton.addEventListener("click", runBatch);
// -------------------------------------------------------------------------
// Canvas chart
// -------------------------------------------------------------------------
function drawTrajectoryChart() {
const canvas = elements.trajectoryChart;
const rect = canvas.getBoundingClientRect();
const width = Math.max(280, rect.width);
const height = 230;
const ratio = Math.min(window.devicePixelRatio || 1, 2);
canvas.width = Math.round(width * ratio);
canvas.height = Math.round(height * ratio);
const context = canvas.getContext("2d");
context.setTransform(ratio, 0, 0, ratio, 0, 0);
context.clearRect(0, 0, width, height);
const margin = { left: 38, right: 12, top: 13, bottom: 28 };
const plotWidth = width - margin.left - margin.right;
const plotHeight = height - margin.top - margin.bottom;
const x = (generation) =>
margin.left + (generation / state.generations) * plotWidth;
const y = (frequency) =>
margin.top + (1 - frequency) * plotHeight;
context.fillStyle = "#0a0f19";
context.fillRect(margin.left, margin.top, plotWidth, plotHeight);
context.font = "10px system-ui, sans-serif";
context.textAlign = "right";
context.textBaseline = "middle";
for (const tick of [0, 0.25, 0.5, 0.75, 1]) {
const py = y(tick);
context.strokeStyle = "#222b3c";
context.lineWidth = 1;
context.beginPath();
context.moveTo(margin.left, py);
context.lineTo(margin.left + plotWidth, py);
context.stroke();
context.fillStyle = "#738097";
context.fillText(
`${Math.round(tick * 100)}%`,
margin.left - 7,
py
);
}
context.textAlign = "center";
context.textBaseline = "top";
for (let i = 0; i <= 4; i++) {
const generation = Math.round((state.generations * i) / 4);
const px = x(generation);
context.strokeStyle = "#1d2535";
context.beginPath();
context.moveTo(px, margin.top);
context.lineTo(px, margin.top + plotHeight);
context.stroke();
context.fillStyle = "#738097";
context.fillText(String(generation), px, margin.top + plotHeight + 7);
}
const batchEntry = state.batch.get(state.population);
if (batchEntry) {
context.beginPath();
context.moveTo(x(0), y(batchEntry.lower[0]));
for (let generation = 1; generation <= state.generations; generation++) {
context.lineTo(x(generation), y(batchEntry.upper[generation]));
}
for (let generation = state.generations; generation >= 0; generation--) {
context.lineTo(x(generation), y(batchEntry.lower[generation]));
}
context.closePath();
context.fillStyle = "rgba(155, 135, 255, 0.17)";
context.fill();
context.beginPath();
for (let generation = 0; generation <= state.generations; generation++) {
const px = x(generation);
const py = y(batchEntry.mean[generation]);
if (generation === 0) context.moveTo(px, py);
else context.lineTo(px, py);
}
context.strokeStyle = "#9b87ff";
context.lineWidth = 1.8;
context.setLineDash([5, 4]);
context.stroke();
context.setLineDash([]);
}
context.save();
context.setLineDash([4, 5]);
context.strokeStyle = "rgba(160, 173, 195, 0.55)";
context.lineWidth = 1;
context.beginPath();
context.moveTo(margin.left, y(state.initialFrequency));
context.lineTo(margin.left + plotWidth, y(state.initialFrequency));
context.stroke();
context.restore();
if (state.liveTrial) {
context.beginPath();
for (let generation = 0; generation <= state.generations; generation++) {
const px = x(generation);
const py = y(state.liveTrial.frequencies[generation]);
if (generation === 0) context.moveTo(px, py);
else context.lineTo(px, py);
}
context.strokeStyle = "#f5f7ff";
context.lineWidth = 2.3;
context.stroke();
const markerX = x(state.generation);
const markerY = y(state.liveTrial.frequencies[state.generation]);
context.fillStyle = "#f5f7ff";
context.beginPath();
context.arc(markerX, markerY, 3.5, 0, Math.PI * 2);
context.fill();
context.strokeStyle = "rgba(245, 247, 255, 0.22)";
context.beginPath();
context.moveTo(markerX, margin.top);
context.lineTo(markerX, margin.top + plotHeight);
context.stroke();
}
context.strokeStyle = "#30394b";
context.lineWidth = 1;
context.strokeRect(margin.left, margin.top, plotWidth, plotHeight);
}
// -------------------------------------------------------------------------
// Controls
// -------------------------------------------------------------------------
elements.populationSelect.addEventListener("change", () => {
state.population = Number(elements.populationSelect.value);
loadLiveTrial(true);
renderSummary();
});
elements.repetitions.addEventListener("input", () => {
state.repetitions = Number(elements.repetitions.value);
elements.repetitionsValue.textContent = String(state.repetitions);
state.trialIndex = Math.min(state.trialIndex, state.repetitions - 1);
loadLiveTrial(true);
markDirty();
});
elements.initialFrequency.addEventListener("input", () => {
state.initialFrequency = Number(elements.initialFrequency.value);
elements.initialFrequencyValue.textContent = state.initialFrequency.toFixed(2);
loadLiveTrial(true);
markDirty();
});
elements.generationCount.addEventListener("input", () => {
state.generations = Number(elements.generationCount.value);
elements.generationCountValue.textContent = String(state.generations);
loadLiveTrial(true);
markDirty();
});
elements.baseSeed.addEventListener("input", () => {
const parsed = Number(elements.baseSeed.value);
state.baseSeed = Number.isFinite(parsed) ? parsed >>> 0 : 0;
elements.baseSeed.value = String(state.baseSeed);
loadLiveTrial(true);
markDirty();
});
elements.shuffleSeedButton.addEventListener("click", () => {
const randomValues = new Uint32Array(1);
crypto.getRandomValues(randomValues);
state.baseSeed = randomValues[0];
elements.baseSeed.value = String(state.baseSeed);
loadLiveTrial(true);
markDirty();
});
elements.populationLadder.addEventListener("input", markDirty);
// -------------------------------------------------------------------------
// Render loop
// -------------------------------------------------------------------------
function animate(time) {
requestAnimationFrame(animate);
if (state.playing) {
if (!lastPlaybackTime) lastPlaybackTime = time;
const interval = 1000 / state.speed;
if (time - lastPlaybackTime >= interval) {
lastPlaybackTime = time;
nextGeneration();
}
} else {
lastPlaybackTime = 0;
}
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
drawTrajectoryChart();
});
// Initialize.
buildVoxelMesh(state.population);
resetCamera();
loadLiveTrial(true);
requestAnimationFrame(animate);
runBatch();
</script>
</body>
</html>
```