Prompt specification
Build or customize the Three.js 3D scene "Migration-rate frequency 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: Migration-rate frequency explorer
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/migration-rate-frequency-explorer-x0912
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring gene flow between populations. Provide a toy migration-rate control between two populations; plot their changing variant frequencies and show that direction and population size affect the outcome. Voxel style.
Working Three.js Starter (migration-rate-frequency-explorer-x0912):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Gene Flow Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #071019;
--panel: rgba(8, 18, 28, 0.91);
--panel-2: rgba(13, 28, 41, 0.94);
--border: #294356;
--muted: #8ca7b9;
--text: #eaf6ff;
--cyan: #66d9ff;
--orange: #ff8a65;
--gold: #ffd166;
--green: #72e0a4;
--shadow: #02070c;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,
"Liberation Mono", monospace;
}
button,
input {
font: inherit;
}
#stage {
position: fixed;
inset: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#stage canvas:active {
cursor: grabbing;
}
.brand {
position: fixed;
z-index: 10;
top: 20px;
left: 22px;
max-width: 390px;
pointer-events: none;
}
.eyebrow {
color: var(--green);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
.brand h1 {
margin: 7px 0 4px;
font-size: clamp(24px, 3vw, 38px);
line-height: 1;
letter-spacing: -0.05em;
text-shadow: 4px 4px 0 var(--shadow);
}
.brand p {
margin: 8px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.panel {
position: fixed;
z-index: 20;
background: var(--panel);
border: 1px solid var(--border);
border-radius: 4px;
box-shadow: 8px 8px 0 rgba(2, 7, 12, 0.72);
backdrop-filter: blur(12px);
}
#controls {
top: 125px;
left: 22px;
width: 342px;
max-height: calc(100vh - 148px);
overflow-y: auto;
padding: 16px;
scrollbar-width: thin;
scrollbar-color: var(--border) transparent;
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 15px;
}
.panel-heading h2,
.panel-heading h3 {
margin: 0;
font-size: 13px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.badge {
padding: 5px 7px;
border: 1px solid #3d665d;
background: rgba(114, 224, 164, 0.08);
color: var(--green);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
}
.badge.paused {
color: var(--gold);
border-color: #6d5b2d;
background: rgba(255, 209, 102, 0.08);
}
.control {
display: block;
margin: 0 0 17px;
}
.control > span {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 8px;
color: #d8e8f3;
font-size: 12px;
font-weight: 700;
}
output {
min-width: 54px;
padding: 3px 6px;
border: 1px solid var(--border);
background: #0a1824;
color: var(--gold);
text-align: center;
font-size: 12px;
}
input[type="range"] {
width: 100%;
height: 8px;
margin: 0;
border: 1px solid #345267;
border-radius: 0;
background: #0b1a27;
accent-color: var(--gold);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 12px;
height: 18px;
border: 1px solid #08131d;
border-radius: 0;
background: var(--gold);
box-shadow: 2px 2px 0 #02070c;
appearance: none;
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 18px;
border: 1px solid #08131d;
border-radius: 0;
background: var(--gold);
box-shadow: 2px 2px 0 #02070c;
}
.small {
display: block;
margin-top: 7px;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.section-label {
margin: 19px 0 9px;
color: #8ca7b9;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.segment {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.segment button,
.actions button {
min-height: 38px;
border: 1px solid var(--border);
border-radius: 0;
background: #0b1a27;
color: #bcd2df;
cursor: pointer;
transition:
background 120ms ease,
color 120ms ease,
transform 120ms ease;
}
.segment button:hover,
.actions button:hover {
border-color: #5b8097;
color: white;
}
.segment button:active,
.actions button:active {
transform: translateY(2px);
}
.segment button.active {
border-color: var(--cyan);
background: rgba(102, 217, 255, 0.13);
color: var(--cyan);
box-shadow: inset 3px 0 0 var(--cyan);
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 19px;
}
.actions .primary {
border-color: #9b7c32;
background: var(--gold);
color: #13202a;
font-weight: 900;
}
.insight {
margin-top: 15px;
padding: 12px;
border-left: 4px solid var(--gold);
background: rgba(255, 209, 102, 0.06);
color: #c5d6e0;
font-size: 11px;
line-height: 1.55;
}
.insight strong {
color: #fff2bd;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 8px 15px;
margin-top: 15px;
padding-top: 13px;
border-top: 1px solid var(--border);
color: var(--muted);
font-size: 10px;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 10px;
height: 10px;
border: 1px solid rgba(255, 255, 255, 0.28);
box-shadow: 2px 2px 0 #02070c;
}
.swatch.variant {
background: var(--gold);
}
.swatch.ancestral-a {
background: #8bd8e8;
}
.swatch.ancestral-b {
background: #c3b2e8;
}
details {
margin-top: 14px;
border-top: 1px solid var(--border);
padding-top: 12px;
}
summary {
color: #a9c2d1;
cursor: pointer;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.formula {
margin-top: 10px;
color: var(--muted);
font-size: 10px;
line-height: 1.7;
}
.formula code {
display: block;
color: #c8e9f7;
overflow-wrap: anywhere;
}
#metrics {
top: 20px;
right: 22px;
width: 300px;
padding: 12px;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 7px;
}
.metric {
min-width: 0;
padding: 10px 8px;
border: 1px solid var(--border);
background: var(--panel-2);
}
.metric span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
}
.metric strong {
display: block;
margin: 5px 0 2px;
font-size: 20px;
line-height: 1;
}
.metric small {
color: #748fa1;
font-size: 8px;
}
.metric.a strong {
color: var(--cyan);
}
.metric.b strong {
color: var(--orange);
}
.flow-stat {
display: flex;
justify-content: space-between;
gap: 10px;
margin-top: 8px;
padding: 8px 3px 0;
color: var(--muted);
font-size: 10px;
}
.flow-stat b {
color: var(--gold);
}
#graph-panel {
right: 22px;
bottom: 22px;
width: 560px;
padding: 13px 14px 10px;
}
.graph-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 7px;
}
.graph-heading h2 {
margin: 0;
font-size: 12px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.graph-legend {
display: flex;
gap: 13px;
color: var(--muted);
font-size: 9px;
}
.graph-legend span::before {
content: "";
display: inline-block;
width: 14px;
height: 3px;
margin-right: 5px;
vertical-align: middle;
background: currentColor;
}
.graph-legend .a {
color: var(--cyan);
}
.graph-legend .b {
color: var(--orange);
}
#plot {
display: block;
width: 100%;
height: 190px;
overflow: visible;
}
#plot .grid-line {
stroke: #203747;
stroke-width: 1;
shape-rendering: crispEdges;
}
#plot .grid-label {
fill: #708b9d;
font: 9px ui-monospace, monospace;
}
#plot .plot-line {
fill: none;
stroke-width: 3;
stroke-linecap: square;
stroke-linejoin: bevel;
vector-effect: non-scaling-stroke;
}
#plot #line-a {
stroke: var(--cyan);
}
#plot #line-b {
stroke: var(--orange);
}
#plot circle {
stroke: #071019;
stroke-width: 2;
}
#dot-a {
fill: var(--cyan);
}
#dot-b {
fill: var(--orange);
}
#scene-hint {
position: fixed;
z-index: 8;
left: 50%;
bottom: 16px;
transform: translateX(-50%);
padding: 7px 10px;
border: 1px solid #233e50;
background: rgba(5, 13, 20, 0.76);
color: #7895a8;
font-size: 9px;
letter-spacing: 0.08em;
pointer-events: none;
}
#loading {
position: fixed;
z-index: 100;
inset: 0;
display: grid;
place-items: center;
background: var(--bg);
color: var(--green);
font-size: 13px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
@media (max-width: 1050px) {
#metrics {
width: 255px;
}
#graph-panel {
width: 480px;
}
}
@media (max-width: 760px) {
.brand {
top: 12px;
left: 12px;
}
.brand h1 {
font-size: 24px;
}
.brand p {
display: none;
}
#controls {
top: 72px;
left: 12px;
width: calc(100vw - 24px);
max-height: 43vh;
padding: 12px;
}
#metrics {
display: none;
}
#graph-panel {
right: 12px;
bottom: 12px;
width: calc(100vw - 24px);
padding: 10px;
}
#plot {
height: 145px;
}
#scene-hint {
display: none;
}
}
</style>
</head>
<body>
<div id="stage"></div>
<div id="loading">Loading voxel population model…</div>
<header class="brand">
<div class="eyebrow">Allele flow lab / two-population model</div>
<h1>Gene flow, voxelized.</h1>
<p>
Change the direction, migration rate, and population sizes.
Watch variant frequencies and random drift reshape both populations.
</p>
</header>
<aside id="controls" class="panel">
<div class="panel-heading">
<h2>Migration controls</h2>
<span id="run-state" class="badge">Running</span>
</div>
<label class="control" for="migration">
<span>
Migration rate
<output id="migration-out">12%</output>
</span>
<input id="migration" type="range" min="0" max="0.30" step="0.01" value="0.12">
<small class="small">
Fraction of the source population emigrating each generation.
</small>
</label>
<div class="section-label">Flow direction</div>
<div class="segment" role="group" aria-label="Migration direction">
<button type="button" data-direction="AB" class="active" aria-pressed="true">
A → B
</button>
<button type="button" data-direction="BA" aria-pressed="false">
B → A
</button>
</div>
<label class="control" for="size-a" style="margin-top:17px">
<span>
Population A size
<output id="size-a-out">80</output>
</span>
<input id="size-a" type="range" min="20" max="140" step="10" value="80">
</label>
<label class="control" for="size-b">
<span>
Population B size
<output id="size-b-out">40</output>
</span>
<input id="size-b" type="range" min="20" max="140" step="10" value="40">
</label>
<div class="actions">
<button id="run" type="button" class="primary">Ⅱ Pause</button>
<button id="reset" type="button">Reset alleles</button>
</div>
<div id="insight" class="insight" aria-live="polite"></div>
<div class="legend" aria-label="Population color legend">
<span><i class="swatch variant"></i>Variant allele</span>
<span><i class="swatch ancestral-a"></i>A ancestral</span>
<span><i class="swatch ancestral-b"></i>B ancestral</span>
</div>
<details>
<summary>Toy model equations</summary>
<div class="formula">
<code>M = m × Nsource</code>
<code>x = min(1, M ÷ Ndestination)</code>
<code>pdestination ← (1−x)pdestination + x psource</code>
<code>drift variance = p(1−p) ÷ (2N)</code>
<p>
The source population supplies migrants. A larger source sends more
migrants; a smaller recipient is replaced more quickly. Small
populations also experience stronger random drift.
</p>
</div>
</details>
</aside>
<aside id="metrics" class="panel">
<div class="metric-grid">
<div class="metric a">
<span>POP A</span>
<strong id="metric-a">68.0%</strong>
<small>variant frequency</small>
</div>
<div class="metric b">
<span>POP B</span>
<strong id="metric-b">32.0%</strong>
<small>variant frequency</small>
</div>
<div class="metric">
<span>GAP</span>
<strong id="metric-gap">36.0%</strong>
<small>|pA − pB|</small>
</div>
</div>
<div class="flow-stat">
<span id="flow-direction">A → B</span>
<span><b id="migrant-count">10</b> migrants/gen</span>
</div>
</aside>
<section id="graph-panel" class="panel">
<div class="graph-heading">
<h2>Variant frequency over time</h2>
<div class="graph-legend">
<span class="a">A</span>
<span class="b">B</span>
<span id="generation">GEN 0</span>
</div>
</div>
<svg id="plot" viewBox="0 0 560 220" role="img"
aria-label="Line plot of variant frequencies in populations A and B">
<g id="grid"></g>
<path id="line-a" class="plot-line"></path>
<path id="line-b" class="plot-line"></path>
<circle id="dot-a" r="4"></circle>
<circle id="dot-b" r="4"></circle>
</svg>
</section>
<div id="scene-hint">DRAG TO ORBIT · SCROLL TO ZOOM · DOUBLE-CLICK TO RESET VIEW</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Toy population model
// -------------------------------------------------------------------------
const $ = (id) => document.getElementById(id);
const clamp = (v, min, max) => Math.max(min, Math.min(max, v));
const state = {
pA: 0.68,
pB: 0.32,
NA: 80,
NB: 40,
migration: 0.12,
direction: "AB",
running: true,
generation: 0
};
let historyA = [state.pA];
let historyB = [state.pB];
function createRng(seed) {
let a = seed >>> 0;
return function () {
a += 0x6d2b79f5;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
let rng = createRng(0x4a17b3);
function gaussian() {
const u = Math.max(1e-9, rng());
const v = rng();
return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
}
function drift(p, n) {
const sd = Math.sqrt((p * (1 - p)) / (2 * n));
return clamp(p + gaussian() * sd, 0, 1);
}
function migrationDetails() {
const sourceIsA = state.direction === "AB";
const sourceN = sourceIsA ? state.NA : state.NB;
const destinationN = sourceIsA ? state.NB : state.NA;
const migrantCount = Math.round(state.migration * sourceN);
const replacement = Math.min(1, migrantCount / destinationN);
return {
sourceIsA,
sourceN,
destinationN,
migrantCount,
replacement
};
}
function stepModel() {
const d = migrationDetails();
let pA = state.pA;
let pB = state.pB;
// Migration occurs before drift.
if (d.sourceIsA) {
pB = (1 - d.replacement) * pB + d.replacement * pA;
} else {
pA = (1 - d.replacement) * pA + d.replacement * pB;
}
state.pA = drift(pA, state.NA);
state.pB = drift(pB, state.NB);
state.generation += 1;
historyA.push(state.pA);
historyB.push(state.pB);
if (historyA.length > 120) {
historyA.shift();
historyB.shift();
}
refreshScene();
renderGraph();
}
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const stage = $("stage");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071019);
scene.fog = new THREE.Fog(0x071019, 25, 53);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
stage.appendChild(renderer.domElement);
const camera = new THREE.OrthographicCamera(-10, 10, 8, -8, 0.1, 100);
const cameraTarget = new THREE.Vector3(0, 0.35, 0);
let cameraYaw = 0.57;
let cameraPitch = 0.66;
let cameraZoom = 1;
function updateCamera() {
const distance = 30;
camera.position.set(
cameraTarget.x +
Math.sin(cameraYaw) * Math.cos(cameraPitch) * distance,
cameraTarget.y + Math.sin(cameraPitch) * distance,
cameraTarget.z +
Math.cos(cameraYaw) * Math.cos(cameraPitch) * distance
);
camera.lookAt(cameraTarget);
camera.zoom = cameraZoom;
camera.updateProjectionMatrix();
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
const viewHeight = Math.max(13.5, 18 / aspect);
camera.left = (-viewHeight * aspect) / 2;
camera.right = (viewHeight * aspect) / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
}
window.addEventListener("resize", resize);
const hemisphere = new THREE.HemisphereLight(
0xa9e5ff,
0x111521,
2.1
);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffffff, 3.1);
sun.position.set(-8, 15, 10);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -15;
sun.shadow.camera.right = 15;
sun.shadow.camera.top = 12;
sun.shadow.camera.bottom = -12;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 40;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x438dff, 1.6);
rim.position.set(10, 5, -10);
scene.add(rim);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(70, 70),
new THREE.MeshStandardMaterial({
color: 0x09141d,
roughness: 1,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.78;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(60, 60, 0x1b3a4b, 0x102733);
grid.position.y = -0.765;
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
const ISLAND_X = 4.7;
const TILE_COUNT = 12;
const TILE_SPACING = 0.52;
function hash01(value) {
const x = Math.sin(value * 127.1 + 311.7) * 43758.5453123;
return x - Math.floor(x);
}
function createIsland(centerX, topColor, lowerColor) {
const group = new THREE.Group();
group.position.x = centerX;
const tileGeometry = new THREE.BoxGeometry(
TILE_SPACING,
0.34,
TILE_SPACING
);
const topMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.82,
metalness: 0.04
});
const lowerMaterial = new THREE.MeshStandardMaterial({
color: lowerColor,
roughness: 0.9,
metalness: 0
});
const top = new THREE.InstancedMesh(
tileGeometry,
topMaterial,
TILE_COUNT * TILE_COUNT
);
const lower = new THREE.InstancedMesh(
tileGeometry,
lowerMaterial,
TILE_COUNT * TILE_COUNT
);
top.castShadow = true;
top.receiveShadow = true;
lower.castShadow = true;
lower.receiveShadow = true;
const dummy = new THREE.Object3D();
const baseColor = new THREE.Color(topColor);
let index = 0;
for (let row = 0; row < TILE_COUNT; row++) {
for (let col = 0; col < TILE_COUNT; col++) {
const x = (col - (TILE_COUNT - 1) / 2) * TILE_SPACING;
const z = (row - (TILE_COUNT - 1) / 2) * TILE_SPACING;
const edge =
row === 0 ||
col === 0 ||
row === TILE_COUNT - 1 ||
col === TILE_COUNT - 1;
dummy.position.set(x, -0.25, z);
dummy.updateMatrix();
top.setMatrixAt(index, dummy.matrix);
const color = baseColor.clone();
color.offsetHSL(0, 0, (hash01(index + 17) - 0.5) * 0.08);
if (edge) color.offsetHSL(0, 0, -0.05);
top.setColorAt(index, color);
dummy.position.set(x, -0.59, z);
dummy.updateMatrix();
lower.setMatrixAt(index, dummy.matrix);
index++;
}
}
top.instanceMatrix.needsUpdate = true;
top.instanceColor.needsUpdate = true;
lower.instanceMatrix.needsUpdate = true;
group.add(lower, top);
scene.add(group);
return group;
}
createIsland(-ISLAND_X, 0x2a596d, 0x173746);
createIsland(ISLAND_X, 0x653c51, 0x3d2639);
const personGeometry = new THREE.BoxGeometry(0.25, 0.46, 0.25);
const personMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.52,
metalness: 0.04
});
function createPopulation(centerX) {
const mesh = new THREE.InstancedMesh(
personGeometry,
personMaterial,
144
);
mesh.position.x = centerX;
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.frustumCulled = false;
scene.add(mesh);
return mesh;
}
const populationA = createPopulation(-ISLAND_X);
const populationB = createPopulation(ISLAND_X);
const VARIANT_COLOR = 0xffd166;
const ANCESTRAL_A = 0x8bd8e8;
const ANCESTRAL_B = 0xc3b2e8;
function updatePopulationMesh(mesh, p, n, ancestralColor, seed) {
const rows = Math.ceil(Math.sqrt(n));
const cols = Math.ceil(n / rows);
const dummy = new THREE.Object3D();
const order = Array.from({ length: n }, (_, i) => i);
order.sort((a, b) => hash01(a + seed) - hash01(b + seed));
const variantCount = Math.round(p * n);
const variantIndices = new Set(order.slice(0, variantCount));
for (let i = 0; i < n; i++) {
const row = Math.floor(i / cols);
const col = i % cols;
const rowCount = Math.min(cols, n - row * cols);
const x = (col - (rowCount - 1) / 2) * 0.43;
const z = (row - (rows - 1) / 2) * 0.43;
const heightScale = 0.88 + hash01(i + seed * 3) * 0.22;
dummy.position.set(x, 0.18 * heightScale, z);
dummy.scale.set(1, heightScale, 1);
dummy.updateMatrix();
mesh.setMatrixAt(i, dummy.matrix);
mesh.setColorAt(
i,
new THREE.Color(
variantIndices.has(i) ? VARIANT_COLOR : ancestralColor
)
);
}
mesh.count = n;
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
}
function createLabel(initialText, accent) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.generateMipmaps = false;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(4.1, 1.02, 1);
function update(text) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(5, 14, 22, 0.88)";
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = accent;
context.fillRect(0, 0, 9, canvas.height);
context.strokeStyle = "rgba(120, 170, 195, 0.5)";
context.lineWidth = 3;
context.strokeRect(2, 2, canvas.width - 4, canvas.height - 4);
context.fillStyle = "#eef8ff";
context.font = "700 37px ui-monospace, monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2 + 4, canvas.height / 2);
texture.needsUpdate = true;
}
update(initialText);
return { sprite, update };
}
const labelA = createLabel("POP A", "#66d9ff");
labelA.sprite.position.set(-ISLAND_X, 1.1, -3.15);
scene.add(labelA.sprite);
const labelB = createLabel("POP B", "#ff8a65");
labelB.sprite.position.set(ISLAND_X, 1.1, -3.15);
scene.add(labelB.sprite);
const flowLabel = createLabel("A → B", "#ffd166");
flowLabel.sprite.position.set(0, 4.55, 0);
flowLabel.sprite.scale.set(2.35, 0.59, 1);
scene.add(flowLabel.sprite);
// Voxel dots trace the migration path.
const pathDots = [];
const pathDotGeometry = new THREE.BoxGeometry(0.11, 0.11, 0.11);
const pathDotMaterial = new THREE.MeshStandardMaterial({
color: 0x8ceaff,
emissive: 0x163a49,
transparent: true,
opacity: 0.32,
roughness: 0.7
});
for (let i = 0; i < 31; i++) {
const dot = new THREE.Mesh(pathDotGeometry, pathDotMaterial);
scene.add(dot);
pathDots.push(dot);
}
const migrants = [];
const migrantGeometry = new THREE.BoxGeometry(0.25, 0.25, 0.25);
for (let i = 0; i < 18; i++) {
const migrant = new THREE.Mesh(
migrantGeometry,
new THREE.MeshStandardMaterial({
color: 0xffd166,
roughness: 0.4,
metalness: 0.05
})
);
migrant.castShadow = true;
migrant.userData.offset = i / 18;
scene.add(migrant);
migrants.push(migrant);
}
let flowCurve;
function rebuildFlowPath() {
const sourceX = state.direction === "AB" ? -ISLAND_X : ISLAND_X;
const destinationX = -sourceX;
flowCurve = new THREE.CatmullRomCurve3(
[
new THREE.Vector3(sourceX, 0.75, 0),
new THREE.Vector3(sourceX, 3.2, 0),
new THREE.Vector3(0, 4.15, 0),
new THREE.Vector3(destinationX, 3.2, 0),
new THREE.Vector3(destinationX, 0.75, 0)
],
false,
"catmullrom",
0.5
);
pathDots.forEach((dot, i) => {
const t = i / (pathDots.length - 1);
dot.position.copy(flowCurve.getPointAt(t));
});
const directionText = state.direction === "AB" ? "A → B" : "B → A";
flowLabel.update(directionText);
}
let flowTime = 0;
function animateMigrants(delta) {
if (state.running && state.migration > 0) {
flowTime += delta * (0.45 + state.migration * 3.0);
}
const visibleCount = Math.ceil(state.migration * 18);
const sourceIsA = state.direction === "AB";
const sourceP = sourceIsA ? state.pA : state.pB;
const ancestral = sourceIsA ? ANCESTRAL_A : ANCESTRAL_B;
migrants.forEach((migrant, i) => {
migrant.visible = i < visibleCount && state.migration > 0;
if (!migrant.visible) return;
const t =
(flowTime * (0.09 + state.migration * 0.24) +
migrant.userData.offset) %
1;
migrant.position.copy(flowCurve.getPointAt(t));
migrant.rotation.set(
flowTime * 1.4 + i,
flowTime * 1.8 + i * 0.3,
flowTime * 1.1
);
migrant.material.color.setHex(
hash01(i + (sourceIsA ? 10 : 90)) < sourceP
? VARIANT_COLOR
: ancestral
);
});
}
// Direct camera controls: no addons or example imports.
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.pointerType === "mouse" && event.button !== 0) return;
dragging = true;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
cameraYaw -= dx * 0.006;
cameraPitch = clamp(cameraPitch + dy * 0.005, 0.28, 1.25);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
updateCamera();
});
function endDrag(event) {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraZoom = clamp(cameraZoom * Math.exp(-event.deltaY * 0.001), 0.7, 1.8);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
cameraYaw = 0.57;
cameraPitch = 0.66;
cameraZoom = 1;
updateCamera();
});
// -------------------------------------------------------------------------
// SVG plot
// -------------------------------------------------------------------------
const SVG_NS = "http://www.w3.org/2000/svg";
const gridGroup = $("grid");
const plotWidth = 560;
const plotHeight = 220;
const plotLeft = 42;
const plotRight = 546;
const plotTop = 17;
const plotBottom = 190;
for (let i = 0; i <= 4; i++) {
const y = plotTop + (i / 4) * (plotBottom - plotTop);
const line = document.createElementNS(SVG_NS, "line");
line.setAttribute("x1", plotLeft);
line.setAttribute("x2", plotRight);
line.setAttribute("y1", y);
line.setAttribute("y2", y);
line.setAttribute("class", "grid-line");
gridGroup.appendChild(line);
const label = document.createElementNS(SVG_NS, "text");
label.setAttribute("x", 32);
label.setAttribute("y", y + 3);
label.setAttribute("text-anchor", "end");
label.setAttribute("class", "grid-label");
label.textContent = `${100 - i * 25}%`;
gridGroup.appendChild(label);
}
function pathFor(values) {
const denominator = Math.max(8, values.length - 1);
return values
.map((value, i) => {
const x = plotLeft + (i / denominator) * (plotRight - plotLeft);
const y = plotBottom - value * (plotBottom - plotTop);
return `${i === 0 ? "M" : "L"}${x.toFixed(2)},${y.toFixed(2)}`;
})
.join(" ");
}
function renderGraph() {
$("line-a").setAttribute("d", pathFor(historyA));
$("line-b").setAttribute("d", pathFor(historyB));
const denominator = Math.max(8, historyA.length - 1);
const lastIndex = historyA.length - 1;
const x = plotLeft + (lastIndex / denominator) * (plotRight - plotLeft);
$("dot-a").setAttribute("cx", x);
$("dot-a").setAttribute("cy", plotBottom - historyA[lastIndex] * (plotBottom - plotTop));
$("dot-b").setAttribute("cx", x);
$("dot-b").setAttribute("cy", plotBottom - historyB[lastIndex] * (plotBottom - plotTop));
$("generation").textContent = `GEN ${state.generation}`;
}
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
function percent(value) {
return `${(value * 100).toFixed(1)}%`;
}
function updateRunButton() {
$("run").textContent = state.running ? "Ⅱ Pause" : "▶ Run";
$("run-state").textContent = state.running ? "Running" : "Paused";
$("run-state").classList.toggle("paused", !state.running);
}
function updateUI() {
const d = migrationDetails();
const sourceName = d.sourceIsA ? "A" : "B";
const destinationName = d.sourceIsA ? "B" : "A";
const sourceP = d.sourceIsA ? state.pA : state.pB;
const destinationP = d.sourceIsA ? state.pB : state.pA;
$("migration-out").textContent = `${Math.round(state.migration * 100)}%`;
$("size-a-out").textContent = state.NA;
$("size-b-out").textContent = state.NB;
$("metric-a").textContent = percent(state.pA);
$("metric-b").textContent = percent(state.pB);
$("metric-gap").textContent = percent(Math.abs(state.pA - state.pB));
$("flow-direction").textContent = `${sourceName} → ${destinationName}`;
$("migrant-count").textContent = d.migrantCount;
let prediction;
if (d.migrantCount === 0) {
prediction = "No migrants are moving, so only random drift changes the frequencies.";
} else if (Math.abs(sourceP - destinationP) < 0.005) {
prediction = `The populations have nearly matching frequencies, so migration will cause little immediate change.`;
} else {
const trend = sourceP > destinationP ? "increase" : "decrease";
prediction =
`${destinationName}'s variant frequency should ${trend} ` +
`toward ${sourceName}'s current frequency.`;
}
const smallerN = Math.min(state.NA, state.NB);
const largerN = Math.max(state.NA, state.NB);
$("insight").innerHTML =
`<strong>${sourceName} → ${destinationName}: ${prediction}</strong><br>` +
`${d.migrantCount} migrants enter ${destinationName} per generation, ` +
`replacing about ${Math.round(d.replacement * 100)}% of that population. ` +
`N=${smallerN} drifts more strongly than N=${largerN}.`;
labelA.update(`POP A p=${percent(state.pA)} N=${state.NA}`);
labelB.update(`POP B p=${percent(state.pB)} N=${state.NB}`);
}
function refreshScene() {
updatePopulationMesh(
populationA,
state.pA,
state.NA,
ANCESTRAL_A,
17
);
updatePopulationMesh(
populationB,
state.pB,
state.NB,
ANCESTRAL_B,
91
);
updateUI();
}
function resetModel() {
state.pA = 0.68;
state.pB = 0.32;
state.generation = 0;
rng = createRng(0x4a17b3);
historyA = [state.pA];
historyB = [state.pB];
refreshScene();
renderGraph();
}
$("migration").addEventListener("input", (event) => {
state.migration = Number(event.target.value);
updateUI();
});
$("size-a").addEventListener("input", (event) => {
state.NA = Number(event.target.value);
refreshScene();
});
$("size-b").addEventListener("input", (event) => {
state.NB = Number(event.target.value);
refreshScene();
});
document.querySelectorAll("[data-direction]").forEach((button) => {
button.addEventListener("click", () => {
state.direction = button.dataset.direction;
document.querySelectorAll("[data-direction]").forEach((other) => {
const active = other === button;
other.classList.toggle("active", active);
other.setAttribute("aria-pressed", String(active));
});
rebuildFlowPath();
updateUI();
});
});
$("run").addEventListener("click", () => {
state.running = !state.running;
updateRunButton();
});
$("reset").addEventListener("click", resetModel);
window.addEventListener("keydown", (event) => {
if (
event.code === "Space" &&
document.activeElement?.tagName !== "INPUT" &&
document.activeElement?.tagName !== "BUTTON"
) {
event.preventDefault();
state.running = !state.running;
updateRunButton();
}
});
// -------------------------------------------------------------------------
// Start
// -------------------------------------------------------------------------
rebuildFlowPath();
resetModel();
updateRunButton();
resize();
updateCamera();
$("loading")?.remove();
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
animateMigrants(delta);
renderer.render(scene, camera);
}
animate();
setInterval(() => {
if (state.running) stepModel();
}, 850);
</script>
</body>
</html>
```