Prompt specification
Build or customize the Three.js 3D scene "Changing probability versus changing trial count" 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: Changing probability versus changing trial count
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/changing-probability-versus-changing-trial-count-x1770
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing a scene with matched binomial distributions side by side and vary one parameter at a time; show changes in center and spread without confusing count with proportion. Stylized solid forms.
Working Three.js Starter (changing-probability-versus-changing-trial-count-x1770):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Matched Binomial Distributions</title>
<style>
:root {
--ink: #18312f;
--muted: #637471;
--paper: #f5f6f1;
--panel: #ffffff;
--line: #dce3dd;
--teal: #167c78;
--teal-soft: #d9efeb;
--orange: #e36e50;
--orange-soft: #f9e4dc;
--navy: #173b3a;
--shadow: 0 18px 48px rgba(28, 53, 49, 0.10);
}
* {
box-sizing: border-box;
}
body {
margin: 0;
color: var(--ink);
background:
radial-gradient(circle at 10% 0%, rgba(22, 124, 120, 0.08), transparent 32rem),
radial-gradient(circle at 95% 10%, rgba(227, 110, 80, 0.08), transparent 30rem),
var(--paper);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
font-variant-numeric: tabular-nums;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
main {
width: min(1480px, calc(100% - 32px));
margin: 0 auto;
padding: 34px 0 42px;
}
.eyebrow {
margin: 0 0 8px;
color: var(--teal);
font-size: 0.75rem;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
max-width: 920px;
margin: 0;
font-size: clamp(2rem, 4.1vw, 4.2rem);
line-height: 0.98;
letter-spacing: -0.055em;
}
.intro {
max-width: 850px;
margin: 18px 0 26px;
color: var(--muted);
font-size: clamp(1rem, 1.5vw, 1.14rem);
line-height: 1.65;
}
.controls {
display: grid;
grid-template-columns: auto minmax(260px, 1fr) auto;
gap: 22px;
align-items: center;
margin-bottom: 16px;
padding: 16px;
border: 1px solid rgba(255, 255, 255, 0.82);
border-radius: 20px;
background: rgba(255, 255, 255, 0.82);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
}
.control-label {
margin: 0 0 8px;
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.segmented {
display: flex;
gap: 5px;
padding: 5px;
border: 1px solid var(--line);
border-radius: 14px;
background: #edf1ec;
}
.segmented button {
min-width: 116px;
padding: 10px 14px;
border: 0;
border-radius: 10px;
background: transparent;
cursor: pointer;
font-weight: 750;
transition: background 160ms ease, color 160ms ease, box-shadow 160ms ease;
}
.segmented button:hover {
background: rgba(255, 255, 255, 0.65);
}
.segmented button[aria-pressed="true"] {
color: white;
background: var(--navy);
box-shadow: 0 5px 12px rgba(23, 59, 58, 0.18);
}
.slider-heading {
display: flex;
justify-content: space-between;
gap: 18px;
align-items: baseline;
}
.slider-heading label {
font-weight: 750;
}
output {
color: var(--teal);
font-size: 1.15rem;
font-weight: 850;
}
input[type="range"] {
width: 100%;
height: 7px;
margin: 13px 0 6px;
border-radius: 999px;
appearance: none;
background:
linear-gradient(
to right,
var(--teal) 0 var(--fill, 50%),
#dbe3dc var(--fill, 50%) 100%
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 21px;
height: 21px;
border: 4px solid white;
border-radius: 50%;
appearance: none;
background: var(--teal);
box-shadow: 0 2px 10px rgba(20, 67, 63, 0.30);
}
input[type="range"]::-moz-range-thumb {
width: 14px;
height: 14px;
border: 4px solid white;
border-radius: 50%;
background: var(--teal);
box-shadow: 0 2px 10px rgba(20, 67, 63, 0.30);
}
.range-ends {
display: flex;
justify-content: space-between;
color: var(--muted);
font-size: 0.78rem;
}
.control-actions {
display: flex;
flex-direction: column;
gap: 8px;
}
.small-button {
padding: 10px 14px;
border: 1px solid var(--line);
border-radius: 11px;
background: white;
cursor: pointer;
font-weight: 750;
white-space: nowrap;
transition: transform 140ms ease, border-color 140ms ease;
}
.small-button:hover {
border-color: #aebdb5;
transform: translateY(-1px);
}
.scene-shell {
position: relative;
height: clamp(510px, 61vh, 680px);
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.9);
border-radius: 26px;
background: #edf1eb;
box-shadow: var(--shadow);
isolation: isolate;
}
.scene-shell canvas {
position: absolute;
inset: 0;
z-index: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
.scene-shell canvas:active {
cursor: grabbing;
}
.scene-top {
position: absolute;
top: 16px;
left: 18px;
right: 18px;
z-index: 3;
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 14px;
pointer-events: none;
}
.legend,
.scale-badge {
border: 1px solid rgba(255, 255, 255, 0.95);
border-radius: 14px;
background: rgba(255, 255, 255, 0.83);
box-shadow: 0 7px 24px rgba(31, 55, 51, 0.08);
backdrop-filter: blur(12px);
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 12px;
padding: 10px 13px;
font-size: 0.82rem;
font-weight: 750;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 7px;
}
.swatch {
width: 12px;
height: 12px;
border-radius: 4px;
}
.swatch.teal {
background: var(--teal);
}
.swatch.orange {
background: var(--orange);
}
.scale-badge {
padding: 10px 13px;
color: var(--muted);
font-size: 0.78rem;
text-align: right;
}
.scale-badge strong {
display: block;
margin-bottom: 2px;
color: var(--ink);
font-size: 0.86rem;
}
.scene-bottom {
position: absolute;
right: 16px;
bottom: 14px;
z-index: 3;
display: flex;
align-items: center;
gap: 9px;
pointer-events: none;
}
.camera-hint {
padding: 8px 11px;
border-radius: 10px;
color: var(--muted);
background: rgba(255, 255, 255, 0.78);
font-size: 0.74rem;
backdrop-filter: blur(10px);
}
#resetCamera {
pointer-events: auto;
box-shadow: 0 5px 14px rgba(31, 55, 51, 0.09);
}
.tooltip {
position: absolute;
z-index: 8;
display: none;
width: 226px;
padding: 13px 14px;
border: 1px solid rgba(255, 255, 255, 0.95);
border-radius: 13px;
color: white;
background: rgba(22, 48, 46, 0.94);
box-shadow: 0 12px 32px rgba(18, 40, 38, 0.22);
pointer-events: none;
font-size: 0.78rem;
line-height: 1.55;
}
.tooltip strong {
display: block;
margin-bottom: 4px;
color: #d5fff7;
font-size: 0.9rem;
}
.tooltip .tooltip-row {
display: flex;
justify-content: space-between;
gap: 12px;
}
.stats-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px;
margin-top: 16px;
}
.stats-card {
padding: 18px;
border: 1px solid rgba(255, 255, 255, 0.92);
border-top: 5px solid var(--teal);
border-radius: 18px;
background: rgba(255, 255, 255, 0.88);
box-shadow: 0 10px 30px rgba(30, 54, 50, 0.07);
}
.stats-card.variant {
border-top-color: var(--orange);
}
.stats-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 16px;
margin-bottom: 13px;
}
.stats-header h2 {
margin: 0 0 4px;
font-size: 1.12rem;
}
.stats-header p {
margin: 0;
color: var(--muted);
font-size: 0.83rem;
}
.parameters {
display: inline-flex;
gap: 7px;
flex-wrap: wrap;
}
.parameter-chip {
padding: 6px 9px;
border-radius: 9px;
color: var(--navy);
background: var(--teal-soft);
font-size: 0.78rem;
font-weight: 800;
}
.variant .parameter-chip {
background: var(--orange-soft);
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.metric {
min-height: 92px;
padding: 12px;
border-radius: 12px;
background: #f3f5f1;
}
.metric-label {
display: block;
margin-bottom: 6px;
color: var(--muted);
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.055em;
text-transform: uppercase;
}
.metric strong {
display: block;
margin-bottom: 4px;
font-size: 1rem;
}
.metric small {
display: block;
color: var(--muted);
line-height: 1.35;
}
.delta {
margin-top: 11px;
padding: 10px 12px;
border-radius: 11px;
color: #794032;
background: var(--orange-soft);
font-size: 0.8rem;
line-height: 1.5;
}
.reading-guide {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 12px;
margin-top: 16px;
}
.guide-item {
padding: 15px 16px;
border: 1px solid var(--line);
border-radius: 15px;
background: rgba(255, 255, 255, 0.56);
}
.guide-item b {
display: block;
margin-bottom: 5px;
color: var(--teal);
font-size: 0.8rem;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.guide-item p {
margin: 0;
color: var(--muted);
font-size: 0.84rem;
line-height: 1.55;
}
.footer-note {
margin: 18px 2px 0;
color: var(--muted);
font-size: 0.76rem;
line-height: 1.55;
}
@media (max-width: 860px) {
main {
width: min(100% - 20px, 1480px);
padding-top: 22px;
}
.controls {
grid-template-columns: 1fr;
gap: 15px;
}
.control-actions {
flex-direction: row;
}
.control-actions button {
flex: 1;
}
.stats-grid,
.reading-guide {
grid-template-columns: 1fr;
}
.scene-shell {
height: 560px;
}
.scene-top {
flex-direction: column;
}
.scale-badge {
text-align: left;
}
.camera-hint {
display: none;
}
}
@media (max-width: 520px) {
.metric-grid {
grid-template-columns: 1fr;
}
.stats-header {
flex-direction: column;
}
.segmented button {
min-width: 0;
flex: 1;
}
}
</style>
</head>
<body>
<main>
<header>
<p class="eyebrow">Interactive comparison · one parameter at a time</p>
<h1>Binomial distributions, without mixing count with proportion.</h1>
<p class="intro">
Reference A and variant B match on every setting except the parameter you
choose. Bar height shows probability mass, the horizontal scale shows a
count of successes, and the lower ruler converts that count to a share of trials.
</p>
</header>
<section class="controls" aria-label="Comparison controls">
<div>
<p class="control-label">Change in B only</p>
<div class="segmented" role="group" aria-label="Parameter to vary">
<button type="button" data-param="n" aria-pressed="false">Trials n</button>
<button type="button" data-param="p" aria-pressed="true">Success p</button>
</div>
</div>
<div>
<div class="slider-heading">
<label id="sliderLabel" for="parameterSlider">Success probability</label>
<output id="sliderValue" for="parameterSlider">62%</output>
</div>
<input
id="parameterSlider"
type="range"
min="0.05"
max="0.95"
step="0.01"
value="0.62"
>
<div class="range-ends">
<span id="rangeMin">5%</span>
<span id="rangeMax">95%</span>
</div>
</div>
<div class="control-actions">
<button class="small-button" id="resetVariant" type="button">Match A</button>
<button class="small-button" id="resetCamera" type="button">Reset view</button>
</div>
</section>
<section class="scene-shell" id="sceneShell" aria-label="Three-dimensional binomial comparison">
<div class="scene-top">
<div class="legend">
<span><i class="swatch teal"></i>A · Reference</span>
<span><i class="swatch orange"></i>B · Variant</span>
</div>
<div class="scale-badge">
<strong>Shared vertical scale</strong>
<span id="scaleText">Bar height = probability mass P(K=k)</span>
</div>
</div>
<div class="tooltip" id="tooltip"></div>
<div class="scene-bottom">
<span class="camera-hint">Drag to orbit · scroll to zoom · hover a bar</span>
<button class="small-button" id="resetCameraBottom" type="button">Reset view</button>
</div>
</section>
<section class="stats-grid" aria-live="polite">
<article class="stats-card" id="referenceStats"></article>
<article class="stats-card variant" id="variantStats"></article>
</section>
<section class="reading-guide" aria-label="How to read the chart">
<article class="guide-item">
<b>1 · Count on x</b>
<p>
A bar at k represents exactly k successes. The upper front ruler is in
counts; the lower front ruler is the same position expressed as k/n.
</p>
</article>
<article class="guide-item">
<b>2 · Probability on y</b>
<p>
Bar height is P(K=k), the probability mass at that exact count.
It is neither the count k nor the proportion k/n.
</p>
</article>
<article class="guide-item">
<b>3 · Center and spread</b>
<p>
The marker is the mean count. The translucent band is ±1 standard
deviation in count units. The cards report both counts and proportions.
</p>
</article>
</section>
<p class="footer-note">
The marker and band summarize location and dispersion; they are not literal
probability-mass intervals. Hovering a bar reveals its count, proportion, and
probability separately. Camera controls are implemented directly with pointer
and wheel events; no camera-control addons are used.
</p>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const sceneShell = document.getElementById("sceneShell");
const tooltip = document.getElementById("tooltip");
const slider = document.getElementById("parameterSlider");
const sliderLabel = document.getElementById("sliderLabel");
const sliderValue = document.getElementById("sliderValue");
const rangeMin = document.getElementById("rangeMin");
const rangeMax = document.getElementById("rangeMax");
const referenceStats = document.getElementById("referenceStats");
const variantStats = document.getElementById("variantStats");
const scaleText = document.getElementById("scaleText");
const reference = { n: 12, p: 0.35 };
const variant = { n: 12, p: 0.62 };
let activeParameter = "p";
const parameterConfig = {
n: {
min: 5,
max: 24,
step: 1,
label: "Number of trials",
shortLabel: "Trials n"
},
p: {
min: 0.05,
max: 0.95,
step: 0.01,
label: "Success probability",
shortLabel: "Success p"
}
};
const palette = {
teal: 0x167c78,
tealDark: 0x0f5552,
orange: 0xe36e50,
orangeDark: 0xa84632,
cream: 0xfaf9f3,
backdrop: 0xf6f7f2,
axis: 0x47605c,
floor: 0xe8ede7
};
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xedf1eb);
const camera = new THREE.OrthographicCamera(-12, 12, 6, -6, 0.1, 100);
const cameraTarget = new THREE.Vector3(0, 2.0, 0);
const cameraState = {
yaw: -0.055,
phi: 1.16,
zoom: 1
};
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
sceneShell.appendChild(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xffffff, 0xbfcac4, 2.2));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(-7, 13, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -15;
keyLight.shadow.camera.right = 15;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -12;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 40;
keyLight.shadow.bias = -0.0006;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0xb9e7df, 1.2);
rimLight.position.set(10, 7, -8);
scene.add(rimLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(50, 32),
new THREE.MeshStandardMaterial({
color: palette.floor,
roughness: 0.96,
metalness: 0
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.36;
floor.receiveShadow = true;
scene.add(floor);
let panelA = null;
let panelB = null;
let allBars = [];
let barAnimations = [];
function logFactorial(n) {
let result = 0;
for (let i = 2; i <= n; i++) result += Math.log(i);
return result;
}
function binomialProbability(n, k, p) {
if (p <= 0) return k === 0 ? 1 : 0;
if (p >= 1) return k === n ? 1 : 0;
const logCombination =
logFactorial(n) - logFactorial(k) - logFactorial(n - k);
const logProbability =
logCombination +
k * Math.log(p) +
(n - k) * Math.log(1 - p);
return Math.exp(logProbability);
}
function describeDistribution(model) {
const probabilities = [];
for (let k = 0; k <= model.n; k++) {
probabilities.push(binomialProbability(model.n, k, model.p));
}
const mean = model.n * model.p;
const variance = model.n * model.p * (1 - model.p);
const standardDeviation = Math.sqrt(variance);
const peak = Math.max(...probabilities);
const modes = [];
probabilities.forEach((value, index) => {
if (Math.abs(value - peak) < 1e-10) modes.push(index);
});
return {
...model,
probabilities,
mean,
variance,
standardDeviation,
peak,
modes
};
}
function roundedShape(width, height, radius) {
const r = Math.max(
0.001,
Math.min(radius, width / 2 - 0.001, height / 2 - 0.001)
);
const shape = new THREE.Shape();
shape.moveTo(-width / 2 + r, 0);
shape.lineTo(width / 2 - r, 0);
shape.quadraticCurveTo(width / 2, 0, width / 2, r);
shape.lineTo(width / 2, height - r);
shape.quadraticCurveTo(width / 2, height, width / 2 - r, height);
shape.lineTo(-width / 2 + r, height);
shape.quadraticCurveTo(-width / 2, height, -width / 2, height - r);
shape.lineTo(-width / 2, r);
shape.quadraticCurveTo(-width / 2, 0, -width / 2 + r, 0);
return shape;
}
function roundedPrism(width, height, depth, radius, material) {
const geometry = new THREE.ExtrudeGeometry(
roundedShape(width, height, radius),
{
depth,
steps: 1,
curveSegments: 5,
bevelEnabled: true,
bevelSegments: 2,
bevelSize: Math.min(0.022, radius * 0.25),
bevelThickness: Math.min(0.022, radius * 0.25)
}
);
geometry.translate(0, 0, -depth / 2);
const mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
function makeTextSprite(
text,
worldWidth,
{
color = "#203b38",
background = null,
fontSize = 62,
fontWeight = 750
} = {}
) {
const canvas = document.createElement("canvas");
canvas.width = 1024;
canvas.height = 160;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
if (background) {
context.fillStyle = background;
context.beginPath();
context.roundRect(6, 6, 1012, 148, 34);
context.fill();
}
let size = fontSize;
context.font = `${fontWeight} ${size}px Inter, system-ui, sans-serif`;
const measured = context.measureText(text).width;
if (measured > 960) {
size *= 960 / measured;
context.font = `${fontWeight} ${size}px Inter, system-ui, sans-serif`;
}
context.fillStyle = color;
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 512, 82);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.generateMipmaps = false;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(worldWidth, worldWidth * canvas.height / canvas.width, 1);
sprite.renderOrder = 20;
return sprite;
}
function addRod(group, start, end, radius, material) {
const a = new THREE.Vector3(...start);
const b = new THREE.Vector3(...end);
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
const geometry = new THREE.CylinderGeometry(
radius,
radius,
length,
10
);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.castShadow = true;
group.add(mesh);
return mesh;
}
function disposePanel(panel) {
if (!panel) return;
panel.group.traverse(object => {
object.userData.dead = true;
if (object.geometry) object.geometry.dispose();
const materials = object.material
? (Array.isArray(object.material) ? object.material : [object.material])
: [];
materials.forEach(material => {
if (material.map) material.map.dispose();
material.dispose();
});
});
scene.remove(panel.group);
}
function buildPanel(distribution, kind, xPosition, scaleMaximum) {
const group = new THREE.Group();
group.position.x = xPosition;
const isReference = kind === "A";
const accent = isReference ? palette.teal : palette.orange;
const accentDark = isReference ? palette.tealDark : palette.orangeDark;
const accentCSS = isReference ? "#167c78" : "#e36e50";
const baseMaterial = new THREE.MeshStandardMaterial({
color: palette.cream,
roughness: 0.78,
metalness: 0.01
});
const backMaterial = new THREE.MeshStandardMaterial({
color: palette.backdrop,
roughness: 0.82,
metalness: 0
});
const accentMaterial = new THREE.MeshStandardMaterial({
color: accent,
roughness: 0.48,
metalness: 0.04,
emissive: accent,
emissiveIntensity: 0.025
});
const axisMaterial = new THREE.MeshStandardMaterial({
color: palette.axis,
roughness: 0.68,
metalness: 0.02
});
const back = roundedPrism(9.55, 4.22, 0.18, 0.20, backMaterial);
back.position.z = -1.57;
group.add(back);
const base = roundedPrism(9.82, 0.34, 4.80, 0.17, baseMaterial);
base.position.y = -0.34;
group.add(base);
const edge = roundedPrism(0.11, 4.20, 0.21, 0.045, accentMaterial);
edge.position.set(-4.61, 0, -1.43);
group.add(edge);
const title = makeTextSprite(
isReference ? "A · REFERENCE" : "B · VARIANT",
3.9,
{ color: accentCSS, fontSize: 68, fontWeight: 850 }
);
title.position.set(0, 4.86, -1.15);
group.add(title);
const subtitle = makeTextSprite(
`n = ${distribution.n} trials · p = ${Math.round(distribution.p * 100)}%`,
3.9,
{ color: "#526864", fontSize: 54, fontWeight: 700 }
);
subtitle.position.set(0, 4.42, -1.12);
group.add(subtitle);
const plotWidth = 8.15;
const chartHeight = 3.76;
const left = -plotWidth / 2;
const right = plotWidth / 2;
const spacing = plotWidth / distribution.n;
const barWidth = Math.min(0.76, spacing * 0.66);
const bars = [];
distribution.probabilities.forEach((probability, k) => {
const barHeight = Math.max(
0.018,
probability / scaleMaximum * chartHeight
);
const material = new THREE.MeshStandardMaterial({
color: accent,
roughness: 0.46,
metalness: 0.025,
emissive: accent,
emissiveIntensity: 0.035
});
const bar = roundedPrism(
barWidth,
barHeight,
0.64,
Math.min(0.085, barWidth * 0.24),
material
);
const x = left + (k + 0.5) * spacing;
bar.position.set(x, 0.025, -0.43);
bar.scale.y = 0.025;
bar.userData.info = {
count: k,
trials: distribution.n,
proportion: k / distribution.n,
probability
};
group.add(bar);
bars.push(bar);
});
const axisLeft = left - 0.38;
const yTop = chartHeight + 0.04;
addRod(
group,
[axisLeft, 0.03, -0.34],
[axisLeft, yTop, -0.34],
0.022,
axisMaterial
);
const probabilityLabel = makeTextSprite(
"P(K=k)",
1.18,
{ color: "#526864", fontSize: 56, fontWeight: 800 }
);
probabilityLabel.position.set(left - 0.14, 4.02, -0.25);
group.add(probabilityLabel);
const probabilityTicks = [0, scaleMaximum / 2, scaleMaximum];
probabilityTicks.forEach(value => {
const y = value / scaleMaximum * chartHeight;
addRod(
group,
[axisLeft - 0.12, y, -0.34],
[axisLeft + 0.05, y, -0.34],
0.018,
axisMaterial
);
const label = makeTextSprite(
value === 0 ? "0" : value.toFixed(2),
0.67,
{ color: "#526864", fontSize: 53, fontWeight: 700 }
);
label.position.set(axisLeft - 0.54, y + 0.02, 0.02);
group.add(label);
});
const countRulerZ = 1.15;
const shareRulerZ = 1.88;
addRod(
group,
[left, 0.055, countRulerZ],
[right, 0.055, countRulerZ],
0.020,
axisMaterial
);
const shareMaterial = new THREE.MeshStandardMaterial({
color: accent,
roughness: 0.6,
metalness: 0.02
});
addRod(
group,
[left, 0.065, shareRulerZ],
[right, 0.065, shareRulerZ],
0.026,
shareMaterial
);
const countTicks = [...new Set([0, Math.round(distribution.n / 2), distribution.n])];
countTicks.forEach(k => {
const x = left + (k / distribution.n) * plotWidth;
addRod(
group,
[x, 0.06, countRulerZ - 0.08],
[x, 0.06, countRulerZ + 0.10],
0.017,
axisMaterial
);
const label = makeTextSprite(
String(k),
0.62,
{ color: "#405854", fontSize: 56, fontWeight: 750 }
);
label.position.set(x, 0.10, countRulerZ + 0.25);
group.add(label);
});
[0, 0.5, 1].forEach(proportion => {
const x = left + proportion * plotWidth;
addRod(
group,
[x, 0.07, shareRulerZ - 0.08],
[x, 0.07, shareRulerZ + 0.10],
0.021,
shareMaterial
);
const label = makeTextSprite(
`${Math.round(proportion * 100)}%`,
0.72,
{ color: accentCSS, fontSize: 53, fontWeight: 800 }
);
label.position.set(x, 0.10, shareRulerZ + 0.27);
group.add(label);
});
const countAxisLabel = makeTextSprite(
"COUNT",
0.93,
{ color: "#405854", fontSize: 48, fontWeight: 850 }
);
countAxisLabel.position.set(right + 0.55, 0.13, countRulerZ);
group.add(countAxisLabel);
const shareAxisLabel = makeTextSprite(
"SHARE k/n",
1.20,
{ color: accentCSS, fontSize: 45, fontWeight: 850 }
);
shareAxisLabel.position.set(right + 0.67, 0.13, shareRulerZ);
group.add(shareAxisLabel);
const centerX = left +
(distribution.mean / distribution.n) * plotWidth;
const spreadStart = Math.max(0, distribution.mean - distribution.standardDeviation);
const spreadEnd = Math.min(
distribution.n,
distribution.mean + distribution.standardDeviation
);
const spreadLeft = left + (spreadStart / distribution.n) * plotWidth;
const spreadRight = left + (spreadEnd / distribution.n) * plotWidth;
const spreadWidth = Math.max(0.06, spreadRight - spreadLeft);
const spreadMaterial = new THREE.MeshStandardMaterial({
color: accent,
roughness: 0.65,
metalness: 0,
transparent: true,
opacity: 0.27,
depthWrite: false
});
const spreadBand = roundedPrism(
spreadWidth,
0.075,
0.62,
0.03,
spreadMaterial
);
spreadBand.position.set(
(spreadLeft + spreadRight) / 2,
0.055,
countRulerZ - 0.03
);
group.add(spreadBand);
const markerMaterial = new THREE.MeshStandardMaterial({
color: accentDark,
roughness: 0.4,
metalness: 0.04
});
addRod(
group,
[centerX, 0.09, countRulerZ],
[centerX, 0.56, countRulerZ],
0.035,
markerMaterial
);
const centerMarker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.13, 0),
markerMaterial
);
centerMarker.position.set(centerX, 0.62, countRulerZ);
centerMarker.castShadow = true;
group.add(centerMarker);
addRod(
group,
[centerX, 0.12, countRulerZ],
[centerX, 0.12, shareRulerZ],
0.026,
markerMaterial
);
const shareMarker = new THREE.Mesh(
new THREE.SphereGeometry(0.105, 16, 12),
markerMaterial
);
shareMarker.position.set(centerX, 0.16, shareRulerZ);
shareMarker.castShadow = true;
group.add(shareMarker);
const spreadLabel = makeTextSprite(
`±1σ = ${distribution.standardDeviation.toFixed(2)} counts`,
1.75,
{ color: accentCSS, fontSize: 43, fontWeight: 800 }
);
spreadLabel.position.set(centerX, 0.94, countRulerZ + 0.02);
group.add(spreadLabel);
scene.add(group);
return {
group,
bars
};
}
function formatModes(distribution) {
const first = distribution.modes[0];
const last = distribution.modes[distribution.modes.length - 1];
if (first !== last) {
return `${first}–${last} successes`;
}
return `${first} success${first === 1 ? "" : "es"}`;
}
function formatSigned(value, decimals = 2) {
const sign = value > 0 ? "+" : value < 0 ? "−" : "";
return `${sign}${Math.abs(value).toFixed(decimals)}`;
}
function statsCard(distribution, isVariant, referenceDistribution) {
const meanProportion = distribution.mean / distribution.n;
const sdProportion = distribution.standardDeviation / distribution.n;
const modeProportion = distribution.modes[0] / distribution.n;
let delta = "";
if (isVariant) {
const deltaMean = distribution.mean - referenceDistribution.mean;
const deltaMeanProportion =
meanProportion - referenceDistribution.mean / referenceDistribution.n;
const deltaSd =
distribution.standardDeviation - referenceDistribution.standardDeviation;
const deltaSdProportion =
sdProportion - referenceDistribution.standardDeviation / referenceDistribution.n;
delta = `
<div class="delta">
<strong>Change from A:</strong>
center ${formatSigned(deltaMean)} successes
(${formatSigned(deltaMeanProportion * 100, 1)} percentage points);
spread ${formatSigned(deltaSd)} successes
(${formatSigned(deltaSdProportion * 100, 1)} percentage points).
</div>
`;
}
return `
<div class="stats-header">
<div>
<h2>${isVariant ? "B · One-parameter variant" : "A · Reference"}</h2>
<p>${
isVariant
? "Matches A except for the selected parameter."
: "The fixed comparison baseline."
}</p>
</div>
<div class="parameters">
<span class="parameter-chip">n = ${distribution.n} trials</span>
<span class="parameter-chip">p = ${Math.round(distribution.p * 100)}%</span>
</div>
</div>
<div class="metric-grid">
<div class="metric">
<span class="metric-label">Center · mean μ</span>
<strong>${distribution.mean.toFixed(2)} successes</strong>
<small>μ/n = ${(meanProportion * 100).toFixed(1)}% of trials</small>
</div>
<div class="metric">
<span class="metric-label">Spread · 1σ</span>
<strong>${distribution.standardDeviation.toFixed(2)} successes</strong>
<small>σ/n = ${(sdProportion * 100).toFixed(1)}% of trials</small>
</div>
<div class="metric">
<span class="metric-label">Most likely count</span>
<strong>${formatModes(distribution)}</strong>
<small>Mode proportion = ${(modeProportion * 100).toFixed(1)}%</small>
</div>
<div class="metric">
<span class="metric-label">Peak probability mass</span>
<strong>${(distribution.peak * 100).toFixed(1)}%</strong>
<small>The maximum height of any one bar</small>
</div>
</div>
${delta}
`;
}
function updateSliderUI() {
const config = parameterConfig[activeParameter];
slider.min = config.min;
slider.max = config.max;
slider.step = config.step;
slider.value = variant[activeParameter];
sliderLabel.textContent = config.label;
if (activeParameter === "p") {
sliderValue.textContent = `${Math.round(variant.p * 100)}%`;
rangeMin.textContent = "5%";
rangeMax.textContent = "95%";
} else {
sliderValue.textContent = `${variant.n} trials`;
rangeMin.textContent = "5 trials";
rangeMax.textContent = "24 trials";
}
const fill =
(Number(slider.value) - Number(config.min)) /
(Number(config.max) - Number(config.min)) *
100;
slider.style.setProperty("--fill", `${fill}%`);
}
function updateComparison() {
const distributionA = describeDistribution(reference);
const distributionB = describeDistribution(variant);
const largestMass = Math.max(
...distributionA.probabilities,
...distributionB.probabilities
);
const scaleMaximum = Math.max(
0.1,
Math.ceil((largestMass + 0.005) * 10) / 10
);
disposePanel(panelA);
disposePanel(panelB);
panelA = buildPanel(distributionA, "A", -5.30, scaleMaximum);
panelB = buildPanel(distributionB, "B", 5.30, scaleMaximum);
allBars = [...panelA.bars, ...panelB.bars];
const animationStart = performance.now();
allBars.forEach((bar, index) => {
barAnimations.push({
mesh: bar,
start: animationStart + index * 9,
duration: 520
});
});
referenceStats.innerHTML = statsCard(
distributionA,
false,
distributionB
);
variantStats.innerHTML = statsCard(
distributionB,
true,
distributionA
);
scaleText.textContent =
`Both panels use 0–${scaleMaximum.toFixed(1)} on the P(K=k) axis`;
updateSliderUI();
}
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
const cosPhi = Math.cos(cameraState.phi);
const radius = 18;
camera.position.set(
cameraTarget.x + radius * sinPhi * Math.sin(cameraState.yaw),
cameraTarget.y + radius * cosPhi,
cameraTarget.z + radius * sinPhi * Math.cos(cameraState.yaw)
);
camera.zoom = cameraState.zoom;
camera.lookAt(cameraTarget);
camera.updateProjectionMatrix();
}
function resetCamera() {
cameraState.yaw = -0.055;
cameraState.phi = 1.16;
cameraState.zoom = 1;
updateCamera();
}
function resizeRenderer() {
const width = sceneShell.clientWidth;
const height = sceneShell.clientHeight;
const aspect = width / height;
renderer.setSize(width, height, false);
const viewHeight = Math.max(10.5, 23.1 / aspect);
camera.left = -viewHeight * aspect / 2;
camera.right = viewHeight * aspect / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
updateCamera();
}
document.querySelectorAll("[data-param]").forEach(button => {
button.addEventListener("click", () => {
activeParameter = button.dataset.param;
const otherParameter = activeParameter === "n" ? "p" : "n";
variant[otherParameter] = reference[otherParameter];
document.querySelectorAll("[data-param]").forEach(candidate => {
candidate.setAttribute(
"aria-pressed",
String(candidate.dataset.param === activeParameter)
);
});
updateComparison();
});
});
slider.addEventListener("input", () => {
variant[activeParameter] = Number(slider.value);
updateComparison();
});
document.getElementById("resetVariant").addEventListener("click", () => {
variant.n = reference.n;
variant.p = reference.p;
updateComparison();
});
document.getElementById("resetCamera").addEventListener("click", resetCamera);
document.getElementById("resetCameraBottom").addEventListener("click", resetCamera);
// Direct camera controls: no OrbitControls or other Three.js addons.
const pointers = new Map();
let dragMoved = false;
let pinchDistance = 0;
const raycaster = new THREE.Raycaster();
const pointerNDC = new THREE.Vector2();
renderer.domElement.addEventListener("pointerdown", event => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
dragMoved = false;
tooltip.style.display = "none";
if (pointers.size === 2) {
const values = [...pointers.values()];
pinchDistance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
});
renderer.domElement.addEventListener("pointermove", event => {
const previous = pointers.get(event.pointerId);
if (!previous) {
showTooltip(event);
return;
}
const dx = event.clientX - previous.x;
const dy = event.clientY - previous.y;
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (Math.abs(dx) + Math.abs(dy) > 1) dragMoved = true;
if (pointers.size === 1) {
cameraState.yaw = THREE.MathUtils.clamp(
cameraState.yaw - dx * 0.005,
-0.58,
0.58
);
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.004,
0.86,
1.38
);
updateCamera();
} else if (pointers.size === 2) {
const values = [...pointers.values()];
const nextDistance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
if (pinchDistance > 0) {
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * (nextDistance / pinchDistance),
0.72,
1.65
);
updateCamera();
}
pinchDistance = nextDistance;
}
});
function releasePointer(event) {
pointers.delete(event.pointerId);
if (pointers.size < 2) pinchDistance = 0;
if (pointers.size === 0) dragMoved = false;
}
renderer.domElement.addEventListener("pointerup", releasePointer);
renderer.domElement.addEventListener("pointercancel", releasePointer);
renderer.domElement.addEventListener("pointerleave", () => {
tooltip.style.display = "none";
});
renderer.domElement.addEventListener(
"wheel",
event => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * Math.exp(-event.deltaY * 0.001),
0.72,
1.65
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
function showTooltip(event) {
if (dragMoved || pointers.size > 0) return;
const rect = renderer.domElement.getBoundingClientRect();
pointerNDC.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointerNDC.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointerNDC, camera);
const hit = raycaster.intersectObjects(allBars, false)[0];
if (!hit) {
tooltip.style.display = "none";
return;
}
const info = hit.object.userData.info;
tooltip.innerHTML = `
<strong>Exactly ${info.count} successes</strong>
<div class="tooltip-row">
<span>Count</span>
<span>${info.count} of ${info.trials}</span>
</div>
<div class="tooltip-row">
<span>Proportion</span>
<span>${(info.proportion * 100).toFixed(1)}%</span>
</div>
<div class="tooltip-row">
<span>Probability mass</span>
<span>${(info.probability * 100).toFixed(2)}%</span>
</div>
`;
const shellRect = sceneShell.getBoundingClientRect();
const localX = event.clientX - shellRect.left;
const localY = event.clientY - shellRect.top;
const tooltipWidth = 226;
const tooltipHeight = 122;
tooltip.style.display = "block";
tooltip.style.left = `${Math.min(
Math.max(10, localX + 14),
sceneShell.clientWidth - tooltipWidth - 10
)}px`;
tooltip.style.top = `${Math.min(
Math.max(10, localY + 14),
sceneShell.clientHeight - tooltipHeight - 10
)}px`;
}
new ResizeObserver(resizeRenderer).observe(sceneShell);
resizeRenderer();
updateComparison();
function animate(now) {
barAnimations = barAnimations.filter(animation => {
if (animation.mesh.userData.dead) return false;
const progress = THREE.MathUtils.clamp(
(now - animation.start) / animation.duration,
0,
1
);
const eased = 1 - Math.pow(1 - progress, 3);
animation.mesh.scale.y = 0.025 + 0.975 * eased;
return progress < 1;
});
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```