Prompt specification
Build or customize the Three.js 3D scene "Repeated inheritance sampling 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: Repeated inheritance sampling explorer
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/repeated-inheritance-sampling-explorer-x0924
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts parental genetic inheritance. Generate many fictional offspring under a displayed one-locus model; compare observed counts with expected probabilities and show sampling variation rather than forcing exact ratios. Voxel style.
Working Three.js Starter (repeated-inheritance-sampling-explorer-x0924):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Genetics — Parental Inheritance Lab</title>
<style>
:root {
--bg: #080c15;
--panel: rgba(13, 20, 35, 0.84);
--panel-solid: #101828;
--line: rgba(255, 255, 255, 0.13);
--text: #f4f7ff;
--muted: #9aa9bf;
--gold: #ffd166;
--mint: #5eead4;
--pink: #f472b6;
--blue: #7397ff;
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button, select, input { font: inherit; }
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas:active { cursor: grabbing; }
.panel {
position: fixed;
z-index: 5;
background: var(--panel);
border: 1px solid var(--line);
box-shadow:
0 20px 60px rgba(0, 0, 0, 0.34),
inset 0 1px 0 rgba(255, 255, 255, 0.04);
backdrop-filter: blur(18px);
-webkit-backdrop-filter: blur(18px);
border-radius: 5px;
}
#hero {
position: fixed;
z-index: 4;
top: 24px;
left: 24px;
width: min(540px, calc(100vw - 48px));
pointer-events: none;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
color: #c8d5e9;
font: 700 11px/1 var(--mono);
letter-spacing: 0.14em;
text-transform: uppercase;
}
.live-dot {
width: 7px;
height: 7px;
background: var(--mint);
box-shadow: 0 0 16px var(--mint);
}
h1 {
margin: 13px 0 8px;
max-width: 540px;
font-size: clamp(30px, 4vw, 52px);
line-height: 0.98;
letter-spacing: -0.055em;
}
h1 span {
color: var(--mint);
}
#hero p {
margin: 0;
max-width: 480px;
color: var(--muted);
font-size: 14px;
line-height: 1.55;
}
#model-panel {
left: 24px;
bottom: 24px;
width: 330px;
padding: 18px;
}
#results {
top: 24px;
right: 24px;
width: 370px;
padding: 18px;
max-height: calc(100vh - 48px);
overflow: auto;
scrollbar-width: thin;
scrollbar-color: #334155 transparent;
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 15px;
}
h2 {
margin: 0;
font-size: 15px;
letter-spacing: -0.01em;
}
.micro-label {
color: var(--muted);
font: 700 10px/1.2 var(--mono);
letter-spacing: 0.1em;
text-transform: uppercase;
}
.model-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.field label {
display: block;
margin-bottom: 6px;
color: var(--muted);
font-size: 11px;
font-weight: 650;
}
select {
width: 100%;
appearance: none;
padding: 10px 30px 10px 11px;
color: var(--text);
background:
linear-gradient(45deg, transparent 50%, #91a0b8 50%) calc(100% - 15px) 50% / 5px 5px no-repeat,
linear-gradient(135deg, #91a0b8 50%, transparent 50%) calc(100% - 10px) 50% / 5px 5px no-repeat,
#0a1120;
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 3px;
outline: none;
font: 700 15px var(--mono);
cursor: pointer;
}
select:focus {
border-color: var(--mint);
box-shadow: 0 0 0 2px rgba(94, 234, 212, 0.1);
}
.range-head {
display: flex;
justify-content: space-between;
align-items: baseline;
margin: 17px 0 7px;
color: var(--muted);
font-size: 11px;
font-weight: 650;
}
output {
color: var(--text);
font: 700 13px var(--mono);
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 5px 0 17px;
appearance: none;
background: #29364d;
border-radius: 0;
outline: none;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
appearance: none;
width: 15px;
height: 15px;
background: var(--mint);
border: 3px solid #102029;
box-shadow: 0 0 0 1px var(--mint);
cursor: ew-resize;
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
background: var(--mint);
border: 3px solid #102029;
border-radius: 0;
cursor: ew-resize;
}
.primary-button {
width: 100%;
padding: 11px 12px;
color: #071512;
background: var(--mint);
border: 0;
border-radius: 3px;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.025em;
cursor: pointer;
transition: transform 120ms ease, filter 120ms ease;
}
.primary-button:hover {
filter: brightness(1.08);
transform: translateY(-1px);
}
.primary-button:active { transform: translateY(0); }
.model-note {
margin-top: 13px;
padding-top: 12px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.allele-key {
display: inline-block;
width: 8px;
height: 8px;
margin-right: 4px;
vertical-align: 1px;
}
.allele-key.a { background: var(--gold); }
.allele-key.mint { background: var(--mint); }
.run-meta {
display: flex;
justify-content: space-between;
padding: 10px 0;
border-top: 1px solid var(--line);
border-bottom: 1px solid var(--line);
color: var(--muted);
font: 11px var(--mono);
}
.run-meta strong {
color: var(--text);
font-weight: 700;
}
.comparison-title {
display: flex;
justify-content: space-between;
margin: 15px 0 11px;
color: var(--muted);
font-size: 10px;
}
.comparison-title span:last-child {
font-family: var(--mono);
}
.genotype-row + .genotype-row {
margin-top: 11px;
}
.genotype-head {
display: grid;
grid-template-columns: 40px 1fr auto;
align-items: center;
gap: 8px;
margin-bottom: 5px;
font: 11px var(--mono);
}
.genotype-code {
font-weight: 800;
}
.observed-count {
color: var(--text);
text-align: right;
}
.expected-count {
color: var(--muted);
font-size: 10px;
}
.bar-track {
position: relative;
height: 44px;
overflow: hidden;
background:
linear-gradient(to top, transparent 24.5%, rgba(255,255,255,.09) 25%, transparent 25.5%),
linear-gradient(to top, transparent 49.5%, rgba(255,255,255,.09) 50%, transparent 50.5%),
rgba(255, 255, 255, 0.035);
border: 1px solid rgba(255, 255, 255, 0.07);
}
.observed-bar {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
min-height: 2px;
opacity: 0.82;
}
.expected-marker {
position: absolute;
left: 0;
width: 100%;
height: 0;
border-top: 2px dashed #f6f8ff;
filter: drop-shadow(0 0 3px rgba(255,255,255,.4));
}
.phenotype-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 15px;
}
.phenotype-card {
padding: 11px;
background: rgba(255, 255, 255, 0.035);
border: 1px solid rgba(255, 255, 255, 0.07);
}
.phenotype-card .name {
margin-bottom: 8px;
color: var(--muted);
font-size: 10px;
}
.phenotype-card .value {
font: 800 19px var(--mono);
}
.phenotype-card .expected {
margin-top: 4px;
color: var(--muted);
font: 10px var(--mono);
}
.variation-note {
margin-top: 13px;
padding: 10px 11px;
color: #c9d5e7;
background: rgba(94, 234, 212, 0.06);
border-left: 2px solid var(--mint);
font-size: 11px;
line-height: 1.5;
}
.fine-print {
margin: 12px 0 0;
color: #77869c;
font-size: 10px;
line-height: 1.45;
}
#legend {
position: fixed;
z-index: 4;
left: 50%;
bottom: 24px;
transform: translateX(-50%);
display: flex;
gap: 15px;
align-items: center;
padding: 9px 12px;
background: rgba(10, 16, 28, 0.72);
border: 1px solid var(--line);
color: var(--muted);
font: 10px var(--mono);
backdrop-filter: blur(10px);
pointer-events: none;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
white-space: nowrap;
}
.swatch {
width: 9px;
height: 9px;
}
#reset-view {
position: fixed;
z-index: 5;
right: 24px;
bottom: 24px;
padding: 9px 11px;
color: #c6d1e2;
background: rgba(13, 20, 35, 0.84);
border: 1px solid var(--line);
border-radius: 3px;
font: 10px var(--mono);
cursor: pointer;
}
#reset-view:hover { color: white; border-color: rgba(255,255,255,.3); }
#tooltip {
position: fixed;
z-index: 10;
display: none;
width: 250px;
padding: 12px;
background: rgba(7, 12, 22, 0.96);
border: 1px solid rgba(255, 255, 255, 0.19);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
pointer-events: none;
font-size: 11px;
line-height: 1.5;
}
#tooltip strong {
display: block;
margin-bottom: 4px;
font: 800 14px var(--mono);
}
#tooltip .tooltip-muted { color: var(--muted); }
#loading {
position: fixed;
z-index: 20;
inset: 0;
display: grid;
place-items: center;
color: var(--mint);
background: var(--bg);
font: 700 12px var(--mono);
letter-spacing: 0.12em;
}
@media (max-width: 900px) {
#hero { top: 16px; left: 16px; }
#model-panel { left: 16px; bottom: 16px; width: 300px; }
#results {
top: 16px;
right: 16px;
width: 330px;
max-height: calc(100vh - 32px);
}
#legend { bottom: 16px; }
#reset-view { right: 16px; bottom: 16px; }
}
@media (max-width: 680px) {
#hero p { display: none; }
#hero h1 { margin-bottom: 0; font-size: 31px; }
#results {
top: 92px;
left: 10px;
right: 10px;
width: auto;
max-height: 35vh;
padding: 13px;
}
#model-panel {
left: 10px;
right: 10px;
bottom: 10px;
width: auto;
padding: 13px;
}
.model-grid { gap: 7px; }
.model-note { display: none; }
#legend {
left: 10px;
bottom: 223px;
transform: none;
gap: 8px;
padding: 7px;
font-size: 9px;
}
#reset-view { display: none; }
.phenotype-grid { display: none; }
.fine-print { font-size: 9px; }
}
</style>
</head>
<body>
<div id="scene"></div>
<div id="loading">LOADING THREE.JS…</div>
<header id="hero">
<div class="eyebrow">
<span class="live-dot"></span>
Population genetics lab / live simulation
</div>
<h1>One locus.<br><span>Many possibilities.</span></h1>
<p>
Every fictional child inherits one allele from each parent.
Expected ratios are probabilities—not quotas—so the observed cohort varies.
</p>
</header>
<section id="model-panel" class="panel">
<div class="panel-heading">
<h2>One-locus model</h2>
<span class="micro-label">Complete dominance</span>
</div>
<div class="model-grid">
<div class="field">
<label for="parent-1">Parent 1</label>
<select id="parent-1">
<option value="AA">AA</option>
<option value="Aa" selected>Aa</option>
<option value="aa">aa</option>
</select>
</div>
<div class="field">
<label for="parent-2">Parent 2</label>
<select id="parent-2">
<option value="AA">AA</option>
<option value="Aa" selected>Aa</option>
<option value="aa">aa</option>
</select>
</div>
</div>
<div class="range-head">
<span>Cohort size</span>
<output id="cohort-output">240</output>
</div>
<input id="cohort-size" type="range" min="80" max="600" step="20" value="240">
<button id="generate" class="primary-button">Generate a new cohort</button>
<div class="model-note">
<span class="allele-key a"></span><b>A</b> is the dominant allele.
<span class="allele-key mint"></span><b>a</b> is recessive.
Each heterozygous parent transmits A or a with probability ½.
</div>
</section>
<section id="results" class="panel" aria-live="polite">
<div class="panel-heading">
<h2>Observed cohort</h2>
<span class="micro-label">Sampling variation</span>
</div>
<div class="run-meta">
<span><strong id="result-count">240</strong> children</span>
<span>seed <strong id="seed-value">00000000</strong></span>
</div>
<div class="comparison-title">
<span>GENOTYPE DISTRIBUTION</span>
<span>bar: observed · dash: expected</span>
</div>
<div id="comparison"></div>
<div class="phenotype-grid">
<div class="phenotype-card">
<div class="name">DOMINANT PHENOTYPE</div>
<div id="dominant-count" class="value">0</div>
<div id="dominant-expected" class="expected">expected 0</div>
</div>
<div class="phenotype-card">
<div class="name">RECESSIVE PHENOTYPE</div>
<div id="recessive-count" class="value">0</div>
<div id="recessive-expected" class="expected">expected 0</div>
</div>
</div>
<div id="variation-note" class="variation-note"></div>
<p class="fine-print">
Every generated offspring contributes to the counts. The 3D gallery previews
up to 42 voxel figures per genotype class. Click a figure to inspect it.
</p>
</section>
<div id="legend">
<span class="legend-item"><i class="swatch" style="background:#ffd166"></i>A allele</span>
<span class="legend-item"><i class="swatch" style="background:#5eead4"></i>a allele</span>
<span class="legend-item"><i class="swatch" style="background:#7397ff"></i>dominant body</span>
<span class="legend-item"><i class="swatch" style="background:#f472b6"></i>recessive body</span>
</div>
<button id="reset-view">RESET VIEW</button>
<div id="tooltip"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = id => document.getElementById(id);
const colors = {
A: 0xffd166,
a: 0x5eead4,
AA: 0xffd166,
Aa: 0x5eead4,
aa: 0xf472b6,
dominant: 0x7397ff,
recessive: 0xf472b6,
skin: 0xe9bb91,
dark: 0x111827
};
const state = {
parent1: "Aa",
parent2: "Aa",
n: 240,
seed: 0,
offspring: [],
counts: { AA: 0, Aa: 0, aa: 0 },
probabilities: { AA: 0, Aa: 0, aa: 0 }
};
// ---------- Renderer and scene ----------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x080c15);
scene.fog = new THREE.FogExp2(0x080c15, 0.022);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.18;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
$("scene").appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
140
);
const cameraTarget = new THREE.Vector3(0, 1.4, -2.1);
const cameraHome = {
theta: 0.34,
phi: 1.00,
radius: 30
};
const cameraState = { ...cameraHome };
function updateCamera() {
const { theta, phi, radius } = cameraState;
const sinPhi = Math.sin(phi);
camera.position.set(
cameraTarget.x + radius * sinPhi * Math.sin(theta),
cameraTarget.y + radius * Math.cos(phi),
cameraTarget.z + radius * sinPhi * Math.cos(theta)
);
camera.lookAt(cameraTarget);
}
updateCamera();
scene.add(new THREE.HemisphereLight(0xbdd7ff, 0x182033, 2.2));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.0);
keyLight.position.set(8, 17, 11);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -20;
keyLight.shadow.camera.right = 20;
keyLight.shadow.camera.top = 18;
keyLight.shadow.camera.bottom = -18;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 55;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const mintLight = new THREE.PointLight(0x5eead4, 35, 30, 2);
mintLight.position.set(-10, 7, -7);
scene.add(mintLight);
const pinkLight = new THREE.PointLight(0xf472b6, 25, 26, 2);
pinkLight.position.set(10, 5, -5);
scene.add(pinkLight);
const floor = new THREE.Mesh(
new THREE.BoxGeometry(32, 0.4, 30),
new THREE.MeshStandardMaterial({
color: 0x0d1424,
roughness: 0.94,
metalness: 0.05
})
);
floor.position.set(0, -0.23, -2);
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(32, 32, 0x3b4b67, 0x202b40);
grid.position.set(0, 0.005, -2);
grid.material.transparent = true;
grid.material.opacity = 0.3;
scene.add(grid);
const backWall = new THREE.Mesh(
new THREE.BoxGeometry(32, 11, 0.4),
new THREE.MeshStandardMaterial({ color: 0x0a1020, roughness: 1 })
);
backWall.position.set(0, 5.1, -15.2);
backWall.receiveShadow = true;
scene.add(backWall);
// Decorative voxel pylons.
for (const side of [-1, 1]) {
for (let i = 0; i < 5; i++) {
const height = 0.6 + i * 0.38;
const pylon = new THREE.Mesh(
new THREE.BoxGeometry(0.8, height, 0.8),
new THREE.MeshStandardMaterial({
color: i % 2 ? 0x17243b : 0x20304a,
roughness: 0.75
})
);
pylon.position.set(side * 14.2, height / 2, 5 - i * 3.4);
pylon.castShadow = true;
scene.add(pylon);
}
}
// Distant particles.
const starPositions = [];
for (let i = 0; i < 180; i++) {
starPositions.push(
(Math.random() - 0.5) * 36,
4 + Math.random() * 20,
-14 + Math.random() * 32
);
}
const starGeometry = new THREE.BufferGeometry();
starGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(starPositions, 3)
);
const stars = new THREE.Points(
starGeometry,
new THREE.PointsMaterial({
color: 0x88a1c9,
size: 0.045,
transparent: true,
opacity: 0.65
})
);
scene.add(stars);
// ---------- Text and voxel helpers ----------
function roundedRect(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
ctx.lineTo(x + w, y + h - r);
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
ctx.lineTo(x + r, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
}
function makeTextPlane(
text,
width,
height,
{
fontSize = 52,
color = "#f4f7ff",
background = null,
align = "center",
weight = 700
} = {}
) {
const canvas = document.createElement("canvas");
canvas.width = 1024;
canvas.height = 256;
const ctx = canvas.getContext("2d");
if (background) {
ctx.fillStyle = background;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
const lines = text.split("\n");
ctx.textAlign = align;
ctx.textBaseline = "middle";
ctx.fillStyle = color;
ctx.font = `${weight} ${fontSize}px ui-monospace, Menlo, Consolas, monospace`;
const x = align === "left" ? 28 : canvas.width / 2;
const startY = canvas.height / 2 - ((lines.length - 1) * fontSize * 0.65);
lines.forEach((line, index) => {
ctx.fillText(
line,
x,
startY + index * fontSize * 1.3,
canvas.width - 56
);
});
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.MeshBasicMaterial({
map: texture,
transparent: true,
depthWrite: false,
side: THREE.DoubleSide,
toneMapped: false
});
return new THREE.Mesh(new THREE.PlaneGeometry(width, height), material);
}
function makeLabelSprite(title, subtitle, accent = "#5eead4", width = 4.5) {
const canvas = document.createElement("canvas");
canvas.width = 768;
canvas.height = 240;
const ctx = canvas.getContext("2d");
roundedRect(ctx, 5, 5, 758, 230, 18);
ctx.fillStyle = "rgba(8, 14, 27, 0.91)";
ctx.fill();
ctx.strokeStyle = "rgba(255,255,255,0.18)";
ctx.lineWidth = 3;
ctx.stroke();
ctx.fillStyle = accent;
ctx.fillRect(18, 18, 10, 204);
ctx.textAlign = "left";
ctx.textBaseline = "middle";
ctx.fillStyle = "#f4f7ff";
ctx.font = "800 56px ui-monospace, Menlo, Consolas, monospace";
ctx.fillText(title, 55, 87, 675);
ctx.fillStyle = "#a8b7cb";
ctx.font = "600 31px ui-monospace, Menlo, Consolas, monospace";
ctx.fillText(subtitle, 57, 160, 675);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false,
toneMapped: false
})
);
sprite.scale.set(width, width * 240 / 768, 1);
return sprite;
}
function makeBadgeSprite(letter, accent) {
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 128;
const ctx = canvas.getContext("2d");
roundedRect(ctx, 6, 6, 116, 116, 12);
ctx.fillStyle = "#0b1323";
ctx.fill();
ctx.strokeStyle = accent;
ctx.lineWidth = 7;
ctx.stroke();
ctx.fillStyle = accent;
ctx.font = "900 67px ui-monospace, Menlo, Consolas, monospace";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(letter, 64, 66);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false,
toneMapped: false
})
);
sprite.scale.set(0.48, 0.48, 1);
return sprite;
}
function boxMesh(width, height, depth, color, x, y, z) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
new THREE.MeshStandardMaterial({
color,
roughness: 0.72,
metalness: 0.05
})
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
function clearGroup(group) {
if (!group) return;
group.traverse(object => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const materials = Array.isArray(object.material)
? object.material
: [object.material];
for (const material of materials) {
if (material.map) material.map.dispose();
material.dispose();
}
}
});
if (group.parent) group.parent.remove(group);
}
function phenotypeFor(genotype) {
return genotype === "aa" ? "recessive" : "dominant";
}
function sortedGenotype(first, second) {
if (first === "A" && second === "a") return "Aa";
if (first === "a" && second === "A") return "Aa";
return first + second;
}
// ---------- Parents ----------
const parentGroups = [];
function createParent(genotype, x, title) {
const group = new THREE.Group();
const phenotype = phenotypeFor(genotype);
const coat = phenotype === "dominant" ? colors.dominant : colors.recessive;
group.add(boxMesh(0.48, 0.75, 0.48, colors.dark, -0.28, 0.38, 0));
group.add(boxMesh(0.48, 0.75, 0.48, colors.dark, 0.28, 0.38, 0));
group.add(boxMesh(0.18, 0.2, 0.62, 0x263449, -0.28, 0.1, 0.08));
group.add(boxMesh(0.18, 0.2, 0.62, 0x263449, 0.28, 0.1, 0.08));
group.add(boxMesh(1.05, 1.0, 0.55, coat, 0, 1.18, 0));
group.add(boxMesh(0.32, 0.88, 0.38, coat, -0.68, 1.16, 0));
group.add(boxMesh(0.32, 0.88, 0.38, coat, 0.68, 1.16, 0));
group.add(boxMesh(0.77, 0.78, 0.72, colors.skin, 0, 2.04, 0));
group.add(boxMesh(0.83, 0.24, 0.77, 0x1d2433, 0, 2.43, 0));
group.add(boxMesh(0.14, 0.14, 0.08, 0x172033, -0.19, 2.08, 0.4));
group.add(boxMesh(0.14, 0.14, 0.08, 0x172033, 0.19, 2.08, 0.4));
const alleles = genotype.split("");
alleles.forEach((allele, index) => {
const alleleX = index === 0 ? -0.38 : 0.38;
const alleleColor = colors[allele];
group.add(boxMesh(0.68, 0.68, 0.68, alleleColor, alleleX, 3.12, 0));
const badge = makeBadgeSprite(
allele,
allele === "A" ? "#ffd166" : "#5eead4"
);
badge.position.set(alleleX, 3.14, 0.38);
group.add(badge);
});
const label = makeLabelSprite(
`${title} · ${genotype}`,
`${phenotype} phenotype`,
phenotype === "dominant" ? "#7397ff" : "#f472b6",
4.3
);
label.position.set(0, 4.35, 0);
group.add(label);
group.position.set(x, 0.45, 3.45);
scene.add(group);
parentGroups.push(group);
return group;
}
createParent("Aa", -8.7, "Parent 1");
createParent("Aa", 8.7, "Parent 2");
function refreshParentAppearance() {
const genotypes = [state.parent1, state.parent2];
const positions = [-8.7, 8.7];
parentGroups.forEach((group, index) => {
const genotype = genotypes[index];
const phenotype = phenotypeFor(genotype);
const coat = phenotype === "dominant" ? colors.dominant : colors.recessive;
group.traverse(object => {
if (!object.isMesh || !object.material) return;
// Torso and arms are the wide central pieces.
const s = object.scale;
if (s.x > 0.8 && s.y > 0.8) {
object.material.color.setHex(coat);
}
});
group.children
.filter(child => child.isSprite)
.forEach(sprite => {
if (sprite.scale.x > 1) {
sprite.material.map?.dispose();
sprite.material.dispose();
const replacement = makeLabelSprite(
`Parent ${index + 1} · ${genotype}`,
`${phenotype} phenotype`,
phenotype === "dominant" ? "#7397ff" : "#f472b6",
4.3
);
sprite.material = replacement.material;
sprite.scale.copy(replacement.scale);
}
});
// Remove and replace the two floating allele badges.
const oldBadges = group.children.filter(child =>
child.isSprite && child.scale.x < 1
);
oldBadges.forEach(badge => {
group.remove(badge);
badge.material.map?.dispose();
badge.material.dispose();
});
genotype.split("").forEach((allele, alleleIndex) => {
const badge = makeBadgeSprite(
allele,
allele === "A" ? "#ffd166" : "#5eead4"
);
badge.position.set(alleleIndex === 0 ? -0.38 : 0.38, 3.14, 0.38);
group.add(badge);
});
});
}
// ---------- Dynamic board, population and flows ----------
let boardGroup = null;
let populationGroup = null;
let flowGroup = null;
let childMesh = null;
const flowParticles = [];
function buildPunnettBoard() {
clearGroup(boardGroup);
boardGroup = new THREE.Group();
boardGroup.position.set(0, 4.75, -11.15);
scene.add(boardGroup);
const maternalGametes = [...new Set(state.parent1.split(""))];
const paternalGametes = [...new Set(state.parent2.split(""))];
const board = boxMesh(7.1, 5.1, 0.3, 0x101a2c, 0, 0, 0);
board.castShadow = false;
boardGroup.add(board);
const title = makeTextPlane("PUNNETT SQUARE", 3.4, 0.42, {
fontSize: 58,
color: "#f4f7ff"
});
title.position.set(0, 2.12, 0.17);
boardGroup.add(title);
const axisLabel = makeTextPlane("PATERNAL GAMETES →", 3.8, 0.28, {
fontSize: 30,
color: "#91a2ba"
});
axisLabel.position.set(0, 1.69, 0.17);
boardGroup.add(axisLabel);
const rows = maternalGametes.length;
const cols = paternalGametes.length;
const cellWidth = 2.3;
const cellHeight = 1.22;
paternalGametes.forEach((allele, col) => {
const x = (col - (cols - 1) / 2) * 2.6;
const header = makeTextPlane(allele, 0.7, 0.5, {
fontSize: 78,
color: allele === "A" ? "#ffd166" : "#5eead4"
});
header.position.set(x, 1.23, 0.18);
boardGroup.add(header);
});
maternalGametes.forEach((allele, row) => {
const y = rows === 1 ? 0.05 : 0.28 - row * 1.42;
const header = makeTextPlane(allele, 0.6, 0.48, {
fontSize: 75,
color: allele === "A" ? "#ffd166" : "#5eead4"
});
header.position.set(-3.04, y, 0.18);
boardGroup.add(header);
paternalGametes.forEach((paternal, col) => {
const x = (col - (cols - 1) / 2) * 2.6;
const genotype = sortedGenotype(allele, paternal);
const probability = 1 / (rows * cols);
const accent = colors[genotype];
const cell = boxMesh(
cellWidth,
cellHeight,
0.13,
new THREE.Color(accent).multiplyScalar(0.13).getHex(),
x,
y,
0.16
);
cell.castShadow = false;
boardGroup.add(cell);
const border = new THREE.LineSegments(
new THREE.EdgesGeometry(cell.geometry),
new THREE.LineBasicMaterial({
color: accent,
transparent: true,
opacity: 0.48
})
);
border.position.copy(cell.position);
boardGroup.add(border);
const cross = makeTextPlane(
`${allele} × ${paternal}`,
1.8,
0.28,
{ fontSize: 35, color: "#b8c6da" }
);
cross.position.set(x, y + 0.28, 0.245);
boardGroup.add(cross);
const result = makeTextPlane(
`${genotype} · ${(probability * 100).toFixed(0)}%`,
1.95,
0.32,
{
fontSize: 43,
color: `#${new THREE.Color(accent).getHexString()}`
}
);
result.position.set(x, y - 0.25, 0.245);
boardGroup.add(result);
});
});
const maternalLabel = makeTextPlane("MATERNAL ↓", 1.7, 0.27, {
fontSize: 28,
color: "#91a2ba"
});
maternalLabel.rotation.z = Math.PI / 2;
maternalLabel.position.set(-3.18, 0.05, 0.18);
boardGroup.add(maternalLabel);
const caption = makeTextPlane(
"one allele from each parent",
3.7,
0.3,
{ fontSize: 30, color: "#71829a" }
);
caption.position.set(0, -2.15, 0.18);
boardGroup.add(caption);
// Voxel DNA rails along both sides of the board.
for (const side of [-1, 1]) {
for (let i = 0; i < 8; i++) {
const color = i % 2 ? colors.A : colors.a;
const voxel = boxMesh(
0.25,
0.25,
0.25,
color,
side * 3.29,
-1.55 + i * 0.43,
0.21
);
voxel.castShadow = false;
boardGroup.add(voxel);
}
}
}
function buildPopulation() {
clearGroup(populationGroup);
populationGroup = new THREE.Group();
scene.add(populationGroup);
const categoryData = [
{ genotype: "AA", x: -7, color: colors.AA, hex: "#ffd166" },
{ genotype: "Aa", x: 0, color: colors.Aa, hex: "#5eead4" },
{ genotype: "aa", x: 7, color: colors.aa, hex: "#f472b6" }
];
const displayed = [];
const instances = [];
const maxPerClass = 42;
for (const category of categoryData) {
const observed = state.counts[category.genotype];
const probability = state.probabilities[category.genotype];
const expected = probability * state.n;
const previewCount = Math.min(observed, maxPerClass);
const bin = boxMesh(
6.35,
0.12,
4.75,
new THREE.Color(category.color).multiplyScalar(0.12).getHex(),
category.x,
0.06,
-3.45
);
bin.castShadow = false;
populationGroup.add(bin);
const outline = new THREE.LineSegments(
new THREE.EdgesGeometry(bin.geometry),
new THREE.LineBasicMaterial({
color: category.color,
transparent: true,
opacity: 0.25
})
);
outline.position.copy(bin.position);
populationGroup.add(outline);
const label = makeLabelSprite(
`${category.genotype} · ${observed} observed`,
`${(probability * 100).toFixed(1)}% expected · ${expected.toFixed(1)} children`,
category.hex,
4.7
);
label.position.set(category.x, 1.55, -7.05);
populationGroup.add(label);
const columns = Math.min(14, previewCount);
const rows = Math.ceil(previewCount / columns);
for (let i = 0; i < previewCount; i++) {
const child = state.offspring.find(
offspring =>
offspring.genotype === category.genotype &&
!offspring.previewed
);
if (!child) break;
child.previewed = true;
displayed.push(child);
const column = i % columns;
const row = Math.floor(i / columns);
const px = category.x + (column - (columns - 1) / 2) * 0.46;
const pz = -2.15 - row * 0.58;
const bodyColor = child.phenotype === "dominant"
? colors.dominant
: colors.recessive;
// body, head, maternal badge, paternal badge
instances.push({
child,
position: [px, 0.27, pz],
scale: [0.27, 0.39, 0.23],
color: bodyColor
});
instances.push({
child,
position: [px, 0.61, pz],
scale: [0.25, 0.25, 0.25],
color: colors.skin
});
instances.push({
child,
position: [px - 0.18, 0.43, pz],
scale: [0.1, 0.1, 0.1],
color: colors[child.maternalAllele]
});
instances.push({
child,
position: [px + 0.18, 0.43, pz],
scale: [0.1, 0.1, 0.1],
color: colors[child.paternalAllele]
});
}
}
const mesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.68,
metalness: 0.04
}),
Math.max(1, instances.length)
);
mesh.count = instances.length;
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.userData.displayed = displayed;
const dummy = new THREE.Object3D();
instances.forEach((instance, index) => {
dummy.position.set(...instance.position);
dummy.scale.set(...instance.scale);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
mesh.setColorAt(index, new THREE.Color(instance.color));
});
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
populationGroup.add(mesh);
childMesh = mesh;
const cohortLabel = makeLabelSprite(
"FICTIONAL COHORT",
"independent allele draws",
"#7397ff",
4.1
);
cohortLabel.position.set(0, 2.15, 0.75);
populationGroup.add(cohortLabel);
}
function addCurve(curve, lineColor, particleColor, count, speed) {
const line = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(curve.getPoints(70)),
new THREE.LineBasicMaterial({
color: lineColor,
transparent: true,
opacity: 0.18
})
);
flowGroup.add(line);
for (let i = 0; i < count; i++) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(0.11, 0.11, 0.11),
new THREE.MeshBasicMaterial({
color: particleColor,
toneMapped: false
})
);
flowGroup.add(mesh);
flowParticles.push({
mesh,
curve,
phase: Math.random(),
speed: speed * (0.75 + Math.random() * 0.5)
});
}
}
function buildFlows() {
clearGroup(flowGroup);
flowGroup = new THREE.Group();
flowParticles.length = 0;
scene.add(flowGroup);
const starts = [
new THREE.Vector3(-8.7, 2.2, 3.2),
new THREE.Vector3(8.7, 2.2, 3.2)
];
starts.forEach((start, index) => {
const curve = new THREE.CatmullRomCurve3([
start,
new THREE.Vector3(start.x * 0.72, 6.7, -1.5),
new THREE.Vector3(start.x * 0.32, 5.9, -7.1),
new THREE.Vector3(0, 4.45, -10.8)
]);
const parentAlleles = (index === 0 ? state.parent1 : state.parent2).split("");
const allele = parentAlleles[Math.floor(Math.random() * parentAlleles.length)];
addCurve(
curve,
colors[allele],
colors[allele],
13,
0.055 + index * 0.006
);
});
const targets = [
{ x: -7, color: colors.AA },
{ x: 0, color: colors.Aa },
{ x: 7, color: colors.aa }
];
targets.forEach(target => {
const curve = new THREE.CatmullRomCurve3([
new THREE.Vector3(0, 3.1, -10.7),
new THREE.Vector3(target.x * 0.35, 2.6, -8.9),
new THREE.Vector3(target.x, 1.35, -6.8),
new THREE.Vector3(target.x, 0.48, -4.3)
]);
addCurve(curve, target.color, target.color, 6, 0.065);
});
}
// ---------- Simulation ----------
function newSeed() {
if (window.crypto?.getRandomValues) {
return window.crypto.getRandomValues(new Uint32Array(1))[0];
}
return (Math.random() * 0xffffffff) >>> 0;
}
function mulberry32(seed) {
return function() {
let t = seed += 0x6D2B79F5;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function simulate() {
state.seed = newSeed();
const random = mulberry32(state.seed);
state.offspring = [];
state.counts = { AA: 0, Aa: 0, aa: 0 };
state.probabilities = { AA: 0, Aa: 0, aa: 0 };
const parent1Alleles = state.parent1.split("");
const parent2Alleles = state.parent2.split("");
for (let i = 0; i < state.n; i++) {
const maternalAllele =
parent1Alleles[Math.floor(random() * parent1Alleles.length)];
const paternalAllele =
parent2Alleles[Math.floor(random() * parent2Alleles.length)];
const genotype = sortedGenotype(maternalAllele, paternalAllele);
state.offspring.push({
id: i + 1,
genotype,
phenotype: phenotypeFor(genotype),
maternalAllele,
paternalAllele,
previewed: false
});
state.counts[genotype]++;
}
const maternalGametes = [...new Set(parent1Alleles)];
const paternalGametes = [...new Set(parent2Alleles)];
maternalGametes.forEach(maternal => {
paternalGametes.forEach(paternal => {
state.probabilities[sortedGenotype(maternal, paternal)] +=
1 / (maternalGametes.length * paternalGametes.length);
});
});
buildPunnettBoard();
buildPopulation();
buildFlows();
refreshParentAppearance();
updateResults();
}
function updateResults() {
$("cohort-output").textContent = state.n;
$("result-count").textContent = state.n;
$("seed-value").textContent =
state.seed.toString(16).padStart(8, "0").toUpperCase();
const rows = ["AA", "Aa", "aa"];
let comparisonHTML = "";
let largestGap = 0;
let largestGapType = "";
for (const genotype of rows) {
const observed = state.counts[genotype];
const probability = state.probabilities[genotype];
const expected = probability * state.n;
const gap = observed - expected;
const absoluteGap = Math.abs(gap);
const accent = `#${new THREE.Color(colors[genotype]).getHexString()}`;
if (absoluteGap > largestGap) {
largestGap = absoluteGap;
largestGapType = genotype;
}
comparisonHTML += `
<div class="genotype-row">
<div class="genotype-head">
<span class="genotype-code" style="color:${accent}">${genotype}</span>
<span class="observed-count">${observed} observed</span>
<span class="expected-count">exp ${expected.toFixed(1)}</span>
</div>
<div class="bar-track"
title="${genotype}: observed ${observed}; expected ${expected.toFixed(2)}">
<div class="observed-bar"
style="height:${(observed / state.n * 100).toFixed(2)}%;
background:${accent}"></div>
<div class="expected-marker"
style="bottom:${(probability * 100).toFixed(2)}%"></div>
</div>
</div>
`;
}
$("comparison").innerHTML = comparisonHTML;
const dominantExpected =
(state.probabilities.AA + state.probabilities.Aa) * state.n;
const recessiveExpected = state.probabilities.aa * state.n;
const dominantObserved = state.counts.AA + state.counts.Aa;
$("dominant-count").textContent = dominantObserved;
$("dominant-expected").textContent =
`expected ${dominantExpected.toFixed(1)}`;
$("recessive-count").textContent = state.counts.aa;
$("recessive-expected").textContent =
`expected ${recessiveExpected.toFixed(1)}`;
$("variation-note").innerHTML = `
<strong>Sampling variation is visible.</strong>
The largest genotype gap is ${largestGap.toFixed(1)} child${largestGap === 1 ? "" : "ren"}
(${largestGapType}). A new random draw can move every count.
`;
}
// ---------- Custom camera controls ----------
const pointer = {
down: false,
moved: false,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0
};
const raycaster = new THREE.Raycaster();
const pointerNDC = new THREE.Vector2();
function resetCamera() {
Object.assign(cameraState, cameraHome);
updateCamera();
}
renderer.domElement.addEventListener("pointerdown", event => {
pointer.down = true;
pointer.moved = false;
pointer.startX = pointer.lastX = event.clientX;
pointer.startY = pointer.lastY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (pointer.down) {
const dx = event.clientX - pointer.lastX;
const dy = event.clientY - pointer.lastY;
if (
Math.abs(event.clientX - pointer.startX) +
Math.abs(event.clientY - pointer.startY) > 5
) {
pointer.moved = true;
}
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.34,
1.38
);
updateCamera();
pointer.lastX = event.clientX;
pointer.lastY = event.clientY;
hideTooltip();
} else {
inspectAt(event.clientX, event.clientY);
}
});
renderer.domElement.addEventListener("pointerup", event => {
pointer.down = false;
if (!pointer.moved) inspectAt(event.clientX, event.clientY);
});
renderer.domElement.addEventListener("pointercancel", () => {
pointer.down = false;
});
renderer.domElement.addEventListener("pointerleave", hideTooltip);
renderer.domElement.addEventListener(
"wheel",
event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
15,
46
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
function inspectAt(clientX, clientY) {
if (!childMesh) return;
const rect = renderer.domElement.getBoundingClientRect();
pointerNDC.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointerNDC.y = -((clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointerNDC, camera);
const hits = raycaster.intersectObject(childMesh, false);
if (!hits.length) {
hideTooltip();
renderer.domElement.style.cursor = "grab";
return;
}
const instanceId = hits[0].instanceId;
const child = childMesh.userData.displayed[Math.floor(instanceId / 4)];
if (!child) return;
renderer.domElement.style.cursor = "pointer";
const tooltip = $("tooltip");
tooltip.innerHTML = `
<strong>Offspring #${child.id}</strong>
<div>Genotype <b style="color:#5eead4">${child.genotype}</b> · ${child.phenotype}</div>
<div class="tooltip-muted">
Parent 1 gave <b style="color:#ffd166">${child.maternalAllele}</b>;
Parent 2 gave <b style="color:#5eead4">${child.paternalAllele}</b>.
</div>
`;
tooltip.style.display = "block";
tooltip.style.left =
`${Math.min(clientX + 15, window.innerWidth - 270)}px`;
tooltip.style.top =
`${Math.min(clientY + 15, window.innerHeight - 130)}px`;
}
function hideTooltip() {
$("tooltip").style.display = "none";
}
// ---------- UI events ----------
$("parent-1").addEventListener("change", event => {
state.parent1 = event.target.value;
simulate();
});
$("parent-2").addEventListener("change", event => {
state.parent2 = event.target.value;
simulate();
});
$("cohort-size").addEventListener("input", event => {
$("cohort-output").textContent = event.target.value;
});
$("cohort-size").addEventListener("change", event => {
state.n = Number(event.target.value);
simulate();
});
$("generate").addEventListener("click", simulate);
$("reset-view").addEventListener("click", resetCamera);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
// ---------- Animation ----------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
parentGroups.forEach((group, index) => {
group.position.y = 0.45 + Math.sin(elapsed * 1.1 + index) * 0.035;
});
if (boardGroup) {
boardGroup.position.y = 4.75 + Math.sin(elapsed * 0.8) * 0.055;
}
for (const particle of flowParticles) {
const t = (elapsed * particle.speed + particle.phase) % 1;
particle.mesh.position.copy(particle.curve.getPointAt(t));
particle.mesh.rotation.set(
elapsed * 1.4,
elapsed * 1.8,
elapsed * 1.2
);
const pulse = 0.85 + Math.sin(elapsed * 5 + particle.phase * 10) * 0.22;
particle.mesh.scale.setScalar(pulse);
}
stars.rotation.y = elapsed * 0.003;
renderer.render(scene, camera);
}
simulate();
animate();
$("loading").remove();
</script>
</body>
</html>
```