Prompt specification
Build or customize the Three.js 3D scene "Founder-size counterfactual simulator" 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: Founder-size counterfactual simulator
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/founder-size-counterfactual-simulator-x0904
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring the founder effect. Allow varying the number of colonists while keeping source frequencies fixed; compare several resulting populations and distinguish sampling effects from later selection or migration. Low-poly.
Working Three.js Starter (founder-size-counterfactual-simulator-x0904):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Founder Effect — Interactive Population Genetics Lab</title>
<style>
:root {
--bg: #08131d;
--panel: #0d1c29;
--panel-2: #122536;
--line: #20374a;
--text: #e7f0f5;
--muted: #91a7b7;
--cyan: #42c9d8;
--orange: #ff8b62;
--lime: #b9ef69;
--gray: #91a0ad;
--purple: #a68aee;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
overflow: hidden;
}
button,
input,
select {
font: inherit;
}
button,
select {
color: var(--text);
}
.app {
height: 100vh;
display: grid;
grid-template-rows: 78px minmax(0, 1fr);
}
header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 14px 22px;
border-bottom: 1px solid var(--line);
background:
radial-gradient(circle at 75% -80%, rgba(66, 201, 216, 0.17), transparent 42%),
#091722;
z-index: 5;
}
.title-block {
min-width: 0;
}
.eyebrow {
margin-bottom: 3px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(20px, 2.4vw, 30px);
line-height: 1;
letter-spacing: -0.04em;
}
.subtitle {
margin-top: 5px;
color: var(--muted);
font-size: 12px;
}
.source-badge {
flex: none;
padding: 10px 14px;
border: 1px solid rgba(66, 201, 216, 0.35);
border-radius: 12px;
background: rgba(66, 201, 216, 0.08);
color: #c9f7fc;
font-size: 12px;
text-align: right;
}
.source-badge strong {
display: block;
margin-top: 3px;
color: var(--cyan);
font-size: 15px;
}
main {
min-height: 0;
display: grid;
grid-template-columns: 310px minmax(0, 1fr);
}
aside {
min-height: 0;
overflow-y: auto;
padding: 18px;
border-right: 1px solid var(--line);
background: #0a1824;
scrollbar-width: thin;
scrollbar-color: #28465b transparent;
}
.section {
padding: 0 0 19px;
margin-bottom: 18px;
border-bottom: 1px solid var(--line);
}
.section:last-child {
border-bottom: 0;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 14px;
color: #dceaf1;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.step {
display: inline-grid;
width: 23px;
height: 23px;
place-items: center;
margin-right: 7px;
border-radius: 7px;
background: rgba(66, 201, 216, 0.12);
color: var(--cyan);
font-size: 10px;
vertical-align: middle;
}
.control {
margin-top: 13px;
}
.control.disabled {
opacity: 0.38;
pointer-events: none;
}
.control-label {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
margin-bottom: 8px;
color: #b9c9d3;
font-size: 12px;
}
.control-value {
color: var(--text);
font-variant-numeric: tabular-nums;
font-weight: 750;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 4px 0;
appearance: none;
border-radius: 999px;
outline: none;
background: #284052;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 16px;
height: 16px;
appearance: none;
border: 3px solid #0c1b27;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 0 1px var(--cyan);
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border: 3px solid #0c1b27;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 0 1px var(--cyan);
}
select {
width: 100%;
padding: 9px 10px;
border: 1px solid #2a4357;
border-radius: 9px;
outline: none;
background: #102331;
font-size: 12px;
}
.hint {
margin: 8px 0 0;
color: #78909f;
font-size: 10.5px;
line-height: 1.5;
}
.hint strong {
color: #aec3cf;
}
.toggle {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 12px;
cursor: pointer;
}
.toggle-copy {
color: #c7d5dd;
font-size: 12px;
font-weight: 700;
}
.toggle-copy small {
display: block;
margin-top: 3px;
color: #78909f;
font-size: 10px;
font-weight: 500;
}
.toggle input {
position: absolute;
opacity: 0;
pointer-events: none;
}
.switch {
position: relative;
flex: none;
width: 38px;
height: 22px;
border-radius: 999px;
background: #2a4050;
transition: 160ms ease;
}
.switch::after {
content: "";
position: absolute;
top: 3px;
left: 3px;
width: 16px;
height: 16px;
border-radius: 50%;
background: #a4b4bf;
transition: 160ms ease;
}
.toggle input:checked + .switch {
background: rgba(185, 239, 105, 0.38);
}
.toggle input:checked + .switch::after {
left: 19px;
background: var(--lime);
}
.force-options {
margin-top: 10px;
padding: 11px;
border: 1px solid #213a4b;
border-radius: 10px;
background: rgba(4, 13, 20, 0.28);
}
.force-options.off {
opacity: 0.38;
pointer-events: none;
}
.primary-button,
.secondary-button {
width: 100%;
border: 0;
border-radius: 10px;
padding: 11px 12px;
cursor: pointer;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.02em;
transition:
transform 120ms ease,
filter 120ms ease;
}
.primary-button {
color: #09202a;
background: linear-gradient(120deg, #55d5df, #78e1bb);
box-shadow: 0 7px 24px rgba(66, 201, 216, 0.15);
}
.secondary-button {
margin-top: 8px;
border: 1px solid #294456;
background: #102433;
}
.primary-button:hover,
.secondary-button:hover {
filter: brightness(1.08);
transform: translateY(-1px);
}
.read-box {
padding: 12px;
border: 1px solid rgba(185, 239, 105, 0.2);
border-radius: 11px;
background: rgba(185, 239, 105, 0.055);
color: #afc1cc;
font-size: 11px;
line-height: 1.55;
}
.read-box strong {
color: var(--lime);
}
.workspace {
min-width: 0;
min-height: 0;
display: grid;
grid-template-rows: minmax(310px, 1fr) 248px;
}
#stage {
position: relative;
min-height: 0;
overflow: hidden;
background: #0a1b29;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#stage canvas:active {
cursor: grabbing;
}
.hud {
position: absolute;
z-index: 2;
pointer-events: none;
}
.hud.top-left {
top: 15px;
left: 15px;
}
.hud.top-right {
top: 15px;
right: 15px;
text-align: right;
}
.glass {
border: 1px solid rgba(130, 170, 190, 0.2);
border-radius: 11px;
background: rgba(8, 22, 32, 0.79);
box-shadow: 0 8px 28px rgba(0, 0, 0, 0.18);
backdrop-filter: blur(10px);
}
.legend {
display: flex;
align-items: center;
gap: 12px;
padding: 9px 11px;
color: #b7c9d3;
font-size: 10px;
}
.legend-item {
display: flex;
align-items: center;
gap: 5px;
white-space: nowrap;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 3px;
}
.swatch.a {
background: var(--orange);
}
.swatch.b {
background: var(--cyan);
}
.swatch.founder {
background: var(--gray);
}
.swatch.final {
background: var(--lime);
}
.swatch.target {
width: 13px;
height: 2px;
border-radius: 0;
background: white;
}
.stage-status {
padding: 8px 11px;
color: #d9e8ee;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.stage-help {
left: 15px;
bottom: 13px;
padding: 8px 10px;
color: #8fa8b7;
font-size: 10px;
}
#resetView {
position: absolute;
z-index: 3;
right: 15px;
bottom: 13px;
padding: 7px 10px;
border: 1px solid rgba(130, 170, 190, 0.24);
border-radius: 8px;
background: rgba(8, 22, 32, 0.78);
color: #b7c9d3;
cursor: pointer;
font-size: 10px;
}
#labels {
position: absolute;
inset: 0;
z-index: 1;
pointer-events: none;
}
.island-label {
position: absolute;
min-width: 112px;
padding: 6px 8px;
border: 1px solid rgba(139, 173, 188, 0.25);
border-radius: 8px;
background: rgba(7, 18, 27, 0.84);
color: #cfe0e7;
font-size: 9.5px;
line-height: 1.45;
text-align: center;
transform: translate(-50%, -100%);
white-space: nowrap;
backdrop-filter: blur(6px);
}
.island-label strong {
display: block;
color: white;
font-size: 10.5px;
}
.island-label .founder-value {
color: #aebdc6;
}
.island-label .final-value {
color: var(--lime);
font-weight: 800;
}
.analytics {
min-width: 0;
display: grid;
grid-template-columns: minmax(0, 1.7fr) minmax(270px, 0.8fr);
gap: 14px;
padding: 14px 16px 16px;
border-top: 1px solid var(--line);
background: #091722;
}
.chart-panel,
.summary-panel {
min-width: 0;
padding: 12px 14px;
border: 1px solid var(--line);
border-radius: 12px;
background: #0c1b27;
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 7px;
}
.panel-heading h2 {
margin: 0;
font-size: 11px;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.panel-heading span {
color: #718b9a;
font-size: 9.5px;
}
#comparisonChart {
display: block;
width: 100%;
height: 184px;
overflow: visible;
}
.summary-panel {
display: grid;
grid-template-rows: repeat(3, 1fr);
gap: 8px;
}
.metric {
padding: 8px 10px;
border-radius: 9px;
background: #102332;
}
.metric-label {
color: #7893a2;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.metric-value {
margin-top: 4px;
color: #edf5f8;
font-size: 13px;
font-weight: 800;
line-height: 1.25;
}
.metric-detail {
margin-top: 3px;
color: #8ea4b1;
font-size: 9.5px;
line-height: 1.4;
}
.lime {
color: var(--lime);
}
.cyan {
color: var(--cyan);
}
.orange {
color: var(--orange);
}
@media (max-width: 1050px) {
main {
grid-template-columns: 275px minmax(0, 1fr);
}
.analytics {
grid-template-columns: minmax(0, 1.45fr) minmax(240px, 0.8fr);
}
}
@media (max-width: 820px) {
body {
overflow: auto;
}
.app {
height: auto;
min-height: 100vh;
grid-template-rows: auto auto;
}
header {
align-items: flex-start;
padding: 15px;
}
.subtitle {
max-width: 430px;
}
main {
display: block;
}
aside {
overflow: visible;
border-right: 0;
border-bottom: 1px solid var(--line);
}
.workspace {
grid-template-rows: 62vh 430px;
}
.analytics {
grid-template-columns: 1fr;
}
.summary-panel {
grid-template-columns: repeat(3, 1fr);
grid-template-rows: 1fr;
}
}
@media (max-width: 560px) {
header {
display: block;
}
.source-badge {
display: inline-block;
margin-top: 12px;
text-align: left;
}
.workspace {
grid-template-rows: 58vh 520px;
}
.summary-panel {
grid-template-columns: 1fr;
grid-template-rows: repeat(3, auto);
}
.legend {
flex-wrap: wrap;
}
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="title-block">
<div class="eyebrow">Interactive Population Genetics</div>
<h1>Founder Effect Observatory</h1>
<div class="subtitle">
Sample the same source population, compare isolated colonies, then separate
founder sampling from later selection or migration.
</div>
</div>
<div class="source-badge">
Fixed source population
<strong id="headerSource">A 50% · a 50%</strong>
</div>
</header>
<main>
<aside>
<section class="section">
<div class="section-title">
<span><span class="step">1</span>Source population</span>
</div>
<div class="control">
<label class="control-label" for="sourceFreq">
Source allele A frequency
<span class="control-value" id="sourceValue">50%</span>
</label>
<input
id="sourceFreq"
type="range"
min="5"
max="95"
step="1"
value="50"
>
<p class="hint">
Every colony samples from this same distribution. Changing the source
starts a new experiment.
</p>
</div>
</section>
<section class="section">
<div class="section-title">
<span><span class="step">2</span>Founding event</span>
</div>
<div class="control">
<label class="control-label" for="compareMode">
Comparison design
</label>
<select id="compareMode">
<option value="replicate">Replicates with the same founder size</option>
<option value="sweep">Compare founder sizes: 2, 4, 8, 16</option>
</select>
</div>
<div class="control" id="nControl">
<label class="control-label" for="founderN">
Colonists per population
<span class="control-value" id="nValue">8</span>
</label>
<input
id="founderN"
type="range"
min="2"
max="24"
step="1"
value="8"
>
</div>
<div class="control" id="populationControl">
<label class="control-label" for="populationCount">
Number of populations
<span class="control-value" id="populationValue">4</span>
</label>
<input
id="populationCount"
type="range"
min="2"
max="6"
step="1"
value="4"
>
</div>
<p class="hint" id="modeHint">
Replicates reveal sampling variation even though the source frequency is fixed.
</p>
</section>
<section class="section">
<div class="section-title">
<span><span class="step">3</span>Later forces</span>
</div>
<label class="toggle" for="useSelection">
<span class="toggle-copy">
Apply selection
<small>Changes allele survival after founding</small>
</span>
<input id="useSelection" type="checkbox">
<span class="switch"></span>
</label>
<div class="force-options off" id="selectionOptions">
<div class="control" style="margin-top: 0">
<label class="control-label" for="selectionDirection">
Favored allele
</label>
<select id="selectionDirection">
<option value="A">Allele A</option>
<option value="a">Allele a</option>
</select>
</div>
<div class="control">
<label class="control-label" for="selectionStrength">
Selection strength, s
<span class="control-value" id="selectionStrengthValue">0.35</span>
</label>
<input
id="selectionStrength"
type="range"
min="0.05"
max="0.8"
step="0.05"
value="0.35"
>
</div>
<div class="control">
<label class="control-label" for="selectionGenerations">
Selection generations
<span class="control-value" id="selectionGenerationsValue">5</span>
</label>
<input
id="selectionGenerations"
type="range"
min="1"
max="10"
step="1"
value="5"
>
</div>
</div>
<label class="toggle" for="useMigration">
<span class="toggle-copy">
Apply migration
<small>Mixes migrants from the unchanged source</small>
</span>
<input id="useMigration" type="checkbox">
<span class="switch"></span>
</label>
<div class="force-options off" id="migrationOptions">
<div class="control" style="margin-top: 0">
<label class="control-label" for="migrationRate">
Migrant fraction, m
<span class="control-value" id="migrationRateValue">0.20</span>
</label>
<input
id="migrationRate"
type="range"
min="0.05"
max="0.5"
step="0.05"
value="0.2"
>
</div>
</div>
<p class="hint">
When both are enabled, the order is
<strong>selection → migration</strong>. Founder draws stay locked when
these settings change, so later effects cannot be mistaken for resampling.
</p>
</section>
<section class="section">
<button class="primary-button" id="reroll" type="button">
Draw new founder populations
</button>
<button class="secondary-button" id="resetDefaults" type="button">
Reset experiment
</button>
</section>
<section class="section">
<div class="read-box">
<strong>How to read the scene</strong><br>
Orange chest chips are allele A; cyan chips are allele a. Gray bars show
each founder frequency, green bars show the final frequency, and the
white dash marks the unchanged source frequency.
</div>
</section>
</aside>
<section class="workspace">
<div id="stage">
<div class="hud top-left">
<div class="glass legend">
<span class="legend-item"><i class="swatch a"></i>A</span>
<span class="legend-item"><i class="swatch b"></i>a</span>
<span class="legend-item"><i class="swatch founder"></i>Founder</span>
<span class="legend-item"><i class="swatch final"></i>Final</span>
<span class="legend-item"><i class="swatch target"></i>Source</span>
</div>
</div>
<div class="hud top-right">
<div class="glass stage-status" id="stageStatus">
Founder sampling only
</div>
</div>
<div id="labels"></div>
<div class="hud stage-help">
Drag to orbit · Scroll to zoom
</div>
<button id="resetView" type="button">Reset camera</button>
</div>
<section class="analytics">
<div class="chart-panel">
<div class="panel-heading">
<h2>Sampling spread vs. later change</h2>
<span>Gray = founder · Green = final · Dashed = source</span>
</div>
<svg
id="comparisonChart"
viewBox="0 0 680 210"
role="img"
aria-label="Comparison of founder and final allele frequencies"
></svg>
</div>
<div class="summary-panel" aria-live="polite">
<div class="metric">
<div class="metric-label">Founder sampling</div>
<div class="metric-value" id="samplingMetric">—</div>
<div class="metric-detail" id="samplingDetail">—</div>
</div>
<div class="metric">
<div class="metric-label">Later forces</div>
<div class="metric-value" id="laterMetric">—</div>
<div class="metric-detail" id="laterDetail">—</div>
</div>
<div class="metric">
<div class="metric-label">Interpretation</div>
<div class="metric-detail" id="interpretation">—</div>
</div>
</div>
</section>
</section>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const state = {
sourceP: 0.5,
founderN: 8,
populationCount: 4,
mode: "replicate",
selection: false,
selectionDirection: "A",
selectionStrength: 0.35,
selectionGenerations: 5,
migration: false,
migrationRate: 0.2
};
let founderPopulations = [];
let finalPopulations = [];
let populationLabels = [];
const stage = $("stage");
const labelLayer = $("labels");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
stage.prepend(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0a1b29);
scene.fog = new THREE.Fog(0x0a1b29, 17, 31);
const camera = new THREE.PerspectiveCamera(43, 1, 0.1, 100);
const orbit = {
theta: 0.12,
phi: 0.86,
radius: 14.2,
target: new THREE.Vector3(0, 0.25, 0),
dragging: false,
lastX: 0,
lastY: 0
};
function updateCamera() {
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + orbit.radius * sinPhi * Math.sin(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + orbit.radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(orbit.target);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xb8ecff, 0x263526, 2.25);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffe6c4, 3.1);
sun.position.set(-7, 12, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.camera.left = -12;
sun.shadow.camera.right = 12;
sun.shadow.camera.top = 12;
sun.shadow.camera.bottom = -12;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 32;
sun.shadow.bias = -0.001;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x4ed8e7, 1.2);
rim.position.set(8, 5, -10);
scene.add(rim);
const dynamicRoot = new THREE.Group();
scene.add(dynamicRoot);
const shared = {
bodyGeometry: new THREE.CylinderGeometry(0.115, 0.145, 0.32, 5),
headGeometry: new THREE.IcosahedronGeometry(0.105, 0),
markerGeometry: new THREE.BoxGeometry(0.075, 0.085, 0.035),
boxGeometry: new THREE.BoxGeometry(1, 1, 1),
trunkGeometry: new THREE.CylinderGeometry(0.055, 0.08, 0.38, 5),
crownGeometry: new THREE.ConeGeometry(0.27, 0.62, 6),
rockGeometry: new THREE.IcosahedronGeometry(0.16, 0),
islandGeometry: new THREE.CylinderGeometry(1.42, 1.52, 0.28, 7),
ringGeometry: new THREE.TorusGeometry(1.43, 0.045, 5, 28),
materialA: new THREE.MeshStandardMaterial({
color: 0xff8b62,
roughness: 0.83,
flatShading: true
}),
materiala: new THREE.MeshStandardMaterial({
color: 0x42c9d8,
roughness: 0.83,
flatShading: true
}),
materialAA: new THREE.MeshStandardMaterial({
color: 0xe8754d,
roughness: 0.9,
flatShading: true
}),
materialAa: new THREE.MeshStandardMaterial({
color: 0x9b82df,
roughness: 0.9,
flatShading: true
}),
materialaa: new THREE.MeshStandardMaterial({
color: 0x32aab9,
roughness: 0.9,
flatShading: true
}),
headMaterial: new THREE.MeshStandardMaterial({
color: 0xf2d6b5,
roughness: 0.95,
flatShading: true
})
};
function makeWater() {
const geometry = new THREE.PlaneGeometry(32, 26, 12, 10);
const position = geometry.attributes.position;
const colors = [];
const low = new THREE.Color(0x0a2735);
const high = new THREE.Color(0x123d4b);
for (let i = 0; i < position.count; i++) {
const x = position.getX(i);
const y = position.getY(i);
const wave =
Math.sin(x * 0.75) * 0.055 +
Math.cos(y * 0.92) * 0.045 +
Math.sin((x + y) * 0.43) * 0.035;
position.setZ(i, wave);
const mix = THREE.MathUtils.clamp((wave + 0.13) / 0.26, 0, 1);
const color = low.clone().lerp(high, mix);
colors.push(color.r, color.g, color.b);
}
geometry.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3));
geometry.computeVertexNormals();
const water = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.8,
metalness: 0.05,
flatShading: true
})
);
water.rotation.x = -Math.PI / 2;
water.position.y = -0.21;
water.receiveShadow = true;
scene.add(water);
const foamMaterial = new THREE.MeshBasicMaterial({
color: 0x62c8d1,
transparent: true,
opacity: 0.08
});
for (let i = 0; i < 15; i++) {
const ring = new THREE.Mesh(
new THREE.RingGeometry(0.25 + Math.random() * 0.5, 0.28 + Math.random() * 0.5, 7),
foamMaterial
);
ring.rotation.x = -Math.PI / 2;
ring.position.set(
(Math.random() - 0.5) * 24,
-0.145,
(Math.random() - 0.5) * 18
);
scene.add(ring);
}
}
makeWater();
function populationSizes() {
if (state.mode === "sweep") {
return [2, 4, 8, 16];
}
return Array(state.populationCount).fill(state.founderN);
}
function randomAlleleCount(totalCopies) {
let count = 0;
for (let i = 0; i < totalCopies; i++) {
if (Math.random() < state.sourceP) {
count++;
}
}
return count;
}
function makeGenotypes(alleleCount, populationSize) {
const genotypes = Array.from(
{ length: populationSize },
() => ({ a: 0 })
);
let remaining = alleleCount;
// First give each individual at most one A copy.
for (const genotype of genotypes) {
if (remaining > 0) {
genotype.a = 1;
remaining--;
}
}
// Then give second copies where needed.
for (const genotype of genotypes) {
if (remaining > 0) {
genotype.a = 2;
remaining--;
}
}
return genotypes;
}
function resampleFounders() {
founderPopulations = populationSizes().map((size) => {
const alleleCount = randomAlleleCount(size * 2);
return {
size,
alleleCount,
founderP: alleleCount / (size * 2),
genotypes: makeGenotypes(alleleCount, size)
};
});
}
function applySelection(alleleCount, populationSize) {
let p = alleleCount / (populationSize * 2);
const q = 1 - p;
const s = state.selectionStrength;
for (let generation = 0; generation < state.selectionGenerations; generation++) {
let wAA;
let wAa;
let waa;
if (state.selectionDirection === "A") {
wAA = 1 + s;
wAa = 1 + s / 2;
waa = 1;
} else {
wAA = 1;
wAa = 1 + s / 2;
waa = 1 + s;
}
const meanFitness =
p * p * wAA +
2 * p * q * wAa +
q * q * waa;
const numeratorA = p * p * wAA + p * q * wAa;
p = numeratorA / meanFitness;
}
return Math.round(p * populationSize * 2);
}
function recomputeFinalPopulations() {
finalPopulations = founderPopulations.map((population) => {
let alleleCount = population.alleleCount;
if (state.selection) {
alleleCount = applySelection(alleleCount, population.size);
}
if (state.migration) {
const sourceCopies = population.size * 2;
alleleCount = Math.round(
(1 - state.migrationRate) * alleleCount +
state.migrationRate * sourceCopies * state.sourceP
);
}
alleleCount = THREE.MathUtils.clamp(
alleleCount,
0,
population.size * 2
);
return {
...population,
alleleCount,
finalP: alleleCount / (population.size * 2),
genotypes: makeGenotypes(alleleCount, population.size)
};
});
}
function layoutPositions(count) {
if (count <= 4) {
return Array.from({ length: count }, (_, index) => ({
x: (index - (count - 1) / 2) * 2.65,
z: 0
}));
}
const positions = [];
for (let index = 0; index < count; index++) {
const row = Math.floor(index / 3);
const column = index % 3;
positions.push({
x: (column - 1) * 3.15,
z: row === 0 ? -2.15 : 2.15
});
}
return positions;
}
function addTree(group, angle, scale = 1) {
const tree = new THREE.Group();
const trunk = new THREE.Mesh(shared.trunkGeometry, shared.headMaterial);
const crown = new THREE.Mesh(
shared.crownGeometry,
new THREE.MeshStandardMaterial({
color: 0x3d805e,
roughness: 0.95,
flatShading: true
})
);
trunk.position.y = 0.18;
crown.position.y = 0.65;
trunk.castShadow = true;
crown.castShadow = true;
tree.add(trunk, crown);
tree.position.set(
Math.cos(angle) * 1.12,
0.22,
Math.sin(angle) * 1.12
);
tree.scale.setScalar(scale);
group.add(tree);
}
function addRock(group, x, z, scale) {
const rock = new THREE.Mesh(
shared.rockGeometry,
new THREE.MeshStandardMaterial({
color: 0x71818a,
roughness: 1,
flatShading: true
})
);
rock.position.set(x, 0.3, z);
rock.scale.set(scale * 1.2, scale * 0.7, scale);
rock.rotation.set(Math.random(), Math.random(), Math.random());
rock.castShadow = true;
group.add(rock);
}
function addPerson(group, genotype, x, z) {
const person = new THREE.Group();
const bodyMaterial =
genotype.a === 2
? shared.materialAA
: genotype.a === 1
? shared.materialAa
: shared.materialaa;
const body = new THREE.Mesh(shared.bodyGeometry, bodyMaterial);
body.position.y = 0.42;
body.castShadow = true;
const head = new THREE.Mesh(shared.headGeometry, shared.headMaterial);
head.position.y = 0.67;
head.castShadow = true;
const firstMarker = new THREE.Mesh(
shared.markerGeometry,
genotype.a >= 1 ? shared.materialA : shared.materiala
);
const secondMarker = new THREE.Mesh(
shared.markerGeometry,
genotype.a === 2 ? shared.materialA : shared.materiala
);
firstMarker.position.set(-0.047, 0.43, 0.123);
secondMarker.position.set(0.047, 0.43, 0.123);
person.add(body, head, firstMarker, secondMarker);
person.position.set(x, 0.24, z);
group.add(person);
}
function addFrequencyBars(group, founderP, finalP) {
const baseY = 0.24;
const maxHeight = 1.42;
const founderMaterial = new THREE.MeshStandardMaterial({
color: 0x91a0ad,
roughness: 0.85,
emissive: 0x17212a
});
const finalMaterial = new THREE.MeshStandardMaterial({
color: 0xb9ef69,
roughness: 0.72,
emissive: 0x24370d
});
const founderBar = new THREE.Mesh(shared.boxGeometry, founderMaterial);
const finalBar = new THREE.Mesh(shared.boxGeometry, finalMaterial);
founderBar.scale.set(0.11, Math.max(0.025, founderP * maxHeight), 0.11);
finalBar.scale.set(0.11, Math.max(0.025, finalP * maxHeight), 0.11);
founderBar.position.set(0.89, baseY + founderBar.scale.y / 2, 0.89);
finalBar.position.set(1.14, baseY + finalBar.scale.y / 2, 0.89);
founderBar.castShadow = true;
finalBar.castShadow = true;
const sourceLineMaterial = new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.92
});
const sourceLine = new THREE.Mesh(
shared.boxGeometry,
sourceLineMaterial
);
sourceLine.scale.set(0.48, 0.025, 0.08);
sourceLine.position.set(
1.015,
baseY + state.sourceP * maxHeight,
0.89
);
group.add(founderBar, finalBar, sourceLine);
}
function clearDynamicScene() {
dynamicRoot.traverse((object) => {
if (object.userData.ownMaterial && object.material) {
object.material.dispose();
}
});
dynamicRoot.clear();
for (const label of populationLabels) {
label.element.remove();
}
populationLabels = [];
}
function rebuildScene() {
clearDynamicScene();
const positions = layoutPositions(finalPopulations.length);
const islandColors = [0x507a58, 0x4b7656, 0x577e5d, 0x497155, 0x5d8160, 0x527b5a];
finalPopulations.forEach((population, index) => {
const group = new THREE.Group();
group.position.set(positions[index].x, 0, positions[index].z);
const islandMaterial = new THREE.MeshStandardMaterial({
color: islandColors[index % islandColors.length],
roughness: 1,
flatShading: true
});
const island = new THREE.Mesh(shared.islandGeometry, islandMaterial);
island.position.y = 0.08;
island.receiveShadow = true;
island.castShadow = true;
const ringMaterial = new THREE.MeshStandardMaterial({
color: 0xb7c58d,
roughness: 0.95,
flatShading: true
});
const ring = new THREE.Mesh(shared.ringGeometry, ringMaterial);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.225;
group.add(island, ring);
const columns = Math.min(6, Math.ceil(Math.sqrt(population.size * 1.55)));
const rows = Math.ceil(population.size / columns);
const spacing = population.size <= 8 ? 0.43 : 0.37;
population.genotypes.forEach((genotype, personIndex) => {
const column = personIndex % columns;
const row = Math.floor(personIndex / columns);
const x =
(column - (Math.min(columns, population.size - row * columns) - 1) / 2) *
spacing;
const z =
(row - (rows - 1) / 2) * spacing - 0.08;
addPerson(group, genotype, x, z);
});
addTree(group, 2.25 + index * 0.16, 0.82);
addTree(group, 3.7 + index * 0.08, 0.68);
addTree(group, 5.0, 0.76);
addRock(group, -1.08, 0.35, 0.78);
addRock(group, -0.98, 0.64, 0.42);
addFrequencyBars(
group,
founderPopulations[index].founderP,
population.finalP
);
dynamicRoot.add(group);
const label = document.createElement("div");
label.className = "island-label";
label.innerHTML = `
<strong>Population ${index + 1} · N=${population.size}</strong>
<span class="founder-value">Founder ${formatPercent(founderPopulations[index].founderP)}</span>
<span class="final-value">Final ${formatPercent(population.finalP)}</span>
`;
labelLayer.appendChild(label);
populationLabels.push({
element: label,
position: new THREE.Vector3(
positions[index].x,
1.25,
positions[index].z
)
});
});
if (finalPopulations.length > 4 && orbit.radius < 15) {
orbit.radius = 15.5;
}
}
function formatPercent(value) {
return `${(value * 100).toFixed(1)}%`;
}
function mean(values) {
return values.reduce((sum, value) => sum + value, 0) / values.length;
}
function theoreticalSD(p, n) {
return Math.sqrt((p * (1 - p)) / (2 * n));
}
function updateChart() {
const svg = $("comparisonChart");
const width = 680;
const height = 210;
const margin = {
left: 78,
right: 22,
top: 24,
bottom: 31
};
const plotWidth = width - margin.left - margin.right;
const plotHeight = height - margin.top - margin.bottom;
const rowHeight = plotHeight / Math.max(finalPopulations.length, 1);
const x = (p) => margin.left + p * plotWidth;
const elements = [
`<defs>
<marker
id="changeArrow"
viewBox="0 0 10 10"
refX="8"
refY="5"
markerWidth="5"
markerHeight="5"
orient="auto-start-reverse"
>
<path d="M 0 0 L 10 5 L 0 10 z" fill="#b9ef69"></path>
</marker>
</defs>`,
`<rect x="${margin.left}" y="${margin.top}" width="${plotWidth}" height="${plotHeight}" rx="8" fill="#091722"></rect>`,
`<line
x1="${x(state.sourceP)}"
y1="${margin.top}"
x2="${x(state.sourceP)}"
y2="${margin.top + plotHeight}"
stroke="#e7f0f5"
stroke-opacity="0.52"
stroke-width="1.2"
stroke-dasharray="4 5"
></line>`,
`<text
x="${x(state.sourceP)}"
y="13"
text-anchor="middle"
fill="#cbd9e0"
font-size="9"
>source ${formatPercent(state.sourceP)}</text>`
];
[0, 0.25, 0.5, 0.75, 1].forEach((tick) => {
elements.push(`
<line
x1="${x(tick)}"
y1="${margin.top + plotHeight}"
x2="${x(tick)}"
y2="${margin.top + plotHeight + 4}"
stroke="#476070"
></line>
<text
x="${x(tick)}"
y="${height - 10}"
text-anchor="middle"
fill="#718b9a"
font-size="9"
>${tick.toFixed(2)}</text>
`);
});
finalPopulations.forEach((population, index) => {
const founder = founderPopulations[index];
const y = margin.top + rowHeight * (index + 0.5);
const founderX = x(founder.founderP);
const finalX = x(population.finalP);
elements.push(`
<text
x="${margin.left - 10}"
y="${y + 3}"
text-anchor="end"
fill="#93a9b6"
font-size="9.5"
>P${index + 1} · N=${population.size}</text>
`);
if (Math.abs(finalX - founderX) > 0.8) {
elements.push(`
<line
x1="${founderX}"
y1="${y}"
x2="${finalX}"
y2="${y}"
stroke="#b9ef69"
stroke-opacity="0.58"
stroke-width="1.6"
marker-end="url(#changeArrow)"
></line>
`);
}
elements.push(`
<circle
cx="${founderX}"
cy="${y}"
r="5"
fill="#91a0ad"
stroke="#dce5ea"
stroke-width="1.2"
></circle>
<circle
cx="${finalX}"
cy="${y}"
r="5"
fill="#b9ef69"
stroke="#efffe0"
stroke-width="1.2"
></circle>
`);
});
svg.innerHTML = elements.join("");
}
function updateSummary() {
const founderValues = founderPopulations.map((population) => population.founderP);
const finalValues = finalPopulations.map((population) => population.finalP);
const founderMean = mean(founderValues);
const finalMean = mean(finalValues);
const founderMin = Math.min(...founderValues);
const founderMax = Math.max(...founderValues);
const laterShift = finalMean - founderMean;
$("samplingMetric").innerHTML =
`${formatPercent(founderMin)} – ${formatPercent(founderMax)}`;
if (state.mode === "replicate") {
const sd = theoreticalSD(state.sourceP, state.founderN);
$("samplingDetail").innerHTML =
`Mean ${formatPercent(founderMean)}. Approx. sampling SD at N=${state.founderN}: ` +
`<span class="cyan">${sd.toFixed(3)}</span>.`;
} else {
const sds = founderPopulations.map((population) =>
theoreticalSD(state.sourceP, population.size).toFixed(2)
);
$("samplingDetail").innerHTML =
`Mean ${formatPercent(founderMean)}. Expected SD by N: ` +
`<span class="cyan">${sds.join(" · ")}</span>.`;
}
const activeForces = [];
if (state.selection) activeForces.push("selection");
if (state.migration) activeForces.push("migration");
if (activeForces.length === 0) {
$("laterMetric").innerHTML = `<span class="cyan">No later change</span>`;
$("laterDetail").textContent =
"Founder and final frequencies are identical. All differences between populations are sampling effects.";
} else {
const shiftClass = laterShift >= 0 ? "lime" : "orange";
$("laterMetric").innerHTML =
`<span class="${shiftClass}">${laterShift >= 0 ? "+" : ""}${formatPercent(laterShift)}</span> mean shift`;
$("laterDetail").textContent =
`Final mean ${formatPercent(finalMean)}. Active: ${activeForces.join(" → ")}. ` +
`The founder draw was retained.`;
}
if (state.mode === "sweep") {
$("interpretation").innerHTML =
`<strong class="cyan">Sampling effect.</strong> Small founder samples produce ` +
`wider allele-frequency spread. Larger N values should cluster more closely ` +
`around the dashed source frequency.`;
} else if (!state.selection && !state.migration) {
$("interpretation").innerHTML =
`<strong class="cyan">Founder effect only.</strong> The source is identical, ` +
`but small random founding samples create different colony frequencies.`;
} else {
$("interpretation").innerHTML =
`<strong class="cyan">Two mechanisms are visible.</strong> Gray-to-green ` +
`movement is later selection or migration; differences among gray points are ` +
`the original founder sampling effect.`;
}
}
function updateStageStatus() {
const stages = ["founder sampling"];
if (state.selection) stages.push("selection");
if (state.migration) stages.push("migration");
$("stageStatus").textContent = stages.join(" → ");
$("headerSource").textContent =
`A ${formatPercent(state.sourceP)} · a ${formatPercent(1 - state.sourceP)}`;
}
function updateControlLabels() {
$("sourceValue").textContent = `${Math.round(state.sourceP * 100)}%`;
$("nValue").textContent = state.founderN;
$("populationValue").textContent = state.populationCount;
$("selectionStrengthValue").textContent = state.selectionStrength.toFixed(2);
$("selectionGenerationsValue").textContent = state.selectionGenerations;
$("migrationRateValue").textContent = state.migrationRate.toFixed(2);
$("selectionOptions").classList.toggle("off", !state.selection);
$("migrationOptions").classList.toggle("off", !state.migration);
const sweep = state.mode === "sweep";
$("nControl").classList.toggle("disabled", sweep);
$("populationControl").classList.toggle("disabled", sweep);
$("modeHint").innerHTML = sweep
? `Founder sizes are <strong>2, 4, 8, and 16</strong>. The source frequency stays fixed, ` +
`so differences reveal the effect of sample size.`
: `Replicates reveal sampling variation even though the source frequency is fixed.`;
}
function updateEverything() {
updateControlLabels();
updateStageStatus();
updateChart();
updateSummary();
}
function newExperiment() {
resampleFounders();
recomputeFinalPopulations();
rebuildScene();
updateEverything();
}
function recomputeLaterStages() {
recomputeFinalPopulations();
rebuildScene();
updateEverything();
}
$("sourceFreq").addEventListener("input", (event) => {
state.sourceP = Number(event.target.value) / 100;
updateControlLabels();
updateStageStatus();
});
$("sourceFreq").addEventListener("change", newExperiment);
$("founderN").addEventListener("input", (event) => {
state.founderN = Number(event.target.value);
updateControlLabels();
});
$("founderN").addEventListener("change", newExperiment);
$("populationCount").addEventListener("input", (event) => {
state.populationCount = Number(event.target.value);
updateControlLabels();
});
$("populationCount").addEventListener("change", newExperiment);
$("compareMode").addEventListener("change", (event) => {
state.mode = event.target.value;
newExperiment();
});
$("useSelection").addEventListener("change", (event) => {
state.selection = event.target.checked;
recomputeLaterStages();
});
$("selectionDirection").addEventListener("change", (event) => {
state.selectionDirection = event.target.value;
recomputeLaterStages();
});
$("selectionStrength").addEventListener("input", (event) => {
state.selectionStrength = Number(event.target.value);
updateControlLabels();
recomputeLaterStages();
});
$("selectionGenerations").addEventListener("input", (event) => {
state.selectionGenerations = Number(event.target.value);
updateControlLabels();
recomputeLaterStages();
});
$("useMigration").addEventListener("change", (event) => {
state.migration = event.target.checked;
recomputeLaterStages();
});
$("migrationRate").addEventListener("input", (event) => {
state.migrationRate = Number(event.target.value);
updateControlLabels();
recomputeLaterStages();
});
$("reroll").addEventListener("click", newExperiment);
$("resetDefaults").addEventListener("click", () => {
Object.assign(state, {
sourceP: 0.5,
founderN: 8,
populationCount: 4,
mode: "replicate",
selection: false,
selectionDirection: "A",
selectionStrength: 0.35,
selectionGenerations: 5,
migration: false,
migrationRate: 0.2
});
$("sourceFreq").value = 50;
$("founderN").value = 8;
$("populationCount").value = 4;
$("compareMode").value = "replicate";
$("useSelection").checked = false;
$("selectionDirection").value = "A";
$("selectionStrength").value = 0.35;
$("selectionGenerations").value = 5;
$("useMigration").checked = false;
$("migrationRate").value = 0.2;
newExperiment();
});
$("resetView").addEventListener("click", () => {
orbit.theta = 0.12;
orbit.phi = 0.86;
orbit.radius = finalPopulations.length > 4 ? 15.5 : 14.2;
updateCamera();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
orbit.dragging = true;
orbit.lastX = event.clientX;
orbit.lastY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!orbit.dragging) return;
const dx = event.clientX - orbit.lastX;
const dy = event.clientY - orbit.lastY;
orbit.lastX = event.clientX;
orbit.lastY = event.clientY;
orbit.theta -= dx * 0.006;
orbit.phi = THREE.MathUtils.clamp(orbit.phi - dy * 0.005, 0.35, 1.35);
updateCamera();
});
function stopDragging(event) {
orbit.dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius + event.deltaY * 0.012,
8,
23
);
updateCamera();
},
{ passive: false }
);
const resizeObserver = new ResizeObserver(() => {
const width = stage.clientWidth;
const height = stage.clientHeight;
if (!width || !height) return;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
});
resizeObserver.observe(stage);
const projected = new THREE.Vector3();
function updateLabels() {
const width = stage.clientWidth;
const height = stage.clientHeight;
for (const label of populationLabels) {
projected.copy(label.position).project(camera);
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
const visible =
projected.z > -1 &&
projected.z < 1 &&
x > -100 &&
x < width + 100 &&
y > -80 &&
y < height + 80;
label.element.style.display = visible ? "block" : "none";
label.element.style.left = `${x}px`;
label.element.style.top = `${y}px`;
}
}
function animate() {
requestAnimationFrame(animate);
updateCamera();
updateLabels();
renderer.render(scene, camera);
}
newExperiment();
animate();
</script>
</body>
</html>
```