Prompt specification
Build or customize the Three.js 3D scene "Random-generation sampling urn" 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: Random-generation sampling urn
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/random-generation-sampling-urn-x0913
Scene Description Prompt:
Sample allele-colored tokens equally from a low-poly transparent urn into an offspring tray. Use Three.js from cdnjs to build one HTML file.
Working Three.js Starter (random-generation-sampling-urn-x0913):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#eef0e9">
<title>Allele Sampling Urn</title>
<style>
:root {
--ink: #243c39;
--muted: #687b77;
--paper: rgba(255, 255, 255, 0.78);
--line: rgba(36, 60, 57, 0.13);
--a: #ef6b5b;
--b: #4c78e8;
--green: #315f57;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #eef0e9;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
outline: none;
}
#scene canvas:active {
cursor: grabbing;
}
.hud {
position: fixed;
inset: 0;
z-index: 2;
pointer-events: none;
}
header {
position: absolute;
top: 30px;
left: 34px;
max-width: 510px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 9px;
color: var(--green);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
width: 26px;
height: 2px;
content: "";
background: var(--green);
}
h1 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(34px, 4vw, 58px);
font-weight: 500;
letter-spacing: -0.045em;
line-height: 0.98;
}
header p {
max-width: 450px;
margin: 15px 0 0;
color: var(--muted);
font-size: 14px;
line-height: 1.55;
}
.panel {
position: absolute;
top: 28px;
right: 28px;
width: 286px;
padding: 19px;
border: 1px solid rgba(255, 255, 255, 0.8);
border-radius: 20px;
background: var(--paper);
box-shadow:
0 18px 50px rgba(45, 65, 60, 0.10),
inset 0 0 0 1px rgba(36, 60, 57, 0.04);
backdrop-filter: blur(18px);
-webkit-backdrop-filter: blur(18px);
}
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 16px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.live-dot {
display: inline-block;
width: 7px;
height: 7px;
margin-right: 6px;
border-radius: 50%;
background: #55a783;
box-shadow: 0 0 0 4px rgba(85, 167, 131, 0.12);
}
.counts {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
}
.count {
min-width: 0;
padding: 11px 9px;
border-radius: 13px;
background: rgba(239, 242, 235, 0.8);
}
.count span {
display: block;
margin-bottom: 6px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.count strong {
font-size: 20px;
font-weight: 650;
}
.probability-head {
display: flex;
align-items: baseline;
justify-content: space-between;
margin-top: 19px;
margin-bottom: 8px;
}
.probability-head span {
color: var(--muted);
font-size: 11px;
}
.probability-head strong {
font-size: 13px;
}
.meter {
height: 7px;
overflow: hidden;
border-radius: 999px;
background: var(--b);
}
.meter i {
display: block;
width: 50%;
height: 100%;
border-radius: inherit;
background: var(--a);
transition: width 300ms ease;
}
.remaining {
margin: 8px 0 0;
color: var(--muted);
font-size: 10px;
}
.legend {
display: flex;
gap: 17px;
margin-top: 18px;
padding-top: 16px;
border-top: 1px solid var(--line);
}
.legend-item {
display: flex;
align-items: center;
gap: 8px;
color: var(--muted);
font-size: 11px;
}
.chip {
width: 12px;
height: 12px;
border: 2px solid rgba(255, 255, 255, 0.8);
border-radius: 50%;
box-shadow: 0 1px 5px rgba(30, 40, 40, 0.16);
}
.chip.a {
background: var(--a);
}
.chip.b {
background: var(--b);
}
.controls-wrap {
position: absolute;
right: 28px;
bottom: 26px;
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 10px;
pointer-events: auto;
}
.status {
display: flex;
align-items: center;
gap: 8px;
min-height: 27px;
padding: 7px 11px;
border: 1px solid rgba(255, 255, 255, 0.8);
border-radius: 999px;
background: rgba(255, 255, 255, 0.7);
color: var(--muted);
font-size: 10px;
box-shadow: 0 6px 22px rgba(45, 65, 60, 0.07);
backdrop-filter: blur(12px);
}
.controls {
display: flex;
gap: 8px;
padding: 8px;
border: 1px solid rgba(255, 255, 255, 0.82);
border-radius: 17px;
background: rgba(255, 255, 255, 0.78);
box-shadow:
0 16px 42px rgba(45, 65, 60, 0.12),
inset 0 0 0 1px rgba(36, 60, 57, 0.04);
backdrop-filter: blur(16px);
}
button {
min-height: 42px;
padding: 0 17px;
border: 0;
border-radius: 11px;
background: transparent;
color: var(--ink);
font: inherit;
font-size: 12px;
font-weight: 700;
cursor: pointer;
transition:
transform 150ms ease,
background 150ms ease,
opacity 150ms ease;
}
button:hover:not(:disabled) {
transform: translateY(-1px);
background: rgba(49, 95, 87, 0.07);
}
button:active:not(:disabled) {
transform: translateY(0);
}
button:focus-visible {
outline: 3px solid rgba(76, 120, 232, 0.32);
outline-offset: 2px;
}
button.primary {
padding-inline: 21px;
background: var(--green);
color: #fff;
box-shadow: 0 7px 16px rgba(49, 95, 87, 0.2);
}
button.primary:hover:not(:disabled) {
background: #264f48;
}
button:disabled {
cursor: not-allowed;
opacity: 0.38;
}
.view-hint {
position: absolute;
bottom: 30px;
left: 34px;
display: flex;
align-items: center;
gap: 9px;
color: rgba(36, 60, 57, 0.58);
font-size: 10px;
font-weight: 650;
letter-spacing: 0.04em;
}
.view-hint button {
width: 31px;
min-height: 31px;
padding: 0;
border: 1px solid rgba(36, 60, 57, 0.13);
border-radius: 50%;
background: rgba(255, 255, 255, 0.6);
color: var(--ink);
font-size: 16px;
}
.view-hint button:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.92);
}
@media (max-width: 820px) {
header {
top: 18px;
left: 18px;
max-width: calc(100% - 36px);
}
header p {
max-width: 360px;
font-size: 12px;
}
.panel {
top: auto;
right: 14px;
bottom: 92px;
width: 230px;
padding: 14px;
}
.panel-title {
margin-bottom: 10px;
}
.count {
padding: 8px 7px;
}
.count strong {
font-size: 17px;
}
.legend {
margin-top: 12px;
padding-top: 11px;
}
.controls-wrap {
right: 14px;
bottom: 14px;
left: 14px;
align-items: stretch;
}
.controls {
width: 100%;
}
.controls button {
flex: 1;
padding-inline: 9px;
}
.status {
align-self: flex-end;
}
.view-hint {
display: none;
}
}
@media (max-width: 520px) {
h1 {
font-size: 34px;
}
header p {
display: none;
}
.panel {
width: 205px;
}
.counts {
gap: 5px;
}
.count span {
font-size: 8px;
}
.count strong {
font-size: 15px;
}
.legend {
gap: 10px;
}
.legend-item {
font-size: 9px;
}
button {
font-size: 11px;
}
}
@media (prefers-reduced-motion: reduce) {
* {
scroll-behavior: auto !important;
transition-duration: 0.01ms !important;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="hud">
<header>
<div class="eyebrow">Population genetics / interactive model</div>
<h1>Allele<br>sampling urn</h1>
<p>
Draw uniformly from 24 equally weighted parent tokens. Each sample moves
without replacement into the offspring tray.
</p>
</header>
<aside class="panel" aria-label="Sampling statistics">
<div class="panel-title">
<span><i class="live-dot"></i>Live sample</span>
<span id="fillLabel">0 / 24</span>
</div>
<div class="counts">
<div class="count">
<span>Urn</span>
<strong id="urnCount">24</strong>
</div>
<div class="count">
<span>A drawn</span>
<strong id="aDrawn">0</strong>
</div>
<div class="count">
<span>a drawn</span>
<strong id="bDrawn">0</strong>
</div>
</div>
<div class="probability-head">
<span>Next draw</span>
<strong id="probabilityLabel">50.0% A</strong>
</div>
<div class="meter" aria-hidden="true">
<i id="probabilityFill"></i>
</div>
<p class="remaining" id="remainingLabel">
12 A · 12 a remaining
</p>
<div class="legend">
<div class="legend-item">
<i class="chip a"></i>
<span>Allele A</span>
</div>
<div class="legend-item">
<i class="chip b"></i>
<span>Allele a</span>
</div>
</div>
</aside>
<div class="view-hint">
<button id="resetCamera" aria-label="Reset camera" title="Reset camera">↺</button>
<span>Drag to orbit · Scroll to zoom</span>
</div>
<div class="controls-wrap">
<div class="status" id="status" role="status" aria-live="polite">
Ready to sample
</div>
<div class="controls">
<button id="sampleOne" class="primary">Sample one</button>
<button id="sampleFour">Sample 4</button>
<button id="resetSimulation">Reset</button>
</div>
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene setup
// -------------------------------------------------------------------------
const sceneHost = document.querySelector("#scene");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xeef0e9);
scene.fog = new THREE.Fog(0xeef0e9, 13, 24);
const camera = new THREE.PerspectiveCamera(
38,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.domElement.setAttribute(
"aria-label",
"Interactive three-dimensional allele sampling urn and offspring tray"
);
renderer.domElement.tabIndex = 0;
sceneHost.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xffffff, 0x8b9a91, 2.2);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff8e8, 3.6);
keyLight.position.set(-4, 9, 6);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -8;
keyLight.shadow.camera.right = 8;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -8;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 22;
keyLight.shadow.normalBias = 0.025;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0xc7ddff, 1.5);
fillLight.position.set(7, 5, -6);
scene.add(fillLight);
const rimLight = new THREE.PointLight(0xffffff, 30, 14, 2);
rimLight.position.set(0, 6, 4);
scene.add(rimLight);
const floorMaterial = new THREE.MeshStandardMaterial({
color: 0xe7e9df,
roughness: 0.94,
metalness: 0
});
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(40, 40),
floorMaterial
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.01;
floor.receiveShadow = true;
scene.add(floor);
const matMaterial = new THREE.MeshStandardMaterial({
color: 0xf2f1e9,
roughness: 0.9,
metalness: 0
});
const urnMat = new THREE.Mesh(
new THREE.CircleGeometry(1.7, 48),
matMaterial
);
urnMat.rotation.x = -Math.PI / 2;
urnMat.position.set(-2.05, 0.002, 0);
urnMat.receiveShadow = true;
scene.add(urnMat);
const trayMat = new THREE.Mesh(
new THREE.PlaneGeometry(5.3, 3.9),
matMaterial
);
trayMat.rotation.x = -Math.PI / 2;
trayMat.position.set(2.05, 0.003, 0);
trayMat.receiveShadow = true;
scene.add(trayMat);
// -------------------------------------------------------------------------
// Low-poly transparent urn
// -------------------------------------------------------------------------
const urnGroup = new THREE.Group();
urnGroup.position.set(-2.05, 0, 0);
scene.add(urnGroup);
const profile = [
new THREE.Vector2(0.43, 0.18),
new THREE.Vector2(0.59, 0.26),
new THREE.Vector2(0.68, 0.58),
new THREE.Vector2(0.77, 1.10),
new THREE.Vector2(0.79, 1.75),
new THREE.Vector2(0.76, 2.27),
new THREE.Vector2(0.83, 2.53)
];
const urnGeometry = new THREE.LatheGeometry(profile, 12);
const glassMaterial = new THREE.MeshPhysicalMaterial({
color: 0xb8d8d3,
roughness: 0.16,
metalness: 0.02,
transmission: 0.58,
transparent: true,
opacity: 0.46,
thickness: 0.16,
side: THREE.DoubleSide,
depthWrite: false
});
const glassBody = new THREE.Mesh(urnGeometry, glassMaterial);
glassBody.castShadow = true;
glassBody.renderOrder = 2;
urnGroup.add(glassBody);
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x527873,
transparent: true,
opacity: 0.32
});
const glassEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(urnGeometry, 18),
edgeMaterial
);
glassEdges.renderOrder = 3;
urnGroup.add(glassEdges);
const urnBaseMaterial = new THREE.MeshStandardMaterial({
color: 0x55756f,
roughness: 0.48,
metalness: 0.08,
transparent: true,
opacity: 0.82
});
const urnBase = new THREE.Mesh(
new THREE.CylinderGeometry(0.68, 0.73, 0.15, 12),
urnBaseMaterial
);
urnBase.position.y = 0.13;
urnBase.castShadow = true;
urnBase.receiveShadow = true;
urnGroup.add(urnBase);
const rimMaterial = new THREE.MeshStandardMaterial({
color: 0x3d625b,
roughness: 0.32,
metalness: 0.18
});
const urnRim = new THREE.Mesh(
new THREE.TorusGeometry(0.83, 0.055, 5, 12),
rimMaterial
);
urnRim.rotation.x = Math.PI / 2;
urnRim.position.y = 2.53;
urnRim.castShadow = true;
urnGroup.add(urnRim);
const innerRim = new THREE.Mesh(
new THREE.TorusGeometry(0.755, 0.025, 4, 12),
rimMaterial
);
innerRim.rotation.x = Math.PI / 2;
innerRim.position.y = 2.535;
urnGroup.add(innerRim);
// -------------------------------------------------------------------------
// Offspring tray
// -------------------------------------------------------------------------
const trayGroup = new THREE.Group();
trayGroup.position.set(2.05, 0, 0);
scene.add(trayGroup);
const trayBaseMaterial = new THREE.MeshStandardMaterial({
color: 0xd6cfbf,
roughness: 0.76,
metalness: 0.02
});
const trayInnerMaterial = new THREE.MeshStandardMaterial({
color: 0xf4f0e5,
roughness: 0.82,
metalness: 0
});
const trayRimMaterial = new THREE.MeshStandardMaterial({
color: 0x416a61,
roughness: 0.52,
metalness: 0.05
});
const trayBase = new THREE.Mesh(
new THREE.BoxGeometry(4.25, 0.16, 3.05),
trayBaseMaterial
);
trayBase.position.y = 0.11;
trayBase.castShadow = true;
trayBase.receiveShadow = true;
trayGroup.add(trayBase);
const trayInner = new THREE.Mesh(
new THREE.BoxGeometry(3.99, 0.055, 2.79),
trayInnerMaterial
);
trayInner.position.y = 0.225;
trayInner.receiveShadow = true;
trayGroup.add(trayInner);
function addTrayWall(width, depth, x, z) {
const wall = new THREE.Mesh(
new THREE.BoxGeometry(width, 0.38, depth),
trayBaseMaterial
);
wall.position.set(x, 0.37, z);
wall.castShadow = true;
wall.receiveShadow = true;
trayGroup.add(wall);
return wall;
}
addTrayWall(4.30, 0.13, 0, -1.49);
addTrayWall(4.30, 0.13, 0, 1.49);
addTrayWall(0.13, 3.02, -2.08, 0);
addTrayWall(0.13, 3.02, 2.08, 0);
const lipGeometryHorizontal = new THREE.BoxGeometry(4.34, 0.07, 0.16);
const lipGeometrySide = new THREE.BoxGeometry(0.16, 0.07, 3.06);
for (const z of [-1.49, 1.49]) {
const lip = new THREE.Mesh(lipGeometryHorizontal, trayRimMaterial);
lip.position.set(0, 0.57, z);
lip.castShadow = true;
trayGroup.add(lip);
}
for (const x of [-2.08, 2.08]) {
const lip = new THREE.Mesh(lipGeometrySide, trayRimMaterial);
lip.position.set(x, 0.57, 0);
lip.castShadow = true;
trayGroup.add(lip);
}
const slotMaterial = new THREE.MeshBasicMaterial({
color: 0x6f9188,
transparent: true,
opacity: 0.17,
side: THREE.DoubleSide,
depthWrite: false
});
const trayPositions = [];
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 6; col++) {
const local = new THREE.Vector3(
-1.55 + col * 0.62,
0.47,
-0.90 + row * 0.60
);
const slot = new THREE.Mesh(
new THREE.RingGeometry(0.205, 0.225, 12),
slotMaterial
);
slot.rotation.x = -Math.PI / 2;
slot.position.set(local.x, 0.265, local.z);
trayGroup.add(slot);
trayPositions.push(local.clone().add(trayGroup.position));
}
}
// -------------------------------------------------------------------------
// Scene labels
// -------------------------------------------------------------------------
function makePlaque(text) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
const radius = 28;
const x = 12;
const y = 14;
const w = 488;
const h = 98;
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + w - radius, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + radius);
ctx.lineTo(x + w, y + h - radius);
ctx.quadraticCurveTo(x + w, y + h, x + w - radius, y + h);
ctx.lineTo(x + radius, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
ctx.fillStyle = "rgba(255,255,255,0.83)";
ctx.fill();
ctx.strokeStyle = "rgba(49,95,87,0.24)";
ctx.lineWidth = 3;
ctx.stroke();
ctx.fillStyle = "#315f57";
ctx.font = "700 35px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 256, 63);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(1.72, 0.43, 1);
sprite.renderOrder = 20;
return sprite;
}
const urnPlaque = makePlaque("PARENT ALLELES");
urnPlaque.position.set(-2.05, 3.02, 0);
scene.add(urnPlaque);
const trayPlaque = makePlaque("OFFSPRING TRAY");
trayPlaque.position.set(2.05, 0.98, 0);
scene.add(trayPlaque);
// -------------------------------------------------------------------------
// Allele tokens
// -------------------------------------------------------------------------
const ALLELE_A = "A";
const ALLELE_a = "a";
const tokenGeometry = new THREE.IcosahedronGeometry(0.19, 1);
const tokenMaterials = {
A: new THREE.MeshStandardMaterial({
color: 0xef6b5b,
roughness: 0.48,
metalness: 0.04,
flatShading: true
}),
a: new THREE.MeshStandardMaterial({
color: 0x4c78e8,
roughness: 0.48,
metalness: 0.04,
flatShading: true
})
};
function makeTokenLabel(letter) {
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, 128, 128);
ctx.font = "800 70px Georgia, serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.lineWidth = 7;
ctx.strokeStyle = "rgba(20,35,50,0.35)";
ctx.strokeText(letter, 64, 64);
ctx.fillStyle = "#ffffff";
ctx.fillText(letter, 64, 64);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
return new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
}
const tokenLabelMaterials = {
A: makeTokenLabel("A"),
a: makeTokenLabel("a")
};
const urnSlots = [];
const layers = [
{ y: 0.58, radius: 0.40, count: 6, offset: 0.00 },
{ y: 0.94, radius: 0.46, count: 6, offset: 0.28 },
{ y: 1.31, radius: 0.48, count: 6, offset: 0.10 },
{ y: 1.67, radius: 0.43, count: 6, offset: 0.38 }
];
for (const layer of layers) {
for (let i = 0; i < layer.count; i++) {
const angle = (i / layer.count) * Math.PI * 2 + layer.offset;
urnSlots.push(
new THREE.Vector3(
Math.cos(angle) * layer.radius,
layer.y,
Math.sin(angle) * layer.radius
)
);
}
}
let urnTokens = [];
let trayTokens = [];
let allTokens = [];
let animations = [];
let sampledA = 0;
let sampleda = 0;
let busy = false;
let pendingDraws = 0;
function shuffledTypes() {
const values = [];
for (let i = 0; i < 12; i++) {
values.push(ALLELE_A, ALLELE_a);
}
for (let i = values.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[values[i], values[j]] = [values[j], values[i]];
}
return values;
}
function createToken(type, position) {
const group = new THREE.Group();
const mesh = new THREE.Mesh(tokenGeometry, tokenMaterials[type]);
mesh.castShadow = true;
mesh.receiveShadow = true;
group.add(mesh);
const label = new THREE.Sprite(tokenLabelMaterials[type]);
label.position.set(0, 0.115, 0);
label.scale.set(0.18, 0.18, 1);
label.renderOrder = 5;
group.add(label);
group.position.copy(position);
group.rotation.set(
Math.random() * Math.PI,
Math.random() * Math.PI,
Math.random() * Math.PI
);
scene.add(group);
const token = { group, type };
allTokens.push(token);
return token;
}
function populateUrn() {
const types = shuffledTypes();
urnSlots.forEach((slot, index) => {
const worldPosition = slot.clone().add(urnGroup.position);
urnTokens.push(createToken(types[index], worldPosition));
});
}
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
const urnCountEl = document.querySelector("#urnCount");
const aDrawnEl = document.querySelector("#aDrawn");
const bDrawnEl = document.querySelector("#bDrawn");
const fillLabelEl = document.querySelector("#fillLabel");
const probabilityLabelEl = document.querySelector("#probabilityLabel");
const probabilityFillEl = document.querySelector("#probabilityFill");
const remainingLabelEl = document.querySelector("#remainingLabel");
const statusEl = document.querySelector("#status");
const sampleOneButton = document.querySelector("#sampleOne");
const sampleFourButton = document.querySelector("#sampleFour");
const resetButton = document.querySelector("#resetSimulation");
function updateUI() {
const remainingA = urnTokens.filter(t => t.type === ALLELE_A).length;
const remaininga = urnTokens.filter(t => t.type === ALLELE_a).length;
const remaining = urnTokens.length;
urnCountEl.textContent = remaining;
aDrawnEl.textContent = sampledA;
bDrawnEl.textContent = sampleda;
fillLabelEl.textContent = `${trayTokens.length} / 24`;
const chanceA = remaining ? (remainingA / remaining) * 100 : 0;
probabilityLabelEl.textContent = remaining
? `${chanceA.toFixed(1)}% A`
: "Urn empty";
probabilityFillEl.style.width = `${remaining ? chanceA : 0}%`;
remainingLabelEl.textContent = remaining
? `${remainingA} A · ${remaininga} a remaining`
: "All parent tokens have been sampled";
sampleOneButton.disabled =
busy || remaining === 0 || trayTokens.length >= 24;
sampleFourButton.disabled =
busy || remaining === 0 || trayTokens.length >= 24;
if (!busy) {
if (remaining === 0) {
statusEl.textContent = "Urn complete — reset to sample again";
} else if (trayTokens.length === 0) {
statusEl.textContent = "Ready to sample";
} else {
statusEl.textContent = `${trayTokens.length} offspring sampled`;
}
}
}
// -------------------------------------------------------------------------
// Sampling and arc animation
// -------------------------------------------------------------------------
const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;
const animationDuration = reducedMotion ? 260 : 820;
function requestSample() {
if (busy || urnTokens.length === 0 || trayTokens.length >= 24) {
return;
}
busy = true;
pendingDraws = Math.max(0, pendingDraws - 1);
// Every token has exactly the same selection probability.
const selectedIndex = Math.floor(Math.random() * urnTokens.length);
const token = urnTokens.splice(selectedIndex, 1)[0];
const from = token.group.position.clone();
const to = trayPositions[trayTokens.length].clone();
const midpoint = from.clone().lerp(to, 0.5);
midpoint.y += 2.05;
const curve = new THREE.QuadraticBezierCurve3(from, midpoint, to);
const lineMaterial = new THREE.LineBasicMaterial({
color: token.type === ALLELE_A ? 0xef6b5b : 0x4c78e8,
transparent: true,
opacity: 0.55,
depthWrite: false
});
const arc = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(curve.getPoints(36)),
lineMaterial
);
arc.renderOrder = 4;
scene.add(arc);
const pulseMaterial = new THREE.MeshBasicMaterial({
color: token.type === ALLELE_A ? 0xef6b5b : 0x4c78e8,
transparent: true,
opacity: 0.8,
side: THREE.DoubleSide,
depthWrite: false
});
const pulse = new THREE.Mesh(
new THREE.RingGeometry(0.205, 0.245, 12),
pulseMaterial
);
pulse.rotation.x = -Math.PI / 2;
pulse.position.set(to.x, 0.285, to.z);
scene.add(pulse);
animations.push({
token,
from,
to,
midpoint,
arc,
pulse,
start: performance.now(),
duration: animationDuration
});
statusEl.textContent =
pendingDraws > 0
? `Sampling batch · ${pendingDraws + 1} remaining`
: "Sampling one allele…";
updateUI();
}
function updateAnimations(now) {
for (let i = animations.length - 1; i >= 0; i--) {
const animation = animations[i];
const progress = Math.min(
1,
(now - animation.start) / animation.duration
);
const eased = progress * progress * (3 - 2 * progress);
const oneMinus = 1 - eased;
animation.token.group.position.set(
oneMinus * oneMinus * animation.from.x +
2 * oneMinus * eased * animation.midpoint.x +
eased * eased * animation.to.x,
oneMinus * oneMinus * animation.from.y +
2 * oneMinus * eased * animation.midpoint.y +
eased * eased * animation.to.y,
oneMinus * oneMinus * animation.from.z +
2 * oneMinus * eased * animation.midpoint.z +
eased * eased * animation.to.z
);
animation.token.group.rotation.x += 0.035;
animation.token.group.rotation.y += 0.045;
const scale = 1 + Math.sin(progress * Math.PI) * 0.13;
animation.token.group.scale.setScalar(scale);
animation.arc.material.opacity = 0.55 * (1 - progress);
animation.pulse.material.opacity = 0.8 * (1 - progress);
animation.pulse.scale.setScalar(1 + progress * 1.4);
if (progress >= 1) {
animation.token.group.position.copy(animation.to);
animation.token.group.scale.setScalar(1);
scene.remove(animation.arc);
scene.remove(animation.pulse);
animation.arc.geometry.dispose();
animation.arc.material.dispose();
animation.pulse.geometry.dispose();
animation.pulse.material.dispose();
trayTokens.push(animation.token);
if (animation.token.type === ALLELE_A) {
sampledA++;
} else {
sampleda++;
}
animations.splice(i, 1);
if (pendingDraws > 0 && urnTokens.length > 0) {
setTimeout(() => {
if (!busy || pendingDraws === 0 || animations.length) return;
busy = false;
requestSample();
}, reducedMotion ? 80 : 150);
} else {
pendingDraws = 0;
busy = false;
updateUI();
}
}
}
}
function resetSimulation() {
for (const animation of animations) {
scene.remove(animation.arc);
scene.remove(animation.pulse);
animation.arc.geometry.dispose();
animation.arc.material.dispose();
animation.pulse.geometry.dispose();
animation.pulse.material.dispose();
}
for (const token of allTokens) {
scene.remove(token.group);
}
animations = [];
urnTokens = [];
trayTokens = [];
allTokens = [];
sampledA = 0;
sampleda = 0;
busy = false;
pendingDraws = 0;
populateUrn();
updateUI();
}
sampleOneButton.addEventListener("click", () => {
if (!busy) requestSample();
});
sampleFourButton.addEventListener("click", () => {
if (busy) return;
pendingDraws = Math.min(4, urnTokens.length);
requestSample();
});
resetButton.addEventListener("click", resetSimulation);
window.addEventListener("keydown", event => {
if (
event.code === "Space" &&
event.target === document.body
) {
event.preventDefault();
if (!busy) requestSample();
}
});
// -------------------------------------------------------------------------
// Direct camera controls — no external controls addon
// -------------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(0.05, 1.05, 0),
azimuth: 0.57,
polar: 1.04,
radius: innerWidth < 600 ? 14 : 11.5,
targetAzimuth: 0.57,
targetPolar: 1.04,
targetRadius: innerWidth < 600 ? 14 : 11.5
};
function resetCamera() {
cameraState.targetAzimuth = 0.57;
cameraState.targetPolar = 1.04;
cameraState.targetRadius = innerWidth < 600 ? 14 : 11.5;
}
document.querySelector("#resetCamera").addEventListener("click", resetCamera);
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const deltaX = event.clientX - pointerX;
const deltaY = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.targetAzimuth -= deltaX * 0.006;
cameraState.targetPolar = THREE.MathUtils.clamp(
cameraState.targetPolar - deltaY * 0.005,
0.35,
1.43
);
});
function endDrag(event) {
dragging = false;
if (
event.pointerId !== undefined &&
renderer.domElement.hasPointerCapture(event.pointerId)
) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
event => {
event.preventDefault();
cameraState.targetRadius = THREE.MathUtils.clamp(
cameraState.targetRadius * Math.exp(event.deltaY * 0.001),
7.5,
18
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
function updateCamera() {
cameraState.azimuth +=
(cameraState.targetAzimuth - cameraState.azimuth) * 0.09;
cameraState.polar +=
(cameraState.targetPolar - cameraState.polar) * 0.09;
cameraState.radius +=
(cameraState.targetRadius - cameraState.radius) * 0.09;
const sinPolar = Math.sin(cameraState.polar);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPolar * Math.sin(cameraState.azimuth),
cameraState.target.y +
cameraState.radius * Math.cos(cameraState.polar),
cameraState.target.z +
cameraState.radius * sinPolar * Math.cos(cameraState.azimuth)
);
camera.lookAt(cameraState.target);
}
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
function onResize() {
camera.aspect = innerWidth / innerHeight;
camera.fov = innerWidth < 600 ? 50 : 38;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
}
window.addEventListener("resize", onResize);
onResize();
populateUrn();
updateUI();
renderer.setAnimationLoop(now => {
updateCamera();
updateAnimations(now);
renderer.render(scene, camera);
});
</script>
</body>
</html>
```