Prompt specification
Build or customize the Three.js 3D scene "Island population drift exhibition" 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: Island population drift exhibition
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/island-population-drift-exhibition-x0915
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring genetic drift. Compose several identical tiny islands with fictional neutral-color organisms; animate independent sampling histories so divergence occurs despite matching environments and rules. Voxel style.
Working Three.js Starter (island-population-drift-exhibition-x0915):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Genetic Drift — Voxel Population Lab</title>
<style>
:root {
--ink: #edf0e5;
--muted: #91a19c;
--panel: rgba(9, 24, 26, 0.84);
--panel-strong: rgba(7, 20, 22, 0.94);
--line: rgba(213, 225, 211, 0.16);
--bone: #ddd3b8;
--charcoal: #555c58;
--teal: #76b9ae;
--shadow: 0 16px 50px rgba(0, 0, 0, 0.25);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #0a2024;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button {
font: inherit;
}
#stage {
position: fixed;
inset: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#stage canvas:active {
cursor: grabbing;
}
.atmosphere {
position: fixed;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 50% 40%, transparent 25%, rgba(3, 13, 16, 0.2) 75%),
linear-gradient(180deg, rgba(2, 14, 17, 0.05), rgba(2, 13, 16, 0.28));
z-index: 2;
}
.panel {
position: fixed;
z-index: 10;
border: 1px solid var(--line);
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
.intro {
top: 20px;
left: 20px;
width: 330px;
padding: 20px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.status-dot {
width: 7px;
height: 7px;
background: var(--teal);
box-shadow: 0 0 12px rgba(118, 185, 174, 0.75);
}
h1 {
margin: 15px 0 11px;
font-size: clamp(34px, 4vw, 52px);
line-height: 0.86;
letter-spacing: -0.055em;
font-weight: 850;
}
h1 span {
display: block;
color: var(--bone);
}
.intro p {
margin: 0;
color: #b9c4bd;
font-size: 12px;
line-height: 1.65;
}
.chips {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-top: 16px;
}
.chips span {
padding: 5px 7px;
border: 1px solid rgba(221, 211, 184, 0.22);
color: #cbd2c8;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
letter-spacing: 0.08em;
}
.species {
display: flex;
align-items: center;
gap: 11px;
margin-top: 17px;
padding-top: 14px;
border-top: 1px solid var(--line);
color: var(--bone);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
font-weight: 700;
letter-spacing: 0.1em;
}
.species small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
font-weight: 500;
letter-spacing: 0.03em;
}
.species-icon {
position: relative;
width: 27px;
height: 23px;
flex: 0 0 auto;
background: #aaa897;
box-shadow:
8px -7px 0 -1px #c1bbaa,
-8px -7px 0 -1px #555c58,
0 11px 0 -4px #555c58;
}
.controls {
top: 20px;
right: 20px;
width: 260px;
padding: 14px;
}
.control-top {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
#run-state {
color: var(--bone);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
letter-spacing: 0.1em;
}
.control-buttons {
display: grid;
grid-template-columns: 1fr 58px 1fr;
gap: 7px;
}
.control-buttons button {
min-height: 36px;
padding: 8px 10px;
border: 1px solid rgba(221, 211, 184, 0.2);
border-radius: 0;
background: rgba(221, 211, 184, 0.07);
color: var(--ink);
cursor: pointer;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.04em;
transition:
background 150ms ease,
border-color 150ms ease,
transform 150ms ease;
}
.control-buttons button:hover {
border-color: rgba(221, 211, 184, 0.5);
background: rgba(221, 211, 184, 0.14);
}
.control-buttons button:active {
transform: translateY(1px);
}
#play-button {
color: #17201c;
border-color: var(--bone);
background: var(--bone);
}
#play-button:hover {
background: #eee5c9;
}
.seed-line {
display: flex;
justify-content: space-between;
margin-top: 10px;
color: #778984;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 8px;
letter-spacing: 0.08em;
}
.readout {
left: 50%;
bottom: 18px;
width: min(920px, calc(100vw - 36px));
padding: 14px;
transform: translateX(-50%);
background: var(--panel-strong);
}
.readout-header {
display: grid;
grid-template-columns: 1fr auto auto;
align-items: center;
gap: 26px;
padding: 0 2px 12px;
border-bottom: 1px solid var(--line);
}
.readout-title {
color: #dce2d8;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.12em;
}
.readout-subtitle {
margin-top: 4px;
color: var(--muted);
font-size: 9px;
}
.metric {
min-width: 92px;
}
.metric small {
display: block;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 8px;
letter-spacing: 0.08em;
}
.metric strong {
display: block;
margin-top: 3px;
color: var(--bone);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 17px;
font-weight: 600;
}
.island-grid {
display: grid;
grid-template-columns: repeat(6, minmax(100px, 1fr));
gap: 8px;
margin-top: 11px;
overflow-x: auto;
scrollbar-width: thin;
}
.island-card {
min-width: 100px;
padding: 9px;
border: 1px solid rgba(218, 228, 216, 0.11);
background: rgba(230, 235, 222, 0.025);
}
.island-card-head {
display: flex;
align-items: center;
justify-content: space-between;
color: #cbd3ca;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
letter-spacing: 0.06em;
}
.island-card-head strong {
color: var(--bone);
font-size: 11px;
font-weight: 600;
}
.frequency-track {
display: flex;
height: 5px;
margin: 8px 0 5px;
overflow: hidden;
background: var(--charcoal);
}
.frequency-track .allele-a {
width: 50%;
background: var(--bone);
transition: width 300ms ease;
}
.sparkline {
display: block;
width: 100%;
height: 26px;
overflow: visible;
}
.sparkline line {
stroke: rgba(220, 228, 215, 0.14);
stroke-width: 0.7;
stroke-dasharray: 3 3;
}
.sparkline path {
fill: none;
stroke: var(--bone);
stroke-width: 1.5;
vector-effect: non-scaling-stroke;
}
.legend {
right: 20px;
bottom: 250px;
width: 220px;
padding: 14px;
}
.legend-title {
margin-bottom: 10px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.13em;
}
.legend-row {
display: flex;
align-items: center;
gap: 8px;
margin: 8px 0;
color: #d8ddd4;
font-size: 10px;
}
.swatch {
width: 12px;
height: 12px;
flex: 0 0 auto;
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.12);
}
.swatch.a {
background: var(--bone);
}
.swatch.b {
background: var(--charcoal);
}
.legend-copy {
margin-top: 11px;
padding-top: 10px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 9px;
line-height: 1.5;
}
.camera-tip {
position: fixed;
left: 20px;
bottom: 252px;
z-index: 9;
color: rgba(215, 225, 216, 0.58);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
letter-spacing: 0.04em;
pointer-events: none;
}
#world-labels {
position: fixed;
inset: 0;
z-index: 5;
pointer-events: none;
overflow: hidden;
}
.world-tag {
position: absolute;
width: 88px;
padding: 6px 7px;
border: 1px solid rgba(220, 226, 214, 0.18);
background: rgba(7, 20, 22, 0.76);
transform: translate(-50%, -100%);
backdrop-filter: blur(7px);
-webkit-backdrop-filter: blur(7px);
transition: opacity 120ms ease;
}
.tag-top {
display: flex;
align-items: center;
justify-content: space-between;
color: #cdd5cc;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 8px;
letter-spacing: 0.08em;
}
.tag-top strong {
color: var(--bone);
font-weight: 600;
}
.tag-track {
display: flex;
height: 3px;
margin-top: 5px;
background: var(--charcoal);
}
.tag-a {
width: 50%;
background: var(--bone);
}
@media (max-width: 980px) {
.legend {
display: none;
}
.camera-tip {
bottom: 250px;
}
.readout {
width: calc(100vw - 28px);
}
.island-grid {
grid-template-columns: repeat(6, 115px);
}
}
@media (max-width: 680px) {
.intro {
top: 10px;
left: 10px;
width: 225px;
padding: 14px;
}
.intro p,
.species {
display: none;
}
h1 {
margin-top: 10px;
font-size: 29px;
}
.chips {
margin-top: 10px;
}
.chips span {
font-size: 7px;
}
.controls {
top: 10px;
right: 10px;
width: 184px;
padding: 10px;
}
.control-buttons {
grid-template-columns: 1fr 46px 1fr;
}
.control-buttons button {
padding: 7px 5px;
font-size: 8px;
}
.seed-line {
display: none;
}
.readout {
bottom: 8px;
width: calc(100vw - 16px);
padding: 10px;
}
.readout-header {
grid-template-columns: 1fr 72px 76px;
gap: 8px;
}
.readout-subtitle {
display: none;
}
.metric {
min-width: 0;
}
.metric strong {
font-size: 13px;
}
.world-tag {
width: 72px;
}
.camera-tip {
display: none;
}
}
</style>
</head>
<body>
<div id="stage"></div>
<div class="atmosphere"></div>
<div id="world-labels"></div>
<section class="panel intro">
<div class="eyebrow">
<span class="status-dot"></span>
Neutral population lab
</div>
<h1>GENETIC <span>DRIFT</span></h1>
<p>
Six identical islands begin with the same founders. In every generation,
each offspring receives two alleles drawn at random from its island's gene
pool. With no selection, mutation, or migration, chance alone splits the
populations apart.
</p>
<div class="chips">
<span>NO SELECTION</span>
<span>NO MIGRATION</span>
<span>NO MUTATION</span>
</div>
<div class="species">
<span class="species-icon"></span>
<span>
UMBERLINGS
<small>2 alleles · 16 diploids / island</small>
</span>
</div>
</section>
<section class="panel controls">
<div class="control-top">
<span class="eyebrow">Live history</span>
<span id="run-state">BREEDING</span>
</div>
<div class="control-buttons">
<button id="play-button" type="button" aria-label="Pause simulation">Ⅱ Pause</button>
<button id="speed-button" type="button" aria-label="Change simulation speed">1×</button>
<button id="new-button" type="button">New drift</button>
</div>
<div class="seed-line">
<span id="generation-label">GEN 000</span>
<span id="seed-label">SEED —</span>
</div>
</section>
<section class="panel readout">
<div class="readout-header">
<div>
<div class="readout-title">ALLELE A FREQUENCY / ISLAND HISTORIES</div>
<div class="readout-subtitle">
Pale tiles = allele A · charcoal tiles = allele B
</div>
</div>
<div class="metric" aria-live="polite">
<small>MEAN p(A)</small>
<strong id="mean-frequency">50.0%</strong>
</div>
<div class="metric" aria-live="polite">
<small>ISLAND SPREAD</small>
<strong id="island-spread">0.0 pp</strong>
</div>
</div>
<div id="island-grid" class="island-grid"></div>
</section>
<aside class="panel legend">
<div class="legend-title">ALLELE KEY</div>
<div class="legend-row">
<span class="swatch a"></span>
<span>A · pale dorsal tile</span>
</div>
<div class="legend-row">
<span class="swatch b"></span>
<span>B · charcoal dorsal tile</span>
</div>
<div class="legend-copy">
The bodies remain neutral. Only the sampled gene tiles differ.
Sparklines record each island's independent history.
</div>
</aside>
<div class="camera-tip">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";
// -------------------------------------------------------------------------
// Basic scene
// -------------------------------------------------------------------------
const stage = document.getElementById("stage");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0a2024);
scene.fog = new THREE.Fog(0x0a2024, 27, 63);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.75));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
stage.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
41,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0, 0.35, 0);
let cameraYaw = 0.57;
let cameraPitch = 0.57;
let cameraRadius = 25;
function resetCamera() {
cameraYaw = 0.57;
cameraPitch = 0.57;
cameraRadius = 25;
}
function updateCamera() {
const horizontal = Math.cos(cameraPitch) * cameraRadius;
camera.position.set(
cameraTarget.x + Math.sin(cameraYaw) * horizontal,
cameraTarget.y + Math.sin(cameraPitch) * cameraRadius,
cameraTarget.z + Math.cos(cameraYaw) * horizontal
);
camera.lookAt(cameraTarget);
}
// Direct camera controls; no external controls addon is used.
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - previousPointerX;
const deltaY = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
cameraYaw -= deltaX * 0.006;
cameraPitch = THREE.MathUtils.clamp(
cameraPitch + deltaY * 0.0045,
0.28,
1.08
);
});
function endDrag(event) {
dragging = false;
if (event.pointerId !== undefined) {
try {
renderer.domElement.releasePointerCapture(event.pointerId);
} catch (_) {
// Some browsers release capture automatically.
}
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
17,
38
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 1.75));
});
// -------------------------------------------------------------------------
// Lighting
// -------------------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0xc5ddd6, 0x172522, 2.1));
const sun = new THREE.DirectionalLight(0xffedcf, 3.1);
sun.position.set(11, 18, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -22;
sun.shadow.camera.right = 22;
sun.shadow.camera.top = 22;
sun.shadow.camera.bottom = -22;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 48;
sun.shadow.bias = -0.0005;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x8eb8b4, 1.1);
fill.position.set(-12, 8, -10);
scene.add(fill);
// -------------------------------------------------------------------------
// Voxel ocean
// -------------------------------------------------------------------------
const oceanColumns = 26;
const oceanRows = 26;
const oceanTileSize = 2;
const oceanCount = oceanColumns * oceanRows;
const oceanGeometry = new THREE.BoxGeometry(1.94, 0.08, 1.94);
const oceanMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.83,
metalness: 0.04
});
const ocean = new THREE.InstancedMesh(
oceanGeometry,
oceanMaterial,
oceanCount
);
ocean.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
ocean.receiveShadow = true;
ocean.frustumCulled = false;
scene.add(ocean);
const oceanDummy = new THREE.Object3D();
const oceanColors = [
new THREE.Color(0x0b3035),
new THREE.Color(0x0d373c),
new THREE.Color(0x0a2c32)
];
for (let row = 0; row < oceanRows; row++) {
for (let column = 0; column < oceanColumns; column++) {
const index = row * oceanColumns + column;
const colorIndex = (row + column) % 3;
ocean.setColorAt(index, oceanColors[colorIndex]);
}
}
if (ocean.instanceColor) {
ocean.instanceColor.needsUpdate = true;
}
function updateOcean(time) {
let index = 0;
for (let row = 0; row < oceanRows; row++) {
for (let column = 0; column < oceanColumns; column++) {
const x = (column - oceanColumns / 2 + 0.5) * oceanTileSize;
const z = (row - oceanRows / 2 + 0.5) * oceanTileSize;
const phase = x * 0.31 + z * 0.27;
oceanDummy.position.set(
x,
-0.17 + Math.sin(time * 0.65 + phase) * 0.012,
z
);
oceanDummy.rotation.set(0, 0, 0);
oceanDummy.scale.set(1, 1, 1);
oceanDummy.updateMatrix();
ocean.setMatrixAt(index, oceanDummy.matrix);
index++;
}
}
ocean.instanceMatrix.needsUpdate = true;
}
// -------------------------------------------------------------------------
// Identical island template
// -------------------------------------------------------------------------
const islandCenters = [
{ x: -7.25, z: -3.0 },
{ x: 0.0, z: -7.45 },
{ x: 7.25, z: -3.0 },
{ x: 7.25, z: 4.1 },
{ x: 0.0, z: 7.45 },
{ x: -7.25, z: 4.1 }
];
const cellSize = 0.52;
const terrainCells = [];
for (let x = -3; x <= 3; x++) {
for (let z = -3; z <= 3; z++) {
const distance = Math.abs(x) + Math.abs(z);
if (distance > 5) continue;
const levels =
distance <= 1 ? 3 :
distance <= 3 ? 2 :
1;
terrainCells.push({ x, z, levels });
}
}
const terrainBlockCount =
terrainCells.reduce((sum, cell) => sum + cell.levels, 0) *
islandCenters.length;
const terrainGeometry = new THREE.BoxGeometry(cellSize, cellSize, cellSize);
const terrainMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.96,
metalness: 0
});
const terrain = new THREE.InstancedMesh(
terrainGeometry,
terrainMaterial,
terrainBlockCount
);
terrain.castShadow = true;
terrain.receiveShadow = true;
scene.add(terrain);
const capCount = terrainCells.length * islandCenters.length;
const capGeometry = new THREE.BoxGeometry(0.49, 0.08, 0.49);
const capMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.93
});
const caps = new THREE.InstancedMesh(capGeometry, capMaterial, capCount);
caps.castShadow = true;
caps.receiveShadow = true;
scene.add(caps);
const terrainDummy = new THREE.Object3D();
const lowerEarth = new THREE.Color(0x786f5b);
const upperEarth = new THREE.Color(0x89816c);
const capColor = new THREE.Color(0x68756b);
let terrainIndex = 0;
let capIndex = 0;
for (let islandIndex = 0; islandIndex < islandCenters.length; islandIndex++) {
const center = islandCenters[islandIndex];
for (const cell of terrainCells) {
for (let layer = 0; layer < cell.levels; layer++) {
terrainDummy.position.set(
center.x + cell.x * cellSize,
(layer + 0.5) * cellSize,
center.z + cell.z * cellSize
);
terrainDummy.rotation.set(0, 0, 0);
terrainDummy.scale.set(1, 1, 1);
terrainDummy.updateMatrix();
terrain.setMatrixAt(terrainIndex, terrainDummy.matrix);
terrain.setColorAt(
terrainIndex,
layer === cell.levels - 1 ? upperEarth : lowerEarth
);
terrainIndex++;
}
terrainDummy.position.set(
center.x + cell.x * cellSize,
cell.levels * cellSize + 0.04,
center.z + cell.z * cellSize
);
terrainDummy.updateMatrix();
caps.setMatrixAt(capIndex, terrainDummy.matrix);
caps.setColorAt(capIndex, capColor);
capIndex++;
}
}
if (terrain.instanceColor) terrain.instanceColor.needsUpdate = true;
if (caps.instanceColor) caps.instanceColor.needsUpdate = true;
terrain.computeBoundingSphere();
caps.computeBoundingSphere();
// -------------------------------------------------------------------------
// Population model
//
// Each island has N diploid organisms. A new generation is produced by
// drawing each allele independently from the previous generation's gene
// pool. The six islands use independent random streams but identical rules.
// -------------------------------------------------------------------------
const POPULATION_SIZE = 16;
const ISLAND_COUNT = islandCenters.length;
const CYCLE_LENGTH = 3.4;
let seed = 0x0a17e5;
let running = true;
let speed = 1;
let simulationTime = 0;
let visualTime = 0;
let currentCycle = 0;
let committedGeneration = 0;
let pendingGenotypes = null;
let cycleCommitted = true;
function mulberry32(initialSeed) {
let value = initialSeed >>> 0;
return function random() {
value += 0x6d2b79f5;
let result = value;
result = Math.imul(result ^ (result >>> 15), result | 1);
result ^= result + Math.imul(result ^ (result >>> 7), result | 61);
return ((result ^ (result >>> 14)) >>> 0) / 4294967296;
};
}
const founderPatterns = [
[0, 0],
[0, 1],
[0, 1],
[1, 1]
];
function founderGenotype(index) {
return founderPatterns[index % founderPatterns.length].slice();
}
const islands = islandCenters.map((center, islandIndex) => ({
...center,
index: islandIndex,
genotypes: Array.from(
{ length: POPULATION_SIZE },
(_, individualIndex) => founderGenotype(individualIndex)
),
frequency: 0.5,
history: [0.5],
random: mulberry32(
(seed ^ Math.imul(islandIndex + 1, 0x9e3779b9)) >>> 0
)
}));
function samplePopulation(population) {
const genePool = [];
for (const genotype of population.genotypes) {
genePool.push(genotype[0], genotype[1]);
}
const nextGenotypes = [];
for (let individual = 0; individual < POPULATION_SIZE; individual++) {
const firstParent =
Math.floor(population.random() * genePool.length);
const secondParent =
Math.floor(population.random() * genePool.length);
nextGenotypes.push([
genePool[firstParent],
genePool[secondParent]
]);
}
return nextGenotypes;
}
// -------------------------------------------------------------------------
// Voxel organism positions and instanced anatomy
// -------------------------------------------------------------------------
const organismCells = [
[-2, -1], [-1, -2], [0, -2], [1, -2],
[2, -1], [-2, 0], [-1, 0], [0, 0],
[1, 0], [2, 0], [-2, 1], [-1, 1],
[0, 1], [1, 1], [2, 1], [0, 2]
];
const cellLookup = new Map(
terrainCells.map((cell) => [`${cell.x},${cell.z}`, cell])
);
const organisms = [];
for (let islandIndex = 0; islandIndex < ISLAND_COUNT; islandIndex++) {
for (let individual = 0; individual < POPULATION_SIZE; individual++) {
const [cellX, cellZ] = organismCells[individual];
const cell = cellLookup.get(`${cellX},${cellZ}`);
organisms.push({
islandIndex,
individual,
x: cellX * cellSize,
z: cellZ * cellSize,
y: cell.levels * cellSize + 0.08,
heading: ((individual * 7 + islandIndex * 3) % 12) * 0.12,
phase: individual * 1.731 + islandIndex * 0.917
});
}
}
const organismCount = organisms.length;
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0xaaa797,
roughness: 0.9
});
const headMaterial = new THREE.MeshStandardMaterial({
color: 0xc0baa8,
roughness: 0.88
});
const limbMaterial = new THREE.MeshStandardMaterial({
color: 0x555b57,
roughness: 0.95
});
const eyeMaterial = new THREE.MeshStandardMaterial({
color: 0x19211f,
roughness: 0.72
});
const alleleAMaterial = new THREE.MeshStandardMaterial({
color: 0xe0d6ba,
roughness: 0.78
});
const alleleBMaterial = new THREE.MeshStandardMaterial({
color: 0x4d5551,
roughness: 0.82
});
function makeDynamicInstancedMesh(geometry, material, count) {
const mesh = new THREE.InstancedMesh(geometry, material, count);
mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
mesh.frustumCulled = false;
mesh.castShadow = true;
scene.add(mesh);
return mesh;
}
const bodies = makeDynamicInstancedMesh(
new THREE.BoxGeometry(0.52, 0.42, 0.64),
bodyMaterial,
organismCount
);
const heads = makeDynamicInstancedMesh(
new THREE.BoxGeometry(0.39, 0.34, 0.35),
headMaterial,
organismCount
);
const tails = makeDynamicInstancedMesh(
new THREE.BoxGeometry(0.19, 0.18, 0.23),
bodyMaterial,
organismCount
);
const legs = makeDynamicInstancedMesh(
new THREE.BoxGeometry(0.12, 0.22, 0.12),
limbMaterial,
organismCount * 4
);
const eyes = makeDynamicInstancedMesh(
new THREE.BoxGeometry(0.07, 0.08, 0.035),
eyeMaterial,
organismCount * 2
);
const alleleTilesA = makeDynamicInstancedMesh(
new THREE.BoxGeometry(0.16, 0.12, 0.25),
alleleAMaterial,
organismCount * 2
);
const alleleTilesB = makeDynamicInstancedMesh(
new THREE.BoxGeometry(0.16, 0.12, 0.25),
alleleBMaterial,
organismCount * 2
);
const zeroMatrix = new THREE.Matrix4().makeScale(0, 0, 0);
const organismDummy = new THREE.Object3D();
const organismMatrix = new THREE.Matrix4();
const localMatrix = new THREE.Matrix4();
const finalMatrix = new THREE.Matrix4();
function setPart(mesh, index, baseMatrix, x, y, z) {
localMatrix.makeTranslation(x, y, z);
finalMatrix.multiplyMatrices(baseMatrix, localMatrix);
mesh.setMatrixAt(index, finalMatrix);
}
function smoothstep(value) {
const t = THREE.MathUtils.clamp(value, 0, 1);
return t * t * (3 - 2 * t);
}
function transitionScale(phase) {
if (phase < 0.54) return 1;
if (phase < 0.72) {
return 1 - smoothstep((phase - 0.54) / 0.18);
}
if (phase < 0.9) {
return smoothstep((phase - 0.72) / 0.18);
}
return 1;
}
function updateOrganisms(time, phase) {
const populationScale = transitionScale(phase);
for (let index = 0; index < organisms.length; index++) {
const organism = organisms[index];
const island = islands[organism.islandIndex];
const genotype = island.genotypes[organism.individual];
const bob = Math.sin(time * 2.15 + organism.phase) * 0.035;
const individualScale =
populationScale *
(0.975 + Math.sin(time * 2.6 + organism.phase) * 0.025);
organismDummy.position.set(
island.x + organism.x,
organism.y + bob,
island.z + organism.z
);
organismDummy.rotation.set(
0,
organism.heading +
Math.sin(time * 1.35 + organism.phase) * 0.065,
0
);
organismDummy.scale.setScalar(individualScale);
organismDummy.updateMatrix();
organismMatrix.copy(organismDummy.matrix);
setPart(bodies, index, organismMatrix, 0, 0.33, 0);
setPart(heads, index, organismMatrix, 0, 0.64, 0.24);
setPart(tails, index, organismMatrix, 0, 0.32, -0.38);
const legBase = index * 4;
setPart(legs, legBase + 0, organismMatrix, -0.17, 0.11, -0.18);
setPart(legs, legBase + 1, organismMatrix, 0.17, 0.11, -0.18);
setPart(legs, legBase + 2, organismMatrix, -0.17, 0.11, 0.18);
setPart(legs, legBase + 3, organismMatrix, 0.17, 0.11, 0.18);
const eyeBase = index * 2;
setPart(eyes, eyeBase + 0, organismMatrix, -0.105, 0.67, 0.421);
setPart(eyes, eyeBase + 1, organismMatrix, 0.105, 0.67, 0.421);
const tileBase = index * 2;
for (let alleleIndex = 0; alleleIndex < 2; alleleIndex++) {
const tileIndex = tileBase + alleleIndex;
const x = alleleIndex === 0 ? -0.13 : 0.13;
if (genotype[alleleIndex] === 0) {
setPart(
alleleTilesA,
tileIndex,
organismMatrix,
x,
0.595,
-0.09
);
alleleTilesB.setMatrixAt(tileIndex, zeroMatrix);
} else {
setPart(
alleleTilesB,
tileIndex,
organismMatrix,
x,
0.595,
-0.09
);
alleleTilesA.setMatrixAt(tileIndex, zeroMatrix);
}
}
}
bodies.instanceMatrix.needsUpdate = true;
heads.instanceMatrix.needsUpdate = true;
tails.instanceMatrix.needsUpdate = true;
legs.instanceMatrix.needsUpdate = true;
eyes.instanceMatrix.needsUpdate = true;
alleleTilesA.instanceMatrix.needsUpdate = true;
alleleTilesB.instanceMatrix.needsUpdate = true;
}
// Small voxel tokens appear during each sampling round.
const tokensPerIsland = 6;
const tokenGeometry = new THREE.BoxGeometry(0.11, 0.11, 0.11);
const tokenMaterial = new THREE.MeshBasicMaterial({
color: 0xeee5ca
});
const samplingTokens = new THREE.InstancedMesh(
tokenGeometry,
tokenMaterial,
ISLAND_COUNT * tokensPerIsland
);
samplingTokens.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
samplingTokens.frustumCulled = false;
scene.add(samplingTokens);
function updateSamplingTokens(time, phase) {
const active = phase >= 0.5 && phase <= 0.78;
const progress = active
? THREE.MathUtils.clamp((phase - 0.5) / 0.28, 0, 1)
: 0;
const pulse = active ? Math.sin(progress * Math.PI) : 0;
let instanceIndex = 0;
for (let islandIndex = 0; islandIndex < ISLAND_COUNT; islandIndex++) {
const island = islands[islandIndex];
for (let token = 0; token < tokensPerIsland; token++) {
const angle =
time * 3.4 +
token * 1.047 +
islandIndex * 1.83;
const radius = 0.82 + Math.sin(angle * 1.4 + token) * 0.18;
const scale = pulse * (0.55 + 0.35 * Math.sin(angle * 2.1));
organismDummy.position.set(
island.x + Math.cos(angle) * radius,
1.35 + Math.sin(angle * 1.8) * 0.34,
island.z + Math.sin(angle) * radius
);
organismDummy.rotation.set(
time * 1.4 + token,
angle * 0.7,
time * 0.9
);
organismDummy.scale.setScalar(scale);
organismDummy.updateMatrix();
samplingTokens.setMatrixAt(instanceIndex, organismDummy.matrix);
instanceIndex++;
}
}
samplingTokens.instanceMatrix.needsUpdate = true;
}
// -------------------------------------------------------------------------
// HUD: cards, world labels, and history graphs
// -------------------------------------------------------------------------
const islandGrid = document.getElementById("island-grid");
const worldLabels = document.getElementById("world-labels");
const cardElements = [];
const worldTagElements = [];
for (let islandIndex = 0; islandIndex < ISLAND_COUNT; islandIndex++) {
const number = String(islandIndex + 1).padStart(2, "0");
const card = document.createElement("article");
card.className = "island-card";
card.innerHTML = `
<div class="island-card-head">
<span>ISLAND ${number}</span>
<strong class="card-frequency">50%</strong>
</div>
<div class="frequency-track">
<span class="allele-a"></span>
</div>
<svg class="sparkline" viewBox="0 0 100 26" preserveAspectRatio="none">
<line x1="0" y1="13" x2="100" y2="13"></line>
<path d="M 0 13"></path>
</svg>
`;
islandGrid.appendChild(card);
cardElements.push({
frequency: card.querySelector(".card-frequency"),
alleleA: card.querySelector(".allele-a"),
path: card.querySelector(".sparkline path")
});
const tag = document.createElement("div");
tag.className = "world-tag";
tag.innerHTML = `
<div class="tag-top">
<span>ISLAND ${number}</span>
<strong class="tag-frequency">A 50%</strong>
</div>
<div class="tag-track">
<span class="tag-a"></span>
</div>
`;
worldLabels.appendChild(tag);
worldTagElements.push({
root: tag,
frequency: tag.querySelector(".tag-frequency"),
alleleA: tag.querySelector(".tag-a")
});
}
const meanFrequencyElement = document.getElementById("mean-frequency");
const islandSpreadElement = document.getElementById("island-spread");
const generationLabel = document.getElementById("generation-label");
const seedLabel = document.getElementById("seed-label");
const runState = document.getElementById("run-state");
function sparklinePath(history) {
if (history.length < 2) return "M 0 13";
return history
.map((frequency, index) => {
const x = (index / (history.length - 1)) * 100;
const y = 2 + (1 - frequency) * 22;
return `${index === 0 ? "M" : "L"} ${x.toFixed(2)} ${y.toFixed(2)}`;
})
.join(" ");
}
function updateStatistics() {
const frequencies = islands.map((island) => {
const alleleACount = island.genotypes.reduce(
(sum, genotype) => sum + (genotype[0] === 0 ? 1 : 0) +
(genotype[1] === 0 ? 1 : 0),
0
);
const frequency = alleleACount / (POPULATION_SIZE * 2);
island.frequency = frequency;
island.history.push(frequency);
return frequency;
});
const mean = frequencies.reduce((sum, value) => sum + value, 0) /
frequencies.length;
const minimum = Math.min(...frequencies);
const maximum = Math.max(...frequencies);
const spread = (maximum - minimum) * 100;
meanFrequencyElement.textContent = `${(mean * 100).toFixed(1)}%`;
islandSpreadElement.textContent = `${spread.toFixed(1)} pp`;
generationLabel.textContent =
`GEN ${String(committedGeneration).padStart(3, "0")}`;
for (let index = 0; index < ISLAND_COUNT; index++) {
const frequency = frequencies[index];
const card = cardElements[index];
const tag = worldTagElements[index];
card.frequency.textContent = `${Math.round(frequency * 100)}%`;
card.alleleA.style.width = `${frequency * 100}%`;
card.path.setAttribute("d", sparklinePath(islands[index].history));
tag.frequency.textContent = `A ${Math.round(frequency * 100)}%`;
tag.alleleA.style.width = `${frequency * 100}%`;
}
}
const projectedPosition = new THREE.Vector3();
function updateWorldLabels() {
for (let index = 0; index < ISLAND_COUNT; index++) {
const island = islands[index];
const tag = worldTagElements[index].root;
projectedPosition.set(island.x, 2.45, island.z).project(camera);
const visible = projectedPosition.z > -1 && projectedPosition.z < 1;
tag.style.opacity = visible ? "1" : "0";
const x = (projectedPosition.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projectedPosition.y * 0.5 + 0.5) * window.innerHeight;
tag.style.left = `${x}px`;
tag.style.top = `${y}px`;
}
}
// -------------------------------------------------------------------------
// Simulation lifecycle
// -------------------------------------------------------------------------
function updateSimulation(deltaTime) {
if (running) {
simulationTime += deltaTime * speed;
}
const cycle = Math.floor(simulationTime / CYCLE_LENGTH);
const phase = (simulationTime % CYCLE_LENGTH) / CYCLE_LENGTH;
if (cycle !== currentCycle) {
currentCycle = cycle;
pendingGenotypes = islands.map(samplePopulation);
cycleCommitted = false;
}
if (
pendingGenotypes &&
phase >= 0.66 &&
!cycleCommitted
) {
for (let index = 0; index < ISLAND_COUNT; index++) {
islands[index].genotypes = pendingGenotypes[index];
}
committedGeneration = currentCycle;
cycleCommitted = true;
updateStatistics();
}
if (!running) {
runState.textContent = "PAUSED";
} else if (phase >= 0.5 && phase <= 0.78) {
runState.textContent = "SAMPLING";
} else {
runState.textContent = "BREEDING";
}
return phase;
}
function resetSimulation() {
seed = (Math.random() * 0xffffffff) >>> 0;
for (let islandIndex = 0; islandIndex < ISLAND_COUNT; islandIndex++) {
const island = islands[islandIndex];
island.genotypes = Array.from(
{ length: POPULATION_SIZE },
(_, individualIndex) => founderGenotype(individualIndex)
);
island.frequency = 0.5;
island.history = [0.5];
island.random = mulberry32(
(seed ^ Math.imul(islandIndex + 1, 0x9e3779b9)) >>> 0
);
}
simulationTime = 0;
currentCycle = 0;
committedGeneration = 0;
pendingGenotypes = null;
cycleCommitted = true;
seedLabel.textContent =
`SEED ${seed.toString(16).toUpperCase().padStart(8, "0").slice(-6)}`;
updateStatistics();
}
const playButton = document.getElementById("play-button");
const speedButton = document.getElementById("speed-button");
const newButton = document.getElementById("new-button");
function updatePlayButton() {
playButton.innerHTML = running
? '<span aria-hidden="true">Ⅱ</span> Pause'
: '<span aria-hidden="true">▶</span> Play';
playButton.setAttribute(
"aria-label",
running ? "Pause simulation" : "Play simulation"
);
}
playButton.addEventListener("click", () => {
running = !running;
updatePlayButton();
});
const speedOptions = [0.5, 1, 2, 4];
speedButton.addEventListener("click", () => {
const currentIndex = speedOptions.indexOf(speed);
speed = speedOptions[(currentIndex + 1) % speedOptions.length];
speedButton.textContent = `${speed}×`;
});
newButton.addEventListener("click", () => {
resetSimulation();
running = true;
updatePlayButton();
});
window.addEventListener("keydown", (event) => {
if (event.code === "Space") {
event.preventDefault();
running = !running;
updatePlayButton();
}
if (event.key.toLowerCase() === "r") {
resetSimulation();
}
});
// -------------------------------------------------------------------------
// Start
// -------------------------------------------------------------------------
seedLabel.textContent =
`SEED ${seed.toString(16).toUpperCase().padStart(8, "0").slice(-6)}`;
updatePlayButton();
updateStatistics();
updateCamera();
const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
const deltaTime = Math.min(clock.getDelta(), 0.05);
visualTime += deltaTime;
const phase = updateSimulation(deltaTime);
updateOcean(visualTime);
updateOrganisms(visualTime, phase);
updateSamplingTokens(visualTime, phase);
updateCamera();
renderer.render(scene, camera);
updateWorldLabels();
});
</script>
</body>
</html>
```