Prompt specification
Build or customize the Three.js 3D scene "Conditional probability denominator puzzle" 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: Conditional probability denominator puzzle
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/conditional-probability-denominator-puzzle-x1780
Scene Description Prompt:
Conditional probability denominator puzzle. Let users choose an event and a conditioning event on a token population; highlight intersection and denominator separately and reject conditioning on an empty set. Please build this with Three.js from cdnjs in one self-contained HTML file, using visible voxel blocks.
Working Three.js Starter (conditional-probability-denominator-puzzle-x1780):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Conditional Probability — Voxel Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #070c15;
--panel: #0d1524;
--panel-2: #111d30;
--line: rgba(167, 196, 230, 0.15);
--text: #edf5ff;
--muted: #93a7bf;
--cyan: #40c9ff;
--orange: #ffad42;
--green: #42e695;
--red: #ff647c;
--shadow: 0 20px 60px rgba(0, 0, 0, 0.32);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
min-height: 100%;
margin: 0;
}
body {
overflow: hidden;
background:
radial-gradient(circle at 80% 20%, rgba(35, 91, 132, 0.13), transparent 35%),
var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
select {
font: inherit;
}
button {
color: inherit;
}
.app {
display: grid;
grid-template-columns: 350px minmax(0, 1fr);
width: 100%;
height: 100vh;
}
.sidebar {
position: relative;
z-index: 3;
overflow-y: auto;
padding: 24px;
background:
linear-gradient(180deg, rgba(17, 29, 48, 0.98), rgba(9, 16, 28, 0.98));
border-right: 1px solid var(--line);
box-shadow: var(--shadow);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 18px;
}
.brand-mark {
display: grid;
grid-template-columns: repeat(2, 9px);
grid-template-rows: repeat(2, 9px);
gap: 3px;
padding: 8px;
background: rgba(64, 201, 255, 0.08);
border: 1px solid rgba(64, 201, 255, 0.25);
border-radius: 10px;
transform: rotate(-4deg);
}
.brand-mark i {
display: block;
background: var(--cyan);
border-radius: 2px;
}
.brand-mark i:nth-child(2) {
background: var(--orange);
}
.brand-mark i:nth-child(3) {
background: var(--green);
}
.brand-mark i:nth-child(4) {
background: rgba(255, 255, 255, 0.2);
}
.eyebrow {
margin: 0 0 3px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 25px;
line-height: 1.1;
letter-spacing: -0.04em;
}
.intro {
margin: 12px 0 22px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.section-label {
display: flex;
align-items: center;
justify-content: space-between;
margin: 22px 0 9px;
color: #c9d8e9;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.population-pill {
padding: 4px 7px;
color: var(--muted);
background: rgba(255, 255, 255, 0.04);
border: 1px solid var(--line);
border-radius: 999px;
font-size: 9px;
letter-spacing: 0.05em;
}
.control {
margin-bottom: 11px;
}
.control label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 7px;
color: #dbe8f6;
font-size: 12px;
font-weight: 700;
}
.count {
color: var(--muted);
font-size: 10px;
font-weight: 600;
}
select {
width: 100%;
height: 43px;
padding: 0 38px 0 12px;
color: var(--text);
background-color: #111d30;
border: 1px solid var(--line);
border-radius: 10px;
outline: none;
cursor: pointer;
}
select:focus {
border-color: rgba(64, 201, 255, 0.75);
box-shadow: 0 0 0 3px rgba(64, 201, 255, 0.09);
}
select.invalid {
border-color: rgba(255, 100, 124, 0.75);
box-shadow: 0 0 0 3px rgba(255, 100, 124, 0.08);
}
.editor {
padding: 13px;
background: rgba(255, 255, 255, 0.025);
border: 1px solid var(--line);
border-radius: 13px;
}
.editor-title {
margin: 0 0 4px;
color: #dce9f7;
font-size: 12px;
font-weight: 750;
}
.editor-copy {
margin: 0 0 11px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.brush-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 6px;
}
.brush {
min-height: 48px;
padding: 7px 4px;
background: rgba(255, 255, 255, 0.035);
border: 1px solid var(--line);
border-radius: 9px;
cursor: pointer;
transition: 140ms ease;
}
.brush:hover {
background: rgba(255, 255, 255, 0.07);
transform: translateY(-1px);
}
.brush.active {
background: rgba(64, 201, 255, 0.11);
border-color: rgba(64, 201, 255, 0.65);
box-shadow: inset 0 0 0 1px rgba(64, 201, 255, 0.12);
}
.brush strong,
.brush small {
display: block;
}
.brush strong {
font-size: 11px;
}
.brush small {
margin-top: 3px;
color: var(--muted);
font-size: 9px;
}
.brush[data-brush="b"] strong {
color: var(--orange);
}
.brush[data-brush="both"] strong {
color: var(--green);
}
.brush[data-brush="none"] strong {
color: #a7b8ca;
}
.stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.stat {
min-width: 0;
padding: 13px;
text-align: left;
background: var(--panel-2);
border: 1px solid var(--line);
border-radius: 13px;
cursor: pointer;
transition: 150ms ease;
}
.stat:hover,
.stat.active {
transform: translateY(-2px);
border-color: currentColor;
}
.stat.numerator {
color: var(--green);
}
.stat.denominator {
color: var(--orange);
}
.stat-top {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.stat-number {
display: block;
margin: 7px 0 3px;
color: var(--text);
font-size: 26px;
font-weight: 850;
letter-spacing: -0.04em;
}
.stat-copy {
display: block;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.result {
position: relative;
overflow: hidden;
margin-top: 11px;
padding: 17px;
background:
radial-gradient(circle at 100% 0, rgba(66, 230, 149, 0.12), transparent 45%),
#101d2e;
border: 1px solid rgba(66, 230, 149, 0.28);
border-radius: 15px;
transition: 180ms ease;
}
.result.invalid {
background:
radial-gradient(circle at 100% 0, rgba(255, 100, 124, 0.14), transparent 45%),
#1b1725;
border-color: rgba(255, 100, 124, 0.45);
}
.result-status {
color: var(--green);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.result.invalid .result-status {
color: var(--red);
}
.result-value {
margin: 8px 0 5px;
color: var(--text);
font-size: 38px;
font-weight: 900;
letter-spacing: -0.055em;
line-height: 1;
}
.result-equation {
color: #dce8f5;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 13px;
}
.result-equation .n {
color: var(--green);
}
.result-equation .d {
color: var(--orange);
}
.result-note {
margin: 10px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.result.invalid .result-note {
color: #f2bdc7;
}
.tip {
margin: 17px 0 0;
color: #7f95ad;
font-size: 10px;
line-height: 1.5;
}
.stage {
position: relative;
min-width: 0;
overflow: hidden;
background: #08111f;
}
#viewport {
position: absolute;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.stage-title {
position: absolute;
top: 20px;
left: 22px;
pointer-events: none;
}
.stage-title strong {
display: block;
margin-bottom: 4px;
font-size: 14px;
letter-spacing: -0.02em;
}
.stage-title span {
color: var(--muted);
font-size: 11px;
}
.view-controls {
position: absolute;
top: 18px;
right: 18px;
display: flex;
align-items: center;
gap: 8px;
}
.segmented {
display: flex;
padding: 4px;
background: rgba(8, 17, 31, 0.78);
border: 1px solid var(--line);
border-radius: 11px;
backdrop-filter: blur(14px);
box-shadow: 0 12px 36px rgba(0, 0, 0, 0.22);
}
.segmented button,
.reset-camera {
min-height: 31px;
padding: 0 10px;
color: var(--muted);
background: transparent;
border: 0;
border-radius: 7px;
font-size: 10px;
font-weight: 750;
cursor: pointer;
}
.segmented button:hover,
.reset-camera:hover {
color: var(--text);
background: rgba(255, 255, 255, 0.06);
}
.segmented button.active {
color: var(--text);
background: rgba(255, 255, 255, 0.1);
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.16);
}
.reset-camera {
min-height: 40px;
background: rgba(8, 17, 31, 0.78);
border: 1px solid var(--line);
border-radius: 11px;
backdrop-filter: blur(14px);
}
.legend {
position: absolute;
bottom: 18px;
left: 20px;
display: flex;
flex-wrap: wrap;
gap: 7px 13px;
max-width: 420px;
padding: 10px 12px;
color: var(--muted);
background: rgba(8, 17, 31, 0.76);
border: 1px solid var(--line);
border-radius: 11px;
font-size: 10px;
backdrop-filter: blur(14px);
pointer-events: none;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 2px;
box-shadow: 0 0 12px currentColor;
}
.swatch.a {
color: var(--cyan);
background: var(--cyan);
}
.swatch.b {
color: var(--orange);
background: var(--orange);
}
.swatch.both {
color: var(--green);
background: var(--green);
}
.swatch.none {
color: #35475f;
background: #35475f;
box-shadow: none;
}
.camera-help {
position: absolute;
right: 20px;
bottom: 21px;
color: #7f94ac;
font-size: 10px;
pointer-events: none;
}
.focus-caption {
position: absolute;
left: 50%;
bottom: 76px;
transform: translateX(-50%);
padding: 8px 13px;
color: #dce9f6;
background: rgba(8, 17, 31, 0.78);
border: 1px solid var(--line);
border-radius: 999px;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.04em;
text-align: center;
white-space: nowrap;
backdrop-filter: blur(14px);
pointer-events: none;
}
.focus-caption.numerator {
color: var(--green);
border-color: rgba(66, 230, 149, 0.3);
}
.focus-caption.denominator {
color: var(--orange);
border-color: rgba(255, 173, 66, 0.3);
}
.token-tooltip {
position: absolute;
z-index: 10;
display: none;
width: 190px;
padding: 10px 12px;
color: var(--text);
background: rgba(8, 16, 29, 0.94);
border: 1px solid rgba(167, 196, 230, 0.25);
border-radius: 10px;
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.35);
font-size: 11px;
line-height: 1.45;
pointer-events: none;
backdrop-filter: blur(12px);
}
.token-tooltip strong {
display: block;
margin-bottom: 4px;
font-size: 12px;
}
.token-tooltip .m-a {
color: var(--cyan);
}
.token-tooltip .m-b {
color: var(--orange);
}
.token-tooltip .m-both {
color: var(--green);
}
@media (max-width: 860px) {
body {
overflow: auto;
}
.app {
display: flex;
flex-direction: column;
height: auto;
min-height: 100vh;
}
.stage {
order: 0;
height: 64vh;
min-height: 470px;
}
.sidebar {
order: 1;
overflow: visible;
border-top: 1px solid var(--line);
border-right: 0;
}
.view-controls {
top: 66px;
left: 14px;
right: auto;
}
.camera-help {
display: none;
}
.focus-caption {
bottom: 69px;
max-width: calc(100% - 24px);
overflow: hidden;
text-overflow: ellipsis;
}
.legend {
right: 14px;
left: 14px;
max-width: none;
}
}
</style>
</head>
<body>
<div class="app">
<aside class="sidebar">
<header class="brand">
<div class="brand-mark" aria-hidden="true">
<i></i><i></i><i></i><i></i>
</div>
<div>
<p class="eyebrow">Probability laboratory</p>
<h1>Conditional / 72</h1>
</div>
</header>
<p class="intro">
Choose an event and a conditioning event. The numerator uses the
intersection; the denominator uses only the conditioning set.
</p>
<div class="section-label">
<span>Events</span>
<span class="population-pill">72 voxel tokens</span>
</div>
<div class="control">
<label for="eventA">
Event A
<span class="count" id="eventACount"></span>
</label>
<select id="eventA">
<option value="all">All tokens</option>
<option value="empty">Empty set</option>
<option value="every3" selected>Every 3rd token</option>
<option value="every4">Every 4th token</option>
<option value="left">Left half</option>
<option value="right">Right half</option>
<option value="custom">Custom set</option>
</select>
</div>
<div class="control">
<label for="eventB">
Conditioning event B
<span class="count" id="eventBCount"></span>
</label>
<select id="eventB">
<option value="all">All tokens</option>
<option value="empty">Empty set</option>
<option value="every3" selected>Every 3rd token</option>
<option value="every4">Every 4th token</option>
<option value="left">Left half</option>
<option value="right">Right half</option>
<option value="custom">Custom set</option>
</select>
</div>
<div class="section-label">
<span>Custom token editor</span>
</div>
<div class="editor">
<p class="editor-title">Paint a membership, then click a voxel.</p>
<p class="editor-copy">
Editing automatically changes the corresponding event to “Custom set.”
</p>
<div class="brush-grid" role="group" aria-label="Token membership brush">
<button class="brush active" data-brush="a" aria-pressed="true">
<strong>A only</strong>
<small>in A</small>
</button>
<button class="brush" data-brush="b" aria-pressed="false">
<strong>B only</strong>
<small>in B</small>
</button>
<button class="brush" data-brush="both" aria-pressed="false">
<strong>Both</strong>
<small>A ∩ B</small>
</button>
<button class="brush" data-brush="none" aria-pressed="false">
<strong>Neither</strong>
<small>outside</small>
</button>
</div>
</div>
<div class="section-label">
<span>Separate the fraction</span>
</div>
<div class="stats">
<button class="stat numerator" id="focusNumerator" type="button">
<span class="stat-top">Numerator · A ∩ B</span>
<span class="stat-number" id="intersectionCount">0</span>
<span class="stat-copy">Intersection blocks. Click to focus.</span>
</button>
<button class="stat denominator" id="focusDenominator" type="button">
<span class="stat-top">Denominator · B</span>
<span class="stat-number" id="denominatorCount">0</span>
<span class="stat-copy">Conditioning blocks. Click to focus.</span>
</button>
</div>
<section class="result" id="resultCard" aria-live="polite">
<div class="result-status" id="resultStatus">Conditional probability</div>
<div class="result-value" id="resultValue">—</div>
<div class="result-equation" id="resultEquation">P(A | B) = —</div>
<p class="result-note" id="resultNote"></p>
</section>
<p class="tip">
Green blocks belong to both events. Orange blocks belong only to B.
In denominator view, the green intersection is visibly contained inside B.
</p>
</aside>
<main class="stage">
<div id="viewport" aria-label="Interactive three-dimensional voxel population"></div>
<div class="stage-title">
<strong>Voxel probability field</strong>
<span>Hover for membership · drag to orbit</span>
</div>
<div class="view-controls">
<div class="segmented" role="group" aria-label="Visible set">
<button data-mode="population" class="active" type="button">Population</button>
<button data-mode="intersection" type="button">Intersection</button>
<button data-mode="denominator" type="button">Denominator</button>
</div>
<button class="reset-camera" id="resetCamera" type="button" title="Reset camera">
Reset view
</button>
</div>
<div class="focus-caption" id="focusCaption">
Population · 72 tokens
</div>
<div class="legend" aria-label="Color legend">
<span><i class="swatch a"></i>A only</span>
<span><i class="swatch b"></i>B only</span>
<span><i class="swatch both"></i>A ∩ B</span>
<span><i class="swatch none"></i>Neither</span>
</div>
<div class="camera-help">
Drag: orbit · Shift-drag: pan · Scroll: zoom
</div>
<div class="token-tooltip" id="tokenTooltip"></div>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Population and event state
// -------------------------------------------------------------------------
const TOTAL = 72;
const COLS = 12;
const ROWS = 6;
const SPACING = 0.68;
const COLOR = {
aOnly: new THREE.Color("#40c9ff"),
bOnly: new THREE.Color("#ffad42"),
both: new THREE.Color("#42e695"),
neither: new THREE.Color("#27374d")
};
const membershipA = new Uint8Array(TOTAL);
const membershipB = new Uint8Array(TOTAL);
const viewport = document.getElementById("viewport");
const eventASelect = document.getElementById("eventA");
const eventBSelect = document.getElementById("eventB");
const eventACount = document.getElementById("eventACount");
const eventBCount = document.getElementById("eventBCount");
const intersectionCount = document.getElementById("intersectionCount");
const denominatorCount = document.getElementById("denominatorCount");
const resultCard = document.getElementById("resultCard");
const resultStatus = document.getElementById("resultStatus");
const resultValue = document.getElementById("resultValue");
const resultEquation = document.getElementById("resultEquation");
const resultNote = document.getElementById("resultNote");
const focusCaption = document.getElementById("focusCaption");
const tokenTooltip = document.getElementById("tokenTooltip");
const brushButtons = [...document.querySelectorAll(".brush")];
const modeButtons = [...document.querySelectorAll("[data-mode]")];
let brush = "a";
let mode = "population";
let layoutInfo = { width: 0, depth: 0, columns: COLS, rows: ROWS };
function presetMask(name) {
const mask = new Uint8Array(TOTAL);
for (let i = 0; i < TOTAL; i++) {
const col = i % COLS;
const row = Math.floor(i / COLS);
switch (name) {
case "all":
mask[i] = 1;
break;
case "every3":
mask[i] = (i + 1) % 3 === 0 ? 1 : 0;
break;
case "every4":
mask[i] = (i + 1) % 4 === 0 ? 1 : 0;
break;
case "left":
mask[i] = col < COLS / 2 ? 1 : 0;
break;
case "right":
mask[i] = col >= COLS / 2 ? 1 : 0;
break;
case "empty":
default:
mask[i] = 0;
}
}
return mask;
}
function applyPreset(target, name) {
if (name === "custom") return;
const mask = presetMask(name);
target.set(mask);
}
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color("#08111f");
scene.fog = new THREE.Fog("#08111f", 13, 32);
const camera = new THREE.PerspectiveCamera(
43,
viewport.clientWidth / viewport.clientHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(viewport.clientWidth, viewport.clientHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.tabIndex = 0;
renderer.domElement.setAttribute(
"aria-label",
"Three-dimensional voxel population. Drag to orbit, shift-drag to pan, and scroll to zoom."
);
viewport.appendChild(renderer.domElement);
const ambient = new THREE.HemisphereLight(0xa9d8ff, 0x101827, 2.0);
scene.add(ambient);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(7, 11, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -12;
keyLight.shadow.camera.right = 12;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -12;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x40c9ff, 28, 25, 2);
rimLight.position.set(-8, 5, -6);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xffad42, 18, 22, 2);
warmLight.position.set(7, 2, -4);
scene.add(warmLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(34, 34),
new THREE.MeshStandardMaterial({
color: 0x091321,
roughness: 0.92,
metalness: 0.08
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.025;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(22, 22, 0x31516e, 0x1a2a3f);
grid.position.y = -0.008;
grid.material.transparent = true;
grid.material.opacity = 0.22;
scene.add(grid);
const cubeGeometry = new THREE.BoxGeometry(0.56, 0.56, 0.56);
const edgeGeometry = new THREE.EdgesGeometry(cubeGeometry);
const labelGeometry = new THREE.PlaneGeometry(0.42, 0.27);
const tokenGroups = [];
const bodyMeshes = [];
function makeTokenLabel(number) {
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 72;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(5, 12, 23, 0.78)";
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "#e7f4ff";
context.font = "700 31px ui-monospace, monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(String(number).padStart(2, "0"), 64, 37);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(4, renderer.capabilities.getMaxAnisotropy());
return texture;
}
for (let i = 0; i < TOTAL; i++) {
const group = new THREE.Group();
const bodyMaterial = new THREE.MeshStandardMaterial({
color: COLOR.neither,
roughness: 0.48,
metalness: 0.18,
emissive: 0x000000,
emissiveIntensity: 0.75
});
const body = new THREE.Mesh(cubeGeometry, bodyMaterial);
body.castShadow = true;
body.receiveShadow = true;
body.userData.tokenIndex = i;
body.userData.active = true;
group.add(body);
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x7390aa,
transparent: true,
opacity: 0.38
});
const edges = new THREE.LineSegments(edgeGeometry, edgeMaterial);
group.add(edges);
const labelMaterial = new THREE.MeshBasicMaterial({
map: makeTokenLabel(i + 1),
transparent: true,
depthWrite: false,
toneMapped: false
});
const label = new THREE.Mesh(labelGeometry, labelMaterial);
label.position.z = 0.286;
label.renderOrder = 2;
group.add(label);
const col = i % COLS;
const row = Math.floor(i / COLS);
const x = (col - (COLS - 1) / 2) * SPACING;
const z = (row - (ROWS - 1) / 2) * SPACING;
group.position.set(x, 0.32, z);
group.userData.targetPosition = group.position.clone();
group.userData.targetScale = 1;
scene.add(group);
tokenGroups.push({
group,
body,
bodyMaterial,
edges,
edgeMaterial
});
bodyMeshes.push(body);
}
// Focus frame around the compact numerator or denominator arrangement.
const frameMaterial = new THREE.LineBasicMaterial({
color: COLOR.both,
transparent: true,
opacity: 0.9
});
const frame = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(),
new THREE.Vector3(),
new THREE.Vector3(),
new THREE.Vector3()
]),
frameMaterial
);
frame.visible = false;
frame.position.y = 0.016;
scene.add(frame);
const frameFill = new THREE.Mesh(
new THREE.PlaneGeometry(1, 1),
new THREE.MeshBasicMaterial({
color: COLOR.both,
transparent: true,
opacity: 0.065,
depthWrite: false,
side: THREE.DoubleSide
})
);
frameFill.rotation.x = -Math.PI / 2;
frameFill.position.y = 0.006;
frameFill.visible = false;
scene.add(frameFill);
// -------------------------------------------------------------------------
// Camera controls, implemented directly without addons
// -------------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 0.2, 0);
const cameraTargetGoal = cameraTarget.clone();
const cameraUp = new THREE.Vector3(0, 1, 0);
const cameraRight = new THREE.Vector3(1, 0, 0);
let theta = 0.58;
let phi = 0.88;
let thetaGoal = theta;
let phiGoal = phi;
let radius = 11.8;
let radiusGoal = radius;
function defaultRadiusForMode() {
if (mode === "population") return 11.8;
const count = mode === "intersection"
? countIntersection()
: countDenominator();
const columns = mode === "intersection" ? 8 : 10;
const rows = Math.ceil(count / columns);
const width = Math.max(1, columns - 1) * SPACING;
const depth = Math.max(1, rows - 1) * SPACING;
return Math.max(
mode === "intersection" ? 4.3 : 5.4,
width * 0.88 + 2.4,
depth * 0.88 + 2.4
);
}
function resetCamera() {
thetaGoal = 0.58;
phiGoal = 0.88;
radiusGoal = defaultRadiusForMode();
cameraTargetGoal.set(0, 0.2, 0);
}
function updateCamera() {
theta += (thetaGoal - theta) * 0.13;
phi += (phiGoal - phi) * 0.13;
radius += (radiusGoal - radius) * 0.11;
cameraTarget.lerp(cameraTargetGoal, 0.12);
const sinPhi = Math.sin(phi);
camera.position.set(
cameraTarget.x + radius * sinPhi * Math.sin(theta),
cameraTarget.y + radius * Math.cos(phi),
cameraTarget.z + radius * sinPhi * Math.cos(theta)
);
camera.lookAt(cameraTarget);
camera.updateMatrixWorld();
}
// -------------------------------------------------------------------------
// Membership calculations and visuals
// -------------------------------------------------------------------------
function countA() {
let count = 0;
for (let i = 0; i < TOTAL; i++) count += membershipA[i];
return count;
}
function countB() {
let count = 0;
for (let i = 0; i < TOTAL; i++) count += membershipB[i];
return count;
}
function countIntersection() {
let count = 0;
for (let i = 0; i < TOTAL; i++) {
if (membershipA[i] && membershipB[i]) count++;
}
return count;
}
function membershipColor(index) {
if (membershipA[index] && membershipB[index]) return COLOR.both;
if (membershipA[index]) return COLOR.aOnly;
if (membershipB[index]) return COLOR.bOnly;
return COLOR.neither;
}
function updateTokenAppearance() {
tokenGroups.forEach((token, index) => {
const color = membershipColor(index);
token.bodyMaterial.color.copy(color);
token.bodyMaterial.emissive.copy(color).multiplyScalar(
color === COLOR.neither ? 0.025 : 0.16
);
token.edgeMaterial.color.copy(color).lerp(
new THREE.Color(0xffffff),
0.28
);
token.edgeMaterial.opacity = color === COLOR.neither ? 0.2 : 0.62;
});
}
function updateSceneTargets() {
const visibleIndices = [];
const positions = new Map();
if (mode === "population") {
for (let i = 0; i < TOTAL; i++) visibleIndices.push(i);
} else {
for (let i = 0; i < TOTAL; i++) {
const visible = mode === "intersection"
? membershipA[i] && membershipB[i]
: membershipB[i];
if (visible) visibleIndices.push(i);
}
}
const maxColumns = mode === "intersection" ? 8 : 10;
const columns = mode === "population"
? COLS
: Math.max(1, Math.min(maxColumns, visibleIndices.length));
const rows = mode === "population"
? ROWS
: Math.max(1, Math.ceil(visibleIndices.length / columns));
visibleIndices.forEach((index, listIndex) => {
const col = listIndex % columns;
const row = Math.floor(listIndex / columns);
const x = (col - (columns - 1) / 2) * SPACING;
const z = (row - (rows - 1) / 2) * SPACING;
positions.set(index, new THREE.Vector3(x, 0.32, z));
});
const width = Math.max(0.8, (columns - 1) * SPACING + 0.9);
const depth = Math.max(0.8, (rows - 1) * SPACING + 0.9);
layoutInfo = { width, depth, columns, rows };
tokenGroups.forEach((token, index) => {
const position = positions.get(index);
const visible = Boolean(position);
token.group.userData.targetPosition.copy(
position || token.group.position
);
token.group.userData.targetScale = visible ? 1 : 0.001;
token.body.userData.active = visible;
});
const focusVisible = mode !== "population";
frame.visible = focusVisible;
frameFill.visible = focusVisible;
if (focusVisible) {
const frameColor = mode === "intersection" ? COLOR.both : COLOR.both;
const frameLineColor = mode === "intersection"
? COLOR.both
: COLOR.bOnly;
frameMaterial.color.copy(frameLineColor);
frameFill.material.color.copy(frameColor);
const halfWidth = width / 2;
const halfDepth = depth / 2;
frame.geometry.dispose();
frame.geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-halfWidth, 0, -halfDepth),
new THREE.Vector3(halfWidth, 0, -halfDepth),
new THREE.Vector3(halfWidth, 0, halfDepth),
new THREE.Vector3(-halfWidth, 0, halfDepth)
]);
frameFill.scale.set(width, depth, 1);
}
}
function updateFocusUI() {
modeButtons.forEach((button) => {
button.classList.toggle("active", button.dataset.mode === mode);
});
document.getElementById("focusNumerator").classList.toggle(
"active",
mode === "intersection"
);
document.getElementById("focusDenominator").classList.toggle(
"active",
mode === "denominator"
);
focusCaption.className = "focus-caption";
if (mode === "population") {
focusCaption.textContent = "Population · 72 tokens";
} else if (mode === "intersection") {
focusCaption.classList.add("numerator");
focusCaption.textContent =
`Numerator · A ∩ B — ${countIntersection()} token` +
`${countIntersection() === 1 ? "" : "s"}`;
} else {
focusCaption.classList.add("denominator");
const suffix = countDenominator() === 0 ? " · empty set" : "";
focusCaption.textContent =
`Denominator · B — ${countDenominator()} token` +
`${countDenominator() === 1 ? "" : "s"}` +
`${suffix} · intersection included`;
}
}
function updateUI() {
const a = countA();
const b = countB();
const intersection = countIntersection();
eventACount.textContent = `${a} token${a === 1 ? "" : "s"}`;
eventBCount.textContent = `${b} token${b === 1 ? "" : "s"}`;
intersectionCount.textContent = intersection;
denominatorCount.textContent = b;
eventBSelect.classList.toggle("invalid", b === 0);
resultCard.classList.toggle("invalid", b === 0);
if (b === 0) {
resultStatus.textContent = "Rejected · empty conditioning set";
resultValue.textContent = "Undefined";
resultEquation.innerHTML =
'<span class="n">P(A | B)</span> = ' +
`<span class="n">${intersection}</span> / ` +
'<span class="d">0</span>';
resultNote.textContent =
"A conditional probability cannot be formed because the conditioning event B contains no tokens. Choose a non-empty B.";
} else {
const probability = intersection / b;
const percent = (probability * 100).toFixed(1);
resultStatus.textContent = "Conditional probability";
resultValue.textContent = `${percent}%`;
resultEquation.innerHTML =
'<span class="n">P(A | B)</span> = ' +
`<span class="n">${intersection}</span> / ` +
`<span class="d">${b}</span>`;
resultNote.textContent =
`The denominator is |B| = ${b}, not the whole population. ` +
`Here P(A ∩ B) = ${intersection}/${TOTAL} and P(B) = ${b}/${TOTAL}.`;
}
updateTokenAppearance();
updateSceneTargets();
updateFocusUI();
}
function setMode(nextMode) {
mode = nextMode;
updateSceneTargets();
updateFocusUI();
thetaGoal = 0.58;
phiGoal = 0.88;
radiusGoal = defaultRadiusForMode();
cameraTargetGoal.set(0, 0.2, 0);
}
// -------------------------------------------------------------------------
// Picking, hover details, and direct editing
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function pickToken(clientX, clientY) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(bodyMeshes, false);
return hits.find((hit) => hit.object.userData.active)?.object ?? null;
}
function showTooltip(index, clientX, clientY) {
const rect = viewport.getBoundingClientRect();
const inA = Boolean(membershipA[index]);
const inB = Boolean(membershipB[index]);
let status;
let className;
if (inA && inB) {
status = "In A ∩ B";
className = "m-both";
} else if (inA) {
status = "In A only";
className = "m-a";
} else if (inB) {
status = "In B only";
className = "m-b";
} else {
status = "In neither event";
className = "";
}
tokenTooltip.innerHTML =
`<strong>Token ${String(index + 1).padStart(2, "0")}</strong>` +
`<span class="${className}">${status}</span>`;
tokenTooltip.style.display = "block";
const tooltipWidth = 190;
const tooltipHeight = 65;
const left = Math.max(
8,
Math.min(clientX - rect.left + 14, rect.width - tooltipWidth - 8)
);
const top = Math.max(
8,
Math.min(clientY - rect.top + 14, rect.height - tooltipHeight - 8)
);
tokenTooltip.style.left = `${left}px`;
tokenTooltip.style.top = `${top}px`;
}
function hideTooltip() {
tokenTooltip.style.display = "none";
}
function paintToken(index) {
switch (brush) {
case "a":
membershipA[index] = 1;
membershipB[index] = 0;
break;
case "b":
membershipA[index] = 0;
membershipB[index] = 1;
break;
case "both":
membershipA[index] = 1;
membershipB[index] = 1;
break;
case "none":
membershipA[index] = 0;
membershipB[index] = 0;
break;
}
eventASelect.value = "custom";
eventBSelect.value = "custom";
updateUI();
}
let dragState = null;
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.setPointerCapture(event.pointerId);
dragState = {
pointerId: event.pointerId,
startX: event.clientX,
startY: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
button: event.button,
moved: false
};
hideTooltip();
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (dragState && dragState.pointerId === event.pointerId) {
const dx = event.clientX - dragState.lastX;
const dy = event.clientY - dragState.lastY;
const totalDx = event.clientX - dragState.startX;
const totalDy = event.clientY - dragState.startY;
if (Math.hypot(totalDx, totalDy) > 4) dragState.moved = true;
if (event.shiftKey || dragState.button === 2) {
cameraRight.setFromMatrixColumn(camera.matrixWorld, 0).normalize();
cameraUp.setFromMatrixColumn(camera.matrixWorld, 1).normalize();
const panScale = radius * 0.0017;
cameraTargetGoal.addScaledVector(cameraRight, -dx * panScale);
cameraTargetGoal.addScaledVector(cameraUp, dy * panScale);
cameraTargetGoal.x = THREE.MathUtils.clamp(
cameraTargetGoal.x,
-6,
6
);
cameraTargetGoal.z = THREE.MathUtils.clamp(
cameraTargetGoal.z,
-6,
6
);
} else {
thetaGoal -= dx * 0.007;
phiGoal = THREE.MathUtils.clamp(
phiGoal - dy * 0.007,
0.25,
1.48
);
}
dragState.lastX = event.clientX;
dragState.lastY = event.clientY;
return;
}
const hit = pickToken(event.clientX, event.clientY);
if (hit) {
showTooltip(hit.userData.tokenIndex, event.clientX, event.clientY);
renderer.domElement.style.cursor = "crosshair";
} else {
hideTooltip();
renderer.domElement.style.cursor = "grab";
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
if (
dragState &&
dragState.pointerId === event.pointerId &&
!dragState.moved &&
event.button === 0
) {
const hit = pickToken(event.clientX, event.clientY);
if (hit) paintToken(hit.userData.tokenIndex);
}
dragState = null;
});
renderer.domElement.addEventListener("pointercancel", () => {
dragState = null;
});
renderer.domElement.addEventListener("pointerleave", () => {
if (!dragState) hideTooltip();
});
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
radiusGoal = THREE.MathUtils.clamp(
radiusGoal * Math.exp(event.deltaY * 0.001),
3,
22
);
},
{ passive: false }
);
// -------------------------------------------------------------------------
// UI events
// -------------------------------------------------------------------------
eventASelect.addEventListener("change", () => {
applyPreset(membershipA, eventASelect.value);
updateUI();
});
eventBSelect.addEventListener("change", () => {
applyPreset(membershipB, eventBSelect.value);
updateUI();
});
brushButtons.forEach((button) => {
button.addEventListener("click", () => {
brush = button.dataset.brush;
brushButtons.forEach((candidate) => {
const selected = candidate === button;
candidate.classList.toggle("active", selected);
candidate.setAttribute("aria-pressed", String(selected));
});
});
});
modeButtons.forEach((button) => {
button.addEventListener("click", () => {
setMode(button.dataset.mode);
});
});
document.getElementById("focusNumerator").addEventListener("click", () => {
setMode("intersection");
});
document.getElementById("focusDenominator").addEventListener("click", () => {
setMode("denominator");
});
document.getElementById("resetCamera").addEventListener("click", resetCamera);
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
const resizeObserver = new ResizeObserver(() => {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
});
resizeObserver.observe(viewport);
function animate() {
requestAnimationFrame(animate);
tokenGroups.forEach((token) => {
token.group.position.lerp(
token.group.userData.targetPosition,
0.13
);
const currentScale = token.group.scale.x;
const nextScale =
currentScale +
(token.group.userData.targetScale - currentScale) * 0.15;
token.group.scale.setScalar(nextScale);
});
updateCamera();
renderer.render(scene, camera);
}
applyPreset(membershipA, eventASelect.value);
applyPreset(membershipB, eventBSelect.value);
updateUI();
animate();
</script>
</body>
</html>
```