Prompt specification
Build or customize the Three.js 3D scene "Migration before and after reproduction" 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: Migration before and after reproduction
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/migration-before-and-after-reproduction-x0910
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts gene flow between populations. Move a chosen number of individuals between fictional populations, then update offspring pools under stated neutral rules; separate migration from mutation and selection. Stylized solid forms.
Working Three.js Starter (migration-before-and-after-reproduction-x0910):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Gene Flow Field Lab</title>
<style>
:root {
--bg: #06131d;
--panel: rgba(8, 24, 34, 0.88);
--panel-solid: #0b202d;
--line: rgba(158, 213, 226, 0.16);
--text: #e8f7fb;
--muted: #91abb7;
--cyan: #58d9ff;
--violet: #a78bfa;
--amber: #ffb45c;
--mint: #58e0bd;
--danger: #ff7d7d;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 20%, #153747 0%, #081b27 45%, #040d14 100%);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, select, input { font: inherit; }
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
}
#labels {
position: fixed;
inset: 0;
pointer-events: none;
overflow: hidden;
}
.world-label {
position: absolute;
min-width: 142px;
padding: 8px 11px;
border: 1px solid rgba(190, 236, 245, 0.2);
border-radius: 10px;
background: rgba(5, 18, 27, 0.8);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.24);
text-align: center;
transform: translate(-50%, -50%);
backdrop-filter: blur(8px);
}
.world-label::after {
content: "";
position: absolute;
left: 50%;
bottom: -9px;
width: 1px;
height: 8px;
background: rgba(190, 236, 245, 0.35);
}
.wl-name {
display: block;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.wl-meta {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.topbar {
position: fixed;
z-index: 10;
top: 18px;
left: 22px;
right: 22px;
display: flex;
align-items: flex-start;
justify-content: space-between;
pointer-events: none;
}
.brand {
max-width: 430px;
text-shadow: 0 2px 18px rgba(0, 0, 0, 0.35);
}
.eyebrow {
color: var(--mint);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 5px 0 3px;
font-size: clamp(24px, 3vw, 40px);
line-height: 1;
letter-spacing: -0.045em;
}
h1 span {
color: #88aab8;
font-weight: 400;
}
.subtitle {
margin: 7px 0 0;
color: #abc0c9;
font-size: 12px;
}
.top-actions {
display: flex;
gap: 8px;
pointer-events: auto;
}
.pill {
padding: 8px 11px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(7, 23, 32, 0.76);
color: #cce0e7;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
backdrop-filter: blur(10px);
}
.pill.off {
color: #a8bcc4;
}
.pill::before {
content: "";
display: inline-block;
width: 6px;
height: 6px;
margin-right: 7px;
border-radius: 50%;
background: var(--mint);
box-shadow: 0 0 9px var(--mint);
}
.pill.off::before {
background: #71858e;
box-shadow: none;
}
.panel {
position: fixed;
z-index: 9;
border: 1px solid var(--line);
border-radius: 16px;
background: var(--panel);
box-shadow: 0 22px 70px rgba(0, 0, 0, 0.36);
backdrop-filter: blur(16px);
}
#controls {
top: 102px;
left: 20px;
width: 326px;
max-height: calc(100vh - 142px);
overflow: auto;
scrollbar-width: thin;
scrollbar-color: #31505c transparent;
}
.panel-section {
padding: 16px;
border-bottom: 1px solid var(--line);
}
.panel-section:last-child { border-bottom: 0; }
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 13px;
color: #dcecf1;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.section-title small {
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.05em;
}
.field-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
label.field-label {
display: block;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.05em;
text-transform: uppercase;
}
select {
width: 100%;
height: 38px;
margin-top: 6px;
padding: 0 30px 0 10px;
border: 1px solid #284653;
border-radius: 9px;
outline: none;
background: #102a38;
color: var(--text);
cursor: pointer;
}
select:focus { border-color: var(--mint); }
.count-row {
display: flex;
align-items: center;
justify-content: space-between;
margin: 14px 0 7px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.count-value {
color: var(--text);
font-size: 13px;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
accent-color: var(--mint);
cursor: pointer;
}
.button {
width: 100%;
min-height: 40px;
margin-top: 10px;
padding: 10px 13px;
border: 1px solid transparent;
border-radius: 10px;
font-size: 11px;
font-weight: 850;
letter-spacing: 0.06em;
text-transform: uppercase;
cursor: pointer;
transition: transform 140ms ease, background 140ms ease, opacity 140ms ease;
}
.button:hover:not(:disabled) { transform: translateY(-1px); }
.button:active:not(:disabled) { transform: translateY(0); }
.button.primary {
background: var(--mint);
color: #06271f;
box-shadow: 0 8px 25px rgba(88, 224, 189, 0.18);
}
.button.secondary {
border-color: #34515e;
background: rgba(18, 46, 59, 0.86);
color: #d9edf2;
}
.button:disabled {
opacity: 0.35;
cursor: not-allowed;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.button-row .button { margin-top: 9px; }
.hint {
margin: 8px 0 0;
color: #839da8;
font-size: 10px;
line-height: 1.45;
}
.hint strong { color: #bcd3db; }
details summary {
color: #dcecf1;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
cursor: pointer;
}
.rules {
margin: 12px 0 0;
padding-left: 17px;
color: #9eb6c0;
font-size: 10px;
line-height: 1.55;
}
.rules li { margin: 7px 0; }
.rules b { color: #d8edf2; }
#statsPanel {
top: 102px;
right: 20px;
width: 292px;
max-height: calc(100vh - 142px);
overflow: auto;
scrollbar-width: thin;
scrollbar-color: #31505c transparent;
}
.population-card {
padding: 13px 0;
border-bottom: 1px solid var(--line);
}
.population-card:first-child { padding-top: 0; }
.pop-head {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 10px;
}
.pop-dot {
width: 8px;
height: 8px;
border-radius: 50%;
box-shadow: 0 0 9px currentColor;
}
.pop-name {
flex: 1;
color: #dbeaf0;
font-size: 11px;
font-weight: 800;
}
.pop-code {
color: #78939e;
font-size: 9px;
letter-spacing: 0.12em;
}
.metric {
display: grid;
grid-template-columns: 62px 1fr;
align-items: center;
gap: 8px;
margin: 7px 0;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.metric strong {
color: #cfe2e8;
font-size: 10px;
font-variant-numeric: tabular-nums;
text-align: right;
}
.allele-bar {
display: flex;
height: 5px;
margin-top: 5px;
overflow: hidden;
border-radius: 999px;
background: #18323f;
}
.allele-bar i {
display: block;
height: 100%;
transition: width 350ms ease;
}
.bar-a { background: var(--cyan); }
.bar-alt { background: var(--amber); }
.allele-legend {
display: flex;
justify-content: space-between;
margin-top: 7px;
color: #78939e;
font-size: 9px;
}
.legend-key {
display: inline-flex;
align-items: center;
gap: 5px;
}
.legend-key i {
width: 7px;
height: 7px;
border-radius: 50%;
}
#eventLog {
display: grid;
gap: 9px;
}
.event {
position: relative;
padding-left: 14px;
color: #9eb5bf;
font-size: 10px;
line-height: 1.45;
}
.event::before {
content: "";
position: absolute;
left: 0;
top: 5px;
width: 5px;
height: 5px;
border-radius: 50%;
background: var(--mint);
}
.event:first-child { color: #d4e7ed; }
.stage-strip {
position: fixed;
z-index: 8;
left: 50%;
bottom: 18px;
display: flex;
align-items: center;
gap: 0;
transform: translateX(-50%);
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(6, 20, 29, 0.84);
box-shadow: 0 14px 40px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(12px);
pointer-events: none;
}
.stage-step {
min-width: 154px;
padding: 10px 15px;
border-right: 1px solid var(--line);
color: #68838e;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.09em;
text-align: center;
text-transform: uppercase;
}
.stage-step:last-child { border-right: 0; }
.stage-step.active {
color: #dff9f4;
background: rgba(88, 224, 189, 0.1);
box-shadow: inset 0 -2px 0 var(--mint);
}
#toast {
position: fixed;
z-index: 20;
left: 50%;
top: 82px;
max-width: 380px;
padding: 10px 15px;
border: 1px solid rgba(255, 180, 92, 0.35);
border-radius: 10px;
background: rgba(34, 27, 19, 0.94);
color: #ffe1b6;
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.3);
font-size: 11px;
opacity: 0;
pointer-events: none;
transform: translate(-50%, -10px);
transition: opacity 180ms ease, transform 180ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
.text-button {
padding: 0;
border: 0;
background: none;
color: #8ca8b2;
font-size: 10px;
font-weight: 700;
cursor: pointer;
}
.text-button:hover { color: var(--mint); }
@media (max-width: 980px) {
#controls { width: 296px; }
#statsPanel { width: 250px; }
.stage-step { min-width: 125px; }
}
@media (max-width: 760px) {
.topbar { top: 13px; left: 14px; right: 14px; }
.subtitle, .top-actions { display: none; }
h1 { font-size: 27px; }
#controls {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 43vh;
}
#statsPanel {
top: 72px;
right: 10px;
width: 205px;
max-height: 30vh;
}
.stage-strip { display: none; }
.panel-section { padding: 13px; }
}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<div id="labels"></div>
<header class="topbar">
<div class="brand">
<div class="eyebrow">Population dynamics / interactive field lab</div>
<h1>Gene Flow <span>Field Lab</span></h1>
<p class="subtitle">Move adults, rebuild offspring pools, and watch neutral alleles spread.</p>
</div>
<div class="top-actions">
<div class="pill">One diploid locus</div>
<div class="pill off">Selection off</div>
</div>
</header>
<section id="controls" class="panel">
<div class="panel-section">
<div class="section-title">
<span>Migration</span>
<small>Adult movement</small>
</div>
<div class="field-grid">
<label class="field-label">
Source population
<select id="sourceSelect"></select>
</label>
<label class="field-label">
Destination
<select id="destinationSelect"></select>
</label>
</div>
<div class="count-row">
<span>Individuals to move</span>
<span id="countValue" class="count-value">3</span>
</div>
<input id="countInput" type="range" min="1" max="6" value="3" />
<button id="migrateButton" class="button primary" type="button">
1 · Move selected adults
</button>
<p class="hint">
Migrants are sampled from the source and move with unchanged alleles.
At least one source adult remains.
</p>
</div>
<div class="panel-section">
<div class="section-title">
<span>Offspring rules</span>
<small>Separate from migration</small>
</div>
<div class="count-row">
<span>Neutral mutation rate / allele</span>
<span id="mutationValue" class="count-value">2.00%</span>
</div>
<input id="mutationInput" type="range" min="0" max="5" step="0.25" value="2" />
<div class="button-row">
<button id="offspringButton" class="button secondary" type="button">
2 · Update pools
</button>
<button id="promoteButton" class="button secondary" type="button" disabled>
3 · Promote
</button>
</div>
<p class="hint">
Each population produces 12 offspring. Parents are sampled uniformly;
mutation is applied only to inherited alleles. No fitness weighting.
</p>
</div>
<div class="panel-section">
<details open>
<summary>Stated neutral rules</summary>
<ol class="rules">
<li><b>Migration:</b> N adults relocate unchanged before reproduction.</li>
<li><b>Reproduction:</b> two parents are sampled uniformly with replacement.</li>
<li><b>Mutation:</b> each inherited allele flips with probability μ.</li>
<li><b>Selection:</b> off; every adult has equal reproductive probability.</li>
<li><b>Drift:</b> random parent and allele sampling can change frequencies.</li>
</ol>
</details>
</div>
<div class="panel-section">
<button id="resetButton" class="text-button" type="button">↺ Reset simulation</button>
</div>
</section>
<aside id="statsPanel" class="panel">
<div class="panel-section">
<div class="section-title">
<span>Population pools</span>
<small id="generationLabel">Generation 1</small>
</div>
<div id="populationStats"></div>
<div class="allele-legend">
<span class="legend-key"><i style="background:var(--cyan)"></i>A</span>
<span class="legend-key"><i style="background:var(--amber)"></i>a</span>
<span class="legend-key"><i style="background:var(--mint)"></i>adult body = population</span>
</div>
</div>
<div class="panel-section">
<div class="section-title">
<span>Event log</span>
<small>Migration ≠ mutation</small>
</div>
<div id="eventLog"></div>
</div>
</aside>
<div class="stage-strip">
<div class="stage-step active">1 · Move adults</div>
<div class="stage-step">2 · Reproduce + mutate</div>
<div class="stage-step">3 · Promote generation</div>
</div>
<div id="toast" role="status" aria-live="polite"></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 TAU = Math.PI * 2;
const POPULATION_Y = 0.43;
const OFFSPRING_PER_POPULATION = 12;
const genotypeColors = {
AA: 0x58d9ff,
Aa: 0xa78bfa,
aa: 0xffb45c
};
const genotypeMaterials = Object.fromEntries(
Object.entries(genotypeColors).map(([key, color]) => [
key,
new THREE.MeshStandardMaterial({
color,
roughness: 0.48,
metalness: 0.08
})
])
);
const renderer = new THREE.WebGLRenderer({
canvas: $("scene"),
antialias: true,
alpha: true
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
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;
const scene = new THREE.Scene();
scene.fog = new THREE.FogExp2(0x071722, 0.017);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const orbit = {
theta: 0,
phi: 0.88,
radius: 25,
target: new THREE.Vector3(0, 0, -0.75)
};
function updateCamera() {
const spherical = new THREE.Spherical(
orbit.radius,
orbit.phi,
orbit.theta
);
camera.position.setFromSpherical(spherical).add(orbit.target);
camera.lookAt(orbit.target);
camera.updateMatrixWorld();
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xbbefff, 0x13232a, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xe9fbff, 3.0);
sun.position.set(-8, 17, 10);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -22;
sun.shadow.camera.right = 22;
sun.shadow.camera.top = 18;
sun.shadow.camera.bottom = -18;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 50;
scene.add(sun);
const rimLight = new THREE.PointLight(0x3ccab6, 22, 32, 2);
rimLight.position.set(0, 9, -9);
scene.add(rimLight);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(70, 70),
new THREE.MeshStandardMaterial({
color: 0x071722,
roughness: 0.94,
metalness: 0.02
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.46;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(56, 28, 0x315563, 0x17323e);
grid.position.y = -0.445;
grid.material.transparent = true;
grid.material.opacity = 0.24;
scene.add(grid);
const populations = [
{
id: "north",
name: "North Shoal",
code: "NS",
color: 0x36d7b0,
pA: 0.82,
x: -6.4,
z: 0.5,
phase: 0.2,
adults: [],
offspring: [],
label: null
},
{
id: "middle",
name: "Middle Reach",
code: "MR",
color: 0x7b86ff,
pA: 0.50,
x: 0,
z: -3.7,
phase: 1.15,
adults: [],
offspring: [],
label: null
},
{
id: "south",
name: "South Delta",
code: "SD",
color: 0xff7d7d,
pA: 0.17,
x: 6.4,
z: 0.5,
phase: 2.1,
adults: [],
offspring: [],
label: null
}
];
const bodyGeometry = new THREE.CylinderGeometry(0.16, 0.22, 0.58, 10);
const headGeometry = new THREE.SphereGeometry(0.18, 14, 10);
const ringGeometry = new THREE.TorusGeometry(0.25, 0.025, 6, 20);
const markerGeometry = new THREE.CylinderGeometry(0.42, 0.42, 0.055, 24);
function makeIsland(pop, index) {
const base = new THREE.Mesh(
new THREE.CylinderGeometry(3.35, 3.58, 0.68, 32),
new THREE.MeshStandardMaterial({
color: 0x102a35,
roughness: 0.86,
metalness: 0.08
})
);
base.position.set(pop.x, -0.02, pop.z);
base.castShadow = true;
base.receiveShadow = true;
scene.add(base);
const top = new THREE.Mesh(
new THREE.CylinderGeometry(3.18, 3.28, 0.13, 32),
new THREE.MeshStandardMaterial({
color: index === 1 ? 0x183744 : 0x16323c,
roughness: 0.8,
metalness: 0.04
})
);
top.position.set(pop.x, 0.355, pop.z);
top.receiveShadow = true;
scene.add(top);
const rim = new THREE.Mesh(
new THREE.TorusGeometry(3.05, 0.035, 8, 80),
new THREE.MeshBasicMaterial({
color: pop.color,
transparent: true,
opacity: 0.48
})
);
rim.rotation.x = Math.PI / 2;
rim.position.set(pop.x, 0.435, pop.z);
scene.add(rim);
const marker = new THREE.Mesh(
markerGeometry,
new THREE.MeshStandardMaterial({
color: pop.color,
emissive: pop.color,
emissiveIntensity: 0.16,
roughness: 0.48
})
);
marker.position.set(pop.x, 0.46, pop.z);
marker.receiveShadow = true;
scene.add(marker);
const label = document.createElement("div");
label.className = "world-label";
$("labels").appendChild(label);
pop.label = label;
}
populations.forEach(makeIsland);
const arcs = new Map();
function makeArc(from, to) {
const start = new THREE.Vector3(from.x, 0.68, from.z);
const end = new THREE.Vector3(to.x, 0.68, to.z);
const midpoint = start.clone().add(end).multiplyScalar(0.5);
const dx = end.x - start.x;
const dz = end.z - start.z;
const length = Math.hypot(dx, dz);
const normalX = -dz / length;
const normalZ = dx / length;
const control = midpoint.clone();
control.x += normalX * 0.85;
control.z += normalZ * 0.85;
control.y = 2.15;
const curve = new THREE.QuadraticBezierCurve3(start, control, end);
const lineMaterial = new THREE.MeshBasicMaterial({
color: 0x477481,
transparent: true,
opacity: 0.24,
depthWrite: false
});
const line = new THREE.Mesh(
new THREE.TubeGeometry(curve, 32, 0.025, 6, false),
lineMaterial
);
scene.add(line);
const arrowMaterial = new THREE.MeshBasicMaterial({
color: 0x477481,
transparent: true,
opacity: 0.46,
depthWrite: false
});
const arrow = new THREE.Mesh(
new THREE.ConeGeometry(0.12, 0.38, 9),
arrowMaterial
);
arrow.position.copy(curve.getPoint(0.82));
const tangent = curve.getTangent(0.82).normalize();
arrow.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
tangent
);
scene.add(arrow);
arcs.set(`${from.id}>${to.id}`, {
line,
arrow,
lineMaterial,
arrowMaterial
});
}
const arcPairs = [
[populations[0], populations[1]],
[populations[1], populations[2]],
[populations[0], populations[2]]
];
arcPairs.forEach(([a, b]) => {
makeArc(a, b);
makeArc(b, a);
});
function highlightArc(fromId, toId, highlighted) {
const arc = arcs.get(`${fromId}>${toId}`);
if (!arc) return;
arc.lineMaterial.color.setHex(highlighted ? 0x68f2d1 : 0x477481);
arc.lineMaterial.opacity = highlighted ? 0.92 : 0.24;
arc.arrowMaterial.color.setHex(highlighted ? 0x68f2d1 : 0x477481);
arc.arrowMaterial.opacity = highlighted ? 1 : 0.46;
}
function resetArcs() {
arcs.forEach(arc => {
arc.lineMaterial.color.setHex(0x477481);
arc.lineMaterial.opacity = 0.24;
arc.arrowMaterial.color.setHex(0x477481);
arc.arrowMaterial.opacity = 0.46;
});
}
let agentId = 1;
function genotypeOf(alleles) {
return alleles[0] === alleles[1]
? alleles[0] + alleles[1]
: "Aa";
}
function createFigure(pop, alleles, isOffspring = false) {
const group = new THREE.Group();
const genotype = genotypeOf(alleles);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: pop.color,
roughness: 0.62,
metalness: 0.08
});
const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
body.position.y = 0.29;
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const head = new THREE.Mesh(headGeometry, genotypeMaterials[genotype]);
head.position.y = 0.73;
head.castShadow = true;
group.add(head);
const ringMaterial = new THREE.MeshBasicMaterial({
color: isOffspring ? 0xdffaff : 0xffd166,
transparent: true,
opacity: isOffspring ? 0.62 : 1,
depthWrite: false
});
const ring = new THREE.Mesh(ringGeometry, ringMaterial);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.025;
ring.visible = isOffspring;
group.add(ring);
scene.add(group);
return {
id: agentId++,
alleles: [...alleles],
genotype,
group,
bodyMaterial,
ring,
ringMaterial,
popId: pop.id,
isOffspring,
immigrant: false
};
}
function destroyAgent(agent) {
if (!agent) return;
scene.remove(agent.group);
agent.bodyMaterial.dispose();
agent.ringMaterial.dispose();
}
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
function adultLocalSlot(pop, index, count) {
let radius;
let angle;
if (count <= 12) {
radius = count <= 6 ? 0.84 + count * 0.018 : 1.18;
angle = (index / count) * TAU + pop.phase;
} else if (index < 12) {
radius = 0.92;
angle = (index / 12) * TAU + pop.phase;
} else {
radius = 1.73;
angle = ((index - 12) / (count - 12)) * TAU + pop.phase + 0.12;
}
return {
x: pop.x + Math.cos(angle) * radius,
z: pop.z + Math.sin(angle) * radius,
angle,
radius
};
}
function offspringLocalSlot(pop, index, count) {
const angle = (index / count) * TAU + pop.phase + 0.16;
const radius = 2.57;
return {
x: pop.x + Math.cos(angle) * radius,
z: pop.z + Math.sin(angle) * radius,
angle,
radius
};
}
function layoutPopulation(pop) {
pop.adults.forEach((agent, index) => {
const slot = adultLocalSlot(pop, index, pop.adults.length);
agent.group.position.set(slot.x, POPULATION_Y, slot.z);
});
}
function initializePopulation(pop) {
const totalAlleles = 12 * 2;
const countA = Math.round(pop.pA * totalAlleles);
const allelePool = [
...Array(countA).fill("A"),
...Array(totalAlleles - countA).fill("a")
];
shuffle(allelePool);
for (let i = 0; i < 12; i++) {
const agent = createFigure(pop, [
allelePool[i * 2],
allelePool[i * 2 + 1]
]);
pop.adults.push(agent);
}
layoutPopulation(pop);
}
function alleleFrequency(agents) {
if (!agents.length) return 0;
let aCount = 0;
for (const agent of agents) {
aCount += agent.alleles.filter(allele => allele === "A").length;
}
return aCount / (agents.length * 2);
}
function formatPercent(value) {
return `${(value * 100).toFixed(1)}%`;
}
function buildStatsCards() {
$("populationStats").innerHTML = populations.map(pop => `
<div class="population-card" id="card-${pop.id}">
<div class="pop-head">
<span class="pop-dot" style="background:#${pop.color.toString(16).padStart(6, "0")};color:#${pop.color.toString(16).padStart(6, "0")}"></span>
<span class="pop-name">${pop.name}</span>
<span class="pop-code">${pop.code}</span>
</div>
<div class="metric">
<span>Adult pool</span>
<strong id="adult-${pop.id}"></strong>
<div class="allele-bar" id="adult-bar-${pop.id}" style="grid-column: 1 / -1">
<i class="bar-a"></i>
<i class="bar-alt"></i>
</div>
</div>
<div class="metric">
<span>Offspring</span>
<strong id="offspring-${pop.id}"></strong>
<div class="allele-bar" id="offspring-bar-${pop.id}" style="grid-column: 1 / -1">
<i class="bar-a"></i>
<i class="bar-alt"></i>
</div>
</div>
</div>
`).join("");
}
function updateStats() {
$("generationLabel").textContent = `Generation ${generation}`;
for (const pop of populations) {
const adultP = alleleFrequency(pop.adults);
const offspringP = pop.offspring.length
? alleleFrequency(pop.offspring)
: null;
$(`adult-${pop.id}`).textContent =
`${pop.adults.length} · p(A) ${adultP.toFixed(2)}`;
const adultBar = $(`adult-bar-${pop.id}`);
adultBar.children[0].style.width = `${adultP * 100}%`;
adultBar.children[1].style.width = `${(1 - adultP) * 100}%`;
$(`offspring-${pop.id}`).textContent = offspringP === null
? "Not updated"
: `${pop.offspring.length} · p(A) ${offspringP.toFixed(2)}`;
const offspringBar = $(`offspring-bar-${pop.id}`);
offspringBar.style.opacity = offspringP === null ? "0.2" : "1";
offspringBar.children[0].style.width = `${(offspringP ?? 0) * 100}%`;
offspringBar.children[1].style.width = `${(1 - (offspringP ?? 0)) * 100}%`;
pop.label.innerHTML = `
<span class="wl-name">${pop.name}</span>
<span class="wl-meta">${pop.adults.length} adults · p(A) ${adultP.toFixed(2)}</span>
`;
}
}
let toastTimer = null;
function toast(message) {
$("toast").textContent = message;
$("toast").classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => $("toast").classList.remove("show"), 2600);
}
function logEvent(message) {
const item = document.createElement("div");
item.className = "event";
item.textContent = message;
$("eventLog").prepend(item);
while ($("eventLog").children.length > 6) {
$("eventLog").lastElementChild.remove();
}
}
function setStage(stage) {
document.querySelectorAll(".stage-step").forEach((element, index) => {
element.classList.toggle("active", index === stage);
});
}
let generation = 1;
let mutationRate = 0.02;
let migrationAnimating = false;
let migrationAnimations = [];
function clearOffspring() {
for (const pop of populations) {
for (const child of pop.offspring) destroyAgent(child);
pop.offspring = [];
}
}
function refreshButtons() {
const source = populations.find(p => p.id === $("sourceSelect").value);
$("migrateButton").disabled =
migrationAnimating || !source || source.adults.length < 2;
$("offspringButton").disabled =
migrationAnimating || populations.some(pop => pop.adults.length === 0);
$("promoteButton").disabled =
migrationAnimating || !populations.every(pop => pop.offspring.length > 0);
}
function runMigration() {
if (migrationAnimating) return;
const source = populations.find(p => p.id === $("sourceSelect").value);
const destination = populations.find(p => p.id === $("destinationSelect").value);
const requested = Number($("countInput").value);
const count = Math.min(requested, source.adults.length - 1);
if (count < 1) {
toast("At least one adult must remain in the source population.");
return;
}
clearOffspring();
const selected = shuffle([...source.adults]).slice(0, count);
const migrantSet = new Set(selected.map(agent => agent.id));
source.adults = source.adults.filter(agent => !migrantSet.has(agent.id));
for (const migrant of selected) {
migrant.popId = destination.id;
destination.adults.push(migrant);
}
const targets = new Map();
source.adults.forEach((agent, index) => {
const slot = adultLocalSlot(source, index, source.adults.length);
targets.set(agent.id, slot);
});
destination.adults.forEach((agent, index) => {
const slot = adultLocalSlot(destination, index, destination.adults.length);
targets.set(agent.id, slot);
});
const affected = [...source.adults, ...destination.adults];
migrationAnimations = affected.map(agent => {
const slot = targets.get(agent.id);
return {
agent,
start: agent.group.position.clone(),
end: new THREE.Vector3(slot.x, POPULATION_Y, slot.z),
migrant: migrantSet.has(agent.id),
arcHeight: migrantSet.has(agent.id) ? 3.8 : 0.3,
startTime: performance.now(),
duration: migrantSet.has(agent.id) ? 1350 : 950
};
});
migrationAnimating = true;
highlightArc(source.id, destination.id, true);
setStage(0);
refreshButtons();
updateStats();
logEvent(
`${count} adult${count === 1 ? "" : "s"} selected from ${source.name} ` +
`will move to ${destination.name}; alleles are unchanged during migration.`
);
}
function finishMigration() {
const source = populations.find(p => p.id === $("sourceSelect").value);
const destination = populations.find(p => p.id === $("destinationSelect").value);
for (const animation of migrationAnimations) {
const agent = animation.agent;
agent.group.position.copy(animation.end);
if (animation.migrant) {
agent.bodyMaterial.color.setHex(destination.color);
agent.immigrant = true;
agent.ring.visible = true;
agent.ringMaterial.color.setHex(0xffd166);
agent.ringMaterial.opacity = 1;
}
}
migrationAnimations = [];
migrationAnimating = false;
setStage(1);
refreshButtons();
updateStats();
logEvent(
`Migration complete: ${source.name} → ${destination.name}. ` +
`The destination gene pool now includes the migrants.`
);
toast("Migration complete. Now update the offspring pools.");
}
function updateMigrationAnimations(now) {
if (!migrationAnimating) return;
let allComplete = true;
for (const animation of migrationAnimations) {
const linear = Math.min(
1,
Math.max(0, (now - animation.startTime) / animation.duration)
);
const eased = linear * linear * (3 - 2 * linear);
animation.agent.group.position.x =
THREE.MathUtils.lerp(animation.start.x, animation.end.x, eased);
animation.agent.group.position.z =
THREE.MathUtils.lerp(animation.start.z, animation.end.z, eased);
animation.agent.group.position.y =
THREE.MathUtils.lerp(animation.start.y, animation.end.y, eased) +
Math.sin(linear * Math.PI) * animation.arcHeight;
if (linear < 1) allComplete = false;
}
if (allComplete) finishMigration();
}
function sampleParentAllele(agent) {
return agent.alleles[Math.floor(Math.random() * 2)];
}
function mutateAllele(allele) {
if (Math.random() >= mutationRate) return allele;
return allele === "A" ? "a" : "A";
}
function updateOffspringPools() {
if (migrationAnimating) return;
clearOffspring();
let mutationCount = 0;
for (const pop of populations) {
if (!pop.adults.length) continue;
for (let i = 0; i < OFFSPRING_PER_POPULATION; i++) {
const parentA = pop.adults[Math.floor(Math.random() * pop.adults.length)];
const parentB = pop.adults[Math.floor(Math.random() * pop.adults.length)];
const inherited = [
sampleParentAllele(parentA),
sampleParentAllele(parentB)
];
const alleles = inherited.map(allele => {
const mutated = mutateAllele(allele);
if (mutated !== allele) mutationCount++;
return mutated;
});
const child = createFigure(pop, alleles, true);
const slot = offspringLocalSlot(
pop,
i,
OFFSPRING_PER_POPULATION
);
child.group.position.set(slot.x, POPULATION_Y, slot.z);
child.group.scale.setScalar(0.58);
pop.offspring.push(child);
}
}
setStage(2);
refreshButtons();
updateStats();
const totalOffspring = populations.reduce(
(sum, pop) => sum + pop.offspring.length,
0
);
logEvent(
`Built ${totalOffspring} offspring. Parents were sampled uniformly; ` +
`${mutationCount} inherited alleles mutated at μ=${formatPercent(mutationRate)}.`
);
logEvent("Selection remained off; mutation was applied only after inheritance.");
}
function promoteOffspring() {
if (!populations.every(pop => pop.offspring.length > 0)) return;
for (const pop of populations) {
for (const adult of pop.adults) destroyAgent(adult);
pop.adults = [];
for (const child of pop.offspring) {
child.isOffspring = false;
child.immigrant = false;
child.popId = pop.id;
child.group.scale.setScalar(1);
child.bodyMaterial.color.setHex(pop.color);
child.ring.visible = false;
pop.adults.push(child);
}
pop.offspring = [];
layoutPopulation(pop);
}
generation++;
setStage(0);
refreshButtons();
updateStats();
logEvent(
`Generation ${generation} promoted. Population sizes reset to 12 ` +
`while retaining the sampled and mutated allele frequencies.`
);
}
function resetSimulation() {
migrationAnimating = false;
migrationAnimations = [];
generation = 1;
for (const pop of populations) {
pop.adults.forEach(destroyAgent);
pop.offspring.forEach(destroyAgent);
pop.adults = [];
pop.offspring = [];
initializePopulation(pop);
}
$("eventLog").innerHTML = "";
resetArcs();
setStage(0);
refreshButtons();
updateStats();
logEvent(
"Baseline restored: 12 adults per population, no migration applied yet."
);
}
function initializeSelects() {
const options = populations.map(pop =>
`<option value="${pop.id}">${pop.name}</option>`
).join("");
$("sourceSelect").innerHTML = options;
$("destinationSelect").innerHTML = options;
$("sourceSelect").value = "north";
$("destinationSelect").value = "middle";
syncDestinationOptions();
}
function syncDestinationOptions() {
const sourceId = $("sourceSelect").value;
[...$("destinationSelect").options].forEach(option => {
option.disabled = option.value === sourceId;
});
if ($("destinationSelect").value === sourceId) {
$("destinationSelect").selectedIndex = [...$("destinationSelect").options]
.findIndex(option => !option.disabled);
}
refreshButtons();
}
initializeSelects();
buildStatsCards();
populations.forEach(initializePopulation);
updateStats();
refreshButtons();
setStage(0);
logEvent(
"Baseline: 12 adults per population. A = cyan, a = amber; mixed genotypes are violet."
);
$("sourceSelect").addEventListener("change", syncDestinationOptions);
$("countInput").addEventListener("input", () => {
$("countValue").textContent = $("countInput").value;
});
$("mutationInput").addEventListener("input", () => {
mutationRate = Number($("mutationInput").value) / 100;
$("mutationValue").textContent = formatPercent(mutationRate);
});
$("mutationInput").addEventListener("change", () => {
if (populations.some(pop => pop.offspring.length)) {
clearOffspring();
setStage(0);
updateStats();
refreshButtons();
logEvent(
`Mutation rate changed to μ=${formatPercent(mutationRate)}; ` +
`the previous offspring preview was cleared.`
);
}
});
$("migrateButton").addEventListener("click", runMigration);
$("offspringButton").addEventListener("click", updateOffspringPools);
$("promoteButton").addEventListener("click", promoteOffspring);
$("resetButton").addEventListener("click", resetSimulation);
// Direct orbit controls: no addons or example modules are used.
let dragging = false;
let lastX = 0;
let lastY = 0;
$("scene").addEventListener("pointerdown", event => {
dragging = true;
lastX = event.clientX;
lastY = event.clientY;
$("scene").setPointerCapture(event.pointerId);
});
$("scene").addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - lastX;
const dy = event.clientY - lastY;
lastX = event.clientX;
lastY = event.clientY;
orbit.theta -= dx * 0.006;
orbit.phi = THREE.MathUtils.clamp(
orbit.phi - dy * 0.005,
0.38,
1.28
);
});
function endDrag(event) {
dragging = false;
if ($("scene").hasPointerCapture(event.pointerId)) {
$("scene").releasePointerCapture(event.pointerId);
}
}
$("scene").addEventListener("pointerup", endDrag);
$("scene").addEventListener("pointercancel", endDrag);
$("scene").addEventListener("wheel", event => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius + event.deltaY * 0.018,
17,
37
);
}, { passive: false });
$("scene").addEventListener("dblclick", () => {
orbit.theta = 0;
orbit.phi = 0.88;
orbit.radius = 25;
});
function updateWorldLabels() {
for (const pop of populations) {
const projected = new THREE.Vector3(pop.x, 1.65, pop.z).project(camera);
const visible = projected.z > -1 && projected.z < 1;
pop.label.style.display = visible ? "block" : "none";
if (visible) {
pop.label.style.left =
`${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
pop.label.style.top =
`${(-projected.y * 0.5 + 0.5) * window.innerHeight}px`;
}
}
}
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
}
window.addEventListener("resize", resize);
function animate(now) {
requestAnimationFrame(animate);
updateMigrationAnimations(now);
updateCamera();
updateWorldLabels();
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```