Prompt specification
Build or customize the Three.js 3D scene "Randomization inference teaching tool" 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: Randomization inference teaching tool
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/randomization-inference-teaching-tool-x1820
Scene Description Prompt:
Use a known synthetic outcome table and repeated randomized labels to display a null comparison distribution; state the design and assumptions rather than presenting a real experimental result. Build this with Three.js from cdnjs as a voxel scene in one self-contained HTML file.
Working Three.js Starter (randomization-inference-teaching-tool-x1820):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Synthetic Randomization Lab — Voxel Permutation Test</title>
<style>
:root {
color-scheme: dark;
--bg: #050a12;
--panel: rgba(9, 18, 31, 0.88);
--panel-strong: rgba(12, 24, 40, 0.96);
--line: rgba(148, 177, 210, 0.18);
--text: #e7f0fb;
--muted: #91a4bb;
--cyan: #38c6f4;
--purple: #a78bfa;
--coral: #ff8066;
--amber: #f8c76a;
--green: #62ddb0;
}
* {
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;
}
body {
position: relative;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas:active {
cursor: grabbing;
}
.header {
position: fixed;
z-index: 5;
top: 28px;
left: 30px;
width: min(570px, calc(100vw - 420px));
pointer-events: none;
text-shadow: 0 2px 18px rgba(0, 0, 0, 0.55);
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 9px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.eyebrow::before {
width: 8px;
height: 8px;
border-radius: 2px;
background: var(--cyan);
box-shadow: 0 0 18px var(--cyan);
content: "";
}
h1 {
max-width: 560px;
margin: 12px 0 10px;
font-size: clamp(30px, 4.2vw, 58px);
font-weight: 760;
line-height: 0.99;
letter-spacing: -0.045em;
}
.header p {
max-width: 530px;
margin: 0;
color: #b5c5d8;
font-size: 14px;
line-height: 1.55;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 16px;
margin-top: 17px;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.04em;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 7px;
}
.swatch {
width: 10px;
height: 10px;
border-radius: 2px;
box-shadow: 0 0 12px currentColor;
}
.swatch.cyan {
color: var(--cyan);
background: var(--cyan);
}
.swatch.purple {
color: var(--purple);
background: var(--purple);
}
.swatch.coral {
color: var(--coral);
background: var(--coral);
}
.panel {
position: fixed;
z-index: 8;
top: 20px;
right: 20px;
bottom: 20px;
width: 370px;
overflow: auto;
padding: 18px;
border: 1px solid var(--line);
border-radius: 20px;
background:
linear-gradient(160deg, rgba(21, 39, 61, 0.68), rgba(7, 15, 27, 0.94)),
var(--panel);
box-shadow:
0 24px 70px rgba(0, 0, 0, 0.38),
inset 0 1px 0 rgba(255, 255, 255, 0.04);
backdrop-filter: blur(18px);
scrollbar-width: thin;
scrollbar-color: #294057 transparent;
}
.panel-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 14px;
}
.panel-head h2 {
margin: 0;
font-size: 15px;
letter-spacing: -0.01em;
}
.chip {
border: 1px solid rgba(98, 221, 176, 0.3);
border-radius: 999px;
padding: 5px 8px;
color: var(--green);
background: rgba(98, 221, 176, 0.08);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.readout {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.metric {
min-height: 88px;
padding: 13px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(4, 12, 23, 0.52);
}
.metric.wide {
grid-column: 1 / -1;
min-height: auto;
}
.metric-label {
display: block;
margin-bottom: 7px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.metric-value {
font-variant-numeric: tabular-nums;
font-size: 24px;
font-weight: 750;
letter-spacing: -0.035em;
}
.metric-value.coral {
color: var(--coral);
}
.metric-value.green {
color: var(--green);
}
.metric-sub {
margin-top: 5px;
color: #8398b0;
font-size: 10px;
line-height: 1.4;
}
.divider {
height: 1px;
margin: 17px 0;
background: var(--line);
}
.section-title {
margin: 0 0 10px;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.controls {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.field {
display: flex;
flex-direction: column;
gap: 6px;
}
.field label {
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.05em;
text-transform: uppercase;
}
input {
width: 100%;
min-width: 0;
height: 38px;
border: 1px solid var(--line);
border-radius: 10px;
outline: none;
padding: 0 10px;
color: var(--text);
background: rgba(3, 10, 20, 0.72);
font: inherit;
font-size: 12px;
}
input:focus {
border-color: rgba(56, 198, 244, 0.7);
box-shadow: 0 0 0 3px rgba(56, 198, 244, 0.09);
}
button {
height: 38px;
border: 1px solid transparent;
border-radius: 10px;
color: #031019;
background: var(--cyan);
font: inherit;
font-size: 11px;
font-weight: 800;
cursor: pointer;
transition:
transform 120ms ease,
filter 120ms ease,
opacity 120ms ease;
}
button:hover {
filter: brightness(1.08);
transform: translateY(-1px);
}
button:active {
transform: translateY(0);
}
button:disabled {
cursor: wait;
opacity: 0.55;
transform: none;
}
button.secondary {
border-color: var(--line);
color: #c5d4e5;
background: rgba(255, 255, 255, 0.035);
}
.run-info {
margin-top: 10px;
color: #8196ad;
font-size: 10px;
line-height: 1.45;
}
.assumption {
padding: 13px;
border: 1px solid rgba(248, 199, 106, 0.19);
border-radius: 13px;
background: rgba(248, 199, 106, 0.055);
}
.assumption strong {
display: block;
margin-bottom: 7px;
color: var(--amber);
font-size: 11px;
letter-spacing: 0.04em;
}
.assumption p,
.assumption ul {
margin: 0;
color: #b6c4d5;
font-size: 11px;
line-height: 1.55;
}
.assumption ul {
padding-left: 17px;
}
.assumption li + li {
margin-top: 5px;
}
details {
border-top: 1px solid var(--line);
}
summary {
padding: 14px 0;
color: #c7d5e5;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
cursor: pointer;
}
.table-wrap {
max-height: 230px;
overflow: auto;
border: 1px solid var(--line);
border-radius: 11px;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 10px;
}
th,
td {
padding: 8px 9px;
border-bottom: 1px solid rgba(148, 177, 210, 0.1);
text-align: left;
white-space: nowrap;
}
th {
position: sticky;
top: 0;
z-index: 1;
color: #8fa4bb;
background: #0b1726;
font-size: 9px;
letter-spacing: 0.06em;
text-transform: uppercase;
}
td.numeric {
text-align: right;
font-variant-numeric: tabular-nums;
}
.arm {
display: inline-block;
width: 7px;
height: 7px;
margin-right: 6px;
border-radius: 2px;
}
.arm.a {
background: var(--cyan);
}
.arm.b {
background: var(--purple);
}
.disclaimer {
padding-top: 14px;
color: #71869e;
font-size: 10px;
line-height: 1.55;
}
.disclaimer strong {
color: #a6b8cb;
}
#tooltip {
position: fixed;
z-index: 20;
display: none;
min-width: 150px;
padding: 9px 11px;
border: 1px solid rgba(56, 198, 244, 0.28);
border-radius: 9px;
pointer-events: none;
color: #e7f0fb;
background: rgba(4, 11, 21, 0.95);
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.34);
font-size: 11px;
line-height: 1.45;
}
#loading {
position: fixed;
z-index: 30;
inset: 0;
display: grid;
place-items: center;
color: #c7d9ea;
background: #050a12;
font-size: 12px;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.loader {
width: 34px;
height: 34px;
margin: 0 auto 14px;
border: 2px solid rgba(56, 198, 244, 0.18);
border-top-color: var(--cyan);
border-radius: 6px;
animation: spin 900ms steps(8) infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
@media (max-width: 900px) {
.header {
top: 18px;
left: 18px;
width: calc(100vw - 36px);
}
h1 {
max-width: 430px;
font-size: 34px;
}
.header p {
max-width: 430px;
font-size: 12px;
}
.legend {
display: none;
}
.panel {
top: auto;
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
max-height: 43vh;
border-radius: 16px;
padding: 14px;
}
.panel-head {
margin-bottom: 10px;
}
.readout {
grid-template-columns: repeat(4, 1fr);
}
.metric {
min-height: 74px;
padding: 10px;
}
.metric.wide {
grid-column: auto;
}
.metric-value {
font-size: 18px;
}
.controls {
grid-template-columns: 1fr 1fr 1fr 1fr;
}
.assumption {
display: none;
}
}
@media (max-width: 560px) {
.header p {
display: none;
}
.readout {
grid-template-columns: 1fr 1fr;
}
.metric.wide {
grid-column: 1 / -1;
}
.controls {
grid-template-columns: 1fr 1fr;
}
}
</style>
</head>
<body>
<div id="scene" aria-label="Interactive three-dimensional synthetic permutation-test scene"></div>
<header class="header">
<div class="eyebrow">Synthetic randomization lab</div>
<h1>A null distribution, built from relabeling.</h1>
<p>
One fixed synthetic outcome table. Thousands of balanced randomized labels.
The voxel histogram shows what group differences could have arisen by
reassigning those same outcomes.
</p>
<div class="legend">
<span><i class="swatch cyan"></i> Arm A label</span>
<span><i class="swatch purple"></i> Arm B label</span>
<span><i class="swatch coral"></i> Observed difference</span>
</div>
</header>
<aside class="panel">
<div class="panel-head">
<h2>Permutation readout</h2>
<span class="chip">Simulated only</span>
</div>
<div class="readout" aria-live="polite">
<div class="metric">
<span class="metric-label">Observed Δ mean</span>
<div class="metric-value coral" id="observedValue">—</div>
<div class="metric-sub">Arm A minus Arm B</div>
</div>
<div class="metric">
<span class="metric-label">Two-sided p</span>
<div class="metric-value green" id="pValue">—</div>
<div class="metric-sub">Monte Carlo, plus-one correction</div>
</div>
<div class="metric wide">
<span class="metric-label">Central 95% of randomized-label differences</span>
<div class="metric-value" id="nullRange">—</div>
<div class="metric-sub">
This is a range of the simulated null distribution, not a confidence
interval for a treatment effect.
</div>
</div>
</div>
<div class="divider"></div>
<h3 class="section-title">Rebuild the null</h3>
<div class="controls">
<div class="field">
<label for="permutations">Relabelings</label>
<input
id="permutations"
type="number"
min="500"
max="100000"
step="500"
value="20000"
>
</div>
<div class="field">
<label for="seed">Random seed</label>
<input id="seed" type="number" min="0" max="999999" value="1729">
</div>
<button id="regenerate" type="button">Regenerate null</button>
<button id="resetCamera" class="secondary" type="button">Reset camera</button>
</div>
<div class="run-info" id="runInfo">
20,000 balanced relabelings will be sampled from the fixed table.
</div>
<div class="divider"></div>
<div class="assumption">
<strong>Design and assumptions</strong>
<ul>
<li>
The 20 outcome scores below are hand-authored synthetic values, not
observations from people, animals, or a real experiment.
</li>
<li>
Each trial keeps exactly 10 Arm A labels and 10 Arm B labels, then
computes the difference in group means.
</li>
<li>
The null assumes the outcome scores are exchangeable under label
reassignment. The scores themselves remain fixed in every trial.
</li>
<li>
The reported p-value is
<em>(1 + extreme trials) / (trials + 1)</em>, where extreme means
|Δ*| ≥ |Δ observed|.
</li>
<li>
Repeated sampling approximates the finite set of balanced
permutations; it is not an exhaustive enumeration.
</li>
<li>
There is no missing-data, clustering, covariate, or power analysis.
These numbers demonstrate a procedure only and support no causal or
real-world claim.
</li>
</ul>
</div>
<details>
<summary>Fixed synthetic outcome table</summary>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Record</th>
<th>Observed arm</th>
<th>Outcome score</th>
</tr>
</thead>
<tbody id="outcomeTable"></tbody>
</table>
</div>
</details>
<details>
<summary>Simulated null histogram bins</summary>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Bin center</th>
<th>Trials</th>
</tr>
</thead>
<tbody id="nullTable"></tbody>
</table>
</div>
</details>
<div class="disclaimer">
<strong>Interpretation guardrail:</strong> every statistic in this panel
is generated from the synthetic table. Even a small p-value here is not
evidence about a real intervention.
</div>
</aside>
<div id="tooltip"></div>
<div id="loading">
<div>
<div class="loader"></div>
Loading Three.js core
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------
// Fixed, hand-authored synthetic outcome table.
// Arm A is the observed "treatment" arm; Arm B is the observed control.
// ---------------------------------------------------------------------
const rows = [
{ id: "T01", arm: "A", outcome: 6.4 },
{ id: "T02", arm: "A", outcome: 7.1 },
{ id: "T03", arm: "A", outcome: 5.8 },
{ id: "T04", arm: "A", outcome: 8.0 },
{ id: "T05", arm: "A", outcome: 6.9 },
{ id: "T06", arm: "A", outcome: 7.5 },
{ id: "T07", arm: "A", outcome: 6.2 },
{ id: "T08", arm: "A", outcome: 7.8 },
{ id: "T09", arm: "A", outcome: 7.3 },
{ id: "T10", arm: "A", outcome: 6.6 },
{ id: "C01", arm: "B", outcome: 5.9 },
{ id: "C02", arm: "B", outcome: 6.3 },
{ id: "C03", arm: "B", outcome: 5.5 },
{ id: "C04", arm: "B", outcome: 7.2 },
{ id: "C05", arm: "B", outcome: 6.1 },
{ id: "C06", arm: "B", outcome: 6.8 },
{ id: "C07", arm: "B", outcome: 5.7 },
{ id: "C08", arm: "B", outcome: 7.0 },
{ id: "C09", arm: "B", outcome: 6.5 },
{ id: "C10", arm: "B", outcome: 5.8 }
];
const armSize = rows.filter(r => r.arm === "A").length;
const controlSize = rows.length - armSize;
const outcomes = rows.map(r => r.outcome);
const total = outcomes.reduce((a, b) => a + b, 0);
const observed =
outcomes
.filter((_, i) => rows[i].arm === "A")
.reduce((a, b) => a + b, 0) / armSize -
outcomes
.filter((_, i) => rows[i].arm === "B")
.reduce((a, b) => a + b, 0) / controlSize;
const observedLabels = rows.map(r => r.arm === "A");
document.getElementById("outcomeTable").innerHTML = rows.map(r => `
<tr>
<td>${r.id}</td>
<td>
<span class="arm ${r.arm.toLowerCase()}"></span>
Arm ${r.arm}
</td>
<td class="numeric">${r.outcome.toFixed(1)}</td>
</tr>
`).join("");
// ---------------------------------------------------------------------
// Deterministic random-number generator and balanced permutation test.
// ---------------------------------------------------------------------
function mulberry32(seed) {
return function () {
let t = seed += 0x6D2B79F5;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function shuffleInPlace(array, random) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
function quantile(sorted, q) {
if (!sorted.length) return NaN;
const pos = (sorted.length - 1) * q;
const lo = Math.floor(pos);
const hi = Math.ceil(pos);
return sorted[lo] + (sorted[hi] - sorted[lo]) * (pos - lo);
}
function runPermutationTest(trialCount, seed) {
const random = mulberry32(seed >>> 0);
const labels = observedLabels.slice();
const differences = new Float64Array(trialCount);
const snapshots = [];
for (let trial = 0; trial < trialCount; trial++) {
shuffleInPlace(labels, random);
let sumA = 0;
for (let i = 0; i < labels.length; i++) {
if (labels[i]) sumA += outcomes[i];
}
differences[trial] =
sumA / armSize - (total - sumA) / controlSize;
if (trial < 7) snapshots.push(labels.slice());
}
const sorted = Array.from(differences).sort((a, b) => a - b);
const tolerance = 1e-12;
let extreme = 0;
for (const difference of differences) {
if (Math.abs(difference) + tolerance >= Math.abs(observed)) {
extreme++;
}
}
// Plus-one correction gives a valid non-zero Monte Carlo p-value.
const pValue = (extreme + 1) / (trialCount + 1);
const sortedOutcomes = outcomes.slice().sort((a, b) => a - b);
const bottomMean =
sortedOutcomes.slice(0, controlSize)
.reduce((a, b) => a + b, 0) / controlSize;
const topMean =
sortedOutcomes.slice(-armSize)
.reduce((a, b) => a + b, 0) / armSize;
const range = Math.ceil((topMean - bottomMean) * 10) / 10;
const binCount = 27;
const counts = new Uint32Array(binCount);
const binWidth = (range * 2) / binCount;
for (const difference of differences) {
let index = Math.floor((difference + range) / binWidth);
index = Math.max(0, Math.min(binCount - 1, index));
counts[index]++;
}
return {
trialCount,
seed,
extreme,
pValue,
q025: quantile(sorted, 0.025),
q975: quantile(sorted, 0.975),
range,
binCount,
binWidth,
counts,
snapshots
};
}
// ---------------------------------------------------------------------
// Three.js scene.
// ---------------------------------------------------------------------
const mount = document.getElementById("scene");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x050a12);
scene.fog = new THREE.FogExp2(0x050a12, 0.027);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
mount.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
const hemisphere = new THREE.HemisphereLight(0xa9d8ff, 0x07101d, 2.0);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xd7eeff, 2.4);
keyLight.position.set(-5, 12, 9);
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x3bc9ff, 28, 24, 2);
rimLight.position.set(6, 5, -4);
scene.add(rimLight);
const purpleLight = new THREE.PointLight(0x9b7bff, 18, 18, 2);
purpleLight.position.set(-8, 4, 3);
scene.add(purpleLight);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(60, 60),
new THREE.MeshStandardMaterial({
color: 0x050b13,
roughness: 0.92,
metalness: 0.05
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.07;
scene.add(ground);
const grid = new THREE.GridHelper(42, 42, 0x24445c, 0x102538);
grid.position.y = -0.055;
grid.material.transparent = true;
grid.material.opacity = 0.38;
scene.add(grid);
const staticGroup = new THREE.Group();
const dynamicGroup = new THREE.Group();
scene.add(staticGroup, dynamicGroup);
const materials = {
armA: new THREE.MeshStandardMaterial({
color: 0x38c6f4,
emissive: 0x06364a,
emissiveIntensity: 0.85,
roughness: 0.38,
metalness: 0.12
}),
armB: new THREE.MeshStandardMaterial({
color: 0xa78bfa,
emissive: 0x281b5d,
emissiveIntensity: 0.85,
roughness: 0.4,
metalness: 0.1
}),
null: new THREE.MeshStandardMaterial({
color: 0x4b7896,
emissive: 0x102a3a,
emissiveIntensity: 0.8,
roughness: 0.5,
metalness: 0.08
}),
tail: new THREE.MeshStandardMaterial({
color: 0xf8c76a,
emissive: 0x50330a,
emissiveIntensity: 0.8,
roughness: 0.48,
metalness: 0.08
}),
observed: new THREE.MeshStandardMaterial({
color: 0xff8066,
emissive: 0x7b1d10,
emissiveIntensity: 1.2,
roughness: 0.3,
metalness: 0.05
}),
zero: new THREE.MeshStandardMaterial({
color: 0xd8e7f4,
emissive: 0x53616f,
emissiveIntensity: 0.55,
roughness: 0.45
}),
panel: new THREE.MeshStandardMaterial({
color: 0x0b1929,
roughness: 0.85,
metalness: 0.08
})
};
const geometryCache = new Map();
function boxGeometry(size, vertical = false) {
const key = `${size}:${vertical}`;
if (!geometryCache.has(key)) {
const geometry = new THREE.BoxGeometry(size, size, size);
if (vertical) geometry.translate(0, size / 2, 0);
geometryCache.set(key, geometry);
}
return geometryCache.get(key);
}
function addPanel(width, depth, x, z) {
const base = new THREE.Mesh(
new THREE.BoxGeometry(width, 0.11, depth),
materials.panel
);
base.position.set(x, -0.015, z);
staticGroup.add(base);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(base.geometry),
new THREE.LineBasicMaterial({
color: 0x31506a,
transparent: true,
opacity: 0.7
})
);
edges.position.copy(base.position);
staticGroup.add(edges);
}
function roundedRect(context, x, y, w, h, r) {
context.beginPath();
context.moveTo(x + r, y);
context.arcTo(x + w, y, x + w, y + h, r);
context.arcTo(x + w, y + h, x, y + h, r);
context.arcTo(x, y + h, x, y, r);
context.arcTo(x, y, x + w, y, r);
context.closePath();
}
function makeLabel(text, color = "#dbeaf7", width = 3.0) {
const canvas = document.createElement("canvas");
canvas.width = 1024;
canvas.height = 256;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(context, 12, 18, 1000, 220, 30);
context.fillStyle = "rgba(5, 13, 24, 0.88)";
context.fill();
context.strokeStyle = "rgba(129, 173, 210, 0.25)";
context.lineWidth = 3;
context.stroke();
context.fillStyle = color;
context.font = "700 58px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 512, 131, 940);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(width, width / 4, 1);
sprite.renderOrder = 10;
return sprite;
}
function addStaticLabel(text, position, color, width = 3.0) {
const label = makeLabel(text, color, width);
label.position.copy(position);
staticGroup.add(label);
return label;
}
addPanel(6.3, 4.0, -4.75, 0.0);
addPanel(6.55, 2.25, 3.45, 0.0);
addPanel(3.25, 2.45, -0.25, -5.25);
addStaticLabel(
"FIXED SYNTHETIC OUTCOMES",
new THREE.Vector3(-4.75, 3.55, 0),
"#dcecf8",
4.7
);
addStaticLabel(
"ARM A · OBSERVED LABELS",
new THREE.Vector3(-4.75, 0.40, -1.75),
"#38c6f4",
3.8
);
addStaticLabel(
"ARM B · OBSERVED LABELS",
new THREE.Vector3(-4.75, 0.40, 1.75),
"#a78bfa",
3.8
);
addStaticLabel(
"NULL DIFFERENCE IN MEANS · A − B",
new THREE.Vector3(3.45, 3.55, 0),
"#dcecf8",
4.7
);
addStaticLabel(
"OBSERVED + 7 RANDOM LABELINGS",
new THREE.Vector3(-0.25, 0.55, -3.85),
"#8fa9c1",
3.6
);
let observedMarker = null;
let dynamicLabelSprites = [];
function clearDynamic() {
for (const sprite of dynamicLabelSprites) {
if (sprite.material?.map) sprite.material.map.dispose();
if (sprite.material) sprite.material.dispose();
}
dynamicLabelSprites = [];
dynamicGroup.clear();
}
function addVoxel(parent, x, y, z, size, material, record = null) {
const mesh = new THREE.Mesh(boxGeometry(size, true), material);
mesh.position.set(x, y, z);
if (record) mesh.userData.record = record;
parent.add(mesh);
return mesh;
}
function buildScene(result) {
clearDynamic();
// Outcome voxel stacks: height is proportional to the absolute score.
const outcomeSize = 0.16;
const startX = -7.25;
const spacing = 0.56;
rows.forEach((record, index) => {
const rowIndex = record.arm === "A" ? index : index - armSize;
const x = startX + rowIndex * spacing;
const z = record.arm === "A" ? -1.05 : 1.05;
const count = Math.max(4, Math.round((record.outcome / 8) * 18));
const material = record.arm === "A" ? materials.armA : materials.armB;
for (let level = 0; level < count; level++) {
addVoxel(
dynamicGroup,
x,
0.055 + level * outcomeSize,
z,
outcomeSize,
material,
record
);
}
});
// Null histogram rendered as voxel columns.
const histStart = 0.45;
const histSpacing = 0.225;
const histSize = 0.18;
const maxCount = Math.max(...result.counts);
const maxLevels = 14;
for (let bin = 0; bin < result.binCount; bin++) {
const count = result.counts[bin];
const center = -result.range + (bin + 0.5) * result.binWidth;
const levels = count
? Math.max(1, Math.ceil((count / maxCount) * maxLevels))
: 0;
const material =
Math.abs(center) + 1e-12 >= Math.abs(observed)
? materials.tail
: materials.null;
for (let level = 0; level < levels; level++) {
addVoxel(
dynamicGroup,
histStart + bin * histSpacing,
0.055 + level * histSize,
0,
histSize,
material
);
}
}
// Zero reference marker.
const zeroX = histStart + ((0 + result.range) / (result.range * 2)) *
result.binCount * histSpacing;
for (let level = 0; level < 18; level++) {
addVoxel(
dynamicGroup,
zeroX,
0.07 + level * 0.16,
0.38,
0.07,
materials.zero
);
}
// Observed difference marker.
const observedX =
histStart +
((observed + result.range) / (result.range * 2)) *
result.binCount *
histSpacing;
observedMarker = new THREE.Group();
dynamicGroup.add(observedMarker);
for (let level = 0; level < 31; level++) {
addVoxel(
observedMarker,
observedX,
0.08 + level * 0.105,
0.50,
0.105,
materials.observed
);
}
const markerLabel = makeLabel(
`OBSERVED Δ ${formatSigned(observed)}`,
"#ff9b84",
3.1
);
markerLabel.position.set(observedX, 3.48, 0.55);
dynamicGroup.add(markerLabel);
dynamicLabelSprites.push(markerLabel);
// Axis labels.
const axisLabels = [
{
text: `−${result.range.toFixed(1)}`,
x: histStart - 0.1
},
{
text: "0",
x: zeroX
},
{
text: `+${result.range.toFixed(1)}`,
x: histStart + result.binCount * histSpacing - 0.1
}
];
for (const axis of axisLabels) {
const label = makeLabel(axis.text, "#7f97af", 1.0);
label.position.set(axis.x, 0.18, 1.02);
dynamicGroup.add(label);
dynamicLabelSprites.push(label);
}
// A small visual sample of the repeated randomized label assignments.
const recentLabels = [observedLabels, ...result.snapshots];
const recentGeometry = boxGeometry(0.095);
const recentMaterial = new THREE.MeshBasicMaterial({
color: 0xffffff,
vertexColors: true
});
const recentMesh = new THREE.InstancedMesh(
recentGeometry,
recentMaterial,
recentLabels.length * rows.length
);
recentMesh.frustumCulled = false;
const dummy = new THREE.Object3D();
const tempColor = new THREE.Color();
let instance = 0;
recentLabels.forEach((labels, rowIndex) => {
labels.forEach((isA, columnIndex) => {
dummy.position.set(
-1.55 + columnIndex * 0.145,
0.08,
-4.45 - rowIndex * 0.225
);
dummy.updateMatrix();
recentMesh.setMatrixAt(instance, dummy.matrix);
tempColor.set(isA ? 0x38c6f4 : 0xa78bfa);
if (rowIndex !== 0) tempColor.multiplyScalar(0.58);
recentMesh.setColorAt(instance, tempColor);
instance++;
});
});
recentMesh.instanceMatrix.needsUpdate = true;
if (recentMesh.instanceColor) recentMesh.instanceColor.needsUpdate = true;
dynamicGroup.add(recentMesh);
}
function formatSigned(value) {
const sign = value >= 0 ? "+" : "−";
return `${sign}${Math.abs(value).toFixed(2)}`;
}
function formatP(value) {
if (value < 0.001) return "< 0.001";
return value.toFixed(3);
}
function updateReadout(result) {
document.getElementById("observedValue").textContent =
formatSigned(observed);
document.getElementById("pValue").textContent =
formatP(result.pValue);
document.getElementById("nullRange").textContent =
`${formatSigned(result.q025)} to ${formatSigned(result.q975)}`;
document.getElementById("runInfo").textContent =
`${result.trialCount.toLocaleString()} balanced relabelings · ` +
`seed ${result.seed} · ${result.extreme.toLocaleString()} extreme trials.`;
document.getElementById("nullTable").innerHTML =
Array.from(result.counts).map((count, index) => {
const center =
-result.range + (index + 0.5) * result.binWidth;
return `
<tr>
<td>${formatSigned(center)}</td>
<td class="numeric">${count.toLocaleString()}</td>
</tr>
`;
}).join("");
}
// ---------------------------------------------------------------------
// Direct camera controls: orbit, pan, wheel zoom, and touch pinch.
// ---------------------------------------------------------------------
const reducedMotion = window.matchMedia(
"(prefers-reduced-motion: reduce)"
).matches;
const desiredCamera = {
theta: 0.66,
phi: 0.94,
radius: 22.5,
target: new THREE.Vector3(-0.8, 1.0, -0.7)
};
const currentCamera = {
theta: desiredCamera.theta,
phi: desiredCamera.phi,
radius: desiredCamera.radius,
target: desiredCamera.target.clone()
};
function resetCamera() {
desiredCamera.theta = 0.66;
desiredCamera.phi = 0.94;
desiredCamera.radius = 22.5;
desiredCamera.target.set(-0.8, 1.0, -0.7);
}
function updateCamera() {
const damping = reducedMotion ? 1 : 0.12;
currentCamera.theta +=
(desiredCamera.theta - currentCamera.theta) * damping;
currentCamera.phi +=
(desiredCamera.phi - currentCamera.phi) * damping;
currentCamera.radius +=
(desiredCamera.radius - currentCamera.radius) * damping;
currentCamera.target.lerp(desiredCamera.target, damping);
const sinPhi = Math.sin(currentCamera.phi);
camera.position.set(
currentCamera.target.x +
currentCamera.radius * sinPhi * Math.sin(currentCamera.theta),
currentCamera.target.y +
currentCamera.radius * Math.cos(currentCamera.phi),
currentCamera.target.z +
currentCamera.radius * sinPhi * Math.cos(currentCamera.theta)
);
camera.lookAt(currentCamera.target);
}
const canvas = renderer.domElement;
const pointerPositions = new Map();
let dragging = false;
let panning = false;
let lastX = 0;
let lastY = 0;
let previousPinchDistance = 0;
function panCamera(dx, dy) {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = forward.clone().cross(camera.up).normalize();
const amount = currentCamera.radius * 0.0014;
desiredCamera.target.addScaledVector(right, -dx * amount);
desiredCamera.target.addScaledVector(forward, dy * amount);
desiredCamera.target.x = THREE.MathUtils.clamp(
desiredCamera.target.x, -8, 8
);
desiredCamera.target.y = THREE.MathUtils.clamp(
desiredCamera.target.y, 0.2, 5
);
desiredCamera.target.z = THREE.MathUtils.clamp(
desiredCamera.target.z, -8, 5
);
}
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("pointerdown", event => {
canvas.setPointerCapture(event.pointerId);
pointerPositions.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
dragging = true;
panning = event.shiftKey || event.button === 2;
lastX = event.clientX;
lastY = event.clientY;
document.getElementById("tooltip").style.display = "none";
});
canvas.addEventListener("pointermove", event => {
if (pointerPositions.has(event.pointerId)) {
pointerPositions.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
}
if (pointerPositions.size >= 2) {
const points = [...pointerPositions.values()];
const distance = Math.hypot(
points[0].x - points[1].x,
points[0].y - points[1].y
);
if (previousPinchDistance > 0) {
desiredCamera.radius = THREE.MathUtils.clamp(
desiredCamera.radius *
(previousPinchDistance / Math.max(distance, 1)),
10,
36
);
}
previousPinchDistance = distance;
return;
}
if (dragging) {
const dx = event.clientX - lastX;
const dy = event.clientY - lastY;
if (panning) {
panCamera(dx, dy);
} else {
desiredCamera.theta -= dx * 0.006;
desiredCamera.phi = THREE.MathUtils.clamp(
desiredCamera.phi - dy * 0.005,
0.36,
1.42
);
}
lastX = event.clientX;
lastY = event.clientY;
return;
}
updateTooltip(event);
});
function endPointer(event) {
pointerPositions.delete(event.pointerId);
dragging = pointerPositions.size > 0;
previousPinchDistance = 0;
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener("pointerleave", () => {
if (!dragging) {
document.getElementById("tooltip").style.display = "none";
}
});
canvas.addEventListener("wheel", event => {
event.preventDefault();
desiredCamera.radius = THREE.MathUtils.clamp(
desiredCamera.radius * Math.exp(event.deltaY * 0.001),
10,
36
);
}, { passive: false });
// Hover readout for the outcome voxels.
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const tooltip = document.getElementById("tooltip");
function updateTooltip(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;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(dynamicGroup.children, true);
const hit = hits.find(item => item.object.userData.record);
if (!hit) {
tooltip.style.display = "none";
return;
}
const record = hit.object.userData.record;
tooltip.innerHTML = `
<strong>${record.id}</strong> · Arm ${record.arm}<br>
Synthetic outcome: <strong>${record.outcome.toFixed(1)}</strong>
`;
tooltip.style.display = "block";
const left = Math.min(
event.clientX + 14,
window.innerWidth - tooltip.offsetWidth - 12
);
const top = Math.min(
event.clientY + 14,
window.innerHeight - tooltip.offsetHeight - 12
);
tooltip.style.left = `${left}px`;
tooltip.style.top = `${top}px`;
}
document.getElementById("resetCamera").addEventListener(
"click",
resetCamera
);
// ---------------------------------------------------------------------
// UI and computation.
// ---------------------------------------------------------------------
function regenerate() {
const button = document.getElementById("regenerate");
button.disabled = true;
requestAnimationFrame(() => {
const trialCount = Math.max(
500,
Math.min(
100000,
Math.round(
Number(document.getElementById("permutations").value) || 20000
)
)
);
const seed = Math.max(
0,
Math.min(
999999,
Math.round(
Number(document.getElementById("seed").value) || 1729
)
)
);
document.getElementById("permutations").value = trialCount;
document.getElementById("seed").value = seed;
const result = runPermutationTest(trialCount, seed);
updateReadout(result);
buildScene(result);
button.disabled = false;
});
}
document.getElementById("regenerate").addEventListener(
"click",
regenerate
);
for (const id of ["permutations", "seed"]) {
document.getElementById(id).addEventListener("keydown", event => {
if (event.key === "Enter") regenerate();
});
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(
Math.min(window.devicePixelRatio || 1, 2)
);
renderer.setSize(window.innerWidth, window.innerHeight);
});
// Initial synthetic run.
const initialResult = runPermutationTest(20000, 1729);
updateReadout(initialResult);
buildScene(initialResult);
renderer.setAnimationLoop(time => {
updateCamera();
if (observedMarker && !reducedMotion) {
const pulse = 1 + Math.sin(time * 0.0025) * 0.08;
observedMarker.scale.x = pulse;
}
renderer.render(scene, camera);
});
document.getElementById("loading").style.display = "none";
</script>
</body>
</html>
```