Prompt specification
Build or customize the Three.js 3D scene "Two population pools and migration bridge" 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: Two population pools and migration bridge
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/two-population-pools-and-migration-bridge-x0909
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing gene flow between populations. Create two token populations with contrasting variant frequencies joined by a narrow bridge; mark migrants individually and preserve their variant identity on arrival. Low-poly.
Working Three.js Starter (two-population-pools-and-migration-bridge-x0909):
```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 Between Two Populations</title>
<style>
:root {
--ink: #19332d;
--muted: #61766f;
--panel: rgba(250, 252, 248, 0.88);
--border: rgba(25, 51, 45, 0.13);
--v1: #f26b4d;
--v2: #2b8cbe;
--shadow: 0 16px 50px rgba(30, 57, 49, 0.12);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e5ece6;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button {
font: inherit;
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
#hud {
position: fixed;
inset: 0;
pointer-events: none;
}
.intro {
position: absolute;
top: 24px;
left: 26px;
max-width: 410px;
}
.eyebrow {
display: block;
margin-bottom: 7px;
color: #557168;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(28px, 3.2vw, 48px);
font-weight: 800;
letter-spacing: -0.045em;
line-height: 0.98;
}
.intro-copy {
max-width: 390px;
margin: 12px 0 15px;
color: #536b62;
font-size: 13px;
line-height: 1.55;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 7px 10px;
border: 1px solid var(--border);
border-radius: 999px;
background: rgba(250, 252, 248, 0.76);
backdrop-filter: blur(12px);
color: #405b52;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.03em;
}
.swatch {
width: 10px;
height: 10px;
flex: 0 0 auto;
border-radius: 3px;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.08);
}
.swatch.v1 {
background: var(--v1);
}
.swatch.v2 {
background: var(--v2);
}
.swatch.migrant {
border: 2px solid #fff;
outline: 1px solid #294a40;
border-radius: 50%;
background: #f4c454;
}
.status-card {
position: absolute;
top: 24px;
right: 26px;
width: 278px;
padding: 17px 18px;
border: 1px solid var(--border);
border-radius: 18px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
}
.status-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
.run-state {
padding: 4px 7px;
border-radius: 999px;
background: #e4eee7;
color: #41675a;
font-size: 9px;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
}
#phase {
min-height: 23px;
font-size: 15px;
font-weight: 800;
letter-spacing: -0.01em;
}
#status-detail {
min-height: 43px;
margin-top: 5px;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
#event-log {
display: grid;
gap: 6px;
margin-top: 12px;
padding-top: 11px;
border-top: 1px solid var(--border);
}
.event {
display: flex;
align-items: flex-start;
gap: 7px;
color: #50675f;
font-size: 9px;
line-height: 1.4;
}
.event-dot {
width: 6px;
height: 6px;
flex: 0 0 auto;
margin-top: 3px;
border-radius: 50%;
}
.population-card {
position: absolute;
bottom: 25px;
width: 250px;
padding: 16px 17px 15px;
border: 1px solid var(--border);
border-radius: 18px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
}
.population-card.left {
left: 26px;
}
.population-card.right {
right: 26px;
}
.population-head {
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
gap: 10px;
margin-bottom: 13px;
}
.population-code {
display: grid;
width: 31px;
height: 31px;
place-items: center;
border-radius: 10px;
color: white;
font-size: 12px;
font-weight: 850;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.06);
}
.population-card.left .population-code {
background: #769765;
}
.population-card.right .population-code {
background: #a58d51;
}
.population-head strong {
display: block;
font-size: 12px;
font-weight: 800;
}
.population-head small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.resident-total {
color: #688078;
font-size: 9px;
font-weight: 750;
text-align: right;
}
.frequency-bar {
display: flex;
width: 100%;
height: 8px;
overflow: hidden;
border-radius: 999px;
background: #dce6df;
}
.frequency-bar span {
height: 100%;
transition: width 500ms cubic-bezier(0.22, 1, 0.36, 1);
}
.frequency-bar .v1 {
background: var(--v1);
}
.frequency-bar .v2 {
background: var(--v2);
}
.frequency-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 8px;
color: #50665e;
font-size: 10px;
}
.frequency-row span:first-child {
display: inline-flex;
align-items: center;
gap: 6px;
font-weight: 750;
}
.mini-dot {
width: 7px;
height: 7px;
border-radius: 2px;
}
.controls {
position: absolute;
bottom: 25px;
left: 50%;
display: flex;
align-items: center;
gap: 7px;
padding: 7px;
border: 1px solid var(--border);
border-radius: 15px;
background: rgba(250, 252, 248, 0.9);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
pointer-events: auto;
transform: translateX(-50%);
}
.controls button {
min-width: 76px;
height: 36px;
padding: 0 12px;
border: 0;
border-radius: 10px;
background: transparent;
color: var(--ink);
cursor: pointer;
font-size: 10px;
font-weight: 800;
transition:
background 160ms ease,
transform 160ms ease;
}
.controls button:hover {
background: #e9f0ea;
}
.controls button:active {
transform: translateY(1px);
}
.controls button.primary {
background: var(--ink);
color: white;
}
.controls button.primary:hover {
background: #294c41;
}
.controls button:disabled {
cursor: default;
opacity: 0.42;
}
.control-divider {
width: 1px;
height: 22px;
background: var(--border);
}
.camera-help {
position: absolute;
right: 28px;
bottom: 168px;
color: rgba(39, 67, 58, 0.68);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.05em;
text-transform: uppercase;
}
#loading {
position: fixed;
inset: 0;
display: grid;
place-items: center;
background: #e5ece6;
color: #47665b;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
z-index: 20;
}
@media (max-width: 900px) {
.intro-copy {
display: none;
}
.status-card {
width: 235px;
}
.population-card {
width: 215px;
}
.camera-help {
display: none;
}
}
@media (max-width: 700px) {
.intro {
top: 15px;
left: 15px;
}
.intro .eyebrow,
.legend {
display: none;
}
h1 {
max-width: 190px;
font-size: 30px;
}
.status-card {
top: 15px;
right: 15px;
width: 190px;
padding: 13px;
}
#event-log {
display: none;
}
.population-card {
bottom: 77px;
width: calc(50% - 22px);
padding: 12px;
}
.population-card.left {
left: 12px;
}
.population-card.right {
right: 12px;
}
.population-head {
margin-bottom: 9px;
}
.population-head small,
.resident-total {
display: none;
}
.controls {
bottom: 13px;
}
.controls button {
min-width: 66px;
padding: 0 9px;
}
}
</style>
</head>
<body>
<div id="loading">Building population model…</div>
<div id="viewport"></div>
<div id="hud">
<section class="intro">
<span class="eyebrow">Low-poly population model</span>
<h1>Gene flow</h1>
<p class="intro-copy">
Two contrasting variant populations exchange individually tagged
migrants across a narrow bridge. Each migrant keeps its original
variant color and identity after settling.
</p>
<div class="legend">
<div class="legend-item">
<span class="swatch v1"></span>
Variant V1
</div>
<div class="legend-item">
<span class="swatch v2"></span>
Variant V2
</div>
<div class="legend-item">
<span class="swatch migrant"></span>
Tagged migrant
</div>
</div>
</section>
<section class="status-card" aria-live="polite">
<div class="status-head">
<span class="eyebrow">Simulation</span>
<span class="run-state" id="run-state">Ready</span>
</div>
<div id="phase">Preparing migration</div>
<div id="status-detail">
Eight carriers will cross the bridge in alternating directions.
</div>
<div id="event-log"></div>
</section>
<article class="population-card left">
<div class="population-head">
<div class="population-code">A</div>
<div>
<strong>Population A</strong>
<small>Western population</small>
</div>
<div class="resident-total">
<span id="a-total">20</span><br />residents
</div>
</div>
<div class="frequency-bar" aria-hidden="true">
<span class="v1" id="a-v1-bar"></span>
<span class="v2" id="a-v2-bar"></span>
</div>
<div class="frequency-row">
<span><i class="mini-dot" style="background: var(--v1)"></i>V1</span>
<span id="a-v1">80% · 16</span>
</div>
<div class="frequency-row">
<span><i class="mini-dot" style="background: var(--v2)"></i>V2</span>
<span id="a-v2">20% · 4</span>
</div>
</article>
<article class="population-card right">
<div class="population-head">
<div class="population-code">B</div>
<div>
<strong>Population B</strong>
<small>Eastern population</small>
</div>
<div class="resident-total">
<span id="b-total">20</span><br />residents
</div>
</div>
<div class="frequency-bar" aria-hidden="true">
<span class="v1" id="b-v1-bar"></span>
<span class="v2" id="b-v2-bar"></span>
</div>
<div class="frequency-row">
<span><i class="mini-dot" style="background: var(--v1)"></i>V1</span>
<span id="b-v1">20% · 4</span>
</div>
<div class="frequency-row">
<span><i class="mini-dot" style="background: var(--v2)"></i>V2</span>
<span id="b-v2">80% · 16</span>
</div>
</article>
<div class="controls" aria-label="Simulation controls">
<button class="primary" id="replay" type="button">↻ Replay</button>
<div class="control-divider"></div>
<button id="pause" type="button">Ⅱ Pause</button>
<button id="speed" type="button">1×</button>
</div>
<div class="camera-help">Drag to orbit · Scroll to zoom · Double-click to reset</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Constants and palette
// -------------------------------------------------------------------------
const VARIANTS = {
v1: { code: "V1", hex: 0xf26b4d, css: "#f26b4d" },
v2: { code: "V2", hex: 0x2b8cbe, css: "#2b8cbe" }
};
const POPULATIONS = {
A: {
id: "A",
name: "Population A",
center: -4.55,
initialCounts: { v1: 16, v2: 4 },
counts: { v1: 16, v2: 4 },
initialFreeSlots: [4, 9, 14, 19],
freeSlots: [4, 9, 14, 19]
},
B: {
id: "B",
name: "Population B",
center: 4.55,
initialCounts: { v1: 4, v2: 16 },
counts: { v1: 4, v2: 16 },
initialFreeSlots: [4, 9, 14, 19],
freeSlots: [4, 9, 14, 19]
}
};
const ISLAND_RADIUS = 3;
const ISLAND_TOP = 1.15;
const BRIDGE_SURFACE = 1.22;
const POPULATION_Y = ISLAND_TOP + 0.02;
const viewport = document.getElementById("viewport");
const loading = document.getElementById("loading");
// -------------------------------------------------------------------------
// Renderer, scene, lights
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe5ece6);
scene.fog = new THREE.Fog(0xe5ece6, 27, 58);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute(
"aria-label",
"Interactive 3D model of gene flow between two populations"
);
viewport.appendChild(renderer.domElement);
const hemiLight = new THREE.HemisphereLight(0xf7fff4, 0x789287, 2.25);
scene.add(hemiLight);
const sun = new THREE.DirectionalLight(0xfff3d5, 3.1);
sun.position.set(-7, 14, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -18;
sun.shadow.camera.right = 18;
sun.shadow.camera.top = 16;
sun.shadow.camera.bottom = -16;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 38;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xc4e6ff, 0.7);
fill.position.set(10, 7, -9);
scene.add(fill);
// -------------------------------------------------------------------------
// Shared geometry and low-poly terrain
// -------------------------------------------------------------------------
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(100, 100),
new THREE.MeshStandardMaterial({
color: 0xd4dfd7,
roughness: 1,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.05;
ground.receiveShadow = true;
scene.add(ground);
const river = new THREE.Mesh(
new THREE.BoxGeometry(3.05, 0.04, 18),
new THREE.MeshStandardMaterial({
color: 0x79b4ae,
roughness: 0.62,
metalness: 0.02
})
);
river.position.y = -0.005;
river.receiveShadow = true;
scene.add(river);
const bankMaterial = new THREE.MeshStandardMaterial({
color: 0xb6aa86,
roughness: 0.95
});
for (const x of [-1.55, 1.55]) {
const bank = new THREE.Mesh(
new THREE.BoxGeometry(0.18, 0.07, 9),
bankMaterial
);
bank.position.set(x, 0.01, 0);
bank.receiveShadow = true;
scene.add(bank);
}
let randomSeed = 1729;
function random() {
randomSeed =
(randomSeed * 1664525 + 1013904223) >>> 0;
return randomSeed / 4294967296;
}
function createIsland(population) {
const isA = population.id === "A";
const topColor = isA ? 0x91b77a : 0xc3b36f;
const sideColor = isA ? 0x708e63 : 0x958450;
const geometry = new THREE.CylinderGeometry(
ISLAND_RADIUS,
ISLAND_RADIUS + 0.34,
ISLAND_TOP,
7,
1,
false
);
const sideMaterial = new THREE.MeshStandardMaterial({
color: sideColor,
roughness: 0.96,
flatShading: true
});
const topMaterial = new THREE.MeshStandardMaterial({
color: topColor,
roughness: 0.98,
flatShading: true
});
const bottomMaterial = new THREE.MeshStandardMaterial({
color: isA ? 0x52694e : 0x71683f,
roughness: 1,
flatShading: true
});
const island = new THREE.Mesh(geometry, [
sideMaterial,
topMaterial,
bottomMaterial
]);
island.position.set(population.center, ISLAND_TOP / 2, 0);
island.castShadow = true;
island.receiveShadow = true;
scene.add(island);
const trunkGeometry = new THREE.CylinderGeometry(0.06, 0.08, 0.42, 5);
const crownGeometry = new THREE.ConeGeometry(0.25, 0.62, 5);
const trunkMaterial = new THREE.MeshStandardMaterial({
color: 0x74583d,
roughness: 1,
flatShading: true
});
const crownMaterial = new THREE.MeshStandardMaterial({
color: isA ? 0x4f8059 : 0x698650,
roughness: 1,
flatShading: true
});
for (let i = 0; i < 8; i++) {
const angle = (i / 8) * Math.PI * 2 + (isA ? 0.78 : 1.12);
const radius = 2.35 + random() * 0.28;
const x = population.center + Math.cos(angle) * radius;
const z = Math.sin(angle) * radius;
const scale = 0.72 + random() * 0.42;
const trunk = new THREE.Mesh(trunkGeometry, trunkMaterial);
trunk.position.set(x, ISLAND_TOP + 0.21 * scale, z);
trunk.scale.setScalar(scale);
trunk.castShadow = true;
scene.add(trunk);
const crown = new THREE.Mesh(crownGeometry, crownMaterial);
crown.position.set(x, ISLAND_TOP + 0.68 * scale, z);
crown.rotation.y = random() * Math.PI;
crown.scale.setScalar(scale);
crown.castShadow = true;
scene.add(crown);
}
const rockGeometry = new THREE.DodecahedronGeometry(0.2, 0);
const rockMaterial = new THREE.MeshStandardMaterial({
color: isA ? 0x81917c : 0x9d9274,
roughness: 1,
flatShading: true
});
for (let i = 0; i < 6; i++) {
const angle = random() * Math.PI * 2;
const radius = 2.2 + random() * 0.55;
const rock = new THREE.Mesh(rockGeometry, rockMaterial);
rock.position.set(
population.center + Math.cos(angle) * radius,
ISLAND_TOP + 0.08,
Math.sin(angle) * radius
);
rock.scale.set(
0.65 + random(),
0.45 + random() * 0.5,
0.65 + random()
);
rock.rotation.set(random(), random(), random());
rock.castShadow = true;
scene.add(rock);
}
}
createIsland(POPULATIONS.A);
createIsland(POPULATIONS.B);
// -------------------------------------------------------------------------
// Narrow bridge
// -------------------------------------------------------------------------
const plankMaterial = new THREE.MeshStandardMaterial({
color: 0xa87349,
roughness: 0.9,
flatShading: true
});
const darkWoodMaterial = new THREE.MeshStandardMaterial({
color: 0x644b36,
roughness: 1,
flatShading: true
});
const bridgeGroup = new THREE.Group();
scene.add(bridgeGroup);
const plankCount = 15;
for (let i = 0; i < plankCount; i++) {
const t = i / (plankCount - 1);
const plank = new THREE.Mesh(
new THREE.BoxGeometry(0.19, 0.13, 1.04),
plankMaterial
);
plank.position.set(
THREE.MathUtils.lerp(-1.68, 1.68, t),
BRIDGE_SURFACE - 0.065,
0
);
plank.rotation.y = (i % 2 === 0 ? 1 : -1) * 0.012;
plank.castShadow = true;
plank.receiveShadow = true;
bridgeGroup.add(plank);
}
for (const z of [-0.43, 0.43]) {
const stringer = new THREE.Mesh(
new THREE.BoxGeometry(3.65, 0.16, 0.13),
darkWoodMaterial
);
stringer.position.set(0, BRIDGE_SURFACE - 0.16, z);
stringer.castShadow = true;
bridgeGroup.add(stringer);
}
const postGeometry = new THREE.CylinderGeometry(0.055, 0.075, 0.57, 5);
const ropeGeometry = new THREE.CylinderGeometry(0.027, 0.027, 3.5, 6);
for (const z of [-0.57, 0.57]) {
for (let i = 0; i < 7; i++) {
const post = new THREE.Mesh(postGeometry, darkWoodMaterial);
post.position.set(-1.62 + i * 0.54, 1.45, z);
post.castShadow = true;
bridgeGroup.add(post);
}
const rope = new THREE.Mesh(ropeGeometry, darkWoodMaterial);
rope.rotation.z = Math.PI / 2;
rope.position.set(0, 1.67, z);
rope.castShadow = true;
bridgeGroup.add(rope);
}
// Small arrow markings make the direction of movement readable.
const arrowMaterial = new THREE.MeshBasicMaterial({
color: 0xf5d17c,
side: THREE.DoubleSide
});
for (const direction of [-1, 1]) {
const shape = new THREE.Shape();
shape.moveTo(-0.12, -0.1);
shape.lineTo(direction * 0.12, 0);
shape.lineTo(-0.12, 0.1);
shape.closePath();
const arrow = new THREE.Mesh(
new THREE.ShapeGeometry(shape),
arrowMaterial
);
arrow.rotation.x = -Math.PI / 2;
arrow.position.set(direction * 0.75, BRIDGE_SURFACE + 0.004, 0);
bridgeGroup.add(arrow);
}
// -------------------------------------------------------------------------
// Canvas-based labels; no addons or external assets
// -------------------------------------------------------------------------
function roundedRectPath(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + width - r, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + r);
ctx.lineTo(x + width, y + height - r);
ctx.quadraticCurveTo(
x + width,
y + height,
x + width - r,
y + height
);
ctx.lineTo(x + r, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
}
function createLabelSprite(
text,
accent = "#f26b4d",
canvasWidth = 512,
canvasHeight = 128,
worldWidth = 2.5
) {
const canvas = document.createElement("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
roundedRectPath(
ctx,
5,
5,
canvasWidth - 10,
canvasHeight - 10,
Math.min(20, canvasHeight * 0.22)
);
ctx.fillStyle = "rgba(23, 47, 40, 0.92)";
ctx.fill();
ctx.fillStyle = accent;
roundedRectPath(
ctx,
14,
14,
Math.max(7, canvasWidth * 0.025),
canvasHeight - 28,
5
);
ctx.fill();
ctx.fillStyle = "#ffffff";
ctx.font = `800 ${Math.floor(canvasHeight * 0.39)}px system-ui, sans-serif`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(
text,
canvasWidth * 0.54,
canvasHeight * 0.53
);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.anisotropy = Math.min(
4,
renderer.capabilities.getMaxAnisotropy()
);
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(
worldWidth,
worldWidth * (canvasHeight / canvasWidth),
1
);
sprite.renderOrder = 40;
return sprite;
}
for (const population of Object.values(POPULATIONS)) {
const label = createLabelSprite(
`POPULATION ${population.id}`,
population.id === "A" ? "#9fc789" : "#d5c47f",
512,
128,
2.65
);
label.position.set(population.center, 2.08, -2.05);
scene.add(label);
}
const bridgeLabel = createLabelSprite(
"MIGRATION BRIDGE",
"#e6bd63",
512,
112,
1.85
);
bridgeLabel.position.set(0, 1.02, 1.02);
scene.add(bridgeLabel);
// -------------------------------------------------------------------------
// Population tokens
// -------------------------------------------------------------------------
const tokenBodyGeometry = new THREE.CylinderGeometry(
0.145,
0.2,
0.36,
6
);
const tokenHeadGeometry = new THREE.IcosahedronGeometry(0.135, 0);
const migrantRingGeometry = new THREE.RingGeometry(0.205, 0.255, 16);
const allTokens = [];
const variantBuckets = {
A: { v1: [], v2: [] },
B: { v1: [], v2: [] }
};
function createPopulationSlots(population) {
const slots = [];
for (let row = 0; row < 4; row++) {
for (let column = 0; column < 6; column++) {
slots.push(
new THREE.Vector3(
population.center + (column - 2.5) * 0.58,
POPULATION_Y,
(row - 1.5) * 0.62
)
);
}
}
return slots;
}
const populationSlots = {
A: createPopulationSlots(POPULATIONS.A),
B: createPopulationSlots(POPULATIONS.B)
};
const occupiedSlots = [
0, 1, 2, 3,
5, 6, 7, 8,
10, 11, 12, 13,
15, 16, 17, 18,
20, 21, 22, 23
];
function createToken(populationId, variantKey, slot, index) {
const variant = VARIANTS[variantKey];
const root = new THREE.Group();
const material = new THREE.MeshStandardMaterial({
color: variant.hex,
emissive: new THREE.Color(variant.hex).multiplyScalar(0.055),
roughness: 0.76,
metalness: 0,
flatShading: true
});
const body = new THREE.Mesh(tokenBodyGeometry, material);
body.position.y = 0.18;
body.castShadow = true;
body.receiveShadow = true;
root.add(body);
const head = new THREE.Mesh(tokenHeadGeometry, material);
head.position.y = 0.455;
head.rotation.y = Math.random() * Math.PI;
head.castShadow = true;
root.add(head);
const originalPosition = populationSlots[populationId][slot].clone();
root.position.copy(originalPosition);
root.rotation.y = (index % 7) * 0.38;
scene.add(root);
const token = {
id: `${populationId}-${String(index + 1).padStart(2, "0")}`,
root,
body,
head,
material,
variantKey,
variant,
originalPop: populationId,
originalPosition,
originalRotationY: root.rotation.y,
label: null,
ring: null,
settled: false
};
allTokens.push(token);
variantBuckets[populationId][variantKey].push(token);
return token;
}
for (const population of Object.values(POPULATIONS)) {
occupiedSlots.forEach((slot, index) => {
const variantKey =
population.id === "A"
? index < 16
? "v1"
: "v2"
: index < 4
? "v1"
: "v2";
createToken(population.id, variantKey, slot, index);
});
}
// -------------------------------------------------------------------------
// Migration schedule
//
// A -> B: 3 V1 carriers, 1 V2 carrier
// B -> A: 1 V1 carrier, 3 V2 carriers
// -------------------------------------------------------------------------
const migrationSchedule = [
{
from: "A",
to: "B",
variantKey: "v1",
token: variantBuckets.A.v1[0]
},
{
from: "B",
to: "A",
variantKey: "v2",
token: variantBuckets.B.v2[0]
},
{
from: "A",
to: "B",
variantKey: "v2",
token: variantBuckets.A.v2[0]
},
{
from: "B",
to: "A",
variantKey: "v2",
token: variantBuckets.B.v2[1]
},
{
from: "A",
to: "B",
variantKey: "v1",
token: variantBuckets.A.v1[1]
},
{
from: "B",
to: "A",
variantKey: "v1",
token: variantBuckets.B.v1[0]
},
{
from: "A",
to: "B",
variantKey: "v1",
token: variantBuckets.A.v1[2]
},
{
from: "B",
to: "A",
variantKey: "v2",
token: variantBuckets.B.v2[2]
}
].map((migration, index) => ({
...migration,
id: `M${String(index + 1).padStart(2, "0")}`
}));
// -------------------------------------------------------------------------
// Interface state
// -------------------------------------------------------------------------
const phaseElement = document.getElementById("phase");
const detailElement = document.getElementById("status-detail");
const runStateElement = document.getElementById("run-state");
const eventLogElement = document.getElementById("event-log");
const pauseButton = document.getElementById("pause");
const replayButton = document.getElementById("replay");
const speedButton = document.getElementById("speed");
let migrationIndex = 0;
let activeMigration = null;
let simulationRunning = true;
let simulationComplete = false;
let simulationSpeed = 1;
let nextMigrationDelay = 0.9;
const speeds = [0.75, 1, 1.5, 2];
function updateFrequencyUI() {
for (const population of Object.values(POPULATIONS)) {
const prefix = population.id.toLowerCase();
const v1 = population.counts.v1;
const v2 = population.counts.v2;
const total = Math.max(1, v1 + v2);
const v1Percent = (v1 / total) * 100;
const v2Percent = (v2 / total) * 100;
document.getElementById(`${prefix}-v1-bar`).style.width =
`${v1Percent}%`;
document.getElementById(`${prefix}-v2-bar`).style.width =
`${v2Percent}%`;
document.getElementById(`${prefix}-v1`).textContent =
`${Math.round(v1Percent)}% · ${v1}`;
document.getElementById(`${prefix}-v2`).textContent =
`${Math.round(v2Percent)}% · ${v2}`;
document.getElementById(`${prefix}-total`).textContent = v1 + v2;
}
}
function logEvent(text, color) {
const event = document.createElement("div");
event.className = "event";
const dot = document.createElement("span");
dot.className = "event-dot";
dot.style.background = color;
const copy = document.createElement("span");
copy.textContent = text;
event.append(dot, copy);
eventLogElement.prepend(event);
while (eventLogElement.children.length > 3) {
eventLogElement.lastElementChild.remove();
}
}
function setRunState(label) {
runStateElement.textContent = label;
}
// -------------------------------------------------------------------------
// Migrant markers
// -------------------------------------------------------------------------
function destroyMigrantMarker(token) {
if (token.label) {
token.root.remove(token.label);
token.label.material.map.dispose();
token.label.material.dispose();
token.label = null;
}
if (token.ring) {
token.root.remove(token.ring);
token.ring.material.dispose();
token.ring = null;
}
token.settled = false;
}
function createMigrantMarker(token, migrationId) {
const label = createLabelSprite(
`${migrationId} · ${token.variant.code}`,
token.variant.css,
256,
80,
0.92
);
label.position.set(0, 0.76, 0);
token.root.add(label);
token.label = label;
const ringMaterial = new THREE.MeshBasicMaterial({
color: token.variant.hex,
transparent: true,
opacity: 0.92,
side: THREE.DoubleSide,
depthWrite: false
});
const ring = new THREE.Mesh(migrantRingGeometry, ringMaterial);
ring.rotation.x = -Math.PI / 2;
ring.position.y = 0.018;
ring.renderOrder = 5;
token.root.add(ring);
token.ring = ring;
}
// -------------------------------------------------------------------------
// Simulation lifecycle
// -------------------------------------------------------------------------
function resetSimulation() {
migrationIndex = 0;
activeMigration = null;
simulationRunning = true;
simulationComplete = false;
nextMigrationDelay = 0.9;
for (const token of allTokens) {
destroyMigrantMarker(token);
token.root.position.copy(token.originalPosition);
token.root.rotation.y = token.originalRotationY;
}
for (const population of Object.values(POPULATIONS)) {
population.counts = {
...population.initialCounts
};
population.freeSlots = [...population.initialFreeSlots];
}
eventLogElement.replaceChildren();
updateFrequencyUI();
phaseElement.textContent = "Preparing migration";
detailElement.textContent =
"Eight carriers will cross the bridge in alternating directions.";
setRunState("Ready");
pauseButton.textContent = "Ⅱ Pause";
pauseButton.disabled = false;
}
function towardCenter(center) {
return center < 0 ? 1 : -1;
}
function innerShore(center) {
return (
center +
towardCenter(center) * (ISLAND_RADIUS - 0.06)
);
}
function createRoute(source, destination, destinationSlot, startPosition) {
const sourceDirection = towardCenter(source.center);
const destinationDirection = towardCenter(destination.center);
const points = [
startPosition.clone(),
new THREE.Vector3(
source.center + sourceDirection * 1.0,
POPULATION_Y,
0
),
new THREE.Vector3(
innerShore(source.center),
POPULATION_Y,
0
),
new THREE.Vector3(
innerShore(destination.center),
BRIDGE_SURFACE + 0.015,
0
),
new THREE.Vector3(
destination.center + destinationDirection * 1.0,
POPULATION_Y,
0
),
destinationSlot.clone()
];
return {
points,
bounds: [0, 0.12, 0.23, 0.75, 0.87, 1]
};
}
function smoothStep(value) {
return value * value * (3 - 2 * value);
}
function sampleRoute(route, progress) {
const { points, bounds } = route;
let segment = 0;
while (
segment < bounds.length - 2 &&
progress > bounds[segment + 1]
) {
segment++;
}
const localProgress = THREE.MathUtils.clamp(
(progress - bounds[segment]) /
(bounds[segment + 1] - bounds[segment]),
0,
1
);
return new THREE.Vector3().lerpVectors(
points[segment],
points[segment + 1],
smoothStep(localProgress)
);
}
function startNextMigration() {
if (migrationIndex >= migrationSchedule.length) {
completeSimulation();
return;
}
const migration = migrationSchedule[migrationIndex];
const source = POPULATIONS[migration.from];
const destination = POPULATIONS[migration.to];
const token = migration.token;
const destinationSlot =
populationSlots[destination.id][destination.freeSlots.shift()];
source.counts[migration.variantKey] -= 1;
updateFrequencyUI();
createMigrantMarker(token, migration.id);
activeMigration = {
...migration,
elapsed: 0,
duration: 2.8,
destinationSlot,
route: createRoute(
source,
destination,
destinationSlot,
token.root.position
)
};
phaseElement.textContent =
`${migration.id} · ${migration.from} → ${migration.to}`;
detailElement.textContent =
`${token.variant.code} carrier crossing the narrow bridge. ` +
`The tag and variant color are attached to this individual.`;
setRunState("In transit");
logEvent(
`${migration.id} left ${source.name} carrying ${token.variant.code}`,
token.variant.css
);
}
function finishActiveMigration() {
const migration = activeMigration;
const token = migration.token;
const destination = POPULATIONS[migration.to];
destination.counts[migration.variantKey] += 1;
token.root.position.copy(migration.destinationSlot);
token.settled = true;
if (token.ring) {
token.ring.material.opacity = 0.48;
token.ring.scale.setScalar(1);
}
if (token.label) {
token.label.position.y = 0.71;
token.label.scale.set(0.82, 0.82 * (80 / 256), 1);
}
updateFrequencyUI();
logEvent(
`${migration.id} arrived in ${destination.name}; ` +
`${token.variant.code} identity retained`,
token.variant.css
);
activeMigration = null;
migrationIndex++;
if (migrationIndex >= migrationSchedule.length) {
completeSimulation();
} else {
nextMigrationDelay = 0.55;
phaseElement.textContent = "Migrant settled";
detailElement.textContent =
`${migration.id} is now a resident of ${destination.name}. ` +
`Its marker remains attached.`;
setRunState("Settled");
}
}
function completeSimulation() {
simulationComplete = true;
setRunState("Complete");
phaseElement.textContent = "Gene flow complete";
detailElement.textContent =
"Population A is now 70% V1 / 30% V2. " +
"Population B is now 30% V1 / 70% V2. " +
"All migrants retained their variant identity.";
pauseButton.disabled = true;
pauseButton.textContent = "Ⅱ Pause";
logEvent(
"Eight migrants settled; all variant identities preserved",
"#e2b950"
);
}
function updateSimulation(delta) {
if (simulationComplete) {
return;
}
if (activeMigration) {
activeMigration.elapsed += delta * simulationSpeed;
const progress = Math.min(
activeMigration.elapsed / activeMigration.duration,
1
);
const position = sampleRoute(activeMigration.route, progress);
position.y += Math.sin(progress * Math.PI * 12) * 0.018;
activeMigration.token.root.position.copy(position);
if (progress >= 1) {
finishActiveMigration();
}
} else {
nextMigrationDelay -= delta * simulationSpeed;
if (nextMigrationDelay <= 0) {
startNextMigration();
}
}
}
function updateActiveMarker(time) {
if (!activeMigration || !activeMigration.token.label) {
return;
}
const token = activeMigration.token;
const pulse = Math.sin(time * 7) * 0.5 + 0.5;
token.label.position.y = 0.77 + pulse * 0.035;
const width = 0.9 + pulse * 0.055;
token.label.scale.set(width, width * (80 / 256), 1);
if (token.ring) {
token.ring.scale.setScalar(1 + pulse * 0.12);
token.ring.material.opacity = 0.72 + pulse * 0.25;
}
}
replayButton.addEventListener("click", () => {
resetSimulation();
});
pauseButton.addEventListener("click", () => {
if (simulationComplete) {
return;
}
simulationRunning = !simulationRunning;
pauseButton.textContent = simulationRunning
? "Ⅱ Pause"
: "▶ Resume";
setRunState(simulationRunning ? "Running" : "Paused");
});
speedButton.addEventListener("click", () => {
const currentIndex = speeds.indexOf(simulationSpeed);
const nextIndex = (currentIndex + 1) % speeds.length;
simulationSpeed = speeds[nextIndex];
speedButton.textContent = `${simulationSpeed}×`;
});
// -------------------------------------------------------------------------
// Direct camera controls: orbit, zoom, pan-free target, touch pinch
// -------------------------------------------------------------------------
const cameraState = {
theta: 0.55,
phi: 0.83,
radius: 17.3,
target: new THREE.Vector3(0, 0.72, 0)
};
const cameraGoal = {
theta: cameraState.theta,
phi: cameraState.phi,
radius: cameraState.radius
};
const pointers = new Map();
let pinchDistance = null;
function updateCamera() {
cameraState.theta +=
(cameraGoal.theta - cameraState.theta) * 0.12;
cameraState.phi +=
(cameraGoal.phi - cameraState.phi) * 0.12;
cameraState.radius +=
(cameraGoal.radius - cameraState.radius) * 0.12;
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y +
cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z +
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
function getPinchDistance() {
const values = [...pointers.values()];
if (values.length < 2) {
return null;
}
return Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 2) {
pinchDistance = getPinchDistance();
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
const previous = pointers.get(event.pointerId);
if (!previous) {
return;
}
const current = {
x: event.clientX,
y: event.clientY
};
pointers.set(event.pointerId, current);
if (pointers.size === 1) {
const deltaX = current.x - previous.x;
const deltaY = current.y - previous.y;
cameraGoal.theta -= deltaX * 0.006;
cameraGoal.phi = THREE.MathUtils.clamp(
cameraGoal.phi + deltaY * 0.005,
0.38,
1.27
);
} else if (pointers.size === 2) {
const newDistance = getPinchDistance();
if (pinchDistance && newDistance) {
cameraGoal.radius = THREE.MathUtils.clamp(
cameraGoal.radius * (pinchDistance / newDistance),
10,
28
);
}
pinchDistance = newDistance;
}
});
function releasePointer(event) {
pointers.delete(event.pointerId);
pinchDistance = pointers.size === 2 ? getPinchDistance() : null;
}
renderer.domElement.addEventListener("pointerup", releasePointer);
renderer.domElement.addEventListener("pointercancel", releasePointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraGoal.radius = THREE.MathUtils.clamp(
cameraGoal.radius + event.deltaY * 0.012,
10,
28
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
cameraGoal.theta = 0.55;
cameraGoal.phi = 0.83;
cameraGoal.radius = 17.3;
});
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
resetSimulation();
updateCamera();
loading.remove();
const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
const delta = Math.min(clock.getDelta(), 0.05);
if (simulationRunning) {
updateSimulation(delta);
}
updateActiveMarker(clock.elapsedTime);
updateCamera();
renderer.render(scene, camera);
});
</script>
</body>
</html>
```