Prompt specification
Build or customize the Three.js 3D scene "One-gene and many-gene trait displays" 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: One-gene and many-gene trait displays
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/one-gene-and-many-gene-trait-displays-x0950
Scene Description Prompt:
Compare stylized single-gene outcome bins with a synthetic many-gene height distribution, labeling the model illustrative. One HTML file using Three.js from cdnjs.
Working Three.js Starter (one-gene-and-many-gene-trait-displays-x0950):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Illustrative: Single-Gene Bins vs. Synthetic Many-Gene Height</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(10, 23, 40, 0.88);
--line: rgba(155, 197, 231, 0.2);
--text: #eef7ff;
--muted: #9db1c7;
--cyan: #56ead2;
--blue: #59a8ff;
--violet: #a884ff;
}
* {
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;
}
#scene {
position: fixed;
inset: 0;
display: block;
width: 100%;
height: 100%;
outline: none;
cursor: grab;
touch-action: none;
}
#scene.dragging {
cursor: grabbing;
}
.header {
position: fixed;
z-index: 10;
top: 24px;
left: 28px;
width: min(660px, calc(100vw - 56px));
pointer-events: none;
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 9px;
margin-bottom: 9px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.eyebrow::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 16px var(--cyan);
content: "";
}
h1 {
margin: 0;
font-size: clamp(25px, 3vw, 42px);
line-height: 1.04;
letter-spacing: -0.035em;
}
.subtitle {
max-width: 600px;
margin: 10px 0 0;
color: var(--muted);
font-size: 14px;
line-height: 1.5;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 16px;
margin-top: 13px;
color: #c4d3e2;
font-size: 12px;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 7px;
}
.swatch {
width: 18px;
height: 8px;
border-radius: 8px;
background: linear-gradient(90deg, var(--cyan), var(--blue));
box-shadow: 0 0 12px rgba(86, 234, 210, 0.25);
}
.swatch.bins {
background: linear-gradient(90deg, var(--cyan), var(--violet));
}
.actions {
position: fixed;
z-index: 20;
top: 22px;
right: 24px;
display: flex;
gap: 8px;
}
button {
border: 1px solid var(--line);
border-radius: 10px;
padding: 9px 12px;
background: rgba(12, 27, 46, 0.88);
color: var(--text);
font: inherit;
font-size: 12px;
cursor: pointer;
transition:
border-color 160ms ease,
background 160ms ease,
transform 160ms ease;
}
button:hover {
border-color: rgba(86, 234, 210, 0.55);
background: rgba(19, 42, 65, 0.96);
transform: translateY(-1px);
}
button:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 2px;
}
button[aria-pressed="true"] {
border-color: rgba(86, 234, 210, 0.65);
color: var(--cyan);
}
.note {
position: fixed;
z-index: 10;
right: 24px;
bottom: 20px;
left: 24px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
margin: 0 auto;
padding: 13px 16px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(7, 17, 31, 0.87);
color: var(--muted);
font-size: 12px;
line-height: 1.45;
backdrop-filter: blur(12px);
}
.note strong {
color: var(--cyan);
}
.note-label {
flex: 0 0 auto;
padding: 5px 8px;
border: 1px solid rgba(86, 234, 210, 0.35);
border-radius: 999px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
#tooltip {
position: fixed;
z-index: 30;
display: none;
min-width: 165px;
max-width: 250px;
padding: 10px 12px;
border: 1px solid rgba(86, 234, 210, 0.35);
border-radius: 10px;
background: rgba(7, 17, 31, 0.96);
color: #dceaff;
font-size: 12px;
line-height: 1.5;
pointer-events: none;
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.35);
}
#tooltip b {
color: var(--cyan);
}
#infoPanel {
position: fixed;
z-index: 25;
top: 72px;
right: 24px;
width: min(380px, calc(100vw - 48px));
padding: 20px;
border: 1px solid var(--line);
border-radius: 15px;
background: rgba(8, 20, 35, 0.97);
box-shadow: 0 20px 70px rgba(0, 0, 0, 0.45);
opacity: 0;
pointer-events: none;
transform: translateY(-8px);
transition:
opacity 180ms ease,
transform 180ms ease;
}
#infoPanel.open {
opacity: 1;
pointer-events: auto;
transform: translateY(0);
}
#infoPanel h2 {
margin: 0 0 12px;
font-size: 19px;
}
#infoPanel p {
margin: 0 0 12px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
#infoPanel p:last-child {
margin-bottom: 0;
}
.formula {
padding: 10px;
border: 1px solid var(--line);
border-radius: 9px;
color: #c8f9ef;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 12px;
line-height: 1.6;
}
@media (max-width: 760px) {
.header {
top: 16px;
left: 16px;
width: calc(100vw - 32px);
}
.subtitle {
max-width: 78%;
font-size: 12px;
}
.legend {
display: none;
}
.actions {
top: auto;
right: 14px;
bottom: 94px;
flex-direction: column;
}
.note {
right: 12px;
bottom: 12px;
left: 12px;
padding: 10px 11px;
font-size: 10px;
}
.note-label {
display: none;
}
#infoPanel {
top: 145px;
right: 12px;
width: calc(100vw - 24px);
}
}
</style>
</head>
<body>
<canvas
id="scene"
tabindex="0"
aria-label="Interactive 3D comparison of stylized single-gene outcome bins and a synthetic many-gene height distribution"
></canvas>
<header class="header">
<div class="eyebrow">Illustrative model · synthetic data</div>
<h1>One locus or many?</h1>
<p class="subtitle">
A stylized single-gene outcome model compared with a synthetic additive
many-gene model of height. Drag to orbit, scroll to zoom, and hover over bars.
</p>
<div class="legend">
<span class="legend-item">
<span class="swatch bins"></span>
Toy single-gene outcome
</span>
<span class="legend-item">
<span class="swatch"></span>
Synthetic height distribution
</span>
</div>
</header>
<div class="actions">
<button id="rotateButton" type="button" aria-pressed="false">Auto rotate</button>
<button id="resetButton" type="button">Reset view</button>
<button id="infoButton" type="button" aria-expanded="false">Model details</button>
</div>
<aside id="infoPanel" aria-hidden="true">
<h2>What this model does</h2>
<p>
<strong>Left:</strong> a fictional classifier assigns a toy cohort to four
discrete height-related outcomes from one illustrative locus.
</p>
<p>
<strong>Right:</strong> 1,800 synthetic heights are generated from 48
independent additive effects plus environmental-style noise.
</p>
<div class="formula">
height = 170 cm<br>
+ Σ(48 synthetic locus effects)<br>
+ environmental noise
</div>
<p>
The parameters, frequencies, labels, and relationship between panels are
invented for demonstration. This is not clinical, biological, or population
genomics evidence.
</p>
</aside>
<div id="tooltip" role="status"></div>
<footer class="note">
<span class="note-label">Illustrative only</span>
<span>
<strong>Not empirical data.</strong>
The left panel is a fictional four-bin classifier; the right panel is a
synthetic many-gene height sample. No biological conclusions should be drawn.
</span>
</footer>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
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;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 24, 48);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
120
);
const target = new THREE.Vector3(0, 2.75, 0);
let yaw = 0;
let pitch = 1.07;
let radius = 23;
let autoRotate = false;
function updateCamera() {
const sinPitch = Math.sin(pitch);
const cosPitch = Math.cos(pitch);
camera.position.set(
target.x + radius * sinPitch * Math.sin(yaw),
target.y + radius * cosPitch,
target.z + radius * sinPitch * Math.cos(yaw)
);
camera.lookAt(target);
}
updateCamera();
scene.add(new THREE.HemisphereLight(0xb9ddff, 0x08101d, 1.8));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.4);
keyLight.position.set(2, 12, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -18;
keyLight.shadow.camera.right = 18;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -8;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x39f2d0, 38, 30);
cyanLight.position.set(-8, 7, 5);
scene.add(cyanLight);
const blueLight = new THREE.PointLight(0x397cff, 34, 28);
blueLight.position.set(8, 6, 3);
scene.add(blueLight);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(42, 14),
new THREE.MeshStandardMaterial({
color: 0x091727,
roughness: 0.92,
metalness: 0.05
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.025;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(42, 42, 0x29425e, 0x172b42);
grid.position.y = -0.015;
grid.material.transparent = true;
grid.material.opacity = 0.32;
scene.add(grid);
const dividerGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, 0.02, -1.8),
new THREE.Vector3(0, 7.9, -1.8)
]);
const divider = new THREE.Line(
dividerGeometry,
new THREE.LineDashedMaterial({
color: 0x56718f,
dashSize: 0.18,
gapSize: 0.16,
transparent: true,
opacity: 0.48
})
);
divider.computeLineDistances();
scene.add(divider);
// -------------------------------------------------------------------------
// Canvas text sprites: implemented without renderer addons.
// -------------------------------------------------------------------------
function roundedRect(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + width, y, x + width, y + height, r);
ctx.arcTo(x + width, y + height, x, y + height, r);
ctx.arcTo(x, y + height, x, y, r);
ctx.arcTo(x, y, x + width, y, r);
ctx.closePath();
}
function makeTextSprite(
lines,
{
worldWidth = 3,
fontSize = 48,
color = "#eef7ff",
background = "rgba(7,17,31,0.82)",
border = "rgba(155,197,231,0.18)",
padding = 26,
lineGap = 10,
align = "center"
} = {}
) {
if (!Array.isArray(lines)) lines = [lines];
const font = `700 ${fontSize}px Inter, system-ui, sans-serif`;
const measureCanvas = document.createElement("canvas");
const measureContext = measureCanvas.getContext("2d");
measureContext.font = font;
const lineHeight = fontSize + lineGap;
const textWidth = Math.max(
...lines.map((line) => measureContext.measureText(line).width)
);
const canvasWidth = Math.ceil(textWidth + padding * 2);
const canvasHeight = Math.ceil(
lines.length * lineHeight + padding * 2 - lineGap
);
const textCanvas = document.createElement("canvas");
textCanvas.width = canvasWidth;
textCanvas.height = canvasHeight;
const context = textCanvas.getContext("2d");
if (background !== "transparent") {
roundedRect(
context,
2,
2,
canvasWidth - 4,
canvasHeight - 4,
Math.min(24, canvasHeight / 4)
);
context.fillStyle = background;
context.fill();
if (border !== "transparent") {
context.strokeStyle = border;
context.lineWidth = 2;
context.stroke();
}
}
context.font = font;
context.fillStyle = color;
context.textAlign = align;
context.textBaseline = "middle";
const x =
align === "center"
? canvasWidth / 2
: align === "right"
? canvasWidth - padding
: padding;
lines.forEach((line, index) => {
const y =
padding + lineHeight * index + fontSize / 2 +
(lines.length - 1) * 0;
context.fillText(line, x, y);
});
const texture = new THREE.CanvasTexture(textCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy());
texture.needsUpdate = true;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false,
toneMapped: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(
worldWidth,
worldWidth * canvasHeight / canvasWidth,
1
);
sprite.renderOrder = 20;
return sprite;
}
function addLine(parent, points, material) {
const geometry = new THREE.BufferGeometry().setFromPoints(
points.map((point) => new THREE.Vector3(...point))
);
const line = new THREE.Line(geometry, material);
parent.add(line);
return line;
}
// -------------------------------------------------------------------------
// Left chart: stylized single-gene outcome bins.
// -------------------------------------------------------------------------
const leftGroup = new THREE.Group();
leftGroup.position.x = -5.9;
scene.add(leftGroup);
const leftTitle = makeTextSprite(
["STYLIZED SINGLE-GENE", "OUTCOME BINS"],
{
worldWidth: 6.25,
fontSize: 51,
background: "rgba(7,17,31,0.72)"
}
);
leftTitle.position.set(0, 8.25, -0.15);
leftGroup.add(leftTitle);
const leftSubtitle = makeTextSprite(
"One toy locus · four discrete outcomes",
{
worldWidth: 5.5,
fontSize: 38,
color: "#9fb3c8",
background: "transparent",
border: "transparent"
}
);
leftSubtitle.position.set(0, 7.52, -0.1);
leftGroup.add(leftSubtitle);
const outcomeBins = [
{ label: "Taller outcome", share: 24, color: 0x49e5c2 },
{ label: "Typical outcome", share: 49, color: 0x4fa8ff },
{ label: "Shorter outcome", share: 17, color: 0xa884ff },
{ label: "No genotype call", share: 10, color: 0x71859d }
];
const leftBarXs = [-1.95, -0.65, 0.65, 1.95];
const leftBaseline = -2.72;
const leftAxisX = -2.75;
const leftPlotRight = 2.75;
const leftGridMaterial = new THREE.LineBasicMaterial({
color: 0x35506c,
transparent: true,
opacity: 0.42
});
const leftAxisMaterial = new THREE.LineBasicMaterial({
color: 0x6f8ba7,
transparent: true,
opacity: 0.78
});
[0, 10, 20, 30, 40, 50].forEach((tick) => {
const y = tick * 0.12;
addLine(
leftGroup,
[[leftAxisX, y, -0.62], [leftPlotRight, y, -0.62]],
leftGridMaterial
);
const label = makeTextSprite(
tick === 50 ? "50%" : String(tick),
{
worldWidth: tick === 50 ? 0.85 : 0.55,
fontSize: 36,
color: "#8fa6bd",
background: "transparent",
border: "transparent"
}
);
label.position.set(leftAxisX - 0.42, y, 0.74);
leftGroup.add(label);
});
addLine(
leftGroup,
[[leftAxisX, 0, 0.72], [leftAxisX, 6.1, 0.72]],
leftAxisMaterial
);
addLine(
leftGroup,
[[leftAxisX, 0, 0.72], [leftPlotRight, 0, 0.72]],
leftAxisMaterial
);
const leftYLabel = makeTextSprite(
"share of toy cohort",
{
worldWidth: 2.75,
fontSize: 34,
color: "#9db3c9",
background: "transparent",
border: "transparent"
}
);
leftYLabel.position.set(-2.55, 6.45, 0.25);
leftGroup.add(leftYLabel);
const pickableBars = [];
const animatedBars = [];
outcomeBins.forEach((bin, index) => {
const height = bin.share * 0.12;
const geometry = new THREE.BoxGeometry(0.92, 1, 1.28);
const color = new THREE.Color(bin.color);
const material = new THREE.MeshStandardMaterial({
color,
emissive: color.clone().multiplyScalar(0.15),
roughness: 0.34,
metalness: 0.16,
transparent: true,
opacity: 0.88
});
const bar = new THREE.Mesh(geometry, material);
bar.position.set(leftBarXs[index], height / 2, 0);
bar.scale.y = 0.001;
bar.castShadow = true;
bar.receiveShadow = true;
bar.userData.targetHeight = height;
bar.userData.delay = index * 90;
bar.userData.tooltip =
`<b>${bin.label}</b><br>${bin.share}% of the fictional toy cohort`;
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry),
new THREE.LineBasicMaterial({
color: 0xd4efff,
transparent: true,
opacity: 0.35
})
);
bar.add(edges);
leftGroup.add(bar);
pickableBars.push(bar);
animatedBars.push(bar);
const valueLabel = makeTextSprite(`${bin.share}%`, {
worldWidth: 1.15,
fontSize: 42,
color: "#f5fbff",
background: "rgba(7,17,31,0.84)"
});
valueLabel.position.set(leftBarXs[index], height + 0.48, 0.05);
leftGroup.add(valueLabel);
const categoryLabel = makeTextSprite(bin.label, {
worldWidth: 2.45,
fontSize: 31,
color: "#c4d3e2",
background: "transparent",
border: "transparent"
});
categoryLabel.position.set(leftBarXs[index], 0.27, 0.94);
leftGroup.add(categoryLabel);
});
// -------------------------------------------------------------------------
// Right chart: deterministic synthetic many-gene height distribution.
// -------------------------------------------------------------------------
function mulberry32(seed) {
return function () {
let value = (seed += 0x6d2b79f5);
value = Math.imul(value ^ (value >>> 15), value | 1);
value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
};
}
const random = mulberry32(20250308);
function normalRandom() {
let u = 0;
let v = 0;
while (u === 0) u = random();
while (v === 0) v = random();
return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
}
const sampleCount = 1800;
const locusCount = 48;
const locusEffectSD = 0.78;
const noiseSD = 2.3;
const syntheticHeights = [];
for (let person = 0; person < sampleCount; person++) {
let additiveEffect = 0;
for (let locus = 0; locus < locusCount; locus++) {
additiveEffect += normalRandom() * locusEffectSD;
}
const height =
170 + additiveEffect + normalRandom() * noiseSD;
syntheticHeights.push(
THREE.MathUtils.clamp(height, 150, 190)
);
}
const meanHeight =
syntheticHeights.reduce((sum, value) => sum + value, 0) /
sampleCount;
const binCount = 26;
const minHeight = 154;
const maxHeight = 186;
const binWidth = (maxHeight - minHeight) / binCount;
const counts = new Array(binCount).fill(0);
syntheticHeights.forEach((height) => {
const index = Math.min(
binCount - 1,
Math.max(0, Math.floor((height - minHeight) / binWidth))
);
counts[index] += 1;
});
const rightGroup = new THREE.Group();
rightGroup.position.x = 6.1;
scene.add(rightGroup);
const rightTitle = makeTextSprite(
["SYNTHETIC MANY-GENE", "HEIGHT DISTRIBUTION"],
{
worldWidth: 7.2,
fontSize: 51,
background: "rgba(7,17,31,0.72)"
}
);
rightTitle.position.set(0, 8.25, -0.15);
rightGroup.add(rightTitle);
const rightSubtitle = makeTextSprite(
"48 additive toy loci · 1,800 simulated people",
{
worldWidth: 6.2,
fontSize: 38,
color: "#9fb3c8",
background: "transparent",
border: "transparent"
}
);
rightSubtitle.position.set(0, 7.52, -0.1);
rightGroup.add(rightSubtitle);
const rightPlotLeft = -4.65;
const rightPlotRight = 4.65;
const rightAxisX = -4.9;
const rightGridMaterial = new THREE.LineBasicMaterial({
color: 0x35506c,
transparent: true,
opacity: 0.4
});
const rightAxisMaterial = new THREE.LineBasicMaterial({
color: 0x6f8ba7,
transparent: true,
opacity: 0.78
});
[0, 2, 4, 6, 8].forEach((tick) => {
const y = tick * 0.82;
addLine(
rightGroup,
[[rightAxisX, y, -0.62], [rightPlotRight, y, -0.62]],
rightGridMaterial
);
const label = makeTextSprite(
tick === 8 ? "8%" : String(tick),
{
worldWidth: tick === 8 ? 0.8 : 0.5,
fontSize: 36,
color: "#8fa6bd",
background: "transparent",
border: "transparent"
}
);
label.position.set(rightAxisX - 0.4, y, 0.74);
rightGroup.add(label);
});
addLine(
rightGroup,
[[rightAxisX, 0, 0.72], [rightAxisX, 6.65, 0.72]],
rightAxisMaterial
);
addLine(
rightGroup,
[[rightAxisX, 0, 0.72], [rightPlotRight, 0, 0.72]],
rightAxisMaterial
);
const rightYLabel = makeTextSprite(
"synthetic share per bin",
{
worldWidth: 3.1,
fontSize: 34,
color: "#9db3c9",
background: "transparent",
border: "transparent"
}
);
rightYLabel.position.set(-4.7, 6.95, 0.25);
rightGroup.add(rightYLabel);
const histogramBars = [];
const curvePoints = [];
const smoothingWeights = [1, 2, 3, 4, 3, 2, 1];
for (let index = 0; index < binCount; index++) {
const binCenter = minHeight + binWidth * (index + 0.5);
const x =
rightPlotLeft +
((binCenter - minHeight) / (maxHeight - minHeight)) *
(rightPlotRight - rightPlotLeft);
const percent = (counts[index] / sampleCount) * 100;
const height = percent * 0.82;
const t = index / (binCount - 1);
const color = new THREE.Color(0x3479ff).lerp(
new THREE.Color(0x48efd0),
t
);
const geometry = new THREE.BoxGeometry(
(rightPlotRight - rightPlotLeft) / binCount * 0.72,
1,
1.32
);
const bar = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
color,
emissive: color.clone().multiplyScalar(0.13),
roughness: 0.4,
metalness: 0.08,
transparent: true,
opacity: 0.7
})
);
bar.position.set(x, height / 2, 0);
bar.scale.y = 0.001;
bar.castShadow = true;
bar.receiveShadow = true;
bar.userData.targetHeight = height;
bar.userData.delay = 180 + index * 14;
bar.userData.tooltip =
`<b>${(binCenter - binWidth / 2).toFixed(1)}–` +
`${(binCenter + binWidth / 2).toFixed(1)} cm</b><br>` +
`${counts[index]} simulated people · ${percent.toFixed(1)}%`;
rightGroup.add(bar);
histogramBars.push(bar);
pickableBars.push(bar);
animatedBars.push(bar);
let smoothedCount = 0;
let totalWeight = 0;
for (
let offset = -Math.floor(smoothingWeights.length / 2);
offset <= Math.floor(smoothingWeights.length / 2);
offset++
) {
const sourceIndex = index + offset;
if (sourceIndex < 0 || sourceIndex >= binCount) continue;
const weight = smoothingWeights[offset + 3];
smoothedCount += counts[sourceIndex] * weight;
totalWeight += weight;
}
const smoothedPercent =
(smoothedCount / totalWeight / sampleCount) * 100;
const smoothedHeight = smoothedPercent * 0.82;
curvePoints.push(
new THREE.Vector3(x, smoothedHeight + 0.04, 0.08)
);
}
const curve = new THREE.CatmullRomCurve3(
curvePoints,
false,
"centripetal"
);
const curveMesh = new THREE.Mesh(
new THREE.TubeGeometry(curve, 180, 0.045, 7, false),
new THREE.MeshBasicMaterial({
color: 0xa5fff2,
transparent: true,
opacity: 0.96,
toneMapped: false
})
);
rightGroup.add(curveMesh);
const meanX =
rightPlotLeft +
((meanHeight - minHeight) / (maxHeight - minHeight)) *
(rightPlotRight - rightPlotLeft);
const meanLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(meanX, 0, -0.38),
new THREE.Vector3(meanX, 6.35, -0.38)
]),
new THREE.LineDashedMaterial({
color: 0xffd18a,
dashSize: 0.16,
gapSize: 0.12,
transparent: true,
opacity: 0.8
})
);
meanLine.computeLineDistances();
rightGroup.add(meanLine);
const meanLabel = makeTextSprite(
`mean ${meanHeight.toFixed(1)} cm`,
{
worldWidth: 2.35,
fontSize: 36,
color: "#ffe0a5",
background: "rgba(7,17,31,0.88)"
}
);
meanLabel.position.set(meanX, 6.52, 0.05);
rightGroup.add(meanLabel);
[160, 165, 170, 175, 180, 185].forEach((height) => {
const x =
rightPlotLeft +
((height - minHeight) / (maxHeight - minHeight)) *
(rightPlotRight - rightPlotLeft);
const label = makeTextSprite(
height === 185 ? "185 cm" : String(height),
{
worldWidth: height === 185 ? 1.25 : 0.85,
fontSize: 34,
color: "#8fa6bd",
background: "transparent",
border: "transparent"
}
);
label.position.set(x, 0.25, 0.94);
rightGroup.add(label);
});
// -------------------------------------------------------------------------
// Direct camera controls: pointer drag, wheel, touch, and keyboard.
// -------------------------------------------------------------------------
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
canvas.classList.add("dragging");
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (dragging) {
const deltaX = event.clientX - previousPointerX;
const deltaY = event.clientY - previousPointerY;
yaw -= deltaX * 0.006;
pitch = THREE.MathUtils.clamp(pitch + deltaY * 0.004, 0.68, 1.34);
previousPointerX = event.clientX;
previousPointerY = event.clientY;
updateCamera();
}
updatePointer(event);
});
function endDrag(event) {
dragging = false;
canvas.classList.remove("dragging");
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
radius = THREE.MathUtils.clamp(
radius * Math.exp(event.deltaY * 0.001),
16,
31
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("keydown", (event) => {
let handled = true;
switch (event.key) {
case "ArrowLeft":
yaw += 0.08;
break;
case "ArrowRight":
yaw -= 0.08;
break;
case "ArrowUp":
pitch = Math.max(0.68, pitch - 0.06);
break;
case "ArrowDown":
pitch = Math.min(1.34, pitch + 0.06);
break;
case "+":
case "=":
radius = Math.max(16, radius - 0.8);
break;
case "-":
case "_":
radius = Math.min(31, radius + 0.8);
break;
case "r":
case "R":
resetView();
break;
default:
handled = false;
}
if (handled) {
event.preventDefault();
updateCamera();
}
});
// -------------------------------------------------------------------------
// Hover picking.
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2(2, 2);
const tooltip = document.querySelector("#tooltip");
let pointerClientX = 0;
let pointerClientY = 0;
let pointerInside = false;
function updatePointer(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
pointerClientX = event.clientX;
pointerClientY = event.clientY;
pointerInside = true;
}
function updateTooltip() {
if (!pointerInside || dragging) {
tooltip.style.display = "none";
return;
}
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(pickableBars, false);
if (!hits.length) {
tooltip.style.display = "none";
return;
}
tooltip.innerHTML = hits[0].object.userData.tooltip;
tooltip.style.display = "block";
const tooltipWidth = tooltip.offsetWidth;
const tooltipHeight = tooltip.offsetHeight;
const left = Math.min(
window.innerWidth - tooltipWidth - 12,
pointerClientX + 15
);
const top = Math.min(
window.innerHeight - tooltipHeight - 12,
pointerClientY + 15
);
tooltip.style.left = `${Math.max(8, left)}px`;
tooltip.style.top = `${Math.max(8, top)}px`;
}
canvas.addEventListener("pointerleave", () => {
pointerInside = false;
tooltip.style.display = "none";
});
// -------------------------------------------------------------------------
// Interface controls.
// -------------------------------------------------------------------------
const rotateButton = document.querySelector("#rotateButton");
const resetButton = document.querySelector("#resetButton");
const infoButton = document.querySelector("#infoButton");
const infoPanel = document.querySelector("#infoPanel");
function resetView() {
yaw = 0;
pitch = 1.07;
radius = 23;
updateCamera();
}
resetButton.addEventListener("click", resetView);
rotateButton.addEventListener("click", () => {
autoRotate = !autoRotate;
rotateButton.setAttribute("aria-pressed", String(autoRotate));
rotateButton.textContent = autoRotate ? "Pause rotation" : "Auto rotate";
});
infoButton.addEventListener("click", () => {
const isOpen = infoPanel.classList.toggle("open");
infoPanel.setAttribute("aria-hidden", String(!isOpen));
infoButton.setAttribute("aria-expanded", String(isOpen));
});
document.addEventListener("keydown", (event) => {
if (event.key === "Escape") {
infoPanel.classList.remove("open");
infoPanel.setAttribute("aria-hidden", "true");
infoButton.setAttribute("aria-expanded", "false");
}
});
// -------------------------------------------------------------------------
// Resize and animation.
// -------------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
const clock = new THREE.Clock();
function easeOutCubic(value) {
return 1 - Math.pow(1 - value, 3);
}
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
const now = performance.now();
if (autoRotate && !dragging) {
yaw -= delta * 0.075;
updateCamera();
}
animatedBars.forEach((bar) => {
const progress = THREE.MathUtils.clamp(
(now - bar.userData.delay) / 850,
0,
1
);
const eased = easeOutCubic(progress);
const height = bar.userData.targetHeight * eased;
bar.scale.y = Math.max(height, 0.001);
bar.position.y = bar.scale.y / 2;
});
updateTooltip();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```